if(MooTools){
   window.addEvent('domready',function(){
      
      //$('productCartForm').addEvent('submit', function(e){
         // Stops the submission of the form.
      //	new Event(e).stop();
   //	});

if($chk($('shopCartForm'))){
   $('shopCartForm')
      .getElements('input.oProductsQty')
      .addEvents({
            'mouseenter':function(){ this.select();},
            'mouseout':function(){ this.onchange();}
         });
   $('shopCartForm').getElements('input.oProductsQty').addEvent('keypress',function(e){ 
      if(e.keyCode==40 && this.value>1){	--this.value;	}
      if(e.keyCode==38 && this.value<50){ ++this.value; }
   });
   
                        
}			

/*
 * SHOP PAGE
 */

AddToCart=function(id){
   if ($('alertbox'))
      $('alertbox').remove();

   var url='index.php?option=com_jdm&view=cart&task=saveCart&format=raw';
   var div  = new Element('div', {id: 'alertbox'});
   var myFx = new Fx.Style(div, 'opacity',  {duration: 4000, transition: Fx.Transitions.linear});
   $('productCartForm').setProperty('action',url);
   $('productCartForm').getElement('input[name=pid]').setProperty('value',id);
   $('productCartForm').send({	
      onRequest: function(){ },
      onComplete: function(response) { 
         div.setText("Product has been added to cart");
         $('cartBox').setText(response);
         div.injectBefore($('cartMessage'));
         myFx.start(1,0);
         (function() {div.remove();}).delay(2500);
      },
      onFailure: function(){
         div.setStyle('color', 'red');
         div.setHTML("Failed to Save to Cart. <br/> Try Again!");
         div.injectBefore($('product-cart'));
         myFx.start(1,0);
         (function() {$('alertbox').remove();}).delay(2500);
      }
   });
}

AddToWishList=function(id){
   if ($('alertbox'))
      $('alertbox').remove();

   var url='index.php?option=com_jdm&view=wishlist&task=saveWish&format=raw';
   var div  = new Element('div', {id: 'alertbox'});
   var myFx = new Fx.Style(div, 'opacity',  {duration: 4000, transition: Fx.Transitions.linear});
   $('productCartForm').setProperty('action',url);
   $('productCartForm').getElement('input[name=pid]').setProperty('value',id);
   $('productCartForm').send({		
      onComplete: function(response) { 
         div.setText("Product has been added to wishlist");
         $('wishBox').setText(response);
         div.injectBefore($('cartMessage'));
         myFx.start(1,0);
         (function() {div.remove();}).delay(2500);
      },
      onFailure: function(){
         div.setStyle('color', 'red');
         div.setHTML("Failed to Save to WishList.<br/> Available to Registered User Only.");
         div.injectBefore($('product-cart'));
         myFx.start(1,0);
         (function() {div.remove();}).delay(2500);
      }
   });
}

/*
 * WISHLIST PAGE
 */

/*DeleteWish=function(id){
   
   var url='index.php?option=com_jdm&view=wishlist&task=deleteWish&format=raw';
   $('wishListForm').setProperty('action',url);
   $('wishListForm').getElement('input[name=pid]').setProperty('value',id);
   $('wishListForm').send({		
      onComplete: function(response) { 
         $('wishBox').setText(response);
      },
      onFailure: function(){
         alert('Failed to Delete to WishList. \n Try Again!');
      }
   });
   
   var row='row-'+id;
   var  myFx = new Fx.Style($(row), 'opacity',  {duration: 1000, transition: Fx.Transitions.linear});
   myFx.start(1,0).chain(function(){
      myFx.start(0,1);
   }).chain(function(){		
      myFx.start(1,0);
   });
   (function() {$(row).remove();}).delay(4000);
   
   
   
}*/

DeleteWish=function(id){
   
   var url='index.php?option=com_jdm&view=wishlist&task=deleteWish&format=raw';
   $('wishListForm').setProperty('action',url);
   $('wishListForm').getElement('input[name=pid]').setProperty('value',id);
   $('wishListForm').send({		
      onComplete: function(response) { 
         $('wishBox').setText(response);
      },
      onFailure: function(){
         alert('Failed to Delete to WishList. \n Try Again!');
      }
   });
   
   var row='row-'+id;
   var  myFx = new Fx.Style($(row), 'opacity',  {duration: 1000, transition: Fx.Transitions.linear});
   myFx.start(1,0);
   (function() {$(row).remove();}).delay(1000);
}


AddItToCart = function(id){
   var url='index.php?option=com_jdm&view=cart&task=saveCart&format=raw';
   $('wishListForm').setProperty('action',url);
   $('wishListForm').getElement('input[name=pid]').setProperty('value',id);
   $('wishListForm').send({	
      onRequest: function(){ },
      onComplete: function(response) { 
         DeleteWish(id);
         $('cartBox').setText(response);
      },
      onFailure: function(){
         alert('Failed to Save to Cart. \n Try Again!');
      }
   });
}

DisplaySummary = function(value){
   var total = $('summaryPrice').value.toFloat();
   var text  = " + ";

   if (value == 1)
      var idValue = $('fastwayPrice').value.toFloat();
   else
      var idValue = $('auspostPrice').value.toFloat();

   var summary = (total + idValue);

   if (idValue == 0)
      text+= "Delivery (Please contact admin for delivery cost)";
   else
      text+= "$ " + idValue + " = $ " + moneyFormat(summary);

   $('summary').setText(text);
}

/*
* SHOPPING CART PAGE
*/


DeleteFromCart=function(id){
// Lets Submit the Form
var url='index.php?option=com_jdm&view=cart&cid='+id;
$('shopCartForm').setProperty('action', url);
$('shopCartForm').getElement('input[name=task]').setProperty('value','deleteFromCart');
$('shopCartForm').submit();
   
}

ChangeQty = function(obj){
   var curQty=obj.value;
   if (isNaN(curQty) || curQty<0){
      alert('Only Numbers between 0-99 allowed.');
      obj.focus();
   }

} //end function


CheckOutCart=function(){	
   $('shopCartForm').getElement('input[name=task]').setProperty('value','checkoutCart');
   //var url='index.php?option=com_jdm&view=cart&p=checkout';	
   //$('shopCartForm').setProperty('action',url);
   $('shopCartForm').submit();
}



/*
 * CHECKOUT
 */

DisplayDiscount = function(values){
   
   condition = true;
   values     = values.toInt();
   
   if (values != 0 && values != 500 && values != 1000)
   {
      condition = false;
      alert("Error: No Such Value");
   }

   if (condition)
   {
      var dRate      = (values == 500) ? 0.05 : 0.1;
      //var points     = $('loyaltyPoints').getText().toInt();
      var points     = $('loyaltyPoints').value.toInt();
      var newPoints  = $('lTotal').getText().clean().toInt();
      var grandTotal = $('sTotal').getText().clean();
      var grandTotal = grandTotal.replace("$ ", "");
      var grandTotal = grandTotal.replace(",", "");
      var grandTotal = grandTotal.toFloat();
      var total      = points - values + newPoints;
      var totalZero  = points + newPoints;
      var discount   = grandTotal * dRate;
      var summary    = grandTotal - discount;
      var text       = points + " - " + values + " + " 
                                      + newPoints + " = " + total;
      var textZero   = points + " + " + newPoints + " = " + totalZero;

      if (values == 0)
      {
         $('discountRate').setText("");
         $('loyaltyTotal').setText(textZero);
         $('grandTotalPrice').setText("$ " + moneyFormat(grandTotal));
         $('allTotal').setText("$ " + moneyFormat(grandTotal));
         $('summaryPrice').value = grandTotal;
         DisplaySummaryCart(1, "code", grandTotal);
      }
      else
      {
         $('discountRate').setText("$ " + moneyFormat(discount));
         $('loyaltyTotal').setText(text);
         $('grandTotalPrice').setText("$ " + moneyFormat(summary));
         $('allTotal').setText("$ " + moneyFormat(summary));
         $('summaryPrice').value = summary;
         DisplaySummaryCart(1, "code", summary);
      }

      if (values == 0)
         $('dsc').value = 0;
      else if (values == 500)
         $('dsc').value = 1;
      else if (values == 1000)
         $('dsc').value = 2;
   }
}

DisplaySummaryCart = function(value, from, total){

   if (from == "html")
      total = $('summaryPrice').value.toFloat();

   //var text  = "$" + moneyFormat(total) + " + ";

   if (value == 1)
   {
      var tempIdValue = $('shipPriceF').value.toFloat();
      var idValue = (tempIdValue == -1) ? 0 : tempIdValue;
   }
   else
      var idValue = 0;

   var summary = (total + idValue);

   var text = "$ " + moneyFormat(summary);

   if (value == 3)
   {
      //text+= "PICK UP";
      $('pickupInfo').removeClass('displaynone');
      $('shipPrice').addClass('displaynone');
   }
   else
   {
      $('pickupInfo').addClass('displaynone');
      $('shipPrice').removeClass('displaynone');
      /*if (idValue == 0)
         text+= "Delivery [Please contact admin for delivery cost]";
      else
         text+= "$" + moneyFormat(summary);*/
         //text+= "$" + idValue + " = AUD $" + moneyFormat(summary);
   }

   $('totalAll').setText(text);
}

ShowShipInfo = function(){
   if($('shipInfo').getStyle('display') == 'none')
   {
      var suburbTarget   = $('targetSuburb').value;
      var postcodeTarget = $('targetPostcode').value;
      var suburbS        = $('S_city').value;
      var postcodeS      = $('S_postcode').value;

      $('shipInfo').removeClass('displaynone');

      if($('billShipCost').getStyle('display') == 'block')
         $('billShipCost').setStyle('display','none');

      if (suburbTarget != suburbS || postcodeTarget != postcodeS)
         $('DeliveryCostBtn').setStyle('display','block');
   }
   else
   {
      var buttonPressed = $('buttonPressed').value;

      if (buttonPressed > 0)
      {
         $('buttonPressed').value = 0;
         $('billShipCost').setStyle('display','block');
      }
      $('shipInfo').addClass('displaynone');
   }
}

ShowDelivery = function(target){
   if (target == "bill")
   {
      if($('billShipCost').getStyle('display') == 'none' && $('shipping_info').checked)
          $('billShipCost').setStyle('display','block');
   }
   else if (target == "send")
   {
      if($('DeliveryCostBtn').getStyle('display') == 'none')
          $('DeliveryCostBtn').setStyle('display','block');
   }
}

empty = function(value){
   if (value == "" || value == null)
      return true;
   else
      return false;
}

CartValidation = function(){
   var condition = true;
   var bEmail    = $('B_email').value;
   var bAddress  = $('B_address').value;
   var bSuburb   = $('B_city').value;
   var bPostcode = $('B_postcode').value;
   var bCountry  = $('B_country').value;
   var sEmail    = $('S_email').value;
   var sAddress  = $('S_address').value;
   var sSuburb   = $('S_city').value;
   var sPostcode = $('S_postcode').value;
   var sCountry  = $('S_country').value;
   var message   = "";

   if (empty(bEmail) || empty(bAddress) || empty(bSuburb) || empty(bPostcode) || empty(bCountry))
      message = "Please Fill All The Form indicate by *<br/>";

   if (!$('shipping_info').checked)
   {
      if (empty(sEmail) || empty(sAddress) || empty(sSuburb) || empty(sPostcode) || empty(sCountry))
         message = "Please Fill All The Form indicate by *<br/>";
   }

   if (!$('shipCompanyC').checked && !$('shipCompanyP').checked)
      message+= "Please Choose Delivery Method<br/>";

   if (!$('terms-acceptance').checked)
      message+= "Please Agree With Term And Condition<br/>";

   if (!$('information-read').checked)
      message+= "Please Read Delivery And Payment Information Provided<br/>";

   return message;
}

ConfirmCart = function (){
   var message     = CartValidation();
   var winScroller = new Fx.Scroll(window);

   if (!empty(message))
   {
      winScroller.toTop();
      $('errorMessage').setHTML(message + "<br/>");
      $('errorMessage').setStyle('display','block');
      (function(){ $('errorMessage').setStyle('display','none'); }).delay(4000);

      return false;
   }
   else
   {
      var suburbTarget   = $('targetSuburb').value;
      var postcodeTarget = $('targetPostcode').value;
      var suburbS        = $('S_city').value;
      var postcodeS      = $('S_postcode').value;
      var suburb         = $('B_city').value;
      var postcode       = $('B_postcode').value;
      var text           = "<h4 class='r'>You have to update delivery cost by pressing " +
                           "the 'update delivery cost' button<br/>Please Wait, delivery " + 
                           "cost will be updated automatically</h4>";

      if (!$('shipping_info').checked)
      {
         if (suburbS != suburbTarget || postcodeS != postcodeTarget)
         {
            winScroller.toElement('billInfo');
            $('deliveryMessage').setStyle('display','block');
            $('deliveryMessage').setHTML(text);
            GetShipCost("send");
            (function(){ $('deliveryMessage').setStyle('display','none'); }).delay(4000);
            return false;
         }
         else
            return true;
      }
      else
      {
         if (suburb != suburbTarget || postcode != postcodeTarget)
         {
            winScroller.toElement('billInfo');
            $('deliveryMessage').setStyle('display','block');
            $('deliveryMessage').setHTML(text);
            GetShipCost("bill");
            (function(){ $('deliveryMessage').setStyle('display','none'); }).delay(4000);
            return false;
         }
         else
            return true;
      }
   }
}

GetShipCost = function(type){

   if (type == "send")
   {
      var suburb   = $('S_city').value;
      var postcode = $('S_postcode').value;
      var button   = $('buttonPressed').value;
      $('buttonPressed').value = button + 1;
      $('DeliveryCostBtn').setStyle('display','none');
   }
   else if (type == "bill")
   {
      var suburb   = $('B_city').value;
      var postcode = $('B_postcode').value;
      $('billShipCost').setStyle('display','none');
   }

   $('targetSuburb').value   = suburb;
   $('targetPostcode').value = postcode;
   var weight                = $('totalWeight').value;
   var target                = $('shipPrice');
   var totalItems            = $('totalItems').value;

   if (suburb == "" || postcode == "" || weight == "")
   {
      alert("Please Fill Suburb And Postcode");
   }
   else
   {
      if ($('shipCompanyC').getProperty('checked'))
         $('shipCompanyC').removeProperty('checked');

      $('totalAll').setText("Please choose delivery method");

      target.setText("Loading...");

      var url      = 'index.php?option=com_jdm&view=cart&task=getShipCost&format=raw&sub='+ 
                     suburb + '&zip=' + postcode + '&weight=' + weight + '&totalItems=' + totalItems;
      var myAjax   = new Ajax( url,{ method: 'get', update: target});

      myAjax.request();
   }
}

 
/* PLACE ORDER */

 recalculate= function(shipping, total){

    var gt=parseInt(shipping) + parseInt(total);
   $('shippingcharge').setText('$ '+moneyFormat(shipping)+ ' (Shipping Charge)* = $ '+moneyFormat(gt));
   
 }




_getContent=function (alink, container){	
      var url = alink + '&task=getVehicleModel&format=raw';
      var myAjax= new Ajax( url,{ method: 'get', update: container});
      myAjax.request();
      return myAjax;

   }


}); // DOMREADY
} //endif





//---------------------------------------------------------------------||
//FUNCTION:    MoneyFormat                                            ||
//PARAMETERS:  Number to be formatted                                 ||
//RETURNS:     Formatted Number                                       ||
//PURPOSE:     Reformats Dollar Amount to #.## format                 ||
//---------------------------------------------------------------------||
function moneyFormat(input) {
var dollars = Math.floor(input);
var tmp = new String(input);

for ( var decimalAt = 0; decimalAt < tmp.length; decimalAt++ ) {
   if ( tmp.charAt(decimalAt)=="." )
      break;
}

var cents  = "" + Math.round(input * 100);
cents = cents.substring(cents.length-2, cents.length)
        dollars += ((tmp.charAt(decimalAt+2)=="9")&&(cents=="00"))? 1 : 0;

if ( cents == "0" )
   cents = "00";

return(dollars + "." + cents);
}

//---------------------------------------------------------------------||
//FUNCTION:    SetCookie                                              ||
//PARAMETERS:  name, value, expiration date, path, domain, security   ||
//RETURNS:     Null                                                   ||
//PURPOSE:     Stores a cookie in the users browser                   ||
//---------------------------------------------------------------------||
function SetCookie (name,value,expires,path,domain,secure) {
document.cookie = name + "=" + escape (value) +
                  ((expires) ? "; expires=" + expires.toGMTString() : "") +
                  ((path) ? "; path=" + path : "") +
                  ((domain) ? "; domain=" + domain : "") +
                  ((secure) ? "; secure" : "");
}



