/**
 *
 * @author			Jochen Vandendriessche
 * Vynckier javascript
 * @since			2008 03 04 14 12
 * 
 */

  window.onload = init;
   
  var _JAH = new joinkJAH();
  var aLink = null;
  var _ACS = [];  
  var _CNT = 0;
//////////////////////////////////////////////////////////////////////////////////////
 
  function ajaxLink(href){
     this.href = href;
     aLink = this;
     this.href.onclick = function(){aLink.doClick();return false;};
  }
 
  ajaxLink.prototype = {
  	
  	doClick : function(){
  		if (_JAH.state === false){
  			window.open(this.href.href);
  			if (parent.joinkBox){
  				parent.joinkBox.hideOverlay();
  			}
  		}else{
  			window.setTimeout(bind(this, this.doClick), 1);
  		}
  	}
  	
  }
 
//////////////////////////////////////////////////////////////////////////////////////
// STORE FUNCTIONS
 
/**
 *
 * @function 	: storeBasket
 * @param id	: integer
 * @description : do an joink.JAH request to store the id in the session array
 */
 
 var FADO = null;
 
 function replaceChars(e) {
    e = e.replace(/\./, '');
    e = e.replace(/\,/, '.');
    return parseFloat(e);
 }
 
 function changeCount(product, accessorie) {
    var id = product + '' + accessorie;
    var count = $('count' + id).value;
    if (!(count = parseInt(count))) {
        if (count != 0) {
            count = 1;
        }
    }
    count = Math.abs(count);
    
    $('count' + id).value = count;
    var price = $('price' + id);
    var unitprice = $('unitprice' + id);
    var total = $('baskettotal');
    
    // get initial prices
    var iunitprice = replaceChars(unitprice.innerHTML);
    var itotal = replaceChars(total.innerHTML) - replaceChars(price.innerHTML);
    
    // spinner
    var im = new Image();
    im.src = BASE_URL + '/assets/i/web/basket-loader.gif';
    var im2 = new Image();
    im2.src = im.src;
    price.innerHTML = '';
    price.appendChild(im);
    total.innerHTML = '';
    total.appendChild(im2);
    
    var o = new Count(product, accessorie, count, iunitprice, itotal);
    p = JSON.stringify(o);          
    _JAH.setParams('article='+p);
    _JAH.setHtmlObj('');
    _JAH.setFunction(processCount); 
    _JAH.doRequest(BASE_URL + '/basket/changecount/', 'POST');
    
 }
 
 function processCount() {
    var a = JSON.parse(_JAH.response);
    
    // change the article price
    $('price' + a.id).innerHTML = a.price;
    
    // change total price
    $('baskettotal').innerHTML = a.total;
 }
 
 function Count(product, accessorie, count, unitprice, total) {
    this.product = product;
    this.accessorie = accessorie;
    this.count = count;
    this.unitprice = unitprice;
    this.total = total;
 }
 
 function storeBasket(id, lang, accessorie){
 	// check of er een accessories link is
 	if (_CNT){
 		_ACS[_CNT.href].add();
 	}
 	
  	if (!_JAH.state){
	 	if (!$('bmsg')){
	 		 createMsg();
	 	}
	 	var msg = $('bmsg');
		var pos = [0, 0];
		if ($('article' + id + accessorie)){
			pos = getPos($('article' + id + accessorie));
		}
		window.clearTimeout(FADO);
		msg.style.left = pos[0] - 45 + 'px';
		msg.style.top = pos[1] - 37 + 'px';
	 	var t = new Article(id, lang, accessorie);
	 	p = JSON.stringify(t);  		
	  	_JAH.setParams('article='+p);
	 	_JAH.setHtmlObj('');
	 	_JAH.setFunction(showSpan);
		if (accessorie == 0){
			doCheck(id, lang);
		}	 		
		if (!$('article' + id + accessorie).checked){
			_JAH.doRequest(BASE_URL + '/basket/remove/', 'POST');
		}else{
	 		_JAH.doRequest(BASE_URL + '/basket/add/', 'POST');
		}
		msg.innerHTML = '';
		var im = new Image();
		im.src = BASE_URL + '/assets/i/web/yajax-loader.gif';
		//im.style.float = 'left';
		msg.appendChild(im);
		$('bmsg').style.display = 'block';
 	}else{
 		window.setTimeout('storeBasket(' + id + ', ' + lang + ', ' + accessorie + ')', 1);
 	}

 }
 
 function doCheck(id, lang){
	 
 	var chk = document.body.getElementsByTagName('input');
 	for (var n = 0;n<chk.length;n++){
 		if (chk[n].type == 'checkbox' && chk[n].className == 'checkbox reqAccGroup'){
 			var reg = new RegExp(id);
 			if (reg.test(chk[n].id)){
 				var aid = chk[n].id.replace('article', '');
 				aid = aid.replace(id, '');
 				if (aid != 0){
	 				if (chk[n].checked){
	 					chk[n].checked = '';
	 				}else{
	 					chk[n].checked = 'checked';
	 				} 					
 					storeBasket(aid, lang, id);
 				}
 			}
 		}
 	} 	
 }
 
 function createMsg(){
 	var div = document.createElement('div');
 	div.id = 'bmsg';
 	document.body.appendChild(div);
 	
 }
 
 function hideMsg(){
 	$('bmsg').style.display = 'none';
 }
 
 function showSpan(){
 	$('bmsg').innerHTML = _JAH.response;
 	FADO = window.setTimeout("hideMsg()", 2000);
 	//window.alert(_JAH.response);
 }
 
 function Article(id, lang, accessorie){
 	this.id = parseInt(id);
 	this.lang = lang;
 	this.accessorie = parseInt(accessorie);
 }

//////////////////////////////////////////////////////////////////////////////////////
// BreakTable

 function BreakTable(tbl){
 	this.table = tbl;
 	this.parent = this.table.parentNode;
 	if (this.table.offsetWidth > this.parent.offsetWidth){
		var div = document.createElement('div');
		div.className = 'breaker';
		var tblClone = this.table.cloneNode(true);
		div.appendChild(tblClone);
		this.parent.insertBefore(div, this.table);
		this.parent.removeChild(this.table);
		
 	}
 }

/////////////////////////////////////////////////////////////////////////////////////
// ADD2CONTENT FUNCTIONS
  
 function init(){
 	// build the joink link
 	var toword = $('toword');
 	if (toword){
 		new ajaxLink(toword);
 	}
 	
 	// gather all the a's on the document with rel = addContent
 	var lnx = document.getElementsByTagName('a');
 	for (var n=0;n<lnx.length;n++){
 		if (lnx[n].rel == 'addContent'){
 			_ACS[lnx[n].href] = new addContent(lnx[n]);
 			_CNT = lnx[n];
  		}
 	}

	//window.alert(_CNT);
 	 	
 	// get all the breakable Tables
 	var tbl = $$('breaktable');
 	for (var n = 0;n<tbl.length;n++){
 		new BreakTable(tbl[n]);
 	}
 	
 	newJoinkBox();
 	
 }

 function fetchPrice(span){
 	this.span = span;
 	this.article = this.span.id.split('-')[1];
 	this.ajax = new joinkJAH();
 	this.doFetch();
 }

 fetchPrice.prototype = {
    
    doFetch : function(){
    	if (/euro/.test(this.span.className)){
    	   this.ajax.setParams('article='+this.article+'&symbol=euro');
    	}else{
	       this.ajax.setParams('article='+this.article);
    	}
    	this.ajax.setFunction(bind(this, this.removeTitle));
	    this.ajax.setHtmlObj(this.span.id);
	    this.ajax.doRequest(BASE_URL + '/navision.php', 'GET');
    },
    
    removeTitle : function(){
    	this.span.title = '';
    }
    
 }

 function doAddContent(a){
	_ACS[a.href].add();
 }

 function addContent(a){
 	this.link = a;
 	this.link.onclick = function(){ doAddContent(this); return false;};
 	this.iSc = 0;
 	this.eSc = 0;
 	this.t = 0;
 	this.s = false;
 }
 
 addContent.prototype = {
 	
 	add:function(){
 		if (!this.s){
	 		if(!_JAH.state){
	 			_JAH.setParams('');
	 			_JAH.setHtmlObj('accessoires');
	 			_JAH.setFunction(bind(this, this.scrollToDiv));
	 			_JAH.doRequest(this.link.href, 'GET');
	 		}else{
	 			window.setTimeout(bind(this, this.add), 1);
	 		}
 		} 		
 	},
 	
 	scrollToDiv:function(){
 		var pos = getPos($('accessoires'));
 		this.s = true;
 		this.iSc = document.documentElement.scrollTop;
 		this.eSc = pos[1];
 		this.animateScroll();
 		
		    var prices = $$('checkArticle');
		    for (var n = 0;n<prices.length;n++){
		      new fetchPrice(prices[n]);
		    } 		
 		
 		// scroll over distance from start_scroll
		//window.scrollTo(0, pos[1]);
 	}, 
 	
 	
 	animateScroll:function(){
 		if (this.t < 30){
			var dist = this.eSc - this.iSc;
			var st = outCubic(this.t, this.iSc, dist, 30);
			window.scrollTo(0, st);
			this.t++;
			window.setTimeout(bind(this, this.animateScroll), 15);	
 		}
 	}
 }

		    function outCubic(t, b, c, d){
			   var ts = (t/=d)*t;
			   var tc = ts*t;
			   return b+c*(tc + -3*ts + 3*t);		
		    }

//////////////////////////////////////////////////////////////////////////////////////
  
 function $(o){
 	if (typeof o == 'object'){
 		return o;
 	}else if(document.getElementById(o)){
 		return document.getElementById(o);
 	}else{
 		return false;
 	}
 }
 
 function getPos(o) {
	var curleft = curtop = 0;
	if (o.offsetParent) {
		curleft = o.offsetLeft
		curtop = o.offsetTop
		while (o = o.offsetParent) {
			curleft += o.offsetLeft
			curtop += o.offsetTop
		}
	}
	return [curleft,curtop];
 }  
 
 // getElementsByClassName
 function $$(c, p){
 	var f = [];
 	var e = [];
 	var r = new RegExp(c);
 	if (p){
	 	if (p.tagName){
	 		e = document.getElementsByTagName('a')
	 	}else if (p.parent){
	 		_$$($(p.parent), e);
	 	}else{
	 		_$$(document, e);
	 	}
 	}else{
 		_$$(document, e);
 	}
 	for (var n=0;n<e.length;n++){
 		if (r.test(e[n].className)){
 			f.push(e[n]);
 		}
 	}
 	if (f.length > 0){
 		return f;
 	}else{
 		return false;
 	}
 }
 
 // getChildNodes from o and push in array a
 function _$$(o, a){
 	if (typeof o == 'object'){
	 	var x = o.childNodes;
		for (var n=0;n<x.length;n++){
			a.push(x[n]);
			_$$(x[n], a);
	 	}
 	}
 }
 
    function DomReady(fn) {
	  if (document.addEventListener) {
	    document.addEventListener("DOMContentLoaded", fn, false);
	  }
	  
		// for Internet Explorer (using conditional comments)
		/*@cc_on @*/
		/*@if (@_win32)
		document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
		var script = document.getElementById("__ie_onload");
		script.onreadystatechange = function() {
			if (this.readyState == "complete") {
				fn();
			}
		};
		/*@end @*/



	  
	}

	function readyState(fn) {
	  if (document.readyState == "interactive") {
	    fn();
	  }
	}

	window.onDomReady = DomReady;

	window.onDomReady(fetchPrices);
	
	function fetchPrices() {
		// get all the checkArticle to fetch the prices
	 	var prices = $$('checkArticle');
	 	for (var n = 0;n<prices.length;n++){
	 	  new fetchPrice(prices[n]);
	 	}
	}