var price_min;
var price_max;
var level_min;
var level_max;
var wt_min;
var wt_max;
var price_coef = 1;
var level_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 RoundLevel(val, direct){
	val = Math.round(GetLevelProgress(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 GetLevelProgress(val, direct)
{
    //alert(val);
    //alert(direct);
	if (val == 0)
		if (direct == 1){
			return level_min;
            
		} else {
			val = 1;
		}
	if (val >= 100){
		if (direct == 2){
			return level_max;
            
		} else {
			val = 99;
		}
	}
    
	if (val > level_coef){
		res = (level_coef / (100 - val  + level_coef) )    * (parseInt(level_max) - parseInt(level_min));
	} else {
		res = (val / 100) * (parseInt(level_max) - parseInt(level_min));
	}
	res += parseInt(level_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]);
    });

    /*Level*/
    level_min = parseInt($('#level_min_default').val());
    level_max = parseInt($('#level_max_default').val());
    var current_min = parseInt($('#level_min').val());
    var current_max = parseInt($('#level_max').val());
    $(".levelbar_slider").slider({
            range: true,
            min: level_min,
			max: level_max,
			values: [ current_min, current_max ],
            change: function(event, ui) {
                CountSearch();
            },
			slide: function( event, ui ) {
				//$( "#amount" ).val( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ] );
                $('.level_slider_1 span').html(ui.values[ 0 ]);
                $('.level_slider_2 span').html(ui.values[ 1 ]);
                $("#level_min").val(ui.values[ 0 ]);
	            $("#level_max").val( ui.values[ 1 ]);
			}
    });

    $(".levelbar_slider .ui-slider-handle").addClass("level_slider_1");
    $(".levelbar_slider .ui-slider-handle:last-child").removeClass("level_slider_1").addClass("level_slider_2");

    $(".levelbar_slider .level_slider_1").html("<span>"+ current_min+"</span>");
    $(".levelbar_slider .level_slider_2").html("<span>"+ current_max+"</span>");

    $("#level_min").keyup(function (e) {
        $(".levelbar_slider").slider( "values", 0, [checkLevelValue('min')] );
        //alert(parseInt($(".levelbar_slider").slider('option', 'values')[0]));
        $(".levelbar_slider .level_slider_1").html("<span>"+parseInt($(this).val())+"</span>");
        //$("#price_min").val($(".pricebar_slider").slider('option', 'values')[0]*(price_max/100));
    });

    $("#level_max").keyup(function (e) {
        $(".levelbar_slider").slider( "values", 1, [checkLevelValue('max')] );
        $(".levelbar_slider .level_slider_2").html("<span>"+parseInt($(this).val())+"</span>");
        //$("#price_max").val($(".pricebar_slider").slider('option', 'values')[1]);
    });
    
    
/*Weightbar*/
    wt_min = parseInt($('#wt_min_default').val());
    wt_max = parseInt($('#wt_max_default').val());
    var current_min = parseInt($('#wt_min').val());
    var current_max = parseInt($('#wt_max').val());
    $(".wt_bar_slider").slider({
            range: true,
            min: wt_min,
			max: wt_max,
			values: [ current_min, current_max ],
            change: function(event, ui) {
                CountSearch();
            },
			slide: function( event, ui ) {
				//$( "#amount" ).val( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ] );
                $('.wt_slider_1 span').html(ui.values[ 0 ]);
                $('.wt_slider_2 span').html(ui.values[ 1 ]);
                $("#wt_min").val(ui.values[ 0 ]);
	            $("#wt_max").val( ui.values[ 1 ]);
			}


                    /*range: true,
                    values: [procentValueLevel(current_min, 1),
                    		 procentValueLevel(current_max, 2)],
                    change: function(event, ui) {
						CountSearch();
                    },
                    slide: function(event, ui) {
						var direct = ($('a.level_slider_1', this)[0].className.indexOf('ui-state-active') > -1)?1:2;
                        //alert(direct);
	                    $(this).find(".ui-state-active").html("<span>"+RoundLevel(ui.value, direct)+"</span>");
	                    $("#level_min").val($(".level_slider_1 span").html());
	                    $("#level_max").val($(".level_slider_2 span").html());
	                }*/
               });

    $(".wt_bar_slider .ui-slider-handle").addClass("wt_slider_1");
    $(".wt_bar_slider .ui-slider-handle:last-child").removeClass("wt_slider_1").addClass("wt_slider_2");

    $(".wt_bar_slider .wt_slider_1").html("<span>"+ current_min+"</span>");
    $(".wt_bar_slider .wt_slider_2").html("<span>"+ current_max+"</span>");

    $("#wt_min").keyup(function (e) {
        $(".wt_bar_slider").slider( "values", 0, [checkWtValue('min')] );
        $(".wt_bar_slider .wt_slider_1").html("<span>"+ parseInt($(this).val())+"</span>");
        //$("#price_min").val($(".pricebar_slider").slider('option', 'values')[0]*(price_max/100));
    });

    $("#wt_max").keyup(function (e) {
        $(".wt_bar_slider").slider( "values", 1, [checkWtValue('max')] );
        $(".wt_bar_slider .wt_slider_2").html("<span>"+ parseInt($(this).val())+"</span>");
        //$("#price_max").val($(".pricebar_slider").slider('option', 'values')[1]);
    });


    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 checkLevelValue(type){
    if (type == 'min'){
        var slide_value = parseInt($("#level_min").val()) > parseInt($("#level_max").val()) ?  $("#level_max").val() : $("#level_min").val();
    } else {
        var slide_value = parseInt($("#level_max").val()) < parseInt($("#level_min").val()) ?  $("#level_min").val() : $("#level_max").val();
    }
    //alert(slide_value);
    slide_value = parseInt(slide_value) > parseInt(level_max) ? parseInt(level_max) : parseInt(slide_value);
    slide_value = parseInt(slide_value) < parseInt(level_min) ? parseInt(level_min) : parseInt(slide_value);
   // alert(slide_value);
    //alert(level_max);
    slide_value = ((slide_value/ level_max)*34);
    //alert(slide_value);
    if (slide_value < 0 || isNaN(slide_value)){
        slide_value = 0;
    }
    return slide_value;
}

function checkWtValue(type){
    if (type == 'min'){
        var slide_value = parseInt($("#wt_min").val()) > parseInt($("#wt_max").val()) ?  $("#wt_max").val() : $("#wt_min").val();
    } else {
        var slide_value = parseInt($("#wt_max").val()) < parseInt($("#wt_min").val()) ?  $("#wt_min").val() : $("#wt_max").val();
    }
    slide_value = parseInt(slide_value) > parseInt(wt_max) ? parseInt(wt_max) : parseInt(slide_value);
    slide_value = parseInt(slide_value) < parseInt(wt_min) ? parseInt(wt_min) : parseInt(slide_value);

    slide_value = ((slide_value/ wt_max)*160);
    
    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, num, price, flag_id){
	flag_id = flag_id || 'in_basket_flag';
    JsHttpRequest.query(
        '/ajax/orders/buy/',
        {
            'id'    : id,
            'number': num,
            'price' : price
        },
        function(result, errors) {
            if (result.res == 1){
                $("#basket_summ").html(result.summ);
                $("#basket_number").html(result.number);
                $("#basket_word").html(result.word);
                $('#cart_block').css('visibility','visible');
                $('#red_button').toggle();
                $('#yellow_button').hide();
				$('#'+flag_id).show();
            }
        },
        true
    );
}

function  OpenImage(src_path, img_id){
    //alert(src_path);
    $('#cover').show();
    var state = $('#pop-up-block').css('display');
    if (state == 'none') {
         $('#pop-up-block').show('fast');
    }
    $('#pop_image_big')[0].src = '/upload/images/'+src_path;
    $('.current').removeAttr('class');
    $('#li_'+img_id).attr('class', 'current');


	//var image = obj.src;
	//image = image.replace(/.*_/i, '').replace('.', '_');
	//window.open('/image/show/'+image,  '_blank', 'width=200,height=200,resizable=1');
}

function closeImage() {
    $('#cover').hide();
    $('#pop-up-block').hide('fast');
}

/**
* Функция получения значения 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;
}

/*
 * функция для обнуления поиска
 */
function resetMainFilter() {
    $.post('/catalog/resetFilter/', function(data){
        location.href= location.href;
    })
}

$(document).ready(function() {
    checkCallTimer();
    checkNewCalls();
})

var intervalCall;
function checkCallTimer() {
    //alert(call_timer);
    intervalCall = setInterval(checkNewCalls, call_timer);
}

function checkNewCalls()  {
    $.getJSON('/calls/checkNewCall/', function(data) {
    	if (data == undefined){
    		var data = new Array();
    		data.res = 0;
    	}
        if (data.res == 1) {
            $('#calls_mesanger').show();
            var text = '<a href="/admin/calls/">Внимание! <span style="font-weight: bold; color: rgb(255, 0, 0);">'+data.count+'</span> '+data.text+' обработки. </a>';
            $('#call_message').html(text);
        } else {
             $('#calls_mesanger').hide();
        }
    });
}

function MoveCenterScreen(objID) {
  var innerHeight_ = window.innerHeight ? window.innerHeight : document.documentElement.offsetHeight;
  var obj = $('#'+objID);

  var H = $(window).width();
  var e = 480;
  var left  = (H-e)/1.5;

  var L = $(window).height();
  var t = obj.height();
  var k = (L-t)/4;

  var scroll_px = ($(window).scrollTop()+k)+'px';
  obj.css('left', left+'px');
  obj.css('top', scroll_px);
}

function getDocumentSize(doc) { // getting a real size document with scrolling etc.
  var r = {width: 0, height: 0};

  var width1=0, width2=0, width3=0, width4=0, maxWidth=0;
  var height1=0, height2=0, height3=0, height4=0, maxHeight=0;


  if (doc.width) maxWidth = doc.width;
  if (doc.body) {
	if (doc.body.scrollWidth) width1 = doc.body.scrollWidth;
	if (doc.body.offsetWidth) width2 = doc.body.offsetWidth;
  }
  if (doc.documentElement) {
	width3 = doc.documentElement.scrollWidth;
	width4 = doc.documentElement.clientWidth;
  }

  maxWidth = Math.max(Math.max(Math.max(width1, width2), Math.max(width3, width4)),maxWidth);

  if (doc.height) maxHeight = doc.height;
  if (doc.body) {
	if (doc.body.scrollHeight) height1 = doc.body.scrollHeight;
	if (doc.body.offsetHeight) height2 = doc.body.offsetHeight;
  }
  if (doc.documentElement) {
	height3 = doc.documentElement.scrollHeight;
	height4 = doc.documentElement.clientHeight;
  }
  maxHeight = Math.max(Math.max(Math.max(height1, height2), Math.max(height3, height4)),maxHeight);

  //r.width = maxWidth;
  r.height = maxHeight;

  return maxHeight;
}
