// ---------------------------------------------------------------------------------------
// parknpool/includes/javascript/product_order_2.js
// Created:      2007-03-16
// Copyright (c) 2007 by ParknPool Corp., all rights reserved.
//
// 2007/03/16	Copied from product_order_css.php
// 2007/07/03	Copied from product_order.js.  Modified for rewrite using jQuery.
//				(jQuery-1.1.3.js must be loaded first.)
// 2008/05/12	Add code to handle modal window (nyroModal).
// 2008/06/04	Move code to handle modal window to another js file specific to model.
// ---------------------------------------------------------------------------------------

// We can define these immediately...
// Global variables to handle error messages...
//alert("product_order.js!");
var qtyError = "(def) Enter a quantity greater than zero.";
var optError = "(def) Select a choice for ";
var modelChildArray = new Array();

function setQtyError(errorText) {
//	alert('setQtyError! ' + errorText); 
	qtyError = errorText;
}

function setOptError(errorText) {
//	alert('setQtyError! ' + errorText); 
	optError = errorText;
}
	
function currency_format(num_str) {
	// Move decimal point right two places...
	var num_str = "" + Math.round(eval(num_str) * 100)
	// Pad with zero to left, if necessary...
	if (num_str.length < 2) {
		num_str = "00" + num_str
	} else if (num_str.length < 3) {
		num_str = "0" + num_str
	}
	// Establish location of decimal point...
	var decpoint = num_str.length - 2
	// Put decimal point into number...
	num_str = num_str.substring(0, decpoint) + "." + num_str.substring(decpoint, num_str.length)
	// Return number with dollar sign...
	return "$" + num_str
}

function modelChildObj(avp, mc, m, up, cp, pl, w) {
//	alert("modelChildObj - AVP:" + avp + ", Model Code: " + mc + ", Multiplier: " + m + ", Price: " + p + ", Weight: " + w);
	this.aidVidPairs = avp;
	this.modelCode = mc;
	this.multiplier = m;
	this.unitPrice = up;
	this.casePrice = cp;
	this.priceLable = pl;
	this.weight = w;
}

//============================================================
// Wait for document...
//============================================================

//============================================================
// Wait for document...
//============================================================
$(document).ready(function() {
//	alert("Document Ready!");
	// Global variables (within ready function) to handle separate display window...
	var content, infoWin;
	var infoWinStatus = false;

	function newWindow(x) {
		// alert('begin newWindow()');
		x.document.close();
		x.document.open();
		x.document.write(content);
		x.document.close();
		x.moveTo(10,10);
		x.focus();
	}

	function updateCodePriceWeight() {
		var quantity = parseInt($("#qty").val());
		if ( isNaN(quantity) || (quantity < 1) ) {
			// Invalid entry, send message, then reset to 1...
			$("#qty").val("1");
			quantity = 1;
		}
//		alert("product_order.js - updateCodePriceWeight! Quatity: " + quantity);

		// Retrieve option value aid and vid...
		var aidArray = new Array();
		var vidArray = new Array();
		var aidVidPairArray = new Array();
		var aid0PairArray = new Array();
		$(".option").each(function(i) {
			optionValue = $(this).val();
			ovArray = optionValue.split("_");
			aidArray[i] = ovArray[0];
			vidArray[i] = ovArray[1];
			aidVidPairArray[i] = ',' + aidArray[i] + '_' + vidArray[i] + ',' ;
			aid0PairArray[i] = ',' + aidArray[i] + '_0,' ;
			optCount = i + 1;
//			alert("updateCodePriceWeight-88! Count: " + optCount + ", Option Value: " + optionValue + ", AID VID Pair: " + aidVidPairArray[i] + ", AID 0 Pair: " + aid0PairArray[i]);
		});
//		alert("updateCodePriceWeight! Size of Model Child Array: " + modelChildArray.length);

		// Find child that matches selected option values (aid_vid pairs)...
		for (i = 0; i < modelChildArray.length; i++) {
			var mcMatch = true; // Assume a match to start.
			for (j = 0; j < optCount; j++) {
//				alert("updateCodePriceWeight-96! MC Count: " + i + ", AVP Count: " + j + ", Child AVPs: " + modelChildArray[i].aidVidPairs + ", AID VID Pair: " + aidVidPairArray[j] + ", AID 0 Pair: " + aid0PairArray[j]);
				if ((modelChildArray[i].aidVidPairs.indexOf(aidVidPairArray[j]) == -1) && (modelChildArray[i].aidVidPairs.indexOf(aid0PairArray[j]) == -1)) {
//					alert("updateCodePriceWeight-98! No Match");
					mcMatch = false;
					break;
				}
			}
//			if (mcMatch) { alert("Match") } else { alert("No Match") };
			if (mcMatch) {
				// We have a match, set model code price and weight...
				if (modelChildArray[i].multiplier == 1) {
					var newQtyLabel = ' each';
				} else {
					if (quantity == 1) {
						var newQtyLabel = ' case pack';
					} else {
						var newQtyLabel = ' case packs';
					}
				}
				var newCode = modelChildArray[i].modelCode;
				var newUnitPrice = modelChildArray[i].unitPrice;
				var newCasePrice = modelChildArray[i].casePrice;
				var newWeight = modelChildArray[i].weight;
		
				// Account for quantity and format for display...
				newCasePrice = quantity * newCasePrice;
//				alert("updateCodePriceWeight! New Unit Price: " + newUnitPrice + ", New Case Price: " + newCasePrice);
				if (newUnitPrice != newCasePrice) {
					newUnitPrice = '(' + currency_format(newUnitPrice) + ' each)';
				} else {
					newUnitPrice = '';
				}
				newCasePrice = currency_format(newCasePrice);
				newWeight = quantity * newWeight + " lbs.";
//				alert("updateCodePriceWeight! Quantity: " + quantity + ", New Code: " + newCode + ", New Unit Price: " + newUnitPrice + ", New Case Price: " + newCasePrice + ", New Weight: " + newWeight);

				// Display
				$("#qtyLabelVal").text(newQtyLabel);
// Do not update model code - keep it simple for the customer...
//				$("#modelCodeVal").text(newCode);
				$("#unitPriceVal").text(newUnitPrice);
				$("#casePriceVal").text(newCasePrice);
				$("#weightVal").text(newWeight);
				break;
			} // End if mcMatch.
		} // End for each model child
	} // End function updateCodePriceWeight.

	function updatePriceWeight() {
		quantity = parseInt($("#qty").val());
//		alert("updatePriceWeight! " + quantity + ', Unit Price: ' + $("#unitPrice").val() + ', Unit Weight: ' + $("#unitWeight").val());

		// Retrieve option value price and weight adjustments, if any...
		priceAdj = new Array();
		weightAdj = new Array();
		$(".option").each(function(i) {
			optionValue = $(this).val();
			ovArray = optionValue.split("_");
			priceAdj[i] = ovArray[2];
			weightAdj[i] = ovArray[3];
			optCount = i + 1;
//			alert("updatePriceWeight! Count: " + optCount + ", Option Value: " + optionValue + ", PA: " + priceAdj[i] + ", WA: " + weightAdj[i]);
		});
//		alert("updatePriceWeight! Option Count: " + optCount);

		// Initialize price and weight...
		newPrice = parseFloat($("#unitPrice").val());
		newWeight = parseInt($("#unitWeight").val());

		// Add any adjustments to price and weight...
		for (i = 0; i < optCount; i++) {
			newPrice += parseFloat(priceAdj[i]);
			newWeight += parseInt(weightAdj[i]);
		}

		// Add any adjustments to price and weight...
		newPrice = currency_format(quantity * newPrice);
		newWeight = quantity * newWeight + " lbs.";
//		alert("updatePriceWeight! New Price: " + newPrice + ', New Weight: ' + newWeight);
		$("#priceVal").text(newPrice);
		$("#weightVal").text(newWeight);
	}
	
	// Create elasticity of model add-to-cart box...
	optionWidth = 0; // Will be maximum width of the option menus, if any.
	$(".option").each(function() {
		itemWidth = $(this).width();
		if (itemWidth > optionWidth) optionWidth = itemWidth;
//		alert("Option Width: " + itemWidth);
	});
	optionWidth += 6; // Allow for padding within model add-to-cart box.
//	alert("Max Option Width plus Padding: " + optionWidth);
	if (optionWidth < 200) optionWidth = 200; // Norrowest box allowed.
	$("#picModelBox").width(optionWidth);
	
	// When alt image is clicked, make the current model image the alt image...
	$(".altImage").mouseover(function(){
//		alert("altImage click! " + $(this).attr("src") + $("#model_image").attr("src"));
		$("#model_image").attr({ src: $(this).attr("src") });
		$("#model_image").attr({ alt: $(this).attr("alt") });
	}); // End altImage click.

	// When model image is clicked, call function to display in seperate window...
	$(".altImage").click(function(){
		// Prepare image...
		var bigImage = $(this).attr("src");
		var regexp = /_h.jpg/;
		bigImage = bigImage.replace(regexp, "_f.jpg");
//		alert("model_image click! " + bigImage);

		// Prepare text...
		var modDesc = $(this).attr("alt");
		modDesc = modDesc.split("~");

		content = '<html><head><title>Model Image Display - ParknPool</title></head>'
		content += '<base href="http://www.parknpool.com" />'
		content += '</head>'
		content += '<body>'
		content += '  <div style=\"text-align:right;\"><a href=\"javascript:window.print()\">Print window</a>&nbsp;&nbsp;<a href=\"javascript:window.close()\">Close window</a></div>'
		content += '  <hr />'
		content += '  <div style=\"text-align:center;\">'
		content += '    <h2 style="text-align:center;">' + modDesc[0] + '</h2>'
		content += '    <img src="' + bigImage + '">'
		content +=  '   <br clear="all" />' + modDesc[1]
		content += '  </div>'
		content += '  <hr />'
		content += '  <div style=\"text-align:right;\"><a href=\"javascript:window.print()\">Print window</a>&nbsp;&nbsp;<a href=\"javascript:window.close()\">Close window</a></div>'
		content += '</body></html>'
		infoWin = open('', 'productImageWindow','width=750,height=550,scrollbars=1,resizable=1')
		newWindow(infoWin)
		infoWin.focus()
		infoWinStatus = true;
	}); // End model image click.

	// When model image is clicked, call function to display in seperate window...
	$("#model_image").click(function(){
		// Prepare image...
		var bigImage = $("#model_image").attr("src");
		var regexp = /_h.jpg/;
		bigImage = bigImage.replace(regexp, "_f.jpg");
//		alert("model_image click! " + bigImage);

		// Prepare text...
		var modDesc = $("#model_image").attr("alt");
		modDesc = modDesc.split("~");

		content = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
		content += '<html><head><title>Model Image Display - ParknPool</title>'
		content += '<base href="http://www.parknpool.com" />'
		content += '</head>'
		content += '<body>'
		content += '  <div style=\"text-align:right;\"><a href=\"javascript:window.print()\">Print window</a>&nbsp;&nbsp;<a href=\"javascript:window.close()\">Close window</a></div>'
		content += '  <hr />'
		content += '  <div style=\"text-align:center;\">'
		if ((modDesc[0] != null) && (modDesc[0] != '')) content += '    <h2 style="text-align:center;">' + modDesc[0] + '</h2>'
		content += '    <img src="' + bigImage + '" />'
		if ((modDesc[1] != null) && (modDesc[1] != '')) content +=  '   <br clear="all" />' + modDesc[1]
		content += '  </div>'
		content += '  <hr />'
		content += '  <div style=\"text-align:right;\"><a href=\"javascript:window.print()\">Print window</a>&nbsp;&nbsp;<a href=\"javascript:window.close()\">Close window</a></div>'
		content += '</body></html>'
		infoWin = open('', 'productImageWindow','width=750,height=550,scrollbars=1,resizable=1')
		newWindow(infoWin)
		infoWin.focus()
		infoWinStatus = true;
	}); // End model image click.

	// Validate quantity entered. Upon change, check for integer value > 0...
	$("#qty").change(function(){
		quantity = parseInt($(this).val());
//		alert("qty change! " + $(this).val() + " parseInt = " + quantity);
		if ( isNaN(quantity) || (quantity < 1) ) {
			// Invalid entry, send message, then reset to 1...
//			alert(qtyError);
			$(this).val("1");
		}
		updateCodePriceWeight();
	}); // End qty change click.

	// Upon change, update...
	$(".option").change(function(){
		quantity = parseInt($("#qty").val());
		if ( isNaN(quantity) || (quantity < 1) ) {
			// Invalid entry, send message, then reset to 1...
			$("#qty").val("1");
		}

		updateCodePriceWeight();
	}); // End option change.

	// Upon submit, check...
	$("form#addForm").submit(function(){
		entryError = false;
		errorMsg = '';
		quantity = parseInt($("#qty").val());
		if ( isNaN(quantity) || (quantity < 1) ) {
			// Invalid entry, send message, then reset to 1...
			entryError = true;
			errorMsg += qtyError;
			$("#qty").val("1");
		}

		$(".option").each(function(i) {
			optionValue = $(this).val();
			idArray = optionValue.split("_");
			if (idArray[1] == "0") {
				if (entryError) errorMsg += "\n";
				entryError = true;
//				alert($(".optLabel").eq(i).text());
				errorMsg += optError + $(this).attr("title");
			}
		});
		if (entryError) {
			alert(errorMsg);
			return false;
		} else {
			return true;
		}
	}); // End addForm submit.
}); // End document ready.
//      curModelImage = $(#model_image).src;
	  

