onBodyLoad = initForm;

function initForm(){
	f = document.forms[0]; // shortcut reference to order form

	prepop("Title", "ti", false);
	prepop("FName", "fn", true);
	prepop("LName", "ln", true);
	prepop("Address1", "a1", true);
	prepop("Address2", "a2", true);
	prepop("City", "ci", true);
	prepop("State", "st", false);
	prepop("Zip", "zi", false)
	prepop("Email", "em", false)
	
	if (f.ID_Type) f.ID_Type.value = getURLValue("ID_Type");
	if (f.Source) f.Source.value = getURLValue("Source");
	if (f.Segment_sourceKey) f.Segment_sourceKey.value = getURLValue("Segment_sourceKey");
	if((f.tcIdA) && (f.tcIdB) ) {
		f.tcIdA.value = getURLValue("v");
		f.tcIdB.value = getURLValue("tc");
	}
	if(f.destId) f.destId.value = getURLValue("destId");   
	if(f.foreign) f.foreign.value  = getURLValue("foreign"); 
	if (f.OSType) f.OSType.value = navigator.userAgent.toString().replace(/\;/g," ");
	if (f.BrowserType) f.BrowserType.value = navigator.appName.toString().replace(/\;/g," ");
}

function validateBillMe() {
	if(!ValidateLocals()) return false;
	if(!ValidateOrderInfo()) return false;
	if(!ValidateGiftOrderInfo()) return false;
	f.submit();
}

// retrieve the value from a pulldown menu
function getOption(pulldown){
	return pulldown.options[pulldown.options.selectedIndex].value;
}

// retrieve the text (label) from a pulldown menu
function getOptionText(pulldown){
	return pulldown.options[pulldown.options.selectedIndex].text;
}

// retrieve the value associated with a radio button group
function getRadio(radio){
	for (i=0; i<radio.length; i++){
		if (radio[i].checked) return radio[i].value;
	}
	return "";
}

// retrieve the value(s) associated with a check box (group)
function getCheck(check){
	if (check.length == undefined) return check.value;
	values = [];
	for (i=0; i<check.length; i++){
		if (check[i].checked) values[values.length] = check[i].value;
	}
	return values;
}

// parse a variable from the query string
function getURLValue(variable){
	queryString = document.location.search.substring(1);
	if (queryString == "") return "";
	pairs = queryString.split("&");
	for (i=0; i<pairs.length; i++){
		if (pairs[i].split("=")[0].toLowerCase() == variable.toLowerCase()) return unescape(pairs[i].split("=")[1]);
	}
	return "";
}

// write a query string variable to the page
function writeVar(varName){
	document.write(getURLValue(varName));
}


// prepop values in form
function prepop(field, value, caps){
	field = document.forms[0][field];
	if (field == undefined) return; // field not found in form? exit here!
	value = getURLValue(value).toLowerCase();
	if (value=="") return; //value not found in querystring? exit here!
	
	if (field.type == "radio" || field.type == "select-one"){ //radios or pulldowns
		for (i=0; i<field.length; i++){
			if (field[i].value.toLowerCase() == value && field.type == "radio") {
				field[i].checked = true;
				return;
			}else if (field[i].value.toLowerCase() == value && field.type == "select-one"){
				field.selectedIndex = [i];
				return
			}
		}
	}else field.value = caps?capitalize(value):value; // text field
}

function capitalize(string){
	// capitalizes all words in a string
	tmp = "";
	string = string.split(/\s+/); // split on any white space
	for (i=0; i<string.length; i++){
		tmp += ((i==0)?"":" ") + string[i].charAt(0).toUpperCase() + string[i].substring(1).toLowerCase();
	}
	return tmp;
}


function wrongPerson(){
	if (getURLValue("fn") == "") return;
	identity = capitalize(getURLValue('fn') + " " + getURLValue('ln'));
	document.write("This communication has been officially prepared for " + identity + ". ");
	document.write("<b>If you are not " + identity + ", <a href='"+ stripQueryString() + "'>please click here.</a></b>");
}

function stripQueryString(){
	//strips the querystring from personalized info while leaving other data
	excluded = "fn,ln,a1,a2,ci,st,zi,ti,em";
	queryString = document.location.search.substring(1);
	if (queryString == "") return document.location.href; // no querystring: return current URL
	else url = document.location.href.substr(0, document.location.href.indexOf("?")) + "?";
	pairs = queryString.split("&");
	for (i=0; i<pairs.length; i++){
		if (excluded.indexOf( pairs[i].split("=")[0].toLowerCase()) == -1 ) url += ((i==0)?"":"&") + pairs[i].split("=")[0] + "=" + pairs[i].split("=")[1];
	}
	return url;
}

function popup(url, w, h){	
	var left = (screen.width - w) / 2;
	var top = (screen.height - h) / 2;
	features = 'width='+w+',height='+h+',top='+top+',left='+left+',toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no';
	newwindow=window.open(url,'newwin',features);
	newwindow.window.focus();
}

function popupScroll(url, w, h){	
	var left = (screen.width - w) / 2;
	var top = (screen.height - h) / 2;
	features = 'width='+w+',height='+h+',top='+top+',left='+left+',toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes';
	newwindow=window.open(url,'newwin',features);
	newwindow.window.focus();
}
//////////////////////////////////////////////////////////////////////////////////////////
var counter = 0;
function check(box, duplicate){
	if (box.checked) counter++;
	else counter--;
	if (counter > 2){
		box.checked = false;
		counter--;
		alert ("You may order up to two magazines only.\nPlease review your selections.");
	}
	if (arguments.length == 2) duplicate.checked = box.checked;
}

/*****************************************************************************/

	function getImageOnly(imgPath)	{
		var img = parseInt(imgPath.lastIndexOf("/"))+1;
		return imgPath.substr(img);
	}

	function openit(sURL,w,h){
		if (urlStringarray[1]){
			sURL=sURL+"?"+urlStringarray[1];
		}else{
			urlStringarray[1]="No Query";
		}	
		newwindow=window.open(sURL,"newwin","scrollbars=no,toolbar=no,directories=no,menubar=no,resizable=yes,status=no,width="+w+",height="+h+"");
		newwindow.window.focus();
	}

	function openit2(sURL,w,h){
		newwindow=window.open(sURL,"nextwin","scrollbars=yes,toolbar=no,directories=no,menubar=no,resizable=yes,status=no,width="+w+",height="+h+"");
		newwindow.window.focus();
	}
	
	function ChangeIT(imgName,imgSrc){
		//alert(noclick);
		document.frmOrder[imgName].src=imgSrc;
	}	
	
	function go(){
		ChangeIT("load","http://a1708.g.akamai.net/7/1708/5303/456456/image.pch.com/opsimages/63fdb558-54a9-4c3a-a4eb-de52eee2fcbe/aq/06/35-52/bireport.gif");
	}	
	
/*
	Chris Donnan
	2003 09 24

	BillMe and Gifting support
	This file is a template for local.js includes for billme pages

	Requires library:
		email.js
*/

	// set this flag to true if your page will support gifts, otherwise - false
	// if this is set to true, we will attempt to validate 
	var IS_GIFT_PAGE = true

	/*
		ValidateLocals():

		insert any added code needed on a page
		by page basis in this section here
		return true if your stuff is valid and OK to submit, 
		return false if your stuff is invalid and we should not allow submit
	*/
	function ValidateLocals() //bool
	{
		/*
			insert any added code needed on a page
			by page basis in this section here
		*/
		if (counter==0){
			alert("This is a gift order only form. Please order any item on this page to continue.")
			window.scrollTo(0,335);
			return false;
		}
		return true
	}

	/*
		newCheck()
		called when a page is submitted
	*/
	function newCheck()//void
	{
		// validates localized page-by-page code
		if(!ValidateLocals())
		{
		      return
		}

		//if we allow gifts
		if(IS_GIFT_PAGE)
		{
			if(!ValidateGiftOrderInfo())
			{
				window.scrollTo(0,2350)
				return
			}				       
		}

		// validates bill me order
		if(!ValidateOrderInfo())
		{
			window.scrollTo(0,2774);
			return
		}

		document.frmOrder.submit();
	}


	/*
		ValidateGiftOrderInfo() 
		called to validate the information in a gift bill me order
	*/
	function ValidateGiftOrderInfo() //bool
	{
		document.frmOrder.GiftOrder.value = 1;
		var titleGift = document.frmOrder.TitleGift.selectedIndex
		var fnameGift = Trim(document.frmOrder.FNameGift.value)
		document.frmOrder.FNameGift.value = fnameGift
		var lnameGift = Trim(document.frmOrder.LNameGift.value)
		document.frmOrder.LNameGift.value = lnameGift
		var address1Gift = Trim(document.frmOrder.Address1Gift.value)
		document.frmOrder.Address1Gift.value = address1Gift
		var address2Gift = Trim(document.frmOrder.Address2Gift.value)
		document.frmOrder.Address2Gift.value = address2Gift
		var cityGift = Trim(document.frmOrder.CityGift.value)
		document.frmOrder.CityGift.value = cityGift 
		var stateGift = document.frmOrder.StateGift.selectedIndex
		var zipGift = Trim(document.frmOrder.ZipGift.value)
		document.frmOrder.ZipGift.value = zipGift
		
		//var emailGift = Trim(document.frmOrder.EmailGift.value)
		//document.frmOrder.EmailGift.value = emailGift 

		if(titleGift==0)
		{
			alert("Please enter a valid Giftee Title")
			document.frmOrder.TitleGift.focus()
			return false
		}
		if(fnameGift=="" || (!strRegEx_FName.test(fnameGift)))
		{
			alert("Please enter a valid Giftee First Name")
			document.frmOrder.FNameGift.focus()
			return false
		}
		if(lnameGift==""|| (!strRegEx_LName.test(lnameGift)))
		{
			alert("Please enter a valid Giftee Last Name")
			document.frmOrder.LNameGift.focus()
			return false
		}

		if(address1Gift==""|| (!strRegEx_Address1.test(address1Gift)))
		{
			alert("Please enter a valid Giftee Address 1")
			document.frmOrder.Address1Gift.focus()
			return false
		}
		if(address2Gift !="" && (!strRegEx_Address2.test(address2Gift)))
		{
			alert("Please enter a valid Giftee Address 2")
			document.frmOrder.Address2Gift.focus()
			return false
		}

		if(cityGift==""|| (!strRegEx_City.test(cityGift)))
		{
			alert("Please enter a valid Giftee City")
			document.frmOrder.CityGift.focus()
			return false
		}
		if(stateGift==0)
		{
			alert("Please enter a valid Giftee State")
			document.frmOrder.StateGift.focus()
			return false
		}
		if(zipGift==""|| (!strRegEx_Zip.test(zipGift)))
		{
			alert("Please enter a valid Giftee Zip")
			document.frmOrder.ZipGift.focus()
			return false
		}
		
		/*
		if(emailGift!="" && (!strRegEx_Email.test(emailGift)))
		{
			alert("Please enter a valid Giftee Email")
			document.frmOrder.EmailGift.focus()
			return false
		}
		*/
		
		return true
	}

	/*
		ValidateOrderInfo() 
		called to validate the information in a standard bill me order
	*/
	function ValidateOrderInfo() //bool
	{

		var title = document.frmOrder.Title.selectedIndex
		var fname = Trim(document.frmOrder.FName.value)
		document.frmOrder.FName.value = fname
		var lname = Trim(document.frmOrder.LName.value)
	        document.frmOrder.LName.value = lname
		var email = Trim(document.frmOrder.Email.value)
		document.frmOrder.Email.value = email
		var address1 = Trim(document.frmOrder.Address1.value)
		document.frmOrder.Address1.value = address1
		var address2 = Trim(document.frmOrder.Address2.value)
		document.frmOrder.Address2.value = address2
		var city = Trim(document.frmOrder.City.value)
		document.frmOrder.City.value = city
		var state = document.frmOrder.State.selectedIndex
		var zip = Trim(document.frmOrder.Zip.value)
		document.frmOrder.Zip.value =  zip

		if(title==0)
		{
			alert("Please enter a valid Title")
			document.frmOrder.Title.focus()
			return false
		}
		if(fname=="" || !strRegEx_FName.test(fname))
		{
			alert("Please enter a valid First Name")
			document.frmOrder.FName.focus()
			return false
		}
		if(lname=="" || (!strRegEx_LName.test(lname)))
		{
			alert("Please enter a valid Last Name")
			document.frmOrder.LName.focus()
			return false
		}

		if(address1==""|| (!strRegEx_Address1.test(address1)))
		{
			alert("Please enter a valid Address 1")
			document.frmOrder.Address1.focus()
			return false
		}
		if(address2 !="" && (!strRegEx_Address2.test(address2)))
		{
			alert("Please enter a valid Address 2")
			document.frmOrder.Address2.focus()
			return false
		}

		if(city==""|| (!strRegEx_City.test(city)))
		{
			alert("Please enter a valid City")
			document.frmOrder.City.focus()
			return false
		}
		if(state==0)
		{
			alert("Please enter a valid State")
			document.frmOrder.State.focus()
			return false
		}
		if(zip==""|| (!strRegEx_Zip.test(zip)))
		{
			alert("Please enter a valid Zip")
			document.frmOrder.Zip.focus()
			return false
		}

 		if(email=="" || (!strRegEx_Email.test(email)))
		{
			alert("Please enter a valid Email")
			document.frmOrder.Email.focus()
			return false
		}
		
		if (!checkEmail(document.frmOrder.Email,"Email")) {
			return false;
		}	
		return true
	}


	/*
		string editing function that trims any leading and trailing whitespace
	*/
	function Trim(str)//string	
	{
		return RTrim(LTrim(str));
	}

	/*
		string editing function that trims any leading whitespace
	*/
	function LTrim(str)//string	
	{
		var whitespace = new String(" \t\n\r");
		var s = new String(str);
		if (whitespace.indexOf(s.charAt(0)) != -1) {
		var j=0, i = s.length;
		while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
			j++;
		s = s.substring(j, i);
		}
		return s;
	}

	/*
		string editing function that trims any trailing whitespace
	*/
	function RTrim(str)//string	
	{
		var whitespace = new String(" \t\n\r");
		var s = new String(str);
		if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
		var i = s.length - 1;       // Get length of string
		while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
			i--;
		s = s.substring(0, i+1);
		}
		return s;
	}



//********************************************************************************//

function wrongPerson(){
	var winURL = window.location.toString();
	var stopat = winURL.indexOf("&fn");
	var getNew = winURL.substring(winURL, stopat);

	window.location = getNew;
}
//Put this part in the .js file//
//*************************************************************************************************************************************************

var WM_startTagFix = '</';
var msie_windows = 0;
if ((navigator.userAgent.indexOf('MSIE') != -1) && (navigator.userAgent.indexOf('Win') != -1)){
  msie_windows = 1;
  document.writeln('<script language="VBscript">');
  document.writeln('\'This will scan for plugins for all versions of Internet Explorer that have a VBscript engine version 2 or greater.');
  document.writeln('\'This includes all versions of IE4 and beyond and some versions of IE 3.');
  document.writeln('Dim WM_detect_through_vb');
  document.writeln('WM_detect_through_vb = 0');
  document.writeln('If ScriptEngineMajorVersion >= 2 then');
  document.writeln('  WM_detect_through_vb = 1');
  document.writeln('End If');
  document.writeln('Function WM_activeXDetect(activeXname)');
  document.writeln('  on error resume next');
  document.writeln('  If ScriptEngineMajorVersion >= 2 then');
  document.writeln('     WM_activeXDetect = False');
  document.writeln('     WM_activeXDetect = IsObject(CreateObject(activeXname))');
  document.writeln('     If (err) then');
  document.writeln('        WM_activeXDetect = False');
  document.writeln('     End If');
  document.writeln('   Else');
  document.writeln('     WM_activeXDetect = False');
  document.writeln('   End If');
  document.writeln('End Function');
  document.writeln(WM_startTagFix+'script>');
}

function WM_pluginDetect(plugindescription, pluginxtension, pluginmime, activeXname){

  //This script block will test all user agents that have a real plug-in array
  //(i.e. Netscape) and set the variables, otherwise it directs the routine
  // to WM_activeXDetect to detect the activeX control.

  

  // First define some variables
  var i,plugin_undetectable=0,detected=0, daPlugin=new Object();


  // Then we check to see if it's an MSIE browser that you can actually

  // check for the plugin in question. 

  if (msie_windows && WM_detect_through_vb){
      plugin_undetectable = 0;
  } else {
      plugin_undetectable = 1;
  }



  // If it has a real plugins or mimetypes array, we look there for the plugin first

  if(navigator.plugins) {
      numPlugins = navigator.plugins.length;
      if (numPlugins > 1) {
	  if (navigator.mimeTypes && navigator.mimeTypes[pluginmime] && navigator.mimeTypes[pluginmime].enabledPlugin && (navigator.mimeTypes[pluginmime].suffixes.indexOf(pluginxtension) != -1)) { // seems like we have it, let's just make sure and check the version (if specified)
	      if ((navigator.appName == 'Netscape') && (navigator.appVersion.indexOf('4.0') != -1)) { // stupid, stupid Netscape can't handle the references to navigator.plugins by number, sooo...
		  for(i in navigator.plugins) {
		      if ((navigator.plugins[i].description.indexOf(plugindescription) != -1) || (i.indexOf(plugindescription) != -1)) { // some versions of quicktime have no description. feh!
			  detected=1;
			  break;
		      }
		  }
	      } else {
		  for (i = 0; i < numPlugins; i++) {
		      daPlugin = navigator.plugins[i];
		      if ((daPlugin.description.indexOf(plugindescription) != -1) || (daPlugin.name.indexOf(plugindescription) != -1)) {
			  detected=1;
			  break;
		      }
		  }
	      }

	      // Mac weirdness
      if (navigator.mimeTypes[pluginmime] == null) {
		  detected = 0;
	      }
	  }
	  return detected;
      } else if((msie_windows == 1) && !plugin_undetectable){
	  return WM_activeXDetect(activeXname);
      } else { 		
	  return 0;
      }
  } else {
      return 0;
  }
}


// this next function just makes it easy to detect the common plugins

function WM_easyDetect(whichPlugin) {

    // this function just makes it easy to do basic plug-in detection without
    // knowing all the mimetypes and activeX names and such

    var isItThere = 0;
    if( (whichPlugin == 'flash') || (whichPlugin == 'Flash') ) {
	isItThere = WM_pluginDetect('Flash', 'swf', 'application/x-shockwave-flash', 'ShockwaveFlash.ShockwaveFlash');
    } else if( (whichPlugin == 'director') || (whichPlugin == 'Director') ) {
	isItThere = WM_pluginDetect('Shockwave', 'dcr', 'application/x-director', 'SWCtl.SWCtl.1');
    } else if( (whichPlugin == 'quicktime') || (whichPlugin == 'Quicktime') || (whichPlugin == 'QuickTime') ) {
	isItThere = WM_pluginDetect('QuickTime', 'mov', 'video/quicktime', '');
    } else if( (whichPlugin == 'realaudio') || (whichPlugin == 'Realaudio') || (whichPlugin == 'RealAudio') ) {
	isItThere = (WM_pluginDetect('RealPlayer', 'rpm', 'audio/x-pn-realaudio-plugin', 'RealPlayer.RealPlayer(tm) ActiveX Control (32-bit)')) || (WM_pluginDetect('RealPlayer', 'rpm', 'audio/x-pn-realaudio-plugin','rmocx.RealPlayer G2 Control')) || (WM_pluginDetect('RealPlayer', 'rpm', 'audio/x-pn-realaudio-plugin','RealPlayer.RealPlayer(tm) ActiveX Control (32-bit)')) || (WM_pluginDetect('RealPlayer', 'rpm', 'audio/x-pn-realaudio-plugin','RealVideo.RealVideo(tm) ActiveX Control (32-bit)'))
    } else {
	alert('You need to tell me which plug-in to look for, like so:\n\n' + '          WM_easyDetect(\'flash\')\n\n' + '          WM_easyDetect(\'director\')\n\n' + '          WM_easyDetect(\'quicktime\')\n\n' + '          WM_easyDetect(\'realaudio\')');
    }
    return isItThere;
}

//*********************************************************************************************************************************