/**
 * @fileoverview This javascript library  is a general purpose library
 * The library is also a framework for validating the HTML forms.
 * The validation mechanism takes cares of the extesibility of various schenarios.
 * @author A207402 Atos Origin India Pvt Ltd.
 * @version 0.1
 */


/**
 * @Global Variables 
 */
var ns4;
var ie4;
var ns6;
var ie5;

/**
 *  Gives us the type of browser with its version.It sets the one of the global variable ns4,ie4,ns6,ie5  to true and others to false.
 *  @type boolean
 *  
 */

function getBrowserVersion() {
    ns4=(document.layers)? true:false;
    ie4=(document.all)? true:false;
    ns6=(document.getElementById && !ie4)? true:false;
    ie5=false;
}

/**
 * Check if a particular variable is defined or not.
 * @param {variable} variable
 * @return {boolean} 
 */
function defined (variable) {
    if (variable==null) {return false;}
    var t=""+typeof(variable);
    if (t.indexOf('undefined')>=0) {
        return false;
    } else {
        return true;
    }
}

/**
 * Gives the form Element Object
 * @param {HTMLFormObject} myfrom
 * @param {String} elementname
 * @return {HTMLFormElement Object}
 */

function getFormElement(myform,elementname) {
    if (!defined(myform)) {
        alert('Form '+myform+' not defined');
        return null;
    }
    getBrowserVersion();
    if (ns4 || ns6) {
        return myform.elements[elementname];
    }
    if (ie4 || ie5) {
        return myform.elements(elementname);
    }
    return null;
}


/**
 * Checks if the year is a leap year or not.
 * @param {int} year
 * @return {boolean} 
 */

function isLeapYear(year) {
    if((year % 4 == 0) && ( (!(year % 100 == 0))|| (year % 400 == 0))) {
        return "true";
    }else {
        return "false";
    }
}

/**
 * Trims the string
 * @param {String} s
 * @return {String}
 */
function trim(s) {
    while (s.substring(0,1) == ' ') {
        s = s.substring(1,s.length);
    }
    while (s.substring(s.length-1,s.length) == ' ') {
        s = s.substring(0,s.length-1);
    }
    return s;
}

trim1= function (trim_value){
    if(trim_value.length < 1){
        return"";
    }
    trim_value = rTrim(trim_value);
    trim_value = lTrim(trim_value);
    if(trim_value==""){
        return "";
    }
    else{
        return trim_value;
    }
} 

rTrim = function (value){
    var w_space = String.fromCharCode(32);
    var v_length = value.length;
    var strTemp = "";
    if(v_length < 0){
        return"";
    }
    var iTemp = v_length -1;
    
    while(iTemp > -1){
        if(value.charAt(iTemp) == w_space){
        }
        else{
            strTemp = value.substring(0,iTemp +1);
            break;
        }
        iTemp = iTemp-1;
	
    }
    return strTemp;
    
} //End Function

lTrim = function (value){
    var w_space = String.fromCharCode(32);
    if(v_length < 1){
        return"";
    }
    var v_length = value.length;
    var strTemp = "";
    var iTemp = 0;
    while(iTemp < v_length){
        if(value.charAt(iTemp) == w_space){
        }
        else{
            strTemp = value.substring(iTemp,v_length);
            break;
        }
        iTemp = iTemp + 1;
    } 
    return strTemp;
} 
    

/**
 *  Checks the validity of the date in mm/dd/yyyy formate
 *  @param {String} date_string
 *  @return {null / Date Object} 
 */
/* checks for mm/dd/yyyy format */

function isValidDate(date_string) {
    var monthLength = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
    var date_format_re=/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
    var date_component=new Array();
    if(date_string==""){return null;}
    if(date_format_re.test(date_string)) {
        date_component=date_format_re.exec(date_string);
    }
    if (date_component[3] % 4 == 0) {
        monthLength[1] = 29;
    }
    if(date_component[1]>12 || date_component[1]<=0) {
        return null;
    }
    if (date_component[2] > monthLength[date_component[1]-1]){
        return null;
    }else {
        var date_entered= new Date();
        date_entered.setYear(date_component[3]);
        date_entered.setMonth(date_component[1]-1);
        date_entered.setDate(date_component[2]);
        return date_entered;
    }
}

/**
 * Checks if the value is null or not
 * @param {String} value
 * @return {boolean}  
 */
function isFieldNull(value) {
    if(value==""){
        return true;
    }
    return false;
}

/**
 *  Checks if the email is a valid email address or not
 *  @param {String} addr
 *  @return {boolean}
 */
function isValidEmail (addr) {
    var re=/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*\.\w{2,}$/
    if(re.test(addr)){		
        var matches = re.exec(addr);
        return true;
    }else {
        return false;
    }
}

/**
 *  calculates the age based on the birth date
 *  @param {Date} birth_date
 *  @return {var}age
 */

function calculateAge(birth_date){
    if(!birth_date) { return false;}
    var today= new Date();
    var curr_year=today.getYear();
    var age=((today.getFullYear()<100)?(today.getFullYear()+1900):today.getFullYear()) - ((birth_date.getFullYear()<100)?(birth_date.getFullYear()+1900):birth_date.getFullYear());
    var a= today.getMonth()+1;
    var b= birth_date.getMonth()+1;
    if((today.getMonth()+1) < birth_date.getMonth()+1) age--;
    if(((today.getMonth()+1) == birth_date.getMonth()) && (today.getDate()< birth_date.getDate())) age--;
    return age;
}

/**
 * Counts the Number of Characters  or Words with in the specified text
 * @param {String} paragraph_text
 * @param {String} count_type can either be "word" or "char" based on what do you want to count
 * @return {int} no of characters or words based on count_type ie. word/char
 */

function countCharsOrWords (paragraph_text,count_type){
    var count_type_re = /.*?[(char)|(word)].*/i;
    var count_type=count_type_re.exec(count_type);
    if(count_type=="char"){
        return paragraph_text.length;
    }
    if (paragraph_text.length <2) {
        total_words = 0;
    }
    var paragraph_text = paragraph_text + " ";
    var re = /^[^A-Za-z0-9]+/gi;
    var clean_text = paragraph_text.replace(re, "");
    var word_list = clean_text.split(" ");
    var total_words = word_list.length -1;
    return total_words;
}

getTextForNWords = function (paragraph_text,max_words) {
    var words=paragraph_text.split(" ");
    var text="";
    for(i=0;i<words.length-1 ;i++) {
        text+=words[i]+ " " ;
        if(i==max_words){
            return text;
        }
    }
    return text;
}

countCharsOrWords1 = function (paragraph_text,count_type){
    var count_type_re = /.*?[(char)|(word)].*/i;
    var count_type=count_type_re.exec(count_type);
    var word_list= new Array();
    if(count_type=="char"){
        return paragraph_text.length;
    }
    if (paragraph_text.length <2) {
        total_words = 0;
    }
    var paragraph_text = paragraph_text + " ";
    var re = /^[^A-Za-z0-9]+/gi;
    var clean_text = paragraph_text.replace(re, "");
    var word_list = clean_text.split(" ");
    var total_words = word_list.length -1;
    return word_list;
}


/**
 * checks if the specified string id numeric
 * @param {String}strig
 * @return {boolean}
 */
function isInteger(strig){
    var i;
    for (i = 0; i < strig.length; i++){   
        var c = strig.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    return true;
}


// to be impleted. the function will support the various types of date formats
isValidDate1=function(date_string,format) {
    var date_formats=[{'type':'us_long','format':"mm/dd/yyyy",'reg_exp':'^(\d{2})\/(\d{2})\/(\d{4})$'},{'type':'us_short','format':"mm/dd/yy",'reg_exp':'^(\d{2})\/(\d{2})\/(\d{2})$'}];

    var date_array=new Array();
    var match;
    var format_re
    for(i=0;i<date_formats.length;i++){
        format_re=new RegExp(date_formats[i]['format']);
        if(format.match(format_re)) {
            date_array=format_re.exec(format);
        }
    }
    if(format_re.exec(format)) {
    }else {
    }

    if(format.match("dd/mm/yyyy")) {
        date_array = date_string.split("/");
        var re= /^(\d{2})\/(\d{2})\/(\d{4})$/;
        match=re.exec(date_string);
        alert(match[1]+""+match[2]+""+match[3]);
    }else if(format=="dd/mm/yyyy") {

    }else {
    }
}

/**
 * Opens the new window showing the url passed.
 * @param {URL} url
 */
function openWindow  (url) {
    window.open(url,"");
}

var message_alert="";
updateErrorMessage = function (alert_type,msg){
    if(alert_type=="div")
    document.getElementById("message_alert").innerHTML+=msg + "\n<br>";
    message_alert+=msg +"\n";
}

clearErrorMessage = function () {
    message_alert="";
}

showErrorMessage = function (alert_type,message_alert) {
    if(alert_type=="div"){
        if(ie4){
            document.getElementById("message_alert").style.visibility = "visible";
            document.getElementById("message_alert").className="txt_error";
        } else {
            document.getElementById("message_alert").display="block";
            document.getElementById("message_alert").className="txt_error";
        }
        
    }else {
        if(ie4) {
            document.getElementById("message_alert").style.visibility = "hidden";
            document.getElementById("message_alert").innerHTML="";
	    
        }else{
            document.getElementById("message_alert").display="none";
        }
        alert(message_alert);
        clearErrorMessage();
    }
}


/**
 * This is a very generic subroutine to get the value of any form element(checkbox, radio,select etc).
 * @param {HTMLFormElement} form_element
 * @return {String} value
 */
function getFormElmenentValue (form_element) {
    var s_value="";
    if (form_element.type == 'checkbox') 
    s_value = form_element.checked ? form_element.value : '';
    else if (form_element.value) // text, password, hidden
    s_value = form_element.value;
    else if (form_element.options) // select
    s_value = form_element.selectedIndex > -1 ? form_element.options[form_element.selectedIndex].value : "";
    else if (form_element.length > 0) // radiobuton
    for (var n_index = 0; n_index < form_element.length; n_index++)
    if (form_element[n_index].checked) {
        s_value = form_element[n_index].value;
        break;
    }
    return s_value;
}


/**
 *  This is a generic form handler routine for validating the HTML forms<br>
 * <a href="tutorial.html"><b>Learn how to use lib.js to validate the form</b></a>
 *  @param {HTMLForm Object} myform The compulsory form handler object to be validated
 *  @param {JavascriptHash} map Is the javascript hash. This hash gives the complete Idea of which elements needs to be validated and which way. <br>
 *  @param {String} alert_type The compulsory string indicating the type of alerting system
 * if alert_type = "div" then it show the alert message in the form body itself
 * if alert_type = "alert" then it shows the javascript alert.
 * @param {String} url Indicates the form action to be taken after successful validation of the form
 */

function validateForm (myform,map,alert_type,url) {
    message_alert="";
    var over_all_result=1;
    if(alert_type=="") { alert_type="alert" ; }
    if(alert_type=="div") document.getElementById("message_alert").innerHTML="<br>";
    
    for(i=0;i<map.length;i++) {
        var element_value=getFormElmenentValue(getFormElement(myform,map[i]['field_name']));
        if(isFieldNull(element_value)){
            over_all_result=0;
            if(map[i]['error_message'] && map[i]['error_message']!="") {
                updateErrorMessage(alert_type,map[i]['error_message']);                
            } else {
                updateErrorMessage(alert_type,"Plase enter the "+ map[i]['lable_name']);
            }
            continue;
        }
        switch(map[i]['validation_type']){
//           case 'not null' :
//             if(getFormElement(myform,map[i]['field_name']).value==""){
//                 updateErrorMessage(alert_type,"Please enter " + map[i]['lable_name'] );
//                 over_all_result=0;
//             }
//             break;
          case 'date' :
            var date_value=getFormElmenentValue(getFormElement(myform,map[i]['field_name']));
            var date_obj=isValidDate(date_value);
            if(date_obj == null) { 
                updateErrorMessage(alert_type,"Please enter valid "+ map[i]['lable_name']);
                over_all_result=0;
            }else if(map[i]['under_age']!=="") {
                var age=calculateAge(date_obj);
                if(age<parseInt(map[i]['under_age'])){
                    updateErrorMessage(alert_type,"You should be at least "+ map[i]['under_age'] +" of age");
                    over_all_result=0;
                }
            }
            break;
          case 'email' : 
            var email=getFormElmenentValue(getFormElement(myform,map[i]['field_name']));
            if(!isValidEmail(email)) {
                updateErrorMessage(alert_type,"Please enter a valid "+map[i]['lable_name']);
                over_all_result=0;
            }
            break;
          case 'zip' : 
            var zip=getFormElmenentValue(getFormElement(myform,map[i]['field_name']));
            if(!validZip(zip)) {
                updateErrorMessage(alert_type,"Please enter a valid "+map[i]['lable_name']);
                over_all_result=0;
            }
            break;
          case 'phone' : 
            var phone=getFormElmenentValue(getFormElement(myform,map[i]['field_name']));
            if(!validPhone(phone)) {
                updateErrorMessage(alert_type,"Please enter a valid "+map[i]['lable_name']+"-- e.g. ddd-ddd-dddd");
                over_all_result=0;
            }
            break;
          case 'validCharacters' :
            var value = getFormElmenentValue(getFormElement(myform,map[i]['field_name']));
            if(!validCharacters(value)) {
            	updateErrorMessage(alert_type,"Please enter a valid "+map[i]['lable_name']);
            	over_all_result=0;
            }
            break;
        }
    }
    if(!over_all_result){
        showErrorMessage(alert_type,message_alert);
    }
    if(over_all_result && url !="") {
        myform.submit();
    }
}


/**
 * Checks if the zip provided is a valid US zip or not
 * @param {String} field_value
 * @return {boolean} result
 */
 
function validZip(field_value){
    var result = true;
    if(field_value=="" || field_value==null) {return false;}
    /*
	  Check for correct zip code
    */
	 
    var zipcode = trim(field_value);
    var valid = "0123456789-";
    var hyphencount = 0;
    if (zipcode.length!=5 && zipcode.length!=10) {
        //alert("Please enter your 5 digit or 5 digit+4 zip code.");
        return false;
    }
    for (var i=0; i < zipcode.length; i++) {
        temp = "" + zipcode.substring(i, i+1);
        if (temp == "-") hyphencount++;
        if (valid.indexOf(temp) == "-1") {
		 	//alert("Invalid characters in your zip code.  Please enter number values.");
		   	return false;
        }
		 
        if ((hyphencount > 1) || ((zipcode.length==10) && ""+zipcode.charAt(5)!="-")) {
            //alert("The hyphen character should be used with a properly formatted 5 digit+four zip code, like '12345-6789'.   Please try again.");
            return false;
        }
    }
	 
    return result;
		
		
}


/**
 * Checks if the phone number provided is a valid US phone number or not
 * @param {int} phone_value
 * @return {boolean} result
 */

function validPhone(phone_value){
    var result = true;
    if(phone_value=="") {return false;}
    var stringto = trim(phone_value);
    var exp = "\\(?\\d{3}\\)?[- ]?\\d{3}[- ]?\\d{4}";
    var reg = new RegExp(exp);
    if (stringto != "") {
        if (!reg.test(stringto)) {
			result = false;
        }
    }
    return result;
}
	    
/**
 * Checks if the value provided is a alphabetic or not
 * @param {HTMLFormField} formField
 * @return {Boolean} result
 */
	    
function validCharacters(formField) {
    var result = true;
    var stringto = trim(formField);

    if (!(stringto.search(/^[a-zA-Z]*$/) != -1)) {
        //alert('Please enter only characters for the "' + fieldLabel +'" field.');
        result = false;
    }

    return result;
} 
