scenarioModel = function(options) {
	
	this.spawnOnAction = "";
	this.optInPreChecked = false;
	this.formShown = false;
	
	$.extend(this, options);	
	
	this.loadCondition = function(obj, action){
		return (action == this.spawnOnAction && !this.formShown);
	}
	this.saveForm = function() {
		// return an object the AJAX can use to save profile data
		var subData = {};
		return subData;
	}
	this.loadAsset = function(){
		goBackToFlash();
		return;
	}
	this.loadFormCommon = function(){
		$("#progression6Title").show();
		$(".progression6").show();
		$(".progression5").show();

		$("#progression6Title").prev().hide();
		$("#emailAddressForm").hide();
	
		$(".pop_1_form_overlay").show();	 		

		$("#profilingSubmit").unbind().bind('click', function(){ scExp.submitProfile(); });
		
		this.formShown = true;
		return;
	}
	this.loadForm = function() {
		return;
	}
	this.closeFormCommon = function() {
		$("#progression6Title").hide();
		$("#expDescription1a").hide();
		$("#expDescription1b2").hide();

		$("#progression6Title").prev().show();
		$("#emailAddressForm").show();
		$("#profilingSubmit").unbind().bind('click', function(){ validatForm(); });

		$(".progression6").css({"display":"none"});
		$(".progression5").css({"display":"none"});
		$(".manageProfileLogin").css({"display":"none"});
		$(".pop_1_form_overlay").css({"display":"none"});	
		
		return;
	}
	this.closeForm = function(){
		// load default behavior for profiling form
		this.closeFormCommon();

		// manipulate the layout of the profile form in scenario 2
		goBackToFlash();
		return;
	}
	this.reqFieldValidationCommon = function(){
	    var name = new RegExp("[^a-zA-Z '\-\]");
	    var retval = true;
	    var invalid = $("#expFirstName").val().length == 0 || name.test($("#expFirstName").val());
	    this.displayValidation("#expFirstName", invalid)
	    if (invalid)
			retval = false;

	    invalid = $("#expLastName").val().length == 0 || name.test($("#expLastName").val());
	    this.displayValidation("#expLastName", invalid)
	    if (invalid)
			retval = false;

	    invalid = $("#expEmailAddress").val().length == 0 || !validate_email($("#expEmailAddress").val());
	    this.displayValidation("#expEmailAddress", invalid)
	    if (invalid)
			retval = false;

	    invalid = $("#expCompanySize").attr("selectedIndex") == 0;
	    this.displayValidation("#expCompanySize", invalid)
	    if (invalid)
			retval = false;

	    return retval;
	}
	this.reqFieldValidation = function(){
		return this.reqFieldValidationCommon();
	}
	this.displayValidation = function(id, invalid){
		var visibility = invalid ? "visible" : "hidden";
		var display = invalid ? "inline" : "none";
		$(id).prev().find("span").css({'visibility':visibility, 'display':display});
	}
}

scenarioProfile = function(options) {
	target = this;
	this.email = "";
	this.firstName = "";
	this.lastName = "";
	this.companySize = "";
	this.jobTitle = "";
	this.department = "";
	this.companyName = "";
	this.industry = "";
	$.extend(this, options);
	
	this.prepopulate = function(){
		this.clearFields(); 
		
		// pre-populate the form with values if exist
		$("#expFirstName").val(this.getData(this.firstName));
		$("#expLastName").val(this.getData(this.lastName));
		$("#expEmailAddress").val(this.getData(this.email));
		if (this.getData(this.companySize).length > 0)
			$("#expCompanySize").val(this.getData(this.companySize));

		$("#expCompanyName").val(this.getData(this.companyName));
		if (this.getData(this.jobTitle).length > 0)
			$("#expJobTitle").val(this.getData(this.jobTitle));
		if (this.getData(this.department).length > 0)
			$("#expDepartment").val(this.getData(this.department));
		if (this.getData(this.industry).length > 0)
			$("#expIndustry").val(this.getData(this.industry));
	}
	this.clearFields = function(){
		$("#expFirstName").val('');
		$("#expLastName").val('');
		$("#expEmailAddress").val('');
		$("#expCompanySize option:first").attr("selected","selected");

		$("#expCompanyName").val('');
		$("#expJobTitle option:first").attr("selected","selected");
		$("#expDepartment option:first").attr("selected","selected");
		$("#expIndustry option:first").attr("selected","selected");
	}
	
	this.getData = function(val){
		// returns blank when value not set or unable to evaluate
		if (typeof(val) != 'undefined' && val != 'undefined' && val.length > 0)
			return val;
		else 
			return "";
	}
}

scenarioExp = function(options) {
	target = this;
	this.currentScenario = "0";
	this.currentScenarioObject = null;
	this.userProfile = null;
	this.isOptIn = false;
	this.isLoggedIn = false;
	this.isSecuredProfile = false;
	this.isContact = false;
	this.currentAssetID = 0;
	this.assetViewed = [];
	$.extend(this, options);

	this.addViewed = function(assetID){
		if (typeof(assetID) != "undefined" && assetID.length > 0 && $.inArray(assetID, this.assetViewed) < 0){
			this.currentAssetID = assetID;
			this.assetViewed.push(assetID);
		}
		return;
	}

	this.setScenario = function(profile) {
		// update scenario and the associate object 
		this.currentScenario = profile.scenario + '';
		
		switch (this.currentScenario) {
		case "7":
			this.currentScenarioObject = new scenarioModel({ spawnOnAction:"onClose", optInPreChecked:false });
			this.currentScenarioObject.loadForm = function() {
				// load default behavior for profiling form
				this.loadFormCommon();
				$("#expDescription1a").show();
				
				// manipulate the layout of the profile form in scenario 1a
				$("#profilingSignUp").show();
				$("#profilingSkipIt").show();

				$("#optInForm").hide();
				$("#profilingSubmit").hide();
				$(".progression6scenario2").hide();
				
				if(window.flashPopUp){ 
					window.document["flashPopUp"].SetVariable("stopVid", "true");
				}else if(document.flashPopUp) {
					document.flashPopUp.SetVariable("stopVid", "true");
				}	
												
				return false;
			}
			this.currentScenarioObject.saveForm = function() {
				// return an object the AJAX can use to save profile data
				var subData = {};
				subData.optIn = "true";
				return subData;
			}
			this.currentScenarioObject.closeForm = function() {
				// load default behavior for profiling form
				this.closeFormCommon();
				
				$("#profilingSignUp").hide();
				$("#profilingSkipIt").hide();

				$("#optInForm").show();
				$("#profilingSubmit").show();
				$(".progression6scenario2").show();

				removeProfileForm();
				var yn = $("#yesno").overlay();
				yn.close();
				
				return;
			}
			break;
		case "8":
			this.currentScenarioObject = new scenarioModel({ spawnOnAction:"onOpen", optInPreChecked:true });
			this.currentScenarioObject.loadForm = function() {
				// load default behavior for profiling form
				this.loadFormCommon();
				$("#expDescription1b2").show();
				
				// manipulate the layout of the profile form in scenario 1b
				$(".progression6scenario2").hide();
				return;
			}
			this.currentScenarioObject.saveForm = function() {
				// return an object the AJAX can use to save profile data
				var subData = {};
				subData.optIn = String($("#optIn").attr("checked"));
				return subData;
			}
			break;
		case "9":
			this.currentScenarioObject = new scenarioModel({ spawnOnAction:"onOpen", optInPreChecked:true });
			this.currentScenarioObject.loadForm = function() {
				// load default behavior for profiling form
				this.loadFormCommon();
				$("#expDescription1b2").show();
								
				// manipulate the layout of the profile form in scenario 2
				return;
			}
			this.currentScenarioObject.saveForm = function() {
				// return an object the AJAX can use to save profile data
				var subData = {};
				subData.jobTitle = $("#expJobTitle").val();
				subData.role = $("#expDepartment").val();
				subData.companyName = $("#expCompanyName").val();
				subData.industry = $("#expIndustry").val();
				subData.optIn = String($("#optIn").attr("checked"));
				return subData;
			}
			this.currentScenarioObject.reqFieldValidation = function(){
				var retval = this.reqFieldValidationCommon();
				
			    var invalid = $("#expCompanyName").val().length == 0;
			    this.displayValidation("#expCompanyName", invalid)
			    if (invalid)
					retval = false;

			    invalid = $("#expJobTitle").attr("selectedIndex") == 0;
			    this.displayValidation("#expJobTitle", invalid)
			    if (invalid)
					retval = false;

			    invalid = $("#expDepartment").attr("selectedIndex") == 0;
			    this.displayValidation("#expDepartment", invalid)
			    if (invalid)
					retval = false;

			    invalid = $("#expIndustry").attr("selectedIndex") == 0;
			    this.displayValidation("#expIndustry", invalid)
			    if (invalid)
					retval = false;

			    return retval;
			}
			break;
		}
		
		// update other attributes
		this.isOptIn = profile.isOptIn == "true";
		this.isContact = profile.isContact == "true";
		this.isLoggedIn = profile.isLoggedIn == "true";
		this.isSecuredProfile = profile.isSecuredProfile == "true";
	}

	this.openAsset = function(assetID) {
		// capture the assetid 
		this.addViewed(assetID);

		// check against the scenario object for handling
		if (this.currentScenarioObject.loadCondition(this, "onOpen"))
			this.spawnProfile();
		else
			this.currentScenarioObject.loadAsset();
	}

	this.closeAsset = function() {
		// check against the scenario object for handling
		if (this.currentScenarioObject.loadCondition(this, "onClose"))
			this.spawnProfile();
		else
			this.currentScenarioObject.closeForm();
	}

	this.relatedAssets = function(assetID) {
		// capture the assetid 
		this.addViewed(assetID);

		// check against the scenario object for handling
		if (this.currentScenarioObject.loadCondition(this, "onClose"))
			this.spawnProfile();
		else
			this.currentScenarioObject.loadAsset();
	}

	this.spawnProfile = function() {
		if (this.isOptIn)
			return;

		// use scenario object to display form depends on the assigned scenario
		$(".formValidation").hide();
		this.currentScenarioObject.loadForm();
		
		// preselect the optin depends on the assigned scenario settings
		$("#optIn").attr("checked", this.currentScenarioObject.optInPreChecked);

/*
		if (!this.isLoggedIn && this.isSecuredProfile)
			$(".manageProfileLogin").show();
		else
			$(".manageProfileLogin").hide();
*/
		
		// pre-populated the form only when unsecured profile or logged in secured profiles
		if (!this.isSecuredProfile || this.isLoggedIn) {
			this.userProfile.prepopulate();
		}
		else{
			this.userProfile.clearFields();
		}
	}
	
	this.skipProfile = function(){
		// hide the profile and continue
		this.hideProfile();
		return;
	}
	
	this.hideProfile = function(){
		this.currentScenarioObject.closeForm();
		return;
	}
	
	this.logUserIn = function() {
		$("#expLoginMessageText").html('').hide();
		
		// check for currentScenarioObject. in baseline case, currentScenarioObject is null and req field check already taken care of
		if (this.currentScenarioObject != null && !this.currentScenarioObject.reqFieldValidation())
			return;
		
		// display loading shield
		$('.resourcesShield').show();	
			
		// log the user into the system
		$.ajax( {
			url : ssl_host_url + "/userLogin.do",
			dataType : "jsonp",
			data : ( {
				"actionMethod" : "login",
				"user.isKeepLoggedIn" : $("#expLoginKeepLoggedIn").attr('checked'),
				"user.emailAddress" : $("#expLoginEmailAddress").val(),
				"user.password" : $("#expLoginPassword").val()
			}),
			success : function(data, textStatus) {
				if (data.success == true) {
					
					// submit the profile
					scExp.submitProfile();
					
					// Omniture tracking
					var trackingObj = {};
					trackingObj.pageName = currentPage + '/Log In';
					trackingObj.events = 'event18';
					trackItem(trackingObj);

					// on successful login, update the vars and objs on page
					$("#login").hide();
					$("#loginLink").hide();
					$("#welcomeName").text(data.fullName);
					$("#logout").show();
					$("#BRC_UID").val(data.userName);
					$("#BRC_EML").val(data.emailAddress);
					$("#BRC_UFN").val(data.firstName);
					$("#BRC_ULN").val(data.lastName);
					$("#BRC_ULO").val("false");

					// hide login and prepop form
					$(".manageProfileLogin").hide();					
				} 
				else {
					// *** error message handling when ajax fails goes here ***
					$("#expLoginMessageText").html(getMessageText(data)).show();

					// remove loading shield
					$('.resourcesShield').hide();					
				}
				
			},
			error : function(XMLHttpRequest, textStatus, errorThrown) {
				// *** error message handling when ajax fails goes here ***
				$("#expLoginMessageText").html(getMessageText(data)).show();
				
				// remove loading shield
				$('.resourcesShield').hide();	
			}
		});
	}

	this.submitProfile = function(){
		
		// validate fields
		if (this.currentScenarioObject != null && !this.currentScenarioObject.reqFieldValidation())
			return;
		
		// capture profile form values
		var subData = {};
		
		if (this.currentScenarioObject != null){
			subData = this.currentScenarioObject.saveForm();
			subData.firstName = $("#expFirstName").val();
			subData.lastName = $("#expLastName").val();
			subData.emailAddress = $("#expEmailAddress").val();
			subData.businessSize = $("#expCompanySize").val();
			subData.assetId = this.currentAssetID;
		}		
		else{
			subData.firstName = $("#firstName").val();
			subData.lastName = $("#lastName").val();
			subData.emailAddress = $("#emailAddress").val();
			subData.businessSize = $("#businessSize").val();
			subData.optIn = String($("#optIn").attr("checked"));
			subData.assetId = currentAssetID;
		}
		subData.contact = String($("#contactChk").attr("checked"));
		subData.actionMethod = "submitProgressiveProfileForm";
		
		// display loading shield
		$('.resourcesShield').show();	
			
		$.ajax({
			url: "profile.do",
			type: "POST",
			data: (subData),
			dataType: "json",
			success: function (data, textStatus) {
			
				if(data.success == true){
					// hide the profile and continue
					if (scExp.currentScenarioObject == null){
						scExp.currentScenarioObject = new scenarioModel({ spawnOnAction:"onOpen", optInPreChecked:false });
					}

					scExp.hideProfile();
				}
				else{
					var errorMessage = getMessageText(data);
					var pleaseLoginMessage = "please login";
					if (errorMessage.toLowerCase().substr(0, pleaseLoginMessage.length) == pleaseLoginMessage)
						$(".manageProfileLogin").show();
				}
				
				// remove loading shield
				$('.resourcesShield').hide();	
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				// *** error message handling when ajax fails goes here ***
				
				// remove loading shield
				$('.resourcesShield').hide();	
			}
		});
		
	}
}

var scExp = new scenarioExp(null);

$(document).ready(function() {
	
});
