/*	
	Document: JavaScript
	Developer: Shegun Konibire
	Studio: Gunzalez
	------------------------------------- */	
	
// Uses functions from gunCore.js

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

/* Change error messages as needed to correspond
   to CSS classes used in the HTML, watch out for quotes. */
   
// var errMsg1 = "This field cannot be empty";
var errMsgArray = new Array();
errMsgArray[1] = "Please complete this field";
errMsgArray[2] = "Please type in some content";
errMsgArray[3] = "Please type in a last name";
errMsgArray[4] = "Invalid phone number, please re-enter";
errMsgArray[5] = "Invalid email address, please re-enter";
errMsgArray[6] = "Non-matching data, please re-enter";
errMsgArray[7] = "Please type in a first line of address";
errMsgArray[8] = "Please type in a second line of address";
errMsgArray[9] = "You must enter a valid postcode";
errMsgArray[10] = "Please pick a country";
errMsgArray[11] = "Please type in a username";
errMsgArray[12] = "Please type in a password";
errMsgArray[13] = "Please type in title";
errMsgArray[14] = "Please type in a first name";
errMsgArray[15] = "Please type in a valid email address";

errMsgArray[16] = "Please type in a company name or \'None\'";
errMsgArray[17] = "Please type in a valid UK phone number";
errMsgArray[18] = "Please type in a city or town";
errMsgArray[19] = "";
errMsgArray[20] = "";

// default message if none is specificed, please specify
var errMsgDefault = "Invalid data, please re-enter";

/////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////

//  Sets up popup links
function setUpPopupLinks(){
    var all_links = document.getElementsByTagName('A');
    if (all_links.length > 0) {
        for (var v = 0; v < all_links.length; v++) {
            var thisLink = all_links[v];
            if (thisLink.className && (' ' + thisLink.className + ' ').indexOf(' darePopup ') != -1) {
                thisLink.onclick = new Function('jsNewWindow(this); return false;');
            }
        }
    }
}

function jsNewWindow(linkHref){
    // var windowFeatures = "height=220,width=400,status=no,toolbar=0,menubar=no,location=no,resizable=0"
    var mywindow = window.open(linkHref, 'mywindow');
    mywindow.focus();
   	// mywindow.moveTo(0, 0);
    return false;
}

// Returns error message text, to be displayed.
function errorText(strErrTag){
	strErrTag = strErrTag.replace(/errMsg/, "");
	return errMsgArray[strErrTag];
}

// Displays error on page, next to input field of the passed input's id
function displayErrorOnPage(obj, errorText){
	var errContainer = document.createElement('SPAN');
	errContainer.className = "errorSpan";
	errContainer.appendChild(document.createTextNode(errorText))			
	insertAfter(obj.parentNode, errContainer, obj)
	// obj.parentNode.appendChild(errContainer);
}

// Removes all error displays on the page, called when page is submitted
function clearAllErrors(){
	var listedErrorSpans = GUNZ.getElementsbyClass(GUNZ.$('main'), "span", "errorSpan")
	if (listedErrorSpans.length > 0) {
		for (var x = 0; x < listedErrorSpans.length; x++) {
			listedErrorSpans[x].parentNode.removeChild(listedErrorSpans[x]);
		}
	}
}	

// Clears error display next to passed object, called when the object is clicked
function clearErrorSpan(oThisField){
	// Removes error message from below field
	if (oThisField.parentNode.hasChildNodes()) {
		for (var x = 0; x < oThisField.parentNode.childNodes.length; x++) {
			if (oThisField.parentNode.childNodes[x].className == "errorSpan") {
				oThisField.parentNode.childNodes[x].parentNode.removeChild(oThisField.parentNode.childNodes[x])
			}
		}
	}
	// Hides error summary
	var listedErrorSpans = GUNZ.getElementsbyClass(GUNZ.$('main'), "span", "errorSpan")
	if (listedErrorSpans.length < 1) {
		if(GUNZ.$('errorNotice')){
			GUNZ.$('errorNotice').style.display = "none";
		}
	}
}
		
// Displays error(s) on page
function reportError(oItemToReport){
	var tempArray = oItemToReport.className.split(' ');
	var errText = errorText(tempArray[2]);
	displayErrorOnPage(oItemToReport, errText)
	oItemToReport.onfocus = new Function('clearErrorSpan(this)');			
}


// Validates the passed form object
// Sample use:
// <input type="password" id="oldPWD" name="oldPWD" maxlength="30" value="" class="validate typeText errMsg1 txtInput" title="" />
// <input type="text" id="newPWD" name="newPWD" maxlength="30" value="" class="validate typeText errMsg1 compare txtInput" title="" />
// <input type="text" id="newPWD2" name="newPWD2" maxlength="30" value="" class="compare txtInput errMsg6" title="" />
// <input type="text" id="uploadText" name="uploadText" maxlength="100" value="" class="validate typeEmail errMsg1 txtInput" title="Type in a short title" />
function validateForm(oForm){

	// clear all errors on screen
	clearAllErrors();
	var errList = 0;
	// get array of input objects to be validated
	var aInputsToValidate = GUNZ.getElementsbyClass(oForm, "*", "validate");
	
	// alert(aInputsToValidate.length)			
	// get array of object to compare
	var aInputsToCompare = GUNZ.getElementsbyClass(oForm, "*", "compare");
		

	// loop through validation, and error reporting
	if(aInputsToValidate.length > 0){
		for(var x = 0; x < aInputsToValidate.length; x++){
			if (aInputsToValidate[x].className && (' ' + aInputsToValidate[x].className + ' ').indexOf(' typeText ') != -1) {
				if (isEmpty(aInputsToValidate[x].value)) {
					errList++;
					reportError(aInputsToValidate[x]);
				}
			} else if (aInputsToValidate[x].className && (' ' + aInputsToValidate[x].className + ' ').indexOf(' typeEmail ') != -1) {
				if (GUNZ.eCheck(aInputsToValidate[x].value) == false) {
					errList++;
					reportError(aInputsToValidate[x]);
				}
			} else if (aInputsToValidate[x].className && (' ' + aInputsToValidate[x].className + ' ').indexOf(' typePhoneUK ') != -1) {
				// if (isNaN($(aItemsToValidate[x]).value) || isEmpty($(aItemsToValidate[x]).value)) {
				if (!checkUKTelephone(aInputsToValidate[x].value)) {
					errList++;
					reportError(aInputsToValidate[x]);
				}
			} else if (aInputsToValidate[x].className && (' ' + aInputsToValidate[x].className + ' ').indexOf(' typeSelect ') != -1) {
				if (aInputsToValidate[x].value == "null") {
					errList++;
					reportError(aInputsToValidate[x]);
				}
			}
		}
	}
	
	// Expects to compares 2 values, works for 2 values per form. 
	if(aInputsToCompare.length > 0){
		if (trimString(aInputsToCompare[0].value) != trimString(aInputsToCompare[1].value)){
			errList++;
			reportError(aInputsToCompare[1]);
		}
	}
				
	// if there are erros stop form from submitting
	if (errList > 0){		
		if(GUNZ.$('errorNotice')){
			GUNZ.$('errorNotice').style.display = "block";
			//$('#errorNotice').show('slow');
		}		
		new ElementMaxHeight(); // special to this website - Links Courier
		return false;
	} else {	
		return true;		
	}
}

						
