/* common javsacript file */
// JavaScript Browser Sniffer
// Eric Krok, Andy King, Michel Plungjan Jan. 31, 2002
// see http://www.webreference.com/ for more information
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.

    var agt=navigator.userAgent.toLowerCase();
    var appVer = navigator.appVersion.toLowerCase();
    var is_minor = parseFloat(appVer);
    var is_major = parseInt(is_minor);

	var is_opera = (agt.indexOf("opera") != -1);

	var is_mac = (agt.indexOf("mac")!=-1);
    var iePos  = appVer.indexOf('msie');
    if (iePos !=-1) {
       if(is_mac) {
           var iePos = agt.indexOf('msie');
           is_minor = parseFloat(agt.substring(iePos+5,agt.indexOf(';',iePos)));
       }
       else is_minor = parseFloat(appVer.substring(iePos+5,appVer.indexOf(';',iePos)));
       is_major = parseInt(is_minor);
    }

    var is_konq = false;
    var kqPos   = agt.indexOf('konqueror');
    if (kqPos !=-1) {                 
       is_konq  = true;
       is_minor = parseFloat(agt.substring(kqPos+10,agt.indexOf(';',kqPos)));
       is_major = parseInt(is_minor);
    }                                 

    var is_getElementById   = (document.getElementById) ? "true" : "false";
    var is_getElementsByTagName = (document.getElementsByTagName) ? "true" : "false";
    var is_documentElement = (document.documentElement) ? "true" : "false";

    var is_safari = ((agt.indexOf('safari')!=-1)&&(agt.indexOf('mac')!=-1))?true:false;
    var is_khtml  = (is_safari || is_konq);

    var is_ie   = ((iePos!=-1) && (!is_opera) && (!is_khtml));
	var is_ie4   = (is_ie && is_major == 4);
    var is_ie5   = (is_ie && is_major == 5);
	var is_ie5up = (is_ie && is_minor >= 5);
	var is_ie5_5  = (is_ie && (agt.indexOf("msie 5.5") !=-1)); // 020128 new - abk
	var is_ie6   = (is_ie && is_major == 6);


/* PC-IE4 and Mac IE 5+ redirect */
	if (is_ie4 || (is_ie5up == true && is_mac == true)) {
/*		window.location="../fail/fail-browser.html";	*/
	}
/* Mac only stylesheet to address BOLD issues */
	if ((is_mac) || ((agt.indexOf('safari')!=-1) == true)) {
		document.write('<link rel="stylesheet" href="../css/mac.css" type="text/css" media="screen" />');
	}

//Trim functions for validation
function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}


/* function to have multiple events within the onload event */
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

function clearText(input) {
	if (input.defaultValue == input.value) {
		input.value = "";
	}
}

// Show Hide / Custom
function showContact(who) {
	var m = document.getElementsByTagName('div'), i;
	for (i = 0; i < m.length; ++i) {
		if (m[i].className == 'options') {
			m[i].style.display = 'none';
		}
	}
	document.getElementById(who).style.display = 'block';
}

// Form validation
var noPass;
var errors = 'Please Update the fields selected in red above\n\n';

function CheckBlank(fname, fdisplayname) {
	var fname = fname;
	var fdisplayname = fdisplayname;
	value = document.getElementById(fname).value;
	if ((value == '') || (value == "-Select-")) {
		errors = errors + fdisplayname + ' is required\n';
//		document.getElementById(fname).style.border = 'solid 2px #CC0000'; 
//		document.getElementById(fname).style.color = '#CC0000';
		noPass = 1;
	} else {
//		document.getElementById(fname).style.border = 'none'; 
//		document.getElementById(fname).style.color = '#2e4a8a'; 
		return true;
	}
}

function checkPhone(type, selection) {
	var phoneType = document.getElementById('preferred_contact_method').value;
	var phoneEntry = document.getElementById(type).value;

	if ((phoneType == selection) && (phoneEntry == '')) {
		errors = errors + 'Phone number entry must match preferred phone contact\n';
//		document.getElementById(type).style.border = 'solid 2px #CC0000'; 
//		document.getElementById(type).style.color = '#CC0000';
		noPass = 1;
	} else {
//		document.getElementById(type).style.border = 'none'; 
//		document.getElementById(type).style.color = '#2e4a8a'; 
		return true;
	}
}

function validateEmail(addr,man,db) {
	var invalidChars = '\/\'\\ ";:?!()[]\{\}^|';
	var atPos = addr.indexOf('@',0);
	var suffix = addr.substring(addr.lastIndexOf('.')+1);

	if ((addr == '') && (man == 1)) {
	   if ((db == 0)) alert('Email address is mandatory');
	   noPass = 1;
	   return false;
	}
	for (i = 0; i<invalidChars.length; i++) {
	   if (addr.indexOf(invalidChars.charAt(i),0) > -1) {
		  if (db == 0) alert('Email address contains invalid characters');
		  noPass = 1;
		  return false;
	   }
	}
	for (i = 0; i<addr.length; i++) {
	   if (addr.charCodeAt(i)>127) {
		  if (db == 0) alert("Email address contains non ascii characters.");
		  noPass = 1;
		  return false;
	   }
	}
	
	if (atPos == -1) {
	   if (db == 0) alert('Email address must contain an @');
	   noPass = 1;
	   return false;
	}
	if (atPos == 0) {
	   if (db == 0) alert('Email address must not start with @');
	   noPass = 1;
	   return false;
	}
	if (addr.indexOf('@', atPos + 1) > - 1) {
	   if (db == 0) alert('Email address must contain only one @');
	   noPass = 1;
	   return false;
	}
	if (addr.indexOf('.', atPos) == -1) {
	   if (db == 0) alert('Email address must contain a period in the domain name');
	   noPass = 1;
	   return false;
	}
	if (addr.indexOf('@.',0) != -1) {
	   if (db == 0) alert('Period must not immediately follow @ in email address');
	   noPass = 1;
	   return false;
	}
	if (addr.indexOf('.@',0) != -1){
	   if (db == 0) alert('Period must not immediately precede @ in email address');
	   noPass = 1;
	   return false;
	}
	if (addr.indexOf('..',0) != -1) {
	   if (db == 0) alert('Two periods must not be adjacent in email address');
	   noPass = 1;
	   return false;
	}
/*	if ((suffix.length > 3) || (suffix.length < 2)) {
	if ((suffix != 'com') && (suffix != 'net') && (suffix != 'org') && (suffix != 'edu') && (suffix != 'int') && (suffix != 'mil') && (suffix != 'gov') && (suffix != 'arpa') && (suffix != 'biz') && (suffix != 'aero') && (suffix != 'name') && (suffix != 'coop') && (suffix != 'info') && (suffix != 'pro') && (suffix != 'museum')) {
		if (db == 0) {
	   		alert('Invalid primary domain in email address');
		}
	   return false;
	}	*/
	return true;
}

function HasInquiryProductChecked(form)
{
	if (form.InquiryProducts_TIDirect.checked) return true;
	if (form.InquiryProducts_THL.checked) return true;
	if (form.InquiryProducts_COM.checked) return true;
	if (form.InquiryProducts_Rural.checked) return true;
	if (form.InquiryProducts_TMF.checked) return true;
	if (form.InquiryProducts_Other.checked) return true;
	return false;
}

function PopupProfile(lngFundID) {
  var strProps = 'top=10,left=10,scrollbars=yes,resizable=yes,toolbar=yes,menubar=no,width=770,height=460';
  window.open('http://www.tower.co.nz/Web_Custom/tnz/products/Web_View_Product.asp?Mode=Profile&ID=' + lngFundID, 'Profile', strProps);
}

function gotoPagePop(lngPageID)
{
	window.open('http://www.tower.co.nz/Web_Content.asp?PID=' + lngPageID, 'Popup', 'toolbar=no,location=no,directories=no,status=no,scrollbars=yes,resizable=no,copyhistory=no,width=770,height=400');
}

var i = 0;
var variable;

function getQueryVariable(variable) {
	var query = window.location.search.substring(1);
	
	if (query.search(variable) != -1) {
		
		var vars = query.split("&");
		
		while (i<vars.length) {
			var pair = vars[i].split("=");
			
			i = i + 1;
			if (pair[0] == variable) {
				return pair[1];
			} 
		} 
		
	} else {
		return "";
	}
}

function getSingleQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  } 
}


function GetVarExists(varname)
{
	var query = window.location.search.substring(1);
	
	if (query.search(variable) != -1) {
		return true;
	} else {
		return false;
	}
}

function QueryToFields()
{
	
	document.getElementById('fName').value = getQueryVariable('s_first_name');
	var lead_last_name = getQueryVariable('s_last_name');
	document.getElementById('lName').value = lead_last_name.replace(/%5bnot%20provided%5d/,'');
	document.getElementById('email').value = getQueryVariable('s_email');  
	document.getElementById('web_source').value=getQueryVariable('source'); 
}

function showhide(commentID) {
	if (document.getElementById(commentID).style.display == 'none' || document.getElementById(commentID).style.display == '') {
		document.getElementById(commentID).style.display = 'block';
	} else {
		if (document.getElementById(commentID).style.display == 'block') {
			document.getElementById(commentID).style.display = 'none';
		}
	}
}

function showError(error_id) {
	document.getElementById(error_id).style.display = 'block';
}


function hideError(error_id) {
	document.getElementById(error_id).style.display = 'none';
}


function validateFormWithProductInterest(form) {
	// Validate common form inputs first
	var isFormValid = validation(form);
	var isOneInterestChecked = false;
	
	if (document.getElementById('prod-Life') != null) {
		if (document.getElementById('prod-Life').checked == true) {
			hideError('error-product_interest');
			isOneInterestChecked = true;
		}
	}
	
	if (document.getElementById('prod-Trauma') != null) {
		if (document.getElementById('prod-Trauma').checked == true) {
			hideError('error-product_interest');
			isOneInterestChecked = true;
		}
	}
	
	if (document.getElementById('prod-Perma') != null) {
		if (document.getElementById('prod-Perma').checked == true) {
			hideError('error-product_interest');
			isOneInterestChecked = true;
		}
	}
	
	if (document.getElementById('prod-Income') != null) {
		if (document.getElementById('prod-Income').checked == true) {
			hideError('error-product_interest');
			isOneInterestChecked = true;
		}
	}
	
	if (document.getElementById('prod-Mortgage') != null) {
		if (document.getElementById('prod-Mortgage').checked == true) {
			hideError('error-product_interest');
			isOneInterestChecked = true;
		}
	}
	
	if (document.getElementById('prod-Children') != null) {
		if (document.getElementById('prod-Children').checked == true) {
			hideError('error-product_interest');
			isOneInterestChecked = true;
		}
	}	
	
	if (!isOneInterestChecked) {
		showError('error-product_interest');
		form.FirstName.focus();
	}
		
	if (isFormValid && isOneInterestChecked) {		
		return true;
	} else {
		return false;
	}
}


function validation(form) {

	var invalidForm = 0;

  	//Check for at least one product interest is checked for quotes.tower.co.nz
	try {
	  	if(!HasInquiryProductChecked(form)) {
			showError('error-winProductInterest');
			invalidForm = 1;
		} else {
			hideError('error-winProductInterest');
		}
	}
	catch(errors) {
	}
  
    try {
	    if(form.CurrentCustomerYes.checked == false && form.CurrentCustomerNo.checked == false) {
		    showError('error-existing');
		    invalidForm = 1;
	    } else {
		    hideError('error-existing');
	    }
	}
	catch(errors) {
	}

	try {
		if(form.Title.value == "") {
			showError('error-title');
			invalidForm = 1;
		} else {
			hideError('error-title');
		}
	}
	catch(err) {
	}

	try {
		if(trim(form.FirstName.value) == '') {
			showError('error-first_name');
			invalidForm = 1;
		} else {
			hideError('error-first_name');
		}
	}
	catch(err) {
	}
	
	try {
		if(trim(form.LastName.value) == '') {
			showError('error-surname');
			invalidForm = 1;
		} else {
			hideError('error-surname');
		}
	}
	catch(err) {
	}

	try {
		if(trim(form.Address_Suburb.value) == '') {
			showError('error-suburb');
			invalidForm = 1;
		} else {
			hideError('error-suburb');
		}
	}
	catch(err) {
	}
	
	try {
		if(trim(form.Address_City.value) == '') {
			showError('error-city');
			invalidForm = 1;
		} else {
			hideError('error-city');
		}
	}
	catch(err) {
	}

	try {
		if(form.Address_City.options[form.Address_City.selectedIndex].value == "") {
			showError('error-city');
			invalidForm = 1;
		} else {
			hideError('error-city');
		}
	}
	catch(err) {
	}

	try {
		//Check how did you hear about us
		if (document.getElementById('SourceMedia').selectedIndex == 0) {
			showError('error-howhear');
			invalidForm = 1;
		} else {
			hideError('error-howhear');
		}
	}
	catch(err) {
	}
	
	try {
		if(form.hiddenHearFrom.value == "") {
			showError('error-hearfrom');
			invalidForm = 1;
		} else {
			hideError('error-hearfrom');
		}
	}
	catch(err) {
	}

	try {
		if(trim(form.Email.value) == '') {
			showError('error-email');
			invalidForm = 1;
		} else {
			hideError('error-email');
		}
	}
	catch(err) {
	}

	try {
		if(trim(form.Email.value) != '') {
			if (!validateEmail(form.Email.value, 0, 1)) {
				showError('error-invalid-email');
				invalidForm = 1;
			} else {
				hideError('error-invalid-email');
			}
		} else {
			hideError('error-invalid-email');
		}
	}
	catch(err) {
	}

	try {
		if(trim(form.HomePhone.value) == '') {
			showError('error-phone');
			invalidForm = 1;	
		} else {
			hideError('error-phone');
		}
	}
	catch(err) {
	}
	
	//Check Contact Day
	try {
		if ((document.getElementById('PreferedContactDayWeekday').checked === false) && (document.getElementById('PreferedContactDayWeekend').checked == false)) {
			showError('error-contact_day');
			invalidForm = 1;
		} else {
			hideError('error-contact_day');
		}
	}
	catch(err) {
	}
	
	//Check Contact Time
	try {
		if ((document.getElementById('PreferedContactTimeMorning').checked === false) && (document.getElementById('PreferedContactTimeEvening').checked == false) && (document.getElementById('PreferedContactTimeAfternoon').checked == false)) {
			showError('error-contact_time');
			invalidForm = 1;
		} else {
			hideError('error-contact_time');
		}
	}
	catch(err) {
	}
			
	//Terms & Conditions
	try {
		if ((document.getElementById('TermsAndConditions').checked != true)) {
			showError('error-terms');
			invalidForm = 1;
		}
		else {
			hideError('error-terms');
		}
	}
	catch(err) {
	}
	
	if (invalidForm == 1) {
		return false;
	} else {
		return true;
	}
}

function toggleMe(container,obj) {
	if (obj.checked == true) {
		document.getElementById(container).style.display = 'block';
	} else {
		document.getElementById(container).style.display = 'none';
	}
}	