// Utils for ForeSee
// Requires JQuery 1.3.2

function toggleDivInit(cur_page) {
// Show/hide sections of the page when the links are clicked, hide all by JS initially unless link to page
// includes a hash value, then open the div related to that hash value

// This function requires jQuery and takes 1 argument:
// 1) cur_page is the path & page name of the current page	
// It requires the ToggleDiv function
	$("#content_col div h2 + div").hide().data('open','no');
	$("#content_col div h2").addClass("closed");
	if(location.hash) {			
		$(location.hash).slideDown("slow");
		$("a[href=" + location.hash + "]").parents("h2").removeClass("closed");
		$(location.hash).data('open','yes');
	}
	
	// Open/Close sections based on header clicks
	$("#content_col div h2 a").click(function(e){
		e.preventDefault();
		toggleDiv(this, cur_page);
		return false;
	});
	
	// Open/Close sections based on subnav clicks
	$("#subnav ul li ul li a").click(function(e) {
		e.preventDefault();
		toggleDiv(this, cur_page);
		return false;
	});
	
	// Open/Close sections based on hash changing (only if it didn't just change via click)
	$(window).bind('hashchange',function(){			
		if($(location.hash).data('open') == 'no') 
		   toggleDiv($("a[href=" + location.hash + "]"), cur_page);
		return false;
	});		
}

function toggleDiv(linkTarget, cur_page) {
// This function requires jQuery and takes 2 arguments:
// 1) linkTarget is a pointer to the link that was clicked
// 2) cur_page is the path & page name of the current page
// This function is called from the ToggleDivInit function

	var divToToggle = $(linkTarget).attr("href");
	divToToggle = divToToggle.substring(divToToggle.indexOf("#"));

	// Close menus and open a new one if the currently open one was not clicked
	$("#content_col div h2 + div").slideUp("slow");			
	$("#content_col div h2").addClass("closed");	
	if ($(divToToggle).data('open') == 'no') {
		$(divToToggle).slideDown("slow");
		$("#content_col div h2 + div").data('open','no');
		$(divToToggle).data('open','yes');
		$("a[href="+divToToggle+"]").parents("h2").removeClass("closed");
	} else {
		$("#content_col div h2 + div").data('open','no');
	}			
	
	// Set subnav class so subnav arrows reflect currently open section
	$("#subnav ul li ul li").removeClass("current");
	$("#subnav ul li ul li a").removeClass("current");

  if ($(divToToggle).data('open') == "yes") {
		$("#subnav a[href="+cur_page+divToToggle+"]").addClass("current").parents("li").addClass("current");
	}	
}

function clients_toggler() {
	$("h2 + div").addClass("logo_slider_closed");
	if(location.hash) {
		$(location.hash).toggleClass("closed");
		var lhash = location.hash.substr(1);
		$("div[id=d"+lhash+"]").slideToggle().toggleClass("logo_slider_closed").slideToggle("slow");
	}
	$("h2").click(function(){
		$(this).toggleClass("closed");
		var divid = "#d" + $(this).attr("id");
		$(divid).slideToggle().toggleClass("logo_slider_closed").slideToggle("slow");
	});
}
	
function formControls (whichForm) {
	// Form Validation and onChange code
	if (whichForm == "contact") {
    $("input[name=Submit]").click(checkContactForm);
  }
	if (whichForm == "req") {
		$("input[name=Submit]").click(checkReqForm);
		$("input[name=otherdetail]").parent("li").hide();
	}
	if (whichForm == "event") {
    $("input[name=Submit]").click(checkEventForm);
		$("input[name=otherdetail]").parent("li").hide();
	}
	
	// Manages Country/State/Province select elements, changes on country selected
	$("option.init").attr("selected","selected");
	$(".province").hide();
	$(".bill_province").hide();
	$("select[name=country]").change(function(){
		var country = $("select[name=country]").val();
		if(country == 'United States') {
			$(".state").show();
			$(".province").hide();
      if (whichForm == "req") {
      	$("label[for=state]").addClass("req");
  			$("label[for=province]").removeClass("req");
      }
			$("select[name=state]").attr("disabled","");
			$("select[name=state] option.init").attr("selected","selected");
			$("select[name=state] option.no_opts").attr("disabled","disabled");
			$("option.init").attr("selected","selected");
		} else if (country == 'Canada') {			
			$(".state").hide();
			$(".province").show();
			if (whichForm == "req") {
      	$("label[for=state]").removeClass("req");
			  $("label[for=province]").addClass("req");
      }
			$("select[name=province]").attr("disabled","");
			$("select[name=province] option.init").attr("selected","selected");
			$("select[name=province] option.no_opts").attr("disabled","disabled");
			$("option.init").attr("selected","selected");
		} else {
			$("label.state").show();
			$("label.province").hide();
			if (whichForm == "req") {
      	$("label[for=state]").removeClass("req");
			  $("label[for=province]").removeClass("req");
      }
			$("option.init").attr("selected","");
			$("option.no_opts").attr("disabled","");
			$("option.no_opts").attr("selected","selected");
			$("select[name=state]").attr("disabled","disabled");
			$("select[name=province]").attr("disabled","disabled");
		}
	});
	$("select[name=bill_country]").change(function(){
		var country = $("select[name=bill_country]").val();
		if(country == 'United States') {
			$(".bill_state").show();
			$(".bill_province").hide();
			$("select[name=bill_state]").attr("disabled","");
			$("select[name=bill_state] option.init").attr("selected","selected");
			$("select[name=bill_state] option.no_opts").attr("disabled","disabled");
			$("select[name=bill_state] option.init").attr("selected","selected");
		} else if (country == 'Canada') {
			$(".bill_state").hide();
			$(".bill_province").show();
			$("select[name=bill_province]").attr("disabled","");
			$("select[name=bill_province] option.init").attr("selected","selected");
			$("select[name=bill_province] option.no_opts").attr("disabled","disabled");
			$("select[name=bill_province] option.init").attr("selected","selected");
		} else {
			$("label.bill_state").show();
			$("label.bill_province").hide();
			$("select[name=bill_province] option.init").attr("selected","");
			$("select[name=bill_state] option.init").attr("selected","");
			$("select[name=bill_province] option.no_opts").attr("disabled","");
			$("select[name=bill_state] option.no_opts").attr("disabled","");
			$("select[name=bill_province] option.no_opts").attr("selected","selected");
			$("select[name=bill_state] option.no_opts").attr("selected","selected");
			$("select[name=bill_state]").attr("disabled","disabled");
			$("select[name=bill_province]").attr("disabled","disabled");
		}
	});

  // Show Other field when other is selected in the dropdown list
  if (whichForm == "req" || whichForm == "event") {
		$("select[name=heardthrough]").change(function(){
			if($(this).val() == "Other") {
				$("input[name=otherdetail]").parent("li").slideDown();
				$("input[name=otherdetail]").attr("disabled","");
			} else if ($("input[name=otherdetail]").is(":visible")) {
					$("input[name=otherdetail]").val("");
					$("input[name=otherdetail]").attr("disabled","disabled");
					$("input[name=otherdetail]").parent("li").slideUp();
			}
		});
	}
}

// Form validating
function checkContactForm () {
  checkForms("contact");
}
function checkReqForm() {
  checkForms("req");
}
function checkEventForm() {
  checkForms("event");
}

// Generic form validation function
function checkForms(formType) {
	var oktosave=true;
	var errormsg="";
	var errorfields=[];
	var num_errs=0;
	
	// Check inputs with labels classes as req (required)
  var reqFieldLabels = $("label.req");
  var isBill = /bill_/i;
  for (var i=0; i<reqFieldLabels.length;i++) {
    targetName = reqFieldLabels.eq(i).attr("for");

    if (!(checkForVal(targetName))) {
      errormsg = "One or more required fields are empty or haven't been selected.";
		  errorfields[num_errs] = $("label[for="+targetName+"]").text().substr(2);
      if (isBill.test(targetName)) {errorfields[num_errs] = "Billing " + $("label[for="+targetName+"]").text().substr(2);}
		  num_errs++;
		  oktosave = false;
    }
  }
  
  // Check email address(es)
  var emailValid = true;
  var billEmailValid = true;
  var emailFlag = -1;
  var billEmailFlag = -1;
  var emailerr1 = "";
	var emailerr2 = "";
  var bemailerr1 = "";
	var bemailerr2 = "";

  emailFlag = checkEmail ("email", "emailconf");
  if (($("input[name=paying]:checked").val() == "invoice") && ($("input[name=bill_same_info]").attr("checked") == false)) {
    billEmailFlag = checkEmail ("bill_email", "bill_emailconf");
  }

  // Set email errors
  switch (emailFlag) {
    case -1:
      // Email was valid
      emailValid = true;
      break;
    case 0:
      // Email has no text, caught earlier, just set to false but no extra errors
      emailValid = false;
      break;
    case 1:
      emailerr1 ="The email addresses you entered do not match.  Please check your email address fields and try again.";
  		errorfields[num_errs] = "Email Address &amp; Confirm Email Address";
  		num_errs++;
      emailValid = false;
      break;
    case 2:
      emailerr2 = "There was a problem with the email address you entered.  Please enter an address in the form of name@domain.com";
			errorfields[num_errs] = "Email Address:";
			num_errs++;
      emailValid = false;
			break;
  }

  // Set email errors
  switch (billEmailFlag) {
    case -1:
      // Email was valid or field does not exist
      billEmailValid = true;
      break;
    case 0:
      // Email has no text, caught earlier, just set to false but no extra errors
      billEmailValid = false;
      break;
    case 1:
      bemailerr1 ="The billing email addresses you entered do not match.  Please check your billing email address fields and try again.";
  		errorfields[num_errs] = "Billing Email Address &amp; Billing Confirm Email Address";
  		num_errs++;
      billEmailValid = false;
      break;
    case 2:
      bemailerr2 = "There was a problem with the billing email address you entered.  Please enter an address in the form of name@domain.com";
			errorfields[num_errs] = "Billing Email Address:";
			num_errs++;
      billEmailValid = false;
			break;
  }




  // If not ok to save or email was invalid, create error div, display and scroll the page up to see it
  if (!oktosave || !emailValid || !billEmailValid) {
		$("div.err").remove();
		var errorDiv = $("<div />");
		errorDiv.addClass("err");
		$("<h3>The following field(s) have errors: </h3>").appendTo(errorDiv);
		var errorList = $("<ul />");
		for (var i=0; i < num_errs; i++) {
			$("<li>"+errorfields[i]+"</li>").appendTo(errorList);
		}
		errorList.appendTo(errorDiv);
		if(errormsg != "") $("<h3>"+errormsg+"</h3>").appendTo(errorDiv);
		if(emailerr1 != "") $("<h3>"+emailerr1+"</h3>").appendTo(errorDiv);
		if(emailerr2 != "") $("<h3>"+emailerr2+"</h3>").appendTo(errorDiv);
		if(bemailerr1 != "") $("<h3>"+bemailerr1+"</h3>").appendTo(errorDiv);
		if(bemailerr2 != "") $("<h3>"+bemailerr2+"</h3>").appendTo(errorDiv);
		errorDiv.appendTo($("#errors"));
		$(window).scrollTo(150,900);
	}

  // If everything is good, submit the form
	if (oktosave && emailValid && billEmailValid) {
    $("div.err").remove();
		if (formType == "contact") {$("#formContact").submit();}
		if (formType == "req") {
      $.cookie('form_submitted', 'true', { expires: 365 });
		  $("#formRequest").submit();
    }
    if (formType == "event") {$("#formEvent").submit();}
	}
}
	
function checkForVal (inputName) {
  // passed the name of a form field, checks to see if it is
  // Input: not empty
  // Input Checkbox: something checked
  // Input Radio: something selected
  // Select: not initial (first) element (usually --Select One-- or similar)
  //
  // If the criteria is not set, sets err class on form field and the associated label

  if (($("input[name="+inputName+"]").length != 0) && ($("input[name="+inputName+"]").attr("type") != "radio") && ($("input[name="+inputName+"]").attr("type") != "checkbox") && ($("input[name="+inputName+"]").attr("disabled") == "")) {
    // validate text box
    if ($("input[name="+inputName+"]").val() == "") {
      $("input[name="+inputName+"]").addClass("err");
      $("label[for="+inputName+"]").addClass("err");
      return false;
  	} else {
      $("input[name="+inputName+"]").removeClass("err");
      $("label[for="+inputName+"]").removeClass("err");
  		return true;
  	}
  } else if ($("input[name="+inputName+"]").attr("type") == "radio") {
    // validate radio button
    if($("input[name="+inputName+"]:checked").length == 0) {
      $("label[for="+inputName+"]").addClass("err");
      return false;
    } else {
      $("label[for="+inputName+"]").removeClass("err");
      return true;
    }
  } else if ($("input[name="+inputName+"]").attr("type") == "checkbox") {
    // validate checkbox
    if($("input[name="+inputName+"]:checked").length == 0) {
      $("label[for="+inputName+"]").addClass("err");
      return false;
    } else {
      $("label[for="+inputName+"]").removeClass("err");
      return true;
    }
  } else if ($("select[name="+inputName+"]").length != 0 && ($("select[name="+inputName+"]").attr("disabled") == "")) {
    // validate select
    if($("select[name="+inputName+"]").val() == "") {
      $("label[for="+inputName+"]").addClass("err");
      return false;
    } else {
      $("label[for="+inputName+"]").removeClass("err");
      return true;
    }
  } else return true; // don't attempt to validate anything except specificied elements
}

function checkEmail (emailElement, emailConfElement) {
  var email = "";
  var emailConf = "";
  if ($("input[name="+emailElement+"]").length > 0) {email = $("input[name="+emailElement+"]").val();}
  if ($("input[name="+emailConfElement+"]").length > 0) {emailConf = $("input[name="+emailConfElement+"]").val();}
  if (email == "") {return 0;}
  var newreg = /^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i;  //set up email parameters
	var emailCorrect = true;

	if (email != "")	{ //see if found
			emailCorrect=newreg.test(email);
      if (emailCorrect) {
				// Valid email address entered
				if($("input[name="+emailConfElement+"]").length > 0) {
          // Check email confirm box for match to email box
  				if(email == emailConf) {
  					$("input[name="+emailElement+"]").removeClass("err");
  					$("label[for="+emailElement+"]").removeClass("err");
  					$("input[name="+emailConfElement+"]").removeClass("err");
  					$("label[for="+emailConfElement+"]").removeClass("err");
            return -1;
  				} else {
  					$("input[name="+emailElement+"]").addClass("err");
  					$("label[for="+emailElement+"]").addClass("err");
  					$("input[name="+emailConfElement+"]").addClass("err");
  					$("label[for="+emailConfElement+"]").addClass("err");
            return 1;
  				}
        } else {
          // Email was correct, no confirm box
          $("input[name="+emailElement+"]").removeClass("err");
  				$("label[for="+emailElement+"]").removeClass("err");
  				$("input[name="+emailConfElement+"]").removeClass("err");
  				$("label[for="+emailConfElement+"]").removeClass("err");
          return -1;
        }
			}	else {
				$("input[name=email]").addClass("err");
				$("label[for=email]").addClass("err");
        $("input[name=emailconf]").addClass("err");
        $("label[for=emailconf]").addClass("err");
        return 2;
			}
		}
		return 0;
}
function checkFormCookies () {
  // Checks if there is a cookie set (for req forms) and bypass form page if so
	var isFormSubmitted = $.cookie('form_submitted');	
	if (isFormSubmitted == "true") {
				var formPage = $("input[name=redirect]").val();
				window.location.replace(formPage);
			}
	}
function eventRegAA () {
  // How paying
    $("input[name=paying]").click(function(){
			if($("input[name=paying]:checked").val() == "speaker_sponsor") {
				if($("fieldset#billing_info").is(":visible")) {
					$("fieldset#billing_info").slideUp();
          $("fieldset#billing_info input").attr("disabled","disabled");
          $("fieldset#billing_info select").attr("disabled","disabled");
				}
				$("input[name=redirect]").val("../news-events/thankyou-event-registration-aa.shtml");
			}
			else if($("input[name=paying]:checked").val() == "cc_paypal") {
				if($("fieldset#billing_info").is(":visible")) {
					$("fieldset#billing_info").slideUp();
					$("fieldset#billing_info input").attr("disabled","disabled");
          $("fieldset#billing_info select").attr("disabled","disabled");
				}
				$("input[name=redirect]").val("../news-events/thankyou-event-registration-aapp.shtml");
			}
			else {
				$("fieldset#billing_info").slideDown();
        $("fieldset#billing_info input").attr("disabled","");
        $("fieldset#billing_info select").attr("disabled","");
        $("fieldset#billing_info select").removeClass("err");
        $("fieldset#billing_info input").removeClass("err");
        $("fieldset#billing_info label").removeClass("err");
        $("input[name=bill_same_info]").data("billing_info","enabled");
		    $("input[name=bill_same_info]").attr("checked",""); // Make sure it unchecked when shown
        $("input[name=redirect]").val("../news-events/thankyou-event-registration-aa.shtml");
			}
		});


		$("input[name=bill_same_info]").data("billing_info","enabled");
		$("input[name=bill_same_info]").attr("checked",""); // Make sure it unchecked on page load
		$("fieldset#billing_info input").attr("disabled","disabled");
    $("fieldset#billing_info select").attr("disabled","disabled");
    $("input[name=bill_same_info]").attr("disabled","");

    // If not paying by invoice, hide billing info section of form
    if(!($("input[name=paying]:checked").val() == "invoice")) {
			$("fieldset#billing_info").hide();
		} else {
      $("fieldset#billing_info input").attr("disabled","");
      $("fieldset#billing_info select").attr("disabled","");
    }

    // Enable / Disable form fields based on checkbox
    $("input[name=bill_same_info]").click(function(){
      if($(this).data("billing_info") == "enabled") {
  		  $("fieldset#billing_info input").attr("disabled","disabled");
        $("fieldset#billing_info select").attr("disabled","disabled");
  			$(this).attr("disabled","");
  			$(this).data("billing_info","disabled");
        $("fieldset#billing_info select").removeClass("err");
        $("fieldset#billing_info input").removeClass("err");
        $("fieldset#billing_info label").removeClass("err");
			} else {
				$("fieldset#billing_info input").attr("disabled","");
        $("fieldset#billing_info select").attr("disabled","");
				$(this).attr("disabled","");
				$(this).data("billing_info","enabled");
			}
		});
}

function superfishIt() {
  // Apply if not IE and allow animations
  if (!($.browser.msie)) {
    $("ul#main_nav").superfish({
      animation: {height:'show',opacity:'show'},
      speed: 200,
      delay: 300,
      autoArrows: false,
      dropShadows: false
    });
  }

  // Apply if IE8 or newer; No Superfish menus for IE7
  if ($.browser.msie && $.browser.version.substr(0,1)>7) {
    $("ul#main_nav").superfish({
      speed:0,
      delay: 200,
      autoArrows: false,
      dropShadows: false
    });
  }

  // Apply if IE6
  if ($.browser.msie && $.browser.version.substr(0,1)<7) {
    $("ul#main_nav").superfish({
      animation: {height:'show',opacity:'show'},
      speed: 200,
      delay: 500,
      autoArrows: false,
      dropShadows: false
    });
  }
}
function fixIE6 () {
  $.ajaxSetup({async: false});
  $.getScript('/js/DD_belatedPNG_0.0.8a-min.js');
  $.ajaxSetup({async: true});
  
  $("#subnav > li").css({'display':'none'});
  $("#subnav > li ul li > ul").css({'display':'none'});
  var cur_page = top.location.pathname;
  $("#subnav a[href="+cur_page+"]").parents("li").css({'display':'block'});
  $("#subnav li.nav_sublinks").css({'display':'block'});
  if ($("#subnav a[href="+cur_page+"]").length == 0) {
    if (cur_page.indexOf("press-releases") != -1) {
      $("#subnav li.nav_news").css({'display':'block'}).addClass("current");
    }
    if (cur_page.indexOf("research-white-papers") != -1) {
      $("#subnav li.nav_rese").css({'display':'block'}).addClass("current");
    }
  }
  $("#products #subnav li.nav_prod,.t3_chan_meas #subnav li.nav_prod li.chan_measures ul,.t3_comp_meas #subnav li.nav_prod li.comp_measures ul,.t3_analysis #subnav li.nav_prod li.analysis ul,.t3_integration #subnav li.nav_prod li.integration ul,.t3_prod_adv #subnav li.nav_prod li.prod_advantages ul,.t3_prod_sci #subnav li.nav_prod li.prod_science ul,#solutions #subnav li.nav_solu,.t3_non_prof #subnav li.nav_solu li.non_profits ul,.t3_priv_sect #subnav li.nav_solu li.priv_sector ul,.t3_govt #subnav li.nav_solu li.govt ul,#research #subnav li.nav_rese,.t3_industry #subnav li.nav_rese li.industry ul,.t3_subject #subnav li.nav_rese li.subject ul,#company #subnav li.nav_comp,#news #subnav li.nav_news,.t3_user_summit #subnav li.nav_news li.user_summit ul,#blogs #subnav li.nav_blog").css({'display': 'block'});
  
  $("#subnav > li > a").css({'background':'url(/images/snav_arrow_lev1.png) 4% 35% no-repeat','padding-left':'18px'});
  $("#subnav ul li > a").css({'border-bottom':'1px solid #e7e7e8'});
  $("#subnav ul li.sublast > a").css({'border-bottom':'none'});

  DD_belatedPNG.fix('#main_nav, #tnav, #logo img, #tease_center h3, #footer #social li, #subnav, .img_container img, td p img, .quote, .quote img, #content_col p img, .logos, form input, form textarea, #primaryNav li, #primaryNav li a, #subnav li.current a');
}

function checkNavExtender() {
	if ($(window).width() < 960) {
		$("#tnav_extender").css("display", "none");
	}
	else {
		$("#tnav_extender").css("display", "block");
	}
}

$(function(){
  $.ajaxSetup({async: false});
  $.getScript('/js/hoverIntent.js');
  $.getScript('/js/superfish.js');
  $.ajaxSetup({async: true});

  superfishIt();

  checkNavExtender();
	$(window).resize(function() {	checkNavExtender(); });

  // IE6 Fixes
  if ($.browser.msie && $.browser.version.substr(0,1)<7) {
    fixIE6();
  }
});
