/* file:     js_Purchase_ValidateForm.js */
/* version:  v1.1 1/5/05 */
/* author:   Jake Roztocil v1.0 on 12/29/04 */
/* contact:  Jake.Roztocil[at]gmail[dot]com */
/* included by: /purchase.php */
/* purpose:  fix client-side validation issues with dynamically sized forms
             submit problems with larger number of items selected for purchase */

function ValidateForm(){
	with(document.Purchase) {
		// init num items on the page and the first picID
		var numItems = document.Purchase['data[]'].length;
		var picID = document.Purchase['data[]'][0].value.split("|")[0];
		// init qtyCounter, the array of quantities (aNumPics), and the running tally of pics
		var qtyCount = 0;
		var aNumPics = new Array();
		var aPicIDs = new Array();
		var picCounter = 0;
		
		// accumulate the quantities selected in aNumPics
		for (picCount=0;picCount<numItems;picCount++) {
			if (picID == document.Purchase['data[]'][picCount].value.split("|")[0]) {
				// we are on the same picID so add the picItem's quantity to qtyCount
				qtyCount = qtyCount + Number(document.Purchase['inputs[]'][picCount].value);
				aPicIDs[picCounter] = picID;
			} else {
				// we have a new picID so:
				// assign our aNumPics array with the its quantity of items and increment picCounter
				aNumPics[picCounter] = qtyCount;
				picCounter++;
				// set the next picID and start qtyCount counting again
				picID = document.Purchase['data[]'][picCount].value.split("|")[0];
				qtyCount = Number(document.Purchase['inputs[]'][picCount].value);
			}
			if (picCount == numItems-1) {
				// we are on the last iteration and need to save the last data set
				aNumPics[picCounter] = qtyCount;
			}
		}
		
		//display a message box with the quantities selected if debug is enabled
		var bDebug = false;
		var bAlertUser = false;
		var picsWithNoQty = "";
		var msg = "Quantities Selected:\n\n";
		var picMsg = " number ";
        for (picNum=1;picNum<=aNumPics.length;picNum++) {
			msg = msg + "Pic number " + picNum + " (PicID: " + aPicIDs[picNum-1] + ") has " + aNumPics[picNum-1] + " items selected.\n";
			if (aNumPics[picNum-1]==0) {
				bAlertUser = true;
				if (picsWithNoQty.length == 0) {
					picsWithNoQty = picsWithNoQty + picNum;
                } else {
					picsWithNoQty = picsWithNoQty + ", " + picNum;
                    picMsg = "s ";
				}	
			}
		}
		if (bDebug) alert(msg);
		
		if (bAlertUser) {
			alert("Please enter a quantity greater than zero for at least one size per picture.");
			alert("Picture" + picMsg + "with no quantity selected: " + picsWithNoQty);
			// implement in v2.0
			//document.Purchase['inputs[]'][picIndex].focus();
			return false;						
		}
	}
	return true;
}