////////////////////////////////////////
window.onload = checkAvailableWidth;
window.onresize = checkAvailableWidth;
//window.onload = checkProduct;

function Elem(sObject){
	return(document.getElementById(sObject));
}

$.extend({
	getUrlParams: function() {
		var params = [], hash;
		var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
		for (var i = 0; i < hashes.length; i++) {
			hash = hashes[i].split('=');
			params.push(hash[0]);
			params[hash[0]] = hash[1];
		}
		return params;
	},
	getUrlParam: function(name) {
		return $.getUrlParams()[name];
	},
	getUrlWithoutParam: function(){
		var hashes = window.location.href.split('?');
		if(hashes){
			var url = hashes[0];
			return url;
		}
	}
});

$(function(){
//	$('.typeface-js').each(function(){
//		$(this).sifr({path:'/_swf/', font: 'calibri', color:'#000'});
//	});
	
//		if(typeof sIFR == "function"){
//			//sIFR.replaceElement(named({sSelector:"body h1", sFlashSrc:"tradegothic.swf", sColor:"#000000", sLinkColor:"#000000", sBgColor:"#FFFFFF", sHoverColor:"#CCCCCC", nPaddingTop:20, nPaddingBottom:20, sFlashVars:"textalign=center&offsetTop=6"}));
//			//sIFR.replaceElement("h5#pullquote", "tradegothic.swf", "#000000", "#000000", "#FFFFFF", "#FFFFFF", 0, 0, 0, 0);
//			//sIFR.replaceElement("h2", "tradegothic.swf", "#000000", null, null, null, 0, 0, 0, 0);
//			//sIFR.replaceElement("h4.subhead", "tradegothic.swf", "#660000", null, null, null, 0, 0, 0, 0);
//			//sIFR.replaceElement("h3.sidebox","tradegothic.swf","#000000", "#000000", "#DCDCDC", "#DCDCDC", 0, 0, 0, 0, null);
//			sIFR.replaceElement(".typeface-js", "/_swf/calibri.swf", "#000000", null, "#CCCCCC", null, 0, 0, 0, 0, null);
//		
//		};
	
	if($.browser.msie){
		if($.browser.version=="6.0" || $.browser.version=="7.0"){
			$('.hyphen').each(function(){
				$(this)[0].innerHTML="&ndash;";
			})
			if($.browser.version=="7.0"){
				$('#itext').css('padding-top','4px').css('height','18px');
			}
		}
		$('#itext').css('padding-top','4px').css('height','18px');
		$('#search_btn').css('margin-top','4px').css('margin-left','5px');
	}
	
	$('#character').click(function(){
		var iProductID=$(this).attr('product_id');
		$('#parent_goods').removeAttr('disabled');
		$('#basket_btn').html("<input type='button' id='btn_to_basket' name='btn_to_basket' onclick='toBasket("+$('.buy_radio').attr('product_id')+","+iProductID+")' />");
		UpdateContent(iProductID);
	});
	$('.buy_radio').click(function(){
		var iProductID=$(this).attr('product_id');
		$('#parent_goods').attr('disabled','disabled');
		$('#basket_btn').html("<input type='button' id='btn_to_basket' name='btn_to_basket' onclick='toBasket("+iProductID+","+iProductID+")' />");
		UpdateContent(iProductID);
	});
	
	var oInner=Elem("inner_text");
	/*наводим на Contact / Call Center*/
	$("#img1").hover(
	  function(){
	   oInner.innerHTML="Многофункциональное решение для работы с основными видами сообщений (звонки, электронная почта, факсимильные сообщения, sms)";
	   $('div#inner_text').attr('align','left');
	  },
	  function(){
	    oInner.innerHTML="<img style='margin-top:20px;' src='/_img/navigation/logo.gif' />";
	    $('div#inner_text').removeAttr('align');
	  }
	);
	/*наводим на IP BPX*/
	$("#img2").hover(
	  function(){
	   oInner.innerHTML="Универсальная современная АТС для управления корпоративной телефонией посредством веб-интерфейса. Обеспечивает гибкость настройки, повышает производительность операторов";
	   $('div#inner_text').attr('align','left');
	  },
	  function(){
	    oInner.innerHTML="<img style='margin-top:20px;' src='/_img/navigation/logo.gif' />";
	    $('div#inner_text').removeAttr('align');
	  }
	);
	/*наводим на Online Monitor*/
	$("#img3").hover(
	  function(){
	   oInner.innerHTML="Удобный административный инструмент, в реальном времени визуализирующий процессы системы: активность и загрузку операторов, регистрации на датчиках и др.";
	   $('div#inner_text').attr('align','left');
	  },
	  function(){
	    oInner.innerHTML="<img style='margin-top:20px;' src='/_img/navigation/logo.gif' />";
	    $('div#inner_text').removeAttr('align');
	  }
	);
	/*наводим на СКУД*/
	$("#img4").hover(
	  function(){
	   oInner.innerHTML="Программно-аппаратный комплекс, решающий задачи контроля и управления доступом к помещениям и учета рабочего времени сотрудников";
	   $('div#inner_text').attr('align','left');
	  },
	  function(){
	    oInner.innerHTML="<img style='margin-top:20px;' src='/_img/navigation/logo.gif' />";
	    $('div#inner_text').removeAttr('align');
	  }
	);
	
//	$(".menu_item",".menu_top").hover(
//	  function(){
//	   $(this).addClass('hover');
//	  },
//	  function(){
//	   $(this).removeClass('hover');
//	  }
//	);

// devices add/substract quantity

$('#substract').click(function(){

	});
	
	$('#show_characters').click(function(){
		var obj = $('#characters_filter')
		var display = obj.css('display');
		if(display=="none"){
			obj.show();
			setCookie("parameters_view",1,"/");
			$(this).html("Скрыть характеристики");
			$('#select_button_td').append($('#select_button'));
		}else{
			obj.hide();
			setCookie("parameters_view",0,"/");
			$('.parameter_item').each(function(){
				$(this)[0].checked=false;
			});
			$(this).html("Показать характеристики");
			$('#select_button_div').append($('#select_button'));
		}
	});
	
	$('.character_group_title').click(function(){
		var obj = $(this).parent().find('.characters');
		var display = obj.css('display');
		if(display=="none"){
			$(this).removeClass('closed').addClass('open');
			$(this).parent().css('border-bottom','1px dashed #C4C4C4');
			obj.show();
		}else{
			$(this).removeClass('open').addClass('closed');
			$(this).parent().css('border-bottom','none medium');
			obj.hide();
		}
	});
	
});

function resizeHeadGrad(){
	var scr = document.documentElement.offsetWidth || document.body.offsetWidth;
	if(scr<1200){
		$('.left','#header').css('background','url("/_img/head/head_grad_left.png") repeat-x scroll left top');
		$('.right','#header').css('background','url("/_img/head/head_grad_right_in.png") repeat-x scroll left top');
	}else{
		$('.left','#header').css('background','url("/_img/head/bg_left_res.png") repeat-x scroll left top');
		$('.right','#header').css('background','url("/_img/head/bg_right_res.png") repeat-x scroll left top');
	};
}

function checkAvailableWidth(){
	var scr = document.documentElement.offsetWidth || document.body.offsetWidth;
	var resizeit=$('#resizeit').val();
	if(scr<1200){
		$('#header_content').css('width','1000px').css('margin','0 auto 0 -500px');
		$('.slogan').css('left','390px');
		$('#main_content').css('width','1000px').css('padding','0 0 155px 5px');
		$('.middle').css('margin','0 10px');
		$('#submit_btn').css('margin-top','10px');
		$('.right_col_inner').css('width','707px').css('margin-left','30px');
		$('.navigation').css('padding','10px');
		$('#footer_content').css('width','900px');
		$('.footer_menu').css('width','450px');
		$('.product_item','.right_col_inner').css('margin-right','25px');
		if(resizeit){
			$('.left','#header').css('background','url("/_img/head/bg_left_res.png") repeat-x scroll left top');
			$('.right','#header').css('background','url("/_img/head/bg_right_res.png") repeat-x scroll left top');
		}
	}else{
		$('#header_content').css('width','1200px').css('margin','0 auto 0 -600px');
		$('.slogan').css('left','500px');
		$('#main_content').css('width','1100px').css('padding','0 50px 155px');
		$('.middle').css('margin','0 30px');
		$('.right_col_inner').css('width','835px').css('margin-left','50px');
		$('.navigation').css('padding','50px');
		$('#footer_content').css('width','1100px');
		$('.footer_menu').css('width','640px');
		$('#submit_btn').css('margin-top','0px');
		$('.product_item','.right_col_inner').css('margin-right','15px');
		if(resizeit){
			$('.left','#header').css('background','url("/_img/head/head_grad_left.png") repeat-x scroll left top');
			$('.right','#header').css('background','url("/_img/head/head_grad_right_in.png") repeat-x scroll left top');
		}
	};
	
		if($.browser.msie){
			if($.browser.version==7.0){
				$('.amount').css('margin-bottom','-1px');
			}
			if($.browser.version==8.0){
				$('.amount_btn').css('margin-bottom','-7px');
			}
		}
		Carousel();
}

function Carousel(){
	$('.jcarousel-clip-horizontal').each(function(){
		var iCarWidth=$(this).width();
		var iItemWidth=$('.jcarousel-list', this).width();
		var iSlideWidth=iCarWidth/3;
		var iSlideWidthFull=0;
		var iSlideCount=0;
		var isMain=$('#main_blocks').val();
		iSlideWidth=Math.ceil(iSlideWidth-10);
		if(iSlideWidth>=200){
			$('.jcarousel-item', this).css('width',iSlideWidth);
		}
		$('.jcarousel-item', this).each(function(){
			iSlideCount=iSlideCount+1;
		});
		if(iItemWidth<=iCarWidth || iSlideCount<3){
			$('.jcarousel-prev', $(this).parent()).hide();
			$('.jcarousel-next', $(this).parent()).hide();
		}else{
			$('.jcarousel-prev', $(this).parent()).show();
			$('.jcarousel-next', $(this).parent()).show();
		}
		if(!isMain){
			iSlideWidthFull=(iSlideWidth+10)*iSlideCount;
			$(this).find('.jcarousel-list').css('width',iSlideWidthFull+'px');
		}
//		$('#mycarousel_analog').css('width',iSlideWidthFull+'px');
//		$('#mycarousel_buy_together').css('width',iSlideWidthFull+'px');
	});
}

function checkProduct(){
	var v=$('.buy_radio').val();
	if(v){
		$('.buy_radio')[0].checked=true;
		$('#parent_goods').attr('disabled','disabled');
		$('#basket_btn').html("<input type='button' id='btn_to_basket' name='btn_to_basket' onclick='toBasket("+$('.buy_radio').attr('product_id')+","+$('.buy_radio').attr('product_id')+")' />");
	}
}

/*Функции скрытия-появление текста в input по умолчанию*/
function focusTxt(id,sTxt){
		var o=Elem(id);
		if(o.value == sTxt){
			o.value='';
		}	
}

function blurTxt(id,sTxt){
		var o=Elem(id);
		if(o.value ==''){
			o.value=sTxt;
		}
}

//добавление товара в корзину
function toBasket(iGoodID,sType,obj){
	var iGoodCount=$('#amount_'+iGoodID).val();
	if(!iGoodCount){
		iGoodCount=1;
	}
	$.post('/ctrl/basket/update.html', {iProductID:iGoodID, iProductCount:iGoodCount}, function(data){
		$('#korz3')[0].innerHTML=data.content;
		if(sType=='price' ){
			$(obj).parent().html('<a href="/basket/" class="to_basket">Уже в корзине</a>');
		}
		if(sType=='list' || sType=='img' || sType=='item'){
			$(obj).removeAttr('onclick');
			$(obj).attr('href','/basket/');
			if(sType=='list' || sType=='item'){
				$(obj).find('#tov2').attr('id','tov2selected');
				if(sType=='item'){
					$('#in_basket_'+iGoodID).attr('value',1);
				}
			}else{
				$(obj).find('.btn_buy_small').attr('class','btn_buy_small_selected');
			}
		}
	}, "json");
	
}

function changeCount(iProductID, sType, sAction){
	var amount_count=$('#amount_count_'+iProductID).val();
	var re=/^[0-9]+$/;
	var sum = 0;
	var total=parseInt(0);
	var inBasket=$('#in_basket_'+iProductID).val();
	switch (sAction){
	  case 'add':
	    var cnt = parseInt($('#amount_'+iProductID).val())+1;
	    $('#substract_'+iProductID).removeAttr('disabled');
	    break;
	  case 'substract':
	  	var cnt = parseInt($('#amount_'+iProductID).val());
	  	if(cnt > 1){
//	  		$('#substract_'+iProductID).removeAttr('disabled');
	    	cnt=cnt-1;
	  	}
	  	if(cnt<=1){
	  		$('#substract_'+iProductID).attr('disabled','disabled');
	  	}
	    break;
	  case 'change':
	    var cnt = parseInt($('#amount_'+iProductID).val());
	    if(cnt > 1){
	   	 $('#substract_'+iProductID).removeAttr('disabled');
	  	}
	    break;
	  default:
	    alert('Ошибка');
	}
	
	if(re.test(cnt)){
		if(sType=='basket'){
			var isBasket=$('#is_basket_'+iProductID).val();
			var aTemp=$('#delivery').val().split(':');
			if(isBasket){
				var price = parseInt($('#price_'+iProductID).val());
				var delivery=parseInt(aTemp[1]);
				sum=cnt*price;
				$('#amount_'+iProductID).val(cnt);
				$('#sum_for_product_'+iProductID).html("<input type='hidden' id='sum_"+iProductID+"' class='sum_for_product' name='sum_"+iProductID+"' value='"+sum+"' />"+sum+"&nbsp;<span class='hyphen'></span><span class='ruble'>р<span class='dot'>уб.</span>&nbsp;</span>");
				$('#sum_'+iProductID).attr('val',sum);
				$('.sum_for_product').each(function(){
					total=total+parseInt($(this).val());
				});
				total=total+delivery;
				$('#total').html(total);
				$('#total').attr('price',total);
//				$('#total').html("<nobr>"+total+"&nbsp;<span class='hyphen' style='color:#6e940d;margin:.3ex 0 0'></span><span class='ruble' style='color:#6e940d;'>р<span class='dot'>уб.</span>&nbsp;</span></nobr>");
			}else{
				$('#amount_'+iProductID).val(cnt);
			}
		}else if(sType=='good_item'){
			$('#amount_'+iProductID).val(cnt);
		}
		
		if(inBasket==1 && cnt>=1){
			$.post('/ctrl/basket/update.html', {iProductID:iProductID, iProductCount:cnt}, function(data){
				$('#korz3')[0].innerHTML=data.content;
				if($('#total')[0]){
					sum=parseInt(data.sum)+delivery;
					$('#total')[0].innerHTML=sum;
				}
			},"json");
		}
	}else{
		$('#amount_'+iProductID).val(amount_count);
		alert("Введены некорректные данные");
	}
		
}

function removeProduct(iProductID,obj){
	$.post('/ctrl/basket/remove.html', {iProductID:iProductID}, function(data){
		//$(obj).parents().find('.good_tr:first').remove();
		$('#tr_'+iProductID).remove();
		if(data.sum!=0){
			$('#korz3')[0].innerHTML=data.content;
			$('#total')[0].innerHTML=data.sum;
		}else{
			document.location="/basket/";
		}
	},"json");
}

function formValidate(){
	var data;
	var aTemp=$('#delivery').val().split(':');
	var iDeliveryID=parseInt(aTemp[0]);
	var sTypeBuyer=$('#buyer').val();
	
	if(sTypeBuyer=='legal_entity'){
		var company_name=$('#company_name').val();
		var inn=$('#inn').val();
	}
	
	if(sTypeBuyer=='individual'){
		var fio=$('#fio').val();
	}
	
	var contact_phone=$('#contact_phone').val();
	var email=$('#email').val();
	
//	if(iDeliveryID > 0){
		var address=$('#address').val();
//	}
	
	var reg_email=/^[-._a-z0-9]+@(?:[a-z0-9][-a-z0-9]+\.)+[a-z]{2,6}$/;
	var captcha=$('#postform_captcha').val();
	var error=0;
	
	if(sTypeBuyer=='legal_entity'){
		if(company_name==""){
			$('#company_name_error').html("Введите название компании");
			error=1;
			return false;
		}else{
			$('#company_name_error').html("");
			error=0;
		}
//		if(inn==""){
//			$('#inn_error').html("Введите ИНН");
//			error=1;
//			return false;
//		}else{
//			$('#inn_error').html("");
//			error=0;
//		}
	}
	
	if(sTypeBuyer=='individual'){
		if(fio==""){
			$('#fio_error').html("Введите ФИО");
			error=1;
			return false;
		}else{
			$('#fio_error').html("");
			error=0;
		}
	}
	
	if(contact_phone==""){
		$('#contact_phone_error').html("Введите контактный телефон");
		error=1;
		return false;
	}else{
		$('#contact_phone_error').html("");
		error=0;
	}
	if(email==""){
		$('#email_error').html("Введите email");
		error=1;
		return false;
	}else{
		if(!reg_email.test(email)){
			$('#email_error').html("Введен некорректный email");
			error=1;
			return false;
		}else{
			$('#email_error').html("");
			error=0;
		}
	}
	if(captcha==""){
		$('#captcha_error').html("Введите цифры");
		error=1;
		return false;
	}else{
		$('#captcha_error').html("");
		error=0;
	}
	if(error!=1){
	
	if(sTypeBuyer=='individual'){	
		data = {
			fio : fio,
			contact_phone : contact_phone,
			email : email,
			address : address,
			postform_captcha : captcha,
			delivery_id : aTemp[0],
			delivery_price : aTemp[1]
		}
	}
	
	if(sTypeBuyer=='legal_entity'){	
		data = {
			company_name : company_name,
			inn : inn,
			contact_phone : contact_phone,
			email : email,
			address : address,
			postform_captcha : captcha,
			delivery_id : aTemp[0],
			delivery_price : aTemp[1]
		}
	}
		
		$('#submit_div').css('padding-top','15px');
		$('#submit_div')[0].innerHTML="<img src='/_img/ajax-loader.gif' />";
		var aTemp=$('#delivery').val().split(':');
		$.post('/ctrl/order/issue.html', data, function(data){
			data=data.replace(/\n/g,'');
			if(data=="captcha_error"){
				$('#captcha_error').html("Неверно введены цифры");
				$('#submit_div')[0].innerHTML="<input type='submit' value='' id='issue' name='issue' />";
			}else{
				window.location="/basket?res=ok";
			}
		});
	} 
}

function formSubmit(){
	$('#submit_div').css('padding-top','15px');
	$('#submit_div')[0].innerHTML="<img src='/_img/ajax-loader.gif' />";
	$.post('/ctrl/order/issue.html',function(data){window.location="/basket?res=ok&order_id="+data.order_id+""});
}

function displayOthers(btn,hidden_id){
	document.getElementById(hidden_id).style.display = "block";
	btn.style.display = "none";
}

//function setCharacter(iCharacterID, i1cID, obj){
function setCharacter(obj){
	var selIndex=$(obj)[0].selectedIndex;
	var iCharacterID=$('#character_'+selIndex).val();
	var i1cID='00000000-0000-0000-0000-000000000000';
	$('#character_'+selIndex).attr('selected','selected');
	$('#character_price').html($('#character_'+selIndex).attr('price'));
	$('#character').val(i1cID);
	$('#basket_btn').html("<input type='button' id='btn_to_basket' name='btn_to_basket' onclick='toBasket("+$('.buy_radio').attr('product_id')+","+iCharacterID+")' />");
	UpdateContent(iCharacterID);
}

function setProductCharacter(iCharacterID,iLine,iCount){
	$('#character').each(function(){
		this.checked = true;
	});
	$('#parent_goods').removeAttr('disabled');
	$('#parent_goods')[0].selectedIndex=iLine;
	$('#character_price').html($('#character_'+iLine).attr('price'));
	$('input[name=amount_count]').val(iCount);
	$('#basket_btn').html("<input type='button' id='btn_to_basket' name='btn_to_basket' onclick='toBasket("+$('.buy_radio').attr('product_id')+","+iCharacterID+")' />")
	UpdateContent(iCharacterID);
}

function shadowboxOpen(){
	Shadowbox.open({
        content:    '<div id="welcome-msg"><video controls width="640" height="360" autoplay=""><source src="/_swf/video.ogv" type="video/ogg" /><source src="/_swf/video.mp4" type="video/mp4" /><embed src="http://www.youtube.com/v/9jn8wsBu1AY?fs=1&amp;hl=ru_RU" type="application/x-shockwave-flash" width="640" height="360" allowscriptaccess="always" allowfullscreen="true" autoplay="true"></embed></video></div>',
        player:     "html",
        width: 640,
        height: 360
    });
}

function news_toggle(id){
	if($('.news_lead','#news_'+id).css('display')=='none'){
		$('.news_lead','#news_'+id).show();
	}else{
		$('.news_lead','#news_'+id).hide();
	}
}

function RegConfValidate(sType){
	var fio=$('#fio').val();
	var company=$('#company').val();
	var phone=$('#phone').val();
	var sector=$('#sector').val();
	var post=$('#post').val();
	var registration_email=$('#registration_email').val();
	var reg_email=/^[-._a-z0-9]+@(?:[a-z0-9][-a-z0-9]+\.)+[a-z]{2,6}$/;
	var error=0;
	if(fio==""){
		$('.fio_error').html("Введите ФИО");
		var error=1;
	}else{
		$('.fio_error').html("");
	}
	if(company==""){
		$('.company_error').html("Введите название компании");
		var error=1;
	}else{
		$('.company_error').html("");
	}
//	if(post==""){
//		$('.post_error').html("Введите должность");
//		var error=1;
//	}else{
//		$('.post_error').html("");
//	}
	if(phone==""){
		$('.phone_error').html("Введите номер телефона");
		var error=1;
	}else{
		$('.phone_error').html("");
	}
	if(registration_email==""){
		$('.email_error').html("Введите email");
		var error=1;
	}else{
		if(!reg_email.test(registration_email)){
			$('.email_error').html("Введите корректный email");
			var error=1;
		}else{
			$('.email_error').html("");
		}
	}
	if(error==0){
//		if(sType!="testdrive"){
			$.post('/ctrl/order/reg_conf.html', {fio:fio, company:company, phone: phone, email:registration_email},
			function(data){
				window.location="/dealers/?res=ok";
			});
//		}else{
//			$.post('/ctrl/order/testdrive.html', {fio:fio, company:company, phone: phone, email:registration_email},
//			function(data){
//				window.location="/testdrive/?res=ok";
//			});
//		}
	}else if(error==1){
		return false;
	}
}

function showCongratulations(sType){
	var oRegBlock=Elem("registration_block");
//	if(sType!="testdrive"){
//		oRegBlock.innerHTML="<div><b>Спасибо за регистрацию. Администрация сайта рассмотрит вашу заявку в ближайшее время.</b><div><a href='/conf/'>Оставить еще одну заявку</a></div></div>";
//	}else{
		oRegBlock.innerHTML="<div><b>Спасибо за регистрацию. Администрация сайта рассмотрит вашу заявку в ближайшее время.</b><div><a href='/dealers/'>Оставить еще одну заявку</a></div></div>";
//	}
}

function show_hide_form(id){
	var oSubmitDiv=Elem("submit_div");
	if (id=="already"){
		showhide("already_form","first_form");
		var on = document.getElementById("already_done");
		var off = document.getElementById("first");
		oSubmitDiv.innerHTML="";
	}
	if(id=="first"){
		showhide("first_form","already_form");
		var on = document.getElementById("first");
		var off = document.getElementById("already_done");
		oSubmitDiv.innerHTML="<input type='submit' value='' id='issue' name='issue' />";
		$('.errors').each(function(i){
			$(this).html("");
		});
	}
	on.className="about_selected";
	off.className="cursor";
}

function showhide(idshow,idhide){
	var a = document.getElementById(idshow);
	var b = document.getElementById(idhide);
	a.style.display="block";
	b.style.display="none";
}

function showHide(sBlock){
	if(sBlock=="individual"){
		$('#fio_tr').show();
		$('#company_name_tr').hide();
		$('#inn_tr').hide();
		$('#buyer').val('individual');
	}
	if(sBlock=="legal_entity"){
		$('#fio_tr').hide();
		$('#company_name_tr').show();
		$('#inn_tr').show();
		$('#buyer').val('legal_entity');
	}
}

function checkFields(id){
	var iReqCount=0;
	var thisText="";
	var iEnable=0;
	$('.req','#already_form').each(function(){
		iReqCount=iReqCount+1;
	});
	$('.req','#already_form').each(function(){
		thisText=$(this).val();
		if(thisText!=""){
			iEnable=iEnable+1;
		}
	});
	if(iEnable==iReqCount){
		$('#login_btn').removeAttr('disabled');
	}else{
		$('#login_btn').attr('disabled','disabled');
	}
}

/*Капча*/
function captcha(){
	var oElem=Elem('captcha_img');
	if(oElem){
		oElem.src='/ctrl.html?ctrl=captcha&rnd='+Math.round(10000*Math.random());
		var oElem=Elem('postform_captcha');
		if(oElem){
			oElem.value='';
		}
	}
}

function UpdateContent(iProductID){
	$.post('/ctrl/products/update_content.html', {iProductID:iProductID}, function(data){
		$('#about_short')[0].innerHTML=data.about_short;
		$('#about')[0].innerHTML=data.about;
		Shadowbox.init({overlayOpacity: 0.8}, setupConf);
	}, "json");
}

function checkForm(){
	var price_min=$('#price_from').val();
	var price_max=$('#price_to').val();
	presense="";
	if($('#presense')[0].checked==true){
		presense=1;
	}
	var vendors="";
	var parameters = "";
	var redir_str="";
	$('.vendor_check').each(function(i){
		if($(this)[0].checked){
			vendors=vendors+$(this).attr('id')+",";
		}
	});
	$('.parameter_item').each(function(){
		if($(this)[0].checked){
			parameters=parameters+$(this).val()+",";
		}
	});
	vendors=vendors.substring(0,vendors.length-1);
	parameters=parameters.substring(0,parameters.length-1);
	if(vendors!="")	redir_str=redir_str+"&filter_vendors="+vendors;
	if(parameters!="")	redir_str=redir_str+"&filter_parameters="+parameters;
	if(price_min!="")	redir_str=redir_str+"&price_min="+price_min;
	if(price_max!="")	redir_str=redir_str+"&price_max="+price_max;
	if(presense!="")	redir_str=redir_str+"&presense="+presense;
	
	if(redir_str){
		document.location="?"+redir_str.substring(1);
	}else{
		document.location = $.getUrlWithoutParam();
	}
	
}


function selectDelivery(){
	var aTemp=$('#delivery').val().split(':');
	var total=0;
	var delivery=parseInt(aTemp[1]);
	var iDeliveryID=parseInt(aTemp[0]);
	$('.sum_for_product').each(function(){
		total=total+parseInt($(this).val());
	});
	total=eval(total)+eval(delivery);
	$('#total').html(total);
	$('#total').attr('price',total);
	if(iDeliveryID > 0){
		$('#address_tr').show();
	}else{
		$('#address_tr').hide();
	}
}

function resetDelivery(){
	$('#delivery')[0].selectedIndex=0;
}

function checkSubmitButton(obj){
	if($(obj)[0].checked==true){
		$('#issue').removeAttr('disabled').css('cursor','pointer');
	}else{
		$('#issue').attr('disabled','disabled').css('cursor','default');
	}
}

////////////////////////////////////////
function addInput(){
	var iCount=Elem('count').value;
	iCount=eval(iCount)+1;
	var oMainDiv=Elem('MainDiv');
	var oDiv=document.createElement('div');
	var oCaption=document.createElement('input');
	var oCaptionLabel=document.createElement('label');
	var oInput=document.createElement('input');
	//var oInputLabel=document.createElement('label');
	var oImg=document.createElement('img');
	oCaption.type='text';
	oCaption.id='caption'+iCount;
	oCaption.name=oCaption.id;
	oCaptionLabel.innerHTML='&nbsp;&nbsp;подпись: ';
	oInput.type='file';
	oInput.id='file'+iCount;
	oInput.name=oInput.id;
	oInput.className='button';
	//oInputLabel.innerHTML='&nbsp;Файл: ';
	oImg.src='/_img/mini_del_red.gif';
	oImg.width=9;
	oImg.height=9;
	oImg.align='absmiddle';
	oImg.onclick=deleteInput;
	oImg.id=iCount;
	oImg.style.paddingLeft='5px';
	oImg.style.cursor='pointer';
	oDiv.id='div'+iCount;
	oDiv.name=oDiv.id;
	oDiv.appendChild(oInput);
	oDiv.appendChild(oCaptionLabel);
	oDiv.appendChild(oCaption);
	//oDiv.appendChild(oInputLabel);
	oDiv.innerHTML=oDiv.innerHTML+'&nbsp;';
	oDiv.appendChild(oImg);
	oMainDiv.appendChild(oDiv);
	Elem('count').value=iCount;
	oMainDiv.style.marginBottom='10px';
	var oAddFile=Elem('add_file');
	if(oAddFile && oAddFile.innerHTML=='Прикрепить файл'){
		oAddFile.innerHTML='Прикрепить еще один файл';
	}
}



////////////////////////////////////////
function deleteInput(){
	var oMainDiv=Elem('MainDiv');
	var oDiv=Elem('div'+this.id);
	if(oDiv){
		oMainDiv.removeChild(oDiv);
		if(oMainDiv.hasChildNodes()==false){
			var oAddFile=Elem('add_file');
			if(oAddFile && oAddFile.innerHTML=='Прикрепить еще один файл'){
				oAddFile.innerHTML='Прикрепить файл';
				oMainDiv.style.marginBottom='0px';
			}
		}
	}
}

function setImage(obj, sImgBig){
	//var oImgBig=Elem("product_image");
	var oDivImgBig=Elem("icons_container");
	/*oImgBig.src=sImgBig;
	oImgBig.height=335;
	oImgBig.width=510;*/
	oDivImgBig.style.background="url('"+ sImgBig +"') no-repeat center";
	
	$('.additional_image').each(function(){
		$(this).find('.underline').remove();
	});
	$(obj).append('<div class="underline"></div>');
}

function setCookie (name, value, path){
	document.cookie = name + "=" + escape(value) +
	((path) ? "; path=" + path : "");
} 

function getCookie(name){
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}

function checkParameterViewCookie(){
	var cookie_parameter_view = getCookie("parameters_view");
	if(cookie_parameter_view == 1){
		$('#characters_filter').show();
		$('#show_characters').html("Скрыть характеристики");
		$('#select_button_td').append($('#select_button'));
	}else{
		$('#characters_filter').hide();
		$('#show_characters').html("Показать характеристики");
	}
}

$(function(){
	var filter_parameters = $.getUrlParam('filter_parameters');
	if(filter_parameters && $('.parameter_item').size()>0){
		var params = filter_parameters.split(',');
		for(i=0; i<params.length; i++){
			$('input[value="'+params[i]+'"]')[0].checked=true;
			$('input[value="'+params[i]+'"]').parents('.character_group').find('.character_group_title').removeClass('closed').addClass('open')
			$('input[value="'+params[i]+'"]').parents('.characters').css('display','block');
		}
	}
	var presense = $.getUrlParam('presense');
	if(presense){
		$('#presense')[0].checked=true
	}
})

function getGeoMap(){
	var query = $('#query_search').val();
	if(query){
		$.post('/ctrl/all4geo/index.html', {query : query}, function(data){
			if(data.result){
				window.open('http://www.all4geo.com/ru/track/?company_id=1&order='+data.result);
//				$('#geo_res').html('<a href="http://www.all4geo.com/ru/track/?company_id=1&order='+data.result+'" target="_blank">Помотреть местонахождение</a><span style="margin-left:20px;color:#1975FE;cursor:pointer;border-bottom:dotted 1px#1975FE;" id="other_number" onclick="OtherNumber()">Ввести другой номер заказа</span>');
			}
			if(data.result_error){
				$('#geo_res').html('Ничего не найдено <span style="margin-left:20px;color:#1975FE;cursor:pointer;border-bottom:dashed 1px#1975FE;" id="other_number" onclick="OtherNumber()">Ввести другой номер заказа</span>');
			}
		},"json");
	}
}

function OtherNumber(){
	$('#geo_res').html('<form method="post" action="javascript:void(0)" onsubmit="getGeoMap()"><input type="text" name="query" style="height: 25px; font-size: 12px; width: 150px; padding-left: 5px;" id="query_search" value="Введите номер заказа"  onfocus="focusTxt(\'query_search\',\'Введите номер заказа\')" onblur="blurTxt(\'query_search\',\'Введите номер заказа\')" /><input type="submit" value="Отследить статус" style="cursor:pointer;margin-left:10px;" /></form>');
}
