/*##############################################################
# Programmer..: dev team

# Name........: global_js_functions.js
# Alias.......: the global javascript file
# Description.:
#
# Usage.......: include and use
# Called by...:
# Calls:......:
# Parameters..:
#
# Tables......:
# Returns.....:
# Example.....:
#
# $Revision: 6401 $
# $Date: 2010-03-30 15:45:25 -0400 (Tue, 30 Mar 2010) $
# $Author: robert $
#
#Copyright (c) 2004-8 Active Response, LLC. All rights reserved.
###############################################################*/

// WE HAD ISSUES IT APPEARS WITH sup_submit 
var ie4= document.all && navigator.userAgent.indexOf("Opera")==-1;
var ns6= document.getElementById && navigator.userAgent.indexOf("Opera")==-1;
var ns4= document.layers;
var advance=1;
var xpc = document.location.search.match(/xpc=1(&|$)/)?1:0;
var ignoreForm=0;
var forceProcess = false;
var lp_title = ""; //need to declare to avoid non-fatal error 9/12/05
var lp_type = ""; //ditto, other value is "multiprize" that should be set in layout for lp
var lp_brand = ""; //ditto
var all_good = -2;
var dropdown_status = 0;
var nocache=0;
var currently_running = '';
var iframe_loaded = 0;
var daPundr = 0;
var send_errors = 1;
var rt_optin=0;
var show_next_optin=0;

function showdebug(mssg,user){
   if(nocache==user) alert (mssg);
}

function report_error(err){
   if(nocache!='0'){ alert("jscript error in function "+currently_running+":\n"+err);}
   else{
      if(!send_errors) return true;
      var a = new XMLHttpRequest();
      var AMPID = ampid.split(/\|/);
      var AMPID_breakdown = "";
      for(var key in AMPID){
         var PAIR = AMPID[key].split(/-/);
         AMPID_breakdown += "&"+PAIR[0]+'='+escape(PAIR[1]);
      }
      AMPID_breakdown += "&stack_trace="+escape(stacktrace());
      var var_arr = new Array();
      for(var i = 0;i<document.forms.ms.length;i++){
         try{
               var_arr[var_arr.length] = document.forms.ms[i].name+": "+document.forms.ms[i].value;
         }
         catch(err){
            var_arr[var_arr.length] = "could not get info for form element "+i;
         }
      }
      var form_vars = var_arr.join(' || ');
      var prize_string= "&pzid="+escape(get_pzid_lp(1));
      var url_string = "&url="+escape(document.location);
      var dpo_string = "";
      if(document.forms.ms.dpo) dpo_string='&dpo='+document.forms.ms.dpo.value;
      var get_string = '/cust/ajax/report_error.php?error='+escape(err)+'&cr='+escape(currently_running)+'&fv='+escape(form_vars)+'&ua='+escape(navigator.userAgent)+AMPID_breakdown+prize_string+url_string+dpo_string;
      a.open("GET",get_string,true);
      a.send(null);
   }
}
onerror = report_error;
function funcname(f) {
    var s = f.toString().match(/function (\w*)/)[1];
    if ((s == null) || (s.length == 0)) return "anonymous";
    return s;
}

function stacktrace() {
    var s = "";  // This is the string we'll return.
    for(var a = arguments.caller; a != null; a = a.caller) {
        s += funcname(a.callee) + " <- ";
        if (a.caller == a) break;
    }
    return s;
}

function $F(form,name) {
   if(form[name]){
      if(form[name].length){
         for(var z=0;z<form[name].length;z++){
            if(form[name][z].disabled) {return false;}
         }
         if(form[name].disabled){return false;}
         return form[name];
      }else{
         if(!form[name].disabled){return form[name];}
         else {return false;}
      }
   }else if(form[name+'[]']){
      if(!form[name+'[]'].disabled) {return form[name+'[]'];}
      else {return false;}
   }
   return false;
}

function need_to_validate(element){
   var validate = true;
   if(element.length && !element.type) {
      for(var i = 0; i < element.length; i++) {
         if(element[i].getAttribute){
            if(element[i].getAttribute('bypass_validation')) validate = false; 
         }else if (element[i].attributes){
            if(element[i].attributes.bypass_validation) validate = false; 
         }else if(element[i].bypass_validation){
            validate = false;
         }
      }
   } else {
      if(element.getAttribute){
         if(element.getAttribute('bypass_validation')) validate = false; 
      }else if (element.attributes){
         if(element.attributes.bypass_validation) validate = false; 
      }else if(element.bypass_validation){
         validate = false;
      }
   }
   return validate;
}

function standard_validation(element,qid,type,reg,name){
     switch(type) {
         case 'text':
         case 'textarea':
         case 'password':
            if(!in_array(q_done,qid)){
               if(!(reg.test(element.value))) { 
                  validation_error[validation_error.length] = "Invalid Format for \""+name+"\"\n";
               }
               q_done[q_done.length] = qid;
            }
            break;
         case 'radio':
            var this_validation_error = 0;
            if(!in_array(q_done,qid)){
                this_validation_error = 1;
                if(!(element.length)){
                  if(element.checked){ this_validation_error=0; }
                }else{
                  for(var i=0; i<element.length; i++){
                     if(element[i].checked){ this_validation_error=0; }
                  }
               }
               if(this_validation_error){ 
                 validation_error[validation_error.length] = "Please answer \""+name+"\"\n"; 
               }
               q_done[q_done.length] = qid;
            }
            break;
         case 'checkbox':
            var this_validation_error=0;
            if(!in_array(q_done,qid)){
               this_validation_error=1;
               if(element.length==null) {
                  if(element.checked){ this_validation_error=0; } 
               }else{
                  for(var i=0; i<element.length; i++){
                     if(element[i].checked){ this_validation_error=0; }
                  }
               }
               if(this_validation_error) { 
                 validation_error[validation_error.length] = "Please answer \""+name+"\"\n";
               }
               q_done[q_done.length] = qid;
            }
            break;
         case 'select':
         case 'select-one':
         case 'select-multiple':
            if(!element.multiple) {
               var this_validation_error=0;
               if(!in_array(q_done,qid)){
                  this_validation_error=1;
                  if(element.type=='hidden' || element.selectedIndex>=1){ this_validation_error=0; }
                  if(this_validation_error){
                     validation_error[validation_error.length] = "Please answer \""+name+"\"\n";
                  }
                  q_done[q_done.length] = qid;
               }
            } else {
               var this_validation_error=0;
               if(!in_array(q_done,qid)){
                  this_validation_error=1;
                  if(element.type=='hidden' || element.selectedIndex>=1){ this_validation_error=0; }
                  if(this_validation_error){
                     validation_error[validation_error.length] = "Please answer \""+name+"\"\n";
                  }
                  q_done[q_done.length] = qid;
               }
            }
            break;
         default:
            break;
      }
}



function showContent(num,content,adv){
   if(content=='' && adv==1) ignoreForm=1;
   if(ie4){ showContentObj=document.all['div'+num]; }
   if(ns6){ showContentObj=document.getElementById("div"+num); }
   if(ie4||ns6){
      if(showContentObj.innerHTML!=content){
         showContentObj.innerHTML=content;
         if(content!=""){
            window['res'+num] = content.match(/q\d+/g);
         }else{
	        if(window['res'+num]){
             for(l=0;l<window['res'+num].length;l++){
	             document.ms[window['res'+num][l]] = false;
             }
	        }
         }
      }else{
         showContentObj.innerHTML="";
      }
   }
   if(ns4){
      document['layer'+num].document.write(content);
      document['layer'+num].document.close();
   }

   if(validate(document.ms)){advance=adv;}
   else {advance = 0;}
}
function showContent2(div,dir,adv){
   var f = document.forms[0];
   daDiv = document.getElementById('drop'+div);
   if(daDiv.style.display=='block'  && adv==1) ignoreForm=1;
   if(dir=='down'){
      daDiv.style.display = 'block';
      dropdown_status = 1;
   }
   window['res'+div] = daDiv.innerHTML.match(/q\d+/g);
	if(window['res'+div]){
       for(l=0;l<window['res'+div].length;l++){
         var T = window['res'+div][l].match(/q\d+/);
         if(T)var elem = T[0];
         if(f[elem]){
            if(f[elem].length){
               for(var z=0;z<f[elem].length;z++){
                  var sub_elem = f[elem][z];
                  if(sub_elem){
                     if(sub_elem.value){
                        sub_elem.disabled = dir=='down'?false:true;
                     }
                  }
               }
            }
            f[elem].disabled = dir=='down'?false:true; //so values on hidden don't get passed
         }
       }
	}
   if(dir=='up'){
      daDiv.style.display = 'none';
      dropdown_status = 0;
   }
   if(validate(document.ms)){advance=adv;}
   else {advance = 0;}
}

function setJSCookie(cname,cvalue,domain) {
   var nextWeek = new Date();
   nextWeek.setMinutes(nextWeek.getUTCMinutes() + 10080);
   document.cookie = cname+"="+cvalue + "; path=/; expires=" + nextWeek.toGMTString() + "; domain=" + domain;
}



tt_set = 0;
tt_try=0;
function setTTIMG(ttid,uk,pid,src,domain,sc) {
   tt_set=0;
   tt_try=0;
   var ssl = ""; //enhance to determine secure status
   var imgtag = document.createElement('img');
   var imgsrc = "http" + ssl + "://" + domain + "/ttset.php?ttid=" + ttid + "&pid=" + pid + "&src=" + src + "&uk=" + uk + sc;
   imgtag.src = imgsrc;
   imgtag.style.border='0px';
   imgtag.style.width='1px';
   imgtag.style.height='1px';
   imgtag.style.position='absolute';
   //document.body.appendChild(imgtag);
   document.getElementById('divTTIMG').appendChild(imgtag);
   tt_set=1;
}


function tracktagListen(tagid){
   var allcookies = document.cookie;
   if(allcookies.indexOf("msadv_"+tagid)!=-1) {document.cookie = "msadv_"+tagid+"=; expires=Fri, 02-Jan-1970 00:00:00 GMT"; top.document.forms['ms'].submit();}
}

function autoAdvance(){
   xpc=1;
   if(advance && (validate(document.ms) || ignoreForm==1)){
   //NOTE ON BELOW: can override the ?bcv token setup (which disables form processing by default)
   //by setting forceProcess=1 somewhere in form
    if(ignoreForm==1 && !forceProcess)document.ms.action = document.ms.action + "?bcv";
    show_spinner();
    document.ms.submit();
   }
   advance=1;
   ignoreForm=0;
}

function xpop(url,xname,hght,wdth){

  if(!xpc){
     if(document.forms[0].xps && document.forms[0].xps.value==1){return true;}
     var xp = window.open(url,'xpop'+xname,'width='+wdth+',height='+hght+',resizable=yes,menubar=yes,scrollbars=yes,screenX=500,screenY=190,left=500,top=190'); 
     return true;
  }else{
	return true;
  }	
}

function show_spinner(){
	if(document.getElementById){
	 if(showSpinner=='yes'){
   		subspin = document.getElementById('spinner');
  		   tbox = document.getElementById('transbox');
         if(document.all){
          finalpos = document.body.scrollTop + (document.body.clientHeight/3) - 50; 
 	  finalHeight = document.body.scrollTop + document.body.clientHeight;
         }else{
          finalpos = window.pageYOffset + (window.innerHeight/3)-10;
  	       finalHeight = window.pageYOffset + window.innerHeight;
         }
         if(subspin){
					subspin.style.top = finalpos + "px";
 					subspin.style.display='block';
         }
			if(tbox){
				tbox.style.height= finalHeight + 'px';
         	tbox.style.display='block';
			}
   	 }
	}
} 

function hide_spinner(){
	if(document.getElementById){
      	   subspin = document.getElementById('spinner');
           tbox = document.getElementById('transbox');
  	   if(subspin) subspin.style.display='none';
  	   if(tbox){
			tbox.style.display='none';
      	tbox.style.height='100px';
		}
	}
}

function getMouseXY(e) {
	if(document.getElementById){
		var posx = 0;
		var posy = 0;
		if (!e) var e = window.event;
		if (e.pageX || e.pageY){
			posx = e.pageX;
			posy = e.pageY;
		}else if (e.clientX || e.clientY){
			posx = e.clientX + document.body.scrollLeft;
			posy = e.clientY + document.body.scrollTop;
		}
  		subspin = document.getElementById('spinner')
  		finalpos = posy;  
  		if(subspin) subspin.style.top = (posy -5) + "px";
  		if(subspin) subspin.style.left = (posx + 10) + "px";
	}
  return true;
}
//moving dots script
direction = 1;
function do_dots(loop){
    var txt="";
    if(loop==limit) direction = -1;
    if(loop==0) direction = 1;
    for(k=0;k<limit+1;k++){
        if(k==loop){
            txt += "<span style='font-size:30px;font-weight:bold;color:#467bb8;'>.</span>";
        }else if((direction==1 && k==(loop-1)) || (direction==-1 && k==(loop+1))){
			   txt += "<span style='font-size:30px;font-weight:bold;color:#B4B2B8;'>.</span>";
		  }else if((direction==1 && k==(loop-2)) || (direction==-1 && k==(loop+2))){
			   txt += "<span style='font-size:30px;font-weight:bold;color:#CAC7CE;'>.</span>";
		  }else{
            txt +="&nbsp;";
        }
    }
    t.innerHTML = txt;
    loop = loop + direction;
    setTimeout('do_dots('+loop+')',speed);
}
/*************
pops the info window on cpas
*************/
times = 0;
pagenum = 1; //gets changed per cpa wall
function cpa_pop(link,offer,pbk,pzk,sk,sbw){
  var a = window.open(link,'_blank','toolbar=0,location=0,directories=0,status=1,menubar=1,scrollbars=1,resizable=1,width=800,height=800,top=100,left=50');
  if(!sbw) { //if sbw (suppress buddy window) isn't set
     var b = window.open("cpa_help2.php?cid="+offer+"&pbk="+pbk+"&pzk="+pzk+"&sk="+sk,'_blank2','toolbar=0,location=0,directories=0,status=1,menubar=0,scrollbars=1,resiable=1,width=300,height=350,top=50,left=10');
  }
  if(times<2 && !sbw){
			 times++;
			 if(b) b.focus();
  }
  var c = new XMLHttpRequest();
  var sesp = document.forms.ms.sesp.value;
  var location = '/cust/ajax/getresult.php?qk=udoW3&sesp='+sesp+'&arg1='+pagenum+'&arg2='+offer;
  c.open("GET",location,true);
  c.send('');
}

default_service_hook='';
function set_hook(hook){ //used in quick_popval below
	if(default_service_hook == '')
		default_service_hook = 'arg';
		
	if(!hook) hook = default_service_hook;
	if(frames['searchIFrame'].document.search.hook) frames['searchIFrame'].document.search.hook.value = hook;
}
function set_action(act){
   daFrame = frames['searchIFrame'];
	if(frames['searchIFrame'].document.search.act) frames['searchIFrame'].document.search.act.value = act;
}
suppressed = 0;
function suppress_submit(){
	//if (frames['searchIFrame'].document.search.submit_parent) 
	frames['searchIFrame'].document.search.submit_parent.value = "0";
	suppressed = 1;
}

/***********************************************************************
supporting functions for the multiple-call popval logic
************************************************************************/
function trim(value) {
   if(!value || !value.length) return false; //needed to be added b/c/ sometimes passed empty or undefined
   var temp = value;
   var obj = /^(\s*)([\W\w]*)(\b\s*$)/m;
   if (obj.test(temp)) { temp = temp.replace(obj, '$2'); }
   var obj = / +/g;
   temp = temp.replace(obj, " ");
   if (temp == " ") { temp = ""; }
   return temp;
}

function get_all_popval_objects(){
	var inp = document.forms[0];
	var resret = new Array();
	for (var j=0;j<inp.length;j++){
	if(inp[j]){
		//alert(inp[j].name);
			if(inp[j].onclick){
		//		alert('found onclick');
				if(parse_call(inp[j].onclick)) resret[j] =  new Array(trim(parse_call(inp[j].onclick)),trim(inp[j].name));
			}else if(inp[j].onchange){
				if(parse_call(inp[j].onchange)) resret[j] = new Array(trim(parse_call(inp[j].onchange)),trim(inp[j].name));
			}else if (inp[j].onsubmit){
				if(parse_call(inp[j].onsubmit)) resret[j] = new Array(trim(parse_call(inp[j].onsubmit)),trim(inp[j].name));
			}else if (inp[j].href){
				resret[j] = new Array(trim(parse_call(inp[j].href)),trim(inp[j].name));
			}
		}
	}
	//now do links, j.i.c
	for(z=0;z<document.links.length;z++){
		daLink = document.links[z];
		call = daLink.href;
		//alert(call);
		if(parse_call(call)) resret[j] = new Array(trim(parse_call(call)),trim(daLink.name));
		//else alert ('parse call failed');
		
	}
	
	if(resret.length > 0){
		return resret;
	}else{
		return false;
	}

}
function parse_call(call,getAll){
		var theCall = call.toString();
		//alert ('the call: '+theCall);
		if(theCall.indexOf("{") > 0){
			theCall = theCall.substring(theCall.indexOf("{") + 3,theCall.indexOf("}"));
		}
		theCall = theCall.replace(/javascript:/,'');
		//alert ('the call 2: '+theCall);
		var theCalls = Array();
		var returnedCalls = "";
		var rl = 0;
		theCalls = theCall.split(/;/);	
		for (var k=0;k<theCalls.length;k++){
			currentCall = theCalls[k];
			//alert ('current call: '+ currentCall);
			if(currentCall.length<5 && !getAll)return false;
         if(currentCall.match(/quick_popval/) || currentCall.match(/popval *\(/)){
				if(getAll){
					returnedCalls += (returnedCalls==""?"":";")+currentCall;
					rl++;
				}else{
				toreturn =  trim(currentCall);
				//alert ('to return '+toreturn);
				return toreturn;
				}
			}
		}
		if(getAll) return returnedCalls;
		return false;
}
function parse_mode(call){
	 res = call[0].substring(call[0].indexOf("("));
	 res = res.replace(/"/g,"");
	 res = res.replace(/'/g,"");
	 res = res.substring(res.indexOf("(")+1,res.indexOf(","));
	 return res;
}
function get_calling_name(mode){
      var DADOM = get_all_popval_objects();
      var DOM = new Array();
      var dl = 0;
      //clean it up
      for(var h=0;h<DADOM.length;h++){
         call = DADOM[h];
         if (call){ DOM[dl] = call; dl++;}
      }
      //loop through DOM and see where the fist call matches the current mode
      for(var x = 0;x<DOM.length;x++){
         var dadom = DOM[x];
         var damode = parse_mode(dadom);
         if (damode == mode){
				//alert ('got onei '+dadom[1].length);
				return (dadom[1].length > 0 ? dadom[1] : calling_field_hash);
            break;
         }
      }
}

function reset_vars(){
	//alert ('resetting vars');
	js_error_mssg = null;
   js_error_mssg = new Array;
	if(val_error_mssg.length > 0) {
		//alert('sup sub 1');
		sup_submit = 1;
	}
	val_error_mssg = null;
   val_error_mssg = new Array;
	total_to_run = 0;
	current_loop = 1;
	sup_popval = 0;
}
function add_to_mssgs(mssg){
	val_error_mssg[current_loop - 1] = mssg;
	js_error_mssg[current_loop - 1] = mssg;
}
function show_js_mssg(){
    //alert ('showing mssg');
	if(js_error_mssg.length > 0 ) alert(js_error_mssg.join('\n'));
}
function should_submit(){
	if(window.sup_submit){
		//alert('submit suppressed');
		sup_submit = 0;
		return false;
	}else{
		//alert('not suppressed');
		sup_submit = 0;
		return true;
	}
}
function show_div_mssg(display_mssg,frm){
   if(!frm) frm = window;
	if(document.getElementById){
     daname = frm.document.getElementById('iForm_errors')?'iForm_errors':'dmsg';
     frm.document.getElementById(daname).innerHTML = display_mssg;
   }else if (document.all){
     if(frm.document.all.iForm_errors)
        frm.document.all.iForm_errors.innerHTML = display_mssg;
     else
        frm.document.all.dmsg.innerHTML = display_mssg;
   }else if (document.layers){
     if(frm.document.layers.iForm_errors)
       frm.document.layers.iForm_errors.innerHTML = display_mssg;
     else
       frm.document.layers.dmsg.innerHTML = display_mssg;
   }

}
/***************************************************************
quick_popval: dynamic prepop and validation.  This master function is a regrouping 
of all the functions under "address validation routines"
that allows for production-friendly prepoulation of form fields
*****************************************************************/
//set up some defaults
dpt=0; //1 means testing, comment out for live
var popval_running = false;
var total_to_run = 0;
var current_loop = 1;
var val_error_mssg = new Array;
var js_error_mssg = new Array;
var sup_submit = 0;
var sup_popval = 0;
var calling_field_hash = 'asdfasdfasdf98as7dfasdf';
var current_popval_mode ='';
var freepass_data = new Array();
var popval_freepass = new Array();
var popval_calls = new Array();
var cb=0;
var iframe_check_loop = 0;
var max_iframe_check_loop = 5;
function quick_popval(mode,f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12){
   if(!iframe_loaded){
      iframe_check_loop = iframe_check_loop+1;
      if(iframe_check_loop<max_iframe_check_loop){
         var lag = 200;
         if(f12) setTimeout("quick_popval('"+mode+"','"+f1+"','"+f2+"','"+f3+"','"+f4+"','"+f5+"','"+f6+"','"+f7+"','"+f8+"','"+f9+"','"+f10+"','"+f11+"','"+f12+"')",lag);
         else if(f11) setTimeout("quick_popval('"+mode+"','"+f1+"','"+f2+"','"+f3+"','"+f4+"','"+f5+"','"+f6+"','"+f7+"','"+f8+"','"+f9+"','"+f10+"','"+f11+"')",lag);
         else if(f10) setTimeout("quick_popval('"+mode+"','"+f1+"','"+f2+"','"+f3+"','"+f4+"','"+f5+"','"+f6+"','"+f7+"','"+f8+"','"+f9+"','"+f10+"')",lag);
         else if(f9) setTimeout("quick_popval('"+mode+"','"+f1+"','"+f2+"','"+f3+"','"+f4+"','"+f5+"','"+f6+"','"+f7+"','"+f8+"','"+f9+"')",lag);
         else if(f8) setTimeout("quick_popval('"+mode+"','"+f1+"','"+f2+"','"+f3+"','"+f4+"','"+f5+"','"+f6+"','"+f7+"','"+f8+"')",lag);
         else if(f7) setTimeout("quick_popval('"+mode+"','"+f1+"','"+f2+"','"+f3+"','"+f4+"','"+f5+"','"+f6+"','"+f7+"')",lag);
         else if(f6) setTimeout("quick_popval('"+mode+"','"+f1+"','"+f2+"','"+f3+"','"+f4+"','"+f5+"','"+f6+"')",lag);
         else if(f5) setTimeout("quick_popval('"+mode+"','"+f1+"','"+f2+"','"+f3+"','"+f4+"','"+f5+"')",lag);
         else if(f4) setTimeout("quick_popval('"+mode+"','"+f1+"','"+f2+"','"+f3+"','"+f4+"')",lag);
         else if(f3) setTimeout("quick_popval('"+mode+"','"+f1+"','"+f2+"','"+f3+"')",lag);
         else if(f2) setTimeout("quick_popval('"+mode+"','"+f1+"','"+f2+"')",lag);
         else if(f1) setTimeout("quick_popval('"+mode+"','"+f1+"')",lag);
         return false;
      }
   }
   iframe_check_loop=0;
	//add to popval calls so we know what's what
	popval_set = 0;
	cb=1;
	for(j=0;j<popval_calls.length;j++){
		if(popval_calls[j] == mode) popval_set = 1;
	}
	if(!popval_set) popval_calls[popval_calls.length] = mode;
	current_popval_mode = mode;
	if (sup_popval > 0){
		current_loop++;
		//alert ('popval suppressed ('+mode+')');
		if((current_loop == total_to_run) || !total_to_run){
		 window.reset_vars();
		}
		return false;
	}
	if(current_loop > 1 && current_loop > total_to_run){ //corner case....
//		alert('greater than, resetting; '+current_loop+' '+total_to_run);
		window.reset_vars();
		setTimeout("quick_popval('"+mode+"', '"+f1+"','"+f2+"','"+f3+"','"+f4+"','"+f5+"','"+f6+"','"+f7+"','"+f8+"','"+f9+"','"+f10+"','"+f11+"','"+f12+"')", 10);
		return;
	}
	//check if we're on loop 1 and sup_submit is set -- shouldn't be
	// ie another corner case
	if(current_loop == 1 && sup_submit == 1) sup_submit = 0;
	//Make sure the last one is done before we do this one.
	if(popval_running) {
	//	alert('timeout for mode: ' + mode);
		setTimeout("quick_popval('"+mode+"', '"+f1+"','"+f2+"','"+f3+"','"+f4+"','"+f5+"','"+f6+"','"+f7+"','"+f8+"','"+f9+"','"+f10+"','"+f11+"','"+f12+"')", 200);
		return;
	}
	popval_running = true;
	/*************
	figure out which call called us and find the total numer of popval calls
	in that call -- this is done for one error message display even if many
	popvals called
	******************/
	if(!total_to_run){
		var calling_field = get_calling_name(mode);
		//alert('calling field: '+calling_field);
		relevant_calls = false;
		if(calling_field || calling_field == calling_field_hash){
		//	if(calling_field != calling_field_hash){ //on hrefs without a name, this returns false
			eval( "var field = document.forms[0]."+calling_field+";");
		//	}else alert('got hash');
			if(!field){
		//	alert('no field 1');
				//could be a <a> . Because IE won't recognize document.links[name], kludge:
				for(zz=0;zz<document.links.length;zz++){
					if(document.links[zz].name == calling_field){
						field = document.links[zz];
						break;
					}
				}
			//if STILL don't have field, super kludge: find first <a> with mode in its href
				if(!field){
		//		alert ('field still not found');
					for(zz=0;zz<document.links.length;zz++){
						if(document.links[zz].href.indexOf(mode) > -1 ){
							field = document.links[zz];
				//			alert(field.name);
							break;
						}
					}
				}
		//		if(!field) alert ('no field at all!');

				if (field.href) var relevant_calls = parse_call(field.href,1);
			}else{
				if(field.onchange)var relevant_calls = parse_call(field.onchange,1);
				else if (field.onclick) var relevant_calls = parse_call(field.onclick,1);
				else if (field.onsubmit) var relevant_calls = parse_call(field.onsubmit,1);
			}
		}
		if(relevant_calls){
			var count_me = relevant_calls.split(";");
			total_to_run = count_me.length;
		}//else alert ('no relevant calls');
	}

	if(dpt) alert(mode);
	set_action(mode);
	suppressed = 0;
	switch (mode){
		case "prepop_citystate_from_zip":
		   set_hook(f4);
		   set_mapping("city",f1);
		   set_mapping("state",f2);
		   set_mapping("zip",f3);
		   suppress_submit();
		   start_validation();
			break;
		case "prepop_citystatearea_from_zip":
		   set_hook(f5);
		   set_mapping("city",f1);
		   set_mapping("state",f2);
		   set_mapping("areacode",f3);
		   set_mapping("zip",f4);
		   suppress_submit();
		   start_validation();
			break;
		case "prepop_area_from_zip":
		   set_hook(f3);
		   set_mapping("areacode",f1);
		   set_mapping("zip",f2);
		   suppress_submit();
			start_validation();
			break;
		case "validate_zip":
		   set_hook(f2);
		   set_mapping("zip",f1);
		   start_validation();
			break;
		case "validate_zip_no_submit":
		   set_hook(f2);
		   set_action("validate_zip");
		   set_mapping("zip",f1);
			suppress_submit();
			start_validation();
			break;
		case "validate_citystatezip":
		   set_hook(f4);
		   set_mapping("city",f1);
		   set_mapping("state",f2);
		   set_mapping("zip",f3);
		   start_validation();
			break;
		case "validate_citystatezip_no_submit":
			set_hook(f4);
			set_action("validate_citystatezip");
			set_mapping("city",f1);
		   set_mapping("state",f2);
		   set_mapping("zip",f3);
		   suppress_submit();
		   start_validation();
			break;
		case "validate_a1a2citystatezip":
			set_hook(f6);
			set_mapping("address1",f1);
			set_mapping("address2",f2);
			set_mapping("city",f3);
			set_mapping("state",f4);
			set_mapping("zip",f5);
			start_validation();
			break;
		case "validate_a1a2citystatezip_no_submit":
			set_hook(f6);
			set_action("validate_a1a2citystatezip");
			suppress_submit();
			set_mapping("address1",f1);
			set_mapping("address2",f2);
			set_mapping("city",f3);
			set_mapping("state",f4);
			set_mapping("zip",f5);
			start_validation();
			break;
		case "validate_a1a2citystatezipzip4":
         set_hook(f7);
			set_mapping("address1",f1);
			set_mapping("address2",f2);
			set_mapping("city",f3);
			set_mapping("state",f4);
			set_mapping("zip",f5);
			start_validation();
			break;		
		case "validate_a1a2citystatezipzip4_no_submit":
			set_hook(f7);
			set_action("validate_a1a2citystatezip");
			suppress_submit();
			set_mapping("address1",f1);
			set_mapping("address2",f2);
			set_mapping("city",f3);
			set_mapping("state",f4);
			set_mapping("zip",f5);
			start_validation();
			break;
		case "validate_email":
			set_hook(f2);
			set_action("validate_email");
			set_mapping("email",f1);
			start_validation();
			break;
		case "validate_email_no_submit":
			set_hook(f2);
			set_action("validate_email");
			set_mapping("email",f1);
			suppress_submit();
			start_validation();
			break;
		case "validate_ssn":
			set_hook(f2);
			set_action("validate_ssn");
			set_mapping("ssn",f1);
			start_validation();
			break;
		case "validate_ssn_no_submit":
			set_hook(f2);
			set_action("validate_ssn");
			set_mapping("ssn",f1);
			suppress_submit();
			start_validation();
			break;
		case "validate_ssn3":
			set_hook(f4);
			set_action("validate_ssn");
			set_mapping("ssn1",f1);
			set_mapping("ssn2",f2);
			set_mapping("ssn3",f3);
			start_validation();
			break;
		case "validate_ssn3_no_submit":
			set_hook(f4);
			set_action("validate_ssn");
			set_mapping("ssn1",f1);
			set_mapping("ssn2",f2);
			set_mapping("ssn3",f3);
			suppress_submit();
			start_validation();
			break;
		case "validate_phone":
			set_hook(f4);
			set_action("validate_phone");
			set_mapping("areacode",f1);
			set_mapping("prefix", f2);
			set_mapping("suffix", f3);
			start_validation();
			break;
		case "validate_phone_no_submit":
			set_hook(f4);
			set_action("validate_phone");
			set_mapping("areacode",f1);
			set_mapping("prefix", f2);
			set_mapping("suffix", f3);
			suppress_submit();
			start_validation();
			break;
		case "validate_phone_cell":
			set_hook(f4);
			set_action("validate_phone_cell");
			set_mapping("areacode",f1);
			set_mapping("prefix", f2);
			set_mapping("suffix", f3);
			start_validation();
			break;
		case "validate_phone_cell_no_submit":
			set_hook(f4);
			set_action("validate_phone_cell");
			set_mapping("areacode",f1);
			set_mapping("prefix", f2);
			set_mapping("suffix", f3);
			suppress_submit();
			start_validation();
			break;
		case "validate_phone_cell_liberal":
			set_hook(f4);
			set_action("validate_phone_cell_liberal");
			set_mapping("areacode",f1);
			set_mapping("prefix", f2);
			set_mapping("suffix", f3);
			start_validation();
			break;
		case "validate_phone_cell_liberal_no_submit":
			set_hook(f4);
			set_action("validate_phone_cell_liberal");
			set_mapping("areacode",f1);
			set_mapping("prefix", f2);
			set_mapping("suffix", f3);
			suppress_submit();
			start_validation();
			break;
		case "validate_phone_land":
			set_hook(f4);
			set_action("validate_phone_land");
			set_mapping("areacode",f1);
			set_mapping("prefix", f2);
			set_mapping("suffix", f3);
			start_validation();
			break;
		case "validate_phone_land_no_submit":
			set_hook(f4);
			set_action("validate_phone_land");
			set_mapping("areacode",f1);
			set_mapping("prefix", f2);
			set_mapping("suffix", f3);
			suppress_submit();
			start_validation();
			break;
      case 'validate_phone_uk':
         set_hook(f2);
         set_mapping('phone',f1);
		   start_validation();
         break;
      case 'validate_phone_uk_cell':
         set_hook(f2);
         set_mapping('phone',f1);
		   start_validation();
         break;
      case 'validate_phone_uk_land':
         set_hook(f2);
         set_mapping('phone',f1);
		   start_validation();
         break;
      case 'validate_phone_uk_no_submit':
         set_hook(f2);
         set_mapping('phone',f1);
         suppress_submit();
		   start_validation();
         break;
      case 'validate_phone_uk_cell_no_submit':
         set_hook(f2);
         set_mapping('phone',f1);
         suppress_submit();
		   start_validation();
         break;
      case 'validate_phone_uk_land_no_submit':
         set_hook(f2);
         set_mapping('phone',f1);
         suppress_submit();
		   start_validation();
         break;
      case 'validate_user':
         set_hook(f12);
         set_action("validate_user");
         set_mapping("email",f1);
         set_mapping("fname",f2);
         set_mapping("lname",f3);
         set_mapping("address1",f4);
         set_mapping("address2",f5);
         set_mapping("city",f6);
         set_mapping("state",f7);
         set_mapping("zip",f8);
         set_mapping("areacode",f9);
         set_mapping("prefix",f10);
         set_mapping("suffix",f11);
         start_validation();
         break;
   default:
			alert("no mode: "+ mode);
			break;
	}
	last_val = mode;
	void(null);
}

function popval(mode,f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12){
   if(!iframe_loaded){
      iframe_check_loop = iframe_check_loop+1;
      if(iframe_check_loop<max_iframe_check_loop){
         var lag = 200;
         if(f12) setTimeout("popval('"+mode+"','"+f1+"','"+f2+"','"+f3+"','"+f4+"','"+f5+"','"+f6+"','"+f7+"','"+f8+"','"+f9+"','"+f10+"','"+f11+"','"+f12+"')",lag);
         else if(f11) setTimeout("popval('"+mode+"','"+f1+"','"+f2+"','"+f3+"','"+f4+"','"+f5+"','"+f6+"','"+f7+"','"+f8+"','"+f9+"','"+f10+"','"+f11+"')",lag);
         else if(f10) setTimeout("popval('"+mode+"','"+f1+"','"+f2+"','"+f3+"','"+f4+"','"+f5+"','"+f6+"','"+f7+"','"+f8+"','"+f9+"','"+f10+"')",lag);
         else if(f9) setTimeout("popval('"+mode+"','"+f1+"','"+f2+"','"+f3+"','"+f4+"','"+f5+"','"+f6+"','"+f7+"','"+f8+"','"+f9+"')",lag);
         else if(f8) setTimeout("popval('"+mode+"','"+f1+"','"+f2+"','"+f3+"','"+f4+"','"+f5+"','"+f6+"','"+f7+"','"+f8+"')",lag);
         else if(f7) setTimeout("popval('"+mode+"','"+f1+"','"+f2+"','"+f3+"','"+f4+"','"+f5+"','"+f6+"','"+f7+"')",lag);
         else if(f6) setTimeout("popval('"+mode+"','"+f1+"','"+f2+"','"+f3+"','"+f4+"','"+f5+"','"+f6+"')",lag);
         else if(f5) setTimeout("popval('"+mode+"','"+f1+"','"+f2+"','"+f3+"','"+f4+"','"+f5+"')",lag);
         else if(f4) setTimeout("popval('"+mode+"','"+f1+"','"+f2+"','"+f3+"','"+f4+"')",lag);
         else if(f3) setTimeout("popval('"+mode+"','"+f1+"','"+f2+"','"+f3+"')",lag);
         else if(f2) setTimeout("popval('"+mode+"','"+f1+"','"+f2+"')",lag);
         else if(f1) setTimeout("popval('"+mode+"','"+f1+"')",lag);
         return false;
      }
   }
   iframe_check_loop = 0;
	preval='no';
	if(validate(document.ms,'alert')){
		show_spinner();
		if(f12) quick_popval(mode,f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12);
		else if (f11) quick_popval(mode,f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11);
		else if (f10) quick_popval(mode,f1,f2,f3,f4,f5,f6,f7,f8,f9,f10);
		else if (f9) quick_popval(mode,f1,f2,f3,f4,f5,f6,f7,f8,f9);
		else if (f8) quick_popval(mode,f1,f2,f3,f4,f5,f6,f7,f8);
		else if (f7) quick_popval(mode,f1,f2,f3,f4,f5,f6,f7);
		else if (f6) quick_popval(mode,f1,f2,f3,f4,f5,f6);
		else if (f5) quick_popval(mode,f1,f2,f3,f4,f5);
		else if (f4) quick_popval(mode,f1,f2,f3,f4);
		else if (f3) quick_popval(mode,f1,f2,f3);
		else if (f2) quick_popval(mode,f1,f2);
		else if (f1) quick_popval(mode,f1);
	}else{
		reset_vars();
		sup_popval = 1;
		void(null);
	}
}



/*************************************************
*	Address validation routines
*************************************************/
M = new Array();
M['zip'] = 'zipId';
M['zip4'] = 'zip4Id';
M['email'] = 'emailId';
M['fname'] = 'fnameId';
M['lname'] = 'lnameId';
M['address1'] = 'address1Id';
M['address2'] = 'address2Id';
M['city'] = 'cityId';
M['state'] = 'stateId';
M['areacode'] = 'areacodeId';
M['prefix'] = 'prefixId';
M['suffix'] = 'suffixId';
M['post'] = 'postId';
M['address'] = 'addressId';

/***********************************
TODO:

make set_mapping set up a freepass_data varialbe, probablyan array
that has all the fields it's working on
the free_pass can use that array to build its unique string of numbers
it's already checked
*************************************/

function set_mapping(fieldName,fieldId){
		eval ("target = frames['searchIFrame'].document.search." + M[fieldName]);
		if(target) target.value = fieldId;
      eval ("if(document.ms." + fieldId+" && frames['searchIFrame'].document.search." + fieldName+") frames['searchIFrame'].document.search." + fieldName + ".value = document.ms." + fieldId + ".value;");
		//add field to list of concatenated valid addr
		if(!freepass_data[current_popval_mode+'_ids']){
			freepass_data[current_popval_mode+'_ids'] = new Array();
		}
		if(!freepass_data[current_popval_mode+'_fields']){
			freepass_data[current_popval_mode+'_fields'] = new Array();
		}
		if(fieldId) freepass_data[current_popval_mode+'_ids'][freepass_data[current_popval_mode+'_ids'].length] = fieldId;
		if(fieldName) freepass_data[current_popval_mode+'_fields'][freepass_data[current_popval_mode+'_fields'].length] = fieldName;
}
function start_validation(){
	//if they get a free pass, just submit form, otherwise, run validation
	if(free_pass() && !suppressed && (current_loop >= total_to_run)){
		//alert ('free pass');
		document.forms[0].js.value='yes';
		return document.ms.submit();
	}else{
	   // alert ('no free pass '+suppressed);
		freepass_data[current_popval_mode+'_ids'] = new Array();
		freepass_data[current_popval_mode+'_fields'] = new Array(); //these need to be reinit here otherwise grow too long
		return frames['searchIFrame'].document.search.submit();
	}
}

var no_freepass_offer='notset'; // set global var to prevent user from getting free pass on per offer basis

//checks the number of submission attempts and lets them through if greater than x
function free_pass(){
   if(no_freepass_offer == 'set') var numberOfValidationAttempts=1000; // no pass for user at offer level - see datapoint 26903 
   else var numberOfValidationAttempts = 2; //2 means 3 attempts (starts @ zero) 
	var freepass = 0;
	for(fl=0;fl<freepass_data[current_popval_mode+"_ids"].length;fl++){ //create the valid string for which they get n tries
      if(document.forms.ms[freepass_data[current_popval_mode+"_ids"][fl]]){
         if(document.forms.ms[freepass_data[current_popval_mode+"_ids"][fl]].value){
            if(!freepass_data[current_popval_mode]) freepass_data[current_popval_mode] = '';
               freepass_data[current_popval_mode] += document.forms.ms[freepass_data[current_popval_mode+"_ids"][fl]].value + "|";
            }
         }
      }
	//get the cookie val, if any, for validAttempts and validString for this mode
    var validString = getCookie(current_popval_mode);
	 freepass_data[current_popval_mode+'_validAttempts'] = getCookie(current_popval_mode+'_validAttempts');
    if(validString == freepass_data[current_popval_mode]) freepass_data[current_popval_mode+'_validAttempts']++;
	 else{
	 	freepass_data[current_popval_mode+'_validAttempts'] = 0;
		temp = popval_freepass;
		popval_freepass.length = 0;
		for(j=0;j<temp.length;j++){ //rebuild popval freepass without this one
			if(temp[j] != current_popval_mode) popval_freepass[j] = temp[j];
		}
		setCookie(current_popval_mode,freepass_data[current_popval_mode]);
		freepass_data[current_popval_mode] = '';
	 }
    setCookie(current_popval_mode+'_validAttempts', freepass_data[current_popval_mode+'_validAttempts']);
	 if(freepass_data[current_popval_mode+'_validAttempts'] < numberOfValidationAttempts){ //havent tried enough times
	 	freepass_data[current_popval_mode] = '';
		return false;
	 }else { //have tried enough times
		sup_submit = 0;
		suppressed = 0;
		if(popval_freepass.length >= total_to_run){
			freepass_data[current_popval_mode] = '';
         if(no_freepass_offer == 'set') {
            var f = document.forms[0];
            f.q26903.value='passed'; // user has passed popval on offer basis
         }
			return true; //we only want to give a freepass to someone who's through the multiple calls
		}else{
			if(!in_array(popval_freepass,current_popval_mode)){
				popval_freepass[popval_freepass.length] = current_popval_mode;
			}
			freepass_data[current_popval_mode] = '';
			return false;
		}
	 }
}

function in_array(arr,val){
	for(j=0;j<arr.length;j++){
		if(arr[j]==val) return true;
	}
	return false;
}

function createIFrame () {
	// for debugging
	document.write("<iframe name=\"searchIFrame\" id=\"searchIFrame\" src=\"lib/searchIForm.php\"></iframe>");
}

/****************
dynamic month / day in month check
***************/
function set_up_months(){
	var f = document.forms[0];
	if(f){
		if(f.ARG_PAGE_BUILT){
			if(f.q11 && f.q12 && f.q11.setAttribute && f.q13){
					f.q11['onchange'] = new Function("set_month_days();bouncer()");
					f.q13['onchange']= new Function("sup_pop(this.value);set_month_days()");
			}
		}else{
			setTimeout('set_up_months()',200);
		}
	}else{
		setTimeout('set_up_months()',200);
	}
}
set_up_months();

function set_month_days(){
	var f = document.forms[0];
	if (f.q12) var mm = f.q11;
	if (f.q11) var dm = f.q12;
	if (f.q13) var ym = f.q13;
	var data = new Array();
	data['01'] = 31; //jan
	data['02'] = (ym.value/4)==Math.floor(ym.value/4) && ym.value>0?29:28; //feb
	data['03'] = 31; //march
	data['04'] = 30; //apr
	data['05'] = 31; //may
	data['06'] = 30; //june
	data['07'] = 31; //july
	data['08'] = 31; //august
	data['09'] = 30; //sept
	data['10'] = 31; //oct
	data['11'] = 30; //nov
	data['12'] = 31; //dec
	if(mm && dm){
		var oldIndex = dm.selectedIndex;
		dm.options.length=0;
		dm.options[0] = new Option('DD','');
		for(l=1;l<data[mm.value]+1;l++){
			value = l<10?'0'+l:l;
			dm.options[l] = new Option(value);	
			if(l==oldIndex) dm.options[l].selected = true;
		}
	}
}

/**************************************************************************
* calculate_age()
*
* returns the age of user based on three hidden fields (birthYear,birthMonth,birthDay)
* that should be included in the page if this script is to work.
**************************************************************************/
function calculate_age(){
    var yy = document.forms[0].birthYear.value;
    var mm = document.forms[0].birthMonth.value;
    var dd = document.forms[0].birthMonth.value;
    var days = new Date();
    var gdate = days.getDate();
    var gmonth = days.getMonth();
    var gyear = days.getFullYear();
    var age = gyear - yy;
    if((mm == (gmonth + 1)) && (dd <= parseInt(gdate))) {
    age = age;
    }
    else {
    if(mm <= (gmonth)) {
    age = age;
    }
    else {
    age = age - 1; 
       }
    }
    return age;
}

/**************************************************************************
* validate_age()
*
* validates the age of current user against an upper and lower limit,then
* automatically set a data point to yes/no depending on whether the age falls
* in that limit.
* NOTE: this function is pretty rigid.  It requires the yes/no target field
* to be two radio buttons, [0] is the yes button, [1] is the no button.
**************************************************************************/
function validate_age(lower,upper,qualField){
	var age = calculate_age();
         yF = eval ('document.forms[0].' + qualField + '[0]');
         nF = eval ('document.forms[0].' + qualField + '[1]');
    if(age < lower || age > upper){
         yF.checked = false;
         nF.checked = true;
    }else{
         yF.checked = true;
         nF.checked = false;       
    }
}
/***************************************************************************
*check_state()
*
* validates a data point against a list of states to be excluded from the leads.
* requires that a hidden "state" variable be inserted into the form so that the
* javascript can verify what state the user is from.
* ALSO requires that the dataPoint be a yes/no radio button, with yes as the first
* value (more flexibility on this function can be added down the line)
*******************************************************************************/

function check_state(dataPoint){
    var optin = eval ('document.forms[0].'+ dataPoint);
    var leadStt = document.forms[0].state.value;
    for(j=0;j<excludeStates.length;j++){
        var checkStt = excludeStates[j];
        if (leadStt==checkStt){
            optin[0].checked = false;
            optin[1].checked = true;
            break;
        }
    }
}

/*************************************************
*	General cookie functions
*************************************************/
/**
 * Sets a Cookie with the given name and value.
 *
 * name       Name of the cookie
 * value      Value of the cookie
 * [expires]  Expiration date of the cookie (default: end of current session)
 * [path]     Path where the cookie is valid (default: current path)
 * [domain]   Domain where the cookie is valid
 *              (default: domain of calling document)
 * [secure]   Boolean value indicating if the cookie transmission requires a
 *              secure transmission
 */
function setCookie(name, value, expires, path, domain, secure)
{
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

/**
 * Gets the value of the specified cookie.
 *
 * name  Name of the desired cookie.
 *
 * Returns a string containing value of specified cookie,
 *   or null if cookie does not exist.
 */
function getCookie(name)
{
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1)
    {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else
    {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
    {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

/**
 * Deletes the specified cookie.
 *
 * name      name of the cookie
 * [path]    path of the cookie (must be same as path used to create cookie)
 * [domain]  domain of the cookie (must be same as domain used to create cookie)
 */
function deleteCookie(name, path, domain)
{
    if (getCookie(name))
    {
        document.cookie = name + "=" + 
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}
//word scrub, each index in a regexp
//                  0   1   2   3   4   5
var tx = new Array('a','e','i','o','u','y');

var scrub = new Array('sh(2|\!|0)t(1)*','p2ss','c4nt','f4ck','wh3r1','p1n2s','b2tch','(0ss|b4m|c3rn|0rs1)(-+|_+| +)*h3l1','f0gg3t','n2gg(1r|0h|0)','w1tb0ck','tw0t','t2ts','spl33g1','sp2c','sl4t','sh1m0l1','q411f','p4ss5(?!(-+|_+| +)*c0t)','l1sb(3|20n)','m0st4rb0','j2zz','g33k','f0t(-+|_+| +)*(0ss|0rs1)','cl2t(s|)','v0g2n0','d2ld3','d2ck(s*).+?(?=(h10d|s4ck|l2ck))','0n4s','b0st0rd','l3v1(-+|_+| +)*b0n0n0','(bl3w|r2m)(_+|-+| +)*j3b','f0rt','f3r1(_+|-+| +)*sk2n','m4ff','n3bj42c1','c4m(_|-| |@)+','p1ck1r','t4rd','^(0ss|b4tt)(_+|-+| +)*(r0mm1r|p2r0t1|((lick|pump|jump|taste)er))*');
var scrub = new Array('sh2t','p2ss','f4ck','v0g2n0','d2ld3','p4ss5(?!(-+|_+| +)*c0t)');
var scrub_words = new Array();
for(z=0;z<scrub.length;z++){
	for(y=0;y<tx.length;y++){
		scrub[z] = scrub[z].replace(new RegExp(y+'','g'),tx[y]);
	}
	scrub_words[scrub_words.length] = new RegExp(scrub[z]);
}
//scrub_words = new Array();

//page awareness
function pageWidth() {return window.innerWidth != null? window.innerWidth : document.documentElement && document.documentElement.clientWidth ?       document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null;}
function pageHeight() {return  window.innerHeight != null? window.innerHeight : document.documentElement && document.documentElement.clientHeight ?  document.documentElement.clientHeight : document.body != null? document.body.clientHeight : null;}
function posLeft() {return typeof window.pageXOffset != 'undefined' ? window.pageXOffset :document.documentElement && document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ? document.body.scrollLeft : 0;}
function posTop() {return typeof window.pageYOffset != 'undefined' ?  window.pageYOffset : document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ? document.body.scrollTop : 0;}
function posRight() {return posLeft()+pageWidth();}
function posBottom() {return posTop()+pageHeight();}

//static lp extracted stuff
function Querystring() {
   this.params = new Object();
   var qs = location.search.substring(1,location.search.length);
   if(qs.length == 0) return;

   qs = qs.replace(/\+/g, ' ');
   var args = qs.split('&');

   for(var i = 0; i < args.length; i++) {
      var value;
      var pair = args[i].split('=');
      var name = unescape(pair[0]);

      if(pair.length == 2) value = unescape(pair[1])
      else value = name

      this.params[name] = value;
   }
}

function add_inputs() {
   if(document.location.pathname.match(/pub\.php/)) return; //so it works on static pages only
   var qs = new Querystring();
   for(var i in qs.params) {
      var tmc = i.match(/^q([0-9]+)$/);
      if(tmc){
         if(tmc[1]>30 || tmc[1]==1 || qs.params['ampinj']){
            if(document.forms[0].elements[i]) {
               if(document.forms[0].elements[i].length) {
                  var element = document.forms[0].elements[i][0];
               } else {
                  var element = document.forms[0].elements[i];
               }
               element.value = qs.params[i];
               continue;
            }
            
            var temp = document.createElement('INPUT');
            temp.type = 'hidden';
            temp.name = i;
            temp.value = qs.params[i];
            document.forms[0].appendChild(temp);
         }
      }else{
         var temp = document.createElement('INPUT');
         temp.type = 'hidden';
         temp.name = i;
         temp.value = qs.params[i];
         document.forms[0].appendChild(temp);
      }
   }
   //also add in the static lp notifier
   var temp = document.createElement('input');
   temp.type = 'hidden';
   temp.name = 'static_lp';
   temp.value = '1';
   document.forms[0].appendChild(temp);
}

function get_ajax_handler() {
var xmlHttp;
  try
    {
    // Firefox, Opera 8.0+, Safari
    xmlHttp=new XMLHttpRequest();
    }
  catch (e)
    {
    // Internet Explorer
    try
      {
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
      }
    catch (e)
      {
      try
        {
        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
      catch (e)
        {
        alert("Your browser does not support AJAX!");
        return false;
        }
      }
    }
    return xmlHttp;
}

function prepop_uk_address(postcode, address) {
   eval("var post = document.forms.ms."+postcode+";");
   eval("var addr = document.forms.ms."+address+";");
   if(post.value.length < 5) {
      return;
   }

   var ajax = get_ajax_handler();
   ajax.onreadystatechange=function() {
      if(ajax.readyState == 4) {
         if(ajax.responseText.indexOf('Error:') != -1) {
            //validation_error[validation_error.length] = ajax.responseText.substring(ajax.responseText.indexOf(':')+1);
            //TODO: give the error
            return;
         } else {
            //Put the options where they need to be.
            for(var i = 0; i < addr.options.length; i++) {
               addr.options[i--] = null;
            }
            var temp = ajax.responseText.split('===');
            var options = temp[0].split('|');
            for(var i = 0; i < options.length; i++) {
               if(options[i])
                  addr.options[addr.options.length] = new Option(options[i]);
            }
            post.value = temp[1];
         }
      }
   }
   ajax.open("GET","/lib/hook_qas_uk.php?post="+post.value,true);
   ajax.send(null);
}

function clear_uk_address(postcode, address) {
   if(document.forms.ms.elements[postcode].value.length < 5) {
      return;
   }
   if(document.forms.ms.elements[address].options.length > 2) {
      return;
   }
   document.forms.ms.elements[postcode].value = '';
   for(var i = 0; i < document.forms.ms.elements[address].options.length; i++) {
      document.forms.ms.elements[address].options[i] = null;
      i--;
   }
   document.forms.ms.elements[address].options[0] = new Option('Please enter a valid post code');
}
function record_value(qid,val,sync){
   if(!document.forms[0].sesp) return;
   if(!document.forms[0].sesp.value.match(/^\d+_\d+$/)) return;
   var tmp = qid.match(/(\d+)$/);
   var id = tmp[1];
   var loc = "custom/ajax/getresult.php?sesp="+document.forms[0].sesp.value+"&qk=y34nnI&arg1="+id+"&arg2="+val
   var a = new XMLHttpRequest();
   var async = sync?0:1;
   a.open("GET",loc,async);
   a.send('');
}
function retrieve_value(code,arg_string,sesp,url){
   if(!code) return '';
   if(!url) url ="custom/ajax/getresult.php?"; 
   var r = new XMLHttpRequest();
   var loc = url? url : url+(sesp?"sesp="+sesp:"")+"&qk="+code+"&"+arg_string;
   r.open("GET",loc,false);
   r.send('');
   return r.responseXML.getElementsByTagName('result')[0].firstChild.data;
}
//wrapper function for specialzed case of above
function get_mod_date(){
   return retrieve_value(true,false,false,'/custom/ajax/mod_date.xml');
}

//This function allows you to toggle a <div> between hidden and shown
function toggleDiv(divid){
    if(document.getElementById(divid).style.display == 'none'){
      document.getElementById(divid).style.display = 'block';
    }else{
      document.getElementById(divid).style.display = 'none';
    }
  }
