/* 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. 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 */

/* CONTENTS of IndexToItem.js (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 */

	/* Internal functions */
/* A. ShowHide (ElementId) */

/* Known PROBLEMS:
3. displaying .txt file as 'inline' - seems to have the bare text surrounded by <pre> tag which will force the width out. Probably inserted through source.document.body.innerHTML
*/

var SubmitButton = false; // Global for 1.0 - modified by event handlers on submit button
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 overlloked!
	var F = new Array ("Title", "Summary", "Text1", "Text2", "LinkURL1", "LinkURL2", "LinkText1", "LinkText2", "Filename1", "Filename2", "Picture1", "Picture2", "PictureURL1", "PictureURL2");
	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;
	} else {
		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;
			}
		}
	} 
}

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 initClass () { // 3.
	// 3.1 Set class names on NOF textareas
	var F = new Array ("Summary", "Text1", "Text2"); // Field ids of NOF component textareas
	var CNOF = new Array ("IndexSummary", "IndexTextbox", "IndexTextbox"); // 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
	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 + "'></iframe></div>";
					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;
						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"); // PictureURL3 added for fiddle on EGB home - 3 index areas with pictures!
	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) {
		getObj(target).innerHTML = source.document.body.innerHTML;
		return;
	}
	var RegEx = /\.(htm|html)$/i;
	if (source.document && source.document.body && getObj(target)) {
		if (RegEx.test(Filename)) { // HTML document
			// alert (source.document.body.outerHTML); // Debug
			if (source.document.body.outerHTML &&
				source.document.body.outerHTML.search(/<\/body>/i) != -1) {
				// alert ("An html file. </body> found.\nLast 20 characters of outerHTML:\n" + source.document.body.outerHTML.slice(source.document.body.outerHTML.length-21) + "\nLast 20 characters of innerHTML:\n" + source.document.body.innerHTML.slice(source.document.body.innerHTML.length-21)); // Debug
				// Still having timing problems?!! - so wait another 100ms
				setTimeout ("doInline(" + i + ", '" + Filename + "', 1)", 200);
				return;
			}
		} else { // .txt
			// alert ("Assuming a text file"); // Debug
			// wait a bit longer
			 setTimeout ("doInline(" + i + ", '" + Filename + "', 1)", 200);
			return;
		}
	}
	setTimeout ("doInline(" + i + ", '" + Filename + "', 0)", 100);
}

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.
	// 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) {
							objPicture.width = Math.floor(PictureW * Adj);
							objPicture.height = Math.floor(PictureH * Adj);
						}
					} 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 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";
		}
	}
}