var Metrosplash;

if (!Metrosplash.component) {
    Metrosplash.component = {};
}

function userNoteDisplay( url, note )
{
   if ( note == false || note == "false" )
   {
      note = "";
   }

   alert( note + "\n\n" +
          "Thank you for shopping through FuelLinks.com.\n\nRemember, to earn Cash for Gas on your purchase, you must always access the merchant's website and complete the order through FuelLinks.com.\n\nIf you go direct to the merchant's site, we cannot record your purchase and credit you with a reward, even if you're completing an order originated through FuelLinks.com.\n\nTo make sure you earn the rewards you deserve, always start and finish your shopping through FuelLinks.com."
        );

   window.open( url, 'affiliatewindow_' + url.replace(/[^0-9]/g, "") );
}

Metrosplash.component.AffiliatesView = function(){

    Ext.QuickTips.init();
    var postUrl = "/generic-requests/affiliates.php";

    var categoryDataStore = new Ext.data.Store({
        url: postUrl,
        reader: new Ext.data.JsonReader({
            root: 'data',
            totalProperty: 'totalCount',
            id: 'id'
        }, [
           {name: 'category_id', mapping: 'id'}, 
           {name: 'name'}, 
           {name: 'icon'}, 
           {name: 'count'}, 
           {name: 'children'},
           {name: 'selected'}
        ]),
        baseParams: {
            type: 'affiliates',
            lang: 'json',
            action: 'categoryList'
        }
    });
    var merchantDataStore = new Ext.data.Store({
        url: postUrl,
        reader: new Ext.data.JsonReader({
            root: 'data',
            totalProperty: 'totalCount',
            id: 'affiliate_merchant_id'
        }, [
           { name: 'merchant_id', mapping: 'affiliate_merchant_id'}, 
           { name: 'name'}, 
           { name: 'image_url'}, 
           { name: 'link_url'}, 
           { name: 'reward', mapping: 'reward_amt'}, 
           { name: 'reward_type', mapping: 'reward_amt_type'}, 
           { name: 'premium'}, 
           { name: 'mid'}, 
           { name: 'note'}, 
           { name: 'display_note'}, 
           { name: 'aggregator_id'}, 
           { name: 'category_id'},
           { name: 'target'}
        ]),
        baseParams: {
            type: 'affiliates',
            lang: 'json',
            limit: 9,
            action: 'search'
        }
    });

    var storeExtraParams = { params: { start: 0 } };
    
    if(document.location.hash && document.location.hash != "")
    {
       var merchantId = Number(document.location.hash.split("#").join(""));
       storeExtraParams.params.merchant_id = merchantId;
    }
    
    categoryDataStore.load(storeExtraParams);
    merchantDataStore.load(storeExtraParams);
    
    var selectedCategoryId = null;
    var searchbox = null;
    var categoryLock = null;
    var merchantDataView = null;
    
    var categoryView;
    
    
    var tpl = new Ext.XTemplate(
    '<tpl for=".">',
       '<div class="category-wrap" id="{category_id}" >',
       '<p class="category">',
       '{name}',
       '<tpl if="this.countSet(count)"> ({count})</tpl>',
       '</p></div>',
       //'<tpl if="this.isSelected(selected, category_id)"></tpl>', 
    '</tpl>', 
    '<div class="x-clear"></div>', {
       countSet: function(count) {
          return count != "";
       },
       isSelected: function(selected, categoryID) {
          if (selected === 1) {
             categoryView.select(categoryID);
          }
          return selected === 1;
       }
       
    });
    
    
    categoryView = new Ext.DataView({
        id: 'categories',
        region: 'west',
        frame: false,
        collapsible: false,
        layout: 'table',
        overClass: 'category-wrap-over',
        itemSelector: 'div.category-wrap',
        selectedClass: 'category-wrap-selected',
        singleSelect: true,
        height: 745,
        width: 190,
        bodyStyle: {
           color: 'black',
           overflow: 'hidden',
           background: 'none'
        },
        tpl: tpl,
        tooltip: 'Click on any of the categories to narrow down the list of retailers to the right.',
        store: categoryDataStore,
            
        loadingText: 'Loading Categories...',
        emptyText: 'No categories to display'
        
    });
    
    
    categoryView.on('beforeclick', function(view, row, node,event){
        var record = categoryDataStore.getAt(row);
        searchBox.reset();
        selectedCategoryId = record.get("category_id");
        merchantDataStore.baseParams.name = null;
        merchantDataStore.baseParams.category_id = selectedCategoryId;
        merchantDataStore.load({ params: { start: 0 }	});
    });
    
   
    // ext:qtip="Click here to visit {name}.<br />You can earn {reward_type}{reward} today!"
    // ext:qtip="Earn {reward_type}{reward} today!" 
    
    var tpl = new Ext.XTemplate(
    '<tpl for=".">',
    
       '<div class="merchant-wrap"',
       'id="{merchant_id} <tpl if="this.isPremium(premium)"> premium</tpl>" style="text-align: center; ">',
       '<div class="merchant">',
    
       '<br /><span id="title"><strong><a href="#" onclick="userNoteDisplay(\'{link_url}\', \'{display_note}\')" ext:qtip="Click here to visit {name}.<br />You can earn ',
       '<tpl if="this.isPercentage(reward_type)">{reward}{reward_type}</tpl>',
       '<tpl if="this.isDollar(reward_type)">{reward_type}{reward}</tpl>',
       ' today!">{name}</a></strong></span>',
       '<br /><br />', 
       '<span id="image"><a href="#" onclick="userNoteDisplay(\'{link_url}\', \'{display_note}\')" ><img src="{image_url}" border="0" width="120" ext:qtip="Click here to visit {name}.<br />You can earn ',
       '<tpl if="this.isPercentage(reward_type)">{reward}{reward_type}</tpl>',
       '<tpl if="this.isDollar(reward_type)">{reward_type}{reward}</tpl>',
       ' today!" /></a></span>', 
       '<br /><br />', 
       '<span id="earnText">Earn&nbsp;&nbsp;&nbsp;<strong ext:qtip="Earn ',
       '<tpl if="this.isPercentage(reward_type)">{reward}{reward_type}</tpl>',
       '<tpl if="this.isDollar(reward_type)">{reward_type}{reward}</tpl>',
       ' today!">',
       '<tpl if="this.isPercentage(reward_type)">{reward}{reward_type}</tpl>',
       '<tpl if="this.isDollar(reward_type)">{reward_type}{reward}</tpl>',
       '</strong></span>&nbsp;&nbsp;&nbsp;&nbsp;',
       '<span id="visitNow"><a href="#" onclick="userNoteDisplay(\'{link_url}\', \'{display_note}\')" ext:qtip="Earn ',
       '<tpl if="this.isPercentage(reward_type)">{reward}{reward_type}</tpl>',
       '<tpl if="this.isDollar(reward_type)">{reward_type}{reward}</tpl>',
       ' today! at: <br />{name}">visit now</a></span>', 
       '', 
       '</div></div>', 
    '</tpl>', 
    '<div class="x-clear"></div>', {
       isPercentage: function(type) {
          return type === '%';
       },
       isDollar: function(type) {
          return type === '$';
       },
       isPremium: function(premium) {
          return premium == true;
       }
       
    });
    
   
    //var tpl = Ext.XTemplate.from('boxTpl');
    var merchantView = new Ext.Panel({
        id: 'merchants',
        region: 'center',
        frame: false,
        collapsible: true,
        height: 530,
        bodyStyle: {
            overflow: 'hidden',
            color: 'black',
            "text-align": "center",
            background: 'none'
        },
        items: [{
              contentEl: 'tandcText'
           },merchantDataView = new Ext.DataView({
            store: merchantDataStore,
            tpl: tpl.compile(),
            collapsible: true,
            layout: 'table',
            bodyStyle: 'margin-left: auto; margin-right: auto;',
            overClass: 'merchant-wrap-over',
            emptyText: 'No retailers to display',
            loadingText: 'Loading retailers...',
            itemSelector: 'div.merchant-wrap',
       	   selectedClass: 'merchant-wrap-selected'
        })],
        bbar: new Ext.PagingToolbar({
            pageSize: 9,
            displayInfo: true,
            displayMsg: 'Retailers {0} - {1} of {2}',
            emptyMsg: "No retailers to display",
            store: merchantDataStore,
            style: {
                color: 'black'
            }
        }),
        tbar: new Ext.Toolbar({
            items: [
            'Find by name: ',
            searchBox = new Ext.form.ComboBox({
                name: 'name',
                store: merchantDataStore,
                listWidth: 0,
                hideLabel: true,
                hideTrigger: true,
                queryDelay: 250
            }), 
            ' ', 
            ' ', 
            categoryLock = new Ext.Button({
                enableToggle: false,
                text: 'Find in category',
                handler: function(){
                    merchantDataStore.load({params: {category_id: selectedCategoryId, start: 0}});
                },
                tooltip: "Press to find Retailers by name only in the selected category."
            }), 
            new Ext.Toolbar.Button({
                handler: function(){
                    merchantDataStore.baseParams.category_id = null;
                    merchantDataStore.baseParams.name = null;
                    categoryDataStore.load();
                    merchantDataStore.load({ params: { start: 0 } });
                    searchBox.reset();
                    categoryLock.toggle(false);
                },
                tooltip: "Press to find Reset the results and start over with the Deals of the Day.",
                text: 'Reset',
                icon: '/generic-assets/ext2/resources/images/default/icons/fam/table_refresh.png',
                cls: 'x-btn-text-icon'
            })],
            style: "color: black; border-bottom: 1px rgb(160,160,160) solid; text-align: left"
        })
    })
    
    
    if (searchBox) {
    
        searchBox.addListener("beforequery", function(queryEvent){
            this.collapse();
            merchantDataStore.baseParams.name = queryEvent.query;
            merchantDataStore.load({ params: { start: 0 } });
            merchantDataStore.on("load", function(){
                this.removeListener("load", this);
            });
            
            return false;
        });
        
        searchBox.addListener("keypress", function(e){
            if (e.getKey() == e.ENTER && this.getValue().length > 0) {
                this.collapse();
                merchantDataStore.baseParams.name = e.query;
                merchantDataStore.load({ params: { start: 0 } });
                merchantDataStore.on("load", function(){
                    this.removeListener("load", this);
                });
            }
        });
        searchBox.addListener("expand", function(combo){
            combo.collapse();
            return false
        });
    }
    
    var config = {
        id: 'merchantComponent',
        layout: 'border',
        layoutConfig: {
           // layout-specific configs go here
           titleCollapse: false,
           animate: true,
           activeOnTop: true
        },
        height: 640,
        frame: true,
        collapsible: false,
        headerAsText: false,
        title: 'FuelLinks Online Retailers',
        bodyStyle: "background: none; border: 0;",
        items: [{
            region: 'west',
            id: 'categoryList',
            title: "Pick a Category",
            items: categoryView,
            bodyStyle: "background: rgb(220,220,220); border: 1px solid #D0D0D0;",
            margins: '0 3 0 0',
            
            collapsible: true,
            width: 190
        }, {
            region: 'center',
            id: 'merchantsPanel',
            title: 'Pick a Retailer:',
            bodyStyle: "background: none; border: 0;",
            items: merchantView
        }]
    }
    if (arguments.length > 2 && typeof(arguments[2]) == 'object') {
        if (arguments[3] && arguments[3] == true) {
            config = arguments[2];
        }
        else {
            for (var x in arguments[2]) {
                config[x] = arguments[2][x];
            }
        }
    }
    
    Metrosplash.component.AffiliatesView.superclass.constructor.call(this, config);
}
Ext.extend(Metrosplash.component.AffiliatesView, Ext.Panel);
