/*startup*/
var arH = [];

var CurBuyBtn = false;
function MoveOnResizeHint($btn, $hint)
{
	b = $btn.offset();
	nt = parseInt(b.top)+$btn.height()-$hint.height()/2+10;
	nl = parseInt(b.left)+$btn.width()-$hint.width()/2;
	$hint.css({'top':nt+'px','left':nl+'px','display':'block'});
}

$(document).ready(function(){

	var width=document.body.clientWidth;
	if (width < 990) document.body.style.width = "990px";
	
	/*table*/
	$('table.cont_table').each(function(){
		$("table.cont_table tr:even").addClass("graytr");
	});
	$("table.table-zebra tr:nth-child(odd)").addClass("second");
	
	
	/* left menu */
	/*$("#red").treeview({
		animated: "fast",
		collapsed: true,
		unique: true,
	   // persist: "cookie",
		toggle: function() {
			window.console && console.log("%o was toggled", this);
		}
	});*/
	for(i=0; i<$('.left-menu .content').length; i++){
		arH[i] = $('.left-menu .content:eq('+i+')').height();
	}
	$('.left-menu .hidnleft').hide().removeClass('hidnleft').css("height", "0px");
	$('.left-menu .pli a').click(function(){
		//if ($(this).is(".active")) return false;
		var idT = $(this).attr("id").split("-");
		var id = parseInt(idT[1], 10);
		if(id>0){
			id--
			only_hide = false; if($('.left-menu .content:eq('+id+')').is(':visible')) only_hide = true;
			$('.left-menu .content:visible').animate({height: "0px" }, 300, false, function (){$(this).hide()});
			if(!only_hide) $('.left-menu .content:eq('+id+')').show().animate({height: arH[id]+"px" }, 300)
			$('.left-menu .pli a').removeClass('active')
			$(this).addClass('active')
			//return false
		}
	})
	
	
	
	/*top auth*/
	/*
	var auth_link = $(".auth_link");
	var auth_block = $("#authform");
	var timeout = null;
	var auth_block_hide_ex = function(){auth_block.hide();}
	var auth_block_hide = function(){
		if (timeout) clearTimeout(timeout);
		timeout = setTimeout(auth_block_hide_ex, 1000);
	}
	auth_link.mouseover(function (){clearTimeout(timeout); auth_block.show(); cantcall_block.hide();});
	auth_block.mouseover(function (){if (timeout) clearTimeout(timeout);});
	auth_link.mouseout(auth_block_hide);
	auth_block.mouseout(auth_block_hide);
	*/
	
	$('#EnterLogin').mouseover(function(){
		$(this).addClass('selected');
	}).mouseout(function(){
		$(this).removeClass('selected');
	});
	
	
	$('#cantcall-link').mouseover(function(){
		$(this).addClass('selected');
	}).mouseout(function(){
		$(this).removeClass('selected');
	});
	
	
	
	/* Buttons */
	$('input:submit', this).each(ButtonAdd);
	$('input:reset', this).each(ButtonAdd);
	$('input:button', this).each(ButtonAdd);
	
	//$('input.red').transformBtn("red");
	//$('.btn').transformBtn("niceBtn");
	//$('.button').transformBtn("niceButton");
	
	
	
	/*
	$('span').hover(function(){$(this).addClass('hover')}, function(){$(this).removeClass('hover')})
	*/
	
	
	//ÊÀÊ ÄÎ ÍÀÑ ÄÎÁÐÀÒÜÑß /contacts/
	$("#howtofind").css("cursor", "pointer");
	$("#howtofind").click(function(){
		$("#howtofind-div").toggle();
	});
	
	//ÊÀÊ ÏÐÎÅÕÀÒÜ /contacts/
	$("#howtogo").css("cursor", "pointer");
	$("#howtogo").click(function(){
		$("#howtogo_div").toggle();
	});	

	
	/*ïëàøêè ïîëîæåíèÿ â êîðçèíó*/
	$('.BuyBtn').click(function(){
		re = /(.+?)_(\d+)/;
		aId = $(this).attr('id')
		elIds= aId.replace(re, "$2");
		elId = parseInt(elIds);
		if(elId<0)
			return true;

		quant = parseInt($('#BU_VALUE_'+elId).val());
		if(isNaN(quant) || quant <= 0 ) quant = 1;
		$('#shortOrQuantity').val(quant);
		$('#shortOrBU').html($('#BU_NAME_'+elId).val());
		$('#shortOrId').val(elId);
		
		MoveOnResizeHint($(this),$('#BasketHint'));
		CurBuyBtn = $(this);
		
		return false;
	});
	$(window).resize(function(){
		if(CurBuyBtn)
			MoveOnResizeHint(CurBuyBtn,$('#BasketHint'));
	});
	
	$('#short_order_form').submit(function(){$('#shortOrAdd').click(); return false;});
	$('#shortOrReset').click(function(){
		$('#BasketHint').css({'top':'-1000px','left':'0px','display':'none'});
		CurBuyBtn = false;
		return false;
	});
	$('#shortOrAdd').click(function(){
		OrForm = $("#short_order_form");
        $.post(  
			OrForm.attr('action'),  
			OrForm.serialize(),
			function (data){window.location ='/catalog/basket/';}
		);
		CurBuyBtn = false;
		return false;
	}); 
	$('#shortOrApply').click(function(){
		OrForm = $("#short_order_form");
		$.post(  
			OrForm.attr('action'),  
			OrForm.serialize(),
			function (data){ $('#small_basket').html(data);}
		);
        setTimeout(function(){
            $.post(
            '/includes/tobasket_right.php',
            '',
            function(data){
                $('#basket_right').html(data);
                $('#basketOrderButton_right').each(ButtonAdd);
            }
        );
        }, 500);
		$('#BasketHint').css({'top':'-1000px','left':'0px','display':'none'});
		CurBuyBtn = false;
		return false;
	});
	
	
		//ÍÅ ÌÎÆÅÒÅ ÄÎÇÂÎÍÈÒÜÑß

        var cantcall_link = $(".cantcall-link");
        var cantcall_block = $("#cantcallform");

        var cantcall_block_hide_ex = function(){cantcall_block.hide();}
        var cantcall_block_hide = function(){
            if (timeout) clearTimeout(timeout);
            timeout = setTimeout(cantcall_block_hide_ex, 1000);
        }
        cantcall_link.mouseover(function (){clearTimeout(timeout); cantcall_block.show(); auth_block.hide();});
        cantcall_block.mouseover(function (){if (timeout) clearTimeout(timeout);});
        cantcall_link.mouseout(cantcall_block_hide);
        cantcall_block.mouseout(cantcall_block_hide);	
		
        
		//ÂÀØÀ ÇÀßÂÊÀ ÏÐÈÍßÒÀ
		$("#cantcallform_ok").css("cursor", "pointer");
        $("#cantcallform_ok").click(function(){
			$(this).hide();
		});
		$('body').click(function(){
			$('#cantcallform_ok').hide();
		});
	
			
         $("#cantcall-fio").val('Èìÿ');
         $("#cantcall-phone").val('Òåëåôîí'); 
        
        $("#cantcall-fio").focus(function(){
          $(this).val('');
        });

        $("#cantcall-fio").blur(function(){
            if ($(this).val()=='')
                $(this).val('Èìÿ');
        });
        
        $("#cantcall-phone").focus(function(){
          $(this).val('');
        });

        $("#cantcall-phone").blur(function(){
            if ($(this).val()=='')
                $(this).val('Òåëåôîí');
        });
        
		
		
		
		
		
		
        $('.bubbleInfo').each(function () {
        var auth_link = $(".trigger");
        var auth_block = $(".popup");
        var timeout = null;
        var auth_block_hide_ex = function(){auth_block.hide();}
        var auth_block_hide = function(){
            if (timeout) clearTimeout(timeout);
            timeout = setTimeout(auth_block_hide_ex, 1000);
        }
		
        auth_link.mouseover(function (){if (timeout) clearTimeout(timeout); auth_block.show();});
        auth_block.mouseover(function (){if (timeout) clearTimeout(timeout);});
        auth_link.mouseout(auth_block_hide);
        auth_block.mouseout(auth_block_hide); 
     });    
		
		
		
	SetPlaceHolder($("#search_input"), 'íàïðèìåð, èçîëÿöèÿ', 'edited');
	$('#short_search_form').submit(function(){
            if($("#search_input").hasClass('edited'))
                return true;
			$("#search_input").attr("value","");
            return true;
         });
		 
		 
	$('#cantcall_block .InpArea input[type="text"]').each(function(){
		SetPlaceHolder($(this), $(this).next('i').text(), 'edited');
	});
	
	$('#cantcall_block form').submit(function(){
		return SetUpFormCantCall();
	});
	
	if ($.browser.msie /*&& $.browser.version <= 7*/) {
		$(".cont_table td").wrapInner('<div style="margin:0 5px;"></div>');
		$(".cont_table td").css("padding-left","0");
		$(".cont_table td").css("padding-right","0");

	}
	
});

// Êíîïêè ïëþñ, ìèíóñ, óäàëèòü â êîðçèíå ñ ïðàâà
// Àíäðåé Îõàïêèí
function basket_right_plus(link){
    var q = $('input[name^=QUANTITY_]',$(link).parent());
    q.val(parseInt(q.val())+1);
    RefreshRightBasket();
}

function basket_right_minus(link){
    var q = $('input[name^=QUANTITY_]',$(link).parent());
    q.val(parseInt(q.val())-1);
    RefreshRightBasket();
    if (q.val() < 1)
        setTimeout(RefreshTopBasket,"500");
}
function basket_right_delete(link){
    var q = $('input[name^=DELETE_]',$(link).parent());
    q.val('Y');
    RefreshRightBasket();
    setTimeout(RefreshTopBasket,"500");
}

function RefreshRightBasket()
{
    $('#basket_right').css('opacity','0.5');
    $('a','#basket_right').removeAttr('onclick');
    $('a','#basket_right').click(function(){return false;});
    $.post(
            '/includes/tobasket_right.php',
            $('form','#basket_right').serialize(),
            function(data){
                setTimeout(function(){
                $('#basket_right').html(data);
                $('#basketOrderButton_right').each(ButtonAdd);
                $('#basket_right').css('background','').css('opacity','');    
                },"500");
            }
    );
}

function RefreshTopBasket()
{
    OrForm = $("#short_order_form");
    $.post(  
        OrForm.attr('action'),  
        '',
        function (data){ $('#small_basket').html(data);}
    );
}
////////////////////////////////////////////////


ButtonAdd = function(){
	var value = $(this).attr('value');
	var onclick='';

		 for (var i = 0; i < this.attributes.length; i++) {
		   if (this.attributes[i].nodeName=='onclick'){
			 onclick = ' onclick="'+this.attributes[i].nodeValue+'"';
			 //console.log(onclick )         
		   }
		 }
	//console.log('<button id="'+ this.id +'" name="'+ this.name +'" onclick="'+ onclick +'" type="'+ this.type +'" class="'+ this.className +'" value="'+ value +'"><span class="png"><span class="png">'+ value +'</span></span>')
	$(this).replaceWith('<button id="'+ this.id +'" name="'+ this.name +'"'+ onclick +' type="'+ this.type +'" class="'+ this.className +'" value="'+ value +'"><span class="png"><span class="png"><nobr>'+ value +'</nobr></span></span></button>');
};

/*buttons*/
/*
$.fn.transformBtn = function(varclass){
	return $(this).each(function(){
		var btn = $('<button type="'+ this.type +'" value="'+ this.value +'" class="'+varclass+' '+$(this).attr('class')+'"><span><span>'+this.value+'</span></span></button>');
		btn.focus(function(){ $(this).addClass('niceBtnFocus')}).blur(function(){ $(this).removeClass('niceBtnFocus')});
		
		if (typeof this.name != 'undefined') btn.attr('name', this.name);
		if (typeof this.id != 'undefined') btn.attr('id', this.id);

		$(this).replaceWith(btn);
	});
};
*/

function SetUpFormCantCall()
{
	SubForm = $('#cantcall_block form');
	$('#cantcall_block input[type="text"]').each(function(){
			if($(this).val() != '' && $(this).val() == $(this).next('i').text())
				$(this).val('');
		});
	$.post("/includes/cant_call.php",  
			SubForm.serialize(),  
			function(data){
				$('#cantcall_block').html(data);
				$('#cantcall_block form').submit(function(){return SetUpFormCantCall();});
				$('#cantcall_block .InpArea input[type="text"]').each(function(){
					SetPlaceHolder($(this), $(this).next('i').text(), 'edited');
				});
			}
		);
		return false;
}

function SetPlaceHolder(el, text, addclass)
{
		if(el.val() == '')
			el.val(text);
        el.focus(function(){
             if($(this).val() == text)
             {
                $(this).val('');
                $(this).addClass(addclass); 
             }
             else
                 $(this).removeClass(addclass); 
         }).blur(function(){
             if($(this).val() == '' || $(this).val() == text)
             {
                $(this).val(text);
                $(this).removeClass(addclass);
             }
             else
                $(this).addClass(addclass);
                
         }).keydown(function(){
            $(this).addClass(addclass);
         });
}



function GetPriceFormat(price)
{
	price = number_format(price, 2, ',', '&nbsp;');
	
	//alert('p='+price.substr(price.length-3));
	if(',00' == price.substr(price.length-3))
	{
		price = price.substr(0, price.length-3);
		//alert('d');
	}
	//alert('e='+price);
	return price;
}

function number_format( number, decimals, dec_point, thousands_sep ) 
{  // Format a number with grouped thousands
    // 
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://crestidg.com)
 
    var i, j, kw, kd, km;
 
    // input sanitation & defaults
    if( isNaN(decimals = Math.abs(decimals)) ){
        decimals = 2;
    }
    if( dec_point == undefined ){
        dec_point = ",";
    }
    if( thousands_sep == undefined ){
        thousands_sep = ".";
    }
 
    i = parseInt(number = (+number || 0).toFixed(decimals)) + "";
	 
    if( (j = i.length) > 3 ){
        j = j % 3;
    } else{
        j = 0;
    }
 
    km = (j ? i.substr(0, j) + thousands_sep : "");
    kw = i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands_sep);
    //kd = (decimals ? dec_point + Math.abs(number - i).toFixed(decimals).slice(2) : "");
    kd = (decimals ? dec_point + Math.abs(number - i).toFixed(decimals).replace(/-/, 0).slice(2) : "");
 
 
    return km + kw + kd;
}

function reset ( array ) 
{  // Set the internal pointer of an array to its first element
    // 
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Legaev Andrey
 
    var first_elm, key;

    if (array.constructor === Array)
	{
        first_elm = array[0];
    } 
	else 
	{
        for (key in array)
		{
            first_elm = array[key];
            break;
        }
    }
 
    return first_elm;
}

function is_array( mixed_var ) 
{    // Finds whether a variable is an array
    // 
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Legaev Andrey
    // +   bugfixed by: Cord
 
    return ( mixed_var instanceof Array );
}

function isset () 
{
	// +   original by: Kevin van Zonneveld 
    // +   improved by: FremyCompany
    // +   improved by: Onno Marsman
    // *     example 1: isset( undefined, true);
    // *     returns 1: false
    // *     example 2: isset( 'Kevin van Zonneveld' );
    // *     returns 2: true
     
    var a=arguments, l=a.length, i=0;
    
    if (l===0) {
       throw new Error('Empty isset'); 
    }
     
    while (i!==l) 
	{
        if (typeof(a[i])=='undefined' || a[i]===null) 
		{ 
            return false; 
        } 
		else 
		{ 
			i++; 
        }
    }
    return true;
}

function is_numeric( mixed_var ) 
{  // Finds whether a variable is a number or a numeric string
    // 
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: David

    return !isNaN( mixed_var );
}

function str_replace ( search, replace, subject ) 
{ // Replace all occurrences of the search string with the replacement string
    // 
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
 
    if(!(replace instanceof Array)){
        replace=new Array(replace);
        if(search instanceof Array){//If search is an array and replace is a string, then this replacement string is used for every value of search
            while(search.length>replace.length){
                replace[replace.length]=replace[0];
            }
        }
    }
 
    if(!(search instanceof Array))search=new Array(search);
    while(search.length>replace.length){//If replace has fewer values than search , then an empty string is used for the rest of replacement values
        replace[replace.length]='';
    }
	 
    if(subject instanceof Array){//If subject is an array, then the search and replace is performed with every entry of subject , and the return value is an array as well.
        for(k in subject){
           subject[k]=str_replace(search,replace,subject[k]);
        }
        return subject;
    }
 
    for(var k=0; k<search.length; k++){
        var i = subject.indexOf(search[k]);
        while(i>-1){
            subject = subject.replace(search[k], replace[k]);
            i = subject.indexOf(search[k],i);
        }
    }
    return subject;
}

function iround(val, i)
{
	i = parseInt(i);
	if(i<=0 || isNaN(i))
		i = 0;
	val = parseFloat(val);
	if(val == 0 || isNaN(val))
		return 0;
	val = val.toFixed(i);
	val = parseFloat(val);
	return val;
}
