/**
 * functions.js - Contains all look n feel functions base on prototype library, for dealing with filter form and hover link
 *
 * @author    timothee@yahoo-inc.com
 * @version   0.1
 */

  /**
   *	Load and apply all event to observe: 
   */
  window.onload = function() {
  	// For "detail du prix" link
  	var sp = $$('span.odt') ;
  	sp.each( function(elem){ elem.observe('mouseover', showPriceDetails); } ) ;
  	sp.each( function(elem){ elem.observe('mouseout', hidePriceDetails); } ) ;
  
  	// For tab system on product page
  	var tab = $$('ul.ptab li') ;
  	tab.each( function(elem){ elem.observe('mouseup', showTab); } ) ;
  }
  
  /**
   *	Apply show class on popup detail price
   */
  function showPriceDetails(event) {
  	var element = event.element();
  	var div = element.adjacent('div') ;
  	div[0].up().addClassName('show');
  }
  
  /**
   *	Remove show class on popup detail price
   */
  function hidePriceDetails(event) {
  	var element = event.element();
  	var div = element.adjacent('div') ;
  	div[0].up().removeClassName('show');
  }
  
  /**
   *	Toggle display on tab system on product page
   */
  function showTab(event) {
  	var element = event.element();
  	if (!element.hasClassName('tab-select')) {
  		var pspec = $$('table.pspec') ;
  		var poffer = $$('.poffer') ;
  		if (element.hasClassName('tab-offer')) {
  			pspec[0].removeClassName('show') ;
  			pspec[0].addClassName('hide') ;
  			poffer[0].removeClassName('hide') ;
  		} else {
  			pspec[0].removeClassName('hide') ;
  			pspec[0].addClassName('show') ;
  			poffer[0].addClassName('hide') ;
  		}
  		element.addClassName('tab-select') ;
  		var list = element.adjacent('li') ;
  		list[0].removeClassName('tab-select');
  	}
  }
  
  /**
   *	Add to action form filter and in a new hidden input values separate by coma to get smart URL
   */
  function filterToUrl(f,param) {
  	var filter = '' ;
  	param.each(function(s){ if (!s.value.empty()){ filter+= (s.value + ',' ) ; } }) ;
  	var action = filter.replace(/,Filtrer,/,'') ;
  	f.action += ('/'+action) ;
  	var i = new Element('input', { 'type': 'hidden', 'value': action, 'name': 'f' ,'id':'f' }) ;
  	f.appendChild(i) ;
  }
  
  /**
   *	Form validation on select change
   */
  function goToSubmit(sel) {
  	var f = $$('form.filter') ;
  	filterToUrl(f[0],f[0].getElements()) ;
  	f[0].submit() ;
  }

  function onlySubmit(sel) {
  	var f = $$('form.filter') ;
  	f[0].submit() ;
  }


/**
* cookie managment
*/

  function getCookieVal(offset)
  {
  	var endstr=document.cookie.indexOf (";", offset);
	if (endstr==-1) endstr=document.cookie.length;
	return unescape(document.cookie.substring(offset, endstr));
	}

   function readCookie(nom)
   {
	var arg=nom+"=";
	var alen=arg.length;
	var clen=document.cookie.length;
	var i=0;
	while (i<clen)
	{
		var j=i+alen;
		if (document.cookie.substring(i, j)==arg) return getCookieVal(j);
		i=document.cookie.indexOf(" ",i)+1;
		if (i==0) break;
	}
	return null;
   }

   function buildswparam(){
   	var param="";
	if (readCookie("swtrafid")){
		param+= "&swtrafid="+readCookie("swtrafid") ;
	}
	if (readCookie("swhistid")){
		param+= "&swhistid="+readCookie("swhistid") ;
	}
        if (readCookie("swcid")){
                param+= "&swcid="+readCookie("swcid") ;
        }
        if (readCookie("kpartnerid")){
                param+= "&kpartnerid="+readCookie("kpartnerid") ;
        }

	return param;
   }

  /**
   *	Leads validation
   */
  function leads_go(url) {

        //send parameters to SearchWare server if only swcid cookie are available
      if (readCookie("swcid")){
	var leadUrl = mp_decode64(url) ;

	var comid=leadUrl.substring(leadUrl.lastIndexOf("comId"));
	comid= comid.substring(6,comid.indexOf("=",6));
	comid = comid.substring(0,comid.indexOf("&",0));

	var catid=leadUrl.substring(leadUrl.lastIndexOf("catId"));
        catid= catid.substring(6,catid.indexOf("=",6));
        catid = catid.substring(0,catid.indexOf("&",0));

        var catidsearch=leadUrl.substring(leadUrl.lastIndexOf("catId"));
         catidsearch = catidsearch.substring(catidsearch.lastIndexOf("=")+1);


	new Ajax.Request('/sw/swcall.php',
  	{
	    method:'get',
	    parameters: {comid: comid, catid: catid, catidsearch: catidsearch},
	    onSuccess: function(transport){
        	    var response = transport.responseText || "no response text";
            	  // alert("Success! \n\n" + response);
	    },
            onFailure: function(){ 
		//alert('Something went wrong...');
		return false;
	     }
        });

       }

	//lead to offer merchant page
	self.open(mp_decode64(url));
	return false ;
  }

  function mp_decode64(input) {
      var output = "";
      var chr1, chr2, chr3 = "";
      var enc1, enc2, enc3, enc4 = "";
      var i = 0;
      var kk_keyStr = "ABCDEFGHIJKLMNOP" +
                   "QRSTUVWXYZabcdef" +
                   "ghijklmnopqrstuv" +
                   "wxyz0123456789+/" +
                   "=";

      // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
      var base64test = /[^A-Za-z0-9\+\/\=]/g;
      if (base64test.exec(input)) {
         return '';
      }
      input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

      do {
         enc1 = kk_keyStr.indexOf(input.charAt(i++));
         enc2 = kk_keyStr.indexOf(input.charAt(i++));
         enc3 = kk_keyStr.indexOf(input.charAt(i++));
         enc4 = kk_keyStr.indexOf(input.charAt(i++));

         chr1 = (enc1 << 2) | (enc2 >> 4);
         chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
         chr3 = ((enc3 & 3) << 6) | enc4;

         output = output + String.fromCharCode(chr1);

         if (enc3 != 64) {
            output = output + String.fromCharCode(chr2);
         }
         if (enc4 != 64) {
            output = output + String.fromCharCode(chr3);
         }

         chr1 = chr2 = chr3 = "";
         enc1 = enc2 = enc3 = enc4 = "";

      } while (i < input.length);

      return output;
   }
