function typeOf(value) {
  var s = typeof value;
  if (s === 'object') {
    if (value) {
      if (value instanceof Array) {
        s = 'array';
      }
    } else {
      s = 'null';
    }
  }
  return s;
}

function boolToInt(value) {
  return value ? 1 : 0;
}

function getQuotePrices(email_quote, url, params, useJSON) {
  useJSON = useJSON || 0;
  if (email_quote === true) {
    if ($("#submitbutton").length) {
      $("#submitbutton").attr("disabled", "disabled");
      $("#submitbutton").val("Preparing your quote...");
      $("#emailresults").html("");
    }
    $("#sendemail").html("Please wait...");
  }
  if (email_quote === true) {
    var quoteref = $("#quoteref").val(),
        email1 = $("#email1").val(),
        email2 = $("#email2").val(),
        artwork = $("#artwork").length ? encodeURIComponent($("#artwork").val()) : null,
        notes = encodeURIComponent($("#notes").val());
    var prices = "retail";
    if ($("#tradeprices:checked").length > 0) {
      prices = "trade";
    } else {
      if ($("#retailprices:checked").length > 0) {
        prices = "retail";
      } else {
        if ($("#allprices:checked").length > 0) {
          prices = "all";
        }
      }
    }
    params += "&send_email=1&quoteref=" + quoteref + "&artwork=" + artwork + "&notes=" + notes + "&prices=" + prices + "&email1=" + email1;
    quoteObj.send_email = 1;
    quoteObj.quoteref = quoteref;
    quoteObj.artwork = artwork;
    quoteObj.notes = notes;
    quoteObj.prices = prices;
    quoteObj.email1 = email1;
    if (email2 !== null && email2 !== "") {
      params += "&email2=" + email2;
      quoteObj.email2 = email2;
    }
  } else {
    quoteObj.send_email = 0;
  }
  quoteObj.fid = [];
  $('[name="finishing"]:checked').each(function() {
    params += "&fid[]=" + this.value;
    quoteObj.fid.push(this.value);
  });
  $('[name="finishing' + quoteObj.pid + '"]:checked').each(function() {
    params += "&fid[]=" + this.value;
    quoteObj.fid.push(this.value);
  });
  quoteObj.deliv = -1;
  $('[name="delivery"]:checked').each(function() {
    params += "&deliv=" + this.value;
    quoteObj.deliv = this.value;
  });
  params += "&rand=" + parseInt(Math.random()*999999999999999);
  var ajaxParams = useJSON ? quoteObj : params;
  params += "&json=1";
  quoteObj.json = 1;
  $.ajax({
    type: "POST",
    url: url,
    cache: false,
    data: ajaxParams,
    dataType: "json",
    success: function(data){
      onQuotePriceJSONResponse(data);
    }
  });
}

function getXMLHTTPRequest() {
  try {
    var xmlhttp = new XMLHttpRequest();
    //alert("Using XMLHttpRequest Object");
  }
  catch(err1) {
    var ieXmlHttpVersions = [];
    ieXmlHttpVersions[ieXmlHttpVersions.length] = "MSXML2.XMLHttp.7.0";
    ieXmlHttpVersions[ieXmlHttpVersions.length] = "MSXML2.XMLHttp.6.0";
    ieXmlHttpVersions[ieXmlHttpVersions.length] = "MSXML2.XMLHttp.5.0";
    ieXmlHttpVersions[ieXmlHttpVersions.length] = "MSXML2.XMLHttp.4.0";
    ieXmlHttpVersions[ieXmlHttpVersions.length] = "MSXML2.XMLHttp.3.0";
    ieXmlHttpVersions[ieXmlHttpVersions.length] = "MSXML2.XMLHttp";
    ieXmlHttpVersions[ieXmlHttpVersions.length] = "Microsoft.XMLHttp";

    var i;
    for (i=0; i < ieXmlHttpVersions.length; i++) {
      try {
        var xmlhttp = new ActiveXObject(ieXmlHttpVersions[i]);
        //alert("Using " + ieXmlHttpVersions[i]);
        break;
      }
      catch (err2) {
        //alert(ieXmlHttpVersions[i] + " not supported.");
      }
    }
  }
  if (typeof xmlhttp == "undefined") {
    alert("Your browser probably doesn't support the XMLHttpRequest object, or has JavaScript disabled");
    return false;
  }
  return xmlhttp;
}

function onQuotePriceJSONResponse(data) {
  if (!data.success) {
    return false;
  }
  var result = data.result;
  // get and display the retail price
  if (result.cost) {
    var productCost = "&pound;" + result.cost.product.toFixed(2);
    var laminationCost = "&pound;" + result.cost.coating.toFixed(2);
    var totalCost = "&pound;" + (result.cost.product + result.cost.coating).toFixed(2);
    setPricesJQ('cost', productCost, laminationCost, totalCost);
  }
  if (result.trade) {
    var productTrade = "&pound;" + result.trade.product.toFixed(2);
    var laminationTrade = "&pound;" + result.trade.coating.toFixed(2);
    var totalTrade = "&pound;" + (result.trade.product + result.trade.coating).toFixed(2);
    setPricesJQ('trade', productTrade, laminationTrade, totalTrade);
  }
  if (result.retail) {
    var productRetail = "&pound;" + result.retail.product.toFixed(2);
    var laminationRetail = "&pound;" + result.retail.coating.toFixed(2);
    var totalRetail = "&pound;" + (result.retail.product + result.retail.coating).toFixed(2);
    setPricesJQ('retail', productRetail, laminationRetail, totalRetail);
  }
  
  var useLitho = result.litho;
  if (useLitho == 1) {
    $(".litho-note").show("fast");
    //$(".litho-note").fadeIn("fast");
    $(".price").addClass("litho-warning");
    $(".costing").addClass("litho-warning");
  } else {
    $(".litho-note").hide("fast");
    //$(".litho-note").fadeOut("fast");;
    $(".price").removeClass("litho-warning");
    $(".costing").removeClass("litho-warning");
  }

  if (document.quoteform.submitbutton) {
    document.quoteform.submitbutton.disabled = "";
    document.quoteform.submitbutton.value = "E-mail me my quote";
  }
  $("#sendemail").html("E-mail me my quote &raquo;");
  $("#sendemail").html("Send now");
  
  if (data.debug) {
    $('#debug2').html(data.debug);
  }
  
  if (result.email) {
    alert("E-mail successfully sent.");
  }
}

function onSendEmailClick() {
  if (!validate_form(document.quoteform)) {
    return false;
  }
  hideEmailPopup();
  getQuotePrice(true);
}

function setPrices(prefix, product, lamination, total) {
  el = document.getElementById(prefix + '_bookletprice');
  if (el !== null) { el.innerHTML = product; }

  el = document.getElementById(prefix + '_laminationprice');
  if (el !== null) { el.innerHTML = lamination; }

  el = document.getElementById(prefix + '_totalprice');
  if (el !== null) { el.innerHTML = total; }
}

function setPricesJQ(prefix, product, lamination, total) {
  if ($("#" + prefix + "_totalprice").text().replace(/�/g,'&pound;') != total) {
//    $("." + prefix + " .price div").hide("fast", function() {
      $("#" + prefix + "_bookletprice").html(product);
      $("#" + prefix + "_laminationprice").html(lamination);
      $("#" + prefix + "_totalprice").html(total);
//      $("." + prefix + " .price div").show("fast");
//    });
  }
}

function showDiv(el, show) {
  el.style.display = show ? "block" : "none";
}

function showDivById(divId, show) {
  showDiv(document.getElementById(divId), show);
}

function showDivByIdJQ(divId, show, animSpeed) {
  var speed = animSpeed || "fast";
  if (show) {
    $("#"+divId).show(speed);
  } else {
    $("#"+divId).hide(speed);
  }
}

var hideEmailPopup = function(e) {
  if (e) {
    e.preventDefault();
  }
  $('#mask, .window').hide();
};

var showEmailPopup = function(e) {
  //Cancel the link behavior
  e.preventDefault();
  //Get the A tag
  var id = "#emaildialog";

  //Get the screen height and width
  var maskHeight = $(document).height();
  var maskWidth = $(window).width();

  //Set height and width to mask to fill up the whole screen
  $('#mask').css({'width':maskWidth,'height':maskHeight,'opacity':0.63});
  
  //transition effect		
  $('#mask').show();	
  //$('#mask').fadeTo(200,0.63);	

  //Get the window height and width
  var winH = $(window).height();
  var winW = $(window).width();
            
  //Set the popup window to center
  $(id).css('top',  (winH-$(id).height()-100)/2);
  $(id).css('left', winW/2-$(id).width()/2);

  //transition effect
  //$(id).fadeIn(400);
  $(id).show();	
  $(id).find("input").first().focus().select();
};


