/* FILE INFO ************

File:		general_site_scripts.js
Module:		N/A
Author:		istvan
Purpose:	JS scripts that are accessible to any page.

Name		Date			Description
================================================================================
istvan		2005/06/24		Created this header comment.
istvan		2005/06/24		Added 'openAddToCart()' for use for displaying add.cfm and addtobasket.cfm in shoppingcart and photoalbum, respectively.

********************** */


// Tick all checkboxes with the specified name.
/*
Args:
theForm		- The name of the form.
theField	- The name of the checkboxes to affect.
doCheck		- Either true or false; use true to tick all boxes, use false to untick all boxes.

Usage examples:
	As a checkbox:
	<input type="checkbox" name="x" value="y" onmouseup="var action=false; if (this.checked == true) action=false; else action=true; tickAllBoxes('formName','fieldName',action);">

	As a set of links:
	<a href="javascript:void(0);" onclick="javascript:tickAllBoxes('formName','fieldName',true); return false;">tick all boxes</a>
	<a href="javascript:void(0);" onclick="javascript:tickAllBoxes('formName','fieldName',false); return false;">un-tick all boxes</a>
*************************** */

function tickAllBoxes(theForm,theField,doCheck)
	{
	var elts = document.forms[theForm].elements[theField];
    var elts_cnt  = (typeof(elts.length) != 'undefined') ? elts.length : 0;
	if (elts_cnt)
		{
        for (var i = 0; i<elts_cnt; i++) { elts[i].checked = doCheck; }
    	}
    else
    	{
    	elts.checked = doCheck;
    	}
    return true;
	}



// Make confirmation box with given 'message', then proceed to the given 'page'.

function popWin(page,message)
	{ if (confirm(message)) location.href = page; }



// Create empty window for the add.cfm file to be loaded into (when adding items to the cart)
// Used on eg: /shoppingcart/display.cfm and /shoppingcart/default.cfm

function openAddToCart()
	{
	var w_width = 210;
	var w_height = 45;

	if ((window.innerWidth >= 0) && (window.innerHeight >= 0))
		{
		winW = window.innerWidth;
		winH = window.innerHeight;
		}
	else if ((document.body.offsetWidth >= 0) && (document.body.offsetHeight >= 0))
		{
		winW = document.body.offsetWidth;
		winH = document.body.offsetHeight;
		}

    var winl = (winW - (w_width / 2)) / 2;
    var wint = (winH - (w_height / 2)) / 2;

	// alert('width: '+winW+', height: '+winH+' --- left: '+winl+', top: '+wint);

	NFW = window.open('','addwindow','toolbar=no,width='+w_width+',height='+w_height);
    NFW.moveTo(winl,wint);
	}



// Read cookie

function read_cookie(name)
	{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
		{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
	return null;
	}



// Delete a cookie
function delete_cookie(cookie_name)
	{
	var kill_time = new Date("November 30, 1975");
	var kill_string = "client_name="+cookie_name+";expires=" + kill_time.toGMTString();
	document.cookie = kill_string;
	}



// Cross browser printing ------------------------
// --- Istvan - 25/05/2004
function printit()
	{
	if (window.print) { window.print(); }
		else
		{
		var WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>';
		document.body.insertAdjacentHTML('beforeEnd', WebBrowser);
		WebBrowser1.ExecWB(6, 2); //Use a 1 vs. a 2 for a prompting dialog box    WebBrowser1.outerHTML = "";
		}
	}



// trim() function - Does what trim() does in, for example, ColdFusion or PHP. -------------------------
// Returns the trimmed string.
// --- Istvan - 25/05/2004

function trim(s)
	{
	if (typeof s != "string") return s;
	else
		{
		// Remove leading spaces and carriage returns
		while ((s.substring(0,1) == ' ') || (s.substring(0,1) == '\n') || (s.substring(0,1) == '\r')) { s = s.substring(1,s.length); }
		// Remove trailing spaces and carriage returns
		while ((s.substring(s.length-1,s.length) == ' ') || (s.substring(s.length-1,s.length) == '\n') || (s.substring(s.length-1,s.length) == '\r')) { s = s.substring(0,s.length-1); }
		return s;
		}
	}



// --- Delayed pop-up-subscribe window --------------------------------------------------------------
// --- Istvan - 15/01/2004


// -- Optional feature to automatically close the pop-up window after a defined amount of time. --
closetime = 0; // '0' means don't close automatically.

function Start(url, width, height) {
// -- Creates the popup window with 'delay' seconds delay. --
	windowprops = "left=50,top=50,width=" + width + ",height=" + height;
	preview = window.open(url, "preview", windowprops);
	if (closetime) setTimeout("preview.close();", closetime*1000);
	}

function doPopup(url, width, height, delay) {
// -- Sets up to create the popup window. --
	// These variables are sent through the "readPopupCookie()" function in the pagestart.cfm file.
	// url = Link to the pop-up file. I.e.: '/popup.cfm'
	// width = Width of window in pixels. I.e.: '300'
	// height = Height of window in pixels. I.e.: '200'
	// delay = Time in seconds before popup opens. I.e.: '10'
	url1 = url;
	width1 = width;
	height1 = height;
	timer = setTimeout("Start(url1, width1, height1)", delay*1000);
	}

function getDaysExpiry(noDays){
// -- Calculate expiry time when days are used. --
    var today = new Date();
    var expr = new Date(today.getTime() + noDays*24*60*60*1000);
    return expr.toGMTString();
	}

function getHoursExpiry(noHours){
// -- Calculate expiry time when hours are used. --
    var today = new Date();
    var expr = new Date(today.getTime() + noHours*60*60*1000);
    return expr.toGMTString();
	}

function wwwPathToDomainName(www_path){
// -- Remove 'http://', 'www.' and 'www.members.' from 'www_path' --
	var pattern1 = /\bhttp:\/\//ig; // anything that begins with 'http://'.
	var pattern2 = /\bwww\./ig; // anything that begins with 'www.'.
	var pattern3 = /\bmembers\./ig; // anything that begins with 'members.'.
	siteDomainA = www_path.replace(pattern1,""); // replace 'http://' with nothing... ie: remove it.
	siteDomainB = siteDomainA.replace(pattern2,""); // replace 'www.' with nothing... ie: remove it.
	siteDomain = siteDomainB.replace(pattern2,""); // if after removing 'www.' the remaining string begins with 'members.', replace that with nothing as well... ie: remove it.
	return siteDomain;
	}

function readPopupCookie(siteID, url, width, height, delay, num_hours, www_path){
// -- Checks and/or makes pop-up cookie and runs pop-up function if no disabling cookies have been set. --
// -- Set in the 'pagestart.cfm' file. --
	var siteDomain = wwwPathToDomainName(www_path); // Clean-up www_path.
	var smShownPop = 'smShownPop' + siteID; // Make name of cookie.
	var smSubscribed = 'smSubscribed' + siteID; // Make name of cookie.

	var smShownPopC = document.cookie.indexOf(smShownPop); // This exists if popup has alredy appeared within 'num_hours'.
	var smSubscribedC = document.cookie.indexOf(smSubscribed); // This exists if someone has already submitted through the popup within 'num_days' (set in the 'subscribed()' function below).

    if (smShownPopC == -1 && smSubscribedC == -1) { // If no pop-up disabling cookies exist... then...
		doPopup(url, width, height, delay); // Runs pop-up function, pop-up appears in 'delay' seconds... and...
		document.cookie=smShownPop + "=shown; path=/; domain=" + siteDomain + "; expires=" + getHoursExpiry(num_hours); // Sets cookie to disable pop-up for 'num_hour' hours.
    	}
	}

function subscribed(siteID,num_days,www_path,theForm,theAltMsg)
	{
	// -- Sets cookie when submit button is pressed in the popup window. --
	// -- Will disable the popup for 'num_days' days. --
	// -- Set in the pop-up file's submit button with 'onClick'. --
	var siteDomain = wwwPathToDomainName(www_path); // Clean-up www_path.
	var smSubscribed = 'smSubscribed' + siteID; // Make name of cookie.
    document.cookie = smSubscribed + "=subscribed; path=/; domain=" + siteDomain + "; expires=" + getDaysExpiry(num_days); // Set cookie.
	submitonce(theForm,theAltMsg);
	}

// - P O P - U P  W I N D O W  F U N C T I O N S  E N D  H E R E  ---------




// ---- Macromedia image rollover -------------------

function MM_preloadImages() { //v3.0
	var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
	var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
	if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
	var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
	var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
	d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
	if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
	for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
	if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
	var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
	if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_showHideLayers() { //v6.0
	var i,p,v,obj,args=MM_showHideLayers.arguments;
	for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
	if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
	obj.visibility=v; }
}




// ---- Bookmark script --------------------------------------------

function bookmark(url,description)
	{
	bkm_operaMsg = "Please press CTRL+T to bookmark this site.";
	bkm_otherMsg = "Please press CTRL+D to bookmark this site.";
	// Check what browser is being used
	bkm_ie4 = (!document.getElementById && document.all)?true:false;
	bkm_ieNewer = (navigator.appVersion.indexOf("MSIE")!=-1)?true:false;
	bkm_opera = (navigator.userAgent.indexOf("Opera")!=-1)?true:false;
	bkm_gecko = (navigator.userAgent.indexOf("Gecko")!=-1)?true:false;
	if (bkm_ie4 || bkm_ieNewer) window.external.AddFavorite(url,description); // For IE
	else if (bkm_opera) alert(bkm_operaMsg); // For Opera
	else alert(bkm_otherMsg); // If some other browser is used, like Netscape.
	}




/*
===============================================================================================

	F O R M   F U N C T I O N S

===============================================================================================
*/
	



// ---- disappearing/reappearing text in the signup and search text field ---------------------------------------

function toggleField(action,element,defaultValue)
	{
	if (action == 'focus')	{ if (element.value == defaultValue)	element.value = ''; }
	if (action == 'blur')	{ if (element.value == '')				element.value = defaultValue; }
	}

	
	
// --- Disable buttons after form submit --------------------------------------------------------------
// --- Istvan - 02/09/2004	

function submitonce(theForm,theAltMsg)
	{
	// if IE 4+ or NS 6+
	if (document.all || document.getElementById)
		{
		// screen thru every element in the form, and hunt down "submit" and "reset"
		for (i=0; i<theForm.length; i++)
			{
			var tempobj=theForm.elements[i];
			if ( (tempobj.type.toLowerCase() == 'submit') || (tempobj.type.toLowerCase() == 'reset') )
				{
				tempobj.disabled = true;
				tempobj.value = theAltMsg;
				}
			}
		}
	}


	

// --- Check for characters that shouldn't be in a string
// --- Istvan - 17/11/2004
/*
Usage:
onclick= / onblur= / onsubmit=
"javascript: return checkforquotes(svalue,'mesg','returnthis');"

svalue		=	Form field value to check (i.e.: 'this.value' or 'document.formname.fieldname.value')
				DO NOT put quotes around this!
mesg		=	Message to show the user in the pop-up alert box. Use single quotes around entire text. Escape any
				single quotes in the text by putting a backslash (\) in fron of it: \'
returnthis	=	If the functuion is used when submitting the form, it needs to retun 'false' to prevent the form
				from being submitted. If this is required to happen, use the word 'false' (in quotes) here.
				Otherwise leave empty quotes.	
*/

var chkq_foundit = 0;

function checkforquotes(svalue,mesg,returnthis)
	{
	chkq_foundit = 0;
	if ( svalue.indexOf('\'') != -1 ) { chkq_foundit = 1; }
	if ( svalue.indexOf('"') != -1 ) { chkq_foundit = 1; }
	
	if (chkq_foundit == 1)
		{
		alert(mesg);
		if (returnthis == 'false') { return false; }
		}

	return true;
	}



// --- Validation for the contact manager/e-club signup form - used on popup.cfm and on pages where there is a signup box. ----------------------------

function validateSubscription(nameField,emailField)
	{
	var nameString = trim(nameField.value);
	var emailString = trim(emailField.value);

	if (nameString == '')
		{
		nameField.value = '';
		nameField.focus();
		alert('Please enter your name.');
		return false;
		}

	return isValidEmail(emailField);

	return true;
	}



// --- Validate email address --------------------------------------------------------------
// --- Istvan - 25/05/2004

function isValidEmail(emailField)
	{
	var emails = trim(emailField.value);
	if (emails != "")
		{
		if (!emailCheck(emails))
			{
			return false;
			emailField.focus();
			}
		}
	else
		{
		alert('The email address field cannot be left blank!');
		emailField.focus();
		return false;
		}
	emailField.value = emails;
	return true;
	}



// --- Validate email address. --------------------------------------------------------------

function emailCheck(emailStr)
	{
	// The following variable tells the rest of the function whether or not to verify that the address ends in a two-letter country or well-known TLD.  1 means check it, 0 means don't.
	var checkTLD=1;
	// The following is the list of known TLDs that an e-mail address must end with.
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum|asn)$/;
	// The following pattern is used to check if the entered e-mail address fits the user@domain format.  It also is used to separate the username from the domain.
	var emailPat=/^(.+)@(.+)$/;
	// The following string represents the pattern for matching all special characters.  We don't want to allow special characters in the address. These characters include ( ) < > @ , ; : \ " . [ ]
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	// The following string represents the range of characters allowed in a username or domainname.  It really states which chars aren't allowed.
	var validChars="\[^\\s" + specialChars + "\]";
	// The following pattern applies if the "user" is a quoted string (in which case, there are no rules about which characters are allowed and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com is a legal e-mail address.
	var quotedUser="(\"[^\"]*\")";
	// The following pattern applies for domains that are IP addresses, rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal e-mail address. NOTE: The square brackets are required.
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	// The following string represents an atom (basically a series of non-special characters.)
	var atom=validChars + '+';
	// The following string represents one word in the typical username. For example, in john.doe@somewhere.com, john and doe are words. Basically, a word is either an atom or quoted string.
	var word="(" + atom + "|" + quotedUser + ")";
	// The following pattern describes the structure of the user
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	// The following pattern describes the structure of a normal symbolic domain, as opposed to ipDomainPat, shown above.
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
	// The coarse pattern to simply break up user@domain into different pieces that are easy to analyze.
	var matchArray=emailStr.match(emailPat);

	if (matchArray==null)
		{
		// Too many/few @'s or something; basically, this address doesn't even fit the general mould of a valid e-mail address.
		alert("Email address seems incorrect (check the @ and dots).\nPlease check your email address and try again.");
		return false;
		}
	var user=matchArray[1];
	var domain=matchArray[2];

	// Start by checking that only basic ASCII characters are in the strings (0-127).
	for (i=0; i<user.length; i++)
		{
		if (user.charCodeAt(i)>127)
			{
			alert("The name in the email address contains invalid characters.\nPlease check your email address and try again.");
			return false;
			}
		}

	for (i=0; i<domain.length; i++)
		{
		if (domain.charCodeAt(i)>127)
			{
			alert("Ths domain name in the email address contains invalid characters.\nPlease check your email address and try again.");
			return false;
			}
		}

	// See if "user" is valid 
	if (user.match(userPat)==null)
		{
		// user is not valid
		alert("The name in the email address doesn't seem to be valid.\nPlease check your email address and try again.");
		return false;
		}

	// if the e-mail address is at an IP address (as opposed to a symbolic host name) make sure the IP address is valid.
	var IPArray=domain.match(ipDomainPat);

	if (IPArray!=null)
		{
		// this is an IP address
		for (var i=1;i<=4;i++)
			{
			if (IPArray[i]>255)
				{
				alert("Destination IP address in the email address is invalid.\nPlease check your email address and try again.");
				return false;
				}
			}
		return true;
		}

	// Domain is symbolic name.  Check if it's valid.
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++)
		{
		if (domArr[i].search(atomPat)==-1)
			{
			alert("The domain name in the email address does not seem to be valid.\nPlease check your email address and try again.");
			return false;
			}
		}

	// domain name seems valid, but now make sure that it ends in a known top-level domain (like com, edu, gov) or a two-letter word, representing country (uk, nl), and that there's a hostname preceding the domain or country.
	if (checkTLD && domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1)
		{
		alert("The email address must end in a well-known domain or two letter country code.\nPlease check your email address and try again.");
		return false;
		}

	// Make sure there's a host name preceding the domain.
	if (len<2)
		{
		alert("The email address is missing a hostname.\nPlease check your email address and try again.");
		return false;
		}

	// If we've gotten this far, everything's valid!
	return true;
	}