﻿/**
 * 捲動式跑馬燈物件v1.0
 * 程式運作需掛載Ext2.2套件，後端WebService須於web.config
 * 開啟HttpPost方式，資料須回傳含有totalRecords及record標籤
 * 每組record標籤內含有n_title及n_url標籤。格式如下:
 * <record>
 * 	<n_title>跑馬燈文字</ad_link>
 * 	<n_url>跑馬燈連結</img_url>
 * </record>
 * <totalRecord>資料筆數</totalRecord>
 * 
 * @param string storeUrl: WebService網址/方法
 * @param string applyTo: 頁面div id
 * @param int sec: 輪播秒數
 * @param int height: 跑馬燈高度
 * @config {storeUrl:'WebService網址/方法', applyTo:'頁面div id', sec: 輪播秒數, height: 跑馬燈高度}
 * @example
 * var mqMsg = new Marquee.marquee();
 * mqMsg.render({config});
 * 
 * @html
 * <div id="marqueebox" style="margin-top: 0px; height: 360px;">
 * 
 * @author hochente@gmail.com
 * @date 2009/06/02
*/
Ext.namespace('Marquee');
Marquee.marquee = function() {}
Marquee.marquee.prototype = {
    loadData: function(opt) {
        var recordTotal = 0;
        var field = Ext.data.Record.create([
			{ name: 'n_title', mapping: 'n_title' },
			{ name: 'n_url', mapping: 'n_url' }
		]);
        if (!Ext.isEmpty(opt.storeUrl)) {
            var store = new Ext.data.Store({
                proxy: new Ext.data.HttpProxy({
                    url: opt.storeUrl,
                    method: 'POST'
                }),
                baseParams: { httpPost: 'ajaxRequest' },
                reader: new Ext.data.XmlReader({
                    totalRecords: "totalRecords",
                    record: "record",
                    id: Ext.id()
                }, field)
            });
            store.load();
            store.on('load', function(s, record) {
                recordTotal = record.length;
                for (var i = 0; i < recordTotal; i++) {
                    var mqDom = Ext.get(opt.applyTo).createChild({ tag: 'div', cls: 'mqbox', html: '<a href=' + Base64.decode(record[i].get('n_url')) + ' class="mqbox">' + record[i].get('n_title') + '</a>' });
                }
                this.runTask(opt, recordTotal);
            }, this);
        }
        else { Ext.Msg.show({ title: '�錯誤!', msg: 'store需要一個webservice位址及指定方法名稱!' }); }
    },
    
     loadJsonData: function(opt) {
        if (!Ext.isEmpty(opt.storeUrl)) {      
        	var store = new Ext.data.JsonStore({
        			url: opt.storeUrl,
				    totalProperty: 'total',
				    root: 'data',
				    timeout:300,
					fields: ['n_title','n_url'],
					autoLoad:{
						scope:this,
						callback:function(record,option,success){	
							if (success){
								 for (var i = 1; i <= record.length; i++) {
				                     var mqDom = Ext.get(opt.applyTo).createChild({ tag: 'div', cls: (opt.itemCls!=undefined&&opt.itemCls!=''?opt.itemCls:'mqbox'), html: '<a href=' + record[i-1].get('n_url') + ' class="' + (opt.fontCls!=undefined&&opt.fontCls!=''?opt.fontCls:'mqboxfont') + '">' + record[i-1].get('n_title') + '</a>' });
				                }
				           		this.runTask(opt, record.length);
							}							
						}
					}
        	});
        	
        }else{ Ext.Msg.show({ title: '�錯誤!', msg: 'store需要一個webservice位址及指定方法名稱!' }); }
    },
    
    
    runTask: function(opt, recordTotal) {
        var mq = Ext.get(opt.applyTo);
        var mouseOver = false;
        mq.setStyle('margin-top', 0 + 'px');
        mq.setStyle('height', mq.dom.offsetHeight);
        
        mq.on('mouseout', function() {
            mouseOver = false;
        });
        mq.on('mouseover', function() {
            mouseOver = true;
        });

        var task = {
            run: function() {
                var sit = setInterval(function() {
                	
                    if ((parseInt(mq.getStyle('margin-top')) % opt.height) != 0) {
                        mq.setStyle('margin-top', parseInt(mq.getStyle('margin-top')) - 1 + 'px');
                        if (Math.abs(parseInt(mq.getStyle('margin-top'))) > (opt.height * (recordTotal -1))) {
                            //mq.setStyle('margin-top', opt.height + 'px');
                        	mq.setStyle('margin-top', '0px');
                        }
                    }
                    else {
                        clearInterval(sit);
                    }
                }, 30);
                if (!mouseOver) mq.setStyle('margin-top', parseInt(mq.getStyle('margin-top')) - 1 + 'px');
            },
            interval: opt.sec
        }
        var runner = new Ext.util.TaskRunner();
        runner.start(task);
    },
    
    render: function(opt) {
        this.loadData(opt);
    },
    
    renderByJson: function(opt) {
        this.loadJsonData(opt);
    }
}

AdTween = function (divId, json) {
    this.container = divId;
    this.total = 0;
    this.jsonText = json;
    this.aTweens = null;
    this.link = null;
    this.image = new Image();
    this.run = null;
    this.task = null;
    this.tcount = 0;
    this.openWin = null;
};

AdTween.prototype = {

    //初始化
    OnInit: function (sec) {
        var obj = null;

        try {
            if (this.jsonText == undefined || this.jsonText == '') throw Error("資料初始化失敗!");

            obj = Ext.util.JSON.decode(this.jsonText);
            this.total = obj.total;
            if (this.total > 0) {
                this.aTweens = obj.data;
                this.link = obj.link;
                this.RunTween(sec, this);
            }
            this.openWin = obj.openWin;
        }
        catch (e) { }
        finally {
            obj = null;
        }
    },

    //執行輪播
    RunTween: function (sec, obj) {
        this.task = {
            run: function () {
                var adHtml = null;
                var con = null;

                if (obj.tcount == (obj.total - 1))
                    obj.tcount = 0;
                else
                    obj.tcount++;

                obj.image.onload = function () {
                    con = Ext.get(obj.container);
                    adHtml = String.format('<a href="{0}" target="{1}" title=""><img src="{2}" style="vertical-align:middle;" alt="" /></a>', obj.link[obj.tcount], obj.openWin[obj.tcount], obj.aTweens[obj.tcount]);

                    if (obj.total == 1) {
                        con.update(adHtml).fadeIn({ endOpacity: 1, duration: 2 });
                        obj.run.stop(obj.task);
                    } else {
                        if (con != undefined && con != null) {
                            con.update(adHtml).fadeIn({ endOpacity: 1, duration: 1.5 });
                        }
                    }
                }
                obj.image.src = obj.aTweens[obj.tcount];
            },
            interval: sec
        }
        this.run = new Ext.util.TaskRunner();
        this.run.start(this.task);
    }
};
