/*
Van Doorn AJAX powered search -- (c) Netbytes 2005
*/
/*
var VarBin.currentCategory=null;
var VarBin.currentType=null;
var VarBin.currentKeywords="";
var VarBin.curCatLink, VarBin.curTypeLink;
var VarBin.resultSet; //most recent search result set
var t = null;
*/
function VarBin()
{}

VarBin.currentCategory=null;
VarBin.currentType=null;
VarBin.currentKeywords="";
VarBin.curCatLink;
VarBin.curTypeLink;
VarBin.resultSet; //most recent search result set
var t = null;

//var searchTypeContent;

// ERROR HANDLER
var reportError = function(t) {
    alert('Error ' + t.status + ' -- ' + t.statusText);
}

// RESUME SEARCH
function resumeSearch()
{
	var u=false;

	if(keywords!="") {
		$('keywrds').value=keywords;	
		VarBin.currentKeywords=$('keywrds').value;	
		u=true;	
	}
	
	if(catid!=null) {
		if(soortid!=null) {
			VarBin.currentType=soortid;			
			fetchTypes(catid, 0);
		}
		else {
			fetchTypes(catid);
		}
		
		u=false;
	}
	
	if(catid==null && soortid!=null)
	{
	    VarBin.currentType=soortid;
	    fetchTypes();
	    u=false;
	}
		
	
	if(u==true) { updateSearch(); }	
}

// CONTAINER HANDLING

function containerHover() {
	$('container-hover').style.backgroundImage="url('"+base_uri+"/img/container-bar-bg-over.gif')";
}

function containerOut() {
	$('container-hover').style.backgroundImage="url('"+base_uri+"/img/container-bar-bg.gif')";
}

function containerDrop(drag, drop) {
	s = new String(drag.id);
	s=parseInt(s.replace(/sr-prod-/g,""));
	
	var prod=VarBin.resultSet[s];
	addToContainer(prod.getElementsByTagName("id")[0].firstChild.nodeValue, 1, 1, '');

	containerOut();
}

function addToContainer(product, quantity, type, comments)
{
	var t;
	t= (type==1) ? "bestelling" : "offerte";


	var url = base_uri+'/en/containeradd/';
	var pars = 'pid='+product+'&quantity='+quantity+'&ordertype='+t+'&comments='+comments;

	var myAjax = new Ajax.Request(
				url, 
				{method: 'post', parameters: pars, onComplete: updateContainerContentsHelper, onFailure: reportError, asynchronous: false}
	);
	
	updateContainerContents();
}

function updateContainerContents()
{
	var url = base_uri+'/en/containercount';
	var pars = '';

	var myAjax = new Ajax.Request(
				url, 
				{method: 'get', parameters: pars, onComplete: updateContainerContentsHelper, onFailure: reportError}
	);
}

function updateContainerContentsHelper(request)
{
	//switch backgrounds if the container was previously empty
	if(parseInt($('numitems').innerHTML)==0) {
		Element.hide('my-container-empty');
		Element.show('my-container-full');
	}

	$('numitems').innerHTML=request.responseXML.getElementsByTagName("count")[0].firstChild.nodeValue;
}


// SPINNERS
function startCatSpinner() {
	$('spinner-cat').className="list-sub-loading";
}

function stopCatSpinner() {
	$('spinner-cat').className="list-sub-waiting";
}
function startTypeSpinner() {
	$('spinner-type').className="list-sub-loading";
}

function stopTypeSpinner() {
	$('spinner-type').className="list-sub-waiting";
}

function startResultSpinner() {
	$('spinner-keywords').className="list-sub-loading";
}

function stopResultSpinner() {
	$('spinner-keywords').className="list-sub-waiting";
}

function updateKeywords()
{
	if (t) { window.clearTimeout(t); }
	t = window.setTimeout("doUpdateKeywords()",300);
}

function doUpdateKeywords()
{
	VarBin.currentKeywords=$('keywrds').value;	
	updateSearch();
}

function nullCategory() {
	/* Nulls the current category and type */
	VarBin.currentCategory=null;
	VarBin.currentType=null;
	
	vdDeleteCookie();
	
	if(VarBin.curCatLink){VarBin.curCatLink.style.backgroundColor = '';}
	VarBin.curCatLink=$('search-cat').firstChild.firstChild.firstChild // first element in li
	VarBin.curCatLink.style.backgroundColor='#c6316b';
	
//	$('search-type').innerHTML=searchTypeContent;
	
	fetchTypes();
	updateSearch();
}

function nullType() {
	VarBin.currentType=null;
	if(VarBin.curTypeLink){VarBin.curTypeLink.style.backgroundColor = '';}
	VarBin.curTypeLink=$('search-type').firstChild.firstChild.firstChild // first element in li
	VarBin.curTypeLink.style.backgroundColor='#c6316b';
	
	updateSearch();
}

function nullKeywords() {
	VarBin.currentKeywords="";
	$('keywrds').value="";
}


// FETCH DATA
function fetchCategories() {
	startCatSpinner();

	var url = base_uri+'/xml/category.php';

	var pars = '';	
	var parray = new Array();
	parray.push("lang="+language);
	pars=parray.join('&');		
	
	//var myAjax = new Ajax.Updater({success: 'search-cat'}, url, {method: 'get', parameters: pars, onFailure: reportError, onSuccess: stopCatSpinner});
	var myAjax = new Ajax.Request(
				url, 
				{method: 'get', parameters: pars, onComplete: formatCatList, onFailure: reportError}
	);
}

function fetchTypes(forCat, doNull)
{
	if(forCat!=null) {
	    
	    if(doNull!=0){ VarBin.currentType=null; }
	    
		VarBin.currentCategory=forCat;
		if(VarBin.curCatLink){VarBin.curCatLink.style.backgroundColor = '';}
		VarBin.curCatLink=$("c"+forCat);

		VarBin.curCatLink.style.backgroundColor='#c6316b';
	}	
	
	hideProduct();
	
	new Effect.Fade($('search-type').firstChild, { afterFinish: fetchTypesHelper, duration: 0.25 });

}


function fetchTypesHelper() {
	var forCat=VarBin.currentCategory;	

	startTypeSpinner();
	
	if($('search-step4').style.display!="none") {
			new Effect.Fade($('search-step4'), { duration: 0.25 } );
			new Effect.Appear($('search-step3'), { duration: 0.25, delay: 0.25 } );
	}

	var url = base_uri+'/xml/type.php';

	// construct parameters
	var pars="";	
	var parray = new Array();
	if(forCat!=null)	{ parray.push("catid="+forCat);	}
	parray.push("lang="+language);
	pars=parray.join('&');
	
	var myAjax = new Ajax.Request(
				url, 
				{method: 'get', parameters: pars, onComplete: formatTypeList, onFailure: reportError}
	);
	
	updateSearch();
}

function startSearch(forType) {
	VarBin.currentType=forType;
	
	if(VarBin.curTypeLink){VarBin.curTypeLink.style.backgroundColor = '';}
	VarBin.curTypeLink=$("t"+forType);
	VarBin.curTypeLink.style.backgroundColor='#c6316b';
	
	updateSearch();
	
}

function updateSearch() {
		
	//set a cookie point
	vdSetCookie();
		
	//hide the product info sheet
	Element.hide($('search-step4'));
		
	hideProduct();
		
	new Effect.Fade($('backtolist'), { duration: 0.25 } );
	new Effect.Appear($('moreinfo'), { duration: 0.25, delay: 0.25 } );	

		
	if((VarBin.currentCategory==null && VarBin.currentType==null) && VarBin.currentKeywords=="") {
		//$('results-step3').replaceChild(document.createElement('ul'), $('results-step3').firstChild);
		//Element.hide('results-step3');
		if($('results-step3').style.display!="none")
		{
			new Effect.Fade($('results-step3'), { duration: 0.25 } );
		}
		if($('search-step3').style.display!="none")
		{
			new Effect.Fade($('search-step3'), { duration: 0.25, delay: 0.5 } );
		}
		if($('welcome').style.display=="none")
		{
			new Effect.Appear($('welcome'), { duration: 0.25, delay: 0.75 } );
		}	
	} else {
		
		// new Effect.Fade($('welcome'), { duration: 0.25 } );
		
		if($('search-step3').style.display=="none")
		{
			new Effect.Appear($('search-step3'), { duration: 0.25, delay: 0.5 } );
		}
		
		//show the result spinner
		startResultSpinner();
		
		// construct parameters
		var pars="";	
		var parray = new Array();
		if(VarBin.currentCategory!=null)	{ parray.push("catid="+VarBin.currentCategory);	}
		if(VarBin.currentType!=null)		{ parray.push("soortid="+VarBin.currentType);		}
		if(VarBin.currentKeywords!="")		{ parray.push("q="+VarBin.currentKeywords);		}
		parray.push("lang="+language);
		pars=parray.join('&');		
		
		var url = base_uri+'/xml/prods.php';
	
		//var pars = 'catid='+forCat+'&soortid='+forType+'&q='+forKeywords;
	
	
		var myAjax = new Ajax.Request(
					url, 
					{method: 'get', parameters: pars, onComplete: formatResultList, onFailure: reportError}
		);
	}	
}

function hideProduct()
{
	new Effect.Fade($('backtolist'), { duration: 0.25 } );
	new Effect.Fade($('search-step4'), { duration: 0.25 });
	new Effect.Appear($('welcome'), { duration: 0.25, delay: 0.25} );
	new Effect.Appear($('moreinfo'), { duration: 0.25, delay: 0.25} );
	new Effect.Appear($('results-step3'), { duration: 0.25, delay: 0.25 });
}

function appearProduct()
{
	new Effect.Fade($('welcome'), { duration: 0.25 } );
	new Effect.Fade($('moreinfo'), { duration: 0.25 } );
	new Effect.Fade($('results-step3'), { duration: 0.25 });
	new Effect.Appear($('backtolist'), { duration: 0.25, delay: 0.25 } );
	new Effect.Appear($('search-step4'), { duration: 0.25, delay: 0.25 });
}	

function onPreload(aImages, nImages)
{
	$('product-image').style.display='';
	$('product-image').src=aImages[0].src;
}

function productAdded()
{
  new Effect.Fade('product-help', { duration: 1.0, queue: 'end' } );
	new Effect.Appear($('product-added'), { duration: 1.0, to: 0.9, queue: 'end' } );
	new Effect.Fade('product-added', { duration: 1.0, delay: 8.0 , queue: 'end' } );
	new Effect.Appear($('product-help'), { duration: 1.0, to: 0.9, queue: 'end' } );
}


function showProduct(id)
{
	//prepare display
	var prod=VarBin.resultSet[id];

	$('product-title').innerHTML=prod.getElementsByTagName("title")[0].firstChild.nodeValue;
	$('product-number').innerHTML="Art. No. "+prod.getElementsByTagName("artno")[0].firstChild.nodeValue;
	$('product-quantity').value=1;
	$('product-comments').value='';
	
	if(prod.getElementsByTagName("unit").length>0) {
		$('product-unit').innerHTML=prod.getElementsByTagName("unit")[0].firstChild.nodeValue;
	}
	else {
		$('product-unit').innerHTML="";
	}
	
	
	$('button-order').onclick=function() {addToContainer(prod.getElementsByTagName("id")[0].firstChild.nodeValue, $('product-quantity').value, 1, $('product-comments').value); productAdded();};
	$('button-quote').onclick=function() {addToContainer(prod.getElementsByTagName("id")[0].firstChild.nodeValue, $('product-quantity').value, 0, $('product-comments').value); productAdded();};

	$('product-description').innerHTML=prod.getElementsByTagName("description")[0].firstChild.nodeValue;

	if(prod.getElementsByTagName("image").length>0) {
		var aImg = [base_uri+"/uploads/producten/"+prod.getElementsByTagName("image")[0].firstChild.nodeValue];
		var ip = new ImagePreloader(aImg, onPreload);
	}
	else
	{
		$('product-image').style.display='none';
	}
	
	if(prod.getElementsByTagName("bigimage").length>0) {

		var bigimage=$('product-bigimage');
		bigimage.setAttribute('href',base_uri+"/uploads/producten/"+prod.getElementsByTagName("bigimage")[0].firstChild.nodeValue);

	} else {
        $('product-bigimage').href="#";
    }
	
	/*
	if(prod.getElementsByTagName("pdf").length>0) {

		var pdflink=$('product-pdf');
		pdflink.setAttribute('href',base_uri+"/uploads/"+prod.getElementsByTagName("pdf")[0].firstChild.nodeValue);
		// $('product-title').innerHTML=prod.getElementsByTagName("pdf")[0].firstChild.nodeValue;
		$('product-pdf').style.display='block';
	
	} else {
		$('product-pdf').style.display='none';
	}
	*/

	appearProduct();
}


//    CONSTRUCT HTML FROM RETRIEVED XML
function formatResultList(originalRequest) {

	var items = originalRequest.responseXML.getElementsByTagName("item");
	
	//clear the result div
	$('results-step3').replaceChild(document.createElement('ul'), $('results-step3').firstChild);
	
	//show the result div, so we can see the results trickle in (when the connection/computer is slow)
	Element.show('results-step3');
	
	//save the complete result tree in an array, for later use (when someone clicks a product)
	VarBin.resultSet=items;

	var title, artno, smallimage;

	for (var i = 0; i < items.length; i++) {
	try {
		title=items[i].getElementsByTagName('title')[0].firstChild.nodeValue;
//		alert(items[i].getElementsByTagName('artno')[0].firstChild.nodeValue);
		if(items[i].getElementsByTagName('artno')[0].firstChild.nodeValue) {
			artno = items[i].getElementsByTagName('artno')[0].firstChild.nodeValue;
		} else {
			artno = '';
		}
	} catch(e) {
		//alert(e.message);
	}
		/*title=items[i].getElementsByTagName('title')[0];//.firstChild.nodeValue;
		if(!title.nodeValue) {
			title = title.firstChild.nodeValue;
		} else {
			title = title.nodeValue;
		}
		
		artno=items[i].getElementsByTagName('artno')[0];//.firstChild.nodeValue;
		if(!artno.nodeValue) {
			artno = artno.firstChild.nodeValue;
		} else {
			artno = artno.nodeValue;
		}
		*/
		
		//do not assume an image
		if(items[i].getElementsByTagName('smallimage').length>0) {
			smallimage=items[i].getElementsByTagName('smallimage')[0].firstChild.nodeValue;
		} else {
			smallimage="";
		}
		formatResultListHelper(i, title, artno, smallimage);
	}
	
	//we're done. hide the spinner, display the number of results, and slide out the results (only if hidden)
	stopResultSpinner();
	
	$('numfound').innerHTML=items.length;
	Element.show('numfound');
}

function formatResultListHelper(id, title, artno, smallimage) {
	var li, a, img, span, script;
	
	li = document.createElement('li');
	
	a = document.createElement('a');
	a.setAttribute('href','javascript:void(0);');
	a.onclick= function() {showProduct(id);};
	
	
	img = document.createElement('img');
	if(smallimage=="") {
		img.setAttribute('src', base_uri+'/img/prod-ni-s.png');
	} else {
		img.setAttribute('src', base_uri+'/uploads/producten/'+smallimage);
	}
	img.onmouseup =  function() {containerOut()};
	img.onmousedown =  function() {containerHover()};
	img.setAttribute('align', 'left');
	img.setAttribute('id', 'sr-prod-'+id);
	img.setAttribute('class', 'result-step3-prodimg')
	img.setAttribute('alt', '');
	img.setAttribute('width', '40');
	img.setAttribute('height', '30');
	
	span = document.createElement('span');
	span.appendChild(document.createTextNode("Art. No. "+artno));
	
	a.appendChild(document.createTextNode(title));
	a.appendChild(document.createElement('br'));
	a.appendChild(span);
	
	li.appendChild(img);
	li.appendChild(a);
	
	$('results-step3').getElementsByTagName("ul")[0].appendChild(li);
	
	new Draggable('sr-prod-'+id, {revert:true});
}

function formatCatList(originalRequest) {
	var list=$('search-cat').getElementsByTagName("ul")[0];
	var items = originalRequest.responseXML.getElementsByTagName("item");
	var title, link;

	if(language=="nl") { appendToList(list, "Alle categoriën", 0, 'nc'); }
	else { appendToList(list, "All categories", 0, 'nc'); }
	
   for (var i = 0; i < items.length; i++) {
		title=items[i].getElementsByTagName('title')[0].firstChild.nodeValue;
		link=items[i].getElementsByTagName('link')[0].firstChild.nodeValue;

		appendToList(list, title, link, 'c');
	}
	stopCatSpinner();

	//see where we left off
	resumeSearch();
}


function formatTypeList(originalRequest) {
	
	//remove all contents, and create an UL
	$('search-type').replaceChild(document.createElement('ul'), $('search-type').firstChild);

	var list=$('search-type').getElementsByTagName("ul")[0];
	var items = originalRequest.responseXML.getElementsByTagName("item");
	var title, link;

	if(language=="nl") { appendToList(list, "Alle typen", 0, 'nt'); }
	else { appendToList(list, "All types", 0, 'nt'); }

	for (var i = 0; i < items.length; i++) {
		title=items[i].getElementsByTagName('title')[0].firstChild.nodeValue;
		link=items[i].getElementsByTagName('link')[0].firstChild.nodeValue;

		appendToList(list, title, link, 't');
		new Effect.Grow(list.lastChild);
	}

	stopTypeSpinner();
}


// UTILITY
function appendToList(list, title, link, t) {
    var li, a;

   li = document.createElement("li");
	if(t!='c' && t!='nc' && t!='nt') {
	li.style.display='none';
	}
   a = document.createElement("a");
   a.setAttribute('href','javascript:void(0);');

   a.appendChild(document.createTextNode(title));
   li.appendChild(a);
		
	if(t=='c') {
		a.onclick = function() {nullKeywords();fetchTypes(link,a);};
		a.setAttribute('id', "c"+link);
	} else if (t=='nc') {
		a.onclick = function() {nullKeywords();nullCategory();};
		VarBin.curCatLink=a;
		VarBin.curCatLink.style.backgroundColor='#c6316b';
	} else if (t=='nt') {
		a.onclick = function() {nullType();};
		if(VarBin.currentType==null) {
			VarBin.curTypeLink=a;
			VarBin.curTypeLink.style.backgroundColor='#c6316b';
		}
	} else {
		a.onclick = function() {startSearch(link,a);};
		a.setAttribute('id', "t"+link);
		if(link==VarBin.currentType) {
			VarBin.curTypeLink=a;
			a.style.backgroundColor="#c6316b";
		}
	}
	
	list.appendChild(li);
}

function traverse(tree) {
 if(tree.hasChildNodes()) {
  document.write('<ul><li>');
  document.write('<b>'+tree.tagName+' : </b>');
  var nodes=tree.childNodes.length;
  for(var i=0; i<tree.childNodes.length; i++)
   traverse(tree.childNodes);
  document.write('</li></ul>');
 }
 else
  document.write(tree.text);
}

//=============================================================================
// Tasty cookies
//=============================================================================

//wrapper method using Van Doorn defaults.
function vdSetCookie() {
    
    //cookies should expire in 15 minutes
    var expires = new Date();
    expires.setTime(expires.getTime() + 15 * 60 * 1000);
    
    ChocolateChip.set("vd_cat", VarBin.currentCategory, expires);
    ChocolateChip.set("vd_type", VarBin.currentType, expires);
    ChocolateChip.set("vd_keywords", VarBin.currentKeywords, expires);
 
}

//retrieves the cookie and sets proper global variables
function vdGetCookie() {
    
    var cat = ChocolateChip.get("vd_cat");
    var type = ChocolateChip.get("vd_type");
    var key = ChocolateChip.get("vd_keywords");
    
    //alert("cat: "+cat+"\ntype: "+type+"\nkeys: "+key);
    if (cat && cat!="null")     { catid=cat; }
    if (type && type!="null")   { soortid=type; }
    if (key && key!="")         { keywords=key; }
    
}

//deletes all cookies
function vdDeleteCookie() {
    ChocolateChip.remove("vd_cat");
    ChocolateChip.remove("vd_type");
    ChocolateChip.remove("vd_keywords");
}

var ChocolateChip = new Object();
ChocolateChip.set = function(name, value, expires, path, domain, secure) {
    document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}
ChocolateChip.get = function(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else {
        begin += 2;
    }
    
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
        end = dc.length;
    }
    
    return unescape(dc.substring(begin + prefix.length, end));
}
ChocolateChip.remove = function(name, path, domain) {
    if (this.get(name)) {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

//=============================================================================
// Image Preloader
//=============================================================================

function ImagePreloader(images,callback)
{
// store the callback
this.callback = callback;

// initialize internal state.
this.nLoaded = 0;
this.nProcessed = 0;
this.aImages = new Array;

// record the number of images.
this.nImages = images.length;

// for each image, call preload()
for ( var i = 0; i < images.length; i++ )
this.preload(images[i]);
}
ImagePreloader.prototype.preload = function(image)
{
// create new Image object and add to array
var oImage = new Image;
this.aImages.push(oImage);

// set up event handlers for the Image object
oImage.onload = ImagePreloader.prototype.onload;
oImage.onerror = ImagePreloader.prototype.onerror;
oImage.onabort = ImagePreloader.prototype.onabort;

// assign pointer back to this.
oImage.oImagePreloader = this;
oImage.bLoaded = false;
oImage.source = image;


// assign the .src property of the Image object
oImage.src = image;
}
ImagePreloader.prototype.onComplete = function()
{
this.nProcessed++;
if ( this.nProcessed == this.nImages )
this.callback(this.aImages);
}
ImagePreloader.prototype.onload = function()
{
this.bLoaded = true;
this.oImagePreloader;
this.oImagePreloader.nLoaded++;
this.oImagePreloader.onComplete();
}
ImagePreloader.prototype.onerror = function()
{
this.bError = true;
this.oImagePreloader.onComplete();
}
ImagePreloader.prototype.onabort = function()
{
this.bAbort = true;
this.oImagePreloader.onComplete();
}

/*   INITIALIZE   */
function initialize() {
    if(catid==null && soortid==null && keywords=="") { vdGetCookie(); }
	fetchCategories();
	fetchTypes();
}

Event.observe(window, 'load', initialize, false);
