Validation=function(options){this.options=options;this.form=$(options.form);this.errors={};var me=this;this.form.submit(function(){return me.validate()});for(field in this.options.fields){var validator=(function(field2){return function(){if(this.pressed)me.validate_field(field2,true)}})(field);this.form.find(field).blur(validator);this.form.find(field).keypress(function(ev){if(ev.keyCode!=9)this.pressed=true})}};Validation.prototype={validate:function(){var me=this;for(field in this.options.fields){me.validate_field(field)};if(this.all_errors().length>0){this.show_errors();return false}else{return true}},validate_field:function(field,show_errors){var me=this;this.field=field;var value=this.form.find(field).removeClass("error").val();this.label_tag(field).find("small").remove();this.errors[field]=[];$(this.options.fields[field]).each(function(){return this(value,me)});if(show_errors)this.show_errors_for_field(field)},error:function(message){if(!this.errors[this.field])this.errors[this.field]=[];this.errors[this.field].push(message)},all_errors:function(){var me=this;var all_errors=[];for(field in this.errors){$(this.errors[field]).each(function(){all_errors.push(me.label_of(field)+" "+this)})};return all_errors},label_tag:function(field){return this.form.find("label[for="+field.replace(/^\#/,'')+"]")},label_of:function(field){return this.label_tag(field).html()},show_errors:function(){var me=this;var all_errors_container=me.form.find(".error-messages").show();if(all_errors_container.size()){var error_tag="p";if(all_errors_container.find("ul").size()>0){error_tag="li";all_errors_container=all_errors_container.find("ul")};all_errors_container.html(" ");$(this.all_errors()).each(function(){var p=$("<"+error_tag+">"+this+"</"+error_tag+">");all_errors_container.append(p)})}for(field in this.errors){this.show_errors_for_field(field)}},show_errors_for_field:function(field){if(this.errors[field].length==0)return false;var me=this;this.form.find(field).addClass("error");var label=this.label_tag(field);text=$(this.errors[field]).map(function(){return"<small>"+this+""});label.append(text.get().join(",</small> ")+"</small>")}};Validation.presense=function(message){if(!message)message="Должно быть заполнено";return function(value,object){if(value){return true}else{object.error(message);return false}}};Validation.length_in=function(f,t,message1,message2){if(!message1)message1="слишком короткое";if(!message2)message2="слишком длинное";return function(value,object){if(value.length<f){object.error(message1);return false};if(value.length>t){object.error(message2);return false}};return true};Validation.match=function(regexp,message){if(!message)message="имеет неверный формат";return function(value,object){if(value.match(regexp)){return true}else{object.error(message);return false}}};
if(!Array.indexOf){Array.prototype.indexOf = function(obj){for(var i=0; i<this.length; i++){if(this[i]==obj){return i;};};return -1;};};


function SetActiveTab(tab)
{
	var listElement = tab.parentNode.parentNode;
	var arTabs = listElement.getElementsByTagName("LI");

	//Hide
	for (var i = 0; i < arTabs.length; i++)
	{
		arTabs[i].className = "";
		var tabBody = document.getElementById(arTabs[i].id + "-body");
		if (tabBody)
			tabBody.style.display = "none";
	}

	//Show
	var tabBody = document.getElementById(tab.parentNode.id + "-body");
	if (tabBody)
	{
		tab.parentNode.className = "active";
		tab.blur();
		tabBody.style.display = "block";
	}
}

function ShowSwf(sSwfPath, width1, height1)
{
	var scroll = 'no';
	var top=0, left=0;

	if(width1 > screen.width-10 || height1 > screen.height-28)
		scroll = 'yes';

	if(height1 < screen.height-28)
		top = Math.floor((screen.height - height1)/2-14);

	if(width1 < screen.width-10)
		left = Math.floor((screen.width - width1)/2);

	width = Math.min(width1, screen.width-10);  
	height = Math.min(height1, screen.height-28); 

	window.open('/bitrix/tools/swfpg.php?width='+width1+'&height='+height1+'&img='+sSwfPath,'','scrollbars='+scroll+',resizable=yes, width='+width+',height='+height+',left='+left+',top='+top);
}

function ShowImg(sImgPath, width, height)
{
	var scroll = 'no';
	var top=0, left=0;

	if(width > screen.width-10 || height > screen.height-28)
		scroll = 'yes';

	if(height < screen.height-28)
		top = Math.floor((screen.height - height)/2-14);

	if(width < screen.width-10)
		left = Math.floor((screen.width - width)/2);

	width = Math.min(width, screen.width-10); 
	height = Math.min(height, screen.height-28);  
	window.open('/bitrix/tools/imagepg.php?img='+sImgPath,'','scrollbars='+scroll+',resizable=yes,width='+width+',height='+height+',left='+left+',top='+top);
}

function SetPrintCSS(isPrint)
{
	var link;

	if (document.getElementsByTagName)
		link = document.getElementsByTagName('link');
	else if (document.all)
		link = document.all.tags('link');
	else
		return;

	for (var index=0; index < link.length; index++)
	{
		if (link[index].title != 'print')
			continue;

		if (isPrint)
		{
			link[index].disabled = false;
			link[index].rel = "stylesheet";
		}
		else
		{
			link[index].disabled = true;
			link[index].rel = "alternate stylesheet";
		}
	}
}

var jsPublicForms =
{
	SetFieldValue: function(id, value)
	{
		var field = document.getElementById(id);
		if(field)
		{
			field.value = value;
		}
	}
}

var jsPublicFilters =
{
	SetCookie: function(Name, Value, ArrName)
	{
		if(ArrName)
			document.cookie = ArrName + "[" + Name + "]=" + Value + "; path=/;";
		else
			document.cookie = Name + "=" + Value + "; path=/;";
	},
	
	ShowHide: function(id, action)
	{
		var filter = document.getElementById(id);
		if(filter)
		{
			if(filter.style.display == "none" || "show" == action)
			{
				filter.style.display = "block";
				jsPublicFilters.SetCookie(id,"on","PublicFilters");
			}
			else
			{
				filter.style.display = "none";
				jsPublicFilters.SetCookie(id,"off","PublicFilters");
			}
		}
	},
	
	GetCookie: function (Name, ArrName) 
	{
		if(ArrName)
			var prefix = ArrName + "[" + Name + "]=";
		else
			var prefix = Name + "=";
		var cookieStartIndex = document.cookie.indexOf(prefix);
		if (cookieStartIndex == -1) 
			return null;
		var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length);
		if (cookieEndIndex == -1) 
			cookieEndIndex = document.cookie.length;
		return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex));
	}
}

var jsPublicTabController =
{
	SetTabCookieId: function(TabSec, TabId)
	{
		document.cookie = "BxTabs[" + TabSec + "]=" + TabId + "; path=/;";
	},
	
	SetTabCookieIdUnload: function()
	{
		//no more then 2 tablists
		for(i=0;i<2;i++)
		{
			var tab_ul = document.getElementById('tab-list-id'+i);
			if(tab_ul)
			{
				tab_li = tab_ul.getElementsByTagName('LI');
				for(j=0;j<tab_li.length;j++)
				{
					if(tab_li[j].className == 'active')
					{
						tab_a = tab_li[j].getElementsByTagName('A');
						tab_a[0].onclick();
					}
				}
			}
			else
				break;
		}
	},

	TabToTabAnchor: function(TabId)
	{
		tab = document.getElementById(TabId);
		if(tab)
		{
			tab_a = tab.getElementsByTagName('A');
			tab_a[0].onclick();
			SetActiveTab(tab_a[0]);
		}
	}
}

window.onbeforeunload = jsPublicTabController.SetTabCookieIdUnload;

//change load window
if (window.jsAjaxUtil)
{
	// show ajax visuality
	jsAjaxUtil.ShowLocalWaitWindow = function (TID, cont, bShadow)
	{
		if (typeof cont == 'string' || typeof cont == 'object' && cont.constructor == String)
			var obContainerNode = document.getElementById(cont);
		else
			var obContainerNode = cont;
		
		if (obContainerNode.getBoundingClientRect)
		{
			var obRect = obContainerNode.getBoundingClientRect();
			var obWndSize = jsAjaxUtil.GetWindowSize();

			var arContainerPos = {
				left: obRect.left + obWndSize.scrollLeft, 
				top: obRect.top + obWndSize.scrollTop, 
				right: obRect.right + obWndSize.scrollLeft, 
				bottom: obRect.bottom + obWndSize.scrollTop
			};
		}
		else
			var arContainerPos = jsAjaxUtil.GetRealPos(obContainerNode);
		
		var container_id = obContainerNode.id;
		
		if (!arContainerPos) return;
		
		if (null == bShadow) bShadow = true;
		
		if (bShadow)
		{
			var obWaitShadow = document.body.appendChild(document.createElement('DIV'));
			obWaitShadow.id = 'waitshadow_' + container_id + '_' + TID;
			obWaitShadow.className = 'waitwindowlocalshadow';
			obWaitShadow.style.top = (arContainerPos.top - 5) + 'px';
			obWaitShadow.style.left = (arContainerPos.left - 5) + 'px';
			obWaitShadow.style.height = (arContainerPos.bottom - arContainerPos.top + 10) + 'px';
			obWaitShadow.style.width = (arContainerPos.right - arContainerPos.left + 10) + 'px';
		}
		
		var obWaitMessage = document.body.appendChild(document.createElement('DIV'));
		obWaitMessage.id = 'wait_' + container_id + '_' + TID;
		obWaitMessage.className = 'waitwindow';
		
		var div_top = arContainerPos.top + 5;
		if (div_top < document.body.scrollTop) div_top = document.body.scrollTop + 5;
		
		obWaitMessage.style.top = div_top + 'px';
		obWaitMessage.style.left = (arContainerPos.left + 5) + 'px';
		obWaitMessage.innerHTML = 'Р—Р°РіСЂСѓР·РєР°...';
		
		if(jsAjaxUtil.IsIE())
		{
			var frame = document.createElement("IFRAME");
			frame.src = "javascript:''";
			frame.id = 'waitframe_' + container_id + '_' + TID;
			frame.className = "waitwindow";
			frame.style.width = obWaitMessage.offsetWidth + "px";
			frame.style.height = obWaitMessage.offsetHeight + "px";
			frame.style.left = obWaitMessage.style.left;
			frame.style.top = obWaitMessage.style.top;
			document.body.appendChild(frame);
		}
		
		function __Close(e)
		{
			if (!e) e = window.event
			if (!e) return;
			if (e.keyCode == 27)
			{
				jsAjaxUtil.CloseLocalWaitWindow(TID, cont);
				jsEvent.removeEvent(document, 'keypress', __Close);
			}
		}
		
		jsEvent.addEvent(document, 'keypress', __Close);
	}
}



if (document.location.hash == '#print')
	SetPrintCSS(true); 

if (document.location.hash.indexOf("#tab-") != -1)
{
	var selectedTabID = document.location.hash.substr(5,document.location.hash.length-10);
	window.onload = function() 
	{
		var tab = document.getElementById("tab-" + selectedTabID);

		if (tab && tab.childNodes[0])
			SetActiveTab(tab.childNodes[0]);
	};
}



/* banner - KP tmp */
function CPublicRotateBanner(items, params)
{
	this.Inited = false;
	this.ItemList = items;	

	this.AutoRotation = params.autorotate ? true : false;
	this.CurrentBunner = (params.current && this.ItemList.length >= params.current) ? params.current : 1;

	this.ActiveObj = params.aObj ? document.getElementById(params.aObj) : null;
	this.ListObj = params.lObj ? document.getElementById(params.lObj) : null;
	this.RotateTime = params.rTime ? params.rTime : 1000;
	
	if(this.ItemList.length>0 && this.ActiveObj && this.ListObj)
		this.Inited = true;

	this.ChangeBanner(this.CurrentBunner);
}

CPublicRotateBanner.prototype.ChangeBanner = function(id, handle)
{	
	if(!id || id<=0 || id>this.ItemList.length || !this.Inited)
		return;
		
	if(handle===true)
		this.AutoRotation = false;

	ExCurrent = this.CurrentBunner;
	this.CurrentBunner = id;
	
	Citem = this.ItemList[id-1];
	if(Citem)
	{
		imgs = this.ActiveObj.getElementsByTagName('IMG');
		btns = this.ListObj.getElementsByTagName('LI');

		if(imgs && btns[id-1])
		{
			imgs[0].src = Citem.image;
			this.ActiveObj.href = Citem.link;
			
			btns[ExCurrent-1].className = "";
			btns[this.CurrentBunner-1].className = "item-selected";
			
			if(Citem.functions)
			{
				for(i = 0; i<Citem.functions.length; i++)
				{
					if(Citem.functions[i].func && Citem.functions[i].arg && typeof(Citem.functions[i].func) == 'function')
						Citem.functions[i].func.apply(null, Citem.functions[i].arg);
				}
			}
		}
	}
}

CPublicRotateBanner.prototype.Rotation = function(start)
{
	if(!this.Inited || !this.AutoRotation)
		return;
	
	if(!start)
		this.ChangeBanner((this.CurrentBunner + 1) > this.ItemList.length ? 1 : (this.CurrentBunner + 1));
	
	_this = this;
	setTimeout(function(){_this.Rotation()}, this.RotateTime);
}

CPublicRotateBanner.prototype.PreLoad = function(skip)
{
	for (var imageIndex = 0; imageIndex < this.ItemList.length; imageIndex++)
	{
		if(skip!=imageIndex)
		{
			var imageObj = new Image();
			imageObj.src = this.ItemList[imageIndex].image;
		}
	}	
}

//from menu component
var jshover = function() {
	var sfEls = document.getElementById("horizontal-multilevel-menu").getElementsByTagName("li");
	for (var i=0; i<sfEls.length; i++) 
	{
		sfEls[i].onmouseover=function()
		{
			this.className+=" jshover";
		}
		sfEls[i].onmouseout=function() 
		{
			this.className=this.className.replace(new RegExp(" jshover\\b"), "");
		}
	}
}

if (window.attachEvent) 
	window.attachEvent("onload", jshover);
// end	

function fix_ie6(){

  function LoadImageInFilter(e, s, b) {
      var f = 'DXImageTransform.Microsoft.AlphaImageLoader';
      var sM = (e.currentStyle.backgroundRepeat == 'no-repeat') ? 'crop' : 'scale';
      s = (s || '').replace(/\(/g, '%28').replace(/\)/g, '%29');

      if (s && !(/IMG|INPUT/.test(e.nodeName) && !b) && e.currentStyle.width == 'auto' && e.currentStyle.height == 'auto'){
          e.style.width = e.offsetWidth + 'px';
          e.style.height = e.clientHeight + 'px';
          if (e.currentStyle.display == 'inline') e.style.display = 'inline-block';
      }

      if (e.filters[f]) {
          e.filters[f].enabled = s ? true : false;
          if (s) with (e.filters[f]) { src = s }
      }
      else if (s) e.style.filter = 'progid:' + f + '(src="' + s + '",sizingMethod="' + sM + '")';

      e.ImageSrc = s;
  }
  
  $("img[src$=.png]").each(function() {
    var me = $(this);
    this.width = this.offsetWidth;
    this.height = this.offsetHeight;
    LoadImageInFilter(this,this.src)
    this.src = "/images/design/blank.gif";
  })
  document.execCommand('BackgroundImageCache', false, true);
}

function init(){
  function hoverer(method){
    return function() {
      $(this)[method]("active")
      if(navigator.userAgent.match(/MSIE 6/)) $(this).parent()[method]("active-ie6")
      return false;
    }
  }
  
  $("#models .offer").hover(hoverer("addClass"), hoverer("removeClass"));
  if($("body.lada #content table.variants").size() && location.href.match(/variants/)) $(specs_tabs);
}

function specs_tabs(){
  var t = $("table.variants");
  var engines = {}
  var engines_keys = []
  var engine_selector = "tr:nth-child(2)"
  t.find(engine_selector + " td").each(function(i) {
    var me = $(this)
    if(i > 0){
      var value = me.html();
      if(!engines[value]){ engines_keys.push(value); engines[value] = [0,i]}
      else engines[value].push(i)
    }
  })
  t.find(engine_selector).remove()
  var div = $("<div class='tab-section-container'></div>")
  div.css("margin-left",'-1px')
  var ul = $("<ul class='tab-list'></ul>")
  div.append(ul)
  var clicked = false;
  $(engines_keys).each(function(i) {
    var engine = this;
    var li = $("<li><a href='#tab-"+i+"'><span>"+engine+"</span></a></li>");
    fun = function() {
      ul.find("li").removeClass("active")
      $(this).addClass("active")
      t.find("td").hide()
      $(engines[engine]).each(function(){
        t.find("td:nth-child("+(this+1)+")").show()
      })
    }
    li.click(fun)
    ul.append(li)
    if(!clicked){
      clicked = true;
      fun();
      li.addClass("active")
    }
  })
  t.before(div)
}

$(init)

var to = {
  root: '/static/to',
  
  calc: function() {
    
    to.redraw_form()
    
    var params;
    var model = $("#to_model").val();
    params = $("#complect_"+model).val();
    
    switch(model){
		case 'matiz':
		case 'nexia':
			params += "-";
			if($("#gur")[0].checked) params += "g";
			if($("#cond")[0].checked) params += "c";
			params = params.replace(/-$/,'');
			
			var mil = $("#milliage").val();
			var age = $("#age").val();
			
			if(!mil || !age) return false;
			
			var to_num = -1;
			$(to.periods_daewoo).each(function(i) {
			  if(mil >= this[0]) to_num = i;
			  if((this[1] != 0) && (age >= this[1])) to_num = i;
			})
			to_num += 1;
			
			params += "/" + to_num + ".html";
			$("#result").html("Загрузка…");
			$("#result").load(to.root + '/' + params, to.show_contacts);
		break;
			
		case 'accent':
		case 'sonata':
			var mil = $("#milliage").val();
			if(!mil) return false;
			var oil = $('#syn').val();
			
			var to_num=0;
			if(mil<1500) to_num=0;
			else if(mil<=1999) to_num=1;
			else to_num=Math.ceil((mil-400)/10000)+1;
			
			params = to.root + '/hyundai.php?p=' + params + oil +'_' + to_num;
			$("#result").html("Загрузка…");
			$("#result").load(params, to.show_contacts);
		break;
			
		default: break;
	}
  },
   
  periods_daewoo: [
    [2000,0],
    [10000,6],
    [20000,12],
    [30000,18],
    [40000,24],
    [50000,30],
    [60000,36],
    [70000,42],
    [80000,48],
    [90000,54],
    [100000,60]
  ],

 
  show_contacts: function() {
    $("#syn").click()
    $("#order_to .contacts").show()
    $("#order_to .note").show()
  },
  
  redraw_form: function(){
    // select 2
    $("#complect_matiz, #complect_nexia, #complect_accent, #complect_sonata").hide().attr("name",'fake_complect');
	to_model=$("#to_model").val();
    complect_field = $("#complect_" + to_model);
    complect_field.show().attr("name",'complect');
    switch(to_model){
		case 'accent':
		case 'sonata':
			$('#p_syn').show();
			$('#p_gur, #p_cond, #p_age').hide();
			if($('#age').val()=="") $('#age').val('0');
			break;
		default:
			$('#p_gur, #p_cond, #p_age').show();
			$('#p_syn').hide();
			break;
	}
    var gur = $("#gur");
    
    //checkboxes
    switch(complect_field.val()){
      case 'mb':
      case 'ma':
        gur.attr("checked","true")
        gur.attr("disabled",'true');
        break;
      default:
        gur.removeAttr("disabled");
    }
    
  }
}


var init_to = function() {
  $("#order_to .auto select, #order_to .auto input").change(to.calc)
  
  var names = "#milliage #age #to_fio #to_phone".split(' ');
  var pres = [Validation.presense("Пожалуйста, введите информацию")];
  var fields = { "#to_email": [Validation.presense("Пожалуйста, введите информацию"), Validation.match(/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i)] };
  for(var i = 0; i < names.length; i++){
    fields[names[i]] = pres;
  }

  var validator = new Validation({form: "#order_to", fields: fields})
}
