var COUPON_ALREADY_APPLIED           = "Only one coupon allowed per order. Please remove existing coupon before entering a new coupon."
var OUTOFORDERQUANTITYMSG            = 'Sorry, quantity is out of stock.';
var INVALIDQUANTITY                  = 'Please, put a valid quantity.';
var PROMPT_DELETE_CONFIRM            = 'Are you sure you want to remove this item from your cart?';
var PROMPT_EMPTY_QUANTITY            = 'Sorry, quantity can not be empty.';
var PROMPT_INVALID_QUANTITY          = 'Please provide a valid quantity.';
var PROMPT_EXCEED_AVAILABLE_QUANTITY = 'Sorry, this quantity is not available.';
var PROMPT_REMOVE_COUPON             = 'Are you sure you want to remove this coupon?';
var SHOW_CART_ON_ITEM_ADD_EVENT      = '';
var INVALID_ZIP_CODE                 = 'Please provide valid zip code.';
var INVALID_STATE                    = 'Please provide valid state.';
var US_ZIP_CODE_PATTERN              = /^\d{5}$|^\d{5}-\d{4}$/;
var VISA_CARD_PATTERN                = /^(4\d{12}(?:\d{3})?)$/;
var MASTER_CARD_PATTERN              = /^5[1-5][0-9]{14}$/;
var DISCOVER_CARD_PATTERN            = /^6(?:011|5[0-9]{2})[0-9]{12}$/;
var AMEX_CARD_PATTERN                = /^3[47][0-9]{13}$/;
var REQUIRE_LOG_IN                   = 1;
var DOEST_NOT_REQUIRE_LOG_IN         = 0;
var COUPON_PRODUCT_RULES_MSG         = 'For coupon discount, please add any of the following items with minimum quantity';
SHOW_ANIMATION_WHEN_ADD_TO_CART      = '';
modifiedProductAttrQueryStr          = '';
selectedProductOptions               = '';
var USASTATES    = new Array();
var CANADASTATES = new Array();

function makeProductAttributesQueryString(productId)
{
   var productAttributesQueryString = '';
   selectedProductOptions           = '';
   var productDataInfo = "action=ret_product_attributes&product_id="+productId;
   $.ajax({
      type: "POST",
      url: "/cart.php",
      data: productDataInfo,
      dataType:"json",
      async: false,
      success: function(attributeNames)
               {
                  for(var i=0; i<attributeNames.length; i++)
                  {
                     if(attributeNames[i].option_type=='Radio')
                     {
                        var optionVal = '';
                        for(var suffix = 0; suffix<attributeNames[i].total_options; suffix++)
                        {
                           if($('#'+attributeNames[i].option_name+'_'+suffix).is(':checked'))
                           {
                              optionVal = $('#'+attributeNames[i].option_name+'_'+suffix).val();
                              productAttributesQueryString+= '&'+attributeNames[i].option_name+'='+optionVal;
                              selectedProductOptions+= '#'+attributeNames[i].option_name+'_'+$('#'+attributeNames[i].option_name+'_'+suffix).next('.label').text();
                              break;
                           }
                        }
                     }
                     else if(attributeNames[i].option_type=='Checkbox')
                     {
                        var optionVal = '';
                        for(var suffix = 0; suffix<attributeNames[i].total_options; suffix++)
                        {
                           if($('#'+attributeNames[i].option_name+'_'+suffix).is(':checked'))
                           {
                              optionVal = $('#'+attributeNames[i].option_name+'_'+suffix).val();
                              productAttributesQueryString+= '&'+attributeNames[i].option_name+'_'+suffix+'='+optionVal;
                              selectedProductOptions+= '#'+attributeNames[i].option_name+'-'+suffix+'_'+$('#'+attributeNames[i].option_name+'_'+suffix).next('.label').text();
                           }
                        }
                     }
                     else if(attributeNames[i].option_type=='Text')
                     {
                        if($('#optionvalue_'+attributeNames[i].id).val().length > 0)
                        {
                           productAttributesQueryString+= '&'+attributeNames[i].option_name+'='+$('#optionvalue_'+attributeNames[i].id).val();
                           selectedProductOptions+= '#'+attributeNames[i].option_name+'_'+$('#optionvalue_'+attributeNames[i].id).val();
                        }
                     }
                     else if(attributeNames[i].option_type=='File')
                     {
                        if(($('#file_'+attributeNames[i].option_name).val().length > 0) || ($('#'+attributeNames[i].option_name).val().length > 0))
                        {
                           productAttributesQueryString+= '&'+attributeNames[i].option_name+'='+$('#file_'+attributeNames[i].option_name).val();
                           selectedProductOptions+= '#'+attributeNames[i].option_name+'_'+$('#'+attributeNames[i].option_name).val();
                        }
                     }

                     else
                     {
                        productAttributesQueryString+= '&'+attributeNames[i].option_name+'='+$('#'+attributeNames[i].option_name).val();
                        optionVal = ($('#'+attributeNames[i].option_name+' :selected').text()) ? $('#'+attributeNames[i].option_name+' :selected').text()
                                                                                               : $('#optionvalue_'+attributeNames[i].id).val();

                        selectedProductOptions+= '#'+attributeNames[i].option_name+'_'+optionVal;
                     }

                  }

               }
    });

   return productAttributesQueryString;
}

function eraseCookie(name) {
   document.cookie = name +'=; expires=Thu, 01-Jan-70 00:00:01 GMT;';	
}


function addTOCart(productId, sku, availableQunatity, fieldId,sourceId,destinationId,imagePrefix)
{
   eraseCookie('jewelrysupply_cart_items_count');
   eraseCookie('jewelrysupply_cart_total');
   
   var quantity = parseInt(document.getElementById(fieldId).value, 10);

   if((quantity <= 0) || isNaN(quantity))
   {
      alert(INVALIDQUANTITY);
      return false;
   }

   if(availableQunatity <= 0)
   {
      alert(OUTOFORDERQUANTITYMSG);
      return false;
   }

   productAttrQueryStr = makeProductAttributesQueryString(productId);

   var productDataInfo = "action=add&product_id="+productId
                       +"&sku="+sku+"&quantity="+quantity+productAttrQueryStr
                       +"&selected_options="+selectedProductOptions;

   $.ajax({
      type: "POST",
      url: "/cart.php",
      data: productDataInfo,
      dataType:"json",
      success: function(cartInfo)
               {
                  document.getElementById('shopping_cart_items').innerHTML = cartInfo.items;
                  document.getElementById('shopping_cart_sub_total').innerHTML = '$'+cartInfo.sub_total;

                  if(cartInfo.cart_status != 'ok')
                  {
                     alert(cartInfo.cart_status);
                  }
                  else
                  {
                  	if(SHOW_CART_ON_ITEM_ADD_EVENT == 'Yes')
                  	{
                  		//document.location.href = '/cart.php?action=view_cart_details&product_id='+productId;
                  		document.location = '/cart.php?action=view_cart_details&product_id='+productId;
                  	}
                  }
               }
    });
    setCheckOut();

    if(SHOW_ANIMATION_WHEN_ADD_TO_CART === 'Yes')
    {
       if(typeof(imagePrefix) != 'undefined') 
       {
          sourceId = imagePrefix+'_'+sourceId;
       }
       
       showAnimationWhenAddToCart(sourceId,destinationId);
    }
}

function setCheckOut()
{
   var checkOutProcess = null;
   var params = "action=check_out_process";
   $.ajax({
      type   : "POST",
      url    : "/checkout.php",
      data   : params,
      dataType : "json",
      success: function(checkOutProcess)
               {

                      if(checkOutProcess.require_authentication == DOEST_NOT_REQUIRE_LOG_IN)
                      {
                         if(document.getElementById('chk_out'))
                         {
                            $("#chk_out").remove();
                            $("#span_view_cart").append('<a href="'+HTTPS_SERVER+'/checkout.php?action=show_order_checkout" id="new_chk_out"><img src="/theme/default/images/checkout.png" alt="Start Checkout"/></a>');
                         }
                         else if(document.getElementById('new_chk_out'))
                         {
                            $("#new_chk_out").remove();
                            $("#span_view_cart").append('<a href="'+HTTPS_SERVER+'/checkout.php?action=show_order_checkout" id="chk_out"><img src="/theme/default/images/checkout.png" alt="Start Checkout"/></a>');
                         }
                      }
                      else if(checkOutProcess.require_authentication == REQUIRE_LOG_IN)
                      {
                         if(checkOutProcess.show_popup_login=='Yes')
                         {
                            if(checkOutProcess.shipping_checkout_method == 'TRADITIONAL')
                            {
                               if(document.getElementById('chk_out'))
                               {
                                  $("#chk_out").click(function(e)
                                  {
                                     e.preventDefault();
                                     tb_show(" ", "/checkout.php?height=400&width=603&action=show_traditional_checkout_screen&modal=true");
                                  });
                               }
                               else if(document.getElementById('new_chk_out'))
                               {
                                   $("#new_chk_out").click(function(e)
                                  {
                                     e.preventDefault();
                                     tb_show(" ", "/checkout.php?height=400&width=603&action=show_traditional_checkout_screen&modal=true");
                                  });
                               }
                            }
                            else if(checkOutProcess.shipping_checkout_method == 'FAST')
                            {
                               if(document.getElementById('chk_out'))
                               {
                                  $("#chk_out").remove();
                                  $("#span_view_cart").append('<a href="/checkout.php?action=show_fast_checkout_screen" id="new_chk_out"><img src="/theme/default/images/checkout.png" alt="Start Checkout"/></a>');
                               }
                               else if(document.getElementById('new_chk_out'))
                               {
                                  $("#new_chk_out").remove();
                                  $("#span_view_cart").append('<a href="/checkout.php?action=show_fast_checkout_screen" id="chk_out"><img src="/theme/default/images/checkout.png" alt="Start Checkout"/></a>');
                               }
                            }
                          }
                          else
                          {
                             if(checkOutProcess.shipping_checkout_method == 'TRADITIONAL')
                             {
                                if(document.getElementById('chk_out'))
                                {
                                   $("#chk_out").remove();
                                   $("#span_view_cart").append('<a href="'+HTTPS_SERVER+'/checkout.php?action=show_login_screen" id="new_chk_out"><img src="/theme/default/images/checkout.png" alt="Start Checkout"/></a>');
                                }
                                else if(document.getElementById('new_chk_out'))
                                {
                                   $("#new_chk_out").remove();
                                   $("#span_view_cart").append('<a href="'+HTTPS_SERVER+'/checkout.php?action=show_login_screen" id="chk_out"><img src="/theme/default/images/checkout.png" alt="Start Checkout"/></a>');
                                }
                             }
                             else if(checkOutProcess.shipping_checkout_method == 'FAST')
                             {
                                if(document.getElementById('chk_out'))
                                {
                                   $("#chk_out").remove();
                                   $("#span_view_cart").append('<a href="/checkout.php?action=show_fast_checkout_screen" id="new_chk_out"><img src="/theme/default/images/checkout.png" alt="Start Checkout"/></a>');
                                }
                                else if(document.getElementById('new_chk_out'))
                                {
                                   $("#new_chk_out").remove();
                                   $("#span_view_cart").append('<a href="/checkout.php?action=show_fast_checkout_screen" id="chk_out"><img src="/theme/default/images/checkout.png" alt="Start Checkout"/></a>');
                                }
                             }
                          }
                      }
                  }
         });
}

function getProductQuantityInStock(productId)
{

}

function ReadCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function cartStatus()
{
   if(ReadCookie('jewelrysupply_cart_items_count') && ReadCookie('jewelrysupply_cart_total'))
   {
      document.getElementById('shopping_cart_items').innerHTML     = ReadCookie('jewelrysupply_cart_items_count') == null ? 0 : ReadCookie('jewelrysupply_cart_items_count');
      document.getElementById('shopping_cart_sub_total').innerHTML = '$'+ReadCookie('jewelrysupply_cart_total');

      return;
   }

   var cartDataInfo = "action=show_header_cart_status";
   $.ajax({
      type: "POST",
      url: "/cart.php",
      data: cartDataInfo,
      dataType:"json",
      success: function(cartInfo)
               {
                  document.getElementById('shopping_cart_items').innerHTML     = cartInfo.items == null ? 0 : cartInfo.items;
                  document.getElementById('shopping_cart_sub_total').innerHTML = '$'+cartInfo.sub_total;

                  SHOW_CART_ON_ITEM_ADD_EVENT      = cartInfo.view_cart;
                  SHOW_ANIMATION_WHEN_ADD_TO_CART  = cartInfo.show_animation;
                  SHOW_MINI_CART                   = cartInfo.show_mini_cart;

                  if(cartInfo.cart_status != 'ok')
                  {
                     alert(cartInfo.cart_status);
                  }
               }
    });
}

function doConfirm()
{
   return confirm(PROMPT_DELETE_CONFIRM);
}

function calculateSubtotal()
{
   var totalItemsInCart = document.getElementById('total_items').value;
   var subTotal         = 0;

   for(var i=0; i<=totalItemsInCart; i++)
   {
      var itemPrice = document.getElementById('item_price_'+i).innerHTML;
      subTotal     += parseFloat(itemPrice.substr(1,itemPrice.length));

   }
   document.getElementById('subtotal').innerHTML = '$'+subTotal;

}

function isInteger (s)
{
   for (var i = 0; i < s.length; i++)
   {
      var c = s.charAt(i);

      if (!isDigit(c)) return false;
   }

   return true;
}

function isDigit (c)
{
   if((c >= "0") && (c <= "9"))
   {
      return true;
   }

   return false;
}


function validateItemsQuantity(totalItems)
{
   for(var i=0;i<totalItems;i++)
   {
      if(document.getElementById('qty_'+i).value.length < 1)
      {
         alert(PROMPT_EMPTY_QUANTITY);
         document.getElementById('qty_'+i).style.border = "1px solid red";
         return false;
      }
      else
      {
         document.getElementById('qty_'+i).style.border = "1px solid black";
      }

      if(!isInteger(document.getElementById('qty_'+i).value))
      {
         alert(PROMPT_INVALID_QUANTITY);
         document.getElementById('qty_'+i).style.border = "1px solid red";
         return false;
      }
      else
      {
         document.getElementById('qty_'+i).style.border = "1px solid black";
      }

      if(parseInt(document.getElementById('available_qty_'+i).value <= 0))
      {
         alert(PROMPT_EXCEED_AVAILABLE_QUANTITY);
         document.getElementById('qty_'+i).style.border = "1px solid red";
         return false;
      }
      else
      {
         document.getElementById('qty_'+i).style.border = "1px solid black";
      }
    }

    return true;
}

function doFormSubmit()
{
   var totalItems = document.getElementById('total_items').value;

   if(!validateItemsQuantity(totalItems))
   {
      return false;
   }

   document.view_cart_details.submit();
}

function change_border_color(elementId)
{
   document.getElementById(elementId).style.border = "1px solid black";
}

function getDistance(x1,y1,x2,y2)
{
   var x = (x1-x2);
   var y = (y1-y2);
   return Math.sqrt((x*x)+(y*y));
}

function showAnimationWhenAddToCart(sourceId,destinationId)
{
  /*clone the source element*/
   var clonedObject = $('#'+sourceId).clone();
   /*append the cloned element to its actual parent*/
   $('#'+sourceId).parent().append(clonedObject);
   /*oh man, why have to do this? but you need to understand this tormented browser's mind*/
   var sourcePosition = $('#'+sourceId).offset();
   /*find a nice flying spot*/
   $(clonedObject).css({position:"absolute",left:sourcePosition.left, top: sourcePosition.top});
   /*getting the destination position*/
   var destinationPosition = $('#'+destinationId).offset();

   /*little bit of physics is applied for achieving constant animation velocity(acceleration? forget it.), long live Newton.*/
   var distance = getDistance(sourcePosition.left,sourcePosition.top,destinationPosition.left,destinationPosition.top);

   var velocity = CART_CART_ANIMATION_SPEED / 40;
   var time     = distance / velocity;


   /*now calling the animation with appropriate params*/
   $(clonedObject).animate(
   		{
                      left: destinationPosition.left, /*setting the final left position of the element*/
                      top:  destinationPosition.top,  /*setting the final top position of the element*/
                      opacity: 0.4                    /*loosing opacity gradually*/
                      },
                      time,                           /*animation  time*/
                      "linear",                       /*setting the way of moving, other might be swing*/
                      function(){
                         /*finally destroying the cloned element*/
                         $(clonedObject).remove();

                   }
               );
   /*setCheckOut();*/
}

function clearWarningIfAny()
{
   $('#error_container').text('');
}

function validateUSZipCode(zip_code)
{
   if(!US_ZIP_CODE_PATTERN.test(zip_code))
   {
      return false;
   }
   else
   {
      return true;
   }
}

function showShippingInformation(zip_code,country)
{
   if(SHIPPING_QUOTE_TIMEOUT == '0')
   {
      var params = "action=estimate_backup_shipping_cost&country="+country+"&zip_code="+zip_code;
   }
   else
   {
      var params = "action=estimate_shipping_cost&country="+country+"&zip_code="+zip_code;
   }

  //change the absolute path to current theme path.
  //also added a preloader that does not match with current theme or background

  $('#shipping_info_container').html("<img src='"+TEMPLATE_DIRECTORY+"/images/preloader.gif'/>");

  $.ajax({
     timeout: SHIPPING_QUOTE_TIMEOUT*1000,
     type: "POST",
     url: "/cart.php",
     data: params,
     error: function(XMLHttpRequest, textStatus)
            {
               //NOW SEND ANOTHER AJAX CALL TO THE STATIC SHIPPING QUOTE TABLE
               //alert("An error has occurred making the request: " + textStatus);
               var params = "action=estimate_backup_shipping_cost&country="+country+"&zip_code="+zip_code;
               $('#shipping_info_container').html("<img src='"+TEMPLATE_DIRECTORY+"/images/preloader.gif'/>");

               $.ajax({
                  type: "POST",
                  url: "/cart.php",
                  data: params,
                  success: function(shippingInfo)
                           {
                              $('#shipping_info_container').html(shippingInfo);
                           }
               });
            },     
     success: function(shippingInfo)
              {
                 $('#shipping_info_container').html(shippingInfo);
              }
  });

}

function updateShippingInfo()
{
   var zip_code     = jQuery.trim($('#zip_code').val());
   var country      = $('select option:selected').val();

   $.ajax({
             type    : "POST",
             url     : "/checkout.php",
             data    : 'action=is_required_zip&country_id='+country,
             success: function(response)
                      {
	                      if(response == 1)
                         {
                            if(country==223 && !validateUSZipCode(zip_code))
                            {
                               $('#zip_code').val('');
                               $('#error_container').text(INVALID_ZIP_CODE);

                               return false;
                            }
                            else
                            {
                               showShippingInformation(zip_code,country);
                            }
                         }
                         else
                         {
                            showShippingInformation(zip_code,country);
                         }
                      }
         });

}

function isEmptyCart()
{
   if(ReadCookie('jewelrysupply_cart_items_count') == '0' || ! ReadCookie('jewelrysupply_cart_items_count'))
   {
      $("#chk_out").remove();
      $("#span_view_cart").append('<a href="/checkout.php?action=show_empty_check_out_screen" id="new_chk_out"><img src="/theme/default/images/checkout.png" alt="Start Checkout"/></a>');
      //$("#chk_out").attr("href","/checkout.php?action=show_empty_check_out_screen");
   }
   else
   {
      defineCheckOutProcess();
   }

   
   /*
   var params = "action=check_for_empty_cart";

   $.ajax({
      type     : "POST",
      url      : "/checkout.php",
      data     : params,
      dataType : "json",
      success: function(response)
               {
                  if(response.status)
                  {
                     $("#chk_out").remove();
                     $("#span_view_cart").append('<a href="/checkout.php?action=show_empty_check_out_screen" id="new_chk_out"><img src="/theme/default/images/checkout.png" alt="Start Checkout"/></a>');
                     //$("#chk_out").attr("href","/checkout.php?action=show_empty_check_out_screen");
                  }
                  else
                  {
                     defineCheckOutProcess();
                  }
               }
    });
    */
}

function defineCheckOutProcess()
{

   var params = "action=check_out_process";

   $.ajax({
      type    : "POST",
      url     : "/checkout.php",
      data    : params,
      dataType: "json",
      success : function(checkOutProcess)
               {
                  if(checkOutProcess.require_authentication == DOEST_NOT_REQUIRE_LOG_IN)
                  {
                     if(document.getElementById('chk_out'))
                     {
                        $("#chk_out").remove();
                        $("#span_view_cart").append('<a href="'+HTTPS_SERVER+'/checkout.php?action=show_order_checkout" id="new_chk_out"><img src="/theme/default/images/checkout.png" alt="Start Checkout"/></a>');
                     }
                     else if(document.getElementById('new_chk_out'))
                     {
                        $("#new_chk_out").remove();
                        $("#span_view_cart").append('<a href="'+HTTPS_SERVER+'/checkout.php?action=show_order_checkout" id="chk_out"><img src="/theme/default/images/checkout.png" alt="Start Checkout"/></a>');
                     }
                  }
                  else if(checkOutProcess.require_authentication == REQUIRE_LOG_IN)
                  {
                     if(checkOutProcess.show_popup_login=='Yes')
                     {
                        if(checkOutProcess.shipping_checkout_method == 'TRADITIONAL')
                        {
                           if(document.getElementById('chk_out'))
                           {
                              $("#chk_out").click(function(e)
                              {
                                 e.preventDefault();
                                 tb_show(" ", "/checkout.php?height=400&width=603&action=show_traditional_checkout_screen&modal=true");
                              });
                           }
                           else if(document.getElementById('new_chk_out'))
                           {
                               $("#new_chk_out").click(function(e)
                              {
                                 e.preventDefault();
                                 tb_show(" ", "/checkout.php?height=400&width=603&action=show_traditional_checkout_screen&modal=true");
                              });
                           }
                        }
                        else if(checkOutProcess.shipping_checkout_method == 'FAST')
                        {
                           if(document.getElementById('chk_out'))
                           {
                              $("#chk_out").remove();
                              $("#span_view_cart").append('<a href="/checkout.php?action=show_fast_checkout_screen" id="new_chk_out"><img src="/theme/default/images/checkout.png" alt="Start Checkout"/></a>');
                           }
                           else if(document.getElementById('new_chk_out'))
                           {
                              $("#new_chk_out").remove();
                              $("#span_view_cart").append('<a href="/checkout.php?action=show_fast_checkout_screen" id="chk_out"><img src="/theme/default/images/checkout.png" alt="Start Checkout"/></a>');
                           }
                        }
                      }
                      else
                      {
                         if(checkOutProcess.shipping_checkout_method == 'TRADITIONAL')
                         {
                            if(document.getElementById('chk_out'))
                            {
                               $("#chk_out").remove();
                               $("#span_view_cart").append('<a href="'+HTTPS_SERVER+'/checkout.php?action=show_login_screen" id="new_chk_out"><img src="/theme/default/images/checkout.png" alt="Start Checkout"/></a>');
                            }
                            else if(document.getElementById('new_chk_out'))
                            {
                               $("#new_chk_out").remove();
                               $("#span_view_cart").append('<a href="'+HTTPS_SERVER+'/checkout.php?action=show_login_screen" id="chk_out"><img src="/theme/default/images/checkout.png" alt="Start Checkout"/></a>');
                            }
                         }
                         else if(checkOutProcess.shipping_checkout_method == 'FAST')
                         {
                            if(document.getElementById('chk_out'))
                            {
                               $("#chk_out").remove();
                               $("#span_view_cart").append('<a href="/checkout.php?action=show_fast_checkout_screen" id="new_chk_out"><img src="/theme/default/images/checkout.png" alt="Start Checkout"/></a>');
                            }
                            else if(document.getElementById('new_chk_out'))
                            {
                               $("#new_chk_out").remove();
                               $("#span_view_cart").append('<a href="/checkout.php?action=show_fast_checkout_screen" id="chk_out"><img src="/theme/default/images/checkout.png" alt="Start Checkout"/></a>');
                            }
                         }
                      }
                  }
               }
    });


}

function pullCustomerInfo()
{
   var params = "action=pull_customer_info&email="+$('#email').val()+"&password="+$('#password').val();
   $.ajax({
      type     : "POST",
      url      : "/checkout.php",
      data     : params,
      dataType : "json",

      success: function(customerInfo)
               {
                  if(customerInfo)
                  {
                     $('#first_name').val(customerInfo.customer_firstname);
                     $('#last_name').val(customerInfo.customer_lastname);
                     $('#telephone_number').val(customerInfo.customer_telephone);
                     $('#street_address').val(customerInfo.billing_info.entry_street_address_line1);
                     $('#address_line_2').val(customerInfo.billing_info.entry_street_address_line2);
                     $('#select_other_country').val(customerInfo.billing_info.entry_country);

                     $('#city').val(customerInfo.billing_info.entry_city);
                     $('#state').val(customerInfo.billing_info.entry_zone_id);

                     if(customerInfo.customer_newsletter)
                     {
                        $('#receive_monthly_email').attr("checked",true);
                     }

                     $('#zip_code').val(customerInfo.billing_info.entry_zipcode);
                     $('#company_name').val(customerInfo.billing_info.entry_company);
                     $('#fax_number').val(customerInfo.customer_fax);
                     $('#resale_number').val(customerInfo.customer_resale_number);
                     resetZipCodeValidationRuleByCountry('zip_code','');
                     populateShippingInfo(customerInfo);
                     $('#confirm_password').val($('#password').val());
                     $('#registration').val('0');
                  }
               }
    });
}

function populateShippingInfo(customerInfo)
{
   $('#shipping_first_name').val(customerInfo.customer_firstname);
   $('#shipping_last_name').val(customerInfo.customer_lastname);
   $('#shipping_telephone_number').val(customerInfo.customer_telephone);
   $('#shipping_street_address').val(customerInfo.billing_info.entry_street_address_line1);
   $('#shipping_address_line_2').val(customerInfo.billing_info.entry_street_address_line2);
   $('#shipping_select_other_country').val(customerInfo.billing_info.entry_country);
   $('#shipping_city').val(customerInfo.billing_info.entry_city);
   $('#shipping_state').val(customerInfo.billing_info.entry_zone_id);

   $('#shipping_zip_code').val(customerInfo.billing_info.entry_zipcode);
   $('#shipping_company_name').val(customerInfo.billing_info.entry_company);
   $('#shipping_fax_number').val(customerInfo.customer_fax);
   $('#shipping_resale_number').val(customerInfo.customer_resale_number);
   resetZipCodeValidationRuleByCountry('shipping_zip_code','');
}

function populateShippingInfoByBillingInfo()
{
   $.ajax({
             type    : "POST",
             url     : "/checkout.php",
             data    : 'action=is_required_zip&country_id='+$('#select_other_country').val(),
             success: function(response)
                      {
	                      if(response == 0)
                         {
                            $('#shipping_zip_code').attr("disabled","true");
                            $("#shipping_zip_code").rules("remove", "required zipCodeUS");
                            $("#shipping_zip_code").removeClass('error');
                            $("#shipping_zip_code").next().remove();
                         }
                         else if(response == 1)
                         {
                            $("#shipping_zip_code").rules("add", "required");
                            if($('#select_other_country').val()=='223')
                            {
                               $("#shipping_zip_code").rules("add", "zipCodeUS");
                            }
                            else
                            {
                               $("#shipping_zip_code").rules("remove", "zipCodeUS");
                               $("#shipping_zip_code").removeClass('error');
                               $("#shipping_zip_code").next('span').children('label').remove();
                            }
                            if($("#shipping_zip_code").next('span').length <= 0)
                            {
                               $("#shipping_zip_code").after('<span class="required_color"> *</span>');
                            }
                            $("#shipping_zip_code").removeAttr('disabled');
                         }
                      }
         });
   $('#shipping_first_name').val($('#first_name').val());
   $('#shipping_last_name').val($('#last_name').val());
   $('#shipping_telephone_number').val($('#telephone_number').val());
   $('#shipping_street_address').val($('#street_address').val());
   $('#shipping_address_line_2').val($('#address_line_2').val());

   $('#shipping_select_other_country').val($('#select_other_country').val());
   $('#shipping_city').val($('#city').val());

   $('#shipping_state').val($('#state :selected').text());
   $('#shipping_zip_code').val($('#zip_code').val());
   $('#shipping_company_name').val($('#company_name').val());
   $('#shipping_fax_number').val($('#fax_number').val());
   $('#shipping_resale_number').val($('#resale_number').val());

}

function toggleShippingInfo()
{
   if($("#ship_to_billing_address").is(':checked'))
   {
      $("#shipping_info_container").hide("slow");
   }
   else
   {
      $("#shipping_info_container").show("slow");
   }
   populateShippingInfoByBillingInfo();
}

function setBillingCountry()
{
   $("#other_country").attr("checked",true);
   $("#other_country").val($("#select_other_country").val());
}

function setShippingCountry()
{
   $("#shipping_other_country").attr("checked",true);
   $("#shipping_other_country").val($("#shipping_select_other_country").val());
}

function submitOrder()
{
   if(validateCreditCardInformation())
   {
     $('#btn_submit_order').hide();
     $('#img_processing_submit_order').show();     
     document.submit_order_frm.submit();     
     
   }
}

function hideFormContents()
{
   $('#tbl_common_border').fadeOut('slow');
   $('form h2').fadeOut('slow');
   $('form p').fadeOut('slow');
   $('form span').not('#toggle_content').fadeOut('slow');
   $('form ol').fadeOut('slow');
   $('#shipping_info_container').fadeOut('slow');
}

function showFormContents()
{
   $('#tbl_common_border').fadeIn('slow');
   $('form h2').fadeIn('slow');
   $('form p').fadeIn('slow');
   $('form span').not('#toggle_content').fadeIn('slow');
   $('form ol').fadeIn('slow');
   $('#shipping_info_container').fadeIn('slow');
   $('#toggle_field').fadeIn('slow');
   $('#submit').next().next('a').remove();
}

function removeRules()
{
   for(var element in validationObj.rules)
   {
      if((element!=='email') || (element!=='password'))
      {
         if(element=='country')
         {
            element='select_other_'+element;
         }
         else if(element=='shipping_country')
         {
            element='shipping_select_other_country';
         }
         if($('#'+element).length > 0)
         {
            $('#'+element).rules('remove');
         }
      }
   }
}

function addElementRules(element,rulesObj)
{
   for(var rule in rulesObj)
   {
      $('#'+element).rules('add',rulesObj);
   }
}

function addRules()
{
   for(var element in validationObj.rules)
   {
      if(element=='country')
      {
         element='select_other_'+element;
      }
      else if(element=='shipping_country')
      {
         element='shipping_select_other_country';
      }
      if($('#'+element).length > 0)
      {
         addElementRules(element,validationObj.rules[element]);
      }
   }
}

function redefineFormViewAndRulesForRegisteredUser()
{
   $('#toggle_field').hide();
   $('#submit').remove();
   $('#toggle_content').html('* <input type="submit" value="submit" id="submit" class="btn_search"><br/>'+
                             '<a style="color:#3B79F5" href="/run.php/Login?cmd=show_request_password_screen">'+
                             'I forgot my password.</a>');

   $('input[name=action]').val('registered_checkout');
   hideFormContents();
   removeRules();
}

function redefineFormViewAndRulesForUnRegisteredUser()
{
   showFormContents();
   $('#email_response_container').text('');
   $('#email_response_container').removeClass('login_info');
   $('#submit').remove();
   $('.btn_submit').html('<input type="submit" value="submit" id="submit" class="btn_search">');
   addRules();
}

function checkEmailExists()
{
   var params = "action=check_if_email_exists&email="+$('#email').val();

   $.ajax({
      type   : "POST",
      url    : "/checkout.php",
      data   : params,
      success: function(response)
               {
                  if(response)
                  {
                     $('#email_response_container').addClass("login_info");
                     $('#email_response_container').text(response);
                     $('#error_msg_container').text('');
                     redefineFormViewAndRulesForRegisteredUser();
                  }
                  else
                  {
                     redefineFormViewAndRulesForUnRegisteredUser();
                  }
               }
    });
}

function checkGuestEmailExists()
{
   var params = "action=check_if_email_exists&email="+$('#email').val();

   $.ajax({
      type   : "POST",
      url    : "/checkout.php",
      data   : params,
      success: function(response)
               {
                  if(response)
                  {
                     $('#email_response_container').addClass("login_info");
                     $('#email_response_container').text(response);

                     $('#toggle_password_field').show();
                      $('#password').rules("add","required");
                     $('#password').focus();

                  }
               }
    });

}
function checkEmailExistsForFirstCheckOut()
{
   var params = "action=check_if_email_exists&email="+$('#email').val();

   $.ajax({
      type   : "POST",
      url    : "/checkout.php",
      data   : params,
      success: function(response)
               {
                  if(response)
                  {
                     $('#email_response_container').addClass("login_info");
                     $('#email_response_container').text(response);

                     $('#toggle_message_field').hide();
                     $('#toggle_confirm_password_field').hide();
                     $('#confirm_password').rules("remove","required");
                     $("#confirm_password").rules("remove", "equalTo");
                  }
               }
    });
}

function setTotalShippingCharge()
{
   var totalShippingCost = parseFloat($('#sub_total').text())+
                           parseFloat($('#shipping_charge').text().substr(1,$('#shipping_charge').text().length))+
                           parseFloat($('#tax').text().substr(1,$('#tax').text().length));

   $('#total').text('$'+totalShippingCost.toPrecision(4));

}

function setTotalCharge()
{
   var totalCost = parseFloat($('#alter_shipping_method_cost').text())+
                   parseFloat($('#tax_rate').text().substr(1,$('#tax_rate').text().length))+
                   parseFloat($('#sub_total').text());

   $('#neat_total').text('$'+totalCost.toPrecision(4));
}

function showOrderSummary(elementId,shippingCharge,shippingModule,methodology,mothodologyTitle,selectService, serviceId)
{
   var shippingCharge = $('#'+shippingCharge).text().substr(1,$('#'+shippingCharge).text().length);

   var params = "action=load_order_total_details&shipping_charge="+shippingCharge+"&module_code="+mothodologyTitle+'&shipping_method='+methodology+'&service_id='+serviceId;

   $.ajax({
     type   : "POST",
     url    : "/checkout.php",
     data   : params,
     dataType : "json",
     success: function(response)
              {
                 if(response)
                 {
                    $('#'+selectedServiceTrId).removeClass('selected');
                    $('#'+selectService).addClass('selected');
                    $('#order_review').html(response.order_review);
                    $('#shipping_module_code').val($('#'+shippingModule).text());
                    $('#shipping_method').val(methodology);
                    $('#shipping_module_code').val(mothodologyTitle);
                    $('#shipping_charges').val(shippingCharge);

                    $('#btn_submit_order').click(function()
                     {
                        submitOrder();
                     });
                    selectedServiceTrId = selectService;
                 }
              }
   });

}
function setShippingInfo(elementId,shippingCharge,shippingModule)
{
   $('#'+elementId).val($('#'+shippingCharge).text().substr(1,$('#'+shippingCharge).text().length));
   $('#shipping_charge').text($('#'+shippingCharge).text());
   $('#shipping_charges').val($('#'+shippingCharge).text().substr(1,$('#'+shippingCharge).text().length));
   $('#shipping_module_code').val($('#'+shippingModule).text());
   $('#alter_shipping_method_name').html('<strong>'+$('#'+shippingModule).text()+':</strong>');
   $('#alter_shipping_method_cost').text($('#'+shippingCharge).text().substr(1,$('#'+shippingCharge).text().length));
   setTotalShippingCharge();
   setTotalCharge();
}

function popUpUpdateBillingInfo()
{
   tb_show('Update Billing Information','/checkout.php?action=ajax_load_billing_address&height=480&width=700');
}

function popUpUpdateShippingInfo()
{
   tb_show('Update Shipping Information','/checkout.php?action=ajax_load_shipping_address&height=480&width=700');
}

function isNumeric(sText)

{
   var validChars = "0123456789.";
   var isNumber=true;
   var Char;


   for (i = 0; i < sText.length && IsNumber == true; i++)
   {
      Char = sText.charAt(i);
      if (validChars.indexOf(Char) == -1)
      {
         isNumber = false;
      }
   }

   return isNumber;
}

function validateCreditCardInformation()
{
   var cc_number = $('#cc_number').val();

   if(PAYMENT_MODULE_PAYMENT_CC_COLLECT_CVV == '1')
   {
      var cc_cvv = $.trim($('#cc_cvv').val());
   }

   //if ((cc_owner.length < 1) || (cc_owner.length < PAYMENT_CC_OWNER_MIN_LENGTH))
   //{
   //
   //	$('#error_container').text("The owner's name of the credit card must be at least 3 characters.");
   //	$('#cc_owner').addClass('error');
   //	return false;
   //}
   if(cc_number.toLowerCase()!= 'call')
   {
      if ((cc_number.length < 1) || (cc_number.length < PAYMENT_CC_NUMBER_MIN_LENGTH))
      {
      	$('#error_container').text(MODULE_PAYMENT_CC_TEXT_JS_CC_NUMBER);
      	$('#cc_number').addClass('error');
      	return false;
      }
   }

   if(PAYMENT_MODULE_PAYMENT_CC_COLLECT_CVV == '1')
   {
   	if(cc_cvv.length > 0)
   	{
   	   if(!/^\d+$/.test(cc_cvv) || (cc_cvv.length < PAYMENT_CC_CVV_MIN_LENGTH))
   	   {
   	      var msg = MODULE_PAYMENT_CC_TEXT_JS_CC_CVV.replace(/#CC_CVV_MIN_LENGTH#/, PAYMENT_CC_CVV_MIN_LENGTH);
   	   	$('#error_container').text(msg);
   	   	$('#cc_cvv').addClass('error');
   	   	return false;
   	   }
   	}
   }

   return true;
}

function hideErrorMark(elementId)
{
   $('#'+elementId).removeClass('error');
   $('#error_container').text('');
}

Array.prototype.in_array = function(p_val) {

	for(var i = 0, l = this.length; i < l; i++) {
		if(this[i] == p_val) {
			return true;
		}
	}
	return false;
}

function selectStatNA(stateId,country)
{
   if($(country).val()== 223 || $(country).val()== 38)
   {
      document.getElementById(stateId).options[0].selected = true;
   }
   else
   {
      document.getElementById(stateId).options[1].selected = true;
   }
}

function selectState(stateId)
{
   document.getElementById(stateId).options[0].selected = true;
}


function selectCountry(state, prefix)
{
   if(USASTATES.in_array(state))
   {
   	if(prefix)
      	$('#'+prefix+'select_other_country').val('223');
      else
      	$('#select_other_country').val('223');
   }
   else if(CANADASTATES.in_array(state))
   {
   	if(prefix)
      	$('#'+prefix+'select_other_country').val('38');
      else
      	$('#select_other_country').val('38');
   }
   else
   {
   	if(prefix)
      	$('#'+prefix+'select_other_country').val('0');
      else
      	$('#select_other_country').val('0');
   }
}

function highlightCreditCardIcon(credit_card_number)
{
   var credit_card_number = credit_card_number.replace(/[^0-9]/g, "");

   if(DISCOVER_CARD_PATTERN.test(credit_card_number))
   {
      $('#discover_card').addClass("highlight");
   }
   else if(VISA_CARD_PATTERN.test(credit_card_number))
   {
      $('#visa_card').addClass("highlight");
   }
   else if(MASTER_CARD_PATTERN.test(credit_card_number))
   {
      $('#master_card').addClass("highlight");
   }
   else if(AMEX_CARD_PATTERN.test(credit_card_number))
   {
      $('#american_express').addClass("highlight");
   }
}

function removeHighlightFromCreditCardIcon()
{
   $('#discover_card').removeClass("highlight");
   $('#visa_card').removeClass("highlight");
   $('#master_card').removeClass("highlight");
   $('#american_express').removeClass("highlight");
}

function removeCoupon()
{
   var shippingCharge     = $('#shipping_charges').val();
   var shippingMethod     = $('#shipping_method').val();
   var shippingModuleCode = $('#shipping_module_code').val();

   var params = 'action=remove_coupon_code&shipping_charge='+shippingCharge+'&shipping_method='+shippingMethod+'&shipping_module_code='+shippingModuleCode;
   if(confirm(PROMPT_REMOVE_COUPON))
   {
      showCouponPreloader();

      $.ajax({
         type     : "POST",
         url      : "/checkout.php",
         data     : params,
         dataType : "json",
         success  : function(response)
                    {
                       if(response.status)
                       {
                          hideCouponPreloader();
                          $('#coupon_code').val('');

                          /*
                          $('#remove_coupon').text(' ');
                          $('#discount_response').text(' ');
                          $('#new_total_response').text(' ');
                          */
                          $('#add_remove_coupon_total_container').html(response.message);
                          
                          
                          if(response.reload_shipping_modules == '1')
                          {						  
						           actionBeforeShippingReload();
                             loadShippingServices();
                          }
                          else
                          {
                           $("#order_review_section_container label[id^=item_discount_container_]").each(function(i, item){
                              item.innerHTML = '';
                              });

                           
                          } 
                          						  

						        //actionBeforeShippingReload();
                          //loadShippingServices();
                       }
                    }
      });
   }
}

function showCouponPreloader()
{
   var pos = $('#apply_button').offset();
   $('#preloader_container').css({left:pos.left + $('#apply_button').width() + 5 , top:pos.top});
   $('#preloader_container').show();
}

function hideCouponPreloader()
{
   $('#preloader_container').hide();
}


function isCouponAlreadyApplied()
{
   var couponCode = $('#coupon_code').val();

   if(!couponCode)
   {
      $('#coupon_code').addClass('error');
      return;
   }

   var params = "action=is_coupon_already_applied";
   $.ajax({
      type    : "POST",
      url     : "/checkout.php",
      data    : params,
      dataType: "json",
      success : function(response)
                {
                   if(response.coupon_apply_status == '1')
                   {
                      alert(COUPON_ALREADY_APPLIED);
                      return true;
                   }
                   else
                   {
                      applyCouponCode();
                   }
                }
         });
}

function applyCouponCode()
{   
   var couponCode         = $('#coupon_code').val();
   var shippingCharge     = $('#shipping_charges').val();
   var shippingMethod     = $('#shipping_method').val();
   var shippingModuleCode = $('#shipping_module_code').val();

   if(!couponCode)
   {
      $('#coupon_code').addClass('error');
      return;
   }

   if($('#coupon_code_error_container').text.length > 0)
   {
      $('#coupon_code_error_container').text(' ');
   }

   var params = 'action=apply_coupon_code&coupon_code='+couponCode+'&shipping_charge='+shippingCharge+'&shipping_method='+shippingMethod+'&shipping_module_code='+shippingModuleCode;
   
   resetHighlightedCartItems();
   showCouponPreloader();

   $.ajax({
      type     : "POST",
      url      : "/checkout.php",
      data     : params,
      dataType : "json",
      success  : function(response)
                 {
                    hideCouponPreloader();
                    if(!response.status)
                    {
                       if(response.items_highlight)
                       {
                          highlightCartItems(response.items);
                       }

                       if(response.items && response.items.length)
                       {                           
                           response.message += getCouponItemContent(response.items);
                       }
                       
                       $('#coupon_code_error_container').html(response.message);
                    }
                    else
                    {
						     //actionBeforeShippingReload();
                       //loadShippingServices();


                       if(response.free_shipping_eligible_coupon == '1')
                       {
                          //$('#add_remove_coupon_total_container').html(response.message);						  
						        actionBeforeShippingReload();
                          loadShippingServices();
                       }
                       else
                       {
                          $('#add_remove_coupon_total_container').html(response.message);
                          var cartItems          = response.cartItems;
                          var discountedItemsSKU = response.discountedItemsSKU;
                          var disCountRate       = response.disCountRate;
                          var onSaleItemsSKU     = response.onSaleItemsSKU;


                          $.each(cartItems,function(i, item){
                           if(discountedItemsSKU.in_array(item.item_sku))
                           {
                              //$("#item_discount_container_"+item.item_sku).html((item.total_price*disCountRate/100).toFixed(2));
                              $("#item_discount_container_"+item.item_sku).html('-$'+item.item_discount);
                           }
                           else
                           {
                              $("#item_discount_container_"+item.item_sku).html('<font color="red">N/A</font>');
                           }
                           });

                          /*
                          $.each(onSaleItemsSKU,function(i, item_sku){
                           
                           $("#item_discount_container_"+item_sku).html('<font color="red">N/A</font>');
                           });
                           */
                       }
                       

                    	  /*
                       $('#coupon_code').val(' ');
                       $('#apply_coupon_response').show();
                       $('#remove_coupon').text('remove');
                       $('#discount_response').html('<strong>'+response.message+'</strong>');
                       $('#new_total_response').html('<strong>'+response.new_total+'</strong>');
                       */
                    }
                 }
    });
}

function clearWarning(elementId)
{
   $('#'+elementId).text(' ');
}

function addNote()
{
   tb_show('Add Note','/checkout.php?action=show_add_note_template&height=200&width=450');
}

function playVideo(relativeVideoPath)
{
	var extension = relativeVideoPath.split('.')[1];

	switch(extension)
	{
	      case 'swf':
         var content = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="300" height="300">\
                           <param name="movie" value="'+relativeVideoPath+'" />\
                           <param name="quality" value="high" />\
                           <param name="play" value="false">\
                           <embed src="'+relativeVideoPath+'" play="false" width="300" height="300" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash"></embed>\
                       </object>';

         break;

         case 'flv':
         var content = '<a href="'+relativeVideoPath+'" id="player"></a>';
         break;
   }

   if(content)
   {
   	if($("#video_popup_container").length)
   	{
   		$("#video_popup_container").remove();
   	}
   	$('body').after('<div id="video_popup_container" style="disply:none;"><div id="div_popup_video" style="disply:none;">'+content+'</p></div></div>');
   	$("#video_popup_container").hide();
   	tb_show("Product Video",'#TB_inline?inlineId=div_popup_video');
   	flowplayer("player", "/ext/FLVPlayer/flowplayer-3.1.4.swf",
   	{
   	clip:
   	{
   	  scaling: 'fit',
        autoPlay: false,
        autoBuffering: false
      },
      onStart: function(clip) {
        document.getElementById('player').style.width = clip.metaData.width +'px';
        document.getElementById('player').style.height = clip.metaData.height +'px';
      }

      });
      
      setTimeout ( "hideThickboxScrolls()", 50 );      
   }
}

function hideThickboxScrolls()
{
    if($('#TB_ajaxContent'))
    {
      $('#TB_ajaxContent').css('overflow','hidden');      
    }
}


function popupWindowEmail(url)
{
   var mywindow = window.open(url, 'popupWindow', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,copyhistory=no,width=600,height=300,screenX=150,screenY=150,top=150,left=150');
   var posX     = (screen.width/2) - (560/2);
   var posY     = (screen.height/2) - (150/2);

   mywindow.moveTo(posX, posY);
}


function popupWindow(url)
{
   var mywindow = window.open(url, 'popupWindow', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,copyhistory=no,width=560,height=290,screenX=150,screenY=150,top=150,left=150');
   var posX     = (screen.width/2) - (560/2);
   var posY     = (screen.height/2) - (150/2);

   mywindow.moveTo(posX, posY);
}


function loadShippingServices()
{
   if(SHIPPING_QUOTE_TIMEOUT == '0')
   {
      var params = "action=ajax_load_backup_shipping_cost_details";
   }
   else
   {
      var params = 'action=ajax_load_shipping_cost_details';
   }

   $.ajax({
      timeout: SHIPPING_QUOTE_TIMEOUT*1000,
      type: "POST",
      url:  "/checkout.php",
      data: params,      
     error: function(XMLHttpRequest, textStatus)
            {
               //NOW SEND ANOTHER AJAX CALL TO THE STATIC SHIPPING QUOTE TABLE
               //alert("An error has occurred making the request: " + textStatus);
               var params = "action=ajax_load_backup_shipping_cost_details";

               $.ajax({
                  type: "POST",
                  url: "/checkout.php",
                  data: params,
                  success: function(response)
                           {
                              $('#shipping_container').html(response);
                           }
               });
            },
      success: function(response)
               {
                  $('#shipping_container').html(response);
               }
   });
}

function previewCCVInfoImage(e)
{
   var pos = $('#link_preview_ccv_info_image').offset();

	$("#preview_ccv_info_image")
	.css("position","absolute")
	.css("top",(pos.top - 416) + "px")
	.css("left",(pos.left ) + "px")
	.fadeIn("fast");
}

function closeCCVInfoImage()
{
   $('#preview_ccv_info_image').fadeOut();
}

function actionBeforeShippingReload()
{
    $('#btn_submit_order').unbind('click');
    $('#shipping_container').html(shippingPreloaderTemplate);	
	$('#td_choosen_shipping_container').html(selectedShippingPreloaderTemplate);
    $('#sub_total4').html('');
}

function actionAfterShippingReload()
{
    $('#btn_submit_order').click(function()
    {
       submitOrder();
    });
}

function getCouponItemContent(items)
{   
   var messageContent = '&nbsp;<a id="link_coupon_details" href="JavaScript:void(0);" onclick="previewCouponDetailMessage(event)">more info</a>';
   messageContent += '<div onclick="closeCouponDetailMessage()" id="div_coupon_details_message" title="Close" alt="Close" style="display:none;">\
                       <span onclick="previewCouponDetailMessage(event)">X</span><p>'+COUPON_PRODUCT_RULES_MSG+':</p><div class="clear"></div>\
                       <table cellpadding="5" cellspacing="0">\
                          <tbody><tr class="header"><td width="30%">Item SKU</td><td width="70%">Minimum Quantity</td></tr>';
   
   for(var i=0,size=items.length;i<size;i++)
   {      
	   messageContent += "<tr><td>"+items[i].item_sku+"</td><td>"+items[i].min_qty+"</td></tr>";      
   }
   messageContent += '</tbody></table></div>';
   
   return messageContent;
}

function previewCouponDetailMessage(e)
{
   var pos = $('#link_coupon_details').offset();   

	$("#div_coupon_details_message")
	.css("position","absolute")
	.css("top",(pos.top - 20 - $('#div_coupon_details_message').height()) + "px")
	.css("left",(pos.left + 40 ) + "px")
	.fadeIn("fast");
}

function closeCouponDetailMessage()
{
   $('#div_coupon_details_message').fadeOut();
}


function highlightCartItems(items)
{   
   if(items && items.length)
   {
      for(var i=0,size=items.length;i<size;i++)
      {
         $('#td_cart_item_sku_'+items[i].item_sku).css({color:'red'});
      }
   }
   else 
   {
      $('td [id^=td_cart_item_sku_]').each(function()
      {
         $(this).css({color:'red'});
      });
   }   
}

function resetHighlightedCartItems()
{   
   $('td [id^=td_cart_item_sku_]').each(function()
      {
         $(this).css({color:'black'});
      });
}

function addBultkItem(product_container_id, image_prefix)
{
   var bulkItems = new Array();

   $("#"+product_container_id+" :text").each(function(index, productBox){
      var bulkItem        = new Object();
      bulkItem.sku        = productBox.id.replace("cart_quantity_", "");
      bulkItem.product_id = $("#cart_products_id_"+bulkItem.sku).val();
      bulkItem.quantity   = productBox.value;

      //validate quantity, if invalid then highlight that productBox
      //and return

      if(bulkItem.quantity > 0)
      {
         bulkItem.imageIndex = index;
         bulkItems.push(bulkItem);
      }
   });

   if(bulkItems.length == 0 )
   {
      return;
   }

   eraseCookie('jewelrysupply_cart_items_count');
   eraseCookie('jewelrysupply_cart_total');

   var bulkItemsJsonStr = $.toJSON(bulkItems);
   var productDataInfo  = "action=add_bulk_items&bulk_items_json_str="+bulkItemsJsonStr;


   $.ajax({
      type: "POST",
      url: "/cart.php",
      data: productDataInfo,
      dataType:"json",
      success: function(cartInfo)
               {
                  document.getElementById('shopping_cart_items').innerHTML = cartInfo.items;
                  document.getElementById('shopping_cart_sub_total').innerHTML = '$'+cartInfo.sub_total;

                  if(cartInfo.cart_status != 'ok')
                  {
                     alert(cartInfo.cart_status);
                  }
                  else
                  {
                  	if(SHOW_CART_ON_ITEM_ADD_EVENT == 'Yes')
                  	{
                  		//document.location.href = '/cart.php?action=view_cart_details&product_id='+productId;
                  		document.location = '/cart.php?action=view_cart_details&product_id='+productId;
                  	}
                  }
               }
    });



   setCheckOut();

   var destinationId = 'cart';

   if(SHOW_ANIMATION_WHEN_ADD_TO_CART === 'Yes')
   {
      $.each(bulkItems, function(index, value) {
         //var sourceId = image_prefix+'_image_'+index;
         var sourceId = image_prefix+'_image_'+value.imageIndex;
         showAnimationWhenAddToCart(sourceId, destinationId);
      });
   }
}

