﻿Ext.namespace('Trakkware', 'Trakkware.WeledaMap');

/* when working with asp.net and Extjs we need the content type to application/json */
if (Ext.Ajax.defaultHeaders === undefined) Ext.Ajax.defaultHeaders = {};
Ext.apply(Ext.Ajax.defaultHeaders, { 'Content-Type': 'application/json' });

Trakkware.WeledaMap = function(uid, ingUID, prodlistUID, titleUID, ingID) {
    this.productList = new Ext.XTemplate(
		'<div style="clear:both; margin-bottom: 2em">',
			'<div class="fairTradeProductsImg">',
				'<a href="{producturl}"><img src="{imgurl}" /></a>',
			'</div>',
			'<div class="fairTradeProductsRightStuff">',
				'<p><a href="{producturl}">{name}</a></p>',
				'<div class="moreButton"><a href="{producturl}"><img src="/images/template/MoreBtn.png" alt="{name}" /></a></div>',
			'</div>',
		'</div>'
	);

    this.ingredientTitle = new Ext.XTemplate(
        '<div class="fairTradeIngTitle">',
            '<h1>{name}</h1>',
        '</div>'
    );

    this.ingredientDetail = new Ext.XTemplate(
		'<div>',
			'<div>{description}</div>',
		'</div>'
	);

    this.uid = uid;
    this.ingredientEl = Ext.get(ingUID);
    this.productsEl = Ext.get(prodlistUID);
    this.titleEl = Ext.get(titleUID);
    this.currentIngredient = 0;
    this.init("");
    
    if(ingID != undefined && ingID != '') miniClicked(ingID);
}

Ext.extend(Trakkware.WeledaMap, Ext.util.Observable, {
    init: function(initData) {

        this.productListStore = new Ext.data.JsonStore({
            url: '/Code/Services/WeledaAjax.svc/GetFairTradeProducts',
            root: 'items',
            fields: ['imgurl', 'name', 'producturl']
        });

        this.ingredientDetailStore = new Ext.data.JsonStore({
            url: '/Code/Services/WeledaAjax.svc/GetFairTradeIngredient',
            root: 'd',
            fields: ['name', 'description']
        });

        /*		var subindex = window.location.href.indexOf('#');
        if (subindex > 0) {
        var startsWith = window.location.href.substring(subindex + 1);
        initData = undefined;
        }

		if (initData !== undefined) {
        this.store.loadData(initData);
        } else {
        this.store.load({
        method: 'POST',
        params: Ext.encode({
        startsWith: (startsWith || 'a')
        })
        });
        }

		Ext.History.on('change', this.historyChanged, this);

		// wire up the index control

		this.indexEl.select('a').on('click', this.indexChanged, this);
        */
    },

    load: function(ingID, count) {
        // set current ingredient
        if (ingID == undefined) ingID = this.currentIngredient;
        this.currentIngredient = ingID;

        //		Ext.History.add(startsWith, true);
        this.ingredientDetailStore.load({
            method: 'POST',
            params: Ext.encode({
                ingID: ingID
            }),
            scope: this,
            callback: function() {
                this.renderIngredient(this.ingredientDetailStore.reader.jsonData.d);
            }
        });

        // Show five ingredients if a count wasn't supplied.
        this.productListStore.load({
            method: 'POST',
            params: Ext.encode({
                ingID: ingID
            }),
            scope: this,
            callback: function() {
                this.renderProductList(this.productListStore.reader.jsonData.d.items, count, ingID);
            }
        });

        // hide the fair trade explanations.
        var left = document.getElementById('leftFairTrade');
        left.style.display = 'none';
        left.style.visibility = 'hidden';

        var right = document.getElementById('rightFairTrade');
        right.style.display = 'none';
        right.style.visibility = 'hidden';

        var title = document.getElementById('fairTradeTitle');
        title.style.display = 'none';
        title.style.visibility = 'hidden';

    },
    /*
    historyChanged: function(arrayOfHistoryTokens) {
    if (arrayOfHistoryTokens.match(/[A-Za-z]+/gi) != null) {
    this.load(arrayOfHistoryTokens);
    } else {
    this.renderIngredientList(this.store.reader.jsonData.d);
    }
    },
    */
    clearSummary: function() {
        this.ingredientEl.update('');
        this.productsEl.update('');
        this.titleEl.update('');

        var left = document.getElementById('leftFairTrade');
        left.style.display = 'block';
        left.style.visibility = 'visible';

        var right = document.getElementById('rightFairTrade');
        right.style.display = 'block';
        right.style.visibility = 'visible';

        var title = document.getElementById('fairTradeTitle');
        title.style.display = 'block';
        title.style.visibility = 'visible';
    },

    // data is array of ingredient items
    renderProductList: function(data, count, ingID) {
        if (data !== undefined) {
            if (count == undefined || count > data.length) {
                count = data.length;
            }

            this.productsEl.update('');

            for (var ii = 0; ii < count; ii++)
                this.productList.append(this.productsEl, data[ii]);

            var easybtn = document.getElementById('fairTradeProductsMoreBtn');
            if (count < data.length) {
                var btn = Ext.get('fairTradeProductsMoreBtn');
                btn.show(true);
                easybtn.onclick = function() { GetWeledaMap().load(); };
            } else {
                easybtn.style.display = 'none';
                easybtn.style.visibility = 'hidden';
            }
        }
    },

    // data is the ingredient data
    renderIngredient: function(data) {
        if (data !== undefined) {
            this.ingredientDetail.overwrite(this.ingredientEl, data);
            this.ingredientTitle.overwrite(this.titleEl, data);
        }
    }

    /*	getDetails: function(e, el) {

	var recid = Ext.fly(el).parent('.details').getAttributeNS('', 'recid');
    Ext.History.add(recid, true);

	this.contentEl.fadeOut({
    endOpacity: 0,
    easing: 'easeOut',
    duration: .5,
    scope: this,
    callback: function() {
    var s = this.store;
    var i = s.find('recId', recid);
    if (i != -1) {
    this.renderIngredientDetails(s.getAt(i).data);
    this.contentEl.setVisible(true);
    } else {
    // we have an error
    }
    }
    });
    },

	indexChanged: function(e, el) {
    var startsWith = Ext.fly(el).getAttributeNS('', 'letter');
    this.load(startsWith);
    }*/
});

