var currentCategory=0;
var baseCategory=0;
var currentProduct=0;

var viewStart=0;
var viewOffset=0;

window.onload=function() {init();}
function init()
{
	if (window.location.hash!='')
	{		
		var hash = window.location.hash.split('/');
		
		if (hash[2]!=undefined && hash[2]!=0)
		{
			loadProducts(hash[2], hash[4], hash[5]);
			cmd("expandProduct");
		}
		
		if (hash[3]!=undefined)
		{
			if (hash[3]==0) 
				closeDetails();
			else
				showDetails(hash[3]);
		}		
	}
}

function $(element) 
{
	return document.getElementById(element);
}

function loadAjax()
{
var xmlHttp=null;
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
return xmlHttp;
}

function expandMenu(cat_id, start, offset, noProd)
{
	//hideDlg('details');
	menu = $("subcat_"+cat_id);
	if (menu==undefined) return;
	expSign = $("expand_sign_"+cat_id);
	if (menu.style.visibility=='visible' && noProd==undefined)
	{
		menu.style.position='absolute';
		menu.style.visibility='hidden';
		menu.style.display='none';
		if (expSign!=undefined)expSign.innerHTML='+';
	}
	else
	{
		if (getChildren(cat_id))
		{
			menu.style.visibility='visible';
			menu.style.position='static';
			menu.style.display='block';
			if (expSign!=undefined)expSign.innerHTML='- ';
		}
	}
	
	if (noProd==undefined)
	loadProducts(cat_id, start, offset);
}

function getChildren(cat_id)
{
	menu = $("subcat_"+cat_id);
	if (!menu)return;
	if (menu.innerHTML.length>0) return true;
	children = loadAjax();
	url = '/main/catchildren/'+cat_id.toString();
	children.open("GET", url, false);
	children.send(null);
	if (children.responseText!='')
	{
		menu.innerHTML=children.responseText;
		return true;
	}
	else return false;
}

function loadProducts(cat_id, start, offset, search)
{
	loadProd=loadAjax();
	url='/main/ajaxproducts/'+cat_id.toString();
	if (start!=undefined) 
	{
		url+='/'+start.toString();
		viewStart = start;
	} else viewStart=0;
	if (offset!=undefined)
	{
		url+='/'+offset.toString();
		viewOffset = offset;
	} else viewOffset=0;
	params = 'baseCat='+baseCategory.toString();
	if (search!=undefined) params+='&search='+encodeURIComponent(search); else 
		{
			$("pSearch").value='Търсене...';
		}
	loadProd.open("POST",url,false);
	loadProd.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
	loadProd.setRequestHeader("Content-length", params.length);
	loadProd.setRequestHeader("Connection", "close");	
	loadProd.send(params);	
	
	if (loadProd.readyState==4)
	{ 
		var p = document.getElementById('products');
		if (loadProd.responseText.length>0)
			p.innerHTML = loadProd.responseText;
	}
	
	currentCategory = cat_id;
	updateHash();
	setTitle($('catTitle').innerHTML);
}

function centerElement(element)
{
	if (self.innerHeight) // all except Explorer
	{
		x = self.innerWidth;
		y = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientHeight)
		// Explorer 6 Strict Mode
	{
		x = document.documentElement.clientWidth;
		y = document.documentElement.clientHeight;
	}
	else if (document.body) // other Explorers
	{
		x = document.body.clientWidth;
		y = document.body.clientHeight;
	}
	
	var left = (x - element.offsetWidth)/2 + document.documentElement.scrollLeft-25;
	var top = (y - element.offsetHeight)/2 + document.documentElement.scrollTop;
	
	element.style.left = left + 'px';
	element.style.top = top + 'px';
}

function showDetails(product_id)
{
	getProductAjax=loadAjax();
	url='/main/ajaxproduct/'+product_id.toString();
	getProductAjax.open("GET",url,false);
	getProductAjax.send(null);
	
	var d = document.getElementById('details');	
	d.innerHTML = getProductAjax.responseText;
	if (d.style.left!='') dontcenter=1; else dontcenter=undefined; 
	showDlg('details',dontcenter);
	movable('details', 'dtMove');
	setTitle($('dtMove').innerHTML);
	currentProduct=product_id;
	updateHash();
	scrollIt();
}

var nextScroll=2;
function scrollIt()
{
	if ($("imageContainer").offsetWidth+100 > $("productImage").offsetWidth) return;
	c = $("imageContainer").scrollLeft;
	$("imageContainer").scrollLeft+=nextScroll;
	if (c == $("imageContainer").scrollLeft) nextScroll=nextScroll*-1;
	if ($("details").style.visibility=='visible')
		window.setTimeout('scrollIt()', 48);
	else
		$("imageContainer").scrollLeft=0;
}

function hideDlg(dlg)
{
	d = document.getElementById(dlg); 
	d.style.visibility='hidden';
	d.style.display='none';
}

function closeDetails()
{
	hideDlg('details');
	currentProduct=0;
	updateHash();
	setTitle($('catTitle').innerHTML);
}

function showDlg(dlg, dontcenter)
{
	d = document.getElementById(dlg);
	d.style.display='block';
	if (dontcenter==undefined) centerElement(d);
	d.style.visibility='visible';
}

function updateHash()
{
	window.location.hash='/'+
		baseCategory.toString()+'/'+
		currentCategory.toString()+'/'+
		currentProduct.toString()+'/'+
		viewStart.toString()+'/'+
		viewOffset.toString();
}

function calculatePrice(p)
{
	var quantity = document.getElementById('productQuantity');
	var price = document.getElementById('productPrice');
	if (!isNaN(quantity.value)) price.value=Math.round(p*quantity.value*100)/100;
}

function addToCart(product_id)
{
	quantity = document.getElementById('productQuantity').value;
	toCart=loadAjax();
	url='/main/addtocart/'+product_id+'/'+quantity;
	toCart.open("GET",url,false);
	toCart.send(null);
	
	eval(toCart.responseText);
}

function viewCart()
{
	cart=loadAjax();
	url='/main/viewcart/';
	cart.open("GET",url,false);
	cart.send(null);

	var text = cart.responseText;
	
	if (text=='1')
	{
		displayMessage('Кошницата е празна.');
	}
	else
	{	
		var d = document.getElementById('cartDlg');	
		d.innerHTML = text;
		if ($('details').style.left!='')
		{
			d.style.left=$('details').style.left;
			d.style.top = $('details').style.top;
			showDlg('cartDlg', 1);
		}else
		showDlg('cartDlg');
		closeDetails();
		
		movable('cartDlg', 'ctMove')
	}
}

function removeFromCart(product_id)
{
	hideDlg('cartDlg');
	delCart = loadAjax();
	url='/main/delcart/'+product_id;
	delCart.open("GET",url,false);
	delCart.send(null);
	eval(delCart.responseText);
}

function displayMessage(message)
{
	d = document.getElementById('msg');
	d.innerHTML = message;
	showDlg('msgDlg');
}

function setView(v)
{
	setV = loadAjax();
	url='/main/setview/'+v;
	setV.open("GET",url,false);
	setV.send(null);
	
	searchFocus();
	if (currentCategory!=0)
	loadProducts(currentCategory,viewStart,viewOffset,$("pSearch").value);
	searchBlur();
}

function auth()
{
	order=loadAjax();
	url='/main/auth';
	order.open("GET",url,false);
	order.send(null);

	var d = document.getElementById('cartDlg');	
	d.innerHTML = order.responseText;
	showDlg('cartDlg',1);
	hideDlg('details');
	if ($("register")!=undefined && $("register").mail.value!='') $("register").register["1"].click();
}

function orderData()
{
	order=loadAjax();
	url='/main/orderdata';
	order.open("GET",url,false);
	order.send(null);

	var d = document.getElementById('cartDlg');	
	d.innerHTML = order.responseText;
	showDlg('cartDlg',1);
	hideDlg('details');
}

var wRegister=undefined;

function willRegister()
{
	$("mailDiv").style.display="block";
	$("passDiv").style.display="block";
	$("passConfirmDiv").style.display="block";
	wRegister = 1;
}
function willNotRegister()
{
	$("mailDiv").style.display="block";
	$("passDiv").style.display="none";
	$("passConfirmDiv").style.display="none";
	wRegister = 0;
}

function defineUser()
{
	url='/main/defineuser';
	params=
		'realMail='+encodeURIComponent($("login").realMail.value)+
		'&realPass='+encodeURIComponent($("login").realPass.value)+		
		'&mail='+encodeURIComponent($("register").mail.value)+
		'&pass='+encodeURIComponent($("register").pass.value)+
		'&passConfirm='+encodeURIComponent($("register").passConfirm.value);
	if (wRegister!=undefined)
		params+='&register='+wRegister;
	defUser=loadAjax();
	defUser.open("POST",url,false);
	defUser.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
	defUser.setRequestHeader("Content-length", params.length);
	defUser.setRequestHeader("Connection", "close");	
	defUser.send(params);
	
	eval(defUser.responseText);
}

function orderDataConfirm()
{
	url='/main/orderdataconfirm';
	params=
		'name='+encodeURIComponent($("orderData").name.value)+
		'&address='+encodeURIComponent($("orderData").address.value)+
		'&phone='+encodeURIComponent($("orderData").phone.value)+
		'&company='+encodeURIComponent($("orderData").company.value)+
		'&companyAddress='+encodeURIComponent($("orderData").companyAddress.value)+
		'&VAT='+encodeURIComponent($("orderData").VAT.value)+
		'&mol='+encodeURIComponent($("orderData").mol.value)+
		'&comments='+encodeURIComponent($("orderData").comments.value);
	order=loadAjax();
	order.open("POST",url,false);
	order.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
	order.setRequestHeader("Content-length", params.length);
	order.setRequestHeader("Connection", "close");	
	order.send(params);	
	
	eval(order.responseText);
}

function confirmDialog()
{
	order=loadAjax();
	url='/main/confirmorder';
	order.open("GET",url,false);
	order.send(null);

	eval(order.responseText);
}

function cartChange(count, value)
{
	$("cartCount").innerHTML = count;
	$("cartValue").innerHTML = value;
}

function logoutIcon(icon)
{
	$("logout").innerHTML = icon;
}

function searchFocus()
{
	if($("pSearch").value=='Търсене...') $("pSearch").value='';
}

function searchBlur()
{
	if($("pSearch").value=='') $("pSearch").value='Търсене...';
}

var pTimeOutId=0
function searchKeyUp()
{
	if (pTimeOutId!=0) 
	{
		window.clearTimeout(pTimeOutId);		
	}
	//if($("pSearch").value!='')
	pTimeOutId = window.setTimeout("loadProducts(currentCategory, 0, 0, $('pSearch').value)", 500);
}

function imageEnlarge()
{
	$("bigImage").src = $("productImage").src;
	showDlg("bigImage");
}

function cmd(container)
{
	eval($(container).innerHTML);
}

function movable(object, caller)
{
	$(caller).onmousedown = function (e) {startMove(object, e);}
	$(caller).onmouseup = function () {stopMove();}
}

function startMove(object, e)
{
	if (e==undefined)
	{
		ox = window.event.clientX + document.body.scrollLeft - document.body.clientLeft - $(object).offsetLeft;
		oy = window.event.clientY + document.body.scrollTop  - document.body.clientTop - $(object).offsetTop;
	}else
	{
		ox = e.pageX - $(object).offsetLeft;
		oy = e.pageY - $(object).offsetTop;
	}
	
	document.onmousemove = function (ev)
	{
		if (ev==undefined)
		{
			$(object).style.left=(window.event.clientX + document.body.scrollLeft - document.body.clientLeft-ox)+'px';
			$(object).style.top=(window.event.clientY + document.body.scrollTop  - document.body.clientTop-oy)+'px';
		}else
		{
			$(object).style.left=(ev.pageX-ox)+'px';
			$(object).style.top=(ev.pageY-oy)+'px';
		}
	}
	document.onmouseup = function() {stopMove();}
}

function stopMove()
{
	document.onmousemove=null;
	document.onmouseup=null
}

function setTitle(v)
{
	if (v!=undefined)
	document.title = v.replace('&amp;', '&')+' :: Titan Trade Ltd';
	else document.title = 'Titan Trade Ltd'; 
}
