﻿var Rpc = null, H = null, T = null, F = null, wath = null;
var pageSize = 15, curPage = 0, totRecords = 0, totPages = 0;
var fromRecord = 0, toRecord = 0;
var prodsList = new Array();
var btSearch;
var ListLimitStep = 40;
var urlWath = null;

function initSearch() {
	Rpc = new ProductSearchRpc();
	H = $('tblResultsTH');
	T = $('tblResultsTB');
	F = $('tblResultsTF');
	new Tip('filtersCnt', searchTexts.textGroupInfo, {
		title: searchTexts.textGroupTitle,
		stem: 'bottomMiddle',
		hook: { target: 'topMiddle', tip: 'bottomMiddle' },
		offset: { x: 210, y: -3 },
		width: 150,
		style: 'protogrey'
	});
	$('filtersCnt').observe('prototip:shown', function() {
		setTipOpacity('protogrey', 0.9);
	});
	$('wath').focus();
	$(btSearch).disabled = false;
	if(urlWath != null) {
		$('wath').value = decodeURIComponent(urlWath);
		search();
	}
}

function search() {
	if($F('wath') == wath) return;
	wath = $F('wath');
	wath = $('wath').value = trim(wath).toString().toLowerCase();
	if(wath.length == 0) return;
	if(wath.length < 3) { alert(searchTexts.tooShort); return; }

	prodsList = new Array();
	Element.hide('tblNoResults');
	_showLoader();
	LoadResults();
}
function cloudSearch(wath) {
	$('wath').value = wath;
	search();
}
var basePL = new Array();
var isFiltered = false;
var isFirstAF = false;
var isGroupedBy = false;
function applyFilters(force) {
	var cat = parseInt($F('sCat'));
	checkPrices();
	var pfrom = CurrencyFormatted($F('sPFrom'));
	var pto = CurrencyFormatted($F('sPTo'));
	var i,c,fprodsList=new Array();
	
	if(!isFirstAF || force) {
		isFirstAF = true;
		basePL = prodsList;
	}
	var isOk = false;
	for(i=0; i<basePL.length; i++) {
		isOk = false;
		if(cat > 0) {
			for(c=0; c<basePL[i].cats.length; c++) {
				if(basePL[i].cats[c].c0 == cat) {
					isOk = true;
					break;
				}
			}
		}
		else
			isOk = true;
		if(pfrom > 0) {
			if(basePL[i].price >= pfrom)
				isOk = (isOk ? true : false);
			else
				isOk = false;
		}
		else
			isOk = (isOk ? true : false);
		if(pto > 0) {
			if(basePL[i].price <= pto)
				isOk = (isOk ? true : false);
			else
				isOk = false;
		}
		else
			isOk = (isOk ? true : false);
		if(isOk)
			fprodsList.push(basePL[i]);
	}
	if(isGroupedBy) {
		fprodsList = groupBySameName(fprodsList);
	}
	else {
		for(i=0; i<fprodsList.length; i++)
			fprodsList[i].SubPS = null;
	}
	prodsList = fprodsList;
	handleSearch();
}
function applyFilterGB() {
	isGroupedBy = isGroupedBy ? false : true;
	$('sGroup').src = 'img/checkbox' + (isGroupedBy ? '_on' : '') + '.gif';
	applyFilters();
}
function removeFilters() {
	$('sCat').selectedIndex = 0;
	$('sPFrom').value = "";
	$('sPTo').value = "";
	applyFilters();
}
function GroupedProds() {
	this.List = [];
	this.IsInList = function(name) {
		for(var i=0; i<this.List.length; i++)
			if(this.List[i].Name == name)
				return i;
		return -1;
	};
	this.IsInSubPS = function(idx, id) {
		for(var i=0; i<this.List[idx].SubPS.length; i++)
			if(this.List[idx].SubPS[i].Prod.id == id)
				return i;
		return -1;
	};
	this.IsInFromProdList = function(id) {
		for(var i=0; i<this.List.length; i++) {
			for(var ii=0; ii<this.List[i].SubPS.length; ii++) {
				if(this.List[i].SubPS[ii].Prod.id == id)
					return true;
			}
		}
		return false;
	};
	this.Append = function(Obj) {
		for(var i=0; i<this.List.length; i++) {
			Obj.push(this.List[i].Prod);
			Obj[Obj.length-1].Name = this.List[i].Name;
			Obj[Obj.length-1].SubPS = this.List[i].SubPS;
		}
		return Obj;
	}
}
function GroupedProd(name, prod) {
	this.Name = name;
	this.Prod = prod;
	this.SubPS = [];
}
function groupBySameName(PL) {
	var i, ii, idx, np, n;
	var resultProdList = new Array();
	var GPS = new GroupedProds();

	for(i=0; i<PL.length; i++) {
		if(PL[i].name.indexOf('(') > 0) {
			np = PL[i].name.split('(');
			n = trim(np[0]);
			if((idx=GPS.IsInList(n)) < 0) {
				GPS.List.push(new GroupedProd(n, PL[i]));
				GPS.List[GPS.List.length-1].SubPS.push(new GroupedProd(n, PL[i]))
			}
			else {
				if(GPS.IsInSubPS(idx, PL[i].id) < 0)
					GPS.List[idx].SubPS.push(new GroupedProd(n, PL[i]));
			}
		}
	}
	resultProdList = GPS.Append(resultProdList);
	for(i=0; i<PL.length; i++) {
		if(!GPS.IsInFromProdList(PL[i].id))
			resultProdList.push(PL[i]);
	}
	return resultProdList;
}
function LoadResults(log, from) {
	if(navigator.userAgent.toLowerCase().indexOf("applewebkit")>0)
	{
		try
		{
			Rpc.Search_Public_Limit(wath, (log ? true : false), (from ? from : 0), ListLimitStep, handleSearchLimitCB);
		}
		catch(e) { alert(e.message); }	
	}
	else
	{
		try
		{
			Rpc.Search_Public(wath, true, handleSearchCB);
			return;
		}
		catch(e) { alert(e.message); }	
	}
}
function handleSearchCB(response) {
	if(response.result && response.result.length)
		prodsList = response.result;
	if(isFiltered) applyFilters(true);
	else handleSearch();
}
function handleSearchLimitCB(response) {
	if(response.result && response.result.length) {
		for(var k=0;k<response.result.length;k++)
			prodsList[prodsList.length]=response.result[k];
	}
	else {
		if(isFiltered) applyFilters(true);
		else handleSearch();
		return;
	}
	LoadResults(false, (prodsList.length + 1));
}
function handleSearch() {
	if(prodsList.length > 0) {
		Element.hide('tagCloudCnt');
		Element.hide('tblNoResults');

		totRecords = prodsList.length;
		curPage = 1;

		if(totRecords > pageSize) {
			if((totRecords % pageSize) == 0)
				totPages = parseInt(totRecords / pageSize);
			else {
				totPages = parseInt(totRecords / pageSize);
				totPages = totPages + 1;
			}
			fromRecord = 0;
			toRecord = pageSize;
		}
		else {
			totPages = 1;
			fromRecord = 0;
			toRecord = totRecords;
		}
		_writePage();
	}
	else {
		_hideLoader();
		Element.show('tagCloudCnt');
		Element.show('tblNoResults');
		Element.hide('tblResults');
	}
}
function _clearPage() {
	var n=T.rows.length;
	while(n>0) T.deleteRow(--n);
	n=H.rows.length;
	while(n>0) H.deleteRow(--n);
	n=F.rows.length;
	while(n>0) F.deleteRow(--n);
}
function _goToPage(page) {
	curPage = page;
	fromRecord = parseInt((curPage * pageSize) - pageSize);
	toRecord = parseInt(fromRecord + pageSize);
	if(toRecord > totRecords)
		toRecord = totRecords;

	_writePage();
}
function _writePage() {
	_showLoader();
	_clearPage();
	var R, Th, Td, A, I, TipImg=null;

	_writePager(1);

	R = document.createElement('tr');
	Td = document.createElement('td');
	Td.colSpan = 2;
	Td.className = 'space';
	R.appendChild(Td)
	H.appendChild(R);

	for(var i=fromRecord; i<toRecord; i++) {
		R = document.createElement('tr');
		Td = document.createElement('td');
		Td.className = 'img';
		Td.style.width = (thumbDimensions.Width + 2) + 'px';
		Td.style.height = (thumbDimensions.Height + 2) + 'px';
		Td.rowSpan = 2;
		I = document.createElement('img');
		if(prodsList[i].firstpicture.length > 0) {
			I.src = prodsList[i].firstpicture;
			if(!Object.isUndefined(prodsList[i].firstpictureW))
				I.style.width = prodsList[i].firstpictureW + 'px';
			if(!Object.isUndefined(prodsList[i].firstpictureH))
			I.style.height = prodsList[i].firstpictureH + 'px';
			Td.appendChild(I);
			I=document.createElement('img');
			I.src=prodsList[i].firstpicture.replace("tiny","");
			I.style.display="none";
			I.className = "imgForTip";
			TipImg="tip_img_"+prodsList[i].code;
			Td.appendChild(I);
			Td.id=TipImg;
		}
		else {
			TipImg=null;
			I.src = "img/no_picture.gif";
			Td.appendChild(I);
		}
		Td.appendChild(I);
		R.appendChild(Td)
		T.appendChild(R);

		Th = document.createElement('th');

		if(!Object.isUndefined(prodsList[i].SubPS) && prodsList[i].SubPS != null) {
			Th.innerHTML = prodsList[i].Name;
			R.appendChild(Th)
			T.appendChild(R);

			R = document.createElement('tr');
			Td = document.createElement('td');

			for(var sp=0; sp<prodsList[i].SubPS.length; sp++) {
				var subprodname = document.createElement('span');
				subprodname.style.fontWeight = 'bold';
				var nf = prodsList[i].SubPS[sp].Prod.name.split('(');
				subprodname.innerHTML = ' - ' + nf[1].replace(')', '') + ' (' + searchTexts.textCode + ' ' + prodsList[i].SubPS[sp].Prod.code + ')';

				var catslinks = document.createElement('span');
				for(var c=0; c<prodsList[i].SubPS[sp].Prod.cats.length; c++) {
					if(catslinks.childNodes.length > 0) catslinks.appendChild(document.createTextNode(', '));

					A = document.createElement('a');
					A.innerHTML = prodsList[i].SubPS[sp].Prod.cats[c].name;
					A.href = '/' + curLang + '/' + prodsList[i].SubPS[sp].Prod.cats[c].c0 + '/' + prodsList[i].SubPS[sp].Prod.cats[c].c1 + '/' + prodsList[i].SubPS[sp].Prod.cats[c].c2 + '/' + prodsList[i].SubPS[sp].Prod.nameforlink + '/' + prodsList[i].SubPS[sp].Prod.id;
					A.setAttribute('title', prodsList[i].SubPS[sp].Prod.cats[c].allnames);
					A.style.whiteSpace='nowrap';

					catslinks.appendChild(A);
				}

				Td.appendChild(subprodname);
				Td.appendChild(document.createElement('br'));
				Td.appendChild(document.createTextNode(searchTexts.textPrice + ' '));
				var sprice = document.createElement('span');
				sprice.className = 'price';
				sprice.innerHTML = toMoney(prodsList[i].SubPS[sp].Prod.price) + ' ' + money;
				if(!showVat)
					sprice.innerHTML += ' +' + searchTexts.textPriceVat;
				Td.appendChild(sprice);
				Td.appendChild(document.createElement('br'));
				Td.appendChild(document.createTextNode(searchTexts.presentIn + ' '));
				Td.appendChild(catslinks);
				Td.appendChild(document.createElement('br'));
				if(sp<(prodsList[i].SubPS.length-1))
					Td.appendChild(document.createElement('br'));
			}
			R.appendChild(Td);
			T.appendChild(R);
		}
		else {
			Th.innerHTML = prodsList[i].name + ' (' + searchTexts.textCode + ' ' + prodsList[i].code + ')';
			R.appendChild(Th)
			T.appendChild(R);

			var catslinks = document.createElement('span');
			for(var c=0; c<prodsList[i].cats.length; c++) {
				if(catslinks.childNodes.length > 0) catslinks.appendChild(document.createTextNode(', '));

				A = document.createElement('a');
				A.innerHTML = prodsList[i].cats[c].name;
				A.href = '/' + curLang + '/' + prodsList[i].cats[c].c0 + '/' + prodsList[i].cats[c].c1 + '/' + prodsList[i].cats[c].c2 + '/' + prodsList[i].nameforlink + '/' + prodsList[i].id;
				A.setAttribute('title', prodsList[i].cats[c].allnames);
				A.style.whiteSpace='nowrap';

				catslinks.appendChild(A);
			}

			R = document.createElement('tr');
			Td = document.createElement('td');
			Td.appendChild(document.createTextNode(searchTexts.textPrice + ' '));
			var sprice = document.createElement('span');
			sprice.className = 'price';
			sprice.innerHTML = toMoney(prodsList[i].price) + ' ' + money;
			if(!showVat)
				sprice.innerHTML += ' +' + searchTexts.textPriceVat;
			if(prodsList[i].pricediscounted != null)
			{
				sprice.innerHTML += '<span class="prodPriceDiscount">' + toMoney(prodsList[i].pricediscounted) + ' ' + money;
				if(!showVat)
					sprice.innerHTML += ' +' + searchTexts.textPriceVat;
				sprice.innerHTML += '</span>';
			}
			Td.appendChild(sprice);
			Td.appendChild(document.createElement('br'));
			Td.appendChild(document.createTextNode(searchTexts.presentIn + ' '));
			Td.appendChild(catslinks);
			Td.appendChild(document.createElement('br'));
			Td.appendChild(document.createElement('br'));
			R.appendChild(Td);
			T.appendChild(R);
		}

		R = document.createElement('tr');
		Td = document.createElement('td');
		Td.colSpan = 2;
		Td.className = 'space';
		R.appendChild(Td)
		T.appendChild(R);

		if(TipImg!=null)
			new Tip(TipImg, $(TipImg).down('img.imgForTip').cloneNode(true), { width: 'auto', border: 1, radius: 1, hook: { target: 'topRight', tip: 'leftMiddle' }, offset: { x: 5, y: 0 } });
	}
	_writePager(2);
	_hideLoader();
}
function _writePager(where) {
	var R, Th, D;

	R = document.createElement('tr');
	Th = document.createElement('th');
	Th.style.backgroundColor = '#f3f3f3';
	Th.colSpan = 2;
	Th.appendChild(D=document.createElement('div'));
	D.className = 'thPL';
	D.appendChild(document.createTextNode(searchTexts.textTotPages.replace('{0}', totRecords).replace('{1}', curPage).replace('{2}', totPages)));
	Th.appendChild(D=document.createElement('div'));
	D.className = 'thPR';
	D.appendChild(document.createTextNode(searchTexts.textCurPage.replace('{0}', (fromRecord + 1)).replace('{1}', toRecord)));
	Th.appendChild(document.createElement('br'));
	if(totPages > 1) {
		Th.appendChild(document.createTextNode(searchTexts.textPages + ' '));
		for(var p=0; p<totPages; p++) {
			var pagina = p + 1;
			A = document.createElement('a');
			A.appendChild(document.createTextNode((pagina)));
			A.Page = pagina
			if(pagina != curPage) {
				A.href = '#cercaTop';
				A.onclick = function() { _goToPage(this.Page); }
			}
			Th.appendChild(A);
			Th.appendChild(document.createTextNode(' '));
		}
	}
	R.appendChild(Th);
	if(where == 1)
		H.appendChild(R);
	else
		F.appendChild(R);
}
function showFilters() {
	if(prodsList.length == 0) return;
	Element.show('filtersCnt');
	Element.hide('aFShow');
	Element.show('aFHide');
	isFiltered = true;
}
function hideFilters() {
	Element.hide('filtersCnt');
	Element.show('aFShow');
	Element.hide('aFHide');
	isFiltered = false;
	removeFilters();
}
function checkStartSearch(e) {
	var key = e.which || e.keyCode;
	if(key == Event.KEY_RETURN && $(btSearch).disabled == false) {
		Event.stop(e);
		window.setTimeout('search()', 10);
		return false;
	}
}
function _showLoader() {
	Element.hide('tblResults');
	Element.show('tblLoader');
}
function _hideLoader() {
	Element.hide('tblLoader');
	Element.show('tblResults');
}
function checkPrices() {
	var value1 = $F('sPFrom');
	var value2 = $F('sPTo');
	var reg = /^\-?([1-9]\d*|0)(\.\d?[1-9])?$/;
	if(!reg.test(value1))
		$('sPFrom').value = '';
	if(!reg.test(value2))
		$('sPTo').value = '';
}
function CurrencyFormatted(amount)
{
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return s;
}
