navigationLoadInProccess = false;

function startLoadNavigationData(){
	
    if(navigationLoadInProccess){
        return false;
    }
	
    navigationLoadInProccess = true;
	
    var overlay = $('advanced-navigation-overlay');
	
    if($$('div.category-products').length > 0){
	
        var element = $$('div.category-products')[0];
    
    }else if($$('div.col-main p.note-msg')){
    
        var element = $$('div.col-main p.note-msg')[0];
    
    }else{
    	
        return;
    }
	
    if(!overlay){
        overlay = $(document.createElement('div'));
        overlay.id = 'advanced-navigation-overlay';
        document.body.appendChild(overlay);
    }
	
    var offsets = element.cumulativeOffset();
    overlay.setStyle({
        'top'	    : offsets[1] + 'px',
        'left'	    : offsets[0] + 'px',
        'width'	    : element.offsetWidth + 'px',
        'height'	: element.offsetHeight + 'px',
        'position'  : 'absolute',
        'display'   : 'block',
        'zIndex'	: '2000' // Value mast be more than any element from content have
    });
	
    var loadinfo = document.createElement('div');
	
    if(loadimagealign == 'bottom'){
	
        loadinfo.innerHTML = gomage_navigation_loadinfo_text+'<img src="'+loadimage+'" alt="" class="align-'+loadimagealign+'"/>';
	
    }else{
		
        loadinfo.innerHTML = '<img src="'+loadimage+'" alt="" class="align-'+loadimagealign+'"/>'+gomage_navigation_loadinfo_text;
		
    }
	
    loadinfo.id = "navigation_loadinfo";
    loadinfo.className = "gan-loadinfo";
	
    document.body.appendChild(loadinfo);
	
    return navigationLoadInProccess;
	
}

function stopLoadNavigationData(){
	
    var overlay = $('advanced-navigation-overlay');
	
    if(overlay){
        overlay.style.display = 'none';
    }
	
    document.body.removeChild($('navigation_loadinfo'));
	
    return navigationLoadInProccess = false;
	
}
	     
function generateUrlWithParams (url, params) {
	
    var query    = {},
    keys     = url.split('?')[1].split('&'),
    key      = '',
    glue     = '',
    strQuery = '',
    i        = -1;
    while (++i < keys.length) {
        key = keys[i].split('=');
        query[key[0]] = key[1];
    }
		
    for (attrname in query) {
        if (!params.hasOwnProperty(attrname))
            params[attrname] = query[attrname];
    }
    params['ajax'] = 0;

    for (key in params) {
        strQuery += glue + key + '=' + params[key];
        glue = '&';
    }
    if (strQuery != '') {
        url = url.split('?')[0] + '?' + strQuery;
    }
    return url;
}

function submitNavigationForm(form, url, is_ajax) {
	
	return;
    var from = $(form).down('input.navigation-from');
    var to = $(form).down('input.navigation-to');
	
    var re = /^[0-9]*$/;
    if (!re.test($(from).value))
    {
        alert('Please use only numbers (0-9) in this field.');
        return false;
    }
    if (!re.test($(to).value))
    {
        alert('Please use only numbers (0-9) in this field.');
        return false;
    }
		
    if ((parseFloat($(from).value) > parseFloat($(to).value)) ||
        ((parseFloat($(from).value) == 0 && parseFloat($(to).value) == 0)))
        {
        alert('Filter range is invalid.');
        return false;
    }
	
    is_ajax = typeof(is_ajax) != 'undefined' ? is_ajax : true;
    
    var url = url.replace(/&amp;/ig, '&');
	
    var elements = form.elements;
	
    //var params = Object.clone(navigationOpenFilters);

    for(var i=0;i< elements.length;i++){
		
        element = elements[i];
		
        switch(element.nodeName){
			
            case 'INPUT': case 'SELECT': case 'TEXTAREA':
				
                if(element.value){
				
                    params[element.name] = element.value;
				
                }
				
                break
			
        }
		
    }
	
    if(!url){
        url = form.action;
    }
	
    if (!is_ajax) {
        setLocation(generateUrlWithParams(url, params));
    } else if(startLoadNavigationData()){
	
	
        var request = new Ajax.Request(url,
        {
            method:'GET',
            parameters:params,
            onSuccess: function(transport){
	    	
                var response = eval('('+(transport.responseText || false)+')');
	    	
                replaceNavigationBlock(response.navigation);
                replaceProductsBlock(response.product_list);
                replaceLeftRightNavigationBlocks('gan-left-nav-main-container', response.navigation_left);
                replaceLeftRightNavigationBlocks('gan-right-nav-main-container', response.navigation_right);
			
                if(response.eval_js){
                    eval(response.eval_js);
                    navigation_eval_js = response.eval_js;
                }
						
                stopLoadNavigationData();
	      
            },
            onFailure: function(){
                stopLoadNavigationData();
            }
        });
	  
    }
	
}

function setNavigationUrl(url){
    is_ajax = typeof(is_ajax) != 'undefined' ? is_ajax : true;
    var url = url.replace(/&amp;/ig, '&');

    if(startLoadNavigationData()){

        var request = new Ajax.Request(url,
        {
            method:'get',
            parameters:navigationOpenFilters,
            onSuccess: function(transport){
	    	
                var response = eval('('+(transport.responseText || false)+')');
	    	
                replaceNavigationBlock(response.navigation);
                replaceProductsBlock(response.product_list);
                replaceLeftRightNavigationBlocks('gan-left-nav-main-container', response.navigation_left);
                replaceLeftRightNavigationBlocks('gan-right-nav-main-container', response.navigation_right);
						
                if(response.eval_js){
                    eval(response.eval_js);
                    navigation_eval_js = response.eval_js;
                }
			
                stopLoadNavigationData();
	      
            },
            onFailure: function(){
                setLocation(url); //trying redirect to url
            }
        });
	  
    }
	
}

function replaceProductsBlock(content){
	
    if($$('div.category-products').length > 0){

        element = $$('div.category-products')[0];

    }else if($$('div.col-main p.note-msg').length > 0){

        element = $$('div.col-main p.note-msg')[0];

    }else{

        return;
    }



    if (content && content.toElement){

        content = content.toElement();

    }else if (!Object.isElement(content)) {

        content = Object.toHTML(content);
        var tempElement = document.createElement('div');
        content.evalScripts.bind(content).defer();
        content = content.stripScripts();
        tempElement.innerHTML = content;


        el =  getElementsByClassName('category-products', tempElement);

        if (el.length > 0)
        {
            content = el[0];
        }
        else
        {
            el = getElementsByClassName('note-msg', tempElement);
            if (el.length > 0)
            {
                content = el[0];
            }
            else
            {
                return;
            }
        }

    }

    element.parentNode.replaceChild(content, element);
    
}



function getElementsByClassName(classname, node) {


    var a = [];

    var re = new RegExp('\\b' + classname + '\\b');

    var els = node.getElementsByTagName("*");

    for(var i=0,j=els.length; i<j; i++){

        if(re.test(els[i].className))a.push(els[i]);
    }
    return a;

}


function replaceNavigationBlock(content){
	
	
    var element = $$('div.block-layered-nav')[0];
    
    if (content && content.toElement){
    	
        content = content.toElement();
    	
    }else if (!Object.isElement(content)) {
    	
        content = Object.toHTML(content);
      
        var tempElement = document.createElement('div');
        content.evalScripts.bind(content).defer();
        tempElement.innerHTML = content;
        content = tempElement.firstChild;
      
    }
    
    element.parentNode.replaceChild(content, element);    
}


function replaceLeftRightNavigationBlocks(element, content)
{
    var element = $(element);
	
    if (content && element)
    {
        if (content && content.toElement){
		    	
            content = content.toElement();
		    	
        }else if (!Object.isElement(content)) {
		    	
            content = Object.toHTML(content);
		      
            var tempElement = document.createElement('div');
            content.evalScripts.bind(content).defer();
            tempElement.innerHTML = content;
            content = tempElement.firstChild;
		      
        }
        element.parentNode.replaceChild(content, element);
    }
}



function initSlider(code, min, max, curr_min, curr_max, url, is_ajax){
	

    var handles = [code+'-handle-from', code+'-handle-to'];
    
    window.valuesPriceSlider = new Array();
    var k = 100;
    var i;

    if (min == $('price-from').value)
        $('price-from').value = 0;
    if (min == $('price-to').value)
        $('price-to').value = 0;

    if(min % 100 != 0 && min < 1000){
        window.valuesPriceSlider.push(min);
        min = min + 100 - min % 100;
    }
    if(min % 1000 != 0 && min < 100000 && min > 1000){
        window.valuesPriceSlider.push(min);
        min = min + 1000 - min % 1000;
        k = 1000;
    }
    if(min % 100000 != 0 && min >= 100000){
        window.valuesPriceSlider.push(min);
        min = min + 100000 - min % 100000;
        k = 5000;
    }
    
    var t = 0;
    for (i = min; i <= max; i+=k){
        t++;
        if (i == $('price-from').value){
            $('price-from').value = t;
        }
        if (i == $('price-to').value){
            $('price-to').value = t;
        }
        window.valuesPriceSlider.push(i);
        if (i >= 1000)
            k = 1000;
        if (i >= 100000)
            k = 5000;
    }
    if (i != max){

        window.valuesPriceSlider.push(max);
        if (max == $('price-from').value){
            $('price-from').value = t;
        }
        if (max == $('price-to').value){
            $('price-to').value = window.valuesPriceSlider.length -1;
        }
    }

    window.s1 = new Control.Slider(handles,code+'-track', {
        axis:'horizontal',
        alignY:0,
        range: $R(0, window.valuesPriceSlider.size() - 1),
        values: $R(0, window.valuesPriceSlider.size() - 1),
        sliderValue: [$('price-from').value, $('price-to').value],
        restricted: true,
        spans: [code+"-square_slider_span"]
        });
    window.s1.options.onChange = function(value){
        if (isNaN(value[0]) || isNaN(value[1]))
        {
            return false;
        }

        $(code+'-filter-form').elements[code+'-from'].value = parseInt(value[0]);
        $(code+'-filter-form').elements[code+'-to'].value = parseInt(value[1]);

        if(min == value[0] && max == value[1]){

            //setNavigationUrl(url);
            submitNavigationForm($(code+'-filter-form'), url, is_ajax);

        }else{

            submitNavigationForm($(code+'-filter-form'), url, is_ajax);

        }

        var htmlvalue = parseInt(value[0]) + ' - ' + parseInt(value[1]);

        if(value[0] >= 0 && value[1] >= 0){


            $(code+'-value-from').innerHTML = parseInt(1*value[0]);
            $(code+'-value-to').innerHTML = parseInt(1*value[1]);



        }

        $(code+'-value').innerHTML = htmlvalue;

    };
    $$('.handle').each(function(e){
        e.observe('mousedown', function(ev){
            if(window.s1.disabled == true){
                $('price_used').checked = true;
                window.s1.disabled = false;
                window.s1.startDrag(ev);
                $$('#narrow-by-list .handle-left .handle-left-bg')[0].addClassName('active');
                $$('#narrow-by-list .handle-right .handle-right-bg')[0].addClassName('active');
                $('price_used_from').innerHTML = ' до '+ window.valuesPriceSlider[$('price-to').value] +' руб.';
                $('price_used_to').innerHTML = ' от '+ window.valuesPriceSlider[$('price-from').value];
                $$('#narrow-by-list .gan-slider-span')[0].style.background = '#F48B6B';
            }
        })
    });
    $('price-from').name = 'disable';
    $('price-to').name = 'disable';
    $('price_used').observe('click', function(ev){
        if ($('price_used').checked == false){
            window.s1.disabled = true;
            $('price-from').name = 'disable';
            $('price-to').name = 'disable';
            $('price_used_to').innerHTML = 'не выбрано';
            $('price_used_from').innerHTML = '';
            $$('#narrow-by-list .handle-left .handle-left-bg')[0].removeClassName('active');
            $$('#narrow-by-list .handle-right .handle-right-bg')[0].removeClassName('active');
            $$('#narrow-by-list .gan-slider-span')[0].style.background = 'none';
        }else{
            window.s1.disabled = false;
            $('price-from').name = 'price_from_index';
            $('price-to').name = 'price_to_index';
            $('price_used_from').innerHTML = ' до '+ window.valuesPriceSlider[$('price-to').value] +' руб.';
            $('price_used_to').innerHTML = ' от '+ window.valuesPriceSlider[$('price-from').value];
            $$('#narrow-by-list .handle-left .handle-left-bg')[0].addClassName('active');
            $$('#narrow-by-list .handle-right .handle-right-bg')[0].addClassName('active');
            $$('#narrow-by-list .gan-slider-span')[0].style.background = '#F48B6B';
        }
    });
    
    $('price_used').observe('click', function(ev){
            if (($('price_used').checked == true)&& (!(($('price-from').value == '0') && ($('price-to').value == window.valuesPriceSlider.size() - 1)))){
                if (window.time) {
                    clearTimeout(window.time);
                }
                window.time = setTimeout(function(){
                    sendAjax(countUrl, $('price-filter-form').serialize());
                    },500);
                }
            if (($('price_used').checked == false)&& (!(($('price-from').value == '0') && ($('price-to').value == window.valuesPriceSlider.size() - 1)))){
                 if (window.time) {
                    clearTimeout(window.time);
                }
                window.time = setTimeout(function(){
                    sendAjax(countUrl, $('price-filter-form').serialize());
                    },500);
                $('price_used_to').innerHTML = 'не выбрано';
                $('price_used_from').innerHTML = '';
            }
        });
    
    window.s1.options.onSlide = function(value){

        if ($('price_used').checked == true){
            if (window.time) {
                clearTimeout(window.time);
            }
            window.time = setTimeout(function(){
                sendAjax(countUrl, $('price-filter-form').serialize());
            },500);
        }

        if (isNaN(value[0]) || isNaN(value[1]))
        {
            return false;
        }

        var htmlvalue = parseInt(value[0]) + ' - ' + parseInt(value[1]);


        if(value[0] >= 0 && value[1] >= 0){
            $(code+'-value-from').innerHTML = parseInt(1*value[0]);
            $(code+'-value-to').innerHTML = parseInt(1*value[1]);
        }
        if ($('price_used').checked == true){
            $('price_used_to').innerHTML = ' от ' + window.valuesPriceSlider[parseInt(1*value[0])];
            $('price_used_from').innerHTML = ' до ' + window.valuesPriceSlider[parseInt(1*value[1])]+' руб.';
        }else{
            $('price_used_to').innerHTML = 'не выбрано';
            $('price_used_from').innerHTML = '';
        }


        $(code+'-value').innerHTML = htmlvalue;
    };
	
    window.s1.draw = function(event)
    {
        var pointer = [Event.pointerX(event), Event.pointerY(event)];
        var offsets = Position.cumulativeOffset(this.track);
        pointer[0] -= this.offsetX + offsets[0];
        pointer[1] -= this.offsetY + offsets[1];
        this.event = event;
	        
        var value = this.translateToValue( this.isVertical() ? pointer[1] : pointer[0] );
	    
        if (isNaN(value)) return false;
	    
        this.setValue(value);
	    
        if (this.initialized && this.options.onSlide)
            this.options.onSlide(this.values.length>1 ? this.values : this.value, this);
    };

}
