// JavaScript Document

$(document).ready(function(){
	$("#lightbox4").overlay({ 
			// some expose tweaks suitable for modal dialogs 
			expose: { 
			color: '#ffffff',
			loadSpeed: 200,
			opacity: 0.8
			},
			closeOnClick: false 
		});	
});

currentLightBox = undefined;
currentForm = undefined;
progressiveForm = {};
progressiveForm["form1"] = {};
progressiveForm["form1"].firstName = true;
progressiveForm["form1"].lastName = true;
progressiveForm["form1"].businessSize = true;

progressiveForm["form2"] = {};
progressiveForm["form2"].industry = true;
progressiveForm["form2"].companyName = true;
progressiveForm["form2"].postCode = true;


progressiveForm["form3"] = {};
progressiveForm["form3"].wireLessNum = true;
progressiveForm["form3"].wireLineNum = true;

progressiveForm["form4"] = {};
progressiveForm["form4"].jobTitle = true;
progressiveForm["form4"].role = true;
//progressiveForm["form4"].timeFrame = true;

progressiveForm["form5"] = {};
progressiveForm["form5"].firstNameContact = true;
progressiveForm["form5"].lastNameContact = true;
progressiveForm["form5"].buisnessSizeContact = true;
//progressiveForm["form5"].industryContact = true;
progressiveForm["form5"].companyNameContact = true;
progressiveForm["form5"].phoneContact = true;
progressiveForm["form5"].postCodeContact = true;
progressiveForm["form5"].wireLessNumContact = true;
progressiveForm["form5"].wireLineNumContact = true;

progressiveForm["form5"].emailAddressContact = true;
//progressiveForm["form5"].industryContact = true;
//progressiveForm["form5"].contactPrefContact = true;
//progressiveForm["form5"].alternateNumContact = true;

loadProfileForm = function(formId,optInBool,contactBool,assetID,emailAddress,firstName,lastName, loggedInBool, securedUserBool, businessSize, companyName, jobTitle, department, industry){
	//alert(formId+","+optInBool+","+contactBool+","+assetID+","+emailAddress+","+firstName+","+lastName)

	if (formId == "undefined")
		return;
	
	if (formId >= 7 && formId <= 9){
		scExp.setScenario({ 'scenario': formId, 'isOptIn':optInBool, 'isContact':contactBool, 'isLoggedIn':loggedInBool, 'isSecuredProfile':securedUserBool });
		scExp.userProfile = new scenarioProfile({ 'email':emailAddress, 'firstName':firstName, 'lastName':lastName, 'companySize':businessSize, 'companyName':companyName, 'jobTitle':jobTitle, 'department':department, 'industry':industry });
		scExp.openAsset(assetID);
		return;
	}
	
	trackPopUpFormItems('/Basic Profile Form Number:'+formId+"/View",'Basic Profile View',',Basic Profile Form Number:'+formId+",View");

	currentAssetID = assetID;	
	currentForm = Number(formId);
	
	 if(firstName != "undefined"){
		 $("#firstName").val(firstName);
		 
	 }
	 if(lastName != "undefined"){
		 $("#lastName").val(lastName);
		 
	 }
	if(optInBool != "true"){
		progressiveForm["form"+currentForm].emailAddress = true;
		 $("#emailAddressForm").css({"display":""});
		 if(emailAddress != "undefined"){
			 $("#emailAddress").val(emailAddress);
			 
		 }
	}else{
		progressiveForm["form"+currentForm].emailAddress = null;
		delete progressiveForm["form"+currentForm].emailAddress;
		 $("#emailAddressForm").css({"display":"none"});
	}
	if(optInBool != "true"){
		 $("#optInForm").css({"display":""});	
		  
	}else{
		 $("#optInForm").css({"display":"none"});
		 $("#optInForm").attr("checked",false);
	}
	if(contactBool != "true"){
		 $("#contactForm").css({"display":""});
	}else{
		 $("#contactForm").css({"display":"none"});		
	}
	
	// display the login when it's secured login and not logged in
	if (securedUserBool && !loggedInBool)
		$(".manageProfileLogin").show();
	else
		$(".manageProfileLogin").hide();
	
	var formLabel =  ".progression"+currentForm;
	 $(formLabel).css({"display":""});
	 $(".pop_1_form_overlay").css({"display":""});	 
	 
	 
}

function validate_email(value)
{	
	apos=value.indexOf("@");
	dotpos=value.lastIndexOf(".");
	if (apos<1||dotpos-apos<2){
	  return false;
	} else {
	  return true;
	}

}
function validate_postal(postalCode)
{
	//US
	//if (postalCode.match(/^[0-9]{5}$/)) {
		//return true;
	//}
	//CAN
	postalCode=postalCode.toUpperCase();
	if (postalCode.match(/^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$/)) {
		return true;
	}
	if (postalCode.match(/^[A-Z][0-9][A-Z].[0-9][A-Z][0-9]$/)) {
		return true;
	}

	return false;
} 

function validate_phone(strng) {

	var stripped = strng.replace(/[\(\)\.\-\ ]/g, ''); //strip out acceptable non-numeric characters
	if (isNaN(parseInt(stripped))) {
	   return false;
	}
	if (!(stripped.length == 10)) {
		return false;
	} 
	return true;
}


validatForm = function(type){
	//var wireLessChkId = "#"+wireLineNumchk;
	if(type == "contact"){
		currentForm = 5;	
		var wireLessNumchk = "#wireLessNumchkContact";
		var wireLineNumchk = "#wireLineNumchkContact";
		var wireLessNum = "wireLessNumContact";
		var wireLineNum = "wireLineNumContact";
	}else{
		var wireLessNumchk = "#wireLessNumchk";
		var wireLineNumchk = "#wireLineNumchk";	
		var wireLessNum = "wireLessNum";
		var wireLineNum = "wireLineNum";
	}
	if(currentForm != undefined){
		var validation = true;
		
		
		for(var a in progressiveForm["form"+currentForm]){
			var id = "#"+a;
			//var id = a.replace(/(:|\.)/g,'\\$1');
			var visible = "visible";
			
			//alert($("#wireLessNumchkContact").attr("type"))
			//if(a == "wireLessNum"){
				//alert($("#wireLessNumchk").attr("checked")+" -- " + validate_phone($(id).val()));
			//}
			
			if( $(id).attr("type")=="text"){
				if(a == "emailAddress" && !validate_email($(id).val())){					
					visible = "visible";	
					validation = false;
				}else if((a == "postCode" || a == "postCodeContact") && !validate_postal($(id).val())){					
					visible = "visible";	
					validation = false;
										
				}else if((a == "phoneContact")  && !validate_phone($(id).val())){	
					visible = "visible";	
					validation = false;
				}else if((a == wireLessNum && $(wireLessNumchk).attr("checked") == true)  && !validate_phone($(id).val())){	
				
				//}else if((a == wireLessNum)  && !validate_phone($(id).val())){	
					visible = "visible";	
					validation = false;
				//}else if((a == wireLineNum)  && !validate_phone($(id).val())){					
				}else if((a == wireLineNum && $(wireLineNumchk).attr("checked") == true)  && !validate_phone($(id).val())){					
					visible = "visible";	
					validation = false;
				}else if($(id).val() == '' && !(a == wireLessNum || a == wireLineNum)){
				//}else if($(id).val() == ''){	
					visible = "visible";	
					validation = false;
				}else{
					visible = "hidden";	
					/*if(a == wireLessNum || a == wireLineNum){
						var chkId = id+"chk";
						if($(chkId).attr("checked") == false)
							$(id).val("");					
					}*/
				}
			}else if( $(id).attr("type")=="select-one" ){
				if($(id).attr("selectedIndex") == 0){
					visible = "visible";
					validation = false;
				}else{
					visible = "hidden";	
				}
			}
			
			var display = visible == "visible" ? "inline" : "none";
			$(id).prev().find("span").css({"visibility":visible, 'display':display});	
		}
		
	
	}
	
	if(validation){
		if(type == "contact"){
			sendContact();
			
		}else{
			//alert($("#contactChk").attr("checked"));
			if($("#contactChk").attr("checked")){
				removeForm(true);
				$("#contactChk").attr("checked",false);
			}else{
				removeForm();	
			}
		}
		
	}
	
}


removeForm = function(showingContactBool){
	
	//testing contact
	//loadContact("#yesno");
	//return;
	if($("#optIn").attr("checked") == true){
		progressiveForm["form"+currentForm].optIn = "true";
	}else{
		progressiveForm["form"+currentForm].optIn = undefined;
	}
	if($("#contactChk").attr("checked") == true){
		progressiveForm["form"+currentForm].contact = "true";
	}else{
		progressiveForm["form"+currentForm].contact = undefined;
	}
	
	switch(currentForm){
		case 1:
			
			break;
		case 2:
			
			break;
		case 3:
			progressiveForm["form"+currentForm].wireLessNumchk = true;
			progressiveForm["form"+currentForm].wireLineNumchk = true;
			break;
		case 4:
			progressiveForm["form"+currentForm].timeFrame = true;
			break;
		
	}
	
	var subData = {};
	//profile.do

	subData.actionMethod = "submitProgressiveProfileForm";
	subData.assetId = currentAssetID;
	for(var a in progressiveForm["form"+currentForm]){
		var id = "#"+a;
		if($(id).attr("type")=="checkbox"){			
			subData[a] = String($(id).attr("checked"));
		}else{
			subData[a] = $(id).val();
		}
		
	}
	//return;
	
	 $('.resourcesShield').show();	
	
		$.ajax({
			url: "profile.do",
			type: "POST",
			data: (subData),
			dataType: "json",
			success: function (data, textStatus) {
			//	alert(data);
				//alert(data.success);
				if(data.success == true){
					hideProgressiveForm(showingContactBool,$("#optIn").attr("checked"));
				}else{
					/*{"propertyMessages":[{"property":"contact.user.emailAddress","messages":["This email address is already in our records."]}],"success":false}*/
					//alert(data.propertyMessages[0].messages[0]);
					if(data.propertyMessages != undefined){
						$("#profileFormValidationErrorID").html("<p>"+data.propertyMessages[0].messages[0]+"</p>");
					}else{
						if(data.globalMessages != undefined){
							var errorMessage = getMessageText(data); 
							var pleaseLoginMessage = "please login";
							if (errorMessage.toLowerCase().substr(0, pleaseLoginMessage.length) == pleaseLoginMessage)
								$(".manageProfileLogin").show();
							else
							$("#profileFormValidationErrorID").html("<p>"+data.globalMessages[0]+"</p>");
						}
						
					}
				}
				$('.resourcesShield').hide();	
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				//alert("error");
				
			}
		});


	 
}

hideProgressiveForm = function(showingContactBool,optInBool){
	 removeProfileForm(); 
	 if(showingContactBool == undefined){
		goBackToFlash();
	 }else{
		loadContact();	 
	 }	
	 
	/* if(trackingFeature){
		loadDoubleClick("feature",false,optInBool);
	}
	if(trackingSpotLight){
		loadDoubleClick("topic",false,optInBool);
	}*/
	//always track no matter what
	loadDoubleClick("feature",false,optInBool);
	
	var tempName = "/Basic Profile";
	var tempEvent = "event12";
	//var tempHier = ",Basic Profile";
	 if(optInBool ){
		 tempName +="/Opt in";
		 tempEvent +=",event10";
		 //tempHier +=",Opt in";
	}
	 if(showingContactBool != undefined){
		 tempName +="/Contact Us";
		  tempEvent +=",event11";
		 //tempHier +=",Contact Us";
	}
	tempName +="/Submit";
	tempEvent +=",event3";
	//tempHier +=",Submit";
	
	 trackPopUpFormItems(tempName,tempEvent,'',optInBool,showingContactBool);
	
}

goBackToFlash = function(){
	 if(window.flashPopUp){ 
		window.document["flashPopUp"].SetVariable("continueFlash", "true");
	 }else if(document.flashPopUp) {
		document.flashPopUp.SetVariable("continueFlash", "true");
	 }	
}


removeProfileForm = function(closedPopUpBool){
	
	 var formLabel =  ".progression"+currentForm;
	 currentForm = undefined;
	 
	 $(formLabel).css({"display":"none"});
	 $(".pop_1_form_overlay").css({"display":"none"});
	
	
	if(closedPopUpBool == "true"){
		 if(window.flashPopUp){ 
			window.document["flashPopUp"].SetVariable("stopVid", "true");
		 }else if(document.flashPopUp) {
			document.flashPopUp.SetVariable("stopVid", "true");
		 }	
		$('.sortSelect').show();
			trackPopUpFormItems('/Close','event9','');
		
	}
}

loadRelatedAssets = function(formId,optInBool,contactBool,assetID,emailAddress,firstName,lastName, loggedInBool, securedUserBool, businessSize, companyName, jobTitle, department, industry){
	
	if (formId == 7){
		scExp.setScenario({ 'scenario': formId, 'isOptIn':optInBool, 'isContact':contactBool, 'isLoggedIn':loggedInBool, 'isSecuredProfile':securedUserBool });
		scExp.userProfile = new scenarioProfile({ 'email':emailAddress, 'firstName':firstName, 'lastName':lastName, 'companySize':businessSize, 'companyName':companyName, 'jobTitle':jobTitle, 'department':department, 'industry':industry });
		scExp.relatedAssets(assetID);
		return;
	}else{	
		goBackToFlash();
	}
}

sendContact = function(){
	var subData = {};
	//profile.do

	subData.actionMethod = "saveContact";
	//subData.assetId = currentAssetID;
	subData.assetId = 120;
	
	subData.firstNameContact = $("#firstNameContact").val();
	subData.lastNameContact = $("#lastNameContact").val();
	subData.businessSizeContact = $("#businessSizeContact").val();
	//subData.industryContact = $("#industryContact").val();
	subData.companyNameContact = $("#companyNameContact").val();
	subData.emailAddressContact = $("#emailAddressContact").val();
	subData.phoneContact = $("#phoneContact").val();
	subData.postCodeContact = $("#postCodeContact").val();
	subData.wireLessNumchkContact = String($("#wireLessNumchkContact").attr("checked"));
	subData.wireLessNumContact = $("#wireLessNumContact").val();
	subData.wireLineNumchkContact = String($("#wireLineNumchkContact").attr("checked"));
	subData.wireLineNumContact = $("#wireLineNumContact").val();
	subData.optInContact = String($("#optInContact").attr("checked"));
	subData.commentsContact = $("#commentsContact").val();
	
	//subData.contactPrefContact = $("#contactPrefContact").val();
	//subData.alternateNumContact = $("#alternateNumContact").val();	
	$('.resourcesShield').show();	
	$.ajax({
			url: "profile.do",
			type: "POST",
			data: (subData),
			dataType: "json",
			success: function (data, textStatus) {
				if(data.success == true){
					removeContactProfile(true);
					var eventParam = "event13,event3";
					if($("#optInContact").attr("checked")){
							eventParam+=",event10";
					}
					
					
					trackPopUpFormItems('/Contact Us/Submit',eventParam,'',$("#optInContact").attr("checked"),true);
					//alert('here')
					if($("#optInContact").attr("checked") &&  (trackingFeature || trackingSpotLight)){
									//alert('optin')
									var axel = Math.random() + "";
									var a = axel * 10000000000000;
									$('#spotlightTaggingProfileOptIn').html('<iframe src="https://fls.doubleclick.net/activityi;src=2278793;type=telus550;cat=conta477;ord=1;num=' + a + '?" width="1" height="1" frameborder="0"></iframe>');
								}
				}else{
					//alert(data.propertyMessages[0].messages[0]);	
					//$("#contactFormValidationErrorID").html("<p>"+data.propertyMessages[0].messages[0]+"</p>");
					
					if(data.propertyMessages != undefined){
						$("#contactFormValidationErrorID").html("<p>"+data.propertyMessages[0].messages[0]+"</p>");
					}else{
						if(data.globalMessages != undefined){
							$("#contactFormValidationErrorID").html("<p>"+data.globalMessages[0]+"</p>");
						}
						
					}
					
				}
				$('.resourcesShield').hide();	
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				//alert("error");
			}
		});
	
	
	
}

loadContact = function(lightBoxLabel){
	//currentLightBox = lightBoxLabel;
	//alert($("#lightbox5"));
	$.ajax({
			url: "profile.do",
			type: "POST",
			data: ({"actionMethod":"getContact"}),
			dataType: "json",
			success: function (data, textStatus) {
				//alert($.toJSON(data));
								
				showContactProfile(data);
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				//alert("error");
				
			}
		});
	
	//$.toJSON(data)
	/*for getContact, here are the names in the json:
  firstNameContact
lastNamContact
buisnessSizeContact
verticleContact
industryContact
companyNameContact
postCodeContact
wireLessNumchkContact
wireLessNumContact
wireLineNumchkContact
wireLineNumContact
optInContact
contactPrefContact
alternateNumContact*/
	
	
	
	//$("#lightbox5").css("z-index","222222222");
	//$("#yesno").css("visibility","hidden");
	
	//var api =  $("#lightbox5").overlay();
	//var api = $(obj).overlay();
	//api.load();		
}

showContactProfile = function(data){
	/*{"wireLessNumchkContact":"0","lastNameContact":"qweqwe","buisnessSizeContact":"small (1-9 employees)","wireLineNumchkContact":"0","firstNameContact":"qwqwe","optInContact":"1"}*/
	
	for(var a in data){
		var id = "#"+a;
		if($(id).attr("type")=="checkbox"){	
			if(data[a] == "1"){
				$(id).attr("checked",true);
				if(a=="wireLessNumchkContact"){
					showContactNumber(true,'wireLessNumContactTitle','wireLessNumContact');
				}else if(a=="wireLineNumchkContact"){
					showContactNumber(true,'wireLineNumContactTitle','wireLineNumContact');
				}
			}
		}else if($(id).attr("type")=="select-one"){	
			//alert(data[a])
			$(id).val(data[a]);
		}else{
			//will this work automatically for select
			$(id).val(data[a]);
		}
		
	}
	
	var top = $("#yesno").css("top");
	$("#lightbox5").css("display","");
	$("#lightbox5").css("top",top);
	$("#yesNoClose").css("display","none");
}

removeContactProfile = function(submitted){
	$("#lightbox5").css("display","none");
	$("#yesNoClose").css("display","");
	goBackToFlash();
	if(submitted == undefined){
		trackPopUpFormItems('/Contact Us/Close','event9','');
	}
	//$("#lightbox5").css("z-index","1");
	//var api =  $(currentLightBox).overlay();
	//var api = $(obj).overlay();
	//api.load();	
	//currentLightBox = undefined;
	
}

loadForgotPassword = function(){
	var api = $("#lightbox4").overlay();			
	api.load();		
}

function submitForgottenPassword() {
	if (validate_email($("#forgottenPassword").val())) {
		$.ajax({
			url: "userLogin.do",
			dataType: "jsonp",
			data: ({
				"actionMethod" : "forgotPassword",
				"user.emailAddress" : $("#forgottenPassword").val()
			}),
			success: function (data, textStatus) {
				if(data.success == true){
					 var api = $("#lightbox4").overlay();
					 api.close();
				}else{
					displayMessages(data, $("#forgot.password.email.not.found.message"))
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				//alert("error");
				
			}
		});
	}
}

showContactNumber = function(bool,titleID,phoneID){
	
	var titleid = "#"+titleID;
	var phoneid = "#"+phoneID;
	if(bool){
	 	var show="";	
	}else{
		 var show="none";
		 $(phoneid).val("");
	}
	//alert(contactNumId+" - "+show)
	$(phoneid).css("display",show);
	$(titleid).css("display",show);
	
}
