// ---------------------------------------------------------------------------------------
// parknpool/includes/javascript/model_review_info.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.
// 2009/03/10 Copy from product_order_2.js and modify for model_info files.
// 2009/08/03	Add code to handle product review functionality.
// ---------------------------------------------------------------------------------------

// We can define these immediately...
// Global variables to handle error messages...
//alert("model_info.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...
//============================================================
$(document).ready(function() {
	//alert("Document Ready!");
	// Take care of some display details...
//	alert("miSecFeaturesTab background: " + $("#miSecFeaturesTab").css("background-image"));
	$("#miSecFeaturesTab").css("background-image", "url(images/tabs/model_info_section_tab_active.gif)");
	$("#miSecFeaturesTab5").css("background-image", "url(images/tabs/model_info_section_tab_active5.gif)");
	$("#miSecFeaturesTab6").css("background-image", "url(images/tabs/model_info_section_tab_active6.gif)");
	
	// 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.

	// When mouse is over Expand Rating Image, fade in the rating list...
	$("#miExpRating").hoverIntent(function(){
//		alert(subCatID + ' Fade In');
		$("#miRatHist").fadeIn("slow");
	},function(){
		$("#miRatHist").fadeOut("slow");
	}); // End When mouse is over Category Link.

	// When section tab is clicked, call function to change tab image and display appropriate section...
	$(".miSecTab").click(function(){
		//alert('in $(".miSecTab").click');
		$(".miSecTab").each(function(i) {
			$(this).css("background-image", "url(images/tabs/model_info_section_tab_inactive.gif)");
			secID = $(this).attr("id");
			secID = secID.substr(0, secID.indexOf("Tab"));
			$("#" + secID).css("display", "none");
		});
		$(this).css("background-image", "url(images/tabs/model_info_section_tab_active.gif)");
		secID = $(this).attr("id");
		secID = secID.substr(0, secID.indexOf("Tab"));
		$("#" + secID).css("display", "block");
	}); // End section tab click.

	// When section tab is clicked, call function to change tab image and display appropriate section...
	$(".miSecTab5").click(function(){
		//alert('in $(".miSecTab5").click');
		$(".miSecTab5").each(function(i) {
			$(this).css("background-image", "url(images/tabs/model_info_section_tab_inactive5.gif)");
			secID = $(this).attr("id");
			secID = secID.substr(0, secID.indexOf("Tab"));
			$("#" + secID).css("display", "none");
		});
		$(this).css("background-image", "url(images/tabs/model_info_section_tab_active5.gif)");
		secID = $(this).attr("id");
		secID = secID.substr(0, secID.indexOf("Tab"));
		//alert('Section to Display: ' + secID);
		$("#" + secID).css("display", "block");
	}); // End section tab 5 click.

	// When section tab is clicked, call function to change tab image and display appropriate section...
	$(".miSecTab6").click(function(){
		//alert('in $(".miSecTab6").click');
		$(".miSecTab6").each(function(i) {
			$(this).css("background-image", "url(images/tabs/model_info_section_tab_inactive6.gif)");
			secID = $(this).attr("id");
			secID = secID.substr(0, secID.indexOf("Tab"));
			$("#" + secID).css("display", "none");
		});
		$(this).css("background-image", "url(images/tabs/model_info_section_tab_active6.gif)");
		secID = $(this).attr("id");
		secID = secID.substr(0, secID.indexOf("Tab"));
		$("#" + secID).css("display", "block");
	}); // End section tab 6 click.

	// When section tab is clicked, call function to change tab image and display appropriate section...
	$("#miReadReviews").click(function(){
		$(".miSecTab6").each(function(i) {
			$(this).css("background-image", "url(images/tabs/model_info_section_tab_inactive6.gif)");
			secID = $(this).attr("id");
			secID = secID.substr(0, secID.indexOf("Tab"));
			$("#" + secID).css("display", "none");
		});
		$("#miSecReviewsTab6").css("background-image", "url(images/tabs/model_info_section_tab_active6.gif)");
		$("#miSecReviews").css("display", "block");
	}); // End Read Reviews click.

	// When the Review Sort Menu changes, call function to use ajax to get newly sorted html...
	$("#miReviewSortMenu").change(function(){
		sortID = $(this).val();
		revSortPID = $("#miReviewSortProductID").val();
		revSortPage = $("#miReviewSortPage").val();
		//alert('Sort By: ' + sortID + ', PID: ' + revSortPID + ', Page: ' + revSortPage);
    $.post("review_sort.php", {
			revSort: sortID, pID: revSortPID, revPage: revSortPage
		}, function(html) {
			$("#miSecReviewsDisplay").html(html);
		});
	}); // End section tab click.

	// When the Review Sort Menu changes, call function to use ajax to get newly sorted html...
	$(".miRvwNewPg").live("click", function(){
		sortID = $("#miReviewSortMenu").val();
		revSortPID = $("#miReviewSortProductID").val();
		revSortPage = $(this).attr("title");
		$("#miReviewSortPage").val(revSortPage);
		//alert('Sort By: ' + sortID + ', PID: ' + revSortPID + ', Page: ' + revSortPage);
    $.post("review_sort.php", {
			revSort: sortID, pID: revSortPID, revPage: revSortPage
		}, function(html) {
			$("#miSecReviewsDisplay").html(html);
		});
	}); // End section tab click.

	// When Review Helpful is clicked, use Ajax to update server database...
	$(".miRvwHlpUpd").live("click", function(){
		elemID = $(this).attr("id");
		revID = elemID.substr(0, elemID.indexOf("rh"));
		helpfulFlag = elemID.substr((elemID.indexOf("rh")+2), 1);
		//alert('revID:' + revID + ', hFlag: ' + helpfulFlag);
    $.post("review_helpful_update.php", {
			rID: revID, hFlag: helpfulFlag
		}, function() {
			alert('Thank you for your input.');
		});
	}); // End section tab click.

	// When Inappropriate Content is clicked, use Ajax to update server database...
	$(".miRvwConFlg").live("click", function(){
		revID = $(this).attr("id");
		revID = revID.substr(0, revID.indexOf("cf"));
		//alert('revID:' + revID);
    $.post("review_flag_content.php", {
			rID: revID
		}, function() {
			alert('This review has been marked for inspection.  Thank you for bringing it to our attention.');
		});
	}); // End section tab click.

	// When model image is clicked, call function to display in seperate window...
	$(".model_image").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 = '<!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.

	// 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.

	// When section tab is clicked, call function to change tab image and display appropriate section...
	$(".miOptLabel").click(function(){
		// Hide all sections...
		$(".miSecTab").each(function(i) {
			$(this).css("background-image", "url(images/tabs/model_info_section_tab_inactive.gif)");
//			$(this).css("background-image", "url(images/tabs/itab-mid.gif)");
			secID = $(this).attr("id");
			secID = secID.substr(0, secID.indexOf("Tab"));
			$("#" + secID).css("display", "none");
		});
		$(".miSecTab5").each(function(i) {
			$(this).css("background-image", "url(images/tabs/model_info_section_tab_inactive5.gif)");
//			$(this).css("background-image", "url(images/tabs/itab-mid.gif)");
			secID = $(this).attr("id");
			secID = secID.substr(0, secID.indexOf("Tab"));
			$("#" + secID).css("display", "none");
		});
		$(".miSecTab6").each(function(i) {
			$(this).css("background-image", "url(images/tabs/model_info_section_tab_inactive6.gif)");
//			$(this).css("background-image", "url(images/tabs/itab-mid.gif)");
			secID = $(this).attr("id");
			secID = secID.substr(0, secID.indexOf("Tab"));
			$("#" + secID).css("display", "none");
		});
		// Show options section...
		$("#miSecOptionsTab").css("background-image", "url(images/tabs/model_info_section_tab_active.gif)");
		$("#miSecOptionsTab5").css("background-image", "url(images/tabs/model_info_section_tab_active5.gif)");
		$("#miSecOptionsTab6").css("background-image", "url(images/tabs/model_info_section_tab_active6.gif)");
		$("#miSecOptions").css("display", "block");
		// Move to Tabs Anchor...
//		$.scrollTo( 0 );
		$.scrollTo( '#miSecTabs', 800, {easing:'easeinout'} )
	}); // End section tab 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 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;
				errorMsg += optError + $(this).attr("title");
			}
		});
		if (entryError) {
			alert(errorMsg);
			return false;
		} else {
			return true;
		}
	}); // End addForm submit.
}); // End document ready.
//      curModelImage = $(#model_image).src;
	  

