//..........................................................
// Calculate the total price on the view and edit orders page
//..........................................................
function jsRecalculateTotal()
{
  var priceproducts = $('#priceproducts').val();
  var priceshipping = $('#priceshipping').val();
  var pricetax = $('#pricetax').val();
  if (priceproducts == "")
  {
    priceproducts = 0;
  }
  if (priceshipping == "")
  {
    priceshipping = 0;
  }
  if (pricetax == "")
  {
    pricetax = 0;
  } 

  var total = parseFloat(priceproducts) + parseFloat(priceshipping) + parseFloat(pricetax);
  total = Math.round(total*100)/100;
  total = total.toFixed(2);
  
  $('#pricetotal').val(total);
}

//..........................................................
// Save a new product
//..........................................................
function jsNewProductAdd()
{
  ShowLoading();

  var urldata = "";
  urldata += "&category=" + $('#category').val();
//  urldata += "&name=" + $('#productname').val().replace(/&/g,"|");
  urldata += "&name=" + jsCleanForURL($('#productname').val());
//  urldata += "&desc=" + $('#productdescription').val().replace(/&/g,"|").replace(/\n/g,"[ENTER]").replace(/%/g,"[PCT]").replace(/#/g,"[PND]");
  urldata += "&desc=" + jsCleanForURL($('#productdescription').val());
  urldata += "&sku=" + $('#productsku').val();
  urldata += "&image=" + $('#productimage').val();
  urldata += "&grp1_quantity=" + $('#grp1_quantity').val();
  urldata += "&grp1_priceeach=" + $('#grp1_priceeach').val();
  urldata += "&grp2_quantity=" + $('#grp2_quantity').val();
  urldata += "&grp2_priceeach=" + $('#grp2_priceeach').val();
  urldata += "&grp3_quantity=" + $('#grp3_quantity').val();
  urldata += "&grp3_priceeach=" + $('#grp3_priceeach').val();
  urldata += "&grp4_quantity=" + $('#grp4_quantity').val();
  urldata += "&grp4_priceeach=" + $('#grp4_priceeach').val();
  urldata += "&grp5_quantity=" + $('#grp5_quantity').val();
  urldata += "&grp5_priceeach=" + $('#grp5_priceeach').val();
  urldata += "&pid=" + $('#pid').val(); 
//alert(urldata);
  $.ajax({
    type: "GET",
    url: "custom/php/ajax_functions.php?action=newproductadd" + urldata + "&random=" + GetRandom(),
    success: function(msg){
//alert(msg);
        if (msg == "1")
        {
          $('#category').val("");
          $('#productname').val("");
          $('#productdescription').val("");
          $('#productsku').val("");
          $('#productimage').val("");
          $('#grp1_quantity').val("");
          $('#grp1_priceeach').val("");
          $('#grp2_quantity').val("");
          $('#grp2_priceeach').val("");
          $('#grp3_quantity').val("");
          $('#grp3_priceeach').val("");
          $('#grp4_quantity').val("");
          $('#grp4_priceeach').val("");
          $('#grp5_quantity').val("");
          $('#grp5_priceeach').val("");
          alert("Your product has been saved.");
          jsReloadProductGrid();
        }
        else
        {
          HideLoading();
          alert("Error occurred while saving record.");
        }
    }
  });
}


//..........................................................
// Clear out all special characters used in urls
//..........................................................
function jsCleanForURL(url)
{
//  url = url.replace(/$/g,"[DL]"); // Dollar ("$")
  url = url.replace(/&/g,"[AM]"); // Ampersand ("&")
  url = url.replace(/\+/g,"[PL]"); // Plus ("+")
  url = url.replace(/,/g,"[CM]"); // Comma (",")
 // url = url.replace(///g,"[FS]"); // Forward slash/Virgule ("/")
  url = url.replace(/:/g,"[CL]"); // Colon (":")
  url = url.replace(/;/g,"[SC]"); // Semi-colon (";")
  url = url.replace(/=/g,"[EQ]"); // Equals ("=")
//  url = url.replace(/?/g,"[QM]"); // Question mark ("?")
  url = url.replace(/@/g,"[AT]"); // 'At' symbol ("@")
  url = url.replace(/#/g,"[PD]"); // Pound symbol ("#")
  url = url.replace(/%/g,"[PT]"); // Percent ("%")

  url = url.replace(/\n/g,"[ENTER]");
  return url;
}


//..........................................................
// Save a new category
//..........................................................
function jsNewCategoryAdd()
{
  ShowLoading();

  var urldata = "";
  urldata += "&parentcategory=" + $('#category').val();
  urldata += "&name=" +  $('#categoryname').val().replace(/&/g,"|");
  urldata += "&desc=" + $('#categorydescription').val().replace(/&/g,"|");
  urldata += "&cid=" + $('#cid').val(); 

  $.ajax({
    type: "GET",
    url: "custom/php/ajax_functions.php?action=newcategoryadd" + urldata + "&random=" + GetRandom(),
    success: function(msg){
//alert(msg);
        if (msg == "1")
        {
          //$('#category').val("");
          //$('#categoryname').val("");
          //$('#categorydescription').val("");
          alert("Your category has been saved.");
          jsReloadCategoryAdd();
          jsReloadCategoryGrid();
          jsReloadCategoryMenu();
        }
        else
        {
          HideLoading();
          alert("Error occurred while saving record.");
        }
    }
  });
}

//..........................................................
// Reload the product grid
//..........................................................
function jsReloadProductGrid()
{
  var urldata = "";
  urldata += "&category=" + $('#categorygridddl').val();
  $.ajax({
    type: "GET",
    url: "custom/php/ajax_functions.php?action=refreshproductgrid" + urldata + "&random=" + GetRandom(),
    success: function(msg){
        HideLoading();
        $('#productgrid').html(msg);
    }
  }); 
}


//..........................................................
// Reload the category grid
//..........................................................
function jsReloadCategoryGrid()
{
  var urldata = "";
  urldata += "&category=" + $('#categorygridddl').val();

  $.ajax({
    type: "GET",
    url: "custom/php/ajax_functions.php?action=refreshcategorygrid" + urldata + "&random=" + GetRandom(),
    success: function(msg){
        $('#categorygrid').html(msg);
    }
  }); 
}

//..........................................................
// Reload the product menu
//..........................................................
function jsReloadCategoryMenu()
{
  $.ajax({
    type: "GET",
    url: "custom/php/ajax_functions.php?action=refreshcategorymenu&random=" + GetRandom(),
    success: function(msg){
        HideLoading();
        $('#categorymenu').html(msg);
    }
  }); 
}


//..........................................................
// Reload the category add
//..........................................................
function jsReloadCategoryAdd()
{
  $.ajax({
    type: "GET",
    url: "custom/php/ajax_functions.php?action=refreshcategoryadd&random=" + GetRandom(),
    success: function(msg){
        $('#categoryadd').html(msg);
    }
  }); 
}

//..........................................................
// Reload the submit order link
//..........................................................
function jsReloadSubmitOrderLink(userid)
{
//alert("reload submit order link");
  $.ajax({
    type: "GET",
    url: "/custom/php/ajax_functions.php?action=refreshmidlevelmenu&userid=" + userid + "&random=" + GetRandom(),
    success: function(msg){
//alert(msg);
        $('#submitorder').html(msg);
    }
  }); 
}


//..........................................................
// Reload add screen with product loaded
//..........................................................
function jsEditProduct(pid)
{
  ShowLoading();

  $.ajax({
    type: "GET",
    url: "custom/php/ajax_functions.php?action=productedit&pid=" + pid + "&random=" + GetRandom(),
    success: function(msg){
        HideLoading();
        $('#productadd').html(msg);
    }
  }); 
}


//..........................................................
// Delete product
//..........................................................
function jsDeleteProduct(pid)
{
  var answer = confirm("Your product will be deleted.  Press OK to continue or Cancel to keep this product.")
  if (answer)
  {
    ShowLoading();
    $.ajax({
    type: "GET",
    url: "custom/php/ajax_functions.php?action=productdelete&pid=" + pid + "&random=" + GetRandom(),
    success: function(msg){
        jsReloadProductGrid();
        alert("Your product was successfully deleted.");
    }
  }); 
  }
}

//..........................................................
// Reload add screen with product loaded
//..........................................................
function jsEditCategory(cid)
{
  ShowLoading();

  $.ajax({
    type: "GET",
    url: "custom/php/ajax_functions.php?action=categoryedit&cid=" + cid + "&random=" + GetRandom(),
    success: function(msg){
        HideLoading();
        $('#categoryadd').html(msg);
    }
  }); 
}


//..........................................................
// Delete category
//..........................................................
function jsDeleteCategory(cid)
{
  var answer = confirm("Your category and all subcategories will be deleted.  Press OK to continue or Cancel to keep this category.")
  if (answer)
  {
    ShowLoading();
    $.ajax({
    type: "GET",
    url: "custom/php/ajax_functions.php?action=categorydelete&cid=" + cid + "&random=" + GetRandom(),
    success: function(msg){
        jsReloadCategoryGrid();
        jsReloadCategoryMenu();
        alert(msg);
        //alert("Your category was successfully deleted.");
    }
  }); 
  }
}


//..........................................................
// Update the quantity in shopping cart
//..........................................................
function jsUpdateQuantity(pid)
{
  ShowLoading();
  quantity = $('#quantity_' + pid).val();

  urldata = "&pid=" + pid;
  urldata += "&quantity=" + quantity;
//alert(urldata);
  $.ajax({
      type: "GET",
      url: "/custom/php/ajax_functions.php?action=updatequantity" + urldata + "&random=" + GetRandom(),
      success: function(msg){
        if (msg == "error")
        {
          HideLoading();
          alert("Error occurred while saving record.");
        }
        else
        {
          HideLoading();
          alert("This products quantity has been updated in your shopping cart.");
        } 
      }
    }); 
}

//..........................................................
// Update the quantity in shopping cart
//..........................................................
function jsUpdateQuantityOrder(copid)
{
  ShowLoading();
  quantity = $('#quantity_' + copid).val();

  urldata = "&copid=" + copid;
  urldata += "&quantity=" + quantity;
//alert(urldata);
  $.ajax({
      type: "GET",
      url: "/custom/php/ajax_functions.php?action=updatequantityorder" + urldata + "&random=" + GetRandom(),
      success: function(msg){
        if (msg != "1")
        {
          HideLoading();
          alert("Error occurred while saving record.");
        }
        else
        {
          HideLoading();
          alert("This product quantity has been updated.");
        } 
      }
    }); 
}

//..........................................................
// Add A product to wishlist
//..........................................................
function jsAddToWishlist(userid, pid)
{

  var quantity = $('#quantity').val();
//alert(quantity);
  if (quantity == undefined)
    quantity = "1";

//  if (userid == 0)
//  {
//    alert("You must login before you can save an item to your shopping cart.");
//  }
//  else
//  {
    ShowLoading();
    var urldata = "";
    urldata += "&userid=" + userid;
    urldata += "&pid=" + pid;
    urldata += "&quantity=" + quantity;

    $.ajax({
      type: "GET",
      url: "/custom/php/ajax_functions.php?action=addtowishlist" + urldata + "&random=" + GetRandom(),
      success: function(msg){
//alert(msg);
        if (msg == "1")
        {
          jsReloadSubmitOrderLink(userid);
          HideLoading();
          alert("This product has been added to your shopping cart.");
        }
        else
        {
          HideLoading();
          alert("Error occurred while saving record.");
        }
         
      }
    }); 
//  }
}

//..........................................................
// Remove an item from the wishlist
//..........................................................
function jsRemoveFromWishlist(userid, wid, view)
{
   ShowLoading();

    var urldata = "";
    urldata += "&userid=" + userid;
    urldata += "&wid=" + wid;
    urldata += "&view=" + view;

    $.ajax({
      type: "GET",
      url: "/custom/php/ajax_functions.php?action=removefromwishlist" + urldata + "&random=" + GetRandom(),
      success: function(msg){
        if (msg == "error")
        {
          HideLoading();
          alert("Error occurred while saving record.");
        }
        else
        {
          $('#wishlist').html(msg);
          jsReloadSubmitOrderLink(userid);
          HideLoading();
          alert("This product has been removed from your shopping cart.");
        } 
      }
    }); 
}

//..........................................................
// Submits a order.  
//..........................................................
function jsSubmitOrderSend(userid, iscookie)
{
   ShowLoading();


  var urldata = "";
  urldata += "&userid=" + userid;
  urldata += "&iscookie=" + iscookie;

  var err = "";
  if (iscookie == "true")
  {
    if ($('#firstname').val() == "")
    {
      err += "\nFirst Name";
    }
    if ($('#lastname').val() == "")  
    {
      err += "\nLast Name";
    }
//    if ($('#phone').val() == "")  
//    {
//      err += "\nPhone";
//    }
    if ($('#phone').val().length < 10)  
    {
      err += "\nPhone # is required and must include area code.";
    }
    if ($('#email').val().indexOf("@") == -1)  
    {
      err += "\nEmail is required and must contain @ symbol.";
    }
    if ($('#state').val() == "")  
    {
      err += "\nState";
    }
    if ($('#zip').val().length < 5)  
    {
      err += "\nZip Code is required and must contain at least 5 digits.";
    }
    if (err != "")
    {
      HideLoading();
      alert("The following fields are required:" + err);
    }
    urldata += "&firstname=" + $('#firstname').val();
    urldata += "&lastname=" + $('#lastname').val();
    urldata += "&email=" + $('#email').val();
    urldata += "&password=" + $('#password').val();
    urldata += "&phone=" + $('#phone').val();
    urldata += "&address1=" + $('#address1').val();
    urldata += "&city=" + $('#city').val();
    urldata += "&state=" + $('#state').val();
    urldata += "&zip=" + $('#zip').val();
  }

  if (err == "")
  {
    $.ajax({
      type: "GET",
      url: "/custom/php/ajax_functions.php?action=submitordersend" + urldata + "&random=" + GetRandom(),
      success: function(msg){
//alert(msg);        
        if (msg == "error")
        {
          HideLoading();
          alert("Error occurred while submitting order.");
        }
        else
        {
          HideLoading();
          alert("Your order# " + msg + " has been submitted.  \n\nIf you entered a password you may now login and view the status of this order using your email address as you username, and then the password you just set.");
          location = "/home";
        } 
      }
     }); 
  }
}

//..........................................................
// Shows the details of an order 
//..........................................................
function jsShowOrderDetails(orderid)
{
  ShowLoading();
  var urldata = "";
  urldata += "&orderid=" + orderid;
//alert(urldata);
  $.ajax({
      type: "GET",
      url: "/custom/php/ajax_functions.php?action=orderdetails" + urldata + "&random=" + GetRandom(),
      success: function(msg){
//alert(msg);
        if (msg == "error")
        {
          HideLoading();
          alert("There was an error in retrieving this information.");
        }
        else
        {
          HideLoading();
          $('#orderdetails').html(msg);
        } 
      }
     }); 
}

//..........................................................
// Shows the details of an order for editing
//..........................................................
function jsEditOrder(orderid)
{
  ShowLoading();
  var urldata = "";
  urldata += "&orderid=" + orderid;
//alert(urldata);
  $.ajax({
      type: "GET",
      url: "/custom/php/ajax_functions.php?action=editorder" + urldata + "&random=" + GetRandom(),
      success: function(msg){
//alert(msg);
        if (msg == "error")
        {
          HideLoading();
          alert("There was an error in retrieving this information.");
        }
        else
        {
          HideLoading();
          $('#orderdetails').html(msg);
        } 
      }
     }); 
}

//..........................................................
// Updated the details of an order
//..........................................................
function jsUpdateOrder()
{
  ShowLoading();
  var urldata = "";
  urldata += "&orderid=" + $('#orderid').val();
  urldata += "&status=" + $('#status').val();
  urldata += "&priceproducts=" + $('#priceproducts').val();
  urldata += "&priceshipping=" + $('#priceshipping').val();
  urldata += "&pricetax=" + $('#pricetax').val();
  urldata += "&pricetotal=" + $('#pricetotal').val();
  urldata += "&firstname=" + $('#firstname').val();
  urldata += "&lastname=" + $('#lastname').val();
  urldata += "&phone=" + $('#phone').val();
  urldata += "&email=" + $('#email').val();
  urldata += "&address1=" + $('#address1').val();
  urldata += "&city=" + $('#city').val();
  urldata += "&state=" + $('#state').val();
  urldata += "&zip=" + $('#zip').val();
  urldata += "&userid=" + $('#userid').val();

//alert(urldata);
  $.ajax({
      type: "GET",
      url: "/custom/php/ajax_functions.php?action=updateorder" + urldata + "&random=" + GetRandom(),
      success: function(msg){
//alert(msg);
        if (msg == "error")
        {
          HideLoading();
          alert("There was an error saving this information.");
        }
        else
        {
          HideLoading();
          alert("The order details were successfully updated.");
          $('#orderlist').html(msg);
          
        } 
      }
     }); 

}

//..........................................................
// Shows a waiting image while ajax processing is going on
//..........................................................
function ShowLoading()
{
  $('#loading').html("<img src='/custom/images/ajax-loader.gif' border='0'/>");
}

//..........................................................
// Removes waiting image after ajax processing is finished
//..........................................................
function HideLoading()
{
  $('#loading').html("");
}

//..........................................................
// Get a random number to avoid IE caching
//..........................................................
function GetRandom()
{
  var randomnumber=Math.floor(Math.random()*10000);
  return randomnumber;
}
