// JavaScript Document
///////GLOBAL VARS
var timers=[];
var params=[];
var places_types=['to_cart_on_center_', 'to_cart_on_new_stuff_', 'to_cart_on_presearch_'];
var CURRENT_ORDER_COUNT={};
var CURRENT_ORDER_SUM={};
var CurrentOrderName='CURRENT_ORDER_CONTENT';
var ORDERS={};

function start_roll_search(direction)
{
	if (timers["roll_search"] != null) 
	{
		clearInterval(timers["roll_search"]);
		timers["roll_search_timeout"]=null;
	}
	if (direction != null) params["roll_search_direction"]=direction;
	if (timers["roll_search_timeout"] != null)
	{
		clearTimeout(timers["roll_search_timeout"]);
		timers["roll_search_timeout"]=null;
	}
	timers["roll_search"]=setInterval(roll_search,10);
}

function input_search()
{
	setTimerInterval('roll_search_timeout',start_roll_search,10000,true);
//	if (timers["roll_search_timeout"] != null) clearTimeout(timers["roll_search_timeout"]);	
//	timers["roll_search_timeout"]=setTimeout(start_roll_search,5000);
	setGlobalParam('roll_search_direction','up');
//	params["roll_search_direction"]='up';
	setTimerInterval('roll_search',roll_search,10,true);
//	if (timers["roll_search"] != null) clearInterval(timers["roll_search"]);
//	timers["roll_search"]=setInterval(roll_search,10);	
}
function roll_search()
{
	var sf_width, sf_obj;
	sf_obj=document.getElementById('search_filed');
	sf_width=sf_obj.style.width;
	sf_width=sf_width.substring(0,sf_width.indexOf('%'));
	if (params["roll_search_direction"] == 'up'){
		sf_width=Number(sf_width)+10;
		document.getElementById('search_lable').innerHTML='Поиск';
		if (sf_width > 80)
		{
			clearTimer('roll_search');
//			if (timers["roll_search"] != null) clearInterval(timers["roll_search"]);
//			timers["roll_search"]=null;
			setGlobalParam('roll_search_direction','down');
//			params["roll_search_direction"]='down';
			setTimerInterval('roll_search_timeout',start_roll_search,5000,true);
//			if (timers["roll_search_timeout"]==null) timers["roll_search_timeout"]=setTimeout(start_roll_search,5000);
			return 0;
			
		}
	}
	else
	{
		sf_width=Number(sf_width)-10;
		if (sf_width < 20)
		{
			clearTimer('roll_search');
//			if (timers["roll_search"] != null) clearInterval(timers["roll_search"]);
//			timers["roll_search"]=null;
			document.getElementById('search_lable').innerHTML='Поиск по каталогу';
			return 0;
		}		
	}
	sf_obj.style.width=sf_width+'%';
	
}

function sart_timer_noopt(f_name)
{
	alert('do');
	timers[f_name]=setInterval(f_name,1000);	
}

function ShowHideSubCategory(element)
{
	var sub_cat_id, sub_cat_obj;;
	if (element.id == null) return 0;
	sub_cat_id=element.id.replace(/_c/,'');
	sub_cat_obj=document.getElementById(sub_cat_id);
	if (sub_cat_obj == null) return 0;
	if (sub_cat_obj.style.display=='none')
	{
		sub_cat_obj.style.display='';
	}else{
		sub_cat_obj.style.display='none';
	}	
}

function presearchOnOver(el)
{
	clearTimer('roll_search_timeout');
	clearTimer('presearch_container_hide');	
}

function presearchOnOut(el)
{
	setTimerInterval('roll_search_timeout',start_roll_search,3000,true);
//	setGlobalParam('presearch_container_make_action','destroy');
//	setTimerInterval('presearch_container_hide',presearchContainer,2000,true);
}

function presearch(el,wheretoplace)
{
	if(el.value.length > 2) 
	{
		setGlobalParam('presearch_container_make_action','make');
		setGlobalParam('presearch_request_string','cgi-bin/catalog_search.pl?act=presearch&search_str='+el.value);
		setGlobalParam('presearch_container_id','presearch_container');
		setTimerTimeout('PRESEARCH_REQ',presearchRequest,1000,true);
		document.getElementById('presearch_loading_img').style.display='';

	}	
}

function presearchRequest()
{
	presearchContainerConstructor();
	
	AJAX_connect(getGlobalParam('presearch_request_string'), getGlobalParam('presearch_container_id'));
	
	if(document.getElementById('presearch_container').innerHTML != '')
	{
		setTimerTimeout('presearch_container_make', presearchContainerShow, 300, true);
		document.getElementById('presearch_loading_img').style.display='none';
	}	
}

function presearchContainerConstructor()
{
	if (params['presearch_container_make_action'] == 'make')
	{
		var coords=getElementPosition('search');
		if (! document.getElementById('conteiner_presearch_container'))
		{
			conteiner_presearch_container=document.createElement('div');
			conteiner_presearch_container.style.display='none';
		}
		else
		{
			conteiner_presearch_container=document.getElementById('conteiner_presearch_container');
		}

		if (! document.getElementById('presearch_container'))
		{
			presearch_container=document.createElement('div');
			presearch_container.style.display='none';
			presearch_container.id='presearch_container';
		}
		else
		{
			presearch_container=document.getElementById('presearch_container');
		}			
			
		//conteiner_presearch_container=document.createElement('div');
		conteiner_presearch_container.id='conteiner_presearch_container';
		conteiner_presearch_container.style.top='0px';
		conteiner_presearch_container.style.left='0px';
		conteiner_presearch_container.style.width='100%';
		conteiner_presearch_container.style.position='fixed';
		conteiner_presearch_container.style.zIndex='100';
		conteiner_presearch_container.style.background='url(img/rt_bg.png)';
		conteiner_presearch_container.style.height='100%';	
		if(window.addEventListener){ // Mozilla, Netscape, Firefox 
			conteiner_presearch_container.addEventListener('click', presearchContainerHide, false); 
		} else { // IE 
			conteiner_presearch_container.attachEvent('onclick', presearchContainerHide); 
		}
		//presearch_container=document.createElement('div');
		
		presearch_container.style.top=coords.top+coords.height+5+'px';
		presearch_container.style.left=coords.left+0+'px';
		presearch_container.style.width=coords.width+'px';
		presearch_container.style.zIndex='101';
		presearch_container.style.position='absolute';
		presearch_container.style.border='2px solid black';
		presearch_container.style.background='#fff';
		presearch_container.style.overflowY='scroll';
		presearch_container.style.height='400px';
		if (! document.getElementById('conteiner_presearch_container'))
		{
			document.body.appendChild(conteiner_presearch_container);
		}

		if (! document.getElementById('presearch_container'))
		{
			document.body.appendChild(presearch_container);
		}
	}
	else
	{
		params['presearch_container_make_action'] = 'make';
		if (document.getElementById('conteiner_presearch_container'))
		{
			document.body.removeChild(document.getElementById('conteiner_presearch_container'));
		}
		if (document.getElementById('presearch_container'))
		{
			document.body.removeChild(document.getElementById('presearch_container'));
		}	
	}
}

function presearchContainerShow()
{
	if (document.getElementById('conteiner_presearch_container'))
	{
		if(document.getElementById('conteiner_presearch_container').style.display=='none');
		{
			document.getElementById('conteiner_presearch_container').style.display='';
		}
	}
	
	if (document.getElementById('presearch_container'))
	{
		if(document.getElementById('presearch_container').style.display=='none');
		{
			document.getElementById('presearch_container').style.display='';
		}
	}	
}

function presearchContainerHide()
{
	if (document.getElementById('conteiner_presearch_container'))
	{
		if(document.getElementById('conteiner_presearch_container').style.display=='');
		{
			document.getElementById('conteiner_presearch_container').style.display='none';
		}
	}
	
	if (document.getElementById('presearch_container'))
	{
		if(document.getElementById('presearch_container').style.display=='');
		{
			document.getElementById('presearch_container').style.display='none';
		}
	}	
}

/*CART*/

function addToCart(el,prefix)
{
	if (Number(el.id.toString()) == 0) { return 0;}
	var fileds_types=['remains_','price_','sum_'];
	var ID=el.id.substr(String(prefix+'input_').length);
	var count = Number(el.value);
	var cookie_order='';
	if (!document.getElementById(prefix+'remains_'+ID))
	{
		return 0;	
	}
	if (!document.getElementById(prefix+'price_'+ID))
	{
		return 0;	
	}	
	var remains=Number(document.getElementById(prefix+'remains_'+ID).innerHTML);
	var price=Number(document.getElementById(prefix+'price_'+ID).innerHTML).toFixed(2);
	if (count > remains) {count=remains;}
	for(place in places_types)
	{
		if (document.getElementById(places_types[place]+'input_'+ID))
		{
			document.getElementById(places_types[place]+'input_'+ID).value=count;
		}
		
		if (document.getElementById(places_types[place]+'sum_'+ID))
		{
			document.getElementById(places_types[place]+'sum_'+ID).innerHTML=Number(count * price).toFixed(2);
		}		
	}
	
	var torit;
	var toritsum=0;
	var toritcount=0;
	CURRENT_ORDER_COUNT[ID]=count;
	CURRENT_ORDER_SUM[ID]=price;
	fillCurrentOrderInfo();
	
	var cookie_order='';
	for(key in CURRENT_ORDER_COUNT)
	{
		cookie_order+=key+'!'+CURRENT_ORDER_COUNT[key]+'@'+CURRENT_ORDER_SUM[key]+'*';	
	}
	
    var expire = new Date ();
    expire.setTime(expire.getTime() + (365 * 24 * 3600 * 1000));
	if (CurrentOrderName=='null'){CurrentOrderName='ORENER_unnamed';}	
	setCookie(''+CurrentOrderName, cookie_order, expire.toGMTString());
	setCookie("CURRENT_ORDER",''+CurrentOrderName);
	//alert(CID);
}

function loadOrder(name)
{
	if (name == null || name == 'NaN' || name == ''){ name='ORDER_unnamed';}
	if(getCookie(name)=='' || getCookie(name)==null || getCookie(name)==undefined){return 0;}
	
	var order_content=unescape(getCookie(name));
	var order_items=order_content.split(/\*/);
	var order_pair;
	//REINITIALIZING TO EXCEPT EMPTY FILEDS
	CURRENT_ORDER_COUNT={};
	CURRENT_ORDER_SUM={};
	for(i in order_items)
	{
		order_pair=order_items[i].split(/!/);
		ID=order_pair[0];
		if (ID == '') {continue;}
		if (order_pair[1] == '') {continue;}
		order_data=String(order_pair[1]).split(/@/);
		CURRENT_ORDER_COUNT[ID]=order_data[0];
		CURRENT_ORDER_SUM[ID]=order_data[1];
	}
	CurrentOrderName=name;
}

function fillCurrentOrderInfo()
{
	var toritsum=0;
	var toritcount=0;
	for(key in CURRENT_ORDER_COUNT)
	{
		toritsum+=Number(CURRENT_ORDER_SUM[key]);
		toritcount+=Number(CURRENT_ORDER_COUNT[key]);
		for(place in places_types)
		{
			if (document.getElementById(places_types[place]+'input_'+key))
			{
				document.getElementById(places_types[place]+'input_'+key).value=Number(CURRENT_ORDER_COUNT[key]);
			}
			
			if (document.getElementById(places_types[place]+'sum_'+key))
			{
				document.getElementById(places_types[place]+'sum_'+key).innerHTML=Number(Number(CURRENT_ORDER_COUNT[key])*Number(CURRENT_ORDER_SUM[key])).toFixed(2);
			}		
		}		
	}
	if (document.getElementById('sum_in_cart'))
	{
		document.getElementById('sum_in_cart').innerHTML=String(Number(Number(toritcount*toritsum).toFixed(2))) + ' руб.';
	}
	if (document.getElementById('count_in_cart'))
	{
		document.getElementById('count_in_cart').innerHTML=String(Number(toritcount))+' шт.';
	}
}

function removeOrder(name)
{
	var expire = new Date ();
    expire.setTime(expire.getTime() - 1);
	if(name == '')
	{
		return 0;	
	}
	else
	{
		setCookie(name,'',expire.toGMTString());
	}
	loadSavedOrders();
}


function fillOrdersFiled()
{
	if (!document.getElementById('container_user_orders')){return 0;}
	document.getElementById('container_user_orders').innerHTML='У <strong>Вас</strong> нет <br /><em>сохраненных</em> заказов';
	var olist='';
	for (key in ORDERS)
	{
		if (key == null || key == 'null' || key == 'undefined' || key==''){continue;} 
		oc=''+ORDERS[key];
		oc=unescape(oc);
		if(oc == 'null'){continue;}
		var order_items;
		order_items=oc.split(/\*/);
		var order_pair;
		
		var c_sum=0, c_count=0;
		
		for(i in order_items)
		{
			order_pair=order_items[i].split(/!/);
			ID=order_pair[0];
			if (ID == '') {continue;}
			if(order_pair[1] == ''){continue;}
			order_data=order_pair[1].split(/@/);
			c_count+=Number(order_data[0]);
			c_sum+=Number(order_data[1])*Number(order_data[0]);
			
		}
		c_sum=c_sum.toFixed(2);
		olist=''+olist+'<div style="white-space:nowrap; font-size:12px;" onmouseover="this.style.background=\'orange\'" onmouseout="this.style.background=\'\'" onclick="ShowHide(\'container_order_'+key.replace(/ORDER_/,'')+'_controls\')" align="justify"><b>'+key.replace(/ORDER_/,'')+'</b> ' + c_sum + ' руб.</div><div id="container_order_'+key.replace(/ORDER_/,'')+'_controls" style="display:none; width:90%; border:1px solid gray;" align="left"><b onmouseover="this.style.color=\'orange\'" onmouseout="this.style.color=\'black\'" onclick="AJAX_connect(\'cgi-bin/orders.pl?act=show_order&order_content='+oc+'\',\'container_center_of_page\');"> смотреть </b><b onmouseover="this.style.color=\'orange\'" onmouseout="this.style.color=\'black\'" onclick="removeOrder(\''+key+'\');"> удалить </b><b onmouseover="this.style.color=\'orange\'" onmouseout="this.style.color=\'black\'" onclick="AJAX_connect(\'cgi-bin/orders.pl?act=do_order&order_data='+oc+'&order_id='+key.replace(/ORDER_/,'')+'\',\'container_order_'+key.replace(/ORDER_/,'')+'_status\'); AJAX_connect(\'cgi-bin/orders.pl?act=list_orders&order_id='+key.replace(/ORDER_/,'')+'\',\'container_order_'+key.replace(/ORDER_/,'')+')orders_list\');" id=\'container_order_'+key.replace(/ORDER_/,'')+'_status\'> заказать </b><div id=\'container_order_'+key.replace(/ORDER_/,'')+')orders_list\'><img src="img/loading.gif" width="60" height="60" onload="AJAX_connect(\'cgi-bin/orders.pl?act=list_orders&order_id='+key.replace(/ORDER_/,'')+'\',\'container_order_'+key.replace(/ORDER_/,'')+')orders_list\');" /></div></div>';
	}
	if(olist.length>0)
	{
		document.getElementById('container_user_orders').innerHTML=olist;
	}
}
/* INITIALIZE ALL GLOBAL PARAMS & ETC*/
function initAll()
{
	timers=[];
	params=[];
	places_types=['to_cart_on_center_', 'to_cart_on_new_stuff_', 'to_cart_on_presearch_'];
	CURRENT_ORDER_COUNT={};
	CURRENT_ORDER_SUM={};
	CurrentOrderName='CURRENT_ORDER_CONTENT';
	ORDERS={};
	
	if (!getCookie('CURRENT_ORDER'))
	{
		setCookie('CURRENT_ORDER',CurrentOrderName);
	}
	
	CurrentOrderName=getCookie('CURRENT_ORDER');
	loadSavedOrders();
	loadOrder(CurrentOrderName);
	fillOrdersFiled();
	fillCurrentOrderInfo();
	
	var now=new Date();
	if(! document.getElementById('order_save_name_input')){return 0;}
	document.getElementById('order_save_name_input').value='заказ';
}

function loadSavedOrders()
{
	try{
	var allcook='';//String(document.cookie);
	allcook=" "+unescape(String(document.cookie))+';';
	if(document.cookie == '' || document.cookie==null || document.cookie == 'null'){return 0;}
	
	allcook=allcook.split(";");
	ORDERS={};
	for(i in allcook)
	{
		//alert(allcook[i]);
		var cstr=String(allcook[i]);
		if (cstr.substr(0,6)=='ORDER_' || cstr.substr(1,6)=='ORDER_')
		{
			var c_ord=cstr.split(/=/);
			if(c_ord[0] && c_ord[1])
			{
				ORDERS[c_ord[0]]=c_ord[1];
			}
		}
	}
		}
	catch(e)
	{	
	}
}


function saveOrder()
{
	try{
	var now=new Date();
	if(! document.getElementById('order_save_name_input')){return 0;}
	var SaveName=document.getElementById('order_save_name_input').value;
	if (!SaveName) {document.getElementById('order_save_name_input').style.background='red'; return 0;}
	SaveName='ORDER_'+SaveName;
	document.getElementById('order_save_name_input').style.background='';
	ORDERS[''+SaveName]=getCookie(CurrentOrderName);
	now.setTime(now.getTime() + (365 * 24 * 3600 * 1000));
	setCookie(SaveName,getCookie(CurrentOrderName),now.toGMTString());
	CurrentOrderName='ORDER_neworder';
	setCookie('CURRENT_ORDER',CurrentOrderName, now.toGMTString());
	
	removeOrder(CurrentOrderName);
	fillOrdersFiled();
	for(key in CURRENT_ORDER_COUNT)
	{
		CURRENT_ORDER_COUNT[key]=0;
		CURRENT_ORDER_SUM[key]=0;	
	}
	fillOrdersFiled();
	fillCurrentOrderInfo();
	ShowHide('container_order_save_name');
	}
	catch(e)
	{	
	}
}

function editUserSettings()
{
	
}

