// JavaScript Document

var clientScreenDimensions = new Object(); 
/* Double click variables */
var axel = Math.random() + "";
var ord = axel * 1000000000000000000;
/* Double click variables */

var loginTimer;
$(document).ready(function(){
//Start JQuery Code 
   
	
    var beenHit = false;
	
	if(Get_Cookie('cqlogincookie')) {
	  var credentials = Get_Cookie('cqlogincookie');
	  var tmp = credentials.split(":");
	  $('#userName').val(tmp[0]);
	  $('#password').val(tmp[1]);	 
	  document.getElementsByName('rememberme').item(0).checked=true;
	}
	
	//Button Hovers
	$(".submit, #print img, #productdescription #col_a li a img").hover(	
		function() {			
			off_img = $(this).attr('src');			
			over_img = off_img.replace('off/','on/');																			
			$(this).attr('src', over_img);		
		},		
		function() {		
			$(this).attr('src', off_img);
		}
	);

	//Print Button
	$("#print").click(function(){
		window.print();
		return false;
	});

	//Print Window Button
	$("#printlink").click(function(){
		window.open('/frame-templates/print_template.cfm','','width=741,height=513,resizable=yes,scrollbars=yes');
		return false;
	});
	
	
	
	
	//Email Background Stretch
	$("#emaillayer").height($("body").height());
			
	//Email Button
	$("#emaillink").click(function(){
		$("#emaillayer").css('display','block');
		$("#email").css('display','block');
		return false;
	});
	
	$('#emailPageForm').ajaxForm( { resetForm: true, success: closeEmailFormWin } );
	
	$("#emailPageForm").validate({
     rules: {     
      recipient_name: "required" ,	  
	  recipient_email: "required",
	  sender_name: "required",
	  sender_email: "required"	 
     },
	 messages: {
			recipient_name: "<div style='font-size: 10px; color: red; margin-bottom: -3px;'><img src='/frame-images/cq/icons/exclamation.gif' style='position: relative; top: 2px;' /> Required field.</div>",
			recipient_email: "<div style='font-size: 10px; color: red; margin-bottom: -3px;'><img src='/frame-images/cq/icons/exclamation.gif' style='position: relative; top: 2px;' /> Required field.</div>",
			sender_name: "<div style='font-size: 10px; color: red; margin-bottom: -3px;'><img src='/frame-images/cq/icons/exclamation.gif' style='position: relative; top: 2px;' /> Required field.</div>",
			sender_email: "<div style='font-size: 10px; color: red; margin-bottom: -3px;'><img src='/frame-images/cq/icons/exclamation.gif' style='position: relative; top: 2px;' /> Required field.</div>"
			
		}, errorPlacement: function(error, element) {				
				error.appendTo($('label[for="'+element.attr('id')+'"]'));			
			}
	
    });					
	
	
	$("#cqloginform").submit(function(){
	 if(isCheckboxGroupChecked('rememberme')) {		 
	  Set_Cookie('cqlogincookie',$('#userName').val()+':'+$('#password').val(),730);
	  //alert(Get_Cookie('cqlogincookie'));
	 }
	 else {
	  Delete_Cookie('cqlogincookie');
	 }
	});
	
	
	//Close Window Button - Email
	$("#email a.closewindow").click(function(){
		$('#emaillayer').css('display','none');
		$('#email').css('display','none');
		return false;
	});

	//Close Window Button - Print
	$("body.print a.closewindow").click(function(){
		window.close();
		return false;
	});	

	//Search Operators
	$("#searchoperators").toggle(	
		function() {			
			$("#searchHelpContainer").css('display','block');
		},		
		function() {		
			$("#searchHelpContainer").css('display','none');
		}
	);

	//Border Stretch
	s_height = $("#sidebar").height() + parseInt($("#sidebar").css('margin-top'));
	height_param = $("#article").height() - s_height;
	
	if (height_param > 0) $("#sidebar").css('padding-bottom', height_param + 'px');

	//Product Table - Initialization
	$(".productdisplay tr td:odd").css('border-left','40px solid white');
	$(".productdisplay :checkbox").attr('checked','');
	if ($(".productdisplay td:last").html() == "&nbsp;") $(".productdisplay tr td:last").css('border-bottom','1px solid white');

	//Product Table Rollovers
	$(".productdisplay td a").hover(	
		function() {			
			$(this).siblings("div").css('display','block');	
		},		
		function() {		
			$(this).siblings("div").css('display','none');	
		}
	);

	//Product Table Selection
	$(".productdisplay :checkbox").click(function(){    
		var selectedList = '';
		$(".productdisplay td a").css('color','#94A7AF');	
		
		
		
		$(".productdisplay :checkbox").each(function(){
		 if($(this).attr('checked')) {
		  if(selectedList != '') {
			selectedList+=','+$(this).val();
		  }
		  else {
			selectedList = $(this).val();   
		  }
		 }
		});
		selectedList = selectedList.split(",");
		$(".productdisplay td a").each(function(){											
            for(var x = 0; x < selectedList.length; x++) {				
			 if($(this).attr('className').indexOf(selectedList[x]) != -1) {
			  $(this).css('color','#113D51');
			 }
			}
          							 
		});
		
		
	});	
	
	// Product Form
	$("#productlist").submit(function(){   
	 var selectedURL = $('#products').val();
	 if(selectedURL != "") {
	  window.location=selectedURL; 
	 }
	 return false;	 
    });	
	
	// Product drop down 
	$("#productselect").change(function(){ 	
	 if($("#productselect").val() != "") {									
	  window.location=$("#productselect").val();										  
	 }
    });												  
	
	//Network Module
	$(".network ul#networknav a").click(function(){
		$(".network ul#networknav a").each(function(){
			$(this).css('background-image', $(this).css('background-image').replace('on/','off/'));	
		});	
		$(".network div").css('display','none');
		
		anchor = $(this).attr('href');	
		$(".network div" + anchor).css('display','block');
		$(this).css('background-image', $(this).css('background-image').replace('off/','on/'));			
		beenHit = true;
		return false;
	});

	$(".network ul#networknav a").hover(	
		function() {	
			off_img = $(this).css('background-image');	
			over_img = off_img.replace('off/','on/');																	
			$(this).css('background-image', over_img);	
			beenHit = false;
		},		
		function() {	
            if (beenHit == false){	
				$(this).css('background-image', off_img);
			};
		}
	);

	//Product Page/Network Features

	$("#productdescription #col_a li a").hover(	
		function() {			
			$(this).siblings("div").css('display','block');	
		},		
		function() {		
			$(this).siblings("div").css('display','none');	
		}
	);

	//Product Page/Image Picker
	$(".moreimages li a").click(function(){
		imageshow = $(this).attr('class');
	
		//Images
		$("#productdescription #col_b img").css('display','none');
		$("#productdescription #col_b img." + imageshow).css('display','inline');

		//Description Divs
		$(".moreimages div").css('display','none');
		$(".moreimages div." + imageshow).css('display','block');
	});


	//Homepage Module - Changed 5/28/08
	$("#featurenav a").click(function(){
		$("#featurenav a").each(function(){
			$(this).css('background-image', $(this).css('background-image').replace('on/','off/'));		
			$(this).removeClass('selected');
		});	
		$("div.featureblock").css('display','none');		
		
		anchor = $(this).attr('href');			
		$("div.featureblock" + anchor).fadeIn(3000);	
		$(this).css('background-image', $(this).css('background-image').replace('off/','on/'));		
		$(this).addClass('selected');
		$(this).blur();
		return false;
	});

	$("#featurenav a").hover(	
		function() {	
			off_img = $(this).css('background-image');	
			over_img = off_img.replace('off/','on/');																	
			$(this).css('background-image', over_img);	
		},		
		function() {	
			  if ($(this).attr('class') != "selected") {
				$(this).css('background-image', off_img);
			};
		}
	);

	//Navigation Background
	$("ul#primary li.secondary ul li:last").children("span.selected").css('margin-bottom','-10px');
	$("ul#primary li.tertiary li:last").children("span.selected").css('margin-bottom','-3px');
	
	$("#prNavID").change(function(){
		document.getElementById('prArchiveForm').submit();
		return false;
	});
	
	//Home page find drop down for all tabs
	$('form[name=productfindForm]').submit(function(){													
      var id = $(this).attr('id').split("_");													
	  window.location=$('#productselect'+id[1]).val();	 
	  return false;
	});
	
	
	
	$('#requestRatesForm').ajaxForm( { beforeSubmit:  validateRequestRate, url: '/actions/_postRequestRates.cfm', type: 'post', clearForm: true, success: registrationThankYou} );
	
	$('#enewsform').ajaxForm( { beforeSubmit:  validateNewsletterSignUp, url: '/actions/_postNewsletterSignUp.cfm', type: 'post', clearForm: true, success: registrationThankYou} );
	
	$('#eventRegistration').ajaxForm( { beforeSubmit:  validateEventRegistration, url: '/actions/_postEventRegistration.cfm', type: 'post', clearForm: true, success: registrationThankYou} );
	

	//Safari Hack - 5/28/08
	if (($.browser.safari) && (parseInt($.browser.version) < 500)) {
		$("a#login").css("margin-top", "-2px");
	}


	
	
	 $("a#login").hover(
      function () {
        $("a#login").css("background-image", "url(frame-images/cq/buttons/selected/login.jpg)");
      }, 
      function () {
        $("a#login").css("background-image", "url(frame-images/cq/buttons/off/login.jpg)");
      }
    );

						   
						   

	$("a#login").click(function(){
		loginshow();
	});

	$("#loginbox a.closewindow").click(function(){
		loginnoshow();
	});
	
	$("#userName").focus(function(){
	  if(loginTimer) {	
	  
	   clearTimeout(loginTimer);
	  }
	});
	
	$("#password").focus(function(){
	  if(loginTimer) {		
	   clearTimeout(loginTimer);
	  }
	});


	if($("body").attr("class") == "home") {		
		loginshow();
		loginTimer = setTimeout("loginnoshow()", 5000);		
	};

	//Target Links - opening outside windows
	$("a.target").click(function(){
		window.open($(this).attr("href"));
		return false;
	});
	
	 $('#userguideactionbtn').click(function(){
		window.open($('#userguides').val());
		return false;
	});


//End JQuery Code
});

function validateEmailPage() {
//	alert("got here");
//	alert($("#emailPageForm fieldset").length);
 //$("#emailPageForm label").addClass('error');
 //var oDiv = document.createElement("div");
 //oDiv.className='error';
 
// $("#recipient_name").wrap(oDiv);

 //$("#recipient_name").after('<img src="/frame-images/cq/icons/exclamation.gif" alt="This field needs attention" title="This field needs attention" class="errorIcon" />');

 return false;	
	
}




function closeEmailFormWin() {	
  $('#emaillayer').css('display','none');
  $('#email').css('display','none');
  alert("Email sent");
  return false;
}

function registrationThankYou(str) {
 //document.write(str);
 updateStatusMsg('Thank you for registering.');
 setTimeout('removeOverlay()',1000); 
}

function showRequest(formData, jqForm, options) { 
    // formData is an array; here we use $.param to convert it to a string to display it 
    // but the form plugin does this for you automatically when it submits the data 
    var queryString = $.param(formData); 
 
    // jqForm is a jQuery object encapsulating the form element.  To access the 
    // DOM element for the form do this: 
    // var formElement = jqForm[0]; 
 
    alert('About to submit: \n\n' + queryString); 
 
    // here we could return false to prevent the form from being submitted; 
    // returning anything other than false will allow the form submit to continue 
    return true; 
} 

function validateRequestRate() {
 clearFormErrors();		
 var errorData = new Object();
 errorData.fieldId = new Array();
 errorData.msg = new Array();	
	
 if($.trim($('#firstname').val()) == "") {
  errorData.fieldId[errorData.fieldId.length]="firstname";
  errorData.msg[errorData.msg.length]="Required field.";
 }
 
 if($.trim($('#lastname').val()) == "") {
  errorData.fieldId[errorData.fieldId.length]="lastname";
  errorData.msg[errorData.msg.length]="Required field.";
 }
 
 if($.trim($('#company').val()) == "") {
  errorData.fieldId[errorData.fieldId.length]="company";
  errorData.msg[errorData.msg.length]="Required field.";
 }
 
 if($.trim($('#address').val()) == "") {
  errorData.fieldId[errorData.fieldId.length]="address";
  errorData.msg[errorData.msg.length]="Required field.";
 }
 
  if($.trim($('#city').val()) == "") {
  errorData.fieldId[errorData.fieldId.length]="city";
  errorData.msg[errorData.msg.length]="Required field.";
 }
 
 if($.trim($('#state').val()) == "") {
  errorData.fieldId[errorData.fieldId.length]="state";
  errorData.msg[errorData.msg.length]="Required field.";
 } 

 if(isNaN($('#zip').val()) || $('#zip').val().length != 5) {
  errorData.fieldId[errorData.fieldId.length]="zip";
  errorData.msg[errorData.msg.length]="Required field. Must be a five digit number xxxxx.";
 }
 
 if(!isValidEmail($('#emailaddress').val())) {
  errorData.fieldId[errorData.fieldId.length]="emailaddress";
  errorData.msg[errorData.msg.length]="Required field. must be a valid email address.";	 
 }
 
 if($.trim($('#phone').val()) == "") {
  errorData.fieldId[errorData.fieldId.length]="phone";
  errorData.msg[errorData.msg.length]="Required field.";
 }  
 
 if(!isCheckboxGroupChecked('adOpportunity')) {
  errorData.fieldId[errorData.fieldId.length]="adOpportunity";
  errorData.msg[errorData.msg.length]="Required field. Please select at least one opportunity.";	 	 
 } 
 
 if(errorData.fieldId.length > 0 || errorData.msg.length > 0) {
  displayFormErrors(errorData);	 
  return false;	
 }
 else {
  addOverlay();
  displayStatusWindow('Please wait while your information is being submitted.');	 
  return true;	 
 }
}

function validateNewsletterSignUp() {	
 clearFormErrors();	
 var errorData = new Object();
 errorData.fieldId = new Array();
 errorData.msg = new Array();		
 
  if(!isCheckboxGroupChecked('newsletters')) {
  errorData.fieldId[errorData.fieldId.length]="newsletters";
  errorData.msg[errorData.msg.length]="Required field. Please select at least one newsletter to sign up for.";	 	 
 }
 
 if(!isValidEmail($('#emailaddress').val())) {
  errorData.fieldId[errorData.fieldId.length]="emailaddress";
  errorData.msg[errorData.msg.length]="Required field. must be a valid email address.";	 
 }
 
 if($.trim($('#firstname').val()) == "") {
  errorData.fieldId[errorData.fieldId.length]="firstname";
  errorData.msg[errorData.msg.length]="Required field.";
 }
 
 if($.trim($('#lastname').val()) == "") {
  errorData.fieldId[errorData.fieldId.length]="lastname";
  errorData.msg[errorData.msg.length]="Required field.";
 }
 
 if($.trim($('#companyCategory').val()) == "") {
  errorData.fieldId[errorData.fieldId.length]="companyCategory";
  errorData.msg[errorData.msg.length]="Required field.";
 }
 
 if(isNaN($('#zip').val()) || $('#zip').val().length != 5) {
  errorData.fieldId[errorData.fieldId.length]="zip";
  errorData.msg[errorData.msg.length]="Required field. Must be a five digit number xxxxx.";
 } 
 
 if($('#issues').attr('selectedIndex') == -1) {
  errorData.fieldId[errorData.fieldId.length]="issues";
  errorData.msg[errorData.msg.length]="Required field.";
 }
 
 if(errorData.fieldId.length > 0 || errorData.msg.length > 0) {
  displayFormErrors(errorData);	 
  return false;	
 }
 else {	
  addOverlay();
  displayStatusWindow('Please wait while your information is being submitted.');  
  return true;	 
 }	
}

function validateEventRegistration() {
 clearFormErrors();		
 var errorData = new Object();
 errorData.fieldId = new Array();
 errorData.msg = new Array();
 var eventSelected=false; 
 
 for(var x = 1; x < 6; x++) {
  if(document.getElementById('event_'+x).checked) {
   eventSelected=true;
   break;
  }
 } 
 
 if(!eventSelected) {
  errorData.fieldId[errorData.fieldId.length]="dncEvent";
  errorData.fieldId[errorData.fieldId.length]="rncEvent";
  errorData.msg[errorData.msg.length]="Required field. Please select at least one event to register for.";
  errorData.msg[errorData.msg.length]="Required field. Please select at least one event to register for.";
 } 
	
 if($.trim($('#firstname').val()) == "") {
  errorData.fieldId[errorData.fieldId.length]="firstname";
  errorData.msg[errorData.msg.length]="Required field.";
 }
 
 if($.trim($('#lastname').val()) == "") {
  errorData.fieldId[errorData.fieldId.length]="lastname";
  errorData.msg[errorData.msg.length]="Required field.";
 }
 
 if($.trim($('#title').val()) == "") {
  errorData.fieldId[errorData.fieldId.length]="title";
  errorData.msg[errorData.msg.length]="Required field.";
 }
 
 if($.trim($('#organization').val()) == "") {
  errorData.fieldId[errorData.fieldId.length]="organization";
  errorData.msg[errorData.msg.length]="Required field.";
 } 
 
 if(!isValidEmail($('#emailaddress').val())) {
  errorData.fieldId[errorData.fieldId.length]="emailaddress";
  errorData.msg[errorData.msg.length]="Required field. must be a valid email address.";	 
 }
 
 if(errorData.fieldId.length > 0 || errorData.msg.length > 0) {
  displayFormErrors(errorData);	 
  return false;	
 }
 else {   
  addOverlay();
  displayStatusWindow('Please wait while your information is being submitted.');	 
  return true;	 
 }
}

function displayFormErrors(errorData) { 
 errorTotal = errorData.fieldId.length;
 $('.error').css('display','block');
 for(var x = 0; x < errorTotal; x++) {
  $("label[for='"+errorData.fieldId[x]+"']").before("<div class='errorlabel'>"+errorData.msg[x]+"</div>");	 
 }
}

function clearFormErrors() {
 $('.error').css('display','none');	
 $(".errorlabel").remove();
}

function isValidEmail(str) {
 if(str.indexOf('@') == -1 || str.indexOf('.') == -1) {
  return false;
 }
 else {
  var tmp1 = str.split("@");
  var tmp2 = tmp1[1].split(".");   
  if(tmp1[0].length < 1 || tmp2[0].length < 2 || tmp2[1].length < 2) {
   return false;
  }   
 }
 return true;
}

function isCheckboxGroupChecked(fieldName) {
 var isChecked = false;
 var total = document.getElementsByName(fieldName).length;
 for(var x = 0; x < total; x++) {
  if(document.getElementsByName(fieldName).item(x).checked) {
   return true;
   break;
  }   
 }
 return false; 
}

//Login Box - 5/28/08
	function loginshow() {
		$("a#login").css("background-image", "url(frame-images/cq/buttons/selected/login.jpg)");
		$("#loginbox").css("visibility","visible");
		if(loginTimer) {
		 clearTimeout(loginTimer);
		}
	}

	function loginnoshow() {	
	
		$("a#login").css("background-image", "url(frame-images/cq/buttons/off/login.jpg)");
		$("#loginbox").css("visibility","hidden");
		if(loginTimer) {		
		 clearTimeout(loginTimer);
		}
	}
	
// this function gets the cookie, if it exists
function Get_Cookie( name ) {	
 var start = document.cookie.indexOf( name + "=" );
 var len = start + name.length + 1;
 if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
  return null;
 }
 if ( start == -1 ) return null;
 var end = document.cookie.indexOf( ";", len );
 if ( end == -1 ) end = document.cookie.length;
 return unescape( document.cookie.substring( len, end ) );
}

/*
 only the first 2 parameters are required, the cookie name, the cookie
 value. Cookie time is in milliseconds, so the below expires will make the 
 number you pass in the Set_Cookie function call the number of days the cookie
 lasts, if you want it to be hours or minutes, just get rid of 24 and 60.

 Generally you don't need to worry about domain, path or secure for most applications
 so unless you need that, leave those parameters blank in the function call.
*/
function Set_Cookie( name, value, expires, path, domain, secure ) {
 // set time, it's in milliseconds
 var today = new Date();
 today.setTime( today.getTime() );
 // if the expires variable is set, make the correct expires time, the
 // current script below will set it for x number of days, to make it
 // for hours, delete * 24, for minutes, delete * 60 * 24
 if ( expires ) {
  expires = expires * 1000 * 60 * 60 * 24;
 }
 //alert( 'today ' + today.toGMTString() );// this is for testing purpose only
 var expires_date = new Date( today.getTime() + (expires) );
 //alert('expires ' + expires_date.toGMTString());// this is for testing purposes only
 document.cookie = name + "=" +escape( value ) +
  ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + //expires.toGMTString()
  ( ( path ) ? ";path=" + path : "" ) + 
  ( ( domain ) ? ";domain=" + domain : "" ) +
  ( ( secure ) ? ";secure" : "" );
}

// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) {
 if ( Get_Cookie( name ) ) document.cookie = name + "=" +
  ( ( path ) ? ";path=" + path : "") +
  ( ( domain ) ? ";domain=" + domain : "" ) +
  ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function addOverlay() { 
 setClientScreenDimensions();
 var oDiv = document.createElement("div");
 oDiv.setAttribute('id','disabledOverlay');  
 oDiv.style.height=getClientHeightWithScroll()+'px'; 
 document.getElementsByTagName("body").item(0).appendChild(oDiv);  
}

function removeOverlay() {
 removeStatusWindow();	
 if(document.getElementById('disabledOverlay')) {
  document.getElementsByTagName("body").item(0).removeChild(document.getElementById('disabledOverlay'));
 }	
}	

function displayStatusWindow(msg) {  
 removeStatusWindow();	 
 var statusWindow = getStatusWindow(msg);  
 document.getElementsByTagName('body').item(0).appendChild(statusWindow); 
}

function removeStatusWindow() {
 if(document.getElementById('statusWindow')) {
  document.getElementsByTagName('body').item(0).removeChild(document.getElementById('statusWindow'),true);	  
 }
}

function updateStatusMsg(msg) {
 if(document.getElementById('statusWindow')) {  
  document.getElementById('statusMsg').innerHTML = msg;
 }	
}

function getStatusWindow(msg) { 
 var oDivContainer = document.createElement("div");
 var oDivMessage = document.createElement("div"); 
 oDivContainer.setAttribute("id","statusWindow");
 oDivContainer.style.top = getVerticalCenterScreen()+'px';
 oDivContainer.style.left = getHorizontalCenterScreen(350)+'px';
 oDivMessage.setAttribute("id","statusMsg");
 oDivMessage.innerHTML = msg; 
 oDivContainer.appendChild(oDivMessage); 
 return oDivContainer;
}

function setClientScreenDimensions() {
 var de = document.documentElement;     
 clientScreenDimensions.height = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight; 
 if(window.pageYOffset) { clientScreenDimensions.vscroll = window.pageYOffset; } else if(document.documentElement && document.documentElement.scrollTop){ clientScreenDimensions.vscroll = document.documentElement.scrollTop; } else if(document.body){ clientScreenDimensions.vscroll = document.body.scrollTop; } 
 clientScreenDimensions.width = window.innerWidth-20 || self.innerWidth-20 || (de&&de.clientWidth) || document.body.clientWidth; 
 clientScreenDimensions.heightWithScroll = parseInt(clientScreenDimensions.height)+parseInt(clientScreenDimensions.vscroll);
}

function getClientHeight() {
 return clientScreenDimensions.height;
}

function getClientHeightWithScroll() {
 return clientScreenDimensions.heightWithScroll;
}

function getClientWidth() {
 return clientScreenDimensions.width;
}

function getVerticalCenterScreen() { 
 var y = clientScreenDimensions.heightWithScroll/2;  
 return Math.floor(y);
}
 
function getHorizontalCenterScreen(widthOffset) {
 var x = widthOffset/2;
 var y = clientScreenDimensions.width/2;  
 return Math.floor(y-x);	 
} 

function auto404() {
 window.location="/";	
}


