/*
Created By:     Ramen Das on 24-Aug-09

Modified By:    Ramen Das on 05-Mar-10
                Improved the script for radio groups and checkboxes
*/

/* Enums */
var validationTypeEnums = {'Required':0, 'Email':1, 'PhoneNumber':2};

/* Regular expressions */
var REGEX_EMAIL = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var REGEX_PHONE = /^(\+[0-9]{1,4})?[ \-\.]?(\(?[0-9]{1,4}\)?)?[ \-\.]?[0-9]{6,11}$/;

/* String constants */
var LEADING_TEXT_FOR_MESSAGE = 'Please complete the following fields:';
var LEADING_TEXT_FOR_ITEMS = '\t* ';


/* Form validation routine */
function ValidateForm(formValidationParams)
{
	if (formValidationParams.length != 3)
	{
	   alert('Parameter array does not have all 3 necessary containing arrays!');
	   return false;
	}
	if (formValidationParams[0].length != formValidationParams[1].length || formValidationParams[1].length != formValidationParams[2].length)
	{
	   alert('Parameter arrays are not of same dimension!');
	   return false;
	}

/*	array#1 holds element IDs (or Name if it's a radio group) */
	var elementIDsToValidate = formValidationParams[0];
/*	array#2 holds validation type from the enum validationTypeEnums. */
	var validationTypes = formValidationParams[1];
/*	array#3 holds message text for alert function to show */
	var validationMessages = formValidationParams[2];

	var message;
	message = '';
	
	for (i=0; i<elementIDsToValidate.length; i++)
	{
		var elementToValidate, regEx, isValid;

		elementToValidate = document.getElementById(elementIDsToValidate[i]);

		if (elementToValidate == null)
		{
		    var groupToValidate = document.getElementsByName(elementIDsToValidate[i]);
    		if (groupToValidate == null) continue;
    		
		    isValid = false;
		    for (j=0; j<groupToValidate.length; j++)
		    {
		        var elementInGroup = groupToValidate.item(j);
		        if (elementInGroup.type == "radio" || elementInGroup.type == "checkbox")
		            if (elementInGroup.checked)
		            {
		                isValid = true;
		                break;
		            }
		    }
        }
        else
        {
		    isValid = true;
		    switch (validationTypes[i])
		    {
		       case validationTypeEnums.Required:
		       default:
		            switch (elementToValidate.type)
		            {
		                case "textbox": default: if (elementToValidate.value == '') isValid = false; break;
		                case "checkbox": if (!elementToValidate.checked) isValid = false; break;
		            }
                    break;

		       case validationTypeEnums.Email:
                    if (elementToValidate.value == '') continue;
                    regEx = REGEX_EMAIL;
                    if (!regEx.test(elementToValidate.value)) isValid = false;
                    break;

		       case validationTypeEnums.PhoneNumber:
                    if (elementToValidate.value == '') continue;
                    regEx = REGEX_PHONE;
                    if (!regEx.test(elementToValidate.value)) isValid = false;
                    break;
		    }
		}
		
	    if (!isValid)
	       message += LEADING_TEXT_FOR_ITEMS + validationMessages[i] + '\n';
	}

	if (message != '')
	{
	   alert(LEADING_TEXT_FOR_MESSAGE + '\n\n' + message);
	   return false;
	}

	/* these are to be commented out after finishing testing */
	/*alert('Successfully sent the form!');
	return false;*/
	/* these are to be commented in after finishing testing */
	return true;
}

/*
An example formValidationParams:

var formParams =
[
// array#1 holds element IDs (or Name if it's a radio group)
   [
        'lead_personfirstname','lead_personlastname','lead_companyname',
	    'lead_persontitle','lead_personemail','lead_personemail',
	    'lead_personphonenumber','lead_personphonenumber'
   ],
// array#2 holds validation type from the enum validationTypeEnums
   [
        validationTypeEnums.Required,validationTypeEnums.Required,
        validationTypeEnums.Required,validationTypeEnums.Required,
        validationTypeEnums.Required,validationTypeEnums.Email,
	    validationTypeEnums.Required,validationTypeEnums.PhoneNumber
   ],
// array#3 holds message text for alert function to show
   [
        'First Name','Last Name','Company','Job Title',
    	'Email','Email, e.g. first.last@ipd.com',
	    'Phone Number','Phone Number, e.g. +44 (02) 123456'
   ]
];
*/



/* Form clearing routine */
function ClearForm(elementIDsToClear)
{
/*	elementIDsToClear holds element IDs (or Name if it's a radio group) */

	for (i=0; i<elementIDsToClear.length; i++)
	{
		var elementToValidate;

		elementToValidate = document.getElementById(elementIDsToClear[i]);

		if (elementToValidate == null)
		{
		    var groupToValidate = document.getElementsByName(elementIDsToClear[i]);
    		if (groupToValidate == null) continue;
    		
		    for (j=0; j<groupToValidate.length; j++)
		    {
		        var elementInGroup = groupToValidate.item(j);
		        if (elementInGroup.type == "radio" || elementInGroup.type == "checkbox")
		            elementInGroup.checked = false;
		    }
        }
        else
        {
            switch (elementToValidate.type)
            {
                case "textbox": default: elementToValidate.value = ''; break;
                case "checkbox": elementToValidate.checked = false; break;
            }
		}
	}
	return false;
}

function lead_companycountry_onchange()
{
    //alert("lead_companycountry_onchange");

    var country = document.getElementById("lead_companycountry");

    if (country != null)
    {
        var lead_c_region = document.getElementById("lead_c_region");

        if (lead_c_region != null)
        {
            lead_c_region.value = GetRegionByCountryName(country.options[country.selectedIndex].text);

            // DEBUG
            //alert("region value: " + lead_c_region.value);
            //var spanDebug = document.getElementById("spanDebug");
            //if (spanDebug != null)
            //{
                //spanDebug.innerHTML = lead_c_region.value;
            //}
        }
        else
        {
            alert("Failed to retrieve hidden field named 'lead_c_region'");
        }
    }
    else
    {
        alert("Failed to retrieve 'lead_companycountry' element");
    }
}

function GetRegionByCountryName(countryName)
{
    var region = "";

    //alert("GetRegionByCountryName called with countryName: " + countryName);

    switch (countryName)
    {
        case "Algeria": case "Angola": case "Botswana": case "Burkina Faso": case "Burundi": case "Cameroon": case "Central African Republic":
        case "Chad": case "Congo": case "Congo, Democratic Republic": case "Djibouti": case "Egypt": case "Eritrea": case "Ethiopia":
        case "French Guyana": case "Gabon": case "Gambia": case "Ghana": case "Guadeloupe (French)": case "Ivory Coast (Cote D'Ivoire)":
        case "Kenya": case "Lesotho": case "Liberia": case "Libya": case "Malawi": case "Mauritania": case "Morocco": case "Mozambique":
        case "Namibia": case "Niger": case "Nigeria": case "Rwanda": case "Senegal": case "Sierra Leone": case "Somalia": case "Sudan": 
        case "Swaziland": case "Togo": case "Uganda": case "Western Sahara": case "Zaire": case "Zambia": case "Zimbabwe": case "South Africa":
            region = "Africa";
            break;

        case "Afghanistan, Islamic State": case "Armenia": case "Azerbaidjan": case "Bahrain": case "Bangladesh": case "Bhutan": case "China": 
        case "Georgia":case "Hong Kong":
            region = "Asia";
            break;

        case "Albania": case "Bosnia-Herzegovina": case "Bulgaria": case "Croatia": case "Czech Republic": case "Estonia": case "Former Czechoslovakia": 
        case "Hungary": case "Latvia": case "Lithuania": case "Macedonia": case "Montenegro": case "Poland": case "Romania": case "Serbia":case "Slovenia":
            region = "CEE";
            break;

        case "Austria": case "Germany":case "Switzerland":
            region = "DACH";
            break;

        case "England": case "Faroe Islands": case "Guernsey": case "Ireland": case "Isle of Man": case "Jersey": case "Northern Ireland": 
        case "Scotland": case "UK": case "United Kingdom":case "Wales":
            region = "UK";
            break;

        case "American Samoa": case "Andorra, Principality of": case "Anguilla": case "Antarctica": case "Antigua and Barbuda": case "Argentina":
        case "Aruba": case "Bahamas": case "Barbados": case "Belarus": case "Belize": case "Benin": case "Bermuda": case "Bolivia": case "Bouvet Island":
        case "Brazil": case "British Indian Ocean Terr.": case "Brunei Darussalam": case "Cambodia, Kingdom of": case "Cape Verde": case "Cayman Islands":
        case "Chile": case "Christmas Island": case "Cocos (Keeling) Islands": case "Colombia": case "Comoros": case "Cook Islands": case "Costa Rica":
        case "Cuba": case "Cyprus": case "Dominica": case "Dominican Republic": case "East Timor": case "Ecuador": case "El Salvador": case "Equatorial Guinea":
        case "Falkland Islands": case "Fiji": case "Finland": case "Former USSR": case "French Southern Territories": case "Gibraltar": case "Greece":
        case "Greenland": case "Grenada": case "Guam (USA)": case "Guatemala": case "Guinea": case "Guinea Bissau": case "Guyana": case "Haiti":
        case "Heard and McDonald Islands": case "Holy See (Vatican City)": case "Honduras": case "Iceland": case "India": case "Indonesia": case "Iran":
        case "Iraq": case "Israel": case "Jamaica": case "Jordan": case "Kazakhstan": case "Kiribati": case "Kuwait": case "Kyrgyz Republic (Kyrgyzstan)":
        case "Laos": case "Lebanon": case "Liechtenstein": case "Luxembourg": case "Macau": case "Madagascar": case "Malaysia": case "Maldives": case "Mali":
        case "Malta": case "Marshall Islands": case "Martinique (French)": case "Mauritius": case "Mayotte": case "Micronesia": case "Moldavia": case "Monaco":
        case "Mongolia": case "Montserrat": case "Myanmar": case "Nauru": case "Nepal": case "Netherlands Antilles": case "Neutral Zone": case "New Caledonia (French)":
        case "Nicaragua": case "Niue": case "Norfolk Island": case "North Korea": case "Northern Mariana Islands": case "Oman": case "Pakistan": case "Palau":
        case "Panama": case "Papua New Guinea": case "Paraguay": case "Peru": case "Philippines": case "Pitcairn Island": case "Polynesia (French)":
        case "Puerto Rico": case "Qatar": case "Reunion (French)": case "Russian Federation": case "S. Georgia S. Sandwich Is.": case "Saint Helena":
        case "Saint Kitts Nevis Anguilla": case "Saint Lucia": case "Saint Pierre and Miquelon": case "Saint Tome (Sao Tome)": case "Saint Vincent Grenadines":
        case "Samoa": case "San Marino": case "Saudi Arabia": case "Seychelles": case "Singapore": case "Slovak Republic": case "Solomon Islands":
        case "South Korea": case "Sri Lanka": case "Suriname": case "Svalbard and Jan Mayen Is.": case "Syria": case "Tadjikistan": case "Taiwan":
        case "Tanzania": case "Thailand": case "Tokelau": case "Tonga": case "Trinidad and Tobago": case "Tunisia": case "Turkey": case "Turkmenistan":
        case "Turks and Caicos Islands": case "Tuvalu": case "Ukraine": case "United Arab Emirates": case "Uruguay": case "USA Minor Outlying Islands":
        case "Uzbekistan": case "Vanuatu": case "Venezuela": case "Vietnam": case "Virgin Islands (British)": case "Virgin Islands (USA)": 
        case "Wallis and Futuna Islands": case "Yemen": case "Australia":case "New Zealand":
            region = "Unclassified";
            break;

        case "Canada":
            region = "Canada";
            break;

        case "Japan":
            region = "Japan";
            break;

        case "Mexico":
            region = "Mexico";
            break;

        case "Netherlands":
            region = "Netherlands";
            break;

        case "Denmark": case "Danmark":
            region = "Denmark";
            break;

        case "Norway":
            region = "Norway";
            break;

        case "Sweden":
            region = "Sweden";
            break;

        case "Belgium":
            region = "Belgium";
            break;

        case "France": case "France (European Territory)":
            region = "France";
            break;

        case "Italy":
            region = "Italy";
            break;

        case "Portugal":
            region = "Portugal";
            break;

        case "Spain":
            region = "Spain";
            break;

        case "United States":
            region = "US";
            break;

        default:
            region = "";
            break;
    }
  
    return region;
}
