/*
	This javascript file is used to generate products collection from either multiple categories or single category through  
    Ajax requests.
*/
var Azexis = Azexis || {};

Azexis.products = (function(){

    var productsDOM = '#shop-category-page #isle';
    
    // cats is an array that is passed to the server in the ajax request
    var cats = [];
    
    /* for now, show the first child as default category. Later, should be able to detect dynamically. 
    *  This can be achieved by getting the default category index from the css class of the active tab 
    */
    var default_cat_index = 0; 
    
    function showWarning(){
       var warning = '<span class="product-collection-warning">Please select a shape</span>';
       $E('#shop-category-page #isle').innerHTML = warning;
    }
    
    function multipleCategories(){
        var categoriesDOM = '#page-body #banner #categories div.tab';
        var activeCatCss = 'tab-active';
        $$(categoriesDOM).each(function(cat_div,index){
            var req_data;
            cat_div.state = 'off';    
            
            cat_div.addEvent('click', function(e){
            
                showAjaxLoadingMsg();
                deactivateAll(categoriesDOM,activeCatCss);
                cat_div.addClass(activeCatCss);
                //cat_div.id will be in the format - categoryTab_ddd, so extract the categoryId after the underscore
                cat_id = cat_div.id.substr(cat_div.id.indexOf('_') + 1);   
            
                /* Only on the first ajax request, 
                 * we should show the default category also along with the category that is clicked.
                */
                if(default_cat_index >= 0){
                    if(index != default_cat_index){ 
                        var default_cat_div = $$('#page-body #categories div')[default_cat_index];
                        var default_cat_id = default_cat_div.id.substr(default_cat_div.id.indexOf('_') + 1); 
                        cats.push(default_cat_id);
                        default_cat_index = -1; //resetting the default_cat_index
                    }
                }
                
                /* Toggling the category state on every click. */
                if(cat_div.state == 'on'){
                      cat_div.state = 'off';
                      cats.remove(cat_id);
                }else{
                      cat_div.state = 'on';
                      cats.push(cat_id);
                }
                
                //Make sure that cats array has only unique elements
                cats = array_unique(cats);
                
                /* Ajax request only when atleast one category is selected
                *  Otherwise, display a message
                */
                if(cats.length > 0){
                    req_data = 'cat_ids=' + cats.join(',');
                    req_data += '&cid=' + Azexis.parseQueryString('cid');
                
                    var options = {
                        data: req_data,
                        method: 'get',
                        onComplete: showProducts
                    }
                    new Ajax('index.php',options).request();
                }else{
                    /* Reset default category, if its deselected for the first time after the page loads.
                    *  Otherwise, its shown along with other categories on the next ajax request.
                    */
                    if(index == default_cat_index){
                        $$(categoriesDOM)[default_cat_index].state = 'off';
                        default_cat_index = -1;
                    }
                    //No ajax request, so display warning message
                    showWarning();
                }
            });
            
            cat_div.addEvent('mouseover', function(e){
               //TODO - 
            });
            
        });
        /* Set the state of only the default category as on */
        var default_cat_div = $$(categoriesDOM)[default_cat_index];
        if(default_cat_div)
            default_cat_div.state = 'on';
    }
    
    function animateProductsHeight(){
       var currentHeight = getHeight(productsDOM+ ' #products').toInt();
       var heightAnim = $E(productsDOM).effect('height');
       //Add padding-top and padding-bottom to the currentHeight. Refer shop/css/layout.css for the padding values
       heightAnim.start(currentHeight+65); 
    }
    
    function showProducts(response){
       $('shop-category-page').innerHTML = response;
       animateProductsHeight();
       //Calling ajaxPageLoader() again to disable links on page numbers and to register events on each page number li item
	   singleCategory();
       ajaxPageLoader();
    }
    
    function showAjaxLoadingMsg(){
       $('products').innerHTML = '<span class="ajax-loading-msg">Loading</span>';
    }
    
    function deactivateAll(container, activeCls){
       var divs = $$(container);
       for(var i=0;i<divs.length;i++){
          var div = divs[i];
          div.removeClass(activeCls);
       }
    }
    
    function singleCategory(){
        var categoriesDOM = '#page-body #banner #categories div.tab';
        var activeCatCss = 'tab-active';
        disableLinks(categoriesDOM + ' a');
        $$(categoriesDOM).each(function(cat_div){
            var req_data;
            
			var link = $E("a", cat_div);
			
            cat_div.addEvent('click', function(e){
                showAjaxLoadingMsg();
                deactivateAll(categoriesDOM,activeCatCss);
                cat_div.addClass(activeCatCss);
                //cat_div.id will be in the format - categoryTab_ddd, so extract the categoryId after the underscore
                cat_id = cat_div.id.substr(cat_div.id.indexOf('_') + 1);   
            
				var options = {
                    method: 'get',
                    onComplete: showProducts
                }
                new Ajax(link.href,options).request();
            });
            
            cat_div.addEvent('mouseover', function(e){
               //TODO - 
            });
            
        });
    }
    function setHeight(container,newHeight){
       $E(container).setStyle("height",newHeight);
    }
    function getHeight(container){
       return $E(container).getStyle("height");
    }
    function ajaxPageLoader(){
        var pageNumbersDOM = '#shop-category-page #isle div.data-grid-nav li';
        var currentPageCss = 'current-page';
        disableLinks(pageNumbersDOM + ' a');
        $$(pageNumbersDOM).each(function(page_li){
            var req_data;
            
            page_li.addEvent('click', function(e){
            
                var page_link, page_num, currentPageLi;
                
                if(page_li.hasClass('separator') || page_li.hasClass('inactive'))
                   return;
                
                page_link = $E('a', page_li);
                //Check whether the page number li has a hyperlink or not and proceed only if it has one
                if(page_link){
                    if(page_li.hasClass('page-num')){   
                        page_link.parentNode.addClass(currentPageCss);
                        page_num = page_link.innerHTML;   
                    }
                    else {
                        currentPageLi = $E('li.current-page','#shop-category-page #isle div.data-grid-nav');
                        if(page_li.hasClass('next')){
                           page_num = parseInt(currentPageLi.innerHTML) + 1;
                        }
                        else if(page_li.hasClass('prev')){
                           page_num = parseInt(currentPageLi.innerHTML) - 1;
                        }
                    }
                    
                    var currentHeight = getHeight(productsDOM);
                    setHeight(productsDOM,currentHeight);
                    
                    showAjaxLoadingMsg();
                    req_data = page_link.search.slice(1);
					page_link = new String(page_link);
					page_url = page_link.substring(0, page_link.indexOf('?'));
                    var options = {
                        data: req_data,
                        method: 'get',
                        onComplete: showProducts
                    }
                    //new Ajax(window.location.pathname,options).request();
					new Ajax(page_url,options).request();
                }
            });
        });
    }
    
    function disableLinks(linksDOM){
        $$(linksDOM).each(function(link){
           link.addEvent('click', function(e){
               e = new Event(e);
               e.preventDefault();
               return false;
           });
        });
    }
    
    /* Generates a unique array from a duplicate array
    */
    function array_unique(dup_array){
       var uniq_array = [];
       for(var i=0;i<dup_array.length;i++){
          if(uniq_array.indexOf(dup_array[i], 0, dup_array) < 0){ 
            uniq_array.push(dup_array[i]); 
          }
       }
       return uniq_array;
    }
    
    return { 
        multipleCategories: multipleCategories,
        singleCategory: singleCategory,
        ajaxPageLoader: ajaxPageLoader
    }
})();

window.addEvent("domready", function() {
    
    //Azexis.products.multipleCategories(); //Enable to show products from multiple categories
    Azexis.products.singleCategory(); // Show products from only a single category by default.
    Azexis.products.ajaxPageLoader();
});

