﻿/* car manager ojbect def */
 _cartManager = function(){
	this._updateThread=null;
   
   this._orderItems = new Object();
   this.subTotal=0;
   this._updating=false;
}
var _cmp = _cartManager.prototype;

/*  */
_cmp._init=function(){
   this._updating=true;
   /* iterate order id's from html dom */
   $('.OrderItemID').each(function(){
      var nID = parseInt($(this).val());
      window.CartManager._orderItems[nID+''] = new _orderItem(nID);
      window.CartManager._orderItems[nID+'']._init();
   });
   this._updateDisplay();
}
_cmp.addOne=function(nID){
   if(this._orderItems[nID+'']){
      this._orderItems[nID+''].addOne();
      this.updateServer();
   }
}
_cmp.subOne=function(nID){
   if(this._orderItems[nID+'']){
      if(this._orderItems[nID+''].subOne()){
         this.updateServer();
      }
   }
}
_cmp._delete=function(nID){
   if(this._orderItems[nID+'']){
      this._JConfirm_DeleteID = nID;
      jConfirm('Remove '+this._orderItems[nID+'']._name + '?','Confirmation',function(r){
         if(r){
            window.CartManager._orderItems[window.CartManager._JConfirm_DeleteID+'']._delete();
            window.CartManager.updateServer();
         }
     });
   }
}
/**/
_cmp.updateServer=function(){
   if(this._updateThread||this._updating){
      /* throttling, if we are awaiting an updatem, cancel that update and queue another
         result will be that the server is contacted only after 1 second without user interaction.
       */
      if(this._updateThread){
         clearTimeout(this._updateThread);
      }
      this._updateThread = setTimeout('window.CartManager._updateThread=null;window.CartManager.updateServer()',1000);
   }else{
      this._updating=true;

      this._updateServerQuantities();
   }
}
_cmp._updateServerQuantities=function(){
      var sQuantities='';
      var sDeleteIDs='';
   
      /* compile id+quantity pairs
         submit new quantities to server */
      /* compile id's of pending delete (quantityt == 0 but deleted = false 
         send list of id's to delete to server */
   
      for(var i in this._orderItems){
         if(this._orderItems[i+'']._quantity==0&&!this._orderItems[i+'']._deleted){
            sDeleteIDs+=this._orderItems[i+'']._id+'|';
         }else{
            sQuantities+=this._orderItems[i+'']._id+':'+this._orderItems[i+'']._quantity+'|';
         }
      }  
      if(!sQuantities){
         /* all item are deleted: just call clearcart, on callback reload cart.asp */
         document.location.href="cart_clear.asp"
      }else{
         $.ajax({
      	   type: "get",
      	   url: "ajax_update_cart.asp?Quantities=" + sQuantities + '&DeleteIDs=' + sDeleteIDs+'&ms='+(new Date().getTime()),
      	   dataType: "xml",
      	   error: function(msg){
      		   jAlert('error:'+msg.status+' : '+msg.statusText+' : '+msg.responseText,'Communications Error');
      		},
      	   success: function(xmlDocument){
      	      $('deletedid',xmlDocument).each(function(){
                  window.CartManager._orderItems[$(this).attr('value')+'']._deleted=true;
                  
      	      });
               window.CartManager._updateDisplay();
      	   }
   	   });
      }
}
_cmp._updateDisplay=function(){
   /* iterate orderitems, set quantity display, subtotal display */
   window.CartManager.subTotal=0;
   $('.OrderItemID').each(function(i){
      var nID = $(this).val();
      var o = window.CartManager._orderItems[nID+''];
      if(o._quantity!=0){
         o.updateDisplay();
         if(o._onsale){
         	window.CartManager.subTotal+=o._subTotal_sale;
      	}else{
         	window.CartManager.subTotal+=o._subTotal;
         }
      }
   });
	$('#OrderSubTotal').html('$'+CurrencyFormatted(window.CartManager.subTotal));
   /* update subtotal, taxes, eParcel (if option selected), total */
   this._updating=false;
}

/*
=====================================================================
*/
/* OrderItem Object def */
function _orderItem(nId){
   this._id=nId;

   this._price=0;
   this._sale_price=0;
   this._onsale=0;
   this._subTotal=0;
   this._subTotal_sale=0;

   this._subTotalLayer=null;

   this._quantity=0;
   this._quantityLayer=null;

   this._name='';
   this._deleted=false;
}
var _oip = _orderItem.prototype;

_oip._init=function(){
   this._quantityLayer = $('#QuantityLayer'+this._id);

   this._quantity = parseInt(this._quantityLayer.text());
   this._subTotalLayer = $('#subTotal'+this._id);

   this._price = parseFloat($('#ProductPrice'+this._id).val());
   this._sale_price = parseFloat($('#ProductSalePrice'+this._id).val());
   this._onsale = (this._sale_price>0) ? 1 : 0;
   this._name = $('#ProductName'+this._id).text();
   this._subTotal = parseFloat(this._price*this._quantity);
   if(this._onsale){
   	this._subTotal_sale = parseFloat(this._sale_price*this._quantity);	
   }
}
_oip.addOne=function(){
   if(this._quantity){
      this._quantity+=1;
      this.updateData();
   }
}
_oip.subOne=function(){
   if(this._quantity>1){
      this._quantity-=1;
      this.updateData();
      return true;   //did change
   }else{
      return false;  //didn't change
   }
}
_oip._delete=function(){
   if(this._quantity){
      $('#o'+this._id).remove();
      this._quantity=0;
   }
}
_oip.updateData=function(){
   if(this._quantity){
	   if(this._onsale){
	   	this._subTotal_sale = parseFloat(this._sale_price*this._quantity);	
	   }
      this._subTotal = parseFloat(this._price*this._quantity);
      this.updateDisplay();
   }
}
_oip.updateDisplay=function(){
   if(this._quantity){
   	if(this._onsale){
      	this._subTotalLayer.html('<font color="red" style="font-size: 10px; text-decoration:line-through"><em>$'+CurrencyFormatted(this._subTotal)+'</em></font>'+
				'<br /><font color="green"><strong>$'+CurrencyFormatted(this._subTotal_sale)+'</strong></font>');
   	}else{
      	this._subTotalLayer.text('$'+CurrencyFormatted(this._subTotal));
      }
     	this._quantityLayer.text(this._quantity);
   }
}

/* ------------------------------------ */

  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 CommaFormatted(s);
   }
   // end of function CurrencyFormatted()
   
   function CommaFormatted(amount)
   {
   	var delimiter = ","; // replace comma if desired
   	var a = amount.split('.',2)
   	var d = a[1];
   	var i = parseInt(a[0]);
   	if(isNaN(i)) { return ''; }
   	var minus = '';
   	if(i < 0) { minus = '-'; }
   	i = Math.abs(i);
   	var n = new String(i);
   	var a = [];
   	while(n.length > 3)
   	{
   		var nn = n.substr(n.length-3);
   		a.unshift(nn);
   		n = n.substr(0,n.length-3);
   	}
   	if(n.length > 0) { a.unshift(n); }
   	n = a.join(delimiter);
   	if(d.length < 1) { amount = n; }
   	else { amount = n + '.' + d; }
   	amount = minus + amount;
   	return amount;
   }
   // end of function CommaFormatted()