function showParSearchable(e,tooltipshift){
	showToolTip(e,'В этом разделе возможен поиск по параметрам',tooltipshift);
}
function showToolTip(e,text,tooltipshift){
	if(document.all)e = event;
	
	var obj = document.getElementById('bubble_tooltip');
	var obj2 = document.getElementById('bubble_tooltip_content');
	obj2.innerHTML = text;
	obj.style.display = 'block';
	var st = Math.max(document.body.scrollTop,document.documentElement.scrollTop);
	if(navigator.userAgent.toLowerCase().indexOf('safari')>=0)st=0; 
	var leftPos = e.clientX - 100 + tooltipshift;
	if(leftPos<0)leftPos = 0;
	obj.style.left = leftPos + 'px';
	obj.style.top = e.clientY - obj.offsetHeight -1 + st + 'px';
}	

function hideToolTip()
{
	document.getElementById('bubble_tooltip').style.display = 'none';
	
}

function showimg(id_img){
	document.getElementById(id_img).className='ImageOn'
	//alert(id_img+' on')
}

function hideimg(id_img){
	document.getElementById(id_img).className='ImageOff'
	//alert(id_img+' off')
}

function loadimg(id_img,imageref){
	//alert(id_img)
	image=document.getElementById(id_img)
	image.innerHTML='<img src="'+imageref+'">'
	image.className='ImageOn'
}

function unloadimg(id_img){
	image=document.getElementById(id_img)
	image.innerHTML=''
	image.className='ImageOff'
}


function chk_qty(id_good){
	//alert('chk_qty: id='+id_good)
	lookup_leadtime(id_good)
}

function lookup_leadtime(id_good){
	document.getElementById('span_chk_good_'+id_good).innerHTML='Минутку.....'
	var make_new = false //Готовимся к вызову Ajax: проверяем наличие объекта xmlhttp
	if (typeof(xmlhttp) == 'undefined') {
		make_new = true
	}
	else{
		if (!xmlhttp) { make_new = true }
	}
	if (make_new){ xmlhttp = getXmlHttpRequest()} 
	if (!xmlhttp) {
		alert('no httprequest object')
		return
	}
	//Вызываем по Ajax страницу sp_response со всеми нужными параметрами
	var xurl='/sp_lookup.html?&id_good='+id_good
	xmlhttp.open('GET',xurl,true)
	xmlhttp.onreadystatechange = refreshleadtime	//В процедуру refreshleadtime идет результат php-скрипта sp_lookup
	xmlhttp.send(null)
}

function leadtime_msg(stock_elfa,contact_mail){
	var msg
	switch(stock_elfa) {
		case '0':
			msg = 'Срок поставки: <a href="mailto:'+contact_mail+'?subject=%E7%E0%EF%F0%EE%F1">По&nbsp;запросу</a>'
			break;
		case 'localhost..':
			msg = 'stock_elfa'
			//msg = '<a href="mailto:'+contact_mail+'?subject=%E7%E0%EF%F0%EE%F1">По запросу</a>'
			break;
		default:
			msg = "<b>Срок поставки: от&nbsp;4-6&nbsp;недель</b><br><font color=\"#F15922\"><b>Наличие на складе<br>(Швеция, Cтокгольм): "+stock_elfa+"</b></font>"
	}
	return msg
}

function refreshleadtime(){
	if (xmlhttp.readyState == 4) {
		if(xmlhttp.status == 200) {
			var requestresult=xmlhttp.responseText
			posgrid = requestresult.indexOf('#')
			if(posgrid){	//id_good#stock_elfa#contact_mail
				var arrres = explode('#',requestresult)
				id_good = arrres[0]
				stock_elfa = arrres[1]
				contact_mail = arrres[2]
				document.getElementById('span_chk_good_'+id_good).innerHTML = leadtime_msg(stock_elfa,contact_mail)
			}
		}
	}
}

function page_links(){
	document.getElementById('page_links_js').className='pljsvis'
	document.getElementById('page_links_html').className='invis'
}

function make_wide(){
	document.getElementById('extra').className='invis'
	ocontent=document.getElementById('content')
	if(ocontent){ ocontent.style.cssText='width:805px; float:left; overflow:visible;'}
}

function make_normal(){
	document.getElementById('extra').className='vis'
	ocontent=document.getElementById('content')
	if(ocontent){ ocontent.style.cssText='width:616px; float:left; overflow:hidden;'} 
}

function loadplist(page){
	//alert('loadplist '+page)
	var spanc=document.getElementById('pagelink_'+page).children
	if (spanc.length>0){
		spanc[0].className='dimmed'
		spanc[0].onclick=''
		//spanc[0].innerHTML=' '
	}
	//alert(spanc.length+'; className='+spanc[0].className)
	attr_recalc('show',page,'','','sp_response')
}

function show_buskets(){
	//var buskets=document.getElementsByName('span_good')
	var buskets=document.getElementsByTagName('span')
	//alert('show_buskets='+buskets.length)
	for (var i=0; i<buskets.length; i++){
		if (buskets[i].id.indexOf('span_good')==0){
		//alert('buskets.name='+buskets[i].name+' class='+buskets[i].className)
		buskets[i].className='vis'
		}
	}
	//document.getElementById('input_submitbusket').className='invis'
	var input_tag=document.getElementById('input_submitbusket')
	if (input_tag){
		input_tag.parentNode.removeChild(input_tag)
	}
}

function putinbusket(id_good,pack){
	qty_input=document.getElementById(id_good).value
	var page=0
	var div_page=document.getElementById('div_page')
	if(div_page){
		page=div_page.innerHTML
	}
	//alert('Good '+id_good+' is going to your busket, value='+qty_input+'; page='+page)
	var valid=false
	mess='valid?'
	if (qty_input>0){
		if(pack>1){
			if ((qty_input % pack)==0){ valid=true }
			else{ mess='Этот товар продается только в количестве, кратном '+pack }
		}
		else { valid=true }
	}
	else { mess='Пожалуйста введите количество!' }
	if (valid){
		document.getElementById('span_'+id_good).innerHTML='Минутку.....'
		busket=document.getElementById('busket_left')
		busket1=document.getElementById('busket_left1')
		busket2=document.getElementById('busket_left2')
		if(busket) { busket.innerHTML='Корзина [*]' }
		if(busket1) { busket1.innerHTML='Корзина [*]' }
		if(busket2) { busket2.innerHTML='Корзина [*]' }
		var response_link='sp_response'
		if (document.URL.indexOf('/search')>0){
			//alert('search!')
			response_link='sr_response'
		}
		if (document.URL.indexOf('/advanced_search')>0){
			//alert('advanced_search!')
			response_link='asr_response'
		}
		attr_recalc('busket',page,id_good,qty_input,response_link)
	}
	else{
		alert(mess)
	}
}

function attr_recalc(arg,page,id_good,qty_input,response_link){
	//Если arg=='select' , то второй аргумент - номер параметра (idn)
	//если arg='show' или 'leadtime', то второй аргумент - номер страницы;
	//если arg='busket', то второй аргумент - id_количество */
	if (arg=='select' && page>0){			//Вызов в режиме select - ткнули в значение параметра; idn>0
		var idn=page
		var sel=document.getElementById('select_'+page)
		var opts=sel.options
		//alert('.....Не ткнули ли в disabled, selectedIndex='+sel.selectedIndex)
		if (sel.selectedIndex<0) {			//Ткнули в disabled, SelectedIndex<0, возвращаемся, ничего не делая
			//sel.selectedIndex=0
			//opts[0].selected=true
			//alert('Ткнули в disabled, SelectedIndex<0')
			return
		}
		else {
			if ((opts[sel.selectedIndex].className=='disab') || opts[sel.selectedIndex].disabled ) {//Ткнули в disabled просто..возвращаемся, ничего не делая
				//alert('Ткнули в disabled просто..')
				//sel.selectedIndex=0
				//opts[0].selected=true
				return // Ткнули в disabled
			}
		}
	}										//Если посетитель выбрал 2 или более, к БД придется обращаться
	var post=formrcreq()				//Формируем паровоз из выбранных значений/параметров
	//alert('attr_recalc: arg='+arg+';  post='+post+';  page='+page)
	var prefix=''
	var div_prefix=document.getElementById('div_prefix')
	if (div_prefix){
		prefix=div_prefix.innerHTML
	}
	//alert('attr_recalc: prefix='+prefix)
	if((post == '') && (arg == 'select')){
		refreshtotal() //Ткнули в значение параметра. Обновляем кнопку 'Показать', ставим полное количество
	}
	else{				//Другие варианты вызова поцедуры. select/show/busket
		if ((arg=='select') || (arg=='show')){//Обновляем кнопку 'Показать', ставим временное сообщение (Подсчет/Вывод)
			var totalbutton=document.getElementById('but_total')
			if (totalbutton){
				if (arg=='select'){ totalbutton.value = 'Подсчет, пожалуйста подождите ...'}
				if (arg=='show')  { totalbutton.value = 'Вывод предложений, пожалуйста подождите...'}
			}
		}
		var make_new = false //Готовимся к вызову Ajax: проверяем наличие объекта xmlhttp
		if (typeof(xmlhttp) == 'undefined') {
			make_new = true
		}
		else{
			if (!xmlhttp) {make_new = true}
		}
		if (make_new) { xmlhttp = getXmlHttpRequest() }
		if (!xmlhttp) {
			alert('no httprequest object')
			return
		}
		//Строка параметров в URL вызывающей страницы
		var query_string=''
		var div_args=document.getElementById('div_args')
		if (div_args){
			query_string = div_args.innerHTML
			query_string = str_replace('&amp;','&',query_string)
			query_string = str_replace(String.fromCharCode(0x2329),'&lang',query_string)
		}
		var price = ''
		var div_price = document.getElementById('div_price')
		if(div_price){
			price = div_price.innerHTML
		}
		var stock = ''
		var div_stock = document.getElementById('div_stock')
		if (div_stock){
			var stock = div_stock.innerHTML
		}
		var table_header = document.getElementById('table_header')
		//Вызываем по Ajax страницу sp_response со всеми нужными параметрами
		//alert ('query_string='+query_string)
		var xurl='/'+response_link+'.php?'+query_string+'&page='+page+'&price='+price+'&stock='+stock+'&mode='+arg+'&id_good='+id_good+'&qty_input='+qty_input
		//xurl=str_replace("&amp;",'&',xurl)
		//alert( 'xurl='+xurl )
		xmlhttp.open('POST',xurl,true)
		xmlhttp.onreadystatechange = refreshselect		//В процедуру refreshselect идет возврат результата отработки php-скрипта sp_response
		xmlhttp.send(post)
	}
}

function isnavigator(nav){
	var navigators  = {'ie': 'Microsoft Internet Explorer', 'opera': 'Opera'}
	var res = false
	if(navigator.appName == navigators[nav]){
		res = true
	}
	return res
}

function corrparbox(){
	var parrowclass='parrow'
	if (isnavigator('ie')){parrowclass='parrow_ie'}
	if (isnavigator('opera')){parrowclass='parrow_opera'}
	if (document.getElementById('div_parrow')) { document.getElementById('div_parrow').className=parrowclass }
	if (document.getElementById('div_partable')) { document.getElementById('div_partable').className=parrowclass }
}

function corrparboxw(){
	var parrowclass='parrow_wide'
	if (isnavigator('ie')){parrowclass='parrow_wide_ie'}
	if (isnavigator('opera')){parrowclass='parrow_wide_opera'}
	if (document.getElementById('div_parrow')) {  document.getElementById('div_parrow').className=parrowclass }
	if (document.getElementById('div_partable')) { document.getElementById('div_partable').className=parrowclass }
}
function resetselection(){
	var opera = isnavigator('opera')
	var table=document.getElementById('table_par')
	if(table){
		opts=table.getElementsByTagName('option')
		for (i=0;i<opts.length;i++){
			opts[i].selected = (opts[i].value == 'any') ? true : false
			opts[i].disabled = false
			if (!opera) { opts[i].className='enab' }
		}
		attr_recalc('select',0,'','','sp_response')
	}
}
function formrcreq(){ //Формируем паровоз из выбранных значений/параметров
	var data = ''
	var div_prefix=document.getElementById('div_prefix')
	if (div_prefix){
		var prefix=div_prefix.innerHTML
		//var data = prefix+"\n"
		//alert('data='+data)
		var table=document.getElementById('table_par')
		if(table){
			var sels=table.getElementsByTagName('select')
			for (var i=0; i<sels.length; i++){
				var adddata = ''
				var opts=sels[i].getElementsByTagName('option')
				for (var j=1; j<opts.length; j++){
					if (opts[j].selected){
						adddata += opts[j].value +','
					}
				}
				if(adddata){
					adddata = adddata.substr(0,adddata.length-1)
					data += sels[i].name+':'+adddata+"\n"
				}
			}
		}
	}
	return data
}



function refreshselect(){	//Сюда идет возврат результата отработки php-скрипта sp_response
	var opera = isnavigator('opera')
	var statusElem = document.getElementById('test_status')
	if (xmlhttp.readyState == 4) {
		if(xmlhttp.status == 200) {
			var requestresult=xmlhttp.responseText
			//alert('refreshselect: \n'+requestresult)
			//Если что-то есть до # - считаем, что это текст кнопки
			var buttonvalue = requestresult.substr(0,requestresult.indexOf('#'))
			//Все, что после # - ответ, который надо вставить в div_goods
			var selectable = requestresult.substr(requestresult.indexOf('#')+1)
			var debug=document.getElementById('debug_output')
			//debug.innerHTML='<p>debug begin</p>'+requestresult+'<p>debug end</p>'
			//alert(requestresult)
			var output=''
			if(selectable.indexOf('gtdlivdcyu')==0){	//Если получили допустимые комбинации параметр-значение
				selectable = selectable.substr(11)
				if (selectable.length>0){
					optreset(true)
					//output += 'selectable='+selectable+'<br>\n'
					var arrselect=selectable.split('/')
					for (i=0;i<arrselect.length;i++){
						var arrcolumnp=arrselect[i].split(':')
						var idn=arrcolumnp[0]
						var arrcolumnv=arrcolumnp[1]
						var arrcolumn=arrcolumnv.split(',')
						for (j=0;j<arrcolumn.length;j++){
							var idv=arrcolumn[j]
							var optid='option_'+idn+'_'+idv
							var opt_ij=document.getElementById('option_'+idn+'_'+idv)
							opt_ij.disabled=false
							if (!opera) { opt_ij.className='enab' }
						}
					}
				}
				else{
					optreset(false)
				}
			}
			else{										//Если другой вариант вызова (mode не select, а show, busket, leadtime,...)

				output+=selectable
			}
			var div_goods=document.getElementById('div_goods')
			if (output.length){							//Все, что получили пихаем в элемент div_goods страницы
				div_goods.innerHTML=output
			}
			var debug=document.getElementById('debug_output')
			//debug.innerHTML='<p>debug begin</p>'+requestresult+'<p>debug end</p>'
			show_buskets()
		}
		else{
			buttonvalue ="Сервер не вернул ответа, попробуйте еще раз ("+xmlhttp.status+")";
		}
		if (document.getElementById('but_total')){
			document.getElementById('but_total').value=buttonvalue
		}
	}
	return false
}

function optreset(disabenab){
	var opera = isnavigator('opera')
	var optclass = disabenab?'disab':'enab'
	var row_par = document.getElementById('row_par')
	var allopts = row_par.getElementsByTagName('option')
	for (i=0;i<allopts.length;i++){
		if (!(allopts[i].value=='any')){
			allopts[i].disabled=disabenab
			if (!opera) { allopts[i].className = optclass } //Глюк в том, что класс не выставляется в некоторых редких случаях
		}
	}
}

function refreshtotal(){
	optreset(false)
	var prefix=document.getElementById('div_prefix').innerHTML
	var total=document.getElementById('div_total').innerHTML
	//alert('refreshtotal, prefix='+prefix+'  total='+total)
	var buttonvalue='Показать все ('+total+')'
	document.getElementById('but_total').value=buttonvalue
}

function explode( delimiter, string ) {	// Split a string by string
	// 
	// +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +   improved by: kenneth
	// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)

	var emptyArray = { 0: '' };

	if ( arguments.length != 2
		|| typeof arguments[0] == 'undefined'
		|| typeof arguments[1] == 'undefined' )
	{
		return null;
	}

	if ( delimiter === ''
		|| delimiter === false
		|| delimiter === null )
	{
		return false;
	}

	if ( typeof delimiter == 'function'
		|| typeof delimiter == 'object'
		|| typeof string == 'function'
		|| typeof string == 'object' )
	{
		return emptyArray;
	}

	if ( delimiter === true ) {
		delimiter = '1';
	}

	return string.toString().split ( delimiter.toString() );
}

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;
}

