﻿/* Last edits: 22 Jan 2010
By: Chris Coray
Note: Added tech support localized keywords */

var isStage = (location.hostname.indexOf("stage") > 0 || location.hostname.indexOf("test") > 0) ? true : false;
var timeOut = false;

function getFormPagePath() {
	var pagePath = location.pathname;
	
	// if popup window, get refering page
	if(pagePath.indexOf("sales_call_request_popup.html") > 0) {
		var referringPage = getQueryParm("profile_url");
		if(referringPage) {
			pagePath = referringPage.substr(referringPage.indexOf(".com")+4);
		}
	}

	if(typeof n_root != "undefined") {
		switch(n_root) {
			case "de-de" :
			case "es-es" :
			case "fr-fr" :
			case "it-it" :
			case "nl-nl" :
			case "cs-cz" :
			case "ja-jp" :
			case "zh-cn" :
			case "zh-tw" :
			case "hu-hu" :
			case "pl-pl" :
			case "pt-br" :
			case "ru-ru" :
			case "sv-se" :
			case "da-dk" :
			case "fi-fi" :
			case "no-no" :
				pagePath = pagePath.replace("/"+n_root, "");
				break;
		}
	}
	return pagePath;
}

// Get Translated string if available
function gt(varname,defaultstring) {
	return ((eval("typeof "+varname) != 'undefined') ? eval(varname) : defaultstring);
}

var formTextFields = [
	["question_6173",gt("firstname_translated","First Name")],
	["question_6174",gt("lastname_translated","Last Name")],
	["question_6175",gt("company_translated","Company")],
	["question_6178",gt("country_translated","Country")],
	["question_6181",gt("city_translated","City")],
	["question_6177",gt("phone_translated","Phone Number")],
	["question_6176",gt("email_translated","E-mail Address")]
];

var allFormTextFields = [
	["question_6173",gt("firstname_translated","First Name")],
	["question_6174",gt("lastname_translated","Last Name")],
	["question_6175",gt("company_translated","Company")],
	["question_6178",gt("country_translated","Country")],
	["question_6181",gt("city_translated","City")],
	["question_6177",gt("phone_translated","Phone Number")],
	["question_6176",gt("email_translated","E-mail Address")]
];

// Convert characters above ascii 127 into html numeric character references (in decimal)
// See http://www.pinyin.info/tools/converter/chars2uninumbers.html for a useful implementation of this
function convertToEntities(input) {
	var output = "";
	for(var i=0; i<input.length; i++) {
		if (input.charCodeAt(i) <= 127) {
			output += input.charAt(i);
		}
		else {
			output += "&#" + input.charCodeAt(i) + ";";
		}
	}
	return output;
}

function convertFormTextToEntities() {
	for (var i = 0; i < allFormTextFields.length; i++) {
		theField = eval("document.getElementById('salescallrequest')." + allFormTextFields[i][0]);
		theField.value = convertToEntities(theField.value);
	}
}

// Phone prefill/validation based on country
var phoneChanged = false;
var racCountry = null;

var phonePrefills = new Array();
phonePrefills["default"] = '+00 000 0000000';
phonePrefills["United States"] = '000-000-0000';
phonePrefills["Canada"] = '000-000-0000';
phonePrefills["Japan"] = '例：00-0000-0000';

function getPhonePrefill(country) {
	var prefillvalue = ' ';
	if(country.length > 0) {
		racCountry = country;
		if(phonePrefills[country]) {
			prefillvalue = phonePrefills[country];
		}
		else {
			prefillvalue = phonePrefills["default"];
		}
	}
	else {
		racCountry = null;
	}
	return prefillvalue;
}

function setPhonePrefill(country) {
	racCountry = country;
	if(!phoneChanged) {
		document.getElementById('question_6177').value = getPhonePrefill(country);
		document.getElementById('question_6177').style.color = '#666';
	}
}

function isPhonePrefill(phonenumber) {
	for(var prefill in phonePrefills) {
		if(phonenumber == phonePrefills[prefill]) {
			return true;
		}
	}
	return false;
}

function setPhoneChanged() {
	phoneChanged = true;
}

function isValidPhoneNumber(phoneTxt) {
	if(phoneTxt.length > 0) {
		if(isPhonePrefill(phoneTxt) || 
			phoneTxt.match("^([1]{9,})|([2]{9,})|([3]{9,})|([4]{9,})|([5]{9,})|([6]{9,})|([7]{9,})|([8]{9,})|([9]{9,})|([0]{9,})$")) { // check to see if still set to prefill or a string of same character
			isValid = false;
			return "<p>" + gt("phoneerror_translated","Please enter a valid phone number.") + "</p>";
		}
		else if(phoneTxt.match("^.*[A-Za-z\!].*$")) { // check to see if it has invalid chars
			isValid = false;
			return "<p>" + gt("phoneerror_digits_translated","Please enter a valid phone number which does not contain any letters or invalid characters.") + "</p>";
		}
		else if(racCountry == "United States" || racCountry == "Canada") { // check format for US/Canada
			var formatRegex = new RegExp("^[0-9][0-9][0-9](\-|\s|\.)?[0-9][0-9][0-9](\-|\s|\.)?[0-9][0-9][0-9][0-9]$");
			if(!formatRegex.test(phoneTxt)) {
				isValid = false;
				return "<p>" + gt("phoneerror_usaformat_translated","Please enter your complete phone number in the following format: ") + phonePrefills[racCountry] + "</p>";
			}
		}
		else if(phoneTxt.length < 9) { // check format for International
			isValid = false;
			return "<p>" + gt("phoneerror_intformat_translated","Please enter your complete phone number containing approriate country and city codes.") + "</p>";
		}
	}
	else {
		return false;
	}
	return true;
}

function clearPrefill(inpt) {
	if(isPhonePrefill(inpt.value)) { 
		inpt.value = '';
		inpt.style.color = '#000';
	}	
}

// form validation
function displayRACError(msg) {
	if($("#racError").size() > 0) {
		$("#racError").html(msg);
	}
	else {
		$("#salescallrequest").prepend('<div id="racError">'+msg+'</div>');
	}
}

function formCheck(frm) {
	var formOK = true;
	var errorMessage = "";
	$(".form-error").removeClass("form-error");
	$("#racError").empty();
	
	// Check Required Fields
	var missingFieldCount = 0;
	for (i = 0; i < formTextFields.length; i++) {
		theField = eval("document.getElementById('salescallrequest')." + formTextFields[i][0]);
		if($.trim(theField.value).length === 0) {
			formOK = false;
			if(missingFieldCount == 0) {
				errorMessage += '<p>' + gt("blank_translated","The following required fields were left blank")+":</p><ul>";
			}
			errorMessage += "<li>" + formTextFields[i][1] + "</li>";
			$(theField).parent().addClass("form-error");
			missingFieldCount++;
		}
	}
	if($("#requestcall_address").is(":visible")) {
		if($("#requestcall_address input").val().length > 0) {
		} else {
			formOK = false;
			if(missingFieldCount == 0) {
				errorMessage += '<p>' + gt("blank_translated","The following required fields were left blank")+":</p><ul>";
			}
			errorMessage += "<li>" + $("#requestcall_address label").text() + "</li>";
			$("#requestcall_address").addClass("form-error");
			missingFieldCount++;
		}
		if($("#requestcall_postal input").val().length > 0) {
		} else {
			formOK = false;
			if(missingFieldCount == 0) {
				errorMessage += '<p>' + gt("blank_translated","The following required fields were left blank")+":</p><ul>";
			}
			errorMessage += "<li>" + $("#requestcall_postal label").text() + "</li>";
			$("#requestcall_postal").addClass("form-error");
			missingFieldCount++;
		}
	}
	if(missingFieldCount > 0) {
		errorMessage += "</ul>";
	}
	
	//check additional fields
	

	// check email address
	var emailTxt = frm.question_6176.value;
	regex = new RegExp("^.+@.+$");
	if (emailTxt != "" && !regex.test(emailTxt)) {
		formOK = false;
		errorMessage += "<p>" + gt("emailerror_translated","Please enter an e-mail address with a valid format (i.e. \"username@domainname\")") + "</p>";
		$(frm.question_6176).parent().addClass("form-error");
	}

	// check phone number
	var phoneTxt = $.trim(frm.question_6177.value);
	if(phoneTxt != "") {
		var phoneStatus = isValidPhoneNumber(phoneTxt);
		if(phoneStatus !== true) {
			formOK = false;
			errorMessage += phoneStatus;
			$(frm.question_6177).parent().addClass("form-error");
		}
	}
	
	// if errors, append error msg
	if (!formOK) {
		displayRACError('<p><strong>'+gt("error_translated","Your form was not submitted because of the following problems:")+'</strong></p><div id="racErrorMsgs">' + errorMessage + '</div>');
		return false;
	}

	//test for spam
	if(timeOut === false){
		alert(gt("timermsg_translated","Your form was not submitted because it was filled out too quickly. In order to protect against bots spamming our form, we have set a timer. Please wait a moment and try submitting this form again."));
		return false;
	}
	
	if(frm.novell_magic_field.value != '') {
		alert(gt("Your browser has triggered a spam security filter. Please make sure you have an updated browser and try submitting the form again."));
		return false;
	}
	
	// set the subject
	var subject = "Novell.com Web Lead - Call Immediately (" + frm.question_6178.value + ")";
	frm.email_subject.value = subject;

	// set the pageencoding (charset)
	if(typeof n_enc != 'undefined') {
		frm.charset.value = n_enc;
	}

	// set the language
	var langtag = (typeof n_lang != 'undefined' ? n_lang.toUpperCase() : 'EN-US');
	var requestfrom = "Request a Call Form:"+langtag;
	frm.request_from.value = requestfrom;
	frm.question_6241.value = langtag;

	// set the refering url
	if(document.referrer && document.referrer.length > 0) {
		frm.question_6243.value = document.referrer;
	}
	
	// set the thankyou page
	if(typeof rc_thankyou_page != 'undefined') {
		frm.thankyou_page.value = rc_thankyou_page;
	}

	// Set the profile_url
	var profileUrl = getQueryParm('profile_url');
	if(profileUrl !== null) {
		frm.profile_url.value = profileUrl;
	}
	else {
		// We are embedded in a page
		frm.profile_url.value = location.href;
	}

	convertFormTextToEntities();

	//add email address to Google Analytics
	pageTracker._setVar(document.getElementById('question_6176').value);
	
	// tech support keyworld filter
	var supportTermsRegex = new RegExp("help|problem|support|tech|probleme|soporte|hilfe|technische|technischer|ayuda|problema|asistencia|técnica|aide|problème|technique|guida|supporto|tecnico|ヘルプ|問題|サポート|技術|テクニカルサポート|probleem|technisch|hjälp|teknisk|帮助|问题|支持|技术|技术支持","i");
	if(frm.question_6184.value.search(supportTermsRegex) >= 0) {
		showRACTech();
		return false;
	}
	
	// home use keyworld filter
	var homeTermsRegex = new RegExp("personal|private|privat|^pr$|individual|^none$|=|^-$|--|home|^no$|no company|^\\^$|^\\.$|abc|^x$|xxx|^xy|^yx|^xyz|priv$|familie|residencial|at my own|one man band|ania|wirek|dom|osoba prywatna|pracownik|prywatnie|zadna|brak|maison|utilisateur domestique|utilisation à la maison|personnel|individuel|aucune compagnie|aucun|aucune|privé|haus|hausgebrauch|persönlich|persönlicher gebrauch|einzeln|keine firma|kein|keine|nein|nessun\'azienda|nessuno|nessuna|casa|utente domestico|uso domestico|personale|privato|famiglia|nenhum|repouso|usuário home|uso home|pessoal|nenhuma companhia|confidencial|família|ama de casa|privado|Никакие|Дом|Домашний потребитель|Домашняя польза|Лично|индивидуально|Отсутствие компании|приватно|семья|无|家|家庭用户|家庭用途|个人|单独|没有公司|私有|家庭|どれも|家|ホームユーザー|家の使用|個人的|個々|会社無し|私用|家族","i");
	if(frm.question_6175.value.search(homeTermsRegex) >= 0) {
		showRACHome();
		return false;
	}
}

//var isInitialized = false;
function initializeRAC() {
	if(!isLoadeEasing || !isLoadedAutoSize) {
		setTimeout(initializeRAC, 1000);
		return;
	}
	var frm = document.getElementById('salescallrequest');
	$("#requestcall textarea.expanding").autoResize();
	$("#question_6178").change(function() {
		var country = $("#question_6178").val();
		if(country == null || country == 'undefined') {
			country = 'undefined';
		} else {
			switch(country) {
				//Asia Pacific
				case "Afghanistan" :
				case "American Samoa" :
				case "Bangladesh" :
				case "Bhutan" :
				case "Brunei Darussalam" :
				case "Cambodia" :
				case "Christmas Island" :
				case "Cocos (Keeling) Islands" :
				case "Fiji Islands" :
				case "French Polynesia" :
				case "Indonesia" :
				case "Micronesia, Federated States" :
				case "Mongolia" :
				case "Myanmar" :
				case "Nepal" :
				case "New Caledonia" :
				case "Pakistan" :
				case "Palau" :
				case "Papua New Guinea" :
				case "Philippines" :
				case "Samoa" :
				case "Solomon Islands" :
				case "Sri Lanka" :
				case "Thailand" :
				case "Tonga" :
				case "Vietnam" :
				
				//Latin America
				case "Anguilla" :
				case "Antigua and Barbuda" :
				case "Argentina" :
				case "Aruba" :
				case "Bahamas" :
				case "Barbados" :
				case "Belize" :
				case "Bermuda" :
				case "Bolivia" :
				case "Brazil" :
				case "Cayman Islands" :
				case "Chile" :
				case "Colombia" :
				case "Costa Rica" :
				case "Dominica" :
				case "Dominican Republic" :
				case "Ecuador" :
				case "El Salvador" :
				case "Falkland Islands (Malvinas)" :
				case "French Guiana" :
				case "Grenada" :
				case "Guadeloupe" :
				case "Guatemala" :
				case "Guyana" :
				case "Haiti" :
				case "Honduras" :
				case "Jamaica" :
				case "Martinique" :
				case "Mexico" :
				case "Netherlands Antilles" :
				case "Nicaragua" :
				case "Panama" :
				case "Paraguay" :
				case "Peru" :
				case "Saint Kitts and Nevis" :
				case "Saint Lucia" :
				case "Saint Vincent & Grenadines" :
				case "Suriname" :
				case "Trinidad and Tobago" :
				case "Turks and Caicos Islands" :
				case "Uruguay" :
				case "Puerto Rico" :
				case "Venezuela" :
				case "Virgin Islands, British" :
				
				//EMEA
				case "Algeria" :
				case "Angola" :
				case "Belarus" :
				case "Benin" :
				case "Botswana" :
				case "Bulgaria" :
				case "Burkina Faso" :
				case "Cameroon" :
				case "Central African Republic" :
				case "Chad" :
				case "Cote d&#39;Ivoire" :
				case "Croatia" :
				case "Cyprus" :
				case "Czech Republic" :
				case "Egypt" :
				case "Estonia" :
				case "Ethiopia" :
				case "Faroe Islands" :
				case "Gabon" :
				case "Ghana" :
				case "Greenland" :
				case "Guadeloupe" :
				case "Hungary" :
				case "Iceland" :
				case "Iraq" :
				case "Israel" :
				case "Jordan" :
				case "Kazakhstan" :
				case "Kenya" :
				case "Kuwait" :
				case "Latvia" :
				case "Lebanon" :
				case "Liberia" :
				case "Lithuania" :
				case "Macedonia" :
				case "Madagascar" :
				case "Malawi" :
				case "Maldives" :
				case "Mali" :
				case "Mauritius" :
				case "Mayotte" :
				case "Moldova, Republic of" :
				case "Morocco" :
				case "Namibia" :
				case "Niger" :
				case "Oman" :
				case "Poland" :
				case "Qatar" :
				case "R&#233;union" :
				case "Romania" :
				case "Russia" :
				case "Rwanda" :
				case "Saint Helena" :
				case "Saudi Arabia" :
				case "Serbia and Montenegro" :
				case "Seychelles" :
				case "Slovakia" :
				case "Slovenia" :
				case "Tanzania" :
				case "Tunisia" :
				case "Turkey" :
				case "Uganda" :
				case "Ukraine" :
				case "United Arab Emirates" :
				case "Uzbekistan" :
				case "Western Sahara" :
				case "Yemen" :
				case "Zambia" :
				case "Zimbabwe" :

				//custom
				case "Austria" :
				case "Germany" :
				case "Switzerland" :
					$("#requestcall_city, #requestcall_address, #requestcall_country").addClass("extra-fields");
					$("#requestcall_address, #requestcall_postal, #requestcall_state").slideDown({ duration: 500, easing: "jswing"});
					break;
				default:
					$("#requestcall_city").css("padding-right","0");
					$("#requestcall_address, #requestcall_postal, #requestcall_state").slideUp({ duration: 500, easing: "jswing"});
			}
			return true;
		}
								   
	});

	// prefil form fields
	frm.question_6173.value = (typeof FIRSTNAME != 'undefined') ? FIRSTNAME : '';
	frm.question_6174.value = (typeof LASTNAME != 'undefined') ? LASTNAME : '';
	frm.question_6175.value = (typeof COMPANY != 'undefined') ? COMPANY : '';
	frm.question_6179.value = (typeof ADDRESS1 != 'undefined') ? ADDRESS1 : '';
	frm.question_6178.value = (typeof COUNTRY != 'undefined' && COUNTRY.length > 0) ? COUNTRY : ((n_country !== null && n_country.length > 3) ? n_country.substring(3) : '');
	frm.question_6181.value = (typeof CITY != 'undefined') ? CITY : '';
		
	if(typeof PHONENUMBER != 'undefined' && PHONENUMBER.length > 0) {
		frm.question_6177.value =  PHONENUMBER;
		isPhoneChanged = true;
	}
	else {
		frm.question_6177.value =  getPhonePrefill(frm.question_6178.value);
	}

	var eMail = (typeof EMAIL != 'undefined') ? EMAIL.substring(EMAIL.lastIndexOf(',')+1) : '';
	frm.question_6176.value = unescape(eMail.toLowerCase());

	//sets the timeout variable if the user is not logged in
	if(typeof isLoggedIn !== "undefined" && isLoggedIn === true) {
		timeOut = true;
	} else {
		setTimeout("timeOut = true;", 4000);
	}
	
	$("#fromUrl").val(window.location.href);
	$("#question_6178").trigger("change"); //if it was set via login info, trigger the change function to handle extra fields for certain countries
}

var hasjQuery = (typeof(jQuery) != "undefined") ? true : false;
var isLoadeEasing = false;
var isLoadedAutoSize = false;
if(hasjQuery) {
	$.getScript("/common/inc/jquery/plugins/autoresize.jquery.min.js", function() { isLoadedAutoSize = true; });
	$.getScript("/common/inc/jquery/plugins/jquery.easing.1.3.js", function() { isLoadeEasing = true; });
	$(document).ready(function() {
		if($("#salescallrequest").length > 0) {
			initializeRAC();
		}
	});
}