/*
 *	==============================================================================================================
 *		Utilities - utilities.js
 *	==============================================================================================================
 */

function openResourcesWindow() {
    window.open("http://www.one-data.com/portal/",
        "Resources",
         config="height=600,width=800,toolbar=no,menubar=no,scrollbars=yes,resizable=no,location=no,directories=no,status=no"
    );
}

//essentially, this function iterates through the document(and layers/frames within a document) to find all objects with names matching the parameter 'n'
function MM_findObj(n, d)
{
var p,i,x;
if(!d) d=document;
if((p=n.indexOf("?"))>0&&parent.frames.length)

{
d=parent.frames[n.substring(p+1)].document;
n=n.substring(0,p);
}
if(!(x=d[n])&&d.all) x=d.all[n];
for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=findObj(n,d.layers[i].document);
return x;
}

function MM_validateForm() { //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) {
    test=args[i+2];
    val=MM_findObj(args[i]);
    if (val) {
      nm=val.name;
      if ((val=val.value)!="") {
        if ((test.indexOf('isEmail')!=-1)) {
          p=val.indexOf('@');
          if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
        } else if (test!='R') {
          if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
          if (test.indexOf('inRange') != -1) {
            p=test.indexOf(':');
            min=test.substring(8,p);
            max=test.substring(p+1);
            if (val<min || max<val) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
          }
        }
      } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n';
    }
  } if (errors) alert('The following error(s) occurred:\n'+errors);
  document.MM_returnValue = (errors == '');
}

 
 /*
 *	==============================================================================================================
 *		DFI - dfi.js
 *	==============================================================================================================
 */
 
var dfi ={
	loadPage: function(url){
		window.location.href=url;

	},
	submitForm:  function(formName){
		document.forms[formName].submit();


	},

	validateUserLogin: function(){

	       var theForm = document.login_form;
	       if(  theForm.j_username.value.length == 0){
		  return false;
	       }else if(  theForm.j_password.value.length == 0){
		  return false;
	       }
	       return true;

	},
	validateUserSignup: function(formName){
	       var theForm = document.forms[formName];
	       var reason="";
	       reason += this.validateEmpty(theForm.first_name,"First Name");
	       reason += this.validateEmpty(theForm.last_name,"Last Name");
	       reason += this.validateEmailField(theForm.email);
               //reason += this.validateEmailField(theForm.email_confirm);
               reason += this.validateEmpty(theForm.title,"Job Title");
               //reason += this.validateEmpty(theForm.department,"Department");
               reason += this.validateEmpty(theForm.organization,"Employer");
	       reason += this.validateEmpty(theForm.phone,"Phone");
	       //reason += this.validateEmpty(theForm.secret_que,"Secret Question");
               //reason += this.validateEmpty(theForm.secret_ans,"Secret Answer");
	       //reason += this.validateEmpty(theForm.secret_ans_confirm,"Confirm Secret Answer");


		if( reason == ""){
	            //reason += this.checkVerifyFields(theForm.email, theForm.email_confirm,"User Email");
	            //reason += this.checkVerifyFields(theForm.secret_ans, theForm.secret_ans_confirm,"Secret Answer");
               }

		if (reason != "") {
		   alert("Please fill in or correct the following fields:\n" + reason);
		   //document.getElementById('formMessage').innerHTML=reason;
		   return false;
	       }

	       return true;
	},

	validateUserActivation: function(formName){
	       var theForm = document.forms[formName];
	       var reason="";
	       reason += this.validateEmpty(theForm.first_name,"First Name");
	       reason += this.validateEmpty(theForm.last_name,"Last Name");
	       reason += this.validateEmailField(theForm.email);
               reason += this.validateEmailField(theForm.email_confirm);
               //reason += this.validateEmpty(theForm.title,"Title");
               //reason += this.validateEmpty(theForm.department,"Department");
               //reason += this.validateEmpty(theForm.organization,"Organization");
	       reason += this.validateEmpty(theForm.password,"Password");
               //reason += this.validateEmpty(theForm.password_confirm,"Confirm Password");
               reason += this.validateEmpty(theForm.phone,"Phone");

              if( reason == ""){
	            reason += this.checkVerifyFields(theForm.email, theForm.email_confirm,"User Email");
	            //reason += this.checkVerifyFields(theForm.password, theForm.password_confirm,"Password");
                    reason += this.checkVerifyPassword(theForm.password, theForm.password_confirm);
	            reason += this.verifyPasswordLength(theForm.password);
               }

		if (reason != "") {
		   alert("Please fill in or correct the following fields:\n" + reason);
		   //document.getElementById('formMessage').innerHTML=reason;
		   return false;
	       }

	       return true;
	},


	validateUserUpdate: function(formName){
	       var theForm = document.forms[formName];
	       var reason="";
	       reason += this.validateEmpty(theForm.first_name,"First Name");
	       reason += this.validateEmpty(theForm.last_name,"Last Name");
	       //reason += this.validateEmpty(theForm.department,"Department");
               reason += this.validateEmpty(theForm.organization,"Employer");
	       reason += this.validateEmpty(theForm.title,"Job Title");
               reason += this.validateEmpty(theForm.phone,"Phone");


		if (reason != "") {
		   alert("Please fill in or correct the following fields:\n" + reason);
		   //document.getElementById('formMessage').innerHTML=reason;
		   return false;
	       }

	       return true;
	},

	validateChangePassword: function(formName){
	       var theForm = document.forms[formName];
	       var reason="";
	       reason += this.validateEmpty(theForm.current_password,"Current Password");
	       reason += this.validateEmpty(theForm.new_password,"New Password");
	       reason += this.validateEmpty(theForm.new_password_confirm,"Confirm New Password");

		if( reason == ""){
	           reason += this.checkVerifyFields(theForm.new_password, theForm.new_password_confirm,"New Password");
               }

		if (reason != "") {
		   alert("Please fill in or correct the following fields:\n" + reason);
		   //document.getElementById('formMessage').innerHTML=reason;
		   return false;
	       }

	       return true;
	},

	validateUsername : function(formName){
	       var theForm = document.forms[formName];
	       var reason="";
	       reason += this.validateEmailField(theForm.user_name);

		if (reason != "") {
		   alert("Please fill in or correct the following fields:\n" + reason);
		   //document.getElementById('formMessage').innerHTML=reason;
		   return false;
	       }

	       return true;
	},



	validateSecretAnswer : function(formName){
	       var theForm = document.forms[formName];
	       var reason="";
	       reason += this.validateEmpty(theForm.secret_ans,"Secret Answer");

		if (reason != "") {
		   alert("Please fill in or correct the following fields:\n" + reason);
		   //document.getElementById('formMessage').innerHTML=reason;
		   return false;
	       }

	       return true;
	},


        validateContactUs: function(formName){
               var theForm = document.forms[formName];
	       var reason="";
	       reason += this.validateEmpty(theForm.user_name,"Your Name");
               reason += this.validateEmpty(theForm.title,"Job Title");
               reason += this.validateEmpty(theForm.organization,"Employer");
               //reason += this.validateEmpty(theForm.department,"Department");
               reason += this.validateEmpty(theForm.phone,"Telephone");
	       reason += this.validateEmailField(theForm.user_email);

               if (reason != "") {
		   alert("Please fill in or correct the following fields:\n" + reason);
		   //document.getElementById('formMessage').innerHTML=reason;
		   return false;
	       }
	       return true;

        },

	validateEmploymentContactUs: function(formName){
        	var theForm = document.forms[formName];
	       	var reason="";

		reason += this.validateEmpty(theForm.first_name,"First Name");
	       	reason += this.validateEmpty(theForm.last_name,"Last Name");
		reason += this.validateEmailField(theForm.email);
		reason += this.validateRadioField(theForm.avail_emp_types,"Employment Type");
		reason += this.validateDropDown(theForm.us_work_authorization,"US Work Authorization");

		if (reason != "") {
		   alert("Please fill in or correct the following fields:\n" + reason);
		   //document.getElementById('formMessage').innerHTML=reason;
		   return false;
	       }
	       return true;


	},

	validateScheduleBriefing: function(formName){
        	var theForm = document.forms[formName];
	       	var reason="";

		reason += this.validateEmpty(theForm.name,"Your Name");
	       	reason += this.validateEmpty(theForm.title,"Job Title/Role");
		reason += this.validateEmpty(theForm.organization,"Organization");
		reason += this.validateEmailField(theForm.email);
		reason += this.validateEmpty(theForm.phone,"Telephone");
		reason += this.validateEmpty(theForm.best_contact_time,"Best time(s) to contact you");
		reason += this.validateEmpty(theForm.subject_areas,"Interest Areas/Data domains");


		if (reason != "") {
		   alert("Please fill in or correct the following fields:\n" + reason);
		   //document.getElementById('formMessage').innerHTML=reason;
		   return false;
	       }
	       return true;


	},

	validateScheduleForm: function(formName){
        	var theForm = document.forms[formName];
	       	var reason="";

		reason += this.validateEmpty(theForm.first_name,"First Name");
	       	reason += this.validateEmpty(theForm.last_name,"Last Name");
		reason += this.validateEmpty(theForm.employer,"Employer");
		reason += this.validateEmpty(theForm.title,"Job Title");
		reason += this.validateEmailField(theForm.email);
		reason += this.validateEmpty(theForm.phone,"Telephone");

		if (reason != "") {
		   alert("Please fill in or correct the following fields:\n" + reason);
		   //document.getElementById('formMessage').innerHTML=reason;
		   return false;
	       }
	       return true;


	},

        validateFeedbackForm: function(){
               var theForm = document.feedback;
	       var reason="";
	       reason += this.validateEmpty(theForm.your_name,"Your Name");
	       reason += this.validateEmpty(theForm.email,"Email Address");
	       if (reason != "") {
		   alert("Please fill in or correct the following fields:\n" + reason);
		   //document.getElementById('formMessage').innerHTML=reason;
		   return false;
	       }
	       return true;


        },

	validateEmailField: function(field){
	       var error = "";
	       if( field.value == ""){
		   field.style.background = 'Yellow';
		   error = "Email address\n";
	       }else if( this.validate_email(field.value) == false){
		   field.style.background = 'Yellow';
		   error = "Invalid Email address\n";

	       }else {
		   field.style.background = 'White';
	       }
	    return error;
	},

	validateRadioField: function(field,fieldName){
	     var error = "";
             var checked = false;
	     for( var i=0; i < field.length; i++){
                  if( field[i].checked == true){
		    checked = true;
                    break;
	         }
	     }
            if( checked == false){
		error= "Select "+fieldName+"\n";
            }
            return error;

	},


	validateEmpty: function(field, fieldName) {
	    var error = "";
	    if (field.value.length == 0) {
		field.style.background = 'Yellow';
		error =fieldName+"\n"
	    } else {
		field.style.background = 'White';
	    }
	    return error;
	},

	validateDropDown: function(field, fieldName) {
	    var error = "";
	    if (field.value == 0) {
		field.style.background = 'Yellow';
		error =fieldName+"\n"
	    } else {
		field.style.background = 'White';
	    }
	    return error;
	},

	validate_email:  function(value)
	{
	     apos=value.indexOf("@");
	     dotpos=value.lastIndexOf(".");
	     if (apos<1||dotpos-apos<2)
	     {
	       return false;
	     } else {
	       return true;
	     }

	},

	validateChangePasswordForm:  function(){
	       var theForm = document.password_modify;
	       var reason="";
	       reason += this.validateEmpty(theForm.user_current_password,"Current Password ");
	       reason += this.validateEmpty(theForm.user_new_password,"New password");
	       reason += this.validateEmpty(theForm.user_new_password_verify,"Verify Password");
               if( reason == ""){
	            reason += this.checkVerifyPassword(theForm.user_new_password, theForm.user_new_password_verify);
	            reason += this.verifyPasswordLength(theForm.user_new_password);
               }

	       if (reason != "") {
		   alert("Some fields need correction:\n" + reason);
		   return false;
	       }

	       return true;
	},

	checkVerifyPassword: function(field1, field2){

	    var error = "";

	    if (field1.value != field2.value) {
		field1.style.background = 'Yellow';
		field2.style.background = 'Yellow';
		error = "Please verify your password again.\n"
	    }
	    return error;

	},
	verifyPasswordLength: function(field){

	    var error = "";
	    if (field.value.length < 8) {
		field.style.background = 'Yellow';
		error = "Password length should be at least 8.\n"
	    }
	    return error;

	},

	checkVerifyFields: function(field1, field2, fieldName){

	    var error = "";

	    if (field1.value != field2.value) {
		field1.style.background = 'Yellow';
		field2.style.background = 'Yellow';
		error = "Please verify your "+fieldName+" again.Values entered do not match.\n"
	    }
	    return error;

	},

	checkModifyUserForm: function(){

	       var theForm = document.user_modify;
	       var reason="";
	       reason += this.validateEmpty(theForm.first_name,"First Name");
	       reason += this.validateEmpty(theForm.last_name,"Last Name");
	       reason += this.validateEmpty(theForm.secret_question,"Secret Question");
	       reason += this.validateEmpty(theForm.secret_answer,"Secret Answer");

	       if (reason != "") {
		   alert("Some fields need correction:\n" + reason);
		   return false;
	       }

	       return true;
	}
}



 
/*
 *	==============================================================================================================
 *		PDF Popup - popupPDF.js
 *	==============================================================================================================
 */
 
// popupPDF.js
// 4/30/2010
// used to pop up a PDF in a Google Viewer, anywhere on the site.
//
// example usage:
// openPDF(this,'http://www.datafoundations.com/example.pdf');
//
function GetWidth()
{
	var x = 0;
	if (self.innerHeight)
	{
			x = self.innerWidth;
	}
	else if (document.documentElement && document.documentElement.clientHeight)
	{
			x = document.documentElement.clientWidth;
	}
	else if (document.body)
	{
			x = document.body.clientWidth;
	}
	return x;
}
 
function GetHeight()
{
	var y = 0;
	if (self.innerHeight)
	{
			y = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientHeight)
	{
			y = document.documentElement.clientHeight;
	}
	else if (document.body)
	{
			y = document.body.clientHeight;
	}
	return y;
}
function openPDF2(PDFlocation){
	
}
function openPDF(PDFlocation){	
	if($.browser.msie && parseInt($.browser.version) <7) {
		window.location = PDFlocation;
		return;
	}
	var myExistingPDFdiv=document.getElementById('dfiPDFshade');
	if(myExistingPDFdiv==null) {
		var docWidth = GetWidth();
		var docHeight = GetHeight();
	
		var shade=document.createElement('div');
		shade.setAttribute('id','dfiPDFshade');
		shade.setAttribute('style','z-index: 999999;position:fixed; top:0; left:0; width:'+docWidth+'px; height: '+docHeight+'px;display:none;background:black;background:rgba(0,0,0,0.5);filter:alpha(opacity=50)');
		
		var myPDFdiv=document.createElement('div');
		myPDFdiv.setAttribute('id', 'dfiPDFdiv');
		myPDFdiv.setAttribute('style',' display:none;position: fixed; top:0; left:0; margin: 50px;  width: '+docWidth+'px; height: '+docHeight+'px;');
		
		var myPDFborder=document.createElement('div');
		myPDFborder.setAttribute('id', 'dfiPDFborder');
		myPDFborder.setAttribute('style', 'display:none;background: #444444; width: 100%; height:100%; border: solid 10px #444444; -moz-border-radius: 10px; -webkit-border-radius: 10px; border-radius: 10px;');
		
		var myPDFframeHolder=document.createElement('div');
		myPDFframeHolder.setAttribute('id','dfiPDFframeHolder');		
		myPDFframeHolder.setAttribute('style','display:none;width:'+(docWidth-120)+'px; height:' + (docHeight-145) + 'px;clear: both;border: none;');
		
		var myPDFframe=document.createElement('iframe');
		myPDFframe.setAttribute('id','dfiPDFframe');
		myPDFframe.setAttribute('style','width:100%; height:100%;border: none;');
		
		var myPDFcontrol=document.createElement('div');
		myPDFcontrol.setAttribute('id','dfiPDFcontrol');
		myPDFcontrol.setAttribute('style','display:none;height:25px; font-family: Arial; text-decoration:underline; color:white;');
		
		var myPDFnodeCloser=document.createElement('span');
		myPDFnodeCloser.setAttribute('style','display: block;float: right; color: white; font-weight: bold; margin: 0 0px;cursor:pointer;');
		myPDFnodeCloser.setAttribute('onclick','closePDF();');
		myPDFnodeCloser.innerHTML='&laquo; Return to DataFoundations.com';
		
		var myPDFDownloader=document.createElement('span');
		myPDFDownloader.setAttribute('style','display: block;float: left; color: white; font-weight: bold; margin: 0 0px;cursor:pointer;');
		myPDFDownloader.setAttribute('onclick','downloadPDF("'+PDFlocation+'");');
		myPDFDownloader.innerHTML='Save this document';
			
		myPDFcontrol.appendChild(myPDFDownloader);
		myPDFcontrol.appendChild(myPDFnodeCloser);
		myPDFborder.appendChild(myPDFcontrol);
		myPDFframeHolder.appendChild(myPDFframe);
		myPDFborder.appendChild(myPDFframeHolder);
		myPDFdiv.appendChild(myPDFborder);
		shade.appendChild(myPDFdiv);
		document.getElementsByTagName('body')[0].appendChild(shade);
		
		$('#dfiPDFdiv').css({'left':((docWidth-120)/2)+'px'});
		$('#dfiPDFdiv').css('display','none');
		$('#dfiPDFborder').css({'display':'none','width':'40px','height':'40px'});
		$('#dfiPDFcontrol').css('display','none');
		$('#dfiPDFframeHolder').css('display','none');
		$('#dfiPDFshade').fadeIn( 500, function () {
			$('#dfiPDFdiv').fadeIn(1000);
			$('#dfiPDFborder').fadeIn(1000);
			$('#dfiPDFborder').animate({
				width: (docWidth-120)+"px"
				}, 1000);				
			$('#dfiPDFdiv').animate({
					left: "0px"
				},1000,"swing",function () {
					$('#dfiPDFdiv').animate({
						height: (docHeight-100)+"px"
					},1000);
					$('#dfiPDFborder').animate({
						height: (docHeight-120)+"px"
					},1000,"swing",function() {	
						$('#dfiPDFcontrol').fadeIn(1000);
						$('#dfiPDFframeHolder').fadeIn(1000);
						myPDFframe.setAttribute('src','http://docs.google.com/viewer?url=' + encodeURIComponent(PDFlocation) + '&embedded=true');
					});
				});
		});
	} else {
		$('#dfiPDFshade').fadeIn(500);
	}	
}
function closePDF(){
	$('#dfiPDFshade').fadeOut(500);
}
function downloadPDF(PDFlocation){
	window.open(PDFlocation);
}
 
 /*
 *	==============================================================================================================
 *		Login Popup - loginPopup.js
 *	==============================================================================================================
 */
 
 function fireMyPopup(divName) {
//Due to different browser naming of certain key global variables, we need to do three different tests to determine their values

// Determine how much the visitor had scrolled

var scrolledX, scrolledY;
if( self.pageYOffset ) {
  scrolledX = self.pageXOffset;
  scrolledY = self.pageYOffset;
} else if( document.documentElement && document.documentElement.scrollTop ) {
  scrolledX = document.documentElement.scrollLeft;
  scrolledY = document.documentElement.scrollTop;
} else if( document.body ) {
  scrolledX = document.body.scrollLeft;
  scrolledY = document.body.scrollTop;
}

// Determine the coordinates of the center of browser's window

var centerX, centerY;
if( self.innerHeight ) {
  centerX = self.innerWidth;
  centerY = self.innerHeight;
} else if( document.documentElement && document.documentElement.clientHeight ) {
  centerX = document.documentElement.clientWidth;
  centerY = document.documentElement.clientHeight;
} else if( document.body ) {
  centerX = document.body.clientWidth;
  centerY = document.body.clientHeight;
}

	var leftOffset = scrolledX + (centerX - 600) / 2;
	var topOffset = scrolledY + (centerY - 425) / 2;

	if(divName == "mypopup") {
		document.getElementById('screen').style.width = centerX + "px";
		document.getElementById('screen').style.height = centerY + "px";
		document.getElementById('screen').style.top = scrolledY + "px";
		document.getElementById('screen').style.display = "";
		leftOffset = scrolledX + (centerX/2) - 140;
		topOffset = scrolledY + (centerY/2) - 80;
	}

  document.getElementById(divName).style.top = topOffset + "px";
  document.getElementById(divName).style.left = leftOffset + "px";
  document.getElementById(divName).style.display = "block";
}

var showStatus = true;

function loginLink(divName){

	if( showStatus || (document.getElementById(divName).style.display == 'none')){
        	fireMyPopup(divName);
		showStatus = false;
	}else{
        	document.getElementById(divName).style.display = 'none';
			document.getElementById('screen').style.display = "none";
	        showStatus = true;
	}
	document.getElementById('j_username').focus();
}

 
 /*
 *	==============================================================================================================
 *		Popup - popup.js
 *	==============================================================================================================
 */
 
 var dragapproved=false
var minrestore=0
var initialwidth,initialheight
var ie5=document.all&&document.getElementById
var ns6=document.getElementById&&!document.all

function iecompattest(){
return (!window.opera && document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function drag_drop(e){
if (ie5&&dragapproved&&event.button==1){
document.getElementById("dwindow").style.left=tempx+event.clientX-offsetx+"px"
document.getElementById("dwindow").style.top=tempy+event.clientY-offsety+"px"
}
else if (ns6&&dragapproved){
document.getElementById("dwindow").style.left=tempx+e.clientX-offsetx+"px"
document.getElementById("dwindow").style.top=tempy+e.clientY-offsety+"px"
}
}

function loadwindow(url,width,height){
if (!ie5&&!ns6)
window.open(url,"","width=width,height=height,scrollbars=1")
else{
document.getElementById("dwindow").style.display=''
document.getElementById("dwindow").style.width=initialwidth=width+"px"
document.getElementById("dwindow").style.height=initialheight=height+"px"
document.getElementById("dwindow").style.left="181px"
document.getElementById("dwindow").style.top=ns6? window.pageYOffset*1+206+"px" : iecompattest().scrollTop*1+206+"px"
document.getElementById("cframe").src=url
}
}

function maximize(){
if (minrestore==0){
minrestore=1 //maximize window
document.getElementById("maxname").setAttribute("src","images/restore.gif")
document.getElementById("dwindow").style.width=ns6? window.innerWidth-20+"px" : iecompattest().clientWidth+"px"
document.getElementById("dwindow").style.height=ns6? window.innerHeight-20+"px" : iecompattest().clientHeight+"px"
}
else{
minrestore=0 //restore window
document.getElementById("maxname").setAttribute("src","images/max.gif")
document.getElementById("dwindow").style.width=initialwidth
document.getElementById("dwindow").style.height=initialheight
}
document.getElementById("dwindow").style.left=ns6? window.pageXOffset+"px" : iecompattest().scrollLeft+"px"
document.getElementById("dwindow").style.top=ns6? window.pageYOffset+"px" : iecompattest().scrollTop+"px"
}

function closeit(){
document.getElementById("dwindow").style.display="none"
}

function stopdrag(){
dragapproved=false;
document.getElementById("dwindow").onmousemove=null;
document.getElementById("dwindowcontent").style.display="" //extra
}

 /*
 *	==============================================================================================================
 *		Enlarge Image Script - enlargeimg.js
 *	==============================================================================================================
 */
 
 function enlargeImage(imageSrc, imageTitle) {
	var scrolledX, scrolledY;
	if( self.pageYOffset ) {
	scrolledX = self.pageXOffset;
	scrolledY = self.pageYOffset;
	} else if( document.documentElement && document.documentElement.scrollTop ) {
	scrolledX = document.documentElement.scrollLeft;
	scrolledY = document.documentElement.scrollTop;
	} else if( document.body ) {
	scrolledX = document.body.scrollLeft;
	scrolledY = document.body.scrollTop;
	}

	var centerX, centerY;
	if( self.innerHeight ) {
	centerX = self.innerWidth;
	centerY = self.innerHeight;
	} else if( document.documentElement && document.documentElement.clientHeight ) {
	centerX = document.documentElement.clientWidth;
	centerY = document.documentElement.clientHeight;
	} else if( document.body ) {
	centerX = document.body.clientWidth;
	centerY = document.body.clientHeight;
	}

	var leftOffset = scrolledX + (centerX - 600) / 2;
	var topOffset = scrolledY + (centerY - 425) / 2;
	var divName = "enlargeImg";

	document.getElementById('screen').style.width = centerX + "px";
	document.getElementById('screen').style.height = centerY + "px";
	document.getElementById('screen').style.display = "";
	leftOffset = scrolledX + (centerX/2) - 450;
	topOffset = scrolledY + (centerY/2) - 275;

	document.getElementById(divName).style.top = topOffset + "px";
	document.getElementById(divName).style.left = leftOffset + "px";
	document.getElementById(divName).style.display = "";

	document.getElementById("enlarged").src = imageSrc;
	document.getElementById("enlargedTitle").innerHTML = imageTitle;
}
 
/*
 *	==============================================================================================================
 *		Outbound Link Script - outboundlinktagger.js
 *	==============================================================================================================
 */

 /*
 * Outbound link tagger
 * Richard Gilchrist
 * 7/12/2010
 *
 * REQUIRES JQUERY
 *
 * This script finds outbound links and
 *  1. adds google analytics tracker to the onclick event
 *  2. forces the link to open in a new window
 */
 
$(document).ready(function() {
	var anchors = document.getElementsByTagName('a');
	for(var i=0; i< anchors.length; i++) {
		var ghn = getHostName(anchors[i].href);
		if(ghn!=document.location.hostname) {
			anchors[i].setAttribute('onclick','_gaq.push(["_trackPageview", "/outbound_links/' + getLogName(anchors[i].href,ghn) + '"]);');
			anchors[i].target="_blank";
		}
	}
});

function getLogName(href,ghn) {
	var i = href.indexOf(ghn);
	if(i>=0) return href.substr(i);
	else return href;
}

function getHostName(href) {
	if(href.length >= 3) {
		if(href.substr(0,4)=="http") {
			var chkstr = "://";
			var stpos = href.indexOf(chkstr);
			if(stpos > 0) {
				stpos += chkstr.length;
				chkstr = href.substr(stpos);
				stpos = chkstr.indexOf(":");
				if(stpos > 0) {
					return chkstr.substr(0,stpos);
				} else {
					stpos = chkstr.indexOf("/");
					if(stpos > 0) {
						return chkstr.substr(0,stpos);
					} else {
						return chkstr;
					}
				}
			}
			else return document.location.hostname;
		}
		else return document.location.hostname;
	}
	else return document.location.hostname;
}
 
/*
 *	==============================================================================================================
 *		News Script - news.js
 *	==============================================================================================================
 */

var xmlDataSource = '/rss.xml';
var ajaxNewsObj;
var newsXml;
var afterLoadCallback;
var afterLoadCallbackVar;

function xmlVal(xparent, xnode) {
	var x = xparent.getElementsByTagName(xnode);
	if(xnode.indexOf(":") > -1 && document.getElementsByTagNameNS !== undefined) {
		x = xparent.getElementsByTagNameNS('*',xnode.substr(xnode.indexOf(":")+1));
	}
	if(x.length < 1) return "";
	x = x[0].childNodes;
	if(x.length < 1) return "";
	return x[0].nodeValue;
}

function parseXml() {
	var newsItems = newsXml.getElementsByTagName('item');
	for(var i = 0; i < newsItems.length; i++) {
		addNews( new newsItem(
			xmlVal(newsItems[i],'dfi:type'),
			xmlVal(newsItems[i],'dfi:startdate'),
			xmlVal(newsItems[i],'dfi:enddate'),
			xmlVal(newsItems[i],'dfi:loc'),
			xmlVal(newsItems[i],'link'),
			xmlVal(newsItems[i],'title'),
			xmlVal(newsItems[i],'description'),
			"",
			"",
			xmlVal(newsItems[i],'dfi:img')
			));
	}
	if(afterLoadCallbackVar && afterLoadCallbackVar!=null && afterLoadCallbackVar!=0)
		afterLoadCallback(afterLoadCallbackVar);
	else
		afterLoadCallback();
}

function onAjaxNewsObjFinished() {
	if(ajaxNewsObj.readyState==4) {
		newsXml=getXml(ajaxNewsObj.responseText);
		parseXml();
	}
}

function loadNews2() {	
	ajaxNewsObj = getXmlHttpObject();
	if(!ajaxNewsObj) return;
	ajaxNewsObj.onreadystatechange=onAjaxNewsObjFinished;
	ajaxNewsObj.open("GET", xmlDataSource, true);
	ajaxNewsObj.send();
}
function getXmlHttpObject(){
	if (window.XMLHttpRequest) return new XMLHttpRequest();
	if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
	alert('Operation Aborted: Your browser does not support AJAX.');
	return null;
}

function getXml(txt) {
	var xmlDoc;
	if (window.DOMParser) {
		parser=new DOMParser();
		xmlDoc=parser.parseFromString(txt,"text/xml");
	}
	else {
		xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async="false";
		xmlDoc.loadXML(txt);
	}
	return xmlDoc;
}


function addNews(myNewsItem) {
	myNewsItems.push(myNewsItem);
	maxYear = Math.max(maxYear,myNewsItems[myNewsItems.length - 1].date.getFullYear());
	minYear = Math.min(minYear,myNewsItems[myNewsItems.length - 1].date.getFullYear());
	return;
	alert('Added News:' +
		'\nType of news: ' + myNewsItem.type +
		'\nStart Date: ' + myNewsItem.date +
		'\nEnd Date: ' + myNewsItem.enddate +
		'\nDuration: ' + myNewsItem.duration +
		'\nLocation: ' + myNewsItem.loc +
		'\nURL for News Headline Link: ' +myNewsItem.myHref +
		'\nText for News Headline Link: ' +myNewsItem.myLinktext +
		'\nDescription Text: ' +myNewsItem.desc +
		'\nURL for Description Text Link: ' +myNewsItem.content_href +
		'\nText for Description Text Link: ' +myNewsItem.content_linktext +
		'\nYear: ' +myNewsItem.year);
}

var myNewsItems = new Array();
var maxYear = 0, minYear = 9999;

var month=new Array(12);
month[0]="January";
month[1]="February";
month[2]="March";
month[3]="April";
month[4]="May";
month[5]="June";
month[6]="July";
month[7]="August";
month[8]="September";
month[9]="October";
month[10]="November";
month[11]="December";

var newsTickerTime = 5000;
var newsTicker_i = -1;
var newsTickerLimit = 0;

function printNewsTicker(howMany) {
	newsTickerLimit = howMany;
	document.write('<div id="dfinews"></div>');
	$("#dfinews").append('<span id="dfinewsText"></span>');
	afterLoadCallback=newsTickerAdvance;
	loadNews2();
}

function newsTickerAdvance(){
	if( myNewsItems.length <= 0 ||  myNewsItems.length == null ||  myNewsItems.length === undefined) return;
	$("#dfinewsText").fadeOut(750, function(){
		$("#dfinewsText").empty();
		newsTicker_i++;
		if(newsTicker_i >= myNewsItems.length || newsTicker_i >= newsTickerLimit) newsTicker_i = 0;
		$("#dfinewsText").append(myNewsItems[newsTicker_i].printTicker());
		$("#dfinewsText").fadeIn(750, function(){
			setTimeout('newsTickerAdvance()',newsTickerTime);
		});
	});
}

function printNews(howMany) {
	document.write('<div id="newscontent"></div>');
	afterLoadCallback=printNewsAsync;
	afterLoadCallbackVar=howMany;
	loadNews2();
}

function printNewsAsync(howMany) {
	var newscontent = document.getElementById('newscontent');
	newscontent.innerHTML = '<table width="100%" border="0" cellspacing="0" cellpadding="0"><tr><td style="padding:3px 0 10px 10px; color: #222222"><b>Latest News &amp; Events</b><br/></td></tr>';
	for(i = 0; i < myNewsItems.length && i < howMany; i++) {
		if(i%2==0)
			newscontent.innerHTML += '<tr><td style="background: #f5f5f5; border-top: dotted 2px #e5e5e5; padding: 3px 10px;" valign="top"><div style="text-align: right; padding: 2px 0; float:left;"><span class="bullet">&raquo;</span></div><div style="padding: 4px 0; width:90%; float: right;"><a href="' + myNewsItems[i].href + '" class="ashlink" title="' + getShortTitle(myNewsItems[i].desc) + '">' + myNewsItems[i].linktext + '</a></div></td></tr>';
		else
			newscontent.innerHTML += '<tr><td style="background: #ffffff; border-top: dotted 2px #e5e5e5; padding: 3px 10px;" valign="top"><div style="text-align: right; padding: 2px 0; float:left;"><span class="bullet">&raquo;</span></div><div style="padding: 4px 0; width:90%; float: right;"><a href="' + myNewsItems[i].href + '" class="ashlink" title="' + getShortTitle(myNewsItems[i].desc) + '">' + myNewsItems[i].linktext + '</a></div></td></tr>';
	}
	newscontent.innerHTML +='<tr><td style="padding:3px 0 3px 10px; text-align: right;" ><a href="news_index.jsp" class="orglinkN">More News &raquo;</a></td></tr></table>';
}

function getShortTitle(desc) {
	if(desc.length<=100) return desc;
	else return desc.substr(0,80) + '&#8230; (Click to read more)';
}

function printNewsPage() {
	document.write('<div id="newscontent" style="float:left; text-align: left;width:89.5%;"></div><div id="yearlist" style="float:right; width:10%;text-align:left;"></div>');
	var search1 = location.search;
	if(search1.length > 1) {
		search1 = search1.substr(1);
		var search2 = search1.split("&");
		for(var i = 0;i < search2.length; i++)
		{
			if(search2[i].split("=")[0]=='dfinews')
			{
				var newsType = search2[i].split("=")[1];
				if(newsType.length > 1) {
					afterLoadCallback=printNewsPageAsync;
					afterLoadCallbackVar=newsType;
					loadNews2();
					return;
				} 
			}	
		}	
	}
	afterLoadCallback=printNewsByYear;
	loadNews2();
}

function printNewsPageAsync(newsType) {
	yearList();
	if(newsType=='press') {
		printNewsType('Press Release');
		return;
	} else if(newsType=='event') {
		printNewsType('Event');
		return;
	} else if(newsType=='news') {
		printNewsType('News');
		return;
	} else if(IsNumeric(newsType)) {
		changeYear(newsType);
		return;
	}
}

function IsNumeric(sText)
{
	var ValidChars = "0123456789.";
	var IsNumber=true;
	var Char;
	
	for (i = 0; i < sText.length && IsNumber == true; i++) 
	{ 
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1) 
		{
			IsNumber = false;
		}
	}
	
	return IsNumber;
}

function printNewsType(newsType) {
	var newscontent = document.getElementById('newscontent');
	if(!newscontent || newscontent == null) return true;
	var printed = 0;
	var itemsToPrint = '<h2>Viewing all ' + newsType + ' items:</h2>';
	for(i = 0; i < myNewsItems.length; i++) {
		if(myNewsItems[i].type == newsType) {
			printed++;
			itemsToPrint += myNewsItems[i].printNewsItem(printed%2);
		}
	}
	newscontent.innerHTML = itemsToPrint;
}

function printNewsByYear() {
	yearList();
	changeYear((new Date()).getFullYear());	
}

function changeYear(changeToYear) {
	var printed = 0;
	var itemsToPrint = '<h2>&nbsp;News &amp; Events for ' + changeToYear + ':</h2>';
	for(i = 0; i < myNewsItems.length; i++) {
		if(myNewsItems[i].year == changeToYear) {
			printed++;
			itemsToPrint += myNewsItems[i].printNewsItem(printed%2);
		}
	}
	document.getElementById('newscontent').innerHTML = itemsToPrint;
}

function yearList() {
	var yearlist = document.getElementById('yearlist');
	var myOutput = '<h2 style="display:block; width: 100%; text-align: center;">Year:</h2><ul style="margin: 0; padding: 0; list-style: none;">';
	for(i = maxYear; i >= minYear; i--) {
		myOutput += '<li><a style="text-decoration:none;display:block; margin: 3px 0; padding: 2px; border: solid 1px #cccccc; background: #eeeeee; text-align: center; cursor:pointer; font-weight:bold; color: #333333; -moz-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px; letter-spacing: normal;" onmouseover="this.style.color=\'black\';this.style.background=\'#cccccc\'; this.style.letterSpacing=\'1px\';" onmouseout="this.style.color=\'#333333\';this.style.background=\'#eeeeee\';this.style.letterSpacing=\'normal\';" href="/news_index.jsp?dfinews='+i+'">' + i + '</a></li>';
	}
	myOutput += '</ul></div>';
	yearlist.innerHTML = myOutput;
}

function newsItem(myType, myDate, myEnddate, myLoc, myHref, myLinktext, myDesc, myHref2, myLinktext2, myImg) {
	this.type = myType;
	this.duration = 0;
	this.date = new Date(myDate);
	if(myEnddate != '') {
		this.enddate = new Date(myEnddate);
		this.duration = 1;
	}
	this.loc = myLoc;
	this.href = myHref;
	this.linktext=myLinktext;
	this.desc=myDesc; 
	this.content_href=myHref2;
	this.content_linktext=myLinktext2;
	this.year = this.date.getFullYear();
	this.img=myImg;
	
	this.printTicker = function() {
		var returnMe = '<a class="dfinewslink" href="' + this.href + '">' + this.linktext + '</a>';
		return returnMe;
	}
	
	this.printNewsItem = function(isOdd) {
		var myBG = "#ffffff";
		if(isOdd==0) myBG = "#f5f5f5";
		var returnMe = '<table border="0" cellpadding="5" cellspacing="0" style="width:98%; padding: 5px; margin: 0px 0; border-bottom: solid 1px #dddddd; border-top: solid 1px #dddddd; background: ' + myBG + ';">' +
							'<tr>' +
								'<td ' + ((this.img.length > 0)?(''):('colspan="2"')) + ' style="vertical-align:top;">'+
									'<p style="margin-top: 0;">' +
										'<a href="' + this.href + '" class="orglinkN" style="font-size: 14px; font-weight:bold;">' + 
											this.linktext + 
										'</a>' +
										'<br />' +
										'<br />' +
										'<span>'+
											this.desc +
										'</span>' +
									'</p>' +
								'</td>' +
								((this.img.length > 0)?('<td style="padding: 10px;width:150px;"><img width="150" src="'+this.img+'" /></td>'):(''))+
							'</tr>' +
							'<tr>' +
								'<td colspan="2" style="border-bottom: solid 1px #bbbbbb; margin: 0; padding: 0;">' +
									'<p style="margin-top:5px;text-align:right;">' +
										'<a href="' + ((this.content_linktext.length > 0)?(this.content_href + '" class="orglinkN">' + this.content_linktext):(this.href + '" class="orglinkN">Read More')) + '&nbsp;&raquo</a>' +
									'</p>' +
								'</td>' + 
							'</tr>' +
							'<tr>' +
								'<td style="font-size: 9px; text-style: italics; color: #666666;">' +
									((this.loc.length > 0)?(this.loc + ' - '):('')) + this.displayDate() +
								'</td>' +
								'<td style="font-size: 9px; text-style: italics; color: #666666; text-align: right; whitespace: nowrap;">' +
									'Filed under ' + this.getFileLink() +
								'</td>' +
							'</tr>' +
						'</table>';
		
		return returnMe;
	}
	
	this.displayDate = function() {
		var returnMe = month[this.date.getMonth()] + ' ' + this.date.getDate();
		if(this.duration > 0) {
			if(this.date.getMonth() == this.enddate.getMonth()) {
				returnMe += '-' + this.enddate.getDate() + ', ' + this.enddate.getFullYear();
			} else {
				returnMe += ' - ' + month[this.enddate.getMonth()] + ' ' + this.enddate.getDate() + ', ' + this.enddate.getFullYear();
			}
		} else {
			returnMe += ', ' + this.date.getFullYear();
		}
		return returnMe;
	}
	
	this.getFileLink = function() {
		var returnMe = '';
		if(this.type == "News") {
			returnMe = '<a href="/news_index.jsp?dfinews=news" class="orglinkN" style="font-size: 9px;">News</a>';
		} else if(this.type == "Press Release") {
			returnMe = '<a href="/news_index.jsp?dfinews=press" class="orglinkN" style="font-size: 9px;">Press Releases</a>';
		} else if(this.type == "Event") {
			returnMe = '<a href="/news_index.jsp?dfinews=event" class="orglinkN" style="font-size: 9px;">Events</a>';
		} else {
			returnMe = this.type + ((this.type.substr(this.type.length -1)=='s') ? '' : 's');
		}
		returnMe += ', <a href="/news_index.jsp?dfinews=' + this.date.getFullYear() + '" class="orglinkN" style="font-size: 9px;">' + this.date.getFullYear() + '</a>';
		return returnMe;
	}
}
 
 
/*
 *	==============================================================================================================
 *		Tab Box Script - dfitab.js
 *	==============================================================================================================
 */

 /*	
 *	DFI Tab Box Script
 *	Feb 16, 2010
 *	Richard Gilchrist
 *
 *	Usage:
 *	----------------------
 *	<link rel="stylesheet" type="text/css" href="/<style_directory>/dfitab.css" />
 *	<script type="text/javascript" src="/<script_directory>/dfitab.js"></script>
 *	<div id="outer_div_ID">
 *		<div id="div1_ID" title="Tab1" class="dfitab_Div">
 *			This is where Div1 content goes
 *		</div>
 *		<div id="div2_ID" title="Tab2" class="dfitab_Div">
 *			This is where Div2 content goes
 *		</div>
 *		<div id="div3_ID" title="Tab3" class="dfitab_Div">
 *			This is where Div3 content goes
 *		</div>
 *	</div>
 *	<script type="text/javascript">
 *		dfitab.init({
 *			maincontainer: "outer_div_ID", // ID of the div where the tab group will be built
 *			behavior: "click" //  when to switch tab -"click" or "mouseover"
 *		})
 *	</script>
 *	----------------------
 */
 var dfitab_instances = new Array()
 var dfitab_defaultCssUrl='/css/dfitab.css'
	
 
 function tabObj(settings) {
		
		this.buildtabs=function(){
			this.outerdiv.className='dfitab'
			var tabStr=''
			tabStr='<div class="dfitab_container"><ul>'
			for(i=0;i<this.divs.length;i++){
				tabStr+='<li id="dfitab_'+i+'-'+this.instanceID+'" class="dfitab_'+(i>0?'in':'')+'active"><span on'+this.behavior+'="dfitab.switchTab('+i+','+this.instanceID+')">'+this.divs[i].tabName+'</span></li>'
				this.divs[i].tabID='dfitab_'+i
			}
			tabStr+='</ul></div>'+this.originalHTML
			this.outerdiv.innerHTML=tabStr
		},
		
		this.init=function(settings){
			this.instanceID = settings.instanceID
			this.outerdiv=document.getElementById(settings.maincontainer)
			this.behavior=settings.behavior
			this.originalHTML=this.outerdiv.innerHTML
			this.divs=new Array()
			var divObjs=this.outerdiv.getElementsByTagName('div')
			for(i=0;i<divObjs.length;i++){
				if(divObjs[i].className=='dfitab_Div'){
					var newDiv=new Object()
					newDiv.divID=divObjs[i].attributes.getNamedItem('id').value
					newDiv.tabName=divObjs[i].attributes.getNamedItem('title').value
					this.divs.push(newDiv)
				}
			}
			this.buildtabs()
			for(i=0;i<this.divs.length;i++){
				document.getElementById(this.divs[i].divID).className='dfitab_'+(i>0?'in':'')+'active_div'
			}
		},
		
		this.init(settings)
	}
 
 var dfitab={	 
	
	setCSS:function(cssUrl){
		if(cssUrl===undefined) cssUrl = dfitab_defaultCssUrl
		var headtg = document.getElementsByTagName('head')[0]
		if (!headtg) {
			return
		}
		var linktg = document.createElement('link')
		linktg.type = 'text/css'
		linktg.rel = 'stylesheet'
		linktg.href = cssUrl
		headtg.appendChild(linktg)
	},
	
	switchTab:function(num, instance){
		for(i=0;i<dfitab_instances[instance].divs.length;i++){
			document.getElementById(dfitab_instances[instance].divs[i].divID).className='dfitab_'+(i!=num?'in':'')+'active_div'
			document.getElementById(dfitab_instances[instance].divs[i].tabID + '-' + instance).className='dfitab_'+(i!=num?'in':'')+'active'
		}
	},
	
	switchTabById:function(myDivId){
		for(i=0;i<dfitab_instances.length;i++){
			for(j=0;j<dfitab_instances[i].divs.length;j++){
				if(dfitab_instances[i].divs[j].divID == myDivId) {
					dfitab.switchTab(j,i);
					return true;
				}
			}
		}
	},
	
	instancereport:function(){
		
		returnme="Instance Array Report"
		for(j=0;j<dfitab_instances.length;j++) {
			mytab = dfitab_instances[j]		
			returnme += "\n--------------------------------------------------------------"
			returnme += "\ninstance: " + j	
			returnme += "\nouter div: " + mytab.outerdiv
			returnme += "\nbehavior: " + mytab.behavior
			returnme += "\n"
			returnme += "\ndiv count: " + mytab.divs.length
			returnme += "\n-------------------------------"
			for(i=0;i<mytab.divs.length;i++){
				returnme += "\ndiv index: " + i
				returnme += "\ndivID: " + mytab.divs[i].divID
				returnme += "\ntabID: " + mytab.divs[i].tabID
				returnme += "\ntabName: " + mytab.divs[i].tabName
				returnme += "\n"
			}
		}
		alert(returnme)
	},
	
	diagnostic:function(settings){
		
		mytab = dfitab_instances[settings.instanceID]
		
		returnme = "Diagnostic report"
		returnme += "\n--------------------------------------------------------------"
		returnme += "\ninstance: " + settings.instanceID
		returnme += "\nouter div: " + mytab.outerdiv
		returnme += "\nbehavior: " + mytab.behavior
		returnme += "\n"
		returnme += "\ndiv count: " + mytab.divs.length
		returnme += "\n--------------------------------------------------------------"
		
		for(i=0;i<mytab.divs.length;i++){
			returnme += "\ndiv index: " + i
			returnme += "\ndivID: " + mytab.divs[i].divID
			returnme += "\ntabID: " + mytab.divs[i].tabID
			returnme += "\ntabName: " + mytab.divs[i].tabName
			returnme += "\n"
		}
		alert(returnme)
		dfitab.instancereport()
	},
	
	init:function(settings) {
		this.setCSS(settings.css);
		settings.instanceID = dfitab_instances.length
		dfitab_instances.push(new tabObj(settings))
		if(settings.diagnosticOutput)
			dfitab.diagnostic(settings)
		var switchToTab = location.hash;
		if(switchToTab != null && switchToTab.length > 0) {
			if(switchToTab.substr(0,8) != "#dfitab:") return true;
			dfitab.switchTabById(switchToTab.substr(8));
		}
	}
 }
 
 
/*
 *	==============================================================================================================
 *		Ajax Submission Scripts - dfiAjaxSubmit.js
 *	==============================================================================================================
 */

 /*
 * Generic AJAX Form Submission, Validation, and Form Builder Routine
 * ------------------------------------------------------------------
 *                       SUBMISSION ROUTINE
 * ------------------------------------------------------------------
 */

var ajaxItem = null;
var handleResponse = null;
var submitCallback = null;
var thisFormId = null;
var default_x = null;
var default_y = null;
var debugOn = false;
var dfiAjaxSubmit_LastResponse = '';
var $errClass='dfiFormErrorField';
var elqPost = "elqPost", ignore = "ignore";
var fieldMap = [
	["firstName","C_FirstName", elqPost],
	["lastName","C_LastName", elqPost],
	["email","C_EmailAddress", elqPost],
	["phone","C_BusPhone", elqPost],
	["organization","C_Company", elqPost],
	["title","C_Title", elqPost],
	["contactMeASAP","C_Contact_Requested1", elqPost],
	["elqFormName","elqFormName", ignore],
	["elqSiteID","elqSiteID", ignore],
	["formId","formId", ignore],
	["State_Province","C_State_Prov", elqPost],
	["Country","C_Country", elqPost],
	["Industry","C_Industry21", elqPost],
	["BusinessLevel","C_Business_Level1", elqPost]
];
var elqMsgField = ["your_message","C_Lead_Detailed_Comments1"];

//Submits a form by posting to the 'submit.form' service
//formID is the id of the form to submit
//myCallback is the function to call when the roundtrip ajax call is finished
//myCallback should accept 1 parameter, which is the responseText of the XmlHttp object
function ajaxSubmit(formID, myCallback) {
	if(formValidated(formID)) {
		showPleaseWait(true);
		ajaxItem = GetXmlHttpObject();
		if (!ajaxItem) return;
		handleResponse = myCallback;
		thisFormId = formID;
		ajaxItem.onreadystatechange = stateChanged;
		//alert('POST: /submit.form?' + buildQuery(formID));
		ajaxItem.open("POST", '/submit.form?' + buildQuery(formID), true);
		ajaxItem.send(null);
		return true;
	}
	return false;
}

//handles cross-browser XmlHttp object generation
function GetXmlHttpObject() {
	if (window.XMLHttpRequest) return new XMLHttpRequest();
	if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
	alert('Operation Aborted: Your browser does not support AJAX.');
	return null;
}

//searches the document for a form with the id specified,
//then builds a query based on INPUT and SELECT object in that form
function buildQuery(formID) {
	var myVars = '';
	var myForms = document.getElementsByTagName('form');
	for(i = 0; i < myForms.length; i++) {
		if(myForms[i].id == formID) {
			var myInputs = myForms[i].elements;
			for(j = 0; j < myInputs.length; j++) {
				myVars += parseInput(myInputs[j]);
			}
		}
	}
	
	myVars += expandForEloqua(myVars);

	return myVars.substring(1); //removes leading ampersand (&)
}

//expands input so that it meets criteria for submission to SoftwareAG's Eloqua server
function expandForEloqua(myVars) {
	var myVarsArray = myVars.substring(1).split('&');
	var myVars2 = '', tempVarName = '', tempVarValue = '', tempMsg = '', tempOtherFields='';
	var foundMatch = false;
	for(i=0;i<myVarsArray.length;i++) {
		foundMatch=false;
		tempVarName = myVarsArray[i].split('=')[0];
		tempVarValue = decodeURIComponent(myVarsArray[i].split('=')[1]);
		for(fm=0;fm<fieldMap.length;fm++) {
			if( tempVarName == fieldMap[fm][0]) {
				if(fieldMap[fm][2]==elqPost) {
					myVars2 += '&' + fieldMap[fm][1] + '=' + encodeURIComponent(tempVarValue);
				}
				foundMatch=true;
			}
		}
		if(!foundMatch) {
			if(tempVarName == elqMsgField[0])
				tempMsg = tempVarValue;
			else
				tempOtherFields += '\n\n' + tempVarName + ': ' + tempVarValue;
		}
	}	
	myVars2 += '&' + elqMsgField[1] + '=Message: ' + encodeURIComponent(tempMsg + tempOtherFields);
	return myVars2;
}

//parses the value from an INPUT or SELECT object
//returns a string that is either
//empty in the case that the object was filtered (for submit, reset, and button types),
//or an id/value pair which is
//selected from an option list (for select types),
//taken directly from the object value (for anything else).
//only picks up checkbox and radio values if the option is checked
function parseInput(inputField) {
	if(inputField.type != 'submit' && inputField.type != 'reset' && inputField.type != 'button' && inputField.id && inputField.value) {
		if(inputField.type == 'text' || inputField.type == 'textarea' || inputField.type == 'hidden' || inputField.type == 'password') {
			return '&' + inputField.id + '=' + encodeURIComponent(inputField.value);
		}
		else if((inputField.type == 'checkbox' || inputField.type == 'radio')&& inputField.checked) {
			return '&' + inputField.id + '=' + encodeURIComponent(inputField.value);
		}
		else if(inputField.type == 'select-one')  {
			return '&' + inputField.id + '=' + encodeURIComponent(inputField.options[inputField.selectedIndex].value);
		}
		else if(inputField.type == 'select-multiple')  {
			var selectedOptions = '';
			for(i = 0; i < inputField.options.length; i ++) {
				if(inputField.options[i].selected) {
					selectedOptions += '&' + inputField.id + '=' + encodeURIComponent(inputField.options[i].value);
				}
			}
			return selectedOptions;
		}
	}
	return '';
}

//checks the readyState of the XmlHttp object when it is changed
//a readyState of 4 indicates that the post has made it round-trip
//and that a response awaits in the XmlHttp object's responseText attribute
function stateChanged() {
	if (ajaxItem.readyState == 4) {
		dfiAjaxSubmit_LastResponse = ajaxItem.responseText;
		setTimeout('showPleaseWait(false)',500);
		defaultHandler(ajaxItem.responseText);
	}
}

//parses the success code & passes to callback
 function defaultHandler(response) {
	var x = response.split("&");
	var success = null;
	var msg = null;
	var myForms = document.getElementsByTagName('form');
	
	for (i = 0; i < x.length; i++) {
		if(x[i].split("=")[0] == "success") {
			success = x[i].split("=")[1];
		}
		if(x[i].split("=")[0] == "msg") {
			msg = x[i].split("=")[1];
		}
	}
	if(debugOn) {
		alert(success);
		alert(msg);
	}
	if(handleResponse == defaultHandler) {//check if submit call indicated default handling. if not, handle with provided handler
		for(i = 0; i < myForms.length; i++) {
			if(myForms[i].id == thisFormId) {
				var formHeight = $("#"+thisFormId).height();
				myForms[i].innerHTML = (success=="0") ? ('<div style="height: '+formHeight+';text-align: center;width: ' + default_x + ';padding-top: ' + default_y + ';font-family:Arial, Helvetica, sans-serif;font-size:15px;font-weight:bold;color:#333333;">Thank you!</div>') : ('<div style="height: '+formHeight+';text-align: center;width: ' + default_x + ';padding-top: ' + default_y + ';font-family:Arial, Helvetica, sans-serif;font-size:15px;font-weight:bold;color:#333333;">Your request could not be completed.</div>');
			}
		}
	} else {
		handleResponse(success);
	}
	if(submitCallback != null)
		submitCallback();
 }
 
 function showPleaseWait(show) {
	if(show) {
		$("#screen").empty();
		$("#screen").append('' +
			'<table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0">' +
				'<tr>' +
					'<td valign="middle" align="center">' +
						'<div style="width:200px; height:110px;border: solid 1px #444444; background:white; text-align: center;">'+
							'<p style="background:#6666cc;text-align: left; padding: 3px; color: white;margin:0; font-weight:bold;">' +
								'DataFoundations.com'+
							'</p>'+
							'<p style="background:#ffffff;text-align: center;padding: 10px;margin:0;">' +
								'<img src="/images/page_loading_ani.gif" />'+
								'<br />'+
								'<span style="font-weight: bold; font-style: italics;font-family: Trebuchet MS; font-size: 16px; color: #1c4165;">Please Wait...</span>'+
							'</p>'+
						'</div>'+
					'</td>' +
				'</tr>' +
			'</table>' +
		'');
		$("#screen").width($(document).width());
		$("#screen").height($(document).height());
		$("#screen").fadeIn(250);
	}else{		
		$("#screen").fadeOut(250, function(){
			$("#screen").empty();
			$("#screen").css('display','none');
		});
	}
 }
 
 function showValidationAlert(show,msg) {
	if(show) {
		$("#screen").empty();
		$("#screen").append('' +
			'<table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0">' +
				'<tr>' +
					'<td valign="middle" align="center">' +
							'<table border="0" cellpadding="0" cellspacing="0" style="width:300px; border: solid 1px #444444; background:white; text-align: left;">'+
								'<tr>'+
									'<td style="background:#3333cc;text-align: left; padding: 3px; color: white;margin:0; font-weight:bold;">' +
										'Required Fields Missing!'+
									'</td>'+
								'</tr>'+
								'<tr>'+
									'<td style="background:#ffffff;text-align: left;padding: 10px;margin:0;">' +
										'<span style="font-weight: bold; font-family: Trebuchet MS; font-size: 12px; color: black;">'+
										msg+
										'</span>'+
									'</td>'+
								'</tr>'+
								'<tr>'+
									'<td style="background:#ffffff;text-align: right;padding: 10px;margin:0;">' +
										'&nbsp;' +
										'<div style="float:right;width: 50px; text-align:center;padding:3px; cursor:pointer; border: solid 1px #444444; background: #dddddd; color:black;" onclick="showValidationAlert(false,\'\')" onmouseover="this.style.background=\'#f5f5f5\'" onmouseout="this.style.background=\'#dddddd\'">OK</div>'+
									'</td>'+
								'</tr>'+
							'</table>'+
					'</td>' +
				'</tr>' +
			'</table>' +
		'');
		$("#screen").width($(document).width());
		$("#screen").height($(document).height());
		$("#screen").fadeIn(250);
	}else{		
		$("#screen").fadeOut(250, function(){
			$("#screen").empty();
			$("#screen").css('display','none');
			if (!$.browser.msie || ($.browser.msie && $.browser.version.substr(0,1)>=7)) {
				$("input."+$errClass+":first").focus();
			}
		});
	}
 
 }
 
//allows user to use default handling, which simply replaces the form content with a default response message.
//specifies x and y to determine width/height for response
function useDefault(x,y,customCallback) {
	default_x = x;
	default_y = y;
	if(customCallback !== null)
		submitCallback = customCallback;
	return defaultHandler;
}
 
/*
 * ------------------------------------------------------------------
 *                       DOM ONREADY ROUTINE
 * ------------------------------------------------------------------
 */
 
 $(document).ready( function(){
	var $abbr='<abbr title="This Field is Required">*</abbr>';
	$('fieldset form ol li input.nonblank').before($abbr);
	$('fieldset form ol li input.phone').before($abbr);
	$('fieldset form ol li input.email').before($abbr);
	$('fieldset form ol li select.mustselect').before($abbr);
	if (!$.browser.msie || ($.browser.msie && $.browser.version.substr(0,1)>=7)) {
		$('fieldset form ol li input:first').focus();
	}
 });
 
/*
 * ------------------------------------------------------------------
 *                       VALIDATION ROUTINE
 * ------------------------------------------------------------------
 */
  
function formValidated(formID) {
	var errMsg = '';
	var myForms = document.getElementsByTagName('form');
	for(i = 0; i < myForms.length; i++) {
		if(myForms[i].id == formID) {
			var myInputs = myForms[i].elements;
			for(j = 0; j < myInputs.length; j++) {
				//if(errMsg == '') myInputs[j].focus(); // Causes errors in IE. Stops the submit during validation, and nothing makes it to POST.
				
				errMsg += checkValid(myInputs[j]);
			}
		}
	}
	if(errMsg == '') return true;
	showValidationAlert(true,'Please fill in or correct the following fields:<ul style="text-align:left;">' + errMsg + '</ul>');
	return false;
}

function checkValid(field) {
	var error = '';
	if(field.className) {
		var myClassNames = field.className.split(' ');
		for(i = 0; i < myClassNames.length; i++) {
			if(myClassNames[i] == 'phone') {
				if( field.value == ''){
					$("#"+field.id).addClass($errClass);
					//alert("Phone Validation 1: $(#"+field.id+").addClass("+$errClass+");");
					error = '<li>' + field.alt + '</li>';
				}else {
					$("#"+field.id).removeClass($errClass);
				}
			} else if(myClassNames[i] == 'email') {
				if( field.value == ''){
					$("#"+field.id).addClass($errClass)
					//alert("Email Validation 1: $(#"+field.id+").addClass("+$errClass+");");
					error = '<li>' + field.alt + '</li>';
				}else if(!validate_email(field.value)){
					$("#"+field.id).addClass($errClass)
					//alert("Email Validation 2: $(#"+field.id+").addClass("+$errClass+");");
					error = '<li>' + field.alt + '</li>';
				}else {
					$("#"+field.id).removeClass($errClass);
				}
			} else if(myClassNames[i] == 'nonblank') {
				if( field.value == ''){
					$("#"+field.id).addClass($errClass)
					//alert("Nonblank Validation 1: $(#"+field.id+").addClass("+$errClass+");");
					error = '<li>' + field.alt + '</li>';
				}else {
					$("#"+field.id).removeClass($errClass);
				}
			} else if(myClassNames[i] == 'mustselect') {
				if( field.selectedIndex <= 0 ){
					$("#"+field.id).addClass($errClass)
					error = '<li>' + field.getAttribute('alt') + '</li>';
				}else {
					$("#"+field.id).removeClass($errClass);
				}
			}
		}
	}
	return error;
}

function validate_email(value) {
	 apos=value.indexOf("@");
	 dotpos=value.lastIndexOf(".");
	 if (apos<1||dotpos-apos<2)
	 {
	   return false;
	 } else {
	   return true;
	 }

}
 
 
/*
 *	==============================================================================================================
 *		Chat Scripts - dfichat.js
 *	==============================================================================================================
 */

/*
 *	DFI Chat Script
 *	June 14, 2010
 *	Richard Gilchrist
 *
 *	Usage:
 *	----------------------
 *	<script type="text/javascript" src="/<script_directory>/dfichat.js"></script>
 *  <x onclick="dfiChatInit();" />
 *	----------------------
 */

var chatId='';
var chatter='';
var lastMsgId=0;
var ajaxObj;
var ajaxAdminObj;
var ajaxAdminAlertObj;
var ajaxSendChatObj;
var ajaxCheckChatObj;
var ajaxJoinChatObj;
var divScroll;
var chatInput;
var chatDiv;
var chatterCount = 0;
var joinTimeout=60000;
var checkVar;
var checkTime=250;
var chatAdminDiv;
var isAdmin=false;
var serv='Server';
var push='::push:: ';
var close='::close::';
var pushWindow;

var chatscroll = new Object();

  chatscroll.Pane = function(scrollContainerId){
    this.bottomThreshold = 100;
    this.scrollContainerId = scrollContainerId;
    this._lastScrollPosition = 100000000;
  }

  chatscroll.Pane.prototype.activeScroll = function(){

    var _ref = this;
    var scrollDiv = document.getElementById(this.scrollContainerId);
    var currentHeight = 0;

    var _getElementHeight = function(){
      var intHt = 0;
      if(scrollDiv.style.pixelHeight)intHt = scrollDiv.style.pixelHeight;
      else intHt = scrollDiv.offsetHeight;
      return parseInt(intHt);
    }

    var _hasUserScrolled = function(){
      if(_ref._lastScrollPosition == scrollDiv.scrollTop || _ref._lastScrollPosition == null){
        return false;
      }
      return true;
    }

    var _scrollIfInZone = function(){
      if( !_hasUserScrolled ||
		  (currentHeight - scrollDiv.scrollTop - _getElementHeight() <= _ref.bottomThreshold)){
		  if($('#'+scrollDiv.id+':animated').length > 0) {
			$('#'+scrollDiv.id+':animated').stop();
			$('#chatDiv p').css({'display':'','opacity':'1','filter':''});
		  }
		  $('#'+scrollDiv.id).animate({
			scrollTop: currentHeight
		  }, 1000);
		  $('#chatDiv p:last').css('display','none').fadeIn(500);
		  _ref._isUserActive = false;
      }
    }


    if (scrollDiv.scrollHeight > 0)currentHeight = scrollDiv.scrollHeight;
    else if(scrollDiv.offsetHeight > 0)currentHeight = scrollDiv.offsetHeight;

    _scrollIfInZone();

    _ref = null;
    scrollDiv = null;

  }
  
function getXmlHttpObject(){
	if (window.XMLHttpRequest) return new XMLHttpRequest();
	if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
	alert('Operation Aborted: Your browser does not support AJAX.');
	return null;
}

function onInitFinished(){
	if (ajaxObj.readyState == 4) {
		chatId=ajaxObj.responseText;
		onAfterInit();
	}
}

function onAfterInit(){
	setupWindow();
	document.getElementById('sendButton').style.display='';
	checkChat();
}

function getXml(txt) {
	var xmlDoc;
	if (window.DOMParser) {
		parser=new DOMParser();
		xmlDoc=parser.parseFromString(txt,"text/xml");
	}
	else {
		xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async="false";
		xmlDoc.loadXML(txt);
	}
	return xmlDoc;
}
function pushOpener(page){
	if(window && window.opener && !window.opener.closed)
		window.opener.location=page;
	else if(pushWindow && !pushWindow.closed)
		pushWindow.location=page;
	else
		pushWindow=window.open(page);
}
function setupLinks(chatMessage) {
	var urlRegex = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/ig
	var matches=chatMessage.match(urlRegex);
	if(matches==null) return chatMessage;
	for(var i = 0; i < matches.length; i++) {
		chatMessage=chatMessage.replace(matches[i],'<span class="chatLink" onclick="pushOpener(\''+matches[i]+'\')">'+matches[i]+'</span>');
	}
	return chatMessage;
}
function writeMessage(chatterName, chatMessage) {
	if(!chatDiv || chatDiv==null) return;
	chatMessage=setupLinks(chatMessage);
	if(chatterName==serv && chatMessage.substr(0,push.length)==push && !isAdmin) {
		var page = chatMessage.substr(push.length);
		pushOpener(page);
	} else if(chatterName==serv && chatMessage.substr(0,close.length)==close) {
		if(isAdmin) {
			popupNote();
		} else {
			lockChat();
			lockButtons();
			popupNote();
		}
	} else if (chatterName==serv) {
		if(chatMessage.indexOf('joined the chat') > 0) chatterCount++;
		chatDiv.innerHTML += 	'<p class="servtext msg-'+lastMsgId+'" style="margin: 0; padding: 3px 0 3px 5px;">' +
									'<span> ' + chatMessage + '</span>' +
								'</p>';
		divScroll.activeScroll();
	} else {
		chatDiv.innerHTML += 	'<p class="' + ((chatter==chatterName) ? 'mytext' : '') + '  msg-'+lastMsgId+'" style="margin: 0; padding: 3px 0 3px 30px;">' +
									'<strong style="margin: 0 0 0 -25px;">' + chatterName + ':' + '</strong>' +
									'<span> ' + chatMessage + '</span>' +
								'</p>';
		divScroll.activeScroll();
	}
}
function lockChat() {
	$('textarea').attr('disabled', 'disabled').animate({
			opacity: 0.2
		  }, 1000);
}
function lockButtons() {
	$('input').attr('disabled', 'disabled').animate({
			opacity: 0.2
		  }, 1000);
}
function popupNote() {
	$("#extras").empty().append('<div id="screen"></div><div id="alertBox"></div>');
	$("#screen").css({'width':'100%','height':$(document).height(),'position':'absolute','left':'0px', 'top':'0px','background':'url(\'/images/chatback.jpg\')','opacity':'0'}).animate({opacity: 0.5},1500);
	$("#alertBox").append("<div onclick='clearNote()' style='margin:0px 10px; height: 20px; width: 20px; float: right; padding: 2px; font-size: 16px;font-weight: bold;border: solid 2px white; color: white; background: red; cursor:pointer;'>X</div><p style='clear:both;margin: 0; padding: 0;'>The chat has ended.</p>").css({'width':'100%', 'position':'absolute','left':'0px', 'bottom':'0px','background':(jQuery.support.opacity?'rgba(0,0,0,0.8)':'rgb(0,0,0)'),'color':'white','text-align':'center','border-top':'solid 3px black','font-weight':'bold','padding-top':'10px','font-size':'20px','opacity':'0'}).animate({
			height: '115px',
			opacity: 1
		  }, 1000);
}

function clearNote() {
	$("#screen").fadeOut(1500, function(){
		$("#extras").empty();
	});
	$("#alertBox").animate({
		height: '5px',
		opacity: 0
	  }, 1000);
}

function onCheckChatFinished(){
	if (ajaxCheckChatObj.readyState == 4) {
		var chatXML=getXml(ajaxCheckChatObj.responseText);
		var messages=chatXML.getElementsByTagName('message');
		for( var i = lastMsgId; lastMsgId < messages.length; lastMsgId++) {
			writeMessage( messages[lastMsgId].attributes.getNamedItem('chatter').value, messages[lastMsgId].attributes.getNamedItem('msg').value);
		}
		checkVar=setTimeout("checkChat()",checkTime);
	}
}

function checkChat(){
	var randomnumber=Math.floor(Math.random()*99999)
	ajaxCheckChatObj=getXmlHttpObject();
	if (!ajaxCheckChatObj) return;
	ajaxCheckChatObj.onreadystatechange=onCheckChatFinished;
	ajaxCheckChatObj.open("GET", '/chat/'+chatId+'.xml?rand=' + randomnumber, true);
	ajaxCheckChatObj.send();
}

function onSendChatDone(){
	if (ajaxSendChatObj.readyState == 4) {
		clearTimeout(checkVar);
		checkChat();
	}
}

function sendChat(){
	var chatMsg = chatInput.value;
	if(!chatMsg || chatMsg==null|| chatMsg=="") return;
	doChat(chatter, chatMsg);
	chatInput.value='';
	chatInput.focus();
}

function joinChat(){
	ajaxJoinChatObj=getXmlHttpObject();
	if (!ajaxJoinChatObj) return;
	ajaxJoinChatObj.open("POST", '/chat.jsp?chatStage=join&chatter='+chatter+'&chatId='+chatId, true);
	ajaxJoinChatObj.send();
}
function doChat(myChatter, chatMsg, skipCheck){
	if(skipCheck === undefined) skipCheck = false;
	chatMsg = chatMsg.replace(/"/gi, '&quot;');
	chatMsg = chatMsg.replace(/>/gi, '&gt;');
	chatMsg = chatMsg.replace(/</gi, '&lt;');
	ajaxSendChatObj=getXmlHttpObject();
	if (!ajaxSendChatObj) return;
	if(!skipCheck)
		ajaxSendChatObj.onreadystatechange=onSendChatDone;
	ajaxSendChatObj.open("POST", '/chat.jsp?chatStage=chat&chatter='+myChatter+'&chatId='+chatId+'&msgId='+(lastMsgId + 1)+'&chatMsg='+encodeURIComponent(chatMsg), true);
	ajaxSendChatObj.send();
}

function pushPage(){
	var page;
	while(page==null) page=prompt('Enter the URL to push to the user','http://');
	doChat(serv,push+page);
}

function closeChat(){
	if(confirm('This will close the chat for all participants. Are you sure you want to close the chat?'))
		endChat();
}

function endChat(){
	doChat(serv,close);
	ajaxAdminObj=getXmlHttpObject();
	if (!ajaxAdminObj) return;
	ajaxAdminObj.open("POST", '/chat.jsp?chatStage=close&chatId='+chatId, true);
	ajaxAdminObj.send();
}

function onLeftChat() {
	ajaxJoinChatObj=getXmlHttpObject();
	if (!ajaxJoinChatObj) return;
	ajaxJoinChatObj.open("POST", '/chat.jsp?chatStage=exit&chatter='+chatter+'&chatId='+chatId, true);
	ajaxJoinChatObj.send();
}

function setupWindow(){
	var maindiv=document.getElementById('chatwindow');
	var maincontent=	'<table cellpadding="0" cellspacing="0" border="0" style="height: 490px; width: 340px; border-collapse: collapse;">'+
							'<tr>' +
								'<td colspan="2" style="height:20px; line-height: 20px; vertical-align: middle;">' +
									'<h1>Data Foundations Live Chat</h1>' +
								'</td>' +
							'</tr>' +
							'<tr>' +
								'<td colspan="2" style="height:360px">' +
									'<div id="chatDiv">' +
									'</div>' +
								'</td>' +
							'</tr>' +
							'<tr id="chatbottom">' +
								'<td valign="top" style="height:95px;width: 245px;">' +
									'<textarea rows="5" id="inputText" onkeydown="if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)) {sendChat();return false;} else return true;" >' +
									'</textarea>' +
								'</td>' +
								'<td valign="top" style="height:95px;">' +
									'<input type="button" class="chatbutton" id="sendButton" value="Send" onclick="sendChat();"/>' +
									'<br/>' +
									'' + (isAdmin ? '<input class="chatbutton" type="button" id="pushButton" value="Push Page" onclick="pushPage();"/>' : '' ) +
									'<br/>' +
									'' + (isAdmin ? '<input class="chatbutton" type="button" id="closechatbutton" value="End Chat" onclick="closeChat();"/>' : '' ) +
								'</td>' +
							'</tr>' +
						'</table>'+
						'<a name="bottom" />';
	maindiv.innerHTML=maincontent;

	divScroll = new chatscroll.Pane('chatDiv');
	divScroll.activeScroll();
	chatDiv = document.getElementById('chatDiv');
	chatInput=document.getElementById('inputText');
	document.getElementById('sendButton').style.display='none';
	establishChatterName();
}
function establishChatterName() {
	if (chatter==null || chatter=='') {
		
		$("#extras").empty().append('<div id="screen1"></div><div id="requestNameBox"></div>');
		$("#screen1").css({'width':'100%','height':$(document).height(),'position':'absolute','left':'0px', 'top':'0px','background':'url(\'/images/chatback.jpg\')','opacity':'0'}).animate({opacity: 0.5},1500);
		$("#requestNameBox").append('<p style="color:white; text-align:center; font-weight:bold; font-size:20px;">Please enter your name.</p><input type="text" id="inputChatterName" style="width:245px; margin:0 10px;" onkeydown="if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)) {checkChatterName();return false;} else return true;" /><input class="chatbutton" type="button" onclick="checkChatterName()" value="OK" />').css({'width':'100%', 'position':'absolute','left':'0px', 'bottom':'0px','background':(jQuery.support.opacity?'rgba(0,0,0,0.8)':'rgb(0,0,0)'),'border-top':'solid 3px black','padding-top':'10px','opacity':'0'}).animate({
				height: '115px',
				opacity: 1
			  }, 1000);
		$('#inputChatterName').focus();
	} else {
		onAfterChatterNameEstablished();
	}
}
function checkChatterName() {
	chatter=$('#inputChatterName').val();
	if (chatter!=null && chatter!='') {
		$("#requestNameBox p").empty().append("Thanks!");
		$("#screen1").fadeOut(1500, function(){
			$("#extras").empty();
		});
		$("#requestNameBox").animate({
			height: '5px',
			opacity: 0
		  }, 1000);
		onAfterChatterNameEstablished();
	}
}
function onAfterChatterNameEstablished() {
	if(!isAdmin) beginCheckForJoins();
	joinChat();
	alertAdmin();
}
function alertAdmin(){
	if(isAdmin) return;
	doChat(serv, "Chat initiated from: " + window.opener.location);
	doChat(serv, "Please wait while a Data Foundations representative is located...");
}
function beginCheckForJoins() {
	setTimeout("apologize()",joinTimeout);
}
function apologize() {
	if(chatterCount < 2) {
		$("#extras").empty().append('<div id="screen"></div><div id="alertBox"></div>');
		$("#screen").css({'height':$(document).height(),'width':'100%','position':'absolute','left':'0px', 'top':'0px','background':'url(\'/images/chatback.jpg\')','opacity':'0'}).animate({opacity: 0.5},1500);
		$("#alertBox").append("<div onclick='clearNote()' style='margin:0px 10px; height: 14px; width: 14px; float: right; padding: 2px; font-size: 10px;font-weight: bold;border: solid 2px white; color: white; background: red; cursor:pointer;'>X</div><p style='clear:both;margin: 0; padding: 0 20px;'>Our Apologies!<br/><span style='font-size:16px;'>We could not locate someone to chat.<br/>Please use the <span style='text-decoration:underline; cursor:pointer' onclick='pushOpener(\"http://www.datafoundations.com/company_contact.jsp\")' >Contact Us Form</span> instead.</span></p>").css({'width':'100%', 'position':'absolute','left':'0px', 'bottom':'0px','background':(jQuery.support.opacity?'rgba(0,0,0,0.8)':'rgb(0,0,0)'),'color':'white','text-align':'center','border-top':'solid 3px black','font-weight':'bold','padding-top':'10px','font-size':'20px','opacity':'0'}).animate({
				height: '115px',
				opacity: 1
			  }, 1000);
	}
}
function initDfiChat(myChatId,myIsAdmin,chatName){
	isAdmin = myIsAdmin;
	if(!(chatName===undefined)) chatter=chatName;
	if(myChatId=='0') {
		ajaxObj=getXmlHttpObject();
		if (!ajaxObj) return;
		ajaxObj.onreadystatechange=onInitFinished;
		ajaxObj.open("POST", '/chat.jsp?chatStage=init' , true);
		ajaxObj.send();
	} else {
		chatId=myChatId;
		onAfterInit();
	}
}
 function dfiChatInit(myChatId,myIsAdmin,chatName) {
	if(myChatId === undefined) myChatId='0';
	if(myIsAdmin === undefined) myIsAdmin=false;
	var newwindow2=window.open('','dfichatwindow','height=510,width=360,scrollbars=no, resize=no, statusbar=no, menubar=no');
	var tmp = newwindow2.document;
	var myOutput =	'<html>' +
						'<head>' +
							'<title>Data Foundations Chat Window</title>' +
							'<script type="text/javascript" src="/js/dfichat.js"></script>'+
							'<script type="text/javascript" src="/js/jquery-1.4.2.min.js"></script>'+
							'<link rel="stylesheet" type="text/css" href="/css/dfichat.css"></script>'+
						'</head>'+
						'<body onunload="onLeftChat()">' +
							'<div id="chatwindow" style="width:350px;height:500px;" >' +
								'Loading Chat...' +
							'</div>'+
							'<script type="text/javascript">'+
								'setTimeout("'+
									'initDfiChat(' +
										'\'' + myChatId + '\'' +
										'' + (myIsAdmin ? ',true' : ',false') +
										'' + (chatName===undefined ? '' : ',\'' + chatName+ '\'' ) +
									')' +
								'",100)' +
							'</script>'+
							'<div id="extras"></div>' +
						'</body>' +
					'</html>';
	tmp.write(myOutput);
	tmp.close();
 }

 function onInitChatAdmin(){
	if (ajaxAdminObj.readyState == 4) {
		var chatAdminXML=getXml(ajaxAdminObj.responseText);
		var conversations=chatAdminXML.getElementsByTagName('title');
		for( var i = 1; i < conversations.length; i++) {
			chatAdminDiv.innerHTML += '<input type="button" value="'+conversations[i].childNodes[0].nodeValue+'" onclick="dfiChatInit(\''+conversations[i].childNodes[0].nodeValue+'\',true,\'admin\')" /><br/>';
		}
	}
 }

 function dfiChatCheckInit(chatAdmin) {
	var search1 = location.search;
	if(search1.length > 1) {
		search1 = search1.substr(1);
		var search2 = search1.split("&");
		for(var i = 0;i < search2.length; i++)
		{
			if(search2[i].split("=")[0]=='dfiChatId') {
				var cid = '' + search2[i].split("=")[1];
				while(dfichat_user===undefined || dfichat_user==null) dfichat_user=prompt("Please enter your name.", "Your Name");

				dfiChatInit(cid,true,dfichat_user);
			}
		}
	} else {
		chatAdminDiv = document.getElementById(chatAdmin);
		ajaxAdminObj=getXmlHttpObject();
		if (!ajaxAdminObj) return;
		ajaxAdminObj.onreadystatechange=onInitChatAdmin;
		ajaxAdminObj.open("GET", '/chat/conversations.xml' , true);
		ajaxAdminObj.send();
	}
 }

 function displayChatImage(displayChat) {
	if(displayChat) {
		document.write('<img border="0" width="198" height="112" src="/images/chaticons/reponline.gif" style="cursor:pointer;" onclick="dfiChatInit();" />');
	} else {
		document.write('<a href="/company_contact.jsp"><img width="198" height="112" border="0" src="/images/chaticons/repoffline.gif" /></a>');
	}

 }

/*
 *	==============================================================================================================
 *		Twitter scripts - twitter.js
 *	==============================================================================================================
 */
function dfiTweets(twitters) {
  var statusHTML = [];
  for (var i=0; i<twitters.length; i++){
    var username = twitters[i].user.screen_name;
    var username2 = twitters[i].user.name;
	var imgsrc = twitters[i].user.profile_image_url;
    var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
      return '<a href="'+url+'">'+url+'</a>';
    }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
      return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
    });
    statusHTML.push('<li><p><a href="http://www.twitter.com/'+username+'" target="_blank"><img height="48" width="48" border="0" src="'+imgsrc+'" alt="'+username+'" title="'+username2+'"/></a>'+status+'</p> <a style="font-size:85%" href="http://twitter.com/'+username+'">@'+username+' - posted '+relative_time(twitters[i].created_at)+'</a></li>');
  }
  document.getElementById('twitter_update_list').innerHTML = statusHTML.join('');
}

function dfiFollowers(twitters) {
  var fl = document.getElementById('twitter_followers_list');
  for (var i=0; i<twitters.length; i++){
    var imgalt = twitters[i].screen_name;
	var imgname = twitters[i].name;
	var imgsrc = twitters[i].profile_image_url;
	var myTD = document.createElement('td');
	var myA = document.createElement('a');
	myA.setAttribute('href', 'http://www.twitter.com/'+imgalt);
	myA.setAttribute('rel', 'nofollow');
	myA.setAttribute('target', '_blank');
	var myImg = document.createElement('img');
	myImg.setAttribute('src', imgsrc);
	myImg.setAttribute('height','48');
	myImg.setAttribute('width','48');
	myImg.setAttribute('border', '0');
	myImg.setAttribute('alt', imgalt);
	myImg.setAttribute('title', imgname);
	myA.appendChild(myImg);
	myTD.appendChild(myA);
	fl.appendChild(myTD);
  }
}

function relative_time(time_value) {
  var values = time_value.split(" ");
  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
  var parsed_date = Date.parse(time_value);
  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
  delta = delta + (relative_to.getTimezoneOffset() * 60);

  if (delta < 60) {
    return 'less than a minute ago';
  } else if(delta < 120) {
    return 'about a minute ago';
  } else if(delta < (60*60)) {
    return (parseInt(delta / 60)).toString() + ' minutes ago';
  } else if(delta < (120*60)) {
    return 'about an hour ago';
  } else if(delta < (24*60*60)) {
    return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
  } else if(delta < (48*60*60)) {
    return '1 day ago';
  } else {
    return (parseInt(delta / 86400)).toString() + ' days ago';
  }
}


/*
 *	==============================================================================================================
 *		Flash scripts - homeflash.js
 *	==============================================================================================================
 */
// -----------------------------------------------------------------------------
// Globals
// Major version of Flash required
var requiredMajorVersion = 10;
// Minor version of Flash required
var requiredMinorVersion = 0;
// Revision of Flash required
var requiredRevision = 2;
// -----------------------------------------------------------------------------

//v1.7
// Flash Player Version Detection
// Detect Client Browser type
// Copyright 2005-2008 Adobe Systems Incorporated.  All rights reserved.
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
function ControlVersion()
{
	var version;
	var axo;
	var e;
	// NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry
	try {
		// version will be set for 7.X or greater players
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {
	}
	if (!version)
	{
		try {
			// version will be set for 6.X players only
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
			
			// installed player is some revision of 6.0
			// GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
			// so we have to be careful. 
			
			// default to the first public version
			version = "WIN 6,0,21,0";
			// throws if AllowScripAccess does not exist (introduced in 6.0r47)		
			axo.AllowScriptAccess = "always";
			// safe to call for 6.0r47 or greater
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}
	if (!version)
	{
		try {
			// version will be set for 4.X or 5.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}
	if (!version)
	{
		try {
			// version will be set for 3.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) {
		}
	}
	if (!version)
	{
		try {
			// version will be set for 2.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) {
			version = -1;
		}
	}
	
	return version;
}
// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer(){
	// NS/Opera version >= 3 check for Flash plugin in plugin array
	var flashVer = -1;
	
	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
			var descArray = flashDescription.split(" ");
			var tempArrayMajor = descArray[2].split(".");			
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];
			var versionRevision = descArray[3];
			if (versionRevision == "") {
				versionRevision = descArray[4];
			}
			if (versionRevision[0] == "d") {
				versionRevision = versionRevision.substring(1);
			} else if (versionRevision[0] == "r") {
				versionRevision = versionRevision.substring(1);
				if (versionRevision.indexOf("d") > 0) {
					versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
				}
			}
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
		}
	}
	// MSN/WebTV 2.6 supports Flash 4
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	// WebTV 2.5 supports Flash 3
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	// older WebTV supports Flash 2
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	else if ( isIE && isWin && !isOpera ) {
		flashVer = ControlVersion();
	}	
	return flashVer;
}
// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
	versionStr = GetSwfVer();
	if (versionStr == -1 ) {
		return false;
	} else if (versionStr != 0) {
		if(isIE && isWin && !isOpera) {
			// Given "WIN 2,0,0,11"
			tempArray         = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
			tempString        = tempArray[1];			// "2,0,0,11"
			versionArray      = tempString.split(",");	// ['2', '0', '0', '11']
		} else {
			versionArray      = versionStr.split(".");
		}
		var versionMajor      = versionArray[0];
		var versionMinor      = versionArray[1];
		var versionRevision   = versionArray[2];
        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
		if (versionMajor > parseFloat(reqMajorVer)) {
			return true;
		} else if (versionMajor == parseFloat(reqMajorVer)) {
			if (versionMinor > parseFloat(reqMinorVer))
				return true;
			else if (versionMinor == parseFloat(reqMinorVer)) {
				if (versionRevision >= parseFloat(reqRevision))
					return true;
			}
		}
		return false;
	}
}
function AC_AddExtension(src, ext)
{
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?'); 
  else
    return src + ext;
}
function AC_Generateobj(objAttrs, params, embedAttrs) 
{ 
  var str = '';
  if (isIE && isWin && !isOpera)
  {
    str += '<object ';
    for (var i in objAttrs)
    {
      str += i + '="' + objAttrs[i] + '" ';
    }
    str += '>';
    for (var i in params)
    {
      str += '<param name="' + i + '" value="' + params[i] + '" /> ';
    }
    str += '</object>';
  }
  else
  {
    str += '<embed ';
    for (var i in embedAttrs)
    {
      str += i + '="' + embedAttrs[i] + '" ';
    }
    str += '> </embed>';
  }
  document.write(str);
}
function AC_FL_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}
function AC_SW_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
     , null
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}
function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();    
    switch (currArg){	
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":	
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblclick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
      case "id":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace": 
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}


function displayHomeFlash() {
	var hasRightVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);
	if(hasRightVersion) {  // if we've detected an acceptable version
		// embed the flash movie
		AC_FL_RunContent(
			'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,2,0',
			'width', '950',
			'height', '225',
			'src', 'images/odBanner',
			'quality', 'high',
			'pluginspage', 'http://www.adobe.com/go/getflashplayer',
			'align', 'middle',
			'play', 'true',
			'loop', 'true',
			'scale', 'showall',
			'wmode', 'transparent',
			'devicefont', 'false',
			'id', 'images/odBanner',
			'bgcolor', '#ffffff',
			'name', 'images/odBanner',
			'menu', 'true',
			'allowFullScreen', 'false',
			'allowScriptAccess','sameDomain',
			'movie', 'images/odBanner',
			'salign', ''
			); //end AC code
	} else {  // flash is too old or we can't detect the plugin
		var alternateContent = '<a href="/LP_MDMVendorRankingReportOffer.jsp" target="_blank"><img src="/images/noflash_leaderboard.jpg" border="0"></a>';
		document.write(alternateContent);  // insert non-flash content
	}
}

function displayHomeFlash2() {
	AC_FL_RunContent(
		'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,2,0',
		'width', '200',
		'height', '82',
		'src', 'logos',
		'quality', 'high',
		'pluginspage', 'http://www.adobe.com/go/getflashplayer',
		'align', 'middle',
		'play', 'true',
		'loop', 'true',
		'scale', 'showall',
		'wmode', 'transparent',
		'devicefont', 'false',
		'id', 'logos',
		'bgcolor', '#ffffff',
		'name', 'images/logos',
		'menu', 'true',
		'allowFullScreen', 'false',
		'allowScriptAccess','sameDomain',
		'movie', 'logos',
		'salign', ''
		);
}

function displayMDRFlash() {
	AC_FL_RunContent(
		'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,2,0',
		'width', '690',
		'height', '225',
		'src', 'images/cloud-flash',
		'quality', 'high',
		'pluginspage', 'http://www.adobe.com/go/getflashplayer',
		'align', 'middle',
		'play', 'true',
		'loop', 'true',
		'scale', 'showall',
		'wmode', 'transparent',
		'devicefont', 'false',
		'id', 'images/cloud-flash',
		'bgcolor', '#ffffff',
		'name', 'images/cloud-flash',
		'menu', 'true',
		'allowFullScreen', 'false',
		'allowScriptAccess','sameDomain',
		'movie', 'images/cloud-flash',
		'salign', ''
		);
}
