/******************************************************************************/
// General Functions
//Migrated from Janus "scripts/" folder for Titanized Account Manager
//-dw 7/14/2009
// Cross browser object access
function getObj(name) {
	if (document.getElementById) {
		this.obj = document.getElementById(name);
	} else if (document.all) {
		this.obj = document.all[name];
	} else if (document.layers) {
		this.obj = document.layers[name];
	}
}
// trim whitespaces from beginning and end of a field
function trim(fieldValue) {
	// strips ALL whitespace (debugging only!)
	//return fieldValue.replace(/\s/g,'');
	// strips only from the beginning and end
	return fieldValue.replace(/^\s*|\s*$/g,'');
}

/******************************************************************************/
// Omniture Helpers

// custom link tracking
function clicktrack(pageName,clickType) {
	var s=s_gi(s_account);
	// Defaults to DHTML pops
	if (clickType != '') {
		s.tl(this,'o','DHTML: ' + pageName);
	} else {
		s.tl(this,'o',clickType + ': ' + pageName);
	}
}

/******************************************************************************/
// RNT live chat

function chatRNT (skillSet) {
	if (skillSet == "")	{
		skillSet = "no referrer";
	}
	window.open( 'http://support.register.com/cgi-bin/register.cfg/php/enduser/live_thin_launch.php?referrer=' + escape(skillSet), '', 'width=472,height=320,resizable=yes,scrollbars=no,toolbar=no,menubar=no');
}

/******************************************************************************/
// Embedded Popups

function showpopbox(sName,offsetX,offsetY,sLink) {
	// fix burn through
	fixBurnThru(true);

	// get the position of the associated link
	if ((sLink == null) || (sLink == "")) { sLink = sName+'_link'; }

	if (document.getElementById(sLink) != null) {
		var xPos = findPos(document.getElementById(sLink),'x');
		var yPos = findPos(document.getElementById(sLink),'y');
		// pad the position so the link will not be covered
		// added the -310 and -163 to adjust to the correct positioning in the Titan page template
		xPos = xPos + 5-310;
		yPos = yPos + 13-163;
	} else {
		// if there's no link to attach to, put the popup under the nav
		var xPos = 100;
		var yPos = 150;
	}
	// move elements if needed
	if (!isNaN(offsetX)) { xPos = xPos + offsetX; }
	if (!isNaN(offsetY)) { yPos = yPos + offsetY; }
	// open the embedded popup
	document.getElementById(sName).style.display = 'block';
	document.getElementById(sName).style.left = xPos + "px";
	document.getElementById(sName).style.top = yPos + "px";
	return;
}
function showinlinepopbox(sName) {
	// fix burn through
    fixBurnThru(true);
	// opens the inline popups
	document.getElementById(sName).style.display = 'block';
	return;
}
function hidepopbox(sName) {
	// Closes the popups
	document.getElementById(sName).style.display = 'none';
	// fix burn through
    fixBurnThru(false);
	return;
}
// finds the position of the click to place the popup
function findPos(obj,axis) {
	var cur = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			if (axis == 'x') { cur += obj.offsetLeft }
			else { cur += obj.offsetTop }
			obj = obj.offsetParent;
		}
	} else {
		if ((axis == 'x') && (obj.x)) { cur += obj.x; }
		if ((axis == 'y') && (obj.y)) { cur += obj.y; }
	}
	return cur;
}
// fix the burnthrough on select elements in IE, ns6 and 7 do not have burn-through
// this script is duplicated in menu_settings.js as "fixBurn" for external sites (RNT, Unopi, etc)
function fixBurnThru(isHidden) {
	// only run for IE 6 or lower
	if (document.all && (navigator.userAgent.indexOf("MSIE 7") == -1)) {
		var rows = document.getElementsByTagName('select');
		for( var i = 0, row; row = rows[i]; i++ ) {
			if (isHidden) {
				row.style.visibility = "hidden";
			} else {
				row.style.visibility = "visible";
			}
		}
	}
	return;
}

/******************************************************************************/
// Learn More inline pops

function expandDetails(elementName) {
	document.getElementById('brief_' + elementName).style.display = 'none';
	document.getElementById('detailed_' + elementName).style.display = 'block';
	document.getElementById('close_' + elementName).style.display = 'block';
}
function collapseDetails(elementName) {
	document.getElementById('detailed_' + elementName).style.display = 'none';
	document.getElementById('close_' + elementName).style.display = 'none';
	document.getElementById('brief_' + elementName).style.display = 'block';
}

/******************************************************************************/
// Regular pop ups

function popup(url,width,height,isFullURL,isScrollable) {
	var windowName = 'newwin'+Math.round(Math.random()*10);
	if (isFullURL != true) {
		// FullURL comes from the script tile at the top of each page
		// append it to the url passed in to get a page on this server
		url = fullURL + url;
	}
	if (isScrollable == true) {
		// This popup will have scroll bars
		isScrollable = "yes";
	} else {
		// Default
		// This popup will not have scroll bars
		isScrollable = "no";
	}
	window.open(url, windowName, 'width='+ width +',height='+ height +'toolbars=no,resizable=yes,scrollbars=' + isScrollable + ',status=no,location=no,menubar=no,titlebar=no');
}

/******************************************************************************/
// Event handling

var	noPop = "0"; // when noPopup=1 do not popup window

// these should be overridden on the page where the popunder is inserted
var	sPopURL = "";
var iPopWidth = 100;
var iPopHeight = 100;
var iType = "up";
var bScroll = 0;

// open the popups
function goPop() {
	if ( (sPopURL != "") && (noPop == 0) ) {
		var	popwin = window.open(sPopURL,'wwin','toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=' + bScroll + ',resizable=yes,width=' + iPopWidth + ',height=' + iPopHeight + ',screenY=100,screenX=100,left=100,top=100');
		if (popwin != null) {
			if (iType == 'up') {
				// pop up
				popwin.focus();
			} else {
				// pop under
				popwin.blur();
			}
		}
	}
}
// event handling for IE users
function handler(e)	{
	e = window.event;

	if (e != null) {
		if (document.all && (navigator.userAgent.indexOf("MSIE") != -1)) {
			if(e.keyCode && e.keyCode == 13) { noPop=1; }
			if(e.type== "click" ||	e.type== "dblclick") { noPop=1; }
			if(e.type== "unload") {
				if((e.clientX >	0 && e.clientX < 120) && e.clientY < 0 ) {	noPop=1; }
				goPop();
			}
			e.cancelBubble=true;
		} else {
			if(e.keyCode && e.keyCode == 13) { noPop=1; }
			if(e.type== "click" ||	e.type== "dblclick") { noPop=1; }
			if(e.type== "unload") {
				goPop();
			}
		}
	}
}

function addhandlers(o)	{
	o.onabort    = handler;
	o.onclick    = handler;
	o.ondblclick = handler;
	o.onerror    = handler;
	//o.onsubmit   = handler;
	o.onunload   = handler;
	o.onkeypress = handler;
}


// NOTE: if starthandlers is present on a page, onclick events will not work for other functions
function starthandlers() {
	//if (document.all && (navigator.userAgent.indexOf("MSIE") != -1)) {
		addhandlers(window);
		addhandlers(document);
		for(var	d="0"; d < document.links.length; d++)
			addhandlers(document.links[d]);
		for(var	d="0"; d < document.images.length; d++)
			addhandlers(document.images[d]);
		for(var	d="0"; d < document.forms.length; d++) {
			addhandlers(document.forms[d]);
			for(var	e="0"; e < document.forms[d].elements.length; e++)
				if(document.forms[d].elements[e].type != "radio") {
					addhandlers(document.forms[d].elements[e]);
				}
		}
	//}
}

/******************************************************************************/
// Form Validation

// validate all the fields in an array and return the errors in one shot
// list required fields in the array
function validateFields(thisForm,type) {
	var formFields = new Array();
	if (type == "validateLoginForm") {
		// login, existing user
		formFields[0] = new Array('username','User Name cannot be empty');
		formFields[1] = new Array('password','Password cannot be empty');
	} else {
		// login, new user
		formFields[0] = new Array('firstname','First Name cannot be empty');
		formFields[1] = new Array('lastname','Last Name cannot be empty');
	}
	var errors = "";
	for (i=0; i<formFields.length; i++) {
		// if the field is empty
		if (trim(thisForm.elements[formFields[i][0]].value) == "") {
			// append the error to the message
			errors += '\n     ' + formFields[i][1];
		}
	}
	if (errors != "") {
		alert('Please correct the following errors:        ' + errors);
		return false;
	} else {
		return true;
	}
}
// pass the original function into the new one
function validateLoginForm(frm) {
	return validateFields(frm,'validateLoginForm');
}
function validateSignInForm(frm) {
	return validateFields(frm,'validateSignInForm');
}

/******************************************************************************/
// RNT Ticket Creation Form Validation

// there are limited fields available on the RNT side so make sure everything
// ends up in the "incident notes" field before sending the form
// list ALL fields in the array, required fields have error message

// RNT requires (firstName, lastName, email, phone)
function validateRNT(thisForm,formFields) {
	// check service agreement
	if (!thisForm.elements['serviceagreement'].checked) {
		alert('You must agree to the Services Agreement to proceed.');
		return false;
	}
	var creditcard = validateCard(thisForm.cc_number.value, thisForm.cc_type.value, thisForm.cc_month.value, thisForm.cc_year.value);
	if (creditcard == false) {
		return false;
	}
	var errors = "";
	for (i=0; i<formFields.length; i++) {
		// if the field is empty and there is a message for the field...
		//alert(formFields[i][0] + ': ' + thisForm.elements[formFields[i][0]].value);
		if ((trim(thisForm.elements[formFields[i][0]].value) == "")
			&& (formFields[i][1] != '')) {
			// append the error to the message
			errors += '\n     ' + formFields[i][1];
		}
	}
	if (errors != "") {
		// display the errors found
		alert('Please correct the following errors:        ' + errors);
		return false;
	} else {
		// put all info into incident notes
		var formString = "";
		for (i=0; i<formFields.length; i++) {
			//...except for the cc number
			if (formFields[i][0] != 'cc_number') {
				formString += '\n' + formFields[i][0] + ':\t\t' + trim(thisForm.elements[formFields[i][0]].value);
			}
		}
		thisForm.incidentNotes.value = formString;
		//alert(formString);
		//return false;
		return true;
	}
}
function copy(thisForm,type) {
	// Copy function for "same as above" links on .pro form
	if (type == 'name') {
		var copyfields = ['firstName', 'lastName', 'middlename', 'suffix'];
	} else {
		var copyfields = ['address1', 'address2', 'city', 'state', 'zip'];
	}
	for (i=0; i<copyfields.length; i++) {
		thisForm.elements['license_' + copyfields[i]].value = thisForm.elements[copyfields[i]].value;
	}
}

/******************************************************************************/
// Create/edit account functions - state/country changes

// Email validation
function validateEmail(fieldObj,hideAlert) {
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	var address = fieldObj.value;
	if(reg.test(address) == false) {
		if (hideAlert != true) {
			alert('Your email address does not appear to be valid.\nPlease enter a valid email address to proceed.');
		}
		return false;
	} else {
		return true;
	}
}

// strip all whitespace
function stripwhitespace(fieldObj) {
	var newString = new String(fieldObj.value);
	fieldObj.value = newString.replace(/\s/g, '');
}

// strip nonalphanumberic characters
function stripalphanonnumeric(formName,fieldName) {
	var field = eval('document.forms[formName].' + fieldName);
	var newString = new String(field.value);
	field.value = newString.replace(/[^0-9A-Za-z -]/g, '');
}

// strip non-numeric characters from phone and fax fields
function stripnonnumeric(formName,fieldName) {
	var field = eval('document.forms[formName].' + fieldName);
	var newString = new String(field.value);
	field.value = newString.replace(/[^0-9]/g, '');
	// check the country code if this is the fax field
	if (fieldName == 'fax') {
		if (document.forms[formName].fax.value != "") {
			document.forms[formName].countryDiallingFax.value = document.forms[formName].country.value;
		} else {
			document.forms[formName].countryDiallingFax.value = '--';
		}
	}
}
// set the radio button automatically when the state field is changed
function stateprov(formName,isEnabled) {
	if (isEnabled == 'false') {
		document.forms[formName].stateOption[1].checked = true;
		document.forms[formName].state.value = "";
	} else {
		document.forms[formName].stateOption[0].checked = true;
	}
}
// change the dialing codes automatically when the country is changed
function setCountries(formName,countryValue,ajaxURL) {
	// set the country dialing codes
	document.forms[formName].country.value = countryValue;
	document.forms[formName].countryDialling.value = countryValue;

	// fax field is optional
	if (document.forms[formName].fax) {
		if (document.forms[formName].fax.value != "") {
			document.forms[formName].countryDiallingFax.value = countryValue;
		} else {
			document.forms[formName].countryDiallingFax.value = '--';
		}
	}

	// set the copy for the example phone number
	if (countryValue == "215") {
		// Great Britain UK
		document.getElementById("exampleTelephone").innerHTML = "01865 474001";
		document.forms[formName].exampleTelephone.value = "01865 474001";
	} else {
		document.getElementById("exampleTelephone").innerHTML = "8001234567";
		document.forms[formName].exampleTelephone.value = "8001234567";
    }
	// call the ajax.js function to populate the states dropdown
	if (ajaxURL != false) {
		changeStateDisplay(ajaxURL, document.forms[formName]);
	}
}

// move the focus off the hidden fields to the specfied field instead (for tabbing issues)
function moveFocus(formName,fieldName) {
	document.forms[formName].elements[fieldName].focus();
}

//Check whether a field is empty or not
function checkEmpty(field,messageKey){
    var val =field.value;
    val = val.replace(/^\s*|\s*$/g,"");
   if(val.length==0){
     alert("Please enter "+messageKey);
     return false;
   }
   return true;
}


function formatZipCode(formName,fieldName) {
	var field = eval('document.forms[formName].' + fieldName);
	var newString = new String(field.value);
	var _indexGB=newString.indexOf('GB');
	var _indexJE=newString.indexOf('JE');
	var _indexGG=newString.indexOf('GG');
	var _indexIM=newString.indexOf('IM');

	if(_indexGB!=0 && _indexJE != 0 && _indexGG != 0 && _indexIM != 0 ) {
		field.value = newString.replace(/[^0-9A-Za-z-]/g, '');
	}
}


/******************************************************************************/
// My Account

// large accounts functions
function expand(elementName,prefix) {
	// expand a single item
	for (i = 1; i<100; i++) {
		if (i < 10) {
			padzeros = "0";
		} else {
			padzeros = "";
		}
		if (document.getElementById(prefix + 'service' + elementName + padzeros + i)) {
			if (document.all && (navigator.userAgent.indexOf("MSIE") != -1)) {
				document.getElementById(prefix + 'service' + elementName + padzeros + i).style.display = 'block';
			} else {
				document.getElementById(prefix + 'service' + elementName + padzeros + i).style.display = 'table-row';
			}
		} else {
			break;
		}
	}
	// only change the buttons if there is at least 1 child element
	if (document.getElementById(prefix + 'service' + elementName + "01")) {
		document.getElementById('expand' + elementName).style.display = 'none';
		document.getElementById('collapse' + elementName).style.display = 'block';
	}
}
function collapse(elementName,prefix) {
	// collapse a single item
	for (i = 1; i<100; i++) {
		if (i < 10) {
			padzeros = "0";
		} else {
			padzeros = "";
		}
		if (document.getElementById(prefix + 'service' + elementName + padzeros + i)) {
			document.getElementById(prefix + 'service' + elementName + padzeros + i).style.display = 'none';
		} else { break; }
	}
	// only change the buttons if there is at least 1 child element
	if (document.getElementById(prefix + 'service' + elementName + "01")) {
		document.getElementById('expand' + elementName).style.display = 'block';
		document.getElementById('collapse' + elementName).style.display = 'none';
	}
}
function expandAll(prefix) {
	//find all ids, loop thru and open them
	var trList = document.getElementsByTagName('tr');
	for (i = 0; i < trList.length; i++) {
		currentTR = trList.item(i).id;
		if (currentTR.indexOf(prefix+'service') != -1) {
			// open the item
			if (document.all && (navigator.userAgent.indexOf("MSIE") != -1)) {
				document.getElementById(currentTR).style.display = 'block';
			} else {
				document.getElementById(currentTR).style.display = 'table-row';
			}
			// get the parent id by replacing the service prefix...
			parentItem = currentTR.replace(prefix+'service','');
			// ...and removing the 2-digit service count from the end of the string
			parentItem = parentItem.substring(0,parentItem.length-2);
			// open the arrow associated with this item
			document.getElementById('expand' + parentItem).style.display = 'none';
			document.getElementById('collapse' + parentItem).style.display = 'block';
		}
	}
	// switch the link to "Collapse All"
	document.getElementById(prefix + 'expandAll').style.display = 'none';
	document.getElementById(prefix + 'collapseAll').style.display = 'block';
}
function collapseAll(prefix) {
	//find all ids, loop thru and close them
	var trList = document.getElementsByTagName('tr');
	for (i = 0; i < trList.length; i++) {
		currentTR = trList.item(i).id;
		if (currentTR.indexOf(prefix+'service') != -1) {
			// close the item
			document.getElementById(currentTR).style.display = 'none';
			// get the parent id by replacing the service prefix...
			parentItem = currentTR.replace(prefix+'service','');
			// ...and removing the 2-digit service count from the end of the string
			parentItem = parentItem.substring(0,parentItem.length-2);
			// close the arrow associated with this item
			document.getElementById('collapse' + parentItem).style.display = 'none';
			document.getElementById('expand' + parentItem).style.display = 'block';
		}
	}
	// switch the link to "Expand All"
	document.getElementById(prefix + 'expandAll').style.display = 'block';
	document.getElementById(prefix + 'collapseAll').style.display = 'none';
}

// delegated accounts
function swapTabs(tabType) {
	if (tabType == 'delegated') {
		// hide
		document.getElementById('accountMain').style.display = 'none';
		document.getElementById('accountMainTab').style.display = 'none';
		// show
		document.getElementById('accountDelegated').style.display = 'block';
		document.getElementById('accountDelegatedTab').style.display = 'block';
	} else {
		//hide
		document.getElementById('accountDelegated').style.display = 'none';
		document.getElementById('accountDelegatedTab').style.display = 'none';
		//show
		document.getElementById('accountMain').style.display = 'block';
		document.getElementById('accountMainTab').style.display = 'block';
	}
}



/******************************************************************************/
// Function for setting track IDs

function getCookie(NameOfCookie) {
if (document.cookie.length > 0) { 
	begin = document.cookie.indexOf(NameOfCookie+"="); 
		if (begin != -1) { 
			begin += NameOfCookie.length+1; 
			end = document.cookie.indexOf(";", begin);
				if (end == -1) end = document.cookie.length;
					return unescape(document.cookie.substring(begin, end));
				} 
		}
	return null; 
}

function setCookie(NameOfCookie, value, expiredays) {
	var ExpireDate = new Date ();
	ExpireDate.setTime(ExpireDate.getTime() + (expiredays * 24 * 3600 * 1000));
	document.cookie = NameOfCookie + "=" + unescape(value) + ((expiredays == null) ? "" : "; expires=" + ExpireDate.toGMTString());
}

function setRtCookie(NameOfCookie, value, expiredays) {
	var ExpireDate = new Date ();
	ExpireDate.setTime(ExpireDate.getTime() + (expiredays * 24 * 3600 * 1000));
	document.cookie = NameOfCookie + "=" + unescape(value) + ((expiredays == null) ? "" : "; expires=" + ExpireDate.toGMTString()) + ( ";path=/");
}

function delCookie (NameOfCookie) {
	if (getCookie(NameOfCookie)) {
		document.cookie = NameOfCookie + "=" +"; expires=Thu, 01-Jan-70 00:00:01 GMT";
	}
}

// Sets the track ID cookie or updates it if it is already set.
function setTRKID(id){
	if(getCookie('R') != null){
		delCookie ('R');
	}
	Stamp = new Date();
	year = Stamp.getYear();
	if (year < 2000) year = 1900 + year;
	month = Stamp.getMonth()+1;
	day = Stamp.getDate();
	hour = Stamp.getHours();
	minute = Stamp.getMinutes();
	second = Stamp.getSeconds();
	cVal='rcomCookieTS&'+year+'-'+month+'-'+day+'/'+hour+':'+minute+':'+second+'&trkid&'+id+'&';
	setCookie('R', cVal, 5);
}

function handleAMVATFieldContent(countryID) { 
	var vatCountries = [ 13, 20, 31, 53, 47, 55, 64, 69, 70, 76, 79, 91, 97, 99, 110, 116, 117, 124, 142, 162, 163, 167, 184, 183, 189, 195, 215 ];
	var vatCountryCodes = [ 'AT', 'BE', 'BG', 'CY', 'CG', 'DK', 'EE', 'FI', 'FR', 'DE', 'EL', 'HU', 'IE', 'IT', 'LV', 'LT', 'LU', 'MT', 'NL', 'PL', 'PT', 'RO', 'SI', 'SK', 'ES', 'SE', 'GB' ];				
	for(var i = 0; i < vatCountries.length; i++) {
		if(countryID == vatCountries[i]) {
			$("#VATNumberFields").css("display", "block");
				document.getElementById('VATNumberCountryCode').value=vatCountryCodes[i];
				return;
		}
	}
	document.getElementById('VATNumberCountryCode').value='--';
	$("#VATNumberFields").css("display", "none");
};
