<!--//

/*
Filter results using sub-genre checkboxes

To disable use of filters and only show content (such as on homepages), set config['hideFilters'] to true.
To disable use of pagination, set config['hidePagination'] to true.
*/

function filter(config) {
    if (typeof(ClickTaleExec) == 'function') {
        // if this doesnt work, create a new instance of the class and close it.
        ClickTaleExec("filter("+config+")"); // if ClickTale exists. 
    }

    this.results            = new Array();       // Store the results from JSON
    this.TimeToFade         = 500.0;

    this.hideFilters        = config['hideFilters'];
    this.hidePagination     = config['hidePagination'];
    this.top                = config['top'];
    this.artist             = config['artist'];
    this.category           = config['category'];
    this.subgenre           = config['subgenre'];
    this.pageNum            = config['pageNum'];
    this.pageType           = config['pageType'];
    this.limit              = config['limit'];
    this.previewSize        = config['previewSize'];
    this.box_list           = config['box_list'];
    this.sector_list        = config['sector_list'];
    this.filter_obj_name    = config['filter_obj_name'];
    this.display_type       = (config['display_type'] ? config['display_type'] : 'vertical');
    this.search_term        = config['search_term'];

    this.filter_form        = 'frm_filters';
    this.filter_sector_form = 'frm_sector_filters';
    this.pagination_div     = $(config['pagination_div']);
    this.products_list      = $(config['products_list']);

    this.no_results         = config['no_results'];
    
    this.staff_pick         = config['staff_pick'];
    
    this.isLoaded           = false;

    var me = this;

    // Make sure all boxes are checked on page load
    this.resetBoxes = function() {
        if (typeof(ClickTaleExec) == 'function') {
            ClickTaleExec("me.resetBoxes()"); // if clicktale exists
        }
        if ($(me.filter_form)) {
            $(me.filter_form).reset();
            $(me.filter_sector_form).reset();
        }
    }
    
    this.set_subgenre = function (subgenre) {
        if (typeof(ClickTaleExec) == 'function') {
            ClickTaleExec("me.set_subgenre("+subgenre+")"); // if clicktale exists
        }
    	me.subgenre = subgenre;
    }

    // Toggle the status of a checkbox in box_list
    this.editBoxList = function(box)
    { 
        if (typeof(ClickTaleExec) == 'function') {
            ClickTaleExec("me.editBoxList("+box+")"); // if clicktale exists
        }
        me.pageNum = 1;
        if (box=='all') {
            me.subgenre = '';
            for (property in me.box_list) {
                if (me.box_list[property]==0) {
                    me.box_list[property] = 1;
                }
            }
            me.resetBoxes();
        }
        else if (box=='none') {
            frm = $(me.filter_form);
            if (frm) {
                for (var el=0; el<frm.length; el++) {
                    me.box_list[frm.elements[el].value] = 0;
                    frm.elements[el].checked = false;
                }
            }
            me.products_list.innerHTML = me.no_results;
            me.pagination_div.innerHTML = "";
        }
        else if (box==this.staff_pick) {
            frm = $(me.filter_form);
            if (frm) {
                for (var el=0; el<frm.length; el++) {
                    if(frm.elements[el].value != this.staff_pick) {
                        me.box_list[frm.elements[el].value] = 0;
                        frm.elements[el].checked = false;
                    }
                }
            }
        }
        else if (box.checked==false) {
            me.box_list[box.value] = 0;
        }
        else {
            me.box_list[box.value] = 1;
        }

        if (box!='none') {
            me.getProducts(me.pageNum); // Uncomment to get requests on each checkbox change
        }
    }

    // Toggle the status of a checkbox in sector_list
    this.editSectorList = function(box)
    {
        if (typeof(ClickTaleExec) == 'function') {
            ClickTaleExec("me.editSectorList("+box+")"); // if clicktale exists
        }
        me.pageNum = 1;

        if (box.checked==false) {
            me.sector_list[box.value] = 0;
        }
        else {
            me.sector_list[box.value] = 1;
        }

        me.getProducts(me.pageNum); // Uncomment to get requests on each checkbox change
    }

    // Request filtered results
    this.getProducts = function(p)
    {
        if (typeof(ClickTaleExec) == 'function') {
            ClickTaleExec("me.getProducts("+p+")"); // if clicktale exists
        }
        // Make sure that any preview popups are closed before displaying a new page of results
        if (typeof activeItem!='undefined' && activeItem != '')
        {
            closePopups();
        }

        // Set page from p if it was passed. Use existing page value otherwise.
        if (p>0) {
            me.pageNum = p;
        }
        me.products_list.innerHTML = "";

        // Get items from box_list to list for submission
        var exclude_list = [];

        if (!me.hideFilters) {
            var n = 0;

            for (property in me.box_list) {
                if (me.box_list[property]==0) {
                    exclude_list[n] = property;
                    n++;
                }
            }
        }
    
        var exclude_sector_list = [];

        if (!me.hideFilters) {
            var n = 0;

            for (property in me.sector_list) {
                if (me.sector_list[property]==0) {
                    exclude_sector_list[n] = property;
                    n++;
                }
            }
        }

        // If another request is already active and not completed, cancel it before starting the new one
        if (me.mfRequest && me.mfRequest.transport.readyState < 4) {
            //alert(me.mfRequest.transport.readyState);
            me.mfRequest.abort();
            me.mfRequest = null;
        }

        // create ajax call
        var url = '/script/ajax/ajax-filters/ajax-filters.php';
        var params  = 'category=' + escape(me.category);
            params += '&subgenre=' + me.subgenre;
            params += '&display_type=' + me.display_type;
            params += '&artist=' + me.artist;
            params += '&exclude_list=' + escape(exclude_list.join('|'));
            params += '&exclude_sector_list=' + escape(exclude_sector_list.join('|'));
            params += '&page=' + me.pageNum;
            params += '&pageType=' + me.pageType;
            params += '&limit=' + me.limit;
            params += '&top=' + me.top;
            params += '&filter=' + me.filter_obj_name;
            
            if (me.search_term != 'undefined' && me.search_term) {
                params += '&searchTerm=' + me.search_term;
            }
            
        this.mfRequest = new Ajax.Request(url, {method:'post', parameters:params, onLoading:me.loading, onComplete:me.showProducts});
    }

    //loading function - this function displays the loading image
    this.loading = function() {
        if (typeof(ClickTaleExec) == 'function') {
            ClickTaleExec("me.loading()"); // if clicktale exists
        }
        if (!$('filter_loading')) {
            if (!me.isLoaded) {
                document.documentElement.style.cursor = 'wait';
        
                // create the div that will hold the loading image
                var div = document.createElement("div");
        
                // set the style properties for the div to display over the tab-page
                div.id = 'filter_loading';
               
                // create the new image and add it to the div
                var img = new Image();
                img.src = 'http://images-cdn.flycell.com/template/shared/images/ajax-loader.gif';
                div.appendChild(img);
                me.products_list.appendChild(div);
                me.isLoaded = true;
            }
        }
    }

    this.showProducts = function(my_results) {
        if (typeof(ClickTaleExec) == 'function') {
            ClickTaleExec("me.showProducts("+my_results+")"); // if clicktale exists
        }
        
        if (Ajax.activeRequestCount < 0) {
            Ajax.activeRequestCount = 0;
        }

        document.documentElement.style.cursor = 'default';
        
        // Assign JSON to the 'results' array
        me.results = eval("(" + my_results.responseText + ")");

        var product_total = me.results['total'];
        var products = me.results['products'];
        
        if (!me.hidePagination && me.pagination_div != 'undefined') {
            me.pagination_div.innerHTML = "";
        }
        
        if (product_total > 0 && products.length > 0) {
            if (!me.hidePagination && me.pagination_div != 'undefined') {
                me.makePagination(products.length, product_total);
            }

            me.makeProduct(0);
        }
        else {
            me.products_list.innerHTML += "No results found";
        }
        
        if ($('filter_loading')) {
            me.products_list.removeChild($('filter_loading'));
        }
    }

    this.makePagination = function(products_length, product_total)
    {
        if (typeof(ClickTaleExec) == 'function') {
            ClickTaleExec("me.makePagination("+products_length+","+product_total+")"); // if clicktale exists
        }
        if (me.results['footer']) {
            me.pagination_div.innerHTML = me.results['footer'];
            me.isLoaded = true;
        } else {
            me.pagination_div.innerHTML = '';
        }
        
        /*
        pages = Math.ceil(product_total / me.limit);

        if (pages > 1) {
            range_start = (me.limit * (me.pageNum - 1)) + 1;
            range_end = (me.limit * (me.pageNum - 1)) + products_length;

            min_page = me.pageNum - 2;
            max_page = me.pageNum + 2;
            if (min_page < 1) {
                min_page = 1;
            }
            if (max_page > pages) {
                max_page = pages;
            }

            //me.pagination_div.innerHTML += "<p>Displaying " + range_start + " to " + range_end + " of " + product_total + " products in " + pages + " pages of results</p>\n";

            // Use these lines to place pagination status shown above at the top of the product list instead of in the footer
            //pagination_status = document.createElement('p');
            //pagination_status_text = document.createTextNode("Displaying " + range_start + " to " + range_end + " of " + product_total + " products in " + pages + " pages of results");
            //pagination_status.appendChild(pagination_status_text);
            //me.products_list.parentNode.insertBefore(pagination_status, me.products_list);
    
            if (me.pageNum > 1) {
                prev_page = me.pageNum - 1;
                plink = document.createElement('a');
                plink.onclick = function() {
                    eval(me.filter_obj_name + '.getProducts('+ prev_page + ')');
                }
                plink.setAttribute('href', 'JavaScript:nolink()');
                ptext = document.createTextNode('\u00ab Previous');
                plink.appendChild(ptext);
                me.pagination_div.appendChild(plink);

                pspace = document.createTextNode(' ');
                me.pagination_div.appendChild(pspace);
            }

            for (x=min_page; x<=max_page; x++) {
                plink = document.createElement('a');
                plink.setAttribute('href', 'JavaScript:nolink()');
                if (x==me.pageNum) {
                    plink.style.fontWeight = 'bold';
                    plink.style.fontSize = '12px';
                }
                else {
                    plink.onclick = function() {
                        eval(me.filter_obj_name + '.getProducts('+ this.innerHTML + ')');
                    }
                }
                ptext = document.createTextNode(x);
                plink.appendChild(ptext);
                me.pagination_div.appendChild(plink);

                pspace = document.createTextNode(' ');
                me.pagination_div.appendChild(pspace);
            }

            if (pages > 1 && max_page < pages) {
                next_page = me.pageNum + 1;
                plink = document.createElement('a');
                plink.onclick = function() {
                    eval(me.filter_obj_name + '.getProducts('+ next_page + ')');
                }
                plink.setAttribute('href', 'JavaScript:nolink()');
                ptext = document.createTextNode('Next \u00bb');
                plink.appendChild(ptext);
                me.pagination_div.appendChild(plink);

                pspace = document.createTextNode(' ');
                me.pagination_div.appendChild(pspace);
            }
        }*/
    }

    this.makeProduct = function(n)
    {
        if (typeof(ClickTaleExec) == 'function') {
            ClickTaleExec("me.makeProduct("+n+")"); // if clicktale exists
        }
        var products = me.results['products'];
        var size = me.previewSize;

        for (n=0; n<products.length; n++) {
            product = products[n];

            product_id = 'product_' + product['default_publication_id'];
            product_li = product['html'];
            me.products_list.innerHTML += product_li;
            product_node = $(product_id);
        }

        //me.productFadeIn(0);
    }

    this.productFadeIn = function(n)
    {
        if (typeof(ClickTaleExec) == 'function') {
            ClickTaleExec("me.productFadeIn("+n+")"); // if clicktale exists
        }
        var products = me.results['products'];

        if (n < products.length) {
            product = products[n];
            product_id = 'product_' + product['default_publication_id'];
            me.fadeIn(product_id);

            n++;
            var fade_timer = setTimeout(me.filter_obj_name + ".productFadeIn(" + n + ")", 10);
        }
    }

    this.fadeIn = function(eid)
    {
        if (typeof(ClickTaleExec) == 'function') {
            ClickTaleExec("me.fadeIn("+eid+")"); // if clicktale exists
        }
        var element = $(eid);
        if(element == null) {
            return;
        }

        element.FadeState = -2;

        if(element.FadeState == 1 || element.FadeState == -1)
        {
            element.FadeState = element.FadeState == 1 ? -1 : 1;
            element.FadeTimeLeft = me.TimeToFade - element.FadeTimeLeft;
        }
        else
        {
            element.FadeState = element.FadeState == 2 ? -1 : 1;
            element.FadeTimeLeft = me.TimeToFade;
            setTimeout(me.filter_obj_name + ".animateFade(" + new Date().getTime()
                + ",'" + eid + "')", 33);
        }
    }

    this.animateFade = function(lastTick, eid)
    { 
        if (typeof(ClickTaleExec) == 'function') {
            ClickTaleExec("me.animateFade("+lastTick+","+eid+")"); // if clicktale exists
        }
        var curTick = new Date().getTime();
        var elapsedTicks = curTick - lastTick;

        var element = $(eid);

        if(element.FadeTimeLeft <= elapsedTicks)
        {
            element.style.opacity = element.FadeState == 1 ? '1' : '0';
            element.style.filter = 'alpha(opacity = '
                + (element.FadeState == 1 ? '100' : '0') + ')';
            element.FadeState = element.FadeState == 1 ? 2 : -2;
            return;
        }

        element.FadeTimeLeft -= elapsedTicks;
        var newOpVal = element.FadeTimeLeft/me.TimeToFade;
        if(element.FadeState == 1) {
            newOpVal = 1 - newOpVal;
        }

        element.style.opacity = newOpVal;
        element.style.filter = 'alpha(opacity = ' + (newOpVal*100) + ')';

        setTimeout(me.filter_obj_name + ".animateFade(" + curTick + ",'" + eid + "')", 33);
    }
}

function nolink() {
    if (typeof(ClickTaleExec) == 'function') {
            ClickTaleExec("me.nolink()"); // if clicktale exists
        }
    // Do nothing
}
//-->

