/*
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
		
	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 
	
	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

*/

//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 isIE2(){
    var detect = navigator.userAgent.toLowerCase();
    return detect.indexOf("ie") + 1; 
}

//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, 
void function restrictKeys(theObject, validKeys, message){
	strWork = validKeys;
	strMsg = '';
	isValidCharacter = false;					

	for(i=0;i < strWork.length;i++){
		if(window.event.keyCode == strWork.charCodeAt(i)) 
		{
		isValidCharacter = true;
		break;
		}
	}
	if(!isValidCharacter){
		if(message == null || message.length == 0){}
			else{alert(message)};

		window.event.returnValue = false;
		theObject.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;
}

//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){alert("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.disabled = true;
		}
}







