/* 
    Copyright (c) 2008 NeonGecko.com Inc. 
    Author and Maintainer: David Graves <dgraves@neongecko.com>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

function neonCart(cartName,merchantID,shipFee,path,domain,expires){
   if(!cartName) {
      cartName = 'neonCart';
   }
   this._cartName=cartName;
   this._merchantID=merchantID;
   if(!path || path==''){
      path=window.location.pathname;
      path=path.replace(/[^\/]+$/,'');
   }
   this._cookiePath=path;
   this._cookieDomain=domain;
   this._cookieExpires=expires;
   this._baseShipFee=this.round(shipFee ? shipFee : 0);
   this.init();
   this.doQS();
}

neonCart.prototype.init=function(thanks){
   var cookies=document.cookie.split("; ");
   var cookiehash=new Array;
   for (var c in cookies){
      var pair=cookies[c].split("=");
      cookiehash[pair[0]]=pair[1];
   }   
   var t = this.load(this._cartName);
   var baseshipfee=false;
   if(t){
      var a=t.split("|");
      this._cntLine=parseInt(a.shift());
      this._total=0;
      this._prodshipfees=0;
      this._lines=new Array;
      for (var i=0 ; i < this._cntLine ; i++){
         this._lines[i]=new Object;
         this._lines[i].sku=unescape(a.shift());
         this._lines[i].qty=parseInt(unescape(a.shift()));
         this._lines[i].price=this.round(unescape(a.shift()));
         var shipfee=unescape(a.shift());
         this._lines[i].shipfee=shipfee;
         if (shipfee == 'F'){
            shipfee=0;
         }else{
            shipfee=this.round(shipfee);
            baseshipfee=true;
         }
         this._lines[i].descr=unescape(a.shift());
         this._lines[i].option=unescape(a.shift());
         this._lines[i].url=unescape(a.shift());
         this._lines[i].total=this.round(this._lines[i].qty*this._lines[i].price);
         this._prodshipfees+=shipfee*this._lines[i].qty;
         this._total+=this._lines[i].qty*this._lines[i].price;
      }
   }
   if(baseshipfee){
      this._shipping=this.round(this._baseShipFee*1 + this._prodshipfees*1);
   }else{
      this._shipping="0.00";
   }

   this._total=this.round(1*this._total+1*this._shipping);
   var div=document.getElementById(this._cartName);
   if(div){
      var credit="<a target=\"_blank\" style=\"position: relative; right: 0px; font-family: sans-serif; font-size: 9px; color: #AAA; text-decoration: none;\" href=\"http://www.neongecko.com/cart/\">Shopping Cart by NeonGecko</a>";
      if (this._cntLine > 0){
         div.innerHTML='';
         this.fixCss();
         var form=this.ce("form");
         form.action="https://checkout.google.com/cws/v2/Merchant/"+this._merchantID+"/checkoutForm";
         form.method="post";
         form.acceptCharset="utf-8";
         var table1=this.ce("table");
         table1.setAttribute("id","neonCart");
         table1.style.width="99%";
         form.appendChild(table1);
         var table=this.ce("tbody");
         table1.appendChild(table);
         var tr=this.ce("tr");
         table.appendChild(tr);
         var th=this.ce("th");
         th.innerHTML="Item";
         th.style.width="4em";
         tr.appendChild(th);
         th=this.ce("th");
         th.innerHTML="Description";
         tr.appendChild(th);
         th=this.ce("th");
         th.innerHTML="Qty";
         th.style.width="4em";
         tr.appendChild(th);
         th=this.ce("th");
         th.innerHTML="Price";
         th.style.width="5em";
         tr.appendChild(th);
         th=this.ce("th");
         th.innerHTML="Total";
         th.style.width="5em";
         tr.appendChild(th);
         var td=this.ce("td");
         //td.style.width="5em";
         tr.appendChild(td);
         var mycart=this; //required to make closures;
         for(var i=0; i < this._cntLine; i++){
            var j=i+1;
            var tr=this.ce("tr");

            var td=this.ce("td");
            td.setAttribute("className","tdata");
            td.setAttribute("class","tdata");
            if(this._lines[i].url.length>1){
               td.innerHTML="<a href=\""+this.safe(this._lines[i].url)+"\">"+this.safe(this._lines[i].sku)+"</a>";
            }else{
               td.innerHTML=this.safe(this._lines[i].sku);
            }
            tr.appendChild(td);

            td=this.ce("td");
            td.setAttribute("className","tdata");
            td.setAttribute("class","tdata");
            td.innerHTML=this.safe(this._lines[i].descr + " " + this._lines[i].option);
            tr.appendChild(td);

            td=this.ce("td");
            td.setAttribute("className","tdata");
            td.setAttribute("class","tdata");

            var input=this.ce("input");
            input.style.width="4em";
            input.style.textAlign="center";
            input.value=this.safe(this._lines[i].qty);
            input.setAttribute("name","item_quantity_"+j);
            input._i=i;
            input.onchange=function(){
               this.onchange=function(){};
               mycart.qty(this._i,this.value);
            }
            input.onkeypress=function(e){
               if(!e){
                  e=window.event;
               }
               if(e.keyCode == 13){
                  this.onchange();
                  return false;
               }
            }
            td.appendChild(input);

            input=this.ce("input");
            input.setAttribute("type","hidden");
            input.setAttribute("name","item_name_"+j);
            input.value=this.safe(this._lines[i].descr + " " + this._lines[i].option);
            td.appendChild(input);

            input=this.ce("input");
            input.setAttribute("type","hidden");
            input.setAttribute("name","item_description_"+j);
            //input.value=this.safe(this._lines[i].descr + " " + this._lines[i].option);
            td.appendChild(input);

            input=this.ce("input");
            input.setAttribute("type","hidden");
            input.setAttribute("name","item_price_"+j);
            input.value=this.safe(this._lines[i].price);
            td.appendChild(input);

            td.style.width="4em";
            td.style.textAlign="center";
            tr.appendChild(td);

            td=this.ce("td");
            td.setAttribute("className","tdata");
            td.setAttribute("class","tdata");
            td.innerHTML=this.safe(this._lines[i].price);
            td.style.textAlign="right";
            tr.appendChild(td);
            
            td=this.ce("td");
            td.setAttribute("className","tdata");
            td.setAttribute("class","tdata");
            td.innerHTML=this.safe(this._lines[i].total);
            td.style.textAlign="right";
            tr.appendChild(td);
            
            td=this.ce("td");
            var btn=this.ce("button");
            btn.innerHTML="Remove";
            btn._i=i;
            btn._a=0;
            btn.onmousedown=function(){
               this._a=1;
            }
            btn.onmouseout=function(){
               this._a=0;
            }
            btn.onclick=function(){
               if(this._a==1){
                  this.onclick=function(){}
                  mycart.del(this._i);
               }
               return false;
            }
            td.appendChild(btn);
            tr.appendChild(td);
            table.appendChild(tr);
         }
         tr=this.ce("tr");
         td=this.ce("td");
         td.setAttribute("colspan","3");
         td.colSpan="3";
         input=this.ce("input");
         input.setAttribute("type","hidden");
         input.setAttribute("name","ship_method_name_1");
         input.setAttribute("value","Standard Shipping");
         td.appendChild(input);
         input=this.ce("input");
         input.setAttribute("type","hidden");
         input.setAttribute("name","ship_method_price_1");
         input.setAttribute("value",this.safe(this._shipping));
         td.appendChild(input);
         var returnUrl=document.location.protocol + "//" + 
		document.location.host + 
		(document.location.port ? ":"+document.location.port : '') + 
		document.location.pathname;
         input=this.ce("input");
         input.setAttribute("type","hidden");
         input.setAttribute("name","checkout-flow-support.merchant-checkout-flow-support.continue-shopping-url");
         input.setAttribute("value",this.safe(returnUrl + "?d=c&thanks=1"));
         td.appendChild(input);
         input=this.ce("input");
         input.setAttribute("type","hidden");
         input.setAttribute("name","checkout-flow-support.merchant-checkout-flow-support.edit-cart-url");
         input.setAttribute("value",this.safe(returnUrl));
         td.appendChild(input);

         var creditdiv=this.ce("div");
         creditdiv.style.textAlign='center';
         creditdiv.innerHTML=credit;
         td.appendChild(creditdiv);

         tr.appendChild(td);
         if(this._shipping > 0){
            th=this.ce("th");
            th.innerHTML="Shipping";
            tr.appendChild(th);
            td=this.ce("td");
            td.setAttribute("className","tdata");
            td.setAttribute("class","tdata");
            td.innerHTML=this.safe(this._shipping);
            td.style.textAlign="right";
            tr.appendChild(td);
            table.appendChild(tr);

            tr=this.ce("tr");
            td=this.ce("td");
            td.setAttribute("colspan","3");
            td.colSpan="3"; 
            tr.appendChild(td);
         }
         th=this.ce("th");
         th.innerHTML="Total";
         tr.appendChild(th);
         td=this.ce("td");
         td.setAttribute("className","tdata");
         td.setAttribute("class","tdata");
         td.innerHTML=this.safe(this._total);
         td.style.textAlign="right";
         tr.appendChild(td);
         table.appendChild(tr);
         tr=this.ce("tr");
         td=this.ce("td");
         td.setAttribute("colspan","5");
         td.colSpan="5";
         td.style.textAlign="right";
         input=this.ce("input");
         input.setAttribute("type","hidden");
         input.setAttribute("name","_charset_");
         td.appendChild(input);
         input=this.ce("input");
         input.setAttribute("type","image");
         input.setAttribute("name","Google Checkout");
         input.setAttribute("alt","Fast checkout through Google");
         input.setAttribute("src","http://checkout.google.com/buttons/checkout.gif?merchant_id="+ this._merchantID +"&w=180&h=46&style=white&variant=text&loc=en_US");
         input.setAttribute("height","46");
         input.setAttribute("width","180");
         td.appendChild(input);
         tr.appendChild(td);
         table.appendChild(tr);
         div.appendChild(form);
      }else if (thanks == 1){
         div.innerHTML="Thank you for you order.<br/><br/> <div>" + credit + "</div>";
      }else{
         div.innerHTML="Cart Empty<br/><br/> <div>" + credit + "</div>";
      } 
   }
}

neonCart.prototype.doQS=function(){
   if (this.param('d') == 'a' && window.location.hash != '#1' ){
      var prod=new Object;
      prod.sku=this.param('sku');
      prod.descr=this.param('descr');
      prod.option=this.param('option');
      prod.price=this.param('price');
      prod.url=this.param('url');
      prod.shipfee=this.param('shipfee');
      if(!prod.shipfee || prod.shipfee==''){
         prod.shipfee='F';
      }
      prod.shipping=this.param('shipping');
      prod.crc=this.param('crc');
      if(prod.crc == this.crc(prod.shipping + prod.price + prod.shipfee + prod.sku + prod.descr + this._merchantID)){
         this.add(prod);
         window.location.hash='1';
         this.init();
      }else{
         //alert(this.crc(prod.shipping + prod.price + prod.shipfee + prod.sku + prod.descr + this._merchantID));
         alert("Invalid Command.\nVisit neongecko.com for implementation details.");
      }
   }else if (this.param('d') == 'd' && window.location.hash != '#1' ){
      var line=this.param('line');
      this.del(parseInt(line));
      window.location.hash='1';
   }else if (this.param('d') == 'c'){
      this._cntLine=0;
      this._lines=[];
      this.save();
      this.init(this.param('thanks'));
   }
}

neonCart.prototype.ce=function(type){
   if(!type) return false;
   if(!this._isIE){
      if(window.ActiveXObject){
         this._isIE=1;
      }else{
         this._isIE=2;
      }
   }
   if(this._isIE == 1){
      return document.createElement(type);
   }else{
      return document.createElementNS("http://www.w3.org/1999/xhtml",type);
   }
}

neonCart.prototype.safe=function(a){
   a=new String(a);
   a=a.replace(/\&/g,"&amp;");
   a=a.replace(/\"/g,"&quot;");
   a=a.replace(/\</g,"&lt;");
   a=a.replace(/\>/g,"&gt;");
   return a;
}

neonCart.prototype.add= function(obj) {
   var qty=parseInt(obj.qty);
   if (!qty) qty=1;
   if (!obj.option) obj.option="";
   if (!obj.url) obj.url="";
   if(parseInt(this._cntLine)){
      for (var i=0; i < this._cntLine; i++){
         var l=this._lines[i];
         if (	l.sku==obj.sku && 
		l.descr==obj.descr && 
		l.option==obj.option && 
		l.price==this.round(obj.price) && 
		l.shipfee==obj.shipfee  ){
            l.qty+=qty;
            this.save();
            return
         }
      }
      this._cntLine++;
   }else{
      this._cntLine=1;
      this._total=0;
      this._prodshipfees=0;
      this._lines=new Array;
   }
   var i=this._cntLine-1;
   this._lines[i]=new Array;
   this._lines[i].sku=obj.sku;
   this._lines[i].qty=qty;
   this._lines[i].price=this.round(obj.price);
   this._lines[i].shipfee=obj.shipfee;
   this._lines[i].descr=obj.descr;
   this._lines[i].option=obj.option;
   this._lines[i].url=obj.url;
   this._lines[i].total=this.round(obj.price*qty);
   this._total+=this._lines[i];
   this.save();
}

neonCart.prototype.del=function(line){
   this._cntLine--;
   this._lines.splice(line,1);
   this.save();
   this.init();
}

neonCart.prototype.qty=function(line,qty){
   if (qty==0){
      this.del(line);
   }else{
      if(isNaN(qty)) qty=1;
      this._lines[line].qty=qty;
      this.save();
      this.init();
   }
}

neonCart.prototype.round=function(a){
   if(isNaN(a)) return "0.00";
   a*=1;
   if(a.toFixed){
      return a.toFixed(2);
   }else{
      return Math.round(a*100)/100;
   }
}

neonCart.prototype.load=function(cookieName){
   var cookies=document.cookie.split("; ");
   var cookiehash=new Object;
   for (var c in cookies){
      var pair=cookies[c].split("=");
      cookiehash[pair[0]]=pair[1];
   }
   var value=cookiehash[cookieName];
   var re=new RegExp(cookieName + "_(\\d+)");
   var elems=new Array;
   for (var i in cookiehash){
      if (i == cookieName){
         elems[0]=cookiehash[i];
      }
      var j;
      if (j=i.match(re)){
         elems[j[1]]=cookiehash[i];
      }
   }
   return elems.join('') ;
} 


neonCart.prototype.save=function(){
   var c=this._cntLine +"|";
   for (var i=0; i < this._cntLine ; i++){
      c+= escape(this._lines[i].sku);
      c+= "|" + escape(this._lines[i].qty);
      c+= "|" + escape(this._lines[i].price);
      c+= "|" + escape(this._lines[i].shipfee);
      c+= "|" + escape(this._lines[i].descr);
      c+= "|" + escape(this._lines[i].option);
      c+= "|" + escape(this._lines[i].url) + "|";
   }
   var cParms=new String;
   if (this._cookiePath){
      cParms+="; path="+this._cookiePath;
   }
   if (this._cookieDomain){
      cParms+="; domain="+this._cookieDomain;
   }
   if (this._cookieExpires){
      cParms+="; expires="+this._cookieExpires;
   }
   var m=4000;
   if(c.length > m){
      var i=0;
      while(c.length){
         var cc=c.substring(0,m);
         c=c.substring(m);
         if(i==0){
            document.cookie=this._cartName + "=" + cc + cParms;
         }else{
            document.cookie=this._cartName + "_" + i + "=" + cc + cParms;
         }
         i++;
      }
   }else{
      document.cookie=this._cartName + "=" + c + cParms;
   }
}

neonCart.prototype.crc=function(a){
   if (!this._crcache){ 
      this._crcache=[];
      for( var i=0; i < 256; i++){ 
         var b=i; 
         for(var j=0; j < 8; j++) b = b & 1 ? 3988292384 ^ (b >>> 1) : b >>> 1; this._crcache[i]=b; 
      }
   } 
   var c=-1; 
   for( var i=0 ; i < a.length ; i++ ) c=(c >>> 8) ^ this._crcache[(c ^ a.charCodeAt(i)) & 255]; 
   c=~c; 
   var h=''; 
   for (var i=0; i<4; i++){ 
      var g=(c & 255).toString(16); 
      h=g.length==1 ? "0"+g+h: g+h; 
      c=c >>> 8; 
   } 
   return h; 
}

neonCart.prototype.param=function(a){
   if(!this._pcache){
      this._pcache=new Object;;
      var s=window.location.search;
      if(s){
         var p=s.substr(1).split("&");
         for (var i=0 ; i < p.length; i++){
            var t=p[i].split("=");
            this._pcache[unescape(t[0])]=unescape(t[1].replace(/\+/g,'%20'));
         }
         if(!this._pcache['shipping'] || !this._freeShipping){
            this._pcache['shipping']="eval(4.5 + this._pcache['weight']*.5)"; //default for ground
         }   
      }
   }
   return this._pcache[a];
}

neonCart.prototype.checkCss=function(){
   var flavor;
   for (si=0; si < document.styleSheets.length; si++){
      if(!flavor){
         if (document.styleSheets[si].cssRules){
            flavor=1;
         }else if (document.styleSheets[si].rules){
            flavor=2;
         }
      }
      var rules;
      if(flavor==1){
         rules=document.styleSheets[si].cssRules;
      }else if (flavor==2){
         rules=document.styleSheets[si].rules;
      }
      for (ri=0; ri < rules.length; ri++){
         if (rules[ri].selectorText.indexOf("#neonCart") != -1 ){
            return true;
         }
      }
   }
   return false;
}

neonCart.prototype.fixCss=function(){
   if(this.checkCss()) return false;
   if(document.styleSheets.length == 0){
      var ss=this.ce('style');   
      ss.setAttribute("type","text/css");
      var head=document.getElementsByTagName("head")[0];
      if (head){
         head.appendChild(ss);
      }else{
         return false;
      }
   }
   var sheet=document.styleSheets[0];
   if (sheet.insertRule){
      sheet.insertRule("#neonCart { font-family: sans-serif; }",0);
      sheet.insertRule("#neonCart th { background-color: #EEE; border-bottom: 1px solid #CCC; border-right: 1px solid #CCC; padding-right: 1em; padding-left: .5em;}",0);
      sheet.insertRule("#neonCart td { padding-right: 1em; padding-left: .5em;}",0);
      sheet.insertRule("#neonCart button { color: white; font-size: 7pt; background-color: #305cc4; border: 1px outset #305cc4;}",0);
      sheet.insertRule("#neonCart td.tdata { border-bottom: 1px solid #CCC;}",0);
   }else if (sheet.addRule){
      sheet.addRule("#neonCart","{ font-family: sans-serif; }");
      sheet.addRule("#neonCart th","{ background-color: #EEE; border-bottom: 1px solid #CCC; border-right: 1px solid #CCC; padding-right: 1em; padding-left: .5em;}");
      sheet.addRule("#neonCart td","{ padding-right: 1em; padding-left: .5em;}");
      sheet.addRule("#neonCart button","{ color: white; font-size: 7pt; background-color: #305cc4; border: 1px outset #305cc4;}");
      sheet.addRule("#neonCart td.tdata","{border-bottom: 1px solid #CCC;}");
   }
}

