﻿/**
 * 輪播式廣告物件v1.0
 * 程式運作需掛載Ext2.2套件，後端WebService須於web.config
 * 開啟HttpPost方式，資料須回傳含有totalRecords及record標籤
 * 每組record標籤內含有ad_link及img_url標籤。格式如下:
 * <record>
 * 	<ad_link>廣告連結</ad_link>
 * 	<img_url>廣告圖檔位址</img_url>
 * </record>
 * <totalRecord>資料筆數</totalRecord>
 * 
 * @param string storeUrl: WebService網址/方法
 * @param string applyTo: 頁面div id
 * @param int sec: 輪播秒數
 * @param bool random: 輪播或靜態展示
 * @config {storeUrl:'WebService網址/方法', applyTo:'頁面div id', sec: 輪播秒數, random: 輪播或靜態展示}
 * @example
 * var ad = new Ad.marquee();
 * ad.render({config});
 * 
 * @author hochente@gmail.com
 * @date 2009/06/02
 */
Ext.namespace('Ad');
Ad.marquee = function() {}
Ad.marquee.prototype = {
    ImgArray: null,
    UrlArray: null,
    random: false,
    currCount: 0,
    adContent: null,
    adDom: null,
    loadData: function(opt) {
        var recordTotal = 0;
        var field = Ext.data.Record.create([
			{ name: 'ad_link', mapping: 'ad_link' },
			{ name: 'img_url', mapping: 'img_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) {
                if (record.length != 0) {

                    this.ImgArray = new Array(record.length);
                    this.UrlArray = new Array(record.length);
                    for (var i = 1; i <= record.length; i++) {
                        this.ImgArray[i - 1] = new Image;
                        this.ImgArray[i - 1].src = Base64.decode(record[i - 1].get('img_url'));
                        this.UrlArray[i - 1] = record[i - 1].get('ad_link');
                    }

                    this.adContent = record;
                    if (this.random)
                        this.runTask(opt);
                    else
                        this.runStatic(s, opt);
                }
            }, this);
        }
        else { Ext.Msg.show({ title: '錯誤!', msg: 'store需要一個webservice位址及指定方法名稱!' }); }
    },

    changeAd: function(ad) {
        if (ad.currCount >= ad.adContent.length) { ad.currCount = 0; }
        //判斷圖片讀取
//        if (ad.ImgArray[ad.currCount].complete) {
            ad.adDom.dom.innerHTML = String.format("<a href=\"{0}\"><img src=\"{1}\" style=\"vertical-align:middle;border:none;\" alt=\"\"/></a>", ad.UrlArray[ad.currCount], ad.ImgArray[ad.currCount].src);
//        } else {
//            ad.adDom.dom.innerHTML = "<img src=\"../images/mstore/loading_s.gif\" style=\"vertical-align:middle;\" alt=\"Loading...\"/><span style=\"font-size:10px; color:#999;\">資料讀取中...</span>";
//            ad.ImgArray[ad.currCount].onload = function() {
//                 ad.adDom.dom.innerHTML = String.format("<a href=\"{0}\"><img src=\"{1}\" style=\"vertical-align:middle;border:none;\" alt=\"\"/></a>", ad.UrlArray[ad.currCount], this.src);
//            }
//        }
        
        ad.adDom.fadeIn({
            endOpacity: 1,
            easing: 'easeNone',
            duration: .8
        });
        if (ad.currCount <= ad.adContent.length) {
            ad.currCount++;
        }
    },

    runStatic: function(st, opt) {
        var xtpl = new Ext.XTemplate(
			'<tpl for=".">',
				'<ul style="list-style: none none outside; margin: 0px; padding: 0px;">',
				'<li style="display:inline; float:left; margin-left:2px; margin-bottom:5px">',
					'<img src="{imgUrl}" style="border:none; width:165px; height:55px; cursor:pointer;" onclick="location.href=\'{url}\';" alt=""/>',
				'</ul>',
				'</li>',
			'</tpl>'
		);
		
        var sideView = new Ext.DataView({
            store: st,
            tpl: xtpl,
            applyTo: opt.applyTo,
            autoHeight: true,
            multiSelect: true,
            overClass: '',
            itemSelector: '',
            prepareData: function(data) {
                data.url = data.ad_link;
                data.imgUrl = Base64.decode(data.img_url);
                return data;
            }
        });
    },
    runTask: function(opt) {
        var task = {
            run: function() {
                this.changeAd(this);
            },
            interval: opt.sec,
            scope: this
        }
        var runner = new Ext.util.TaskRunner();
        runner.start(task);
    },
    render: function(opt) {
        this.random = opt.random;
        this.adDom = Ext.get(opt.applyTo);

        this.loadData(opt);
    }
}