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 setCookie(name, value, expiredays, path, domain, secure) {
	if (expiredays) {
		var exdate=new Date();
		exdate.setDate(exdate.getDate()+expiredays);
		var expires = exdate.toGMTString();
	}
	document.cookie = name + "=" + escape(value) + ((expiredays) ? "; expires=" + expires : "") + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : "");
}
//------------------------------------------
// Основные функции
//------------------------------------------
var wait_time;
//------------------------------------------
function wait() {
  el = $('#search_button').val();
  if (el != "Что будем искать?" && el !=  "") {
    clearTimeout(wait_time);
    //search(el.value);
    wait_time = setTimeout('search("'+el+'")',400);
  }
  else {
     $('#status_load').hide();
     $('#status_msg').hide();
     $('#search_out').html("");
     $('#spell').html("");
     $('#spell').hide();
     $('#copy_link').html("");
     $('#copy_link').hide();
  }
}
function search(str) {
	var str2 = $('#search_button').val();
	if (str == $('#search_button').val() && str2.length >= 3) {
		$('#maintheme_search').show();
		var post  = "function=search&search="+encodeURIComponent(str);
		var url = "http://skoda-tech.ru/index.php";
		$('#status_load').show();
		$.ajax({
			type: "POST",
			data: post,
			url: url,
			success:  function(msg){
				clearTimeout(wait_time);
				construct(msg);
				$('#status_load').hide();
			}
		});
	}
	else {
		clearTimeout(wait_time);
		wait_time = setTimeout("wait('"+document.getElementById('search_button').value+"')",300);
	}
}
/* функция по сбору таблицы ответа. */
function construct(out) {
   var t = "";	//имя прошлой таблицы
   var s = "";	//статус прошлой таблицы
   var i = 0;	//счетчик полей
   var y = 0;	//счетчик таблиц
   var str = "";
   var tabs = new Array();
   var pref = ""; //префикс Альтернативности
   var clas = ""; //переменная класса, цвет строки
   tabs = out.split('|'); //разбиваем на таблицы
   var top_max = tabs[1]; //верхняя граница кол-ва таблиц
   top_max = (top_max * 1) + 4;
   if (top_max > 4) {
     var s1 = "";
     var s2 = "";
     var char_num1 = 0;
     var char_num2 = 0;
     char_num = tabs[2].length - 1;
     if (tabs[2].charAt(char_num) == 1) { s1 = "найдена <b>"+tabs[2]+"</b> позиция"; }
     if (tabs[2].charAt(char_num) == 2) { s1 = "найдено <b>"+tabs[2]+"</b> позиции";  }
     else { s1 = "найдено <b>"+tabs[2]+"</b> позиций"; }
     if (tabs[3] != "") {
       document.getElementById('spell').style.display = "block";
       document.getElementById('spell').innerHTML = "Вероятнее всего Вы хотели найти: <b><a href='http://skoda-tech.ru/s_"+encodeURIComponent(tabs[3])+"' class='link'>"+tabs[3]+"</a></b>";
       document.getElementById('copy_link').innerHTML = "Ссылка на данную выборку: <a href='http://skoda-tech.ru/s_"+encodeURIComponent(tabs[3])+"'>http://skoda-tech.ru/s_"+tabs[3]+"</a>";
     }
     else {
       document.getElementById('spell').innerHTML = "";
       document.getElementById('spell').style.display = "none";
       document.getElementById('copy_link').innerHTML = "Ссылка на данную выборку: <a href='http://skoda-tech.ru/s_"+encodeURIComponent(document.getElementById('search_button').value)+"'>http://skoda-tech.ru/s_"+document.getElementById('search_button').value+"</a>";
     }
     document.getElementById('copy_link').style.display = "block";
     if (tabs[1] == 1) { s2 = " в <b>"+tabs[1]+"</b> разделе."; }
     else { s2 = " в <b>"+tabs[1]+"</b> разделах."; }
     document.getElementById('status_msg').style.display = "block";
     document.getElementById('status_msg').innerHTML = "По вашему запросу было "+s1+s2;
     document.getElementById('status_msg').style.visibility = "visible";
     for (y=4;top_max>y;y++) {
       var rows = new Array();
       var cols = new Array();
       var part = new Array();
       part = tabs[y].split('@'); //отделяем и разбиваем хедеры
       if (part[1] == "1" ) { pref = ""; }
       if (part[1] == "2") { pref = "<acronym class='alter' title='Был совершен нестрогий поиск'>(Альтернативный поиск)<acronym>" }
       if (part[1] == "3") { pref = "<acronym class='alter' title='В Вашем запросе присуствуют орфографические ошибки'>(Альтернативный поиск - орфография)<acronym>" }
       rows = part[3].split('#'); //разбиваем на строки
       var top_line = part[2] * 1;
       if (top_line > 0) {
         str += "<p class='head_small'><b>";
         if (part[0] == "spares_sk") { str += "<a href='http://skoda-tech.ru/catalog.html' class='link'>Каталог</a>-><a href='http://skoda-tech.ru/price/price_sk.xls' class='link'>Запчасти Шкода</a>"+" "+pref; }
         if (part[0] == "service") { str += "<a href='http://skoda-tech.ru/catalog.html' class='link'>Каталог</a>-><a href='http://skoda-tech.ru/price/price.doc' class='link'>Сервис</a>"+" "+pref; }
         if (part[0] == "spares_sk_acc") { str += "<a href='http://skoda-tech.ru/catalog.html' class='link'>Каталог</a>-><a href='http://skoda-tech.ru/price/spares_sk_acc.xls' class='link'>Аксессуары Шкода</a>"+" "+pref; }
         if (part[0] == "spares_vw") { str += "<a href='http://skoda-tech.ru/catalog.html' class='link'>Каталог</a>-><a href='http://skoda-tech.ru/price/spares_vw.xls' class='link'>Запчасти VW</a>"+" "+pref; }
         str += "</b></p>";
         str += "<table class='out_table' cellpadding='7px'>";
         for (i=0;top_line>i;i++) {
           cols = rows[i].split('$'); //раздеряем тело на колонки
           if ((i % 2) == 0) { clas = "grey"; }
           else { clas = "white"; }
           var loc_num = cols[0].replace("<span class=\"marker\">","");
           var loc_desc = cols[1].replace("<span class=\"marker\">","");
           var loc_money = cols[2].replace("<span class=\"marker\">","");
           loc_num = loc_num.replace("</span>","");
           loc_desc = loc_desc.replace("</span>","");
           loc_money = loc_money.replace("</span>","");
           var words = cols[1].split(" ");
           if (words[0] != "" && words[0].length > 2) { word = words[0]; }
           else { word = words[0]+" "+words[1]; }
           str += "<tr class='"+clas+"'>";
           cols[1] = cols[1].replace(word,"<a href='http://skoda-tech.ru/s_"+encodeURIComponent(word)+"' class='link'>"+word+"</a>");
		   if (loc_money == "замена") { loc_money = 0; }
           str += "<td class='bag_line'>"+"<a href='javascript:add_spare_in_bag(\""+loc_num+"\",\""+loc_desc+"\",\""+1+"\",\""+loc_money+"\",\""+part[0]+"\")'><img src='http://skoda-tech.ru/img/general/"+clas+".jpg' border='0px'></a>"+"</td>";
           str += "<td class='number'>"+cols[0]+"</td>";
           str += "<td class='desc'>"+cols[1]+"</td>";
           if (cols[2] == "замена") { str += "<td class='money'>"+cols[2]+"</td>"; }
           else { str += "<td class='money'>"+cols[2]+"руб.</td>"; }
           str += "</tr>";
         }
       }
       str += "</table>";
       delete(rows);
       delete(cols);
       delete(part);
     }
   }
   else {
     $('#status_load').hide();
     $('#status_msg').hide();
     $('#search_out').html("");
     $('#spell').hide();
	 $('#spell').html("");
     $('#copy_link').hide();
	 $('#copy_link').html("");
     str += "По Вашему запросу <b>ничего не найдено</b>. Уточните запрос или перезвоните менеджеру. <b>Запчасти - 211-51-46</b>, <b>Ремонт - 211-66-10</b>.";
   }
   $('#search_out_ajax').html(str);
}
//добавляем в корзину деталь
var tables_glob = "";
function add_spare_in_bag(number,name,count,money,table) {
	$.blockUI({ 
		theme:     true, // true to enable jQuery UI support 
		draggable: true, // draggable option is only supported when jquery UI script is included 
		title:    '<table width="100%"><tr><td align="left">Добавление в корзину</td><td align="right"><img style="cursor: pointer;" id="img_close" width="24px" height="24px" src="/img/ico/cancel_48.png"></td></tr></table>', // only used when theme == true 
		message:   window_tpl[0]
	});
    $('.blockMsg').css({'width':'50%','left':'25%'});
	$('#add_spare_number').html(number);
	$('#add_spare_name').html(name);
	$('#add_spare_count').val(count);
	$('#add_spare_money').html(money);
	$('#add_spare_sum').html(count*money);
	tables_glob = table;
}
function add_spare_reload() {
  var num = $('#add_spare_money').text();
  var num1 = $('#add_spare_count').val();
  num = parseFloat(num) * parseFloat(num1);
  $('#add_spare_sum').html(num.toFixed(2));
}
//------------------------------------------
// Основные функции
//------------------------------------------