var price_min;
var price_max;
var price_coef = 1;

function RoundPrice(val, direct){
	val = Math.round(GetPriceProgress(val, direct));
	if (val < 100) return val;
	if (val < 1000) return Math.round(val/10)*10;
	if (val < 10000) return Math.round(val/100)*100;
	return Math.round(val/1000)*1000;
}

function GetPriceProgress(val, direct)
{
	if (val == 0)
		if (direct == 1){
			return price_min;
		} else {
			val = 1;
		}
	if (val >= 100){
		if (direct == 2){
			return price_max;
		} else {
			val = 99;
		}
	}
	if (val > price_coef){
		res = (price_coef / (100 - val  + price_coef) )    * (parseInt(price_max) - parseInt(price_min));
	} else {
		res = (val / 100) * (parseInt(price_max) - parseInt(price_min));
	}
	res += parseInt(price_min);
	return res;
}

function procentValue(val, type){
	var interval = parseInt(price_max) - parseInt(price_min);
	//alert(interval);
	var x = 100 + price_coef - ((price_coef * interval) / val);
	//if (type == 1) x +=  price_coef;
	return x;
}

$(document).ready(function(){
    
    $(".spec_offer_text").css("margin-top", (-1)*$(".spec_offer_text").height()+"px");
    $(".rightspacer").css("height", $(".spec_offer_text").height()+"px");

/*Pricebar*/
    price_min = $('#price_min_default').val();
    price_max = $('#price_max_default').val();
    var current_min = $('#price_min').val();
    var current_max = $('#price_max').val();
    $(".pricebar_slider").slider({
                    range: true,
                    values: [procentValue(current_min, 1), 
                    		 procentValue(current_max, 2)], 
                    change: function(event, ui) { 
						CountSearch();
                    },
                    slide: function(event, ui) {
						var direct = ($('a.price_slider_1', this)[0].className.indexOf('ui-state-active') > -1)?1:2;
	                    $(this).find(".ui-state-active").html("<span>"+RoundPrice(ui.value, direct)+"</span>");
	                    $("#price_min").val($(".price_slider_1 span").html());
	                    $("#price_max").val($(".price_slider_2 span").html());
	                }
               });
    
    $(".pricebar_slider .ui-slider-handle").addClass("price_slider_1");
    $(".pricebar_slider .ui-slider-handle:last-child").removeClass("price_slider_1").addClass("price_slider_2");

    $(".pricebar_slider .price_slider_1").html("<span>"+ current_min+"</span>");
    $(".pricebar_slider .price_slider_2").html("<span>"+ current_max+"</span>");
    
    $("#price_min").keyup(function (e) {
        $(".pricebar_slider").slider( "values", 0, [checkPriceValue('min')] );
        $(".pricebar_slider .price_slider_1").html("<span>"+ parseInt($(".pricebar_slider").slider('option', 'values')[0]*price_max/100)+"</span>");
        //$("#price_min").val($(".pricebar_slider").slider('option', 'values')[0]*(price_max/100));
    });
    
    $("#price_max").keyup(function (e) {
        $(".pricebar_slider").slider( "values", 1, [checkPriceValue('max')] );
        $(".pricebar_slider .price_slider_2").html("<span>"+ parseInt($(".pricebar_slider").slider('option', 'values')[1]*price_max/100)+"</span>");
        //$("#price_max").val($(".pricebar_slider").slider('option', 'values')[1]);
    });    
    
    
/*Weightbar*/
    var wtvalue = $('#wt_default').val();
    var current_wtvalue = $('#wt').val();
    $(".wtbar_slider").slider({
					range: "min", 
					value: parseInt(current_wtvalue/(wtvalue/100)), 
					change: function(event, ui){
						CountSearch();
					},
                    slide: function(event, ui) {
                            $(this).find(".ui-state-active").html("<span>"+parseInt(ui.value*(wtvalue/100))+"</span>");
                            $("#wt").val(parseInt(ui.value*(wtvalue/100)));
                            }
                    });
    $(".wtbar_slider .ui-slider-handle").html("<span>"+ current_wtvalue+"</span>");
    $(".wtbar_slider .ui-slider-handle").addClass("wt_slider_1");
    
    $("#wt").keyup(function (e) {
            $(".wtbar_slider").slider("option", "value", parseInt($("#wt").val()/(wtvalue/100)));
            $(".wtbar_slider .ui-slider-handle").html("<span>"+ $("#wt").val()+"</span>");
            //$("#wt").val($(".wtbar_slider").slider("value"));
    });    

/* Spring switch     
    $("select#matras_type").change(function () {
        if ($(this).val() == "Пружинный" ) {
            $("#spring_type").show(); 
            $("#spring_type select").removeAttr("disabled"); 
        } else {
            $("#spring_type").hide(); 
            $("#spring_type select").attr("disabled", true); 
        }
    });
    if ($(this).val() == "Пружинный" ) {
        $("#spring_type").show(); 
        $("#spring_type select").removeAttr("disabled"); 
    } else {
        $("#spring_type").hide(); 
        $("#spring_type select").attr("disabled", true); 
    }*/
    
/* Size switch */
    $("#size_switch").change(function () {
            if ($("#size_switch").attr('checked')){
                $("#non_standart_size").show();
                $("#non_standart_size input").removeAttr("disabled");
                
                $("#standart_size").hide();
                $("#standart_size select").attr('disabled',true);
            } else {
                $("#standart_size").show();
                $("#standart_size select").removeAttr("disabled");
                $("#non_standart_size input").attr('disabled',true);
                $("#non_standart_size").hide();
            }
        });
    if ($("#size_switch").attr('checked')){
        $("#non_standart_size").show();
        $("#non_standart_size input").removeAttr("disabled");
        
        $("#standart_size").hide();
        $("#standart_size select").attr('disabled',true);
    } else {
        $("#standart_size").show();
        $("#standart_size select").removeAttr("disabled");
        $("#non_standart_size input").attr('disabled',true);
        $("#non_standart_size").hide();
    }
    
    
    
    
/* Side switch */    
    $("#side_switch").click(function () {
            if ($("#side_switch").attr('checked')){
                //$("#double-sided").show();
                $("#double-sided select").removeAttr("disabled");
                
                //$("#single_side").hide();
                $("#single_side select").attr('disabled',true);
            } else {
                //$("#double-sided").hide();
                //$("#single_side").show();
                $("#double-sided select").attr('disabled',true);
                $("#single_side select").removeAttr("disabled");
            }
        });
    if ($("#side_switch").attr('checked')){
                //$("#double-sided").show();
                $("#double-sided select").removeAttr("disabled");
                
                //$("#single_side").hide();
                $("#single_side select").attr('disabled',true);
            } else {
                //$("#double-sided").hide();
                //$("#single_side").show();
                $("#double-sided select").attr('disabled',true);
                $("#single_side select").removeAttr("disabled");
            }
    $(".hits td").each(function(i){
        if ((++i*210) > $("#c_inner").width()) $(this).hide();
    })
    
    $(window).resize(function(){    
    
        $(".hits td").each(function(i){
            if ((++i*210) > $("#c_inner").width()) $(this).hide();
            else $(this).removeAttr("style");
        })
    })
});



function testKey(e)
{
  // Make sure to use event.charCode if available
  var key = (typeof e.charCode == 'undefined' ? e.keyCode : e.charCode);

  // Ignore special keys
  if (e.ctrlKey || e.altKey || key < 32)
    return true;

  key = String.fromCharCode(key);
  return /[\d\.]/.test(key);
  
}

function wtapp(){
	$(".wtbar_slider").slider("option", "value", $("#wt").val());
}

function getStar(obj){
	obj = $(obj); 
    $('#star_value').val(obj.attr('title'));
    var x = parseInt(obj.attr('rel'));
    for (var y = 0; y < orto_counter; y++){
        if (y <= x){
            $('#star'+y)[0].src = image_src_path+'images/rating_1.png';
        } else {1
            $('#star'+y)[0].src = image_src_path+'images/rating_0.png';
        }
    }
}

function checkPriceValue(type){
    if (type == 'min'){
        var slide_value = parseInt($("#price_min").val()) > parseInt($("#price_max").val()) ?  $("#price_max").val() : $("#price_min").val();
    } else {
        var slide_value = parseInt($("#price_max").val()) < parseInt($("#price_min").val()) ?  $("#price_min").val() : $("#price_max").val();
    }
    slide_value = parseInt(slide_value) > parseInt(price_max) ? parseInt(price_max) : parseInt(slide_value);
    slide_value = parseInt(slide_value) < parseInt(price_min) ? parseInt(price_min) : parseInt(slide_value);
    slide_value = ((slide_value/ price_max)*100);
    if (slide_value < 0 || isNaN(slide_value)){
        slide_value = 0;
    }
    return slide_value;
}

function addToCompare(id, obj){
	JsHttpRequest.query(
        '/ajax/catalog/addToCompare/',
        { cat_id: id },
        function(result, error) {
            if (result.state){
				var span = document.createElement('span');
				span.innerHTML = 'Уже ';
                obj.innerHTML = 'в сравнении';
				obj.href = '/catalog/compare/';
				obj.onclick = function(){};
				obj.target = '_blank';
				$(obj).before(span);
				$('#compare_number').text(result.number);
				$('#compare_word').text(result.word);
            }
        },
        function(result, debugMessages) {},
        false
    )
}

function CountSearch()
{
	$('#search_count').html('<div style="padding-top:20px;" ><img src="'+image_src_path+'images/loader.gif" /></div>');
	$('#search_count_word').html('');
	JsHttpRequest.query(
		'/ajax/catalog/CountSearch/',
		{ cond: $('#search_form')[0] },
		function(result, errors) {
			$('#search_count').text(result.count);
			$('#search_count_word').text(result.word);
		},false
    );
}

/**
 * Добавление в корзину
 */
function orderItem(id, recomand){
    JsHttpRequest.query(
        '/ajax/orders/buy/',
        {
            'id': 		id,
            'recomand':	recomand
        },
        function(result, errors) {
            if (result.res == 1){
                $("#basket_summ").html(result.summ);
                $("#basket_number").html(result.number);
                $("#basket_word").html(result.word);
                $("#basket_word2").removeClass('hide');
                $("#basket_valute").removeClass('hide');
                $("#basket_go").removeClass('hide');
            }
        },
        true
    );
}

function  OpenImage(obj){
	var image = obj.src;
	image = image.replace(/.*_/i, '').replace('.', '_');
	window.open('/image/show/'+image,  '_blank', 'width=200,height=200,resizable=1');
}

/**
* Функция получения значения select-box'a и подставновки его в url
*/
function addValueToUrl(var_name,obj){
	var x;
	var url_params;
	var temp_url = new String(window.location);
	var url_array = temp_url.split('?');
	if (url_array[1] && temp_url.search(var_name) != -1){
		url_params = url_array[1].split('&');
		for(x in url_params){
			if (typeof(url_params[x]) === 'function'){
				continue;
			} else {
				if (url_params[x].search(var_name) != -1){
					url_params[x] = var_name + '=' + obj.value;
				}
			}
		}
		var new_url = url_array[0] + '?' + url_params.join('&');
	} else {
		var new_url = temp_url + (temp_url.search(/\?/)==-1?'?':'&') + var_name + '=' + obj.value;
	}
	window.location = new_url;
}
