/*
Link with <script type="text/javascript" src="PATH/hhgreggCommons.js"></script>

Commons Javascript functions that will:

	Check if the browser is Internet Explorer
		isIE(): returns boolean

	Check if the browser is Opera
		isOpera(): returns boolean
		
	Get the parent form of any element, really cool to use with this
		getParentForm(AnyElement): returns form node
		
	Restricts keys that can entered in a text field, best if used with onKeyPress
		restrictKeys(theTextField, allAllowedKeysString, alertMessageString):void
			theTextField: the text field that this will work with, with onKeyPress just use this
			allAllowedKeysString: just the allowed characters, for numbers you would use "0123456789", for y or n use "yn"
			alertMessageString: when the user trys to enter in an invalid key a message will be displayed of this string
						no message displays when this is null.
						
	Print specific content on your page
		openPrintWindow(contentString):void
			contentString: just the string that will be printed, can be Html, to print all contents of a tag use node.innerHTML 
			
	Get all elements by class name
		getElementsByClassName(classNameString):returns array of nodes

	Trim a string
		trim(string):void
		
	Trim all fields of a form
		trimValues(aForm):void
			aForm: the form node to trim all the values of
			
	Perform validation on a form, this works by having an additional attribute on a field called invalidMessage, which sets the
	invalid message and marks the field as required for this validation, NOTE: only validates the first form although this is easily
	changed
		validateForm():returns true if validates 
	
	Perfom validation on a form, same as above except now finds the corresponding label and highlights it
		validateFormWithLabels(theForm, labelColor, highlightColor)
	
	
	Get a list of the fields for a form
		getAllFormFields(aForm):returns array of fields	
	
	Disable or enable a control through a toggle (toggle means if it's disabled then the method will enable it and vice-versa)
		toggleDisableControl(stringId):void
			stringId: the id of the element

	Disable All fields for a given form
		disableAllFormFields(aForm):void
			aForm: the form node that contains the controls to be disabled
	
	Resize textarea to fit all text
		resizeTextAreaToShowAllText
			textarea: the textarea to resize

*/

//Switch on/off DEBUG mode 
var DEBUG = false;


function debug(thing){if(DEBUG == true){alert(thing);}}
//debug("Debug Mode is on");

//Check if browser is Internet Explorer
function isIE(){
    var detect = navigator.userAgent.toLowerCase();
    return detect.indexOf("ie") + 1; 
}

//Check if browser is Opera
function isOpera(){
	return (window.opera)
}

//Get the parent form of the object theObject, if no parent form is found returns null
function getParentForm(theObject){
    var theForm = document.getElementsByTagName("form");
    for(x=0; x < theForm.length; x++)
    {
        var formCollection = theForm[x].getElementsByTagName(theObject.nodeName);
        for(i=0; i < formCollection.length; i++)
        {
            if (formCollection[i] == theObject)
            {
                return theForm[x]
            }
        }
    }
	return null;
}

//Restrict Keys for the field:theObject, 
function restrictKeys(e, validKeys, message){
	var strWork = new String(validKeys);
	strMsg = '';
	isValidCharacter = false;					

	var theElement = isIE() ? e.srcElement : e.currentTarget; 
	
	var theKeyCode = (isIE() || isOpera()) ? e.keyCode : e.charCode;
	
	for(i=0;i < strWork.length;i++){
		if(theKeyCode == strWork.charCodeAt(i) || theKeyCode == 0) 
		{
		isValidCharacter = true;
		break;
		}
	}
	//alert(e.charCode)
	
	if(!isValidCharacter){
		if(message == null || message.length == 0){}
			else{alert(message)};

		if(isIE()){
			e.returnValue = false
		}
		else{e.preventDefault();}
		theElement.focus();
	}
}

//Open page to print string: content
function openPrintWindow(content){
var win1 = window.open('', 'PrintPage','width=25,height=25');
    win1.document.open();
    win1.document.write('<head><title>Print View</title><link type="text/css" rel="stylesheet" href="css/style.css"/></head><body onload="window.print(),window.close()">');
    win1.document.write('<style>.noteText{overflow:visible;}</style>'+content+'</body>');
    win1.document.close();
}

//Get elements by class name string classname
function getElementsByClassName(classname)
{
    var a = [];
    var re = new RegExp('\\b' + classname + '\\b');
    var els = document.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++)
        if(re.test(els[i].className))a.push(els[i]);
    return a;
}

//Trim String s
function trim(s) {
  while ((s.substring(0,1) == ' ') || (s.substring(0,1) == '\n') || (s.substring(0,1) == '\r')) {
    s = s.substring(1,s.length);
  }
  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;
}

//Trim all values of form theForm
function trimValues(theForm){
    debug(theForm);
    for(i=0; i < theForm.length; i++)
    {
        debug(theForm[i].name+theForm[i].value);
        if (theForm[i].value != null)
        {
            theForm[i].value = trim(theForm[i].value)
        }
    }
}

//Validate all required fields that are annotated with the 'invalidMessage' attribute within a form
function validateForm(theForm)
{
	debug("Entered Function");
	var inputNodes = getAllFormFields(theForm);
	debug(inputNodes.length);
	for(x=0; x < inputNodes.length; x++){
		var theNode = inputNodes[x];
		if(theNode.disabled == true || (theNode.getAttribute('invalidMessage') == null)){continue;}
		if(theNode.value == null || theNode.value == ""){
			alert(theNode.getAttribute('invalidMessage'));
			return false;
		}
	}
	return true;
}

//Validate all required fields that are annotated with the 'invalidMessage' attribute within a form, highlighting the corresponding label
function validateFormWithLabels(theForm, labelColor, highlightColor){
	debug("Entered Function validateFormWithLabels" + ',' + theForm + ',' + labelColor + ',' + highlightColor);
	var inputNodes = getAllFormFields(theForm);
	var validated = true;

	try{
	 for(x=0; x < inputNodes.length; x++){
		var theNode = inputNodes[x];
		if(theNode.disabled == true || (theNode.getAttribute('invalidMessage') == null)){continue;}
		if(theNode.value == null || theNode.value == ""){
			debug("Node Found for " + theNode.name)
			var theLabelNode = getLabelByField(theNode.name)
			if(theLabelNode != null){
				theLabelNode.style.color = highlightColor
			}
			validated = false
		}
		else{
			if(theNode.style.color == highlightColor){
				theNode.style.color = labelColor
			}
		}
	 }
	}
	catch(e){alert("Error when evoking validateFormWithLabels(): \n\n"+e.message)}
	debug("validateFormWithLabels returned " + validated)
	return validated
}

//Find a the corresponding label for a form element
function getLabelByField(fieldName){
	var labelNodes = document.getElementsByTagName("label")
	for(x=0; x < labelNodes.length; x++){
		var theNode = labelNodes[x];
		debug(theNode.nodeName + " "+ theNode.getAttribute("htmlfor"))
		if(theNode.getAttribute("for") == fieldName || theNode.getAttribute("htmlfor") == fieldName){
			debug("Label Node Found for " + fieldName + " " + theNode)
			return theNode
		}
	}
	return null
}

//Returns all field elements of the form theForm
function getAllFormFields(theForm){
	try{
	var inputFields = theForm.getElementsByTagName("input");
	var selectFields = theForm.getElementsByTagName("select");
	var textFields = theForm.getElementsByTagName("textarea");
	var array = new Array(inputFields + selectFields + textFields);
	for(i=0; i < array.length; i++){
		for(x=0; x < inputFields.length; x++){
			array[i] = inputFields[x];
			i++
		}
		for(a=0; a < selectFields.length; a++){
			array[i] = selectFields[a];
			i++
		}
		for(t=0; t < textFields.length; t++){
			debug("Text box Found"+textFields.name);
			array[i] = textFields[t];
			i++
		}
	}
	}
	catch(e){debug("Error when evoking getAllFormFields(): \nSomething is probably wrong with the form you passed in\n\n"+e.message)}
	debug(array.toString());
	return array;
}


//Toggle disabled on object by objects id string: controlToDisableId
function toggleDisableControl(controlToDisableId)
{
    var object = document.getElementById(controlToDisableId);
    try{
    if(object.disabled == true){object.disabled = false;}else{object.disabled = true;}
    }
    catch(e){alert("Error when evoking toggleDisableControl(): \n No object found with this id : \n"+controlToDisableId+"\n\n"+e.message);}
}

//Disable All fields for a given form
function disableAllFormFields(theForm){
	var inputNodes = getAllFormFields(theForm);
	debug(inputNodes.length);
	for(x=0; x < inputNodes.length; x++){
		var theNode = inputNodes[x];
		theNode.readOnly = true;
	}
}

//Expand textarea to fit all text
function resizeTextAreaToShowAllText(textarea){
	a = textarea.value.split('\n');
	b=1;
	for (x=0;x < a.length; x++) {
 		if (a[x].length >= textarea.cols) b+= Math.floor(a[x].length/textarea.cols);
 	}
	b+= a.length;
	if (b > textarea.rows) textarea.rows = b;
}

//Expand all textareas in a form
function resizeAllTextAreasToShowAllText(theForm){
	var textFields = theForm.getElementsByTagName("textarea");
		for(x=0; x < textFields.length; x++){
			resizeTextAreaToShowAllText(textFields[x]);
			x++
		}
}





