/*
 *  how this works:
 *  1. jQuery(window).hashchange(function(e){ .... });  detects any change in the url hash section. It needs the hashChange plugin.
 *  2. triggers the handleHashChange function
 *  3. the handlehashchange function reads the url get params and generates a new url, based on the hash + the ajax=1 parameter.
 *  (To test the result, just add &ajax=1 to any regular catalog url)
 *  4. the jquery.get function retrieves the ajax contents and updates the page contents.
 *  5. Any page can be called using just the function : loadAjaxProductsList(url,update_layered_navigation,update_compare_box,update_cart_box)
 *  Example:
 *      jQuery("a.link").click({
 *          loadAjaxProductsList( "http://www.mydomain.com/somepage.html?ajax=1" ,false,false,false);
 *      });
 *  That function should load the contents of http://www.mydomain.com/somepage.html in the col-main div (the central contents div)
 *
 **/

jQuery(document).ready(function(){
    var i=true;
    var j=true;
    var k="";
    var l="";
    
    /* sets whether to reload the navigation block/compare block , todo: remove them and to use only variables */
    function setReload_nav(a){
        window.reload_nav=a
    }
    function getReload_nav(){
        return window.reload_nav
    }
    function setReload_compare(a){
        window.reload_compare=a
    }
    function getReload_compare(){
        return window.reload_compare
    }
    function setCartDeleteText(a){
        window.cartDeleteText=a
    }

    setReload_nav(true);
    setReload_compare(true);

    /* 1. checking initial status of the url hash section  */
    var m=location.hash.slice(1);
    var currentHref = window.location.href;
    if(m!=""){  /*  if hash exists, trigger function */
        handleHashChange()
    }
    jQuery(window).hashchange(function(e){  /* declaring hash change function  */
    	if(currentHref.indexOf('privacy') !== -1 || currentHref.indexOf('terms') !== -1) {
    		if(location.hash.slice(1).indexOf('sby') !== -1) {
    			handleHashChange();
    		}
    	} else {
    		handleHashChange();
    	}
    });

    /* function to start the price slider */

    function StartSlider(){
        min_price=0;
        max_price=parseInt(jQuery("input#price_maximum").val());
        step_val=jQuery("input#step_value").val();
        step_val=parseInt(step_val);

        /* starts the slider, for more info, http://jqueryui.com/demos/slider/ */
        jQuery("#slider-range-price").slider({
            range:true,
            min:0,
            max:max_price,
            step:step_val,
            values:[jQuery("#init_price_minimum").val(),jQuery("#init_price_maximum").val()],
            slide:function(a,b){
                jQuery("input#price_maximum").val(jQuery("#slider-range-price").slider("values",1));
                jQuery("input#price_minimum").val(jQuery("#slider-range-price").slider("values",0))
            },
            change:function(a,b){
                jQuery("input#price_maximum").val(jQuery("#slider-range-price").slider("values",1));
                jQuery("input#price_minimum").val(jQuery("#slider-range-price").slider("values",0));
                new_url=jQuery("#price_slider_url").val()+"&price="+jQuery("#slider-range-price").slider("values",0)+","+jQuery("#slider-range-price").slider("values",1);
                setReload_nav(true);
                setReload_compare(false);
                window.location.hash=hashUrl(new_url)
            }
        });
        jQuery("input#price_maximum").val(jQuery("#slider-range-price").slider("values",1));
        jQuery("input#price_minimum").val(jQuery("#slider-range-price").slider("values",0))
    }

    /* start slider after page is loaded */
    StartSlider();


    /* all of those functions change the url hash, then the hashchange function handles the ajax page loading  */
    jQuery(".pager select, .toolbar select").live('change',function(){
        setReload_nav(true);
        setReload_compare(true);
        window.location.hash=hashUrl(jQuery(this).val());
        return false
    });
    jQuery(".pager a, .toolbar a").live('click',function(){
        setReload_nav(false);
        setReload_compare(false);
        window.location.hash=hashUrl(jQuery(this).attr("href"));
        return false
    });
    jQuery("#amshopby-price-btn, .amshopby-attr-selected a, .amshopby-attr a, .block-layered-nav #narrow-by-list a, .block-layered-nav .currently a, .block-layered-nav .actions a, .price_choice").live("click",function(){
    	setReload_nav(true);
        setReload_compare(true);
        if(jQuery(this).attr("id")=="price-filter-button"){
            step_val=parseInt(jQuery("input#step_value").val());
            request_price_min=Math.floor(jQuery("#price_minimum").val()/step_val)*step_val;
            request_price_max=Math.ceil(jQuery("#price_maximum").val()/step_val)*step_val;
            new_url=jQuery("#price_slider_url").val()+"&price="+request_price_min+","+request_price_max;
            window.location.hash=hashUrl(new_url)
        }else{
            window.location.hash=hashUrl(jQuery(this).attr("href"))
        }
        return false
    });
    jQuery(".col-main .add-to-links a.link-compare").live('click',function(){
        setReload_nav(false);
        setReload_compare(true);
        loadAjaxProductsList(jQuery(this).attr("href"),false,true);
        return false
    });
    jQuery(".block.block-compare a.btn-remove, .block.block-compare .actions a").live('click',function(){
        setReload_nav(false);
        setReload_compare(true);
        loadAjaxProductsList(jQuery(this).attr("href"),false,true);
        return false
    });

    /* function to handle the keyup even in the priceslider text boxes, if the user enters the values manually and not via the keyboard */
    jQuery("#price_minimum, #price_maximum").live("keyup",function(a){
        if(a.keyCode==13){
            jQuery("#price-filter-button").click()
        }
    });


    /* this function loads the ajax url when the hash has changed */

    function handleHashChange(){

        /* remove url variables and places the hash at the end of the url to retrieve the ajax content */
        var a=location.hash.slice(1);
        path=window.location.href;
        /*    
            changes 4.11.11
            path=path.split("?")[0];
         path=ajaxListURL(path+"?"+a);  */
        /* adds the ajax=1 variable to the url */
       
        path=path.split("#")[0];
        path=path.split("shopby/")[0];
        _sections = path.split("?");
        path=_sections[0];
        vars= _sections[1];
        if(!a){
        	path=window.location.href;
            path=path.replace("#","");
        }else if(a){
        	if(a.indexOf("sby") != -1) {
            	a = a.replace("sby","");
            	var tmp = a.split("/");
            	if(a.indexOf("?") != -1) {
            		pos = a.indexOf("?"); a = [a.substring(0, pos), a.substr(pos + 1)];
            		a[0] = a[0].replace(/&/g,"/"); 
            		a[1] = a[1].replace(/\?/g,"&");
            		a = a.join("?");
            		path=path+"shopby/"+a;
            	} else {
            		path=path+"shopby/"+a.replace(/&/g, '/');
            	}
            } else {
            	path=path+"?"+a;
            }
        }
        path = removeCMS(path);
        /* eof changes 4.11.11 */

        /** finds whether to reload the navigation and the compare box **/
        nv=getReload_nav();
        cm=getReload_compare();
        /* loads the ajax page contents */
        loadAjaxProductsList(path,nv,cm,false);
        /* resets the options to default */
        setReload_nav(true);
        setReload_compare(true);
    }
    
    function removeCMS(path) {
    	path = path.replace("about-qp", "");
    	path = path.replace("why-qp", "");
    	path = path.replace("education", "");
    	path = path.replace("terms", "");
    	path = path.replace("privacy", "");
    	path = path.replace("contacts/", "");
    	return path;
    }

    function loadAjaxProductsList(e,f,g,h){
        /* adds the loader to the page */
        jQuery(".col-main").append("<div class=\"products-list-loader\"><div></div></div>");
        /* adds the loader to the sidebar if the option is set to yes */
        if(f){
            jQuery(".block-layered-nav").append("<div class=\"products-list-loader\"><div></div></div>")
        }

        /* function to load the ajax contents via a get call */

        jQuery.get(e,{},function(a,b,c){
        	
        	var colMain = jQuery(a).find('.col-main');
        	var colLeft = jQuery(a).find('.block-layered-nav');
        	var cmsBlock = jQuery(a).find('.cms_block_top');
        	var titleText = jQuery(a).filter('title').text();

            if(b=="error"){
                jQuery(".col-main").html("<p>There was an error making the AJAX request</p>")
            }else{
            	var d = document.getElementById("page"); var sliderdiv = document.getElementById("slider-wrapper"); 
            	if(d != null && sliderdiv != null) {
                	d.removeChild(sliderdiv);
            	}
                /* loading the results to the main column */
                jQuery(".col-main").replaceWith(colMain);
                
                document.title = titleText;
                
                if(jQuery(".cms_block_top").length > 0) {
                	jQuery(".cms_block_top").replaceWith(cmsBlock);
                } else {
	                if(cmsBlock) {
	                	jQuery(".main-container").before(cmsBlock);
	                }
                }
                
                pageInit();
                /* loading layered navigation contents if needed */
                if(f){
                    jQuery(".block-layered-nav").replaceWith(colLeft);
                    //StartSlider()
                }
            }
        })
    }

    /* gets the url get parameters and appends them to the hash section of the current window  */
    function hashUrl(a){
        a.match(/\?(.+)$/);
        var b=RegExp.$1;
        if(b.indexOf("ajax=1")>=0){
            b=b.replace("ajax=1&","");
            b=b.replace("&ajax=1","");
            b=b.replace("ajax=1","");
        }
        if(a.indexOf("/shopby/") != -1) {
        	var tmp = a.split("/shopby/", 2);
        	tmp = tmp[1].split("/");
        	var counter = false;
        	for(var i=0;i<tmp.length;i++) {
        		if(tmp[i].indexOf("&") != -1) {
        			if(!counter) {
        				tmp[i] = tmp[i].replace('&',"?");
        				counter = true;
        			}
        		}
        	}
            b = tmp.join('&');
            b = "sby"+b;
            b = b.replace('.html','');
        }
        return b
    }
/*jQuery("#products-list button.btn-cart").live("click",function(){
    loadAjaxProductsList(jQuery(this).attr("rel"),false,false,true);
    return false
    })*/
});
