// Client Validation functions
/*------------------------------------------------------------*/

// Variable declarations
var messageTag ;	
var colorLeft = "#eeeeee" ;
var colorRight = "#ffeecc" ;
var colorError = "#ffff33" ;
var firstError = true;

/// A new version of the text area validation that handles things in Divs,
/// and also counts down, instead of showing an error when one exists.
function ValidateTextAreaCountdown(objectOrName, mlength, submitButtonId, event) {

    var textArea;
    var cursorLocation;

    if (objectOrName.type == 'text' || objectOrName.type == 'textarea') {
        textArea = objectOrName;
    }
    else {
        textArea = document.getElementById(objectOrName);
    }

    if (event != undefined) {
        if (event.keyCode == 16 || event.keyCode == 17 || (event.keyCode >= 33 && event.keyCode <= 40)) {
            return true;
        }
    }

    var myName = textArea.name;
    cursorLocation = getCursorLocation(textArea);
    //console.log(textArea.value.length);
    // Get submit button to disable (if any)
    //--------------------------------
    var submitButton = null;
    var disableSubmit = false;
    if (submitButtonId !== null && document.getElementById(submitButtonId) !== undefined) {
        submitButton = document.getElementById(submitButtonId);
        disableSubmit = true;
    }

    var myRow = textArea.parentNode;
    // we don't care about rows if we are inside a nice DIV
    if (myRow.nodeName != 'DIV') {
        // wrong one
        return ValidateTextArea(objectOrName, mlength, submitButtonId, event);
    }

    // Handle SMALL tag for error message
    //--------------------------------

    // Quick check to see if we have our SMALL tag
    if (document.getElementById('messageTag' + myName) == undefined) {

        // Check for an sauitable existing SMALL tag under Textarea that we can use
        //-- From server validation postback
        var hasExisiting = false;
        //var nodesCollection = textArea.parentNode.childNodes ;
        var nodesCollection = textArea.parentNode.getElementsByTagName('SMALL');

        if (nodesCollection[0] != undefined) {
            messageTag = nodesCollection[0];
            messageTag.setAttribute('id', 'messageTag' + myName);
            hasExisiting = true;
        }

        // Otherwise create a new node and add it to the DOM
        //-- Propbablly first visit to the page
        if (hasExisiting == false) {

            messageTag = document.createElement('DIV');
            messageTag.setAttribute('id', 'messageTag' + myName);

            // Add below textarea
            textArea.parentNode.appendChild(document.createElement('small')).appendChild(messageTag);
        }
    }
    // Use the correct one
    else {
        messageTag = document.getElementById('messageTag' + myName);
    }

    // Process character length validation
    //---------------------------------------
    var textAreaLength = textArea.value.replace(/\n/g, "\n\r").length;

    var charactersLeft = mlength - textAreaLength;
    var origCharactersLeft = charactersLeft;
    if (charactersLeft < 0) {
        charactersLeft = 0;
    }
    messageTag.innerHTML = charactersLeft + " characters remaining";
    
    // Too long
    if (origCharactersLeft < 0) {
        myRow.style.backgroundColor = colorError;
        submitButton.disabled = true;
        return false;
    }

    // Not too long
    else {
        if (!firstError) {
            myRow.style.backgroundColor = colorLeft;
        } else {
            firstError = false;
        }
        submitButton.disabled = false;
        return true;
    }
}


// Text Area maximum character validation
//-----------------------------------------------
//-- Input paramaters: ByRef TextArea As Object, ByRef maximum character length
//-- Validates client side and manipulates the DOM to set the error colour for related table cells


function ValidateTextArea(objectOrName,mlength,submitButtonId,event){

    var textArea ;
    var cursorLocation;
    
	if ( objectOrName.type == 'text' || objectOrName.type == 'textarea' ) {
		textArea = objectOrName;
	}
	else {
		textArea = document.getElementById(objectOrName);
	}
			
    if (event != undefined){
        if (event.keyCode == 16 || event.keyCode == 17 || (event.keyCode >= 33 && event.keyCode <= 40)){
            return true;
        }
    }			
			
	var myName = textArea.name;	
    cursorLocation = getCursorLocation(textArea);
//console.log(textArea.value.length);
	// Get submit button to disable (if any)
	//--------------------------------
	var submitButton = null ;
	var disableSubmit = false ;
	if (submitButtonId!==null && document.getElementById(submitButtonId) !== undefined) {
		submitButton = document.getElementById(submitButtonId) ;
		disableSubmit = true ;
	}
		
	// Loop up to get the first parent ROW
	//--------------------------------
	var myRow = textArea.parentNode;
    while (myRow.nodeName != 'TR') {
        myRow = myRow.parentNode;
    }

    // Get cells for that row
    //--------------------------------
    var cells = new Array()
    for (var ix = 0; ix <= myRow.childNodes.length - 1; ix++) {
        if (myRow.childNodes[ix].nodeName == 'TD') {
            cells.push(myRow.childNodes[ix])
        }
    }
	
	// Handle SMALL tag for error message
	//--------------------------------
	
	// Quick check to see if we have our SMALL tag
	if(document.getElementById('messageTag'+myName) == undefined) {
				
		// Check for an sauitable existing SMALL tag under Textarea that we can use
		//-- From server validation postback
		var hasExisiting = false ;
		//var nodesCollection = textArea.parentNode.childNodes ;
		var nodesCollection = textArea.parentNode.getElementsByTagName('SMALL') ;		
		
		if(nodesCollection[0]!=undefined) {
			messageTag = nodesCollection[0];
			messageTag.setAttribute('id', 'messageTag' + myName);
			hasExisiting = true ;
		}
						
		// Otherwise create a new node and add it to the DOM
		//-- Propbablly first visit to the page
		if( hasExisiting == false) {
		
			messageTag = document.createElement('DIV');
			messageTag.setAttribute('id', 'messageTag' + myName);
							
			// Add below textarea
			textArea.parentNode.appendChild(document.createElement('br'))
			textArea.parentNode.appendChild(document.createElement('small')).appendChild(messageTag);

			// We do this because Firefox has a bug where the cursor will jump to the end of the textbox
			// Unfortunately, this removes keyboard selection for the first character only.
			insertAtCursor(textArea, cursorLocation);
		}
	}
	// Use the correct one
	else {
		messageTag = document.getElementById('messageTag'+myName);
	}


	// Set the SMALL tag alignment
	if(cells != undefined && cells.length==1) {
		messageTag.setAttribute('align', 'center');
	}
	
							
	// Process character length validation
	//---------------------------------------
	var textAreaLength = textArea.value.replace(/\n/g, "\n\r").length ;
	
	// Too long
	if (textArea.getAttribute && textAreaLength > mlength) {
		
		// Add error message
		var reduceBy = textAreaLength - mlength ;
		var text = "Please reduce your entry by " + reduceBy + " character" + ((reduceBy==1) ? "" : "s")
		messageTag.innerHTML = text ;
		
		// Set error color
		for ( var index=0 ; index <= cells.length-1 ; index ++) {
			cells[index].setAttribute('bgColor', colorError);
		}

		// Disable button?
		if(disableSubmit==true) {
			submitButton.disabled = true ;
		}
		return false ;
	}
	
	// Not too long
	else {
		
		// Remove error message
		messageTag.innerHTML = "" ;
		
		// Restore original colors
		if(cells.length==1) {
			cells[0].setAttribute('bgColor', colorRight) ;
		}
		else {
			cells[0].setAttribute('bgColor', colorLeft);
			cells[1].setAttribute('bgColor', colorRight) ;
		}	
		
		// Enable button?
		if(disableSubmit==true) {
			submitButton.disabled = false ;
		}	
		return true;
	}
}



// Text box required field validation
//-----------------------------------------------
//-- Input paramaters: Text box Id
//-- Validates client side and manipulates the DOM to set the error colour for related table cells
function ValidateRequired(elementId){
	
	var element = document.getElementById(elementId) ;
	var myName = element.name;	
	
		
	// Loop up to get the first parent ROW
	//--------------------------------
	var myRow = element.parentNode;
	while (myRow.nodeName!='TR') {
		myRow = myRow.parentNode ;
	}
			
	// Get cells for that row
	//--------------------------------
	var cells = new Array()
	for ( var ix=0 ; ix <= myRow.childNodes.length-1 ; ix++) {
		if(myRow.childNodes[ix].nodeName == 'TD'){
			cells.push(myRow.childNodes[ix])
		}
	}

	// Handle SMALL tag for error message
	//--------------------------------
	
	// Quick check to see if we have our SMALL tag
	if(document.getElementById('messageTag'+myName) == undefined) {
				
		// Check for an suitable existing SMALL tag under element that we can use
		//-- From server validation postback
		var hasExisiting = false ;
		//var nodesCollection = element.parentNode.childNodes ;
		var nodesCollection = element.parentNode.getElementsByTagName('SMALL') ;		
		
		if(nodesCollection[0]!=undefined) {
			messageTag = nodesCollection[0];
			messageTag.setAttribute('id', 'messageTag' + myName);
			hasExisiting = true ;
		}
						
		// Otherwise create a new node and add it to the DOM
		//-- Propbablly first visit to the page
		if( hasExisiting == false) {
		
			messageTag = document.createElement('DIV');
			messageTag.setAttribute('id', 'messageTag' + myName);
							
			// Add below element
			element.parentNode.appendChild(document.createElement('br'))
			element.parentNode.appendChild(document.createElement('small')).appendChild(messageTag);
		}
	}
	// Use the correct one
	else {
		messageTag = document.getElementById('messageTag'+myName);
	}


	// Set the SMALL tag alignment
	if(cells.length==1) {
		messageTag.setAttribute('align', 'center');
	}
	
							
	// Process character length validation
	//---------------------------------------
	
	// Too long
	if (element.getAttribute && element.value.length == 0) {
		
		// Add error message
		var text = "This field is required"  ;
		messageTag.innerHTML = text ;
		
		// Set error color
		for ( var index=0 ; index <= cells.length-1 ; index ++) {
			cells[index].setAttribute('bgColor', colorError);
		}
	
		return false
	}
	
	// Not too long
	else {
		
		// Remove error message
		messageTag.innerHTML = "" ;
		
		// Restore original colors
		if(cells.length==1) {
			cells[0].setAttribute('bgColor', colorRight) ;
		}
		else {
			cells[0].setAttribute('bgColor', colorLeft);
			cells[1].setAttribute('bgColor', colorRight) ;
		}	
		
		return true
	}
}

function getCursorLocation(myField){
if (!document.selection) {
    return myField.selectionStart;
}
}

function insertAtCursor(myField, cursorLocation) {
if (!document.selection) {
    if (myField.selectionStart || myField.selectionStart == '0') {
        myField.selectionStart = cursorLocation;
        myField.selectionEnd = cursorLocation;
        myField.focus();
    }
}
}
