/* author: Don Kent, eShopHost Ltd */
/* Copyright (C) 2005, eShopHost Ltd. */

/* HISTORY
1.0, 11/01/05
1.1, 27/01/05 3. Added support for Filename1 and 2 - display of files
1.2, 31/01/05 4, 5. added
1.3, 02/02/05 3. extended to hide other elements. A. added
1.4, 06/02/05 3. extended to convert Filename areas into inline HTML if required. Prevents submit on CR for admin.
1.5, 20/02/05 7. Added auto-image resizing for any referenced PictureURL
1.6, 19/05/05 1.6 Enhanced test for object existence to avoid bomb out
1.7, 10/06/05 3. fiddle to support EGB
1.8, 26/06/05 doInline (3.2 helper). iframe source appears to be incomplete on occasion, so extra test & delay added.
1.9, 06/07/05 3.3 added "Text1" to be hidden if blank
1.10 11/07/05 Replace getElementById by getObj & .currentStyle by getStyleProperty for wider compatibility
1.11 12/07/05 Removed  getStyleProperty to eshophj1.js
1.12 04/08/05 Improvement on release 1.8 - using iframe window onload event to prevent timing problem. Also avoids outerHTML (Only IE) & fixes .txt inline display
1.13 22/08/05 1.3 added new fields PictureCaption1 & 2
1.14 19/10/05 1.3 added new fields FileCaption1 & 2
1.15 31/12/05 Cleaned up comments, improved comments. 3.3 Added new fields. 7.1 catered for missing container dimension
1.16 01/01/06 7.1 added test for 0 adjustment (can occur on initial load)
1.17 02/01/06 Helper 3.2 added test for zero source file content returned (NN7) and display a link instead
1.18 04/01/06 added new fields to be used by egb ride schedule - initclass()
1.19 15/02/06 7.1 bug fix on Hadj
1.20 05/10/06 1.7 added to avoid null title. 8 & B. added
*/

/* CONTENTS (utility functions for the IndexToItem function using the NOF dB Component)
	Public functions
1. doSubmit (form) - Populates/ Validates fields in newsadminrecordedit.asp
2. init (form) - Populates fields in newsadminrecordedit.asp
3. initClass () - assigns a class attribute to specified form controls produced by NOF dB Component; also initialises Filename1 & 2 display
4. SetTextFile () - sets the selected value of the text file into the href of the view button
5. SetModifyRecord (Type) - sets the ItemId of the selected text or image file into the query string for the href of the button
6. SetImageFile () - sets the selected value of the image file into the href of the view button
7. autoAdjustImageSize() - proportions a loaded image to fit into its containing box.
	(Test: AutoImageResizeFeature.html)
8. indextoitemnewinit () - sets the FROM & TO dates to today as the initial default

	Internal functions
A. ShowHide (ElementId)
B. TwoDigit (num)
*/

	/* Globals */
var iframeloaded = 0; // set to false and make true when onload event triggers
var SubmitButton = false; // Global for 1.0 - modified by event handlers on submit button
var objiframewin = new Array (); // Make global for 3.2 so are still valid after 3. completes
var divid = new Array ();
var iframeid, objFilename, Filename, objFilenameArea;


function doSubmit(form){ // 1. Admin - record update or new
	// 1.0 Don't submit on CR
	if (!SubmitButton) {return false;}

	// 1.1 Concatenate Date Fields
	form.DateFrom.value = form.FromY.value+form.FromM.value+form.FromD.value;
	form.DateTo.value = form.ToY.value+form.ToM.value+form.ToD.value; 

/*	// 1.2 Set default image filename
	var B = "PhotoHome99.gif"; // Standard 'blank' image
	if (form.Picture1.value == "") {form.Picture1.value = B;}
	if (form.Picture2.value == "") {form.Picture2.value = B;} */ // Not needed now as area blanked out

	// 1.3 Change null fields to space & remove leading spaces if overlooked!
	var F = new Array ("Title", "Summary", "Text1", "Text2", "LinkURL1", "LinkURL2", "LinkText1", "LinkText2", "Filename1", "Filename2", "Picture1", "Picture2", "PictureURL1", "PictureURL2", "PictureCaption1", "PictureCaption2", "FileCaption1", "FileCaption2");
	for (i = 0; i < form.length; i++) {
		for (j = 0; j < F.length; j++) {
			if (form.elements[i].name == F[j]) {
				if (form.elements[i].value == "") {
					// Put space in blank fields to avoid dB returning "null"
					form.elements[i].value = " ";
				} else {
					// Strip out any leading space from a filename! (not easy to see!)
					if (form.elements[i].value.length>1 && form.elements[i].value.charAt(0) == " ") {
						form.elements[i].value = form.elements[i].value.substr(1);
					}
				}
			}
		}
	}	

	// 1.4 Build Picture URL
	var P = "../assets/images/"; // Base URL
	if (form.Picture1.value != " ") {
		form.PictureURL1.value = P + form.Picture1.value;
	}
	if (form.Picture2.value != " ") {
		form.PictureURL2.value = P + form.Picture2.value;
	}

	// 1.5 Default value for Display Date
	if ((form.elements["DisplayDate"]) && (form.elements["DisplayDate"].value == "")) {
		form.elements["DisplayDate"].value = form.FromD.value + "/" + form.FromM.value + "/" + form.FromY.value;
	}

	// 1.6 Check that form data is not excessive - IE6 just does nothing if the URL is too long from using the GET method.
	var Count = 0;
	for (j = 0; j < F.length; j++) {
		objEl = getObj (F[j]);
		try {
			Count += objEl.value.length;
		} catch (e) {/* Just skip any error */}
	}
	if (Count > 2000) { // IE may allow ~2000
		alert ("Sorry, you have exceeded the capacity of the data allowed in the fields. Typically you will need to remove text from 'Text1' and/ or 'Text2' (and possibly 'Summary'). Please use one or more of the facilities: 'LinkURL1' (or 2) to refer to a web page; or 'Filename1' (or 2) to refer to an uploaded file (text file, etc.).");
		return false;
	}

	// 1.7 Check non-null title as required for the link!
	if (form.elements["Title"].value.search(/\w/) == -1) {
		alert ("Sorry, you must have a title!");
		return false;
	}
	return true;
}


function init (form){ // 2. For Admin
	// 2.1 Split Date fields & set the combo boxes
	var objSelect = new Array (form.FromY, form.FromM, form.FromD, form.ToY, form.ToM, form.ToD);
	var DateFrom = form.DateFrom.value;
	var DateTo = form.DateTo.value;
	var val = new Array (DateFrom.substr(0,4), DateFrom.substr(4,2), DateFrom.substr(6,2), DateTo.substr(0,4), DateTo.substr(4,2), DateTo.substr(6,2) );
	for (j = 0; j < 6; j++) {
		for (i = 0; i < objSelect[j].length; i++) {
			if (objSelect[j].options[i].value == val[j]) {
				objSelect[j].options[i].selected = true;
				continue;
			}
		}
	} 
}


function initClass () { // 3.
	// 1 Assigns a class attribute to specified form controls produced by NOF dB Component
	// 2 Initialises Filename1 & 2 display
	// 3 Hide or Show specific elements if null content

	// 3.1 Set class names on NOF textareas.
	// Note: Only FORM textareas.
	// Note: 'Summary' is not a form field on the public web page (only on Admin)
	var F = new Array ("Summary", "Text1", "Text2", "Details", "Classes1", "Classes2", "SpecialInstructions"); // Field ids of NOF component textareas
	var CNOF = new Array ("IndexSummary", "IndexTextbox", "IndexTextbox", "RideTextbox", "RideTextbox", "RideTextbox", "RideTextbox"); // class values
	for (i = 0; i < F.length; i++) {
		objF = getObj (F[i]);
		if (objF) {
			// Set class value as no other access to NOF component's output
			objF.className = CNOF[i];
		}
	}

	// 3.2 Initialise Filename display: iframe/ inline/ downloadable
	var Filenameids = new Array ("Filename1", "Filename2");
	var RegEx = /\.(txt|htm|html)$/; // Can display in iframe
	for (i = 0; i < Filenameids.length; i++) {
		objFilename = getObj(Filenameids[i]);
		if (objFilename) {Filename = objFilename.value;};
		objFilenameArea = getObj(Filenameids[i] + "Area");
		if (Filename != " ") { // Field not left empty (space char)
			if (RegEx.test(Filename)) { // Displayable file
				// 3.2.1 Display in iframe
				if (objFilenameArea) {
					iframeid = "iframeid" + i;
					divid[i] = "divid" + i;
					objFilenameArea.innerHTML = objFilenameArea.innerHTML + "<div id='" + divid[i] + "'><iframe id='" + iframeid + "' class='IndexFilename' src='../ItemFiles/" + Filename + "' onload='iframeloaded=1;'></iframe></div>";
//alert ("Display in iframe. objFilenameArea.innerHTML: " + objFilenameArea.innerHTML);
					// Display inline
					if (IndexFilenameBehaviour == "inline") {
						// var set by NOF variable
						// get body contents of file referenced by iframe and replace the iframe
						objiframewin[i] = getObj(iframeid).contentWindow;
//alert ("Display inline. objiframewin[i]: " + objiframewin[i]);
						if (objiframewin[i]) {
							doInline (i, Filename, 0); // Helper function that waits, then replaces the iframe
						}
					}
				}
			} else { // 3.2.2 Downloadable file
				// Link directly to it
				if (objFilenameArea) {
					objFilenameArea.innerHTML = objFilenameArea.innerHTML + "<p><a href='../ItemFiles/" + Filename + "' target='_blank'>Click: <img border='0'  src='../assets/images/downloadicon.gif'></a></p>";
				}
			}
		}
	}
	
	// 3.3 Hide or Show specific elements if null (space) or not
	var Elements = new Array ("Text1", "Text2", "PictureURL1", "PictureURL2", "Filename1", "Filename2", "LinkURL1", "LinkURL2", "PictureURL3", "PictureCaption1", "PictureCaption2", "FileCaption1", "FileCaption2", "Details", "Classes1", "Classes2", "SpecialInstructions");
	// Note: PictureURL3 added for fiddle on EGB home - 3 index areas with pictures!
	// Note: Caption elements are typically self-collapsing (Table row without non-breaking spaces), so don't need hidden adddressable field - i.e. OK to omit. Or part of parent Area.
	for (i = 0; i < Elements.length; i++) {
		ShowHide (Elements[i]);
	}
}

function doInline (i, Filename, Success) { // Helper to 3.2 - waits for loading
	var source = objiframewin[i];
	var target = divid[i];
	if (Success) {
		var RegEx = /\.(htm|html)$/i;
		var divhtml;
		if (RegEx.test(Filename)) { // HTML document
			divhtml = source.document.body.innerHTML;
			if (divhtml == "") { // For some reason, no content so put in a link!
				divhtml = "<p><a href='../ItemFiles/" + Filename + "' target='_blank'>Sorry, your browser does not support the required functionality. Please click: <img border='0'  src='../assets/images/downloadicon.gif'></a></p>";
			}
		} else { // assume text (.txt, etc.)
			divhtml =  "<p>" + source.document.body.innerText + "</p>";
		}
		getObj(target).innerHTML = divhtml;
		return;
	}
	if (source.document && source.document.body && getObj(target)) {
		if (iframeloaded) {
			setTimeout ("doInline(" + i + ", '" + Filename + "', 1)", 5);
			return;
		}
	}
	setTimeout ("doInline(" + i + ", '" + Filename + "', 0)", 100); // wait
}

function SetTextFile () { // 4.
	/* Sets the selected value of the text file into the href of a new window */
	var objFilesNotReferenced = getObj ("FilesNotReferenced"); // Select Tag
	if (objFilesNotReferenced) {
		var filename = objFilesNotReferenced.value;
		if (filename != "") {
			window.open ("../ItemFiles/" + filename, "newWin", "height=200, width=300, resizable=yes, scrollbars=yes, status=no, toolbar=no");
			return true;
		} else {
			alert ("Please select a file first!");
			return false;
		}
	} else {
		alert ("Refresh page to retry. If problem persists contact support. Error on page: objFilesNotReferenced not found.");
		return false;
	}
}

function SetModifyRecord (Type) { // 5.
	/* Sets the ItemId of the selected text or image file into the query string for the href of the button */
	var ElementId;
	if (Type == "Text") {
		ElementId = "FilesReferenced";
	} else {
		ElementId = "ImagesReferenced";
	}
	var objReferenced = getObj (ElementId); // Select Tag
	if (objReferenced) {
		var ItemId = objReferenced.value;
		if (ItemId == "") {
			alert ("Error  - please select the file that is referenced, at the top, before attempting to modify a record.");
			return false;
		}
		location.href = "../admin/newsadminrecordedit.asp?ItemId=" + ItemId;
		return true;
	} else {
		alert ("Refresh page to retry. If problem persists contact support. Error on page: objModifyRecord or objFilesReferenced not found.");
		return false;
	}
}

function SetImageFile () { // 6
	/* Sets the selected value of the image file into the href of a new window */
	var objImagesNotReferenced = getObj ("ImagesNotReferenced"); // Select Tag
	if (objImagesNotReferenced) {
		var filename = objImagesNotReferenced.value;
		if (filename != "") {
			window.open ("../assets/images/" + filename, "newWin", "height=200, width=100, resizable=yes, scrollbars=yes, status=no, toolbar=no");
			return true;
		} else {
			alert ("Please select a file first!");
			return false;
		}
	} else {
		alert ("Refresh page to retry. If problem persists contact support. Error on page: objImagesNotReferenced not found.");
		return false;
	}
}

function autoAdjustImageSize() { // 7. Called from web page
	// proportions a loaded image to fit into its containing box
	var k;
	for (k = 1; k <= 2; k++) {
		autoAdjustImage (k);
	}
}
function autoAdjustImage (Pic) { // 7.1
	var objArea = getObj("PictureURL" + Pic + "Area");
	if (objArea) { // got valid reference for containing object
		var i, objP, objPicture;
		for (i = 0; i < objArea.childNodes.length; i++) {
			objP = objArea.childNodes[i]; // 1st level - expect <p>
			for (i = 0; i < objP.childNodes.length; i++) {
				objPicture = objP.childNodes[i]; // 2nd level
				// alert ("Child Node found for Picture " + Pic + ". nodeName = " + objPicture.nodeName);
				if (objPicture.nodeName == "IMG") { // got image element
					// alert ("Image element found for Picture " + Pic);
					if (objPicture.complete) { // loaded, so process
						// alert ("loaded, so process for Picture " + Pic);
						var AreaW = getStyleProperty(objArea, "width");
						AreaW = AreaW.replace( /\D/g, "");
						var AreaH = getStyleProperty(objArea, "height");
						AreaH = AreaH.replace( /\D/g, "");
						var PictureW = objPicture.width;
						var PictureH = objPicture.height;
						// alert ("AreaW: " + AreaW + "; AreaH: " + AreaH + "; PictureW: " + PictureW + "; PictureH: " + PictureH);
						var Wadj = 0;
						if (PictureW > AreaW) {
							Wadj = 1 - (PictureW - AreaW)/PictureW;
						}
						var Hadj = 0;
						if (PictureH > AreaH) {
							Hadj = 1 - (PictureH - AreaH)/PictureH;
						}
						var Adj;
						Adj = Math.min(Wadj, Hadj);
						if (Adj == 0) { // probably one size limit not present
							Adj = Math.max(Wadj, Hadj); // so take the other
						}
						if (Adj > 0) {
							objPicture.width = Math.floor(PictureW * Adj);
							objPicture.height = Math.floor(PictureH * Adj);
						} else { // Zero dimension anomaly on 1st load can occur - just try again
							setTimeout ("autoAdjustImage(" + Pic + ")", 100);
						}
					} else { // image not loaded
						setTimeout ("autoAdjustImage(" + Pic + ")", 100);
					}
				} // end if got element object
			} // end for objP
		} // end for objArea
	} else { // containing object reference not yet valid
		setTimeout ("autoAdjustImage(" + Pic + ")", 100);
	}
}


function indextoitemnewinit () { // 8. sets the FROM & TO dates to today as the initial default
	var form = getObj("IndexToItemNew");
	if (!form) {
		form = getObj ("FromY").form;
	}
	if (form) {
		var objSelect = new Array (form.FromY, form.FromM, form.FromD, form.ToY, form.ToM, form.ToD);
		var D = new Date();
		var DateFrom = D.getFullYear() + TwoDigit(D.getMonth() + 1) + TwoDigit(D.getDate());
		D.setMonth(D.getMonth() + 1); // add 1 month
		var DateTo = D.getFullYear() + TwoDigit(D.getMonth() + 1) + TwoDigit(D.getDate());
		var val = new Array (DateFrom.substr(0,4), DateFrom.substr(4,2), DateFrom.substr(6,2), DateTo.substr(0,4), DateTo.substr(4,2), DateTo.substr(6,2) );
		for (j = 0; j < val.length; j++) {
			for (i = 0; i < objSelect[j].length; i++) {
				if (objSelect[j].options[i].value == val[j]) {
					objSelect[j].options[i].selected = true;
					continue;
				}
			}
		} 
	}
}


function ShowHide (ElementId) { // A.
	var objElement = getObj(ElementId);
	var FieldValue;
	if (objElement) {FieldValue = objElement.value;};
	var objElementArea = getObj (ElementId + "Area");
	if (objElementArea) {
		if (FieldValue == " ") { // Field left empty (space char)
			// Hide Area
			objElementArea.style.display = "none";
		} else { // Field populated
			// Show Area
			objElementArea.style.display = "block";
		}
	}
}


function TwoDigit (num) { // B.
	return num < 10 ? "0" + num : num.toString();
}
