// JavaScript file
// DDW 2006-08-21


// GENERAL USAGE NOTES ON REFERRING TO AN ELEMENT
// REFERRING FROM						NAME TO USE
// same element							this
// same form							[elementName]
// same window, outside of form			document.[formName].[elementName]
//										alternately, use document.forms[0] or document.forms[n]
// different window*					[windowName].document.[formName].[elementName]
// * -- untested

/****
*	Returns a confirm if a specified number is not an int, and disables the form if not.
*	@param 	this			object	Required	The element to test.
*	@param	intMinLength	int		Optional	If set, will ensure the length is no less.
*	@param	intMaxLength	int		Optional	If set, will ensure the length is no greater.
*	@return	alert if not valid
*
*
*	USAGE
*	onBlur="isInt(this, intMaxLength, FormName);"
*	NOTES
*	screenname and validated must be attributes (usually form fieldnames are rather dull)
**/
function validateInt(el, intMinLength, intMaxLength)
{
	
	intNumChars 	= el.value.length;
	strScreenAttr 	= 'screenname';
	strValAttr		= 'validated';
	strScreenName 	= el.getAttribute(strScreenAttr);
	blnIsInt 		= true;
	
	//alert(el.getAttribute('validated')+" - ");
	if (intNumChars==0)
	{
		blnIsInt=false;	
	}else
	{		
		for (i=0;i<intNumChars;i++)
		{
			if 	(isNaN(el.value.charAt(i)))
			{
				blnIsInt=false;	
			}
		}
	}
	
	if (!blnIsInt)
	{
		alert(strScreenName+" is an invalid number (no text/punctuation)");	
		//el.focus();
	}else 
	{
		if (!isNaN(intMinLength) && el.value.length<intMinLength)
		{
			alert(strScreenName+' needs to be greater or equal to '+intMinLength);	
			blnIsInt=false;				
			//el.focus();		
		}else 
		{
			if (!isNaN(intMaxLength) && el.value.length>intMaxLength)
			{
				alert(strScreenName+' needs to be less than or equal to '+intMaxLength);	
				blnIsInt=false;	
				//el.focus();	
			}
		}
	}
	if (blnIsInt==true)
	{
		//alert('Setting '+strValAttr+' true')
		el.setAttribute(strValAttr, true);
	}else
	{
		el.setAttribute(strValAttr, false);		
	}
}

/****
*	Determines from a list of element names if all are validated (Attribute of validated).
*	@param 	arrNames	array	Required	The List of element names to check are validated.
*	@return	alert if not valid
*
*
*	USAGE
*	onSubmit="return(allValidated(array('name1', 'name2', ...)));"
**/
function allValidated(arrNames)
{
	intCount = arrNames.length;
	strScreenAttr 	= 'screenname';
	strValAttr		= 'validated';
	strNotValidated = '';
	//alert('Num to validate '+intCount);
	for (i=0;i<intCount;i++)
	{
		strName = arrNames[i];
		el = getElement(strName);
		strScreenName = el.getAttribute(strScreenAttr);
		strValidated = el.getAttribute(strValAttr);
		//alert(typeof(el)+' '+strName+' is '+strValidated);
		if (strValidated=='false')
		{
			strNotValidated += strScreenName+' is invalid \n';
		}
	}
	//alert('Not Valid: '+strNotValidated);
	if (strNotValidated.length>0)
	{
		alert(strNotValidated);
		return false;
	}else
	{
		return true;	
	}
	
}


function setCheckboxGroupValue()
{
// for checkbox and radio groups (arrays)
// LOOK FOR THIS CODE IN THE RELOAD PAGE OF THE INDAILY SURVEY
// I DID IT ONCE AND WE DON'T WANT TO HAVE TO DO IT AGAIN!
// see /var/local/common/javascript/include/reloadFormValues.php
}

//sets the specified element value to the action
function setElementValue(elName, elValue) 
{
	elements = document.getElementsByName(elName);
	element = elements[0];
	if (!element)
	{
		element = document.getElementById(elName);	
	}
	element.value=elValue;
}

//returns the specified element's value
function getElementValue(elName) 
{
	elements = document.getElementsByName(elName);
	element = elements[0];
	if (!element)
	{
		element = document.getElementById(elName);	
	}
	return (element.value);
}

// To clear the value in a text field
// USAGE
// onclick="clearTextFieldValue([fieldName]);"
function clearTextFieldValue(el)
{
	el.value = '';
}

// To clear the value in a text field IF the current value is the default value
// USAGE
// onclick="clearTextFieldValue([fieldName], [defaultValue]);"
function clearTextFieldDefaultValue(el, defaultValue)
{
	if (el.value == defaultValue)
		el.value = '';
}

// Set a text field's value (can be used to reset the default value)
// USAGE
// onclick="setTextFieldValue([fieldName], \'Fill this in\');"
function setTextFieldValue(el, val)
{
	el.value = val;
}

// Returns true if the control element is empty
// or if there are only spaces in the field
// USAGE
// onclick="if(isEmpty(document.[formName].[fieldName])){[jsaction];}else{[jsaction];};return true;"
function isEmpty(el)
{
	if (trimString(el.value) == '')
		return true;
	return false;		
}

// USAGE (within JS code)
// str = trimString(str);
function trimString (str)
{
	// trim left side spaces
	while (str.charAt(0) == ' ')
		str = str.substring(1);
	// trim right side spaces
	while (str.charAt(str.length - 1) == ' ')
		str = str.substring(0, str.length - 1);

	return str;
}


// use a master checkbox to set the value of all children
// @param	elMaster	The Element which contains the Javascript
// @param	elChildGroup	The Group to change
// @param	blnSwitch	Whether to swap existing values
// USAGE
// onclick="setAllCheckboxes(elMaster, elChildGroup, blnSwitch);"
function setAllCheckboxes(elMaster, elChildGroup, blnSwitch)
{
	if (elChildGroup)
	{	
		for (i=0; i<elChildGroup.length; i++)
		{
			if (blnSwitch)
			{
				if (elChildGroup[i].checked)
				{
					elChildGroup[i].checked = false;
				}else
				{
					elChildGroup[i].checked = true;					
				}
			}else
			{
				elChildGroup[i].checked = elMaster.checked;
			}
		}
	}
}

// redirect to another page
// USAGE
// redirect('[url]')
// example <body onload="redirect('[url]');">
function redirect (url)
{
	window.location = url;
}

// popup a URL
function popUpNoMenu (url, width, height, left, top) 
{
	day = new Date();
	id = day.getTime();
	if (width == null) width = 800;
	if (height == null) height = 600;
	if (left == null) left = 80;
	if (top == null) top = 80;
	eval("page" + id + " = window.open('" + url + "', '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=" + width + ",height=" + height + ",left=" + left + ",top=" + top + "');");
}

// open a page in another window
// USAGE
// openWindow('[url]', '[strWindowName]', '[strFeatures]')
// example <a onClick="openWindow('http://google.com', 'Google', 'width=200,height=400');">
function openWindow(strUrl,strWindowName,strFeatures) 
{ 
	window.open(strUrl,strWindowName,strFeatures);
}

// Allows showing and hiding of anything within div tags with the id of strClass
// USAGE
// showHideLayer('strClass');
// example <a onClick="showHideLayer('mainClass');">
// Table to hide needs to be bracketed with <div id="mainClas></div>
function showHideLayer(strClass)
{
	if (document.getElementById)
	{
		// this is the way the standards work
		var style2 = document.getElementById(strClass).style;
		style2.display = style2.display? "":"block";
	}
	else if (document.all)
	{
		// this is the way old msie versions work
		var style2 = document.all[strClass].style;
		style2.display = style2.display? "":"block";
	}
	else if (document.layers)
	{
		// this is the way nn4 works
		var style2 = document.layers[strClass].style;
		style2.display = style2.display? "":"block";
	}
}

/***
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var minYear=1900;
var maxYear=2100;
function isDate(dtStr, dtCh)
{
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	//alert(pos1+' '+pos2+'!!'+strDay+' '+strMonth+' '+strYear);
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) 
	{
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1)
	{
		alert("The date format should be : dd/mm/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12)
	{
		alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month])
	{
		alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear)
	{
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false)
	{
		alert("Please enter a valid date")
		return false
	}
	return true
}
//different from isInt, this one required for isDate
function isInteger(s)
{
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag)
{
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year)
{
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) 
{
	for (var i = 1; i <= n; i++) 
	{
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

//finds the iframe, appends the specified url and refreshes
//usage: onClick="refreshIframe('FrameName', '&something=something');"
function refreshIframe(strFrameName, strUrlAppend)
{
	objFrame = frames[strFrameName];
	if (!objFrame)
	{
		objFrame = parent.frames[strFrameName];	
	}
	strOldUrl = objFrame.location.href;
	//alert('Frame '+strFrameName+' Old Url '+strOldUrl);
	if (strUrlAppend.indexOf('?')>=0)
	{	
		strNewUrl = strUrlAppend;
	}
	else if (strOldUrl.indexOf('?'))
	{
		strNewUrl = strOldUrl+'&'+strUrlAppend;
	}else if (strOldUrl.indexOf('&'))
	{
		strNewUrl = strOldUrl+'?'+strUrlAppend;		
	}else
	{
		strNewUrl = strOldUrl;	
	}
	//alert('Frame '+strFrameName+' New Url '+strNewUrl);
	objFrame.location.href=strNewUrl;

}	

//returns the specified element's value
function getElementValue(elName) 
{
	elements = document.getElementsByName(elName);
	element = elements[0];
	return (element.value);
}	

//returns the specified element
function getElement(elName) 
{
	elements = document.getElementsByName(elName);
	element = elements[0];
	return (element);
}

function getCheckedElements(el)
{
	strIds = '';
	if (el)
	{
		if (el.length)
		{
			for ($i=0;$i<el.length;$i++)
			{	
				if (el[$i].checked)
				{
					strIds += el[$i].value+',';
				}
			}
		}else//if only one element, then it's not an array
		{
			strIds = el.value;	
		}
		
	}
	
	return strIds;
	
}

//math.round only works on integers, this takes care of that
function roundNumber(intNum, intPlaces) 
{
	var rnum = intNum;
	var rlength = intPlaces; // The number of decimal places to round to
	if (rnum > 8191 && rnum < 10485) 
	{
		rnum = rnum-5000;
		var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
		newnumber = newnumber+5000;
	} else 
	{
		var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
	}
	return newnumber;
}

//math.round only works on integers, this takes care of that, pads final 0's also
function formatDollar(intNum) 
{

	var intNewNumber = Math.round(intNum*Math.pow(10,2))/Math.pow(10,2);
	strNewNumber = intNewNumber.toString();
	intDecPos = strNewNumber.lastIndexOf(".");
	//alert(intNewNumber+" - "+intDecPos);
	if (intDecPos == -1)
	{
		strNewNumber = strNewNumber+".00";
	}
	else if (strNewNumber.substr(intDecPos).length==2)//2 is . and last number
	{
		strNewNumber = strNewNumber+"0";	
	}
	return strNewNumber;
}

function validateEmail(elem)
{
	var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
	if(elem.value.match(emailExp))
	{
		return true;
	}else
	{
		return false;
	}
}



//Searches an array for a specific value (can't find a JS function for this)
function inArray(mxdVal, arrSearch)
{
	blnExists=false
	for (var i=0;i<=arrSearch.length;i++)
	{
		if (arrSearch[i]==mxdVal)
		{
			blnExists=true;
		}					
	}
	return blnExists;
}




// show / hide layer and toggle button between + and - text
// usage: <input type="button" onClick="showHideLayerAndToggleButton(\'hide_row_groupname\', this);" value="+" />
function showHideLayerAndToggleButton(p_groupname, p_button)
{
	var elements = document.getElementsByTagName("tr");
	var button = p_button;
	// alternately, use
	// <tr onClick="showHideLayer(\'arts_center_item_events_row\', \'arts_centre_item_events_button\');">
	// to allow clicking the title row to hide the contents
	// along with this next line here instead of the previous
	//var button = document.getElementById(p_button);

	for(var i=0; thisRow = elements[i]; i++)
	{
		// alert("p_groupname: " + p_groupname + "className: " + thisRow.getAttribute("groupname"));

		if (thisRow.getAttribute("groupname") == p_groupname)
		{
			if (thisRow.style.display == "none")
			{
				thisRow.style.display = "block";
				button.value = "-";
			}
			else if (thisRow.style.display == "block")
			{
				thisRow.style.display = "none";
				button.value = "+";
			}
		}
	}

	return false;
}
