var count = 0;
//Document Ready
$(function(){
		 
	if($.trim($("#contactform :input[name=state]").val()) != "" && !($('#notlisted').is(':checked')) ) {
		updateSchoolsContact($("#contactform :input[name=state]").val());
	}
	
	$(".signInLink").click(signIn);
	$(".signUpLink").click(signUp);
	$(".checkSignedInLink").click(checkSignedIn);

	$("#createnewaccount").click(function(event){
	
		// Prevent the default action
			event.preventDefault();
	
		// First thing we do is close the signIn Dialog Box
			var loginBox = $("#loginbox");
			
			loginBox.dialog("close");
			
		// Now open up the registration box.
			signUp();
		
	});
	
	$("#forgotpassword").click(function(event){
	
		// Prevent the default action
			event.preventDefault();
	
		// First thing we do is close the signIn Dialog Box
			var loginBox = $("#loginbox");
			
			loginBox.dialog("close");
			
		// Now open up the registration box.
			forgotPassword();
		
	});
	
	
	
	$("#closeRegistrationBox").click(function(event){
	
		// Prevent the default action
			event.preventDefault();
	
		// First thing we do is close the signIn Dialog Box
			var registerBox = $("#registrationbox");			
			registerBox.dialog("close");		
	});
	
	 
	/* Allow IE to submit forms using the <button> tag */
	$(function(){
		$('input').keydown(function(e){
			if (e.keyCode == 13) {
				$(this).parents('form').submit();
				return false;
			}
		});
	});
			   
	 // bind to the form's submit event 
    $('#loginform').submit(function() { 
        // inside event callbacks 'this' is the DOM element so we first 
        // wrap it in a jQuery object and then invoke ajaxSubmit 
		
        $(this).ajaxSubmit({
						   
				dataType: 'text',
				beforeSubmit: function(formData, jqForm, options){
					 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]; 
				 		$('#signinBTN').attr("disabled", "true");
					//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; 
				},
				error: function(obj, e){
					
					alert(e);
				},
				success: function(text2) {
					//remove submitType after submission
					//and restore name to button
					
					//alert("text = "+text2);	
					
					if(text2 == ""){
						// We got a response back from the login_ajax.jsp page which tells
						// us what URL to go to.
						//							
						// Refresh to the URL of the link
						
							var currentlocation = $(".signInLink").attr("href");
							
							var loginformcontent = $("#loginformcontent").hide();
							var processingBox = $("#processingBox").show();
							
							//alert("redirecting to "+text2);
							// Delay the refresh for 1 second
							var loginBox = $("#loginbox");
							var successFn = loginBox.data("successFn");
							if(typeof successFn != 'undefined' && successFn != null) {
								successFn(currentlocation);
								
							} else {
								window.location.href = currentlocation;
							}
							return;
						
					}else{
						$('#signinBTN').attr("disabled", "");
						$("#response").html(trim(text2));
						return;
					}
				}
	
		}); 
 
        // !!! Important !!! 
        // always return false to prevent standard browser submit and page navigation 
        return false; 
    });	  
	
	
	 // bind to the form's submit event 
    $('#forgotpasswordform').submit(function() { 
        // inside event callbacks 'this' is the DOM element so we first 
        // wrap it in a jQuery object and then invoke ajaxSubmit 
		
        $(this).ajaxSubmit({
						   
				dataType: 'text',
				beforeSubmit: function(formData, jqForm, options){
					 var queryString = $.param(formData); 
	 
	 					//alert("before submit");
					// jqForm is a jQuery object encapsulating the form element.  To access the 
					// DOM element for the form do this: 
					// var formElement = jqForm[0]; 
				 		$('#forgotPasswordBTN').attr("disabled", "true");
					//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; 
				},
				error: function(obj, e){
					
					alert(e);
				},
				success: function(text2) {
					//remove submitType after submission
					//and restore name to button
					
					//alert("text = "+text2);	
					
					if(text2 == ""){
						// We got a response back from the login_ajax.jsp page which tells
						// us what URL to go to.
						//							
						// Refresh to the URL of the link
						var forgotPasswordBox = $("#forgotpasswordbox");
						forgotPasswordBox.dialog("close");
						
						var forgotPasswordSuccessBox = $("#forgotpasswordsuccess_box");
						if(forgotPasswordSuccessBox.is(".ui-dialog-content")) {
							forgotPasswordSuccessBox.dialog("open");
						} else {
							forgotPasswordSuccessBox.dialog({
								autoOpen:true, 
								resizable:false,
								width:350, 
								height:350, 
								draggable:false, 
								modal:true,
								overlay:{
								 backgroundColor:"#000",
								 opacity:"0.45"
								},
								title:"Password has been sent",
								closeable:true
						   });
						}
						
						
					}else{
						$('#forgotPasswordBTN').attr("disabled", "");
						$("#forgotresponse").html(trim(text2));
						return;
					}
				}
	
		}); 
 
        // !!! Important !!! 
        // always return false to prevent standard browser submit and page navigation 
        return false; 
    });	  
	
		
	
	$("#termsconditions_link").click(function(){	
			
		/* $("#uploadSpreadsheetBTN").attr("disabled",false); */
		var termsBox = $("#termsandconditions_box");
		if(termsBox.is(".ui-dialog-content")) {
			termsBox.dialog("open");
		} else {
			termsBox.dialog({
				autoOpen:true, 
				resizable:false,
				width:400, 
				height:600, 
				draggable:false, 
				modal:true,
				overlay:{
				 backgroundColor:"#000",
				 opacity:"0.45"
				},
				title:"Tech Ed Terms and Conditions",
				closeable:true
		   });
		}
	});
	
	$("#g8sweepsrules_link").click(function(){	
			
		/* $("#uploadSpreadsheetBTN").attr("disabled",false); */
		var g8RullesBox = $("#g8sweepsrules_box");
		if(g8RullesBox.is(".ui-dialog-content")) {
			g8RullesBox.dialog("open");
		} else {
			g8RullesBox.dialog({
				autoOpen:true, 
				resizable:false,
				width:400, 
				height:600, 
				draggable:false, 
				modal:true,
				overlay:{
				 backgroundColor:"#000",
				 opacity:"0.45"
				},
				title:"Pontiac G8 GT Sweepstakes",
				closeable:true,
				position:['center','top']
		   });
		}
	});


	// Event that fires when submit button is clicked on the registration form
	$('#registerform').submit(function() {
								
		$("#registerBTN").attr("value","Submitting...");							
		$("#registerBTN").attr("disabled","disabled");							   
									   
	//$("#registerBTN").click(function(event){
	
		var errors = 0;
		var messageErrors = "";
		//var forms = $(".registerform");
		
		//alert("STARTING TO SUBMIT "+forms);
		
		//var submitForms = function(jqForm){
		
			$(this).ajaxSubmit({
				dataType: 'text',
				beforeSubmit: function(formData, jqForm, options){
					 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; 
				},
				error: function(obj, e){
					
					alert(e);
				},
				success: function(text) {
					//remove submitType after submission
					//and restore name to button
					var hasErrors = false;
					
					
					// First remove all the registererror class from all the ID's
					$("#username_register").removeClass("registererror");
					$("#password").removeClass("registererror");
					$("#password2").removeClass("registererror");
					$("#emailaddress").removeClass("registererror");
					$("#schoolstate").removeClass("registererror");
					$("#schoolname").removeClass("registererror");
					$("#instructorname").removeClass("registererror");
					$("#enrolltype").removeClass("registererror");
					$("#vtterms").removeClass("registererror");
					$("#graddate").removeClass("registererror");
					
					$("#usernameTxt").html("");
					$("#passwordTxt").html("");
					$("#password2Txt").html("");	
					$("#emailaddressTxt").html("");
						
					var errorString = trim(text);
					var gotoStep = 3;

					// Step 3
						if(errorString.indexOf("[username]") >= 0){			$("#username_register").addClass("registererror");		gotoStep = 3;	hasErrors = true;	}
						else if(errorString.indexOf("[usernamespaces]") >= 0){	
							$("#username_register").addClass("registererror");
							$("#usernameTxt").html("Username CAN'T contain any spaces");
							gotoStep = 3;
							hasErrors = true;
						}	
						else if(errorString.indexOf("[usernamelength]") >= 0){
							$("#username_register").addClass("registererror");
							$("#usernameTxt").html("Username has to be 6 - 12 characters long");
							gotoStep = 3;
							hasErrors = true;
						}
						else if(errorString.indexOf("[usernameexists]") >= 0){
							$("#username_register").addClass("registererror");
							$("#usernameTxt").html("Username "+$("#registerform :input[name=username]").val()+" already exists.  Please choose another username.");
							gotoStep = 3;
							hasErrors = true;
						}
						
						if(errorString.indexOf("[password]") >= 0){				$("#password").addClass("registererror");		gotoStep = 3;hasErrors = true;	}							
						if(errorString.indexOf("[passwordconfirm]") >= 0){		$("#password2").addClass("registererror");		gotoStep = 3;hasErrors = true;	}
						
						if(errorString.indexOf("[passwordlength]") >= 0){
							$("#password").addClass("registererror");
							$("#password2").addClass("registererror");
							$("#passwordTxt").html("Password has to be 6 - 8 characters long");
							$("#password2Txt").html("Password has to be 6 - 8 characters long");							
							gotoStep = 3;
							hasErrors = true;
						}
						else if(errorString.indexOf("[passwordmatch]") >= 0){
							$("#password").addClass("registererror");
							$("#password2").addClass("registererror");
							$("#passwordTxt").html("Passwords do not match");
							$("#password2Txt").html("Passwords do not match");	
							gotoStep = 3;
							hasErrors = true;
						}
						
						if(errorString.indexOf("[email]") >= 0){				$("#emailaddress").addClass("registererror");	gotoStep = 3;hasErrors = true;		}
						else if(errorString.indexOf("[emailvalid]") >= 0){
							$("#emailaddress").addClass("registererror");
							$("#emailaddressTxt").html("Please enter a valid email address (abc@123.com)");	
							gotoStep = 3;
							hasErrors = true;
						}
						else if(errorString.indexOf("[emailexists]") >= 0){
							$("#emailaddress").addClass("registererror");
							$("#emailaddressTxt").html("E-mail is already used by another account");	
							gotoStep = 3;
							hasErrors = true;
						}
												
						if(errorString.indexOf("[terms]") >= 0){				$("#vtterms").addClass("registererror");		gotoStep = 3;	hasErrors = true;	}
					
					// Step 2
						if(errorString.indexOf("[schoolstate]") >= 0){			$("#schoolstate").addClass("registererror");	gotoStep = 2;	hasErrors = true;	}							
						if(errorString.indexOf("[schoolname]") >= 0){			$("#schoolname").addClass("registererror");		gotoStep = 2;hasErrors = true;		}							
						if(errorString.indexOf("[instructorname]") >= 0){		$("#instructorname").addClass("registererror");	gotoStep = 2;	hasErrors = true;	}
						if(errorString.indexOf("[graddate]") >= 0){				$("#graddate").addClass("registererror");		gotoStep = 2;hasErrors = true;		}	
					
					// Step 1
						if(errorString.indexOf("[enrollment]") >= 0){			$("#enrolltype").addClass("registererror"); gotoStep = 1;hasErrors = true;	}
						
						
					//alert("hasErrors = "+hasErrors);	
						
					if(hasErrors){	
						// Enable the Submit button
						$("#registerBTN").attr("disabled","");
						$("#registerBTN").attr("value","Submit");
														 
						if(gotoStep == 1){
							// Only move the registration slides
							// if the user isn't on the first slide
							if(count > 0){
								resetRegistrationForm();
							}
						}else if(gotoStep == 2){
							
							
							
							// IF the user is on the first slide
							// move the slide to the left
							// ELSE IF
							// move the slide to the right if they are
							// on the third slide
							// ELSE
							// keep them on the slide they are on
							
							if(count == 0){
								$("#wrapper").animate({
									marginLeft: "-=570px"
								}, 600);
							}else if(count == 2){							
								$("#wrapper").animate({
									marginLeft: "+=570px"
								}, 600);
							}
							
							count = 1;
							step(count);
						}else if(gotoStep == 3){
							
							if(count == 0){
								$("#wrapper").animate({
									marginLeft: "-=1140px"
								}, 600);
							}else if(count == 1){							
								$("#wrapper").animate({
									marginLeft: "-=570px"
								}, 600);
							}
							
							count = 2;
							step(count);
							
						}
					
						$("#registerresponse").html("Please correct the fields in red");
					}else{
							
						// We now need to refresh the page so that the proper information is displayed
						// such as Student Pricing now that the user is signed in.
						var currentlocation = $(".signUpLink").attr("href")+"?register=thankyou";
						//alert("refresh to = "+currentlocation);
						window.location.href = currentlocation;
						return;					
						
					}
					
				}
			});
		//}
		
		//submitForms(forms);
		
		 // !!! Important !!! 
        // always return false to prevent standard browser submit and page navigation 
        return false; 

	});
	
	
	// Next and Previous buttons used in the registration process
	$(".right").click(function(){
		$("#wrapper").animate({
			marginLeft: "-=570px"
		}, 600);
	
		count++;
		step(count);
	});	

	$(".left").click(function(){
		$("#wrapper").animate({
			marginLeft: "+=570px"
		}, 600);
		
		count--;
		step(count);
	});
	
	step(count);

	// Generating the current year
	var now         = new Date();
	var year        = now.getYear();
	if(year < 2000) { year = year + 1900; }
	
	$("#currentYear").html(""+year);
		
});



var signIn = function(event, fn){
	/* Make the disable button NOT disabled */
	$('#signinBTN').attr("disabled", "");
	
	var loginBox = $("#loginbox");
	if(!loginBox.data("hasDialog")) {
		loginBox.dialog({
			autoOpen:true, 
			resizable:false,
			width:350, 
			height:350, 
			draggable:false, 
			modal:true,
			overlay:{
			 backgroundColor:"#000",
			 opacity:"0.45"
			},
			title:"Sign Into Your Account",
			closeable:true
	   });
		loginBox.data("hasDialog",true);
	} else {
		loginBox.dialog("open");
	}
	loginBox.data("successFn",fn);
	document.loginform.username.focus();
	
	event.preventDefault();
		
}
var signUp = function(event){
		
	resetRegistrationForm();	
	
	var registrationBox = $("#registrationbox");
	
	if(!registrationBox.data("hasDialog")) {
		registrationBox.dialog({
			autoOpen:true, 
			resizable:false,
			width:600, 
			height:520, 
			draggable:false, 
			modal:true,
			overlay:{
			 backgroundColor:"#000",
			 opacity:"0.45"
			},
			title:"Sign Up Now",
			closeable:true
	   });
	}else{
		registrationBox.dialog("open");			
	}
	
	event.preventDefault();
}

/* Checks to see if the loginID cookie exists.  If it does, they are signed in, otherwise, they need to sign in */
var checkSignedIn = function(event){
	var loginID = getCookie('loginID');
	var _this = this;
	if(loginID == ""){
		signIn(event, function(currentlocation){
			//do stuff here
			$(_this).click();
		});
		event.preventDefault();
	}else{
		if($(this).attr("href").indexOf(".jsp") == -1){
		
			$(this).parents("form").eq(0).submit();
		}else{
			
			window.location.href = $(this).attr("href");
			return;
		}
		
	}
	
}

var forgotPassword = function(event){
		
	var registrationBox = $("#forgotpasswordbox");
	
	if(!registrationBox.data("hasDialog")) {
		registrationBox.dialog({
			autoOpen:true, 
			resizable:false,
			width:350, 
			height:350, 
			draggable:false, 
			modal:true,
			overlay:{
			 backgroundColor:"#000",
			 opacity:"0.45"
			},
			title:"Forgot your password?",
			closeable:true
	   });
	}else{
		registrationBox.dialog("open");			
	}
	
}


/* Cookie function to get the value of a specific cookie */
function getCookie(c_name)
{
if (document.cookie.length>0){
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1){ 
    c_start=c_start + c_name.length+1; 
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    } 
  }
return "";
}

function toggleContainer(targetId,textId)
{
	target = document.getElementById(targetId);
	link_textt = document.getElementById(textId);

	if (target.style.display == "none")
	{
		target.style.display="";
		link_textt.innerHTML = "Hide";
	} 
	else 
	{
		target.style.display="none";
		link_textt.innerHTML = "Show";
	}
}


function checkAll(field)
{
	var text = document.getElementById('checktext');
	if(text.innerHTML == "Check All"){

	for (i = 0; i < field.length; i++)
		field[i].checked = true ;
	
		text.innerHTML = "Uncheck All";	
	}
	else{
		for (i = 0; i < field.length; i++)
			field[i].checked = false ;
			
		text.innerHTML = "Check All";
	}
}

function step(num){

	if(num == 0){
		$("#step").html("Step 1 of 3");		
	}else if(num == 1){
		$("#step").html("Step 2 of 3");		
		
	}else if(num == 2){
		
		$("#step").html("Step 3 of 3");		
	}
	
}

 
function changeBG(containerName, image){
	div = document.getElementById(containerName);
	//alert(div.style.backgroundImage);
	div.style.backgroundImage = "url(/TechEd/images/"+image+")";
}


function hideLayer(whichLayer) {

	target = document.getElementById(whichLayer);

	if (target.style.display == ""){
		target.style.display="none";
	} 
}

function showLayer(whichLayer) {	
	target = document.getElementById(whichLayer);	
	target.style.display="";	
}

// Used in the contact form
function handleClick(whichClick) {
	if (whichClick == "showstu") {
		hideLayer("instructor1");
		hideLayer("instructor2");
		hideLayer("instructor3");
		hideLayer("instructor4");
		
		showLayer("student1");
		showLayer("student2");
	
	}
	else if (whichClick == "showinstr") {
		showLayer("instructor1");
		showLayer("instructor2");
		showLayer("instructor3");
		showLayer("instructor4");
		
		hideLayer("student1");
		hideLayer("student2");
	}
	
	else if (whichClick == "showmatcorepname") {
		showLayer("matcorepname");
	}
	
	else if (whichClick == "hidematcorepname") {
		hideLayer("matcorepname");
	}
}

function toggle(targetId){
	target = document.getElementById(targetId);
	if (target.style.display == "none"){
		target.style.display="";
	} 
	else{
		target.style.display="none";
	}
}

// Internal function used when getting output from the ajax pages
function trim(s){
	var l=0; var r=s.length -1;
	while(l < s.length && s[l] == ' ')
	{	l++; }
	while(r > l && s[r] == ' ')
	{	r-=1;	}
	return s.substring(l, r+1);
}

// Brings the user back to the first Step in the registration process
function resetRegistrationForm(){
	// Reset the step variable
	count = 0;
	step(count);	
	
	// Reset the form to the beginning
	$("#wrapper").animate({
		marginLeft: "0px"
	}, 0);
	
	
}

// Used in the Recommend a Friend page
function checkReferForm(d){
	if(d.Email_0.value == ""){
	 alert("Please fill an your e-mail address");
	 return false;
	}
	else if(!validEmail(d.Email_0.value)){
	 alert("Please provide a valid e-mail address for your e-mail address.");
	 return false;
	}
	
	if(d.Email_1.value != "" && !validEmail(d.Email_1.value)){
	 alert("Please provide a valid e-mail address for "+d.Email_1.value);
	 return false;
	}
	
	if(d.Email_2.value != "" && !validEmail(d.Email_2.value)){
	 alert("Please provide a valid e-mail address for "+d.Email_2.value);
	 return false;
	}
	
	if(d.Email_3.value != "" && !validEmail(d.Email_3.value)){
	 alert("Please provide a valid e-mail address for "+d.Email_3.value);
	 return false;
	}
	
	if(d.Email_4.value != "" && !validEmail(d.Email_4.value)){
	 alert("Please provide a valid e-mail address for "+d.Email_4.value);
	 return false;
	}
	
	if(d.Email_5.value != "" && !validEmail(d.Email_5.value)){
	 alert("Please provide a valid e-mail address for "+d.Email_5.value);
	 return false;
	}

	
	if(	d.Email_5.value != "" || d.Email_4.value != "" || d.Email_3.value != "" || d.Email_2.value != "" || d.Email_1.value != ""){
		return true;	
	}else{
		alert("Please fill in at least 1 e-mail address to send this request to.");
		return false;
	}
	
}

function validEmail(email){
	var x = email;
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	
	if (!filter.test(x)){
		return false;
	}else{
		return true;	
	}
}
// Popup that is displayed after a successful registration
function displayRegisterThankYou(){
	
	var registerthankyou = $("#registerthankyou_box");
		if(registerthankyou.is(".ui-dialog-content")) {
			registerthankyou.dialog("open");
		} else {
			registerthankyou.dialog({
				autoOpen:true, 
				resizable:false,
				width:570, 
				height:320, 
				draggable:false, 
				modal:true,
				overlay:{
				 backgroundColor:"#000",
				 opacity:"0.45"
				},
				title:"Registration Complete",
				closeable:true
		   });
		}
}


/* Below functions are used on the Current Specials and New and Exclusives page */

function addKitCart(itemID, theForm) {
    theForm.quantity.value = "addKitCart";
    theForm.item.value = itemID;
    theForm.submit();
}

function addIndKitCart(itemID, theForm) {
    theForm.quantity.value = "addIndKitCart";
    theForm.item.value = itemID;
    theForm.submit();
}

function addWish(itemID, theForm) {
    theForm.quantity.value = "123456789";
    theForm.item.value = itemID;
    theForm.submit();
}

function addCart(longItemId,theForm){theForm.quantity.value=1;theForm.item.value=longItemId;theForm.submit();}

function attachLoadEvent(loadEvent){
	if(window.addEventListener){
			window.addEventListener("load",loadEvent,false);
	}else if(window.attachEvent){window.attachEvent("onload",loadEvent);
	}else if(window.onload){window.onload=loadEvent;}
}
