var ccSubmitDimensionsProcessed = false;
var upsMsg = '<p>This item exceeds UPS package limits, but we can still ship your order. <a href="/c2sm/ups-limits/" onclick="ajaxLightBox(this); return false;">Learn More &raquo;</a></p>'
var ccMsg = '<p>This item has special pricing and cannot be custom cut at this size.</p>'

var outOfStockMsg = '<p class="bold">This Item is out of stock.</p>';
//dom ready
$(function() {
  $.ajaxSetup({cache: false});
  
	imgCustomPrice= new Image(); 
  imgCustomPrice.src="/images/products/core/get-custom-cut-on.png"; 
	imgAddToCart= new Image(); 
  imgAddToCart.src="/images/products/core/add-to-cart-on.png";
	imgAddToCart= new Image(); 
  imgAddToCart.src="/images/products/core/add-to-cart-on.png";
	imgEditInCart= new Image(); 
  imgEditInCart.src="/images/products/core/edit-in-cart-on.png";				 
					 
  $("input[name='submetaltype'][default='true']").attr("checked", "checked");
  disableStandardCut();
  resetCustomCut();
  
  if ($("#selectdimension0 option[default='true']").length == 0) {
    $("#selectdimension0 option:eq(0)").attr("selected", "selected");
  }
  else {
    // loading sku: make active, select defaults
    $("#proddimensions select").removeAttr("disabled");
    $("#proddimensions select option[default='true']").attr("selected", "selected");
  }
  
  if ($("#loadSku").text() == 'Y') {
    loadSizes($("#proddimensions select").length, getAlloy(), $("#productrefid").text(), true);
		if ($("#custom_cut").text() != 'TRUE') {
			$('#tabcustom').removeClass('active');
			$('#tabstandard').addClass('active');
			$('#contentcustom').removeClass('active');
			$('#contentstandard').addClass('active');
		}
  }
	
	
  
  
	// Load Cart images
	cartImgOn= new Image(); 
  cartImgOn.src="/images/products/core/add-to-cart-on.gif";
	
	// tabswitching on the product section.
	$(".prodtabs a").click(function(){
		parentDiv = $(this).parent('div').attr('id');
		if(this.className != 'active') { 
			$("#" + parentDiv + " a").removeClass("active");
			$(this).addClass("active");
			tabId = this.id;
			$("#" + parentDiv).nextAll("div.active").removeClass("active");
			contentId = tabId.replace(/tab/, "content");
			$('#'+contentId).addClass('active');
		} 
		return false;
	});

	//add zebra sriping on specs tables with the class stripes. 
	$('table.stripes tr:even td').addClass('alt'); 
});


var showCustomCut = function(){ 
	$('#tabstandard').removeClass('active');
	$('#tabcustom').show();
	$('#tabcustom').addClass('active');
	$('#contentstandard').removeClass('active');
	$('#contentcustom').addClass('active');
}


//switch channel diamgrams in step one if the product ref id is ACH
var switchChannel = function(alloy) { 
	var imgSrc = $('#dimensionsdiagram').attr('src');
	var imgSrcSplit = imgSrc.split('_');
	var newImgSrc = imgSrcSplit[0] + "_" + alloy + ".gif";
	$('#dimensionsdiagram').attr('src',newImgSrc);
	var thSrc = $('#prodthumb').attr('src');
	var thSrcSplit = thSrc.split('_');
	var newthSrc = thSrcSplit[0] + "_" + alloy + ".gif";
	$('#prodthumb').attr('src',newthSrc);
}

// Product Select - Step 1
var alloySelect = function(prodRef, alloy, alloyDescr, totalStages) {
	
  // reset Step 2 dimensions
  resetDimensions(-1, totalStages);
  $("#alloydescr").html(alloyDescr);
	showCustomCut();
	
	$('#dimensionsloadimg').css('display','inline');
	$("#proddimension0").load("/product/includes/selection-dimensions.jsp", "alloy=" + alloy + "&dim=0&refid=" + prodRef, function(){
		if(prodRef == "ACH") { 
			switchChannel(alloy);
		}
		$('#dimensionsloadimg').css('display','none');	
	});
}


// Dimension Select - Step 2
var dimensionsSelect = function(lmnt, stage, totalStages, alloy, prodRef) {
  // dimension selected 
  showCustomCut();
  // alert("stage=" + stage + "\ntotalStages=" + totalStages + "\nalloy=" + alloy + "\nprodRef=" + prodRef);
	dimSelection = lmnt.value;
	nextStage = stage + 1;
	
	// reset selections
	resetDimensions(stage, totalStages)
	if (dimSelection == '') {
	  // first option (nothing) selected
    $("#seldimension" + stage).html('');
    $("#seldimension" + stage).nextAll('span').html('');
    //alert("stage="+stage + ", total=" + totalStages)
  }
	else {
	  // a valid dimension selected
		$("#seldimension" + stage).html($("#selectdimension" + stage + " option:selected").text());
		
		if (stage < (totalStages - 1)) {
		  // have other dimensions following
		  var parms = "alloy=" + alloy + "&dim=" + (stage + 1) + "&refid=" + prodRef;
		  for (var i = 0; i <= stage; i++) {
		    parms += "&dim" + i + "=" + $("#selectdimension" + i).val();
		  }
		  // alert(parms);
			$('#dimensionsloadimg').css('display','inline');
		  $("#proddimension" + (stage + 1)).load("/product/includes/selection-dimensions.jsp", parms, function(){
				$('#dimensionsloadimg').css('display','none');
			}); 
		}
		else {
		  // at the last dimension
		  dimensionsFinished = allDimensionsSelected();	  
	  
  	  if (dimensionsFinished) {
  	    // all dimensions selected
  	    loadSizes(totalStages, alloy, prodRef);
  	  }
		}
	} 
}

var sizeSelectMsg = function() { 
	$('#standardmsg').empty();
	$('#cutinhalf').css("display", "none");
	
	var inventoryStatus = $("#selectsize option:selected").attr('inventory_status');
	var exceedsUPS = $("#selectsize option:selected").attr("exceeds_ups");
	var ccValue = $("#selectsize option:selected").attr("custom_cut");
	var cutInHalf = $("#selectsize option:selected").attr("cut_in_half");
	
  if (cutInHalf == 'Y') {
    $('#cutinhalf').css("display", "inline");
  }
    
    
	if (inventoryStatus == 'OUTOFSTOCK') { 
		$('#standardmsg').append(outOfStockMsg);
	}
	else if (inventoryStatus == 'FUTURE') { 
    $('#standardmsg').append('<p class="bold">This Item is on order and will be available on ' + $("#selectsize option:selected").attr("avail_date") + '</p>');
  }
	if (exceedsUPS == 'true') { 
		$('#standardmsg').append(upsMsg);
	}
	if (ccValue == 'N') { 
		$('#standardmsg').append(ccMsg);
	}
}


var loadSizes = function(totalStages, alloy, prodRef, onload) {
  $("#sizeminiload").show();
  
  var parms = "alloy=" + alloy + "&refid=" + prodRef;
  for (var i = 0; i < totalStages; i++) {
    parms += "&dim" + i + "=" + $("#selectdimension" + i).val();
  }
  parms += "&sku=" + $("#sku").val();

  //alert(parms)
  $("#selectsize").load("/product/includes/selection-size.jsp", parms, function() {
    $("#selectsize").removeAttr("disabled");
    $(".customcut").removeAttr("disabled");
    $(".ccfraction input").css("color","#6699ff");
    $(".qty").removeAttr("disabled");
    $("#sizeminiload").hide();
    
    if ($("#selectsize option").size() == 2) {
      // preselect the only size option
      $("#selectsize option:eq(1)").attr("selected", "selected");
    }
    
    sizeSelectMsg();
    
    
    // set maximums
    var maxWidth = 0;
    var maxLength = 0;
    $("#selectsize option:gt(0)").each(function(i) {
      if (haveWidth()) {
        if (parseFloat($("#" + this.id).attr('width')) > maxWidth) {
          maxWidth = parseFloat($("#" + this.id).attr('width'));
        }
      }
      if (parseFloat($("#" + this.id).attr('length')) > maxLength) {
        maxLength = parseFloat($("#" + this.id).attr('length'));
      }
    });
    
    $('.ccWidthMax').text('Max: ' + maxWidth + ' Inches');
    $('.ccLengthMax').text('Max: ' + maxLength + ' Inches');
    //alert($("#selectsize option:selected").attr('custom_cut'));

    var ccAvail = false;
    $("#selectsize option").each(function(){
      if($(this).attr('custom_cut') == 'Y') {
				ccAvail = true;
			}
    });
		if (!ccAvail) { 
			$('#tabstandard').addClass('active');
			$('#contentstandard').addClass('active');
			$('#tabcustom').hide();
			$('#contentcustom').removeClass('active');
		}
    
    if (onload) {
      if ($('#custom_cut').text() == 'TRUE') {
        if ($('#ccprecut').attr('default') == 'checked') {
          $('#ccprecut').attr('checked', 'checked');
        }
        $('#customcutqty').val($('#customcutqty').attr('default'));
        $('#yourSelectionQty').text($('#customcutqty').attr('default'));
        
        if ($('#ccWidth').attr('default') === undefined) {
          // linear item
        }
        else {
          var arr = $('#ccWidth').attr('default').split(' ');
          $('#ccWidth').val(arr[0]);
          if (arr.length >= 2) {
            $('#ccWidthFraction').val(arr[1]);
          }
          else {
            $('#ccWidthFraction').val('');
          }
          $('#ccWidthFraction').css("color", "#000000");
        }
        if ($('#ccLength').attr('default') != '') {
          var arr = $('#ccLength').attr('default').split(' ');
          $('#ccLength').val(arr[0]);
          if (arr.length >= 2) {
            $('#ccLengthFraction').val(arr[1]);
          }
          else {
            $('#ccLengthFraction').val('');
          }
          $('#ccLengthFraction').css("color", "#000000");
        }
        
        
        setCustomCut(true);
        $("#selectsize option:eq(0)").attr("selected", "selected");
				sizeSelectMsg();
      }
    }    
  });
}


var resetDimensions = function(dimStage, totalStages) {
  //alert('reset dimensions');
	disableStandardCut();
	resetCustomCut();
	$('.sizebox').removeClass('active');
	$('selectionmsg').empty();
	$('.ccprice').empty();
  for (var i = 0; i < totalStages; i++) {
    if (i > dimStage) {
      // reset the 'following' dimension selects
      $("#selectdimension" + i + " option:eq(0)").attr("selected", "selected");
      $("#selectdimension" + i).attr('disabled', 'disabled');
      $("#seldimension" + i).text('');
    }
  }
  
  $(".qty").attr('default', '');
  
  
}


var resetStandardCut = function() { 
	$("#selectsize option:eq(0)").attr("selected", "selected");	
	$("#selectsizeqty").val($("#selectsizeqty").attr('default'));
	$('.selectionmsg').empty();
}

var disableStandardCut = function() {
	resetStandardCut();
	$("#selectsize").attr('disabled', 'disabled');
  $("#prodstandardcut .qty").attr('disabled', 'disabled');
}

var resetCustomCut = function(source) {
  $(".customcut").val("");
  $(".ccfraction input").val(FRACTION_EX);
  $(".ccfraction input").css("color", "#666666");
  $('#ccprecut').attr('checked', false);
  if (source != 'size') {
    $('.ccWidthMax').text('');
    $('.ccLengthMax').text('');
  }
	$("#customcutqty").val($("#customcutqty").attr('default'));
	ccSubmitDimensionsProcessed = false;
  
  if (!allDimensionsSelected()) {
    $(".customcut").attr("disabled", "disabled");
    $(".ccfraction input").attr("disabled", "disabled");
  }
  setCustomCut(false);
}



//Product Select - Step 3: Select Size

var doingCustomCut = false;
var FRACTION_EX = 'ex. 1/2';

var isCustomCut = function() {
  return doingCustomCut;
}

var setCustomCut = function(b) {
  doingCustomCut = b;
  
  $("#prodcustomcut").toggleClass('active', b);
}

//reset quatity in the form fields
var qtySelect = function(lmnt) { 
	
	$('selectionmsg').empty();
	qty = $(lmnt).val()
	//$("#yourSelectionQty").text(qty);
}

var sizeSelect = function(lmnt) {
	$('#ccprice').empty();
	if (isCustomCut()) { // reset the custom size fields & your selection
		resetCustomCut('size');
	}
	sizeSelectMsg();
}


var isDefaultFractionVal = function(f) {
  if (f == '' || f == FRACTION_EX || f == '0') {
    return true;
  }
  
  return false;
}


// Custom Cut: input change event
var customCutChange = function(){ 
	$('selectionmsg').empty();
	if (!isCustomCut()) { // reset the preset size <select>
	  $("#selectsize option:eq(0)").attr("selected", "selected");
		$("#selectsizeqty").val('');
		//$('#yourSelectionQty').text('');
		resetStandardCut();
	}
	
	setCustomCut(true);
	ccSubmitDimensionsProcessed = false
}

var customCutClear = function(lmnt){ 
	if(lmnt.value == FRACTION_EX) { 
		$(lmnt).val('');
		$(lmnt).css("color","#333");
	}
}

var addToCart = function(lmnt) { 
  var msg = "";
  var qty = 0;
  var outOfStock = false;
  if (isCustomCut()) {
    qty = $("#customcutqty").val();
    if (!ccSubmitDimensionsProcessed) {
      msg += "Please complete the Custom Cut form and click on the 'Get Custom Cut Price' button\n";
    }
  }
  else {
    if ($("#selectsize option:selected").attr('inventory_status') == 'OUTOFSTOCK') {
      msg += "This part is out of stock\n"; 
      outOfStock = true;
    }
    else {
      qty = $("#selectsizeqty").val();
      if (!allDimensionsSelected()) {
        msg += "Step 2: Dimensions not selected\n";
      }
      
      if ($("#selectsize").val() == '') {
        msg += "Step 3: Size not selected\n";
      }
    }
  }
  
  if (!outOfStock) {
    if (qty == '') {
      msg += "Quantity not entered\n";
    }
    else {
      if (!isQuantity(qty)) {
        msg += "Quantity is not a valid number\n";
      }
    }
  }
  
  
	if (msg == '') {
	  hideButton(lmnt);
	  $('selectionmsg').empty();
	  
	  if (isCustomCut()) {
      $.get("/add-custom-cut-to-cart?&zoi_quantity-1=" + qty + "&cat=" + $("#cat").text() + "&cartitemid=" + $("#cartitemid").val() + "&" + getCustomCutParms(), function(data) {
        addToCartAjaxCallback(data);
      });
	  }
	  else {
  	  $.get("/add-sku-to-cart?zoi_sku-1=" + $("#selectsize").val() + "&zoi_quantity-1=" + qty + "&cat=" + $("#cat").text() + "&cartitemid=" + $("#cartitemid").val() + "&cutinhalf=" + $("#cutinhalfcbx").attr("checked"), function(data) {
  	    addToCartAjaxCallback(data);
  	  });
	  }
	} 
	else { 
    alert("The following errors were found with your order:\n\n" + msg);
	}
}


var addToCartAjaxCallback = function(data) {
  var response = jQuery.trim(data);
  if (response != 'OK') {
    if (response == 'OUT_OF_STOCK') {
      alert("We're sorry, this part is out of stock");
    }
    else if (response == 'NOT_ENOUGH_INVENTORY') {
      alert("We're sorry, we don't have enough inventory for your selected quantity, please decrease your quantity and try again");
    }
    else {
      alert("We're sorry, we are experiencing technical difficulties.  Please try again later.");
    }
  }
  else {
		document.location.href = '/checkout/';
  }
}


var allDimensionsSelected = function() {
  var status = true;
  $('#proddimensions select').each(function(i) {
    // alert(i + ":" + this.value);
    if (this.value == '') {
      // alert("error at " + i)
      status = false;
      
      // trigger .each exit
      return false;
    } 
  });
  
  return status;
}


function isInt(v) { 
  if (v.match(/^\d+$/) == null) { 
    return false;
  }
  return true;
}

function isQuantity(v) { 
  if (isInt(v)) {
    if (v > 0) {
      return true;
    }
  }
  
  return false;
}

var submitDimensions = function() {
  if (!allDimensionsSelected()) {
    alert("Step 2 Dimensions not selected");
    return;
  }
  
  if (!checkCustomCutInputs()) {
    return;
  }

  
  //setYourSelectionSizeAndPrice();
  
  var qp = getCustomCutParms();
  // alert(qp)
  
  hideButton('submitdimensionsbtn');
  $.get("/product/includes/custom-cut-price.jsp?zoi_quantity-1=" + $("#customcutqty").val() + "&" + qp, function(data) {
		var a = jQuery.trim(data).split('|');
		scrollMe('addtocart');
		showButton('submitdimensionsbtn');
    
    if (a[0] != 'OK') {
      if (a[0] == 'OUT_OF_STOCK') {
        alert("We're sorry, this part is out of stock");
      }
      else if (a[0] == 'NOT_ENOUGH_INVENTORY') {
        alert("We're sorry, we don't have enough inventory for your selected quantity, please decrease your quantity and try again");
      }
      else {
        alert("We're sorry, we are experiencing technical difficulties.  Please try again later.");
      }
      return;
    }
		if (jQuery.trim(a[2]) == "true") { 
			$('#ccmsg').html(upsMsg);
		} 
		else { 
			$('#ccmsg').empty();
		}
		
    $("#yourSelectionPrice").html(a[1]);
		$("#yourSelectionTotal").html(a[3]);
		//$("#ccmsg").append(a[4]);
    ccSubmitDimensionsProcessed = true;
  });
}


var getCustomCutParms = function() {
  var qp = "refid=" + $("#productrefid").text();
  qp += '&alloy=' + getAlloy();
  
  $('#proddimensions select').each(function(i) {
    qp += '&dim' + i + '=' + this.value;
  });
  
  qp += '&length=' + $("input[name='customcut_length']").val();
  qp += '&length_fraction=' + (isDefaultFractionVal($("input[name='customcut_length_fraction']").val()) ? '' : $("input[name='customcut_length_fraction']").val());
  qp += '&width=' + $("input[name='customcut_width']").val();
  qp += '&width_fraction=' + (isDefaultFractionVal($("input[name='customcut_width_fraction']").val()) ? '' : $("input[name='customcut_width_fraction']").val());
  
  qp += '&accept_precutpiece_substitution=' + $('#ccprecut').attr('checked');
  
  return qp;
}


var ccCheckboxesClick = function() {
  $('#prodcustomcut input:checkbox').each(function(i) {
    if(this.checked) {
      customCutChange();
      
      return false;
    }
  });  
}


var checkCustomCutInputs = function() {
  // check the inches
  var msg = "";
  $('.ccinches input').each(function(i) {
    if (!isInt(this.value)) {
      msg += (this.name == 'customcut_width' ? "Width" : "Length") + " must be a whole number\n";
    }
  });
  
  // check the fractions
  $('.ccfraction input').each(function(i) {
    if (this.value == '' || this.value == FRACTION_EX || this.value == '0') {
      // skip
    }
    else if (!isFraction(this.value)) {
      msg += (this.name == 'customcut_width_fraction' ? "Width" : "Length") + " Fraction is not a valid fraction\n";
    }
    else if (!checkFractionDenominator(this.value)) {
      msg += (this.name == 'customcut_width_fraction' ? "Width" : "Length") + " Fraction denominator must be either: 2, 4, 8, 16, 32\n";
    }
  });
  
  if (!isQuantity($("#customcutqty").val())) {
    msg += "Quantity is not a valid number";
  }
    
  
  if (msg == '') {
    if (!isValidSize()) {
      msg += "Custom cut dimensions exceeds the maximum stock size";
    }
  }
  
  if (msg != '') {
    alert("Please correct the following errors:\n\n" + msg);
    return false;
  }
  
  return true;
}


var isValidSize = function() {
  
  var length = parseInt($("#ccLength").val());
  if ($("#ccLengthFraction").val() != '' && $("#ccLengthFraction").val() != FRACTION_EX) {
    length += eval($("#ccLengthFraction").val());
  }

  var width = 0;
  var haveWidth = false;
  if ($("#ccWidth").length > 0) {
    haveWidth = true;
    var width = parseInt($("#ccWidth").val());
    if ($("#ccWidthFraction").val() != '' && $("#ccWidthFraction").val() != FRACTION_EX) {
      width += eval($("#ccWidthFraction").val());
    }
  }
  
  var ok = false;
  $("#selectsize option:gt(0)").each(function(i) {
    if (haveWidth) {
      if (width <= parseFloat($("#" + this.id).attr('width')) && length <= parseFloat($("#" + this.id).attr('length'))) {
        ok = true;
        return false; // break out of each()
      }
    }
    else {
      if (length <= parseFloat($("#" + this.id).attr('length'))) {
        ok = true;
        return false; // break out of each()
      }
    }
  });
  
  return ok;
}


var isFraction = function(f) {
  var rv = true;
  if (f == '') {
    return true;
  }
  
  if (f.match(/^[\d]+\/[\d]+$/) == null) { 
    return false;
  }
  
  var a = f.split("/");
  if (!isInt(a[0]) || !isInt(a[1])) {
    return false;
  }
  
  var num = parseInt(a[0]);
  var den = parseInt(a[1]);
  
  if (num >= den) {
    return false;
  }
  
  if (num <= 0) {
    return false;
  }
  
  
  return rv;
}


var checkFractionDenominator = function(f) {
  var a = f.split("/");
  var d = a[1];
  if (d != 2 && d != 4 && d != 8 && d != 16 && d != 32) {
    return false;
  }
  
  return true;
}


var haveWidth = function() {
  var rv = false;
  if ($("#ccWidth").length > 0) {
    rv = true;
  }
  
  return rv;
}



//note: make sure that lightbox.js is loaded first. 
var loadAlloy = function(alloyList) { 
	parmNames = '';
	parmIds = '';
	alloyArray = alloyList.split(',');
	for (x in alloyArray) { 
		parmNames = parmNames + 'articleNames=metal' + x + '&';
		parmIds = parmIds + 'metal' + x + '.refid=' + alloyArray[x] + '&';
	}
	parms = parmNames + parmIds;
	lbMaskLoad();
	$("#lightboxload").after(ajaxBoxHTML);
	$("#lightbox").css("top",lbTopPos);
	lbLeftPos = (Math.round(winWidth/2))-200;
	$("#lightbox").css("left",lbLeftPos);
	$("#lightboxclose img").css("behavior","url(/iepngfix.htc)");
	$("#ajaxboxcontent").load("/product/includes/help-choose.jsp", parms, function(){
		$("#lightboxload").remove();
		//set the mask height again just to make sure we don't have the white space in the footer
		docHeight = $(document).height();
		$("#mask").css("height",docHeight);
		//show the content
		$("#lightboxutil img").css("behavior","url(/iepngfix.htc)");
		$("#lightbox").fadeIn('normal', function(){
			lbStage = 'loaded';
		});
		if($('#ajaxboxcopy').height() > 400) { 
			$('#ajaxboxcopy').css('height','400px');
			$('#ajaxboxcopy').css('overflow','auto');
			$('#ajaxboxcopy').css('width','325px');
			$('#ajaxboxcopy').css('padding-right','10px');
		}
	});
}


var getAlloy = function() {
  var rv = null;
  if ($("input[name='submetaltype']").length == 1) {
    rv = $("input[name='submetaltype']").val()
  }
  else {
    rv = $("input[name='submetaltype']:checked").val()
  }
  return rv;
}
