/* author: Don Kent, eShopHost Ltd */
/* Copyright (C) 2005-10, 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
1.21 22/02/07 3.2.1 added class TextInsert to div to give same <p> spacing behaviour as normal self-updates; 1.3 now removes all leading and lagging spaces from fields (not just 1st leading)
1.22 10/05/08 7.1 Bug fix: nested for loops were sharing same loop variable!
1.23 05/12/09 3 Remove unused fiddle for EGB rides from issue 1.7
	CN106, 16 3.3.2 support for: 'Add Picture 1 + caption as a standard on the index page (From CN11)'
1.24 05/03/10 BR119, 1.8 Text in Text2 has £ symbol stripped by NOF db component. Add htmlEscape to doSubmit()
*/

/* INSTRUCTIONS
	1. On index page: add script just before </body>: initClass (), autoAdjustImageSize()
	2. On item page: ditto
	3. On administration page for new or edit: ...
*/

/* CSS Classes set by this script InitClass() on the Index page for old NOF pages (set manually on Item page)
	Element id			CSS Class
	----------			---------
	Summary				IndexSummary
	Text1 & 2			IndexTextbox
	Text1Area & 2		IndexTextbox - aliases for Text1 & 2
	Filename1Area & 2	IndexFilename - applied to iframe within the specified element
*/

/* 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 file (text or image) 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;
var IndexImages = new Array (); // to do a final reveal of loaded images after window loaded


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 & trailing spaces if overlooked!
	var F1 = new Array ("Title", "Summary", "Text1", "Text2", "LinkText1", "LinkText2", "Filename1", "Filename2",  "PictureCaption1", "PictureCaption2", "FileCaption1", "FileCaption2");
	var F2 = new Array ("LinkURL1", "LinkURL2", "Picture1", "Picture2", "PictureURL1", "PictureURL2");
	var F = F1.concat(F2);
	for (var i = 0, k = form.length; i < k; i++) {
		for (var j = 0, l = F.length; j < l; 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 or lagging spaces from a filename! (not easy to see!)
					var field = form.elements[i].value;
					if (field.length > 1) {
						form.elements[i].value = field.replace(/^\s+|\s+$/g, "");
					}
				}
			}
		}
	}	

	// 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;
	var objEl;
	for (j = 0, l = F.length; j < l; 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;
	}
	
	// 1.8 HTML escape stuff - use array F1
	for (i = 0, l = F1.length; i < l; i++) {
		objEl = getObj(F1[i]);
		objEl.value = htmlEscape(objEl.value);
	}
	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 e.g. Text boxes or pictures
	// 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"); // Field ids of NOF component textareas
	var CNOF = new Array ("IndexSummary", "IndexTextbox", "IndexTextbox"); // classes
	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)$/i; // 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 class='TextInsert' 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
	// 3.3.1 ids of elements to show or hide: (ids with suffix 'Area' are also treated the same way)
	var Elements = new Array ("Text1", "Text2", "PictureURL1", "PictureURL2", "Filename1", "Filename2", "LinkURL1", "LinkURL2", "PictureURL3", "PictureCaption1", "PictureCaption2", "FileCaption1", "FileCaption2");
	// 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 they are part of parent Area.
	for (i = 0; i < Elements.length; i++) {
		ShowHide (Elements[i]); // A.
	}
	// 3.3.2 Special processing for PictureURL1 on index page
	// - find NOF labels with a class of: (uses <span> element)
	var className = "IndexPictureURL";
	var spans = document.getElementsByTagName ("span");
	var span;
	for (var i=0; i < spans.length; i++) {
		span = spans[i];
		if (span.className != className) continue; // incorrect span
		// - Does it contain a URL?
		if (span.innerText == " ") continue; // No
		// - find container
		var finished = false;
		var cont = span;
		var imgs = null, img;
		do {
			cont = cont.parentNode;
			if (! cont) {
				finished = true;
			} else {
				if (cont.className == className) {
					finished = true;
					// show container
					cont.style.display = "block";
					// add standard AutoHide (in case wrong URL) & AutoSize (to make fit)
					imgs = cont.getElementsByTagName ("img");
					img = imgs[0];
					if (img) {
						if (img.complete) {
							// already loaded
							// - just AutoSize as already visible
							AutoSize (img);
						} else {
							// not yet loaded
							// - add handler to onload event (handler does unhide & autosize)
							img.style.display = "none"; // hide first
							if (img.addEventListener) {
								img.addEventListener ("load", IndexAddHandler);
							} else if (img.attachEvent) {
								img.attachEvent ("load", IndexAddHandler);
							}
							IndexImages.push (img);
						}
					}
				}
			}
		} while (!finished)
	}
}

function IndexAddHandler (e) { // Helper to 3.3.2 - to set AutoHide & AutoSize to PictureURL1 on index page
	e = e ? e : (event ? event : null);
	if (!e) return;
	var img = e.target ? e.target : (e.srcElement ? e.srcElement : null);
	if (!img) return;
	AutoHideThis (img);
	AutoSize (img);
}

function IndexPictureShow () { // Helper to 3.3.2 - to set AutoHide & AutoSize to PictureURL1 on index page
	// Back-up - after window loaded - reveal & resize any index pictures that should be if actually loaded
	var img;
	for (var i = 0; i < IndexImages.length; i++) {
		img = IndexImages[i];
		if (img && img.complete) {
			img.style.display = "inline";
			AutoSize (img);
		}
	}
}
// direct code
	if (typeof Inits == "object") { // eShopHost standard Array for multiple initialisations on a page
		Inits.push (IndexPictureShow); // add to job list
	} else {
		window.onload = IndexPictureShow; // if no job list, just carry on as usual!
	};


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 (var j = 0; j < objP.childNodes.length; j++) {
				objPicture = objP.childNodes[j]; // 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();
}
