var siteCredits_ToDisappear;
var siteCredits_ToAppear;
var toolTipContainer_toolTip_displayPreferences;
var isReloading = false;
var EmailAFriendBody;

$(document).ready(function()
{
	//initHMRFaces();
	initMiscPages();
	showSomeShareLinks();	
	initNumericStepper();
	initGlobalButtons();
	
	$('[toolTipPrompt]').click(showThisToolTip);
	
	$('#pageVeil').height($(document).height());
	/*$("#ProcessingMessage").css(
	{
		left: $(document).width() / 2 - (400 * 0.75)
	});*/
	
	$("input[GetLocationOnZipcode='true']").keyup(getLocationOnZipcode_KeyUp);
	$("input[GetLocationOnZipcode='true']").change(getLocationOnZipcode_KeyUp);
	$("input[CheckUserExistance='true']").blur(checkUserExistance_Blur);
	$("input[CheckUserExistance='true']").keyup(checkUserExistance_Blur);
	//$("input[checkFieldValueMatched='true']").blur(checkFieldValueMatched_KeyUp);
	//$("input[checkMatchingFields='true']").blur(checkMatchingFields_Blur);
	//$("input[matchMinMaxLength='true']").blur(checkMatchMinMaxLength_KeyUp);
	
	
	// take care of login-required links in content
	$("a[href='/Enjoy/Recipe_Submit']:not([LoginRequired='true'])").attr("LoginRequired", true);
	$("a[href='/Inspire/Out_And_About/Submit_Out_and_About']:not([LoginRequired='true'])").attr("LoginRequired", true);
	$("a[href='/Inspire/HMR_Success_Stories/Submit_Your_Story']:not([LoginRequired='true'])").attr("LoginRequired", true);
	$("a[href='/My_Profile']:not([LoginRequired='true'])").attr("LoginRequired", true);
	
	// handle LoginRequired links set natively and by the above querying
	$("a[LoginRequired='true']").click(LoginRequired_Click);
	$("*[initSiteCredits='true']").click(initSiteCredits);
	siteCredits_ToDisappear = $('#siteCredits_ToDisappear');
	siteCredits_ToAppear = $('#siteCredits_ToAppear');
	
	// SoMe links hook for stat reporting
	$("a.SoMeLink[Source]").click(someLink_Click);
	
	// specific external links for stat reporting
	$("a[ExternalLinkType]").click(externalLink_Click);
	
	// detect account in session and add hash
	initGlobalAssignAffiliateAccountHash();
	toolTipContainer_toolTip_displayPreferences = $('#toolTipContainer_toolTip_displayPreferences');
	if(Browser.isIE && Browser.Version == 7)
	{
	  toolTipContainer_toolTip_displayPreferences.css("top", "480px");
	}
	
	EmailAFriendBody = $('#EmailAFriend_PersonalMessage').html();
	
});


function createLinkInText(text) {
	var urlRegex = /(https?:\/\/[^\s]+)/g;
	return text.replace(urlRegex, function(url) {
		return '<a href="' + url + '" target="_blank">' + url + '</a>';
	})
}


function showThisToolTip(e){
	xOffset = 22;
	yOffset = 960;
	
	var thisObj = $(this);
	var thisObj_ToolTip = $('#' + thisObj.attr("toolTipPrompt"));
	var tipBoxObj = $('#' + thisObj.attr("toolTipPrompt") + ' .tipBox');
	checkS(e);
	
	var leftPos = posx - ((document.body.offsetWidth / 2) - xOffset);
	thisObj_ToolTip.fadeIn(400, function(){
		$(document).one("click", function(){thisObj_ToolTip.fadeOut(400);})
	});
}

function initSiteCredits(){
	siteCredits_ToDisappear.fadeOut(200).delay(6000).fadeIn(200);
	siteCredits_ToAppear.animate({right: '53'}, 600).delay(5000).animate({right: '-380'}, 600);
}

function openInNewWindow(newURL, type, width, height, status, modal, resizable){
	window.open(newURL, type, 'width=600, height=340, status=no, modal=yes, resizable=yes, scrollbars=yes');
}

function initGlobalAssignAffiliateAccountHash()
{
	var hash = location.hash.replace(/#/g, "");
	var hashKey;
	var urlInfo = Url.parse();
	//dumpObject(urlInfo.hashGroups)
	// check for URL variable ACCOUNT in case of re-write and server-side code can't read it
	if( urlInfo.queryVariables.hasOwnProperty("account") )
	{
		var newUrl = urlInfo.url.replace("account=" + urlInfo.queryVariables.account, "");
		newUrl = newUrl.replace("?&", "?");
		if( newUrl[newUrl.length-1] == "?" )
		{
			newUrl = newUrl.replace("?", "");
		}
		
		if (!urlInfo.isHomepage) 
		{
			location.href = newUrl + "#Acct(" + urlInfo.queryVariables.account + ")";
			return;
		}
	}
	
	// if ALERT key found, fire custom alert and remove value
	if( Url.HasHashGroup("Alert") )
	{
		var alertId = urlInfo.hashGroups.Alert;
		Url.RemoveHashGroup( "Alert" );
		callCustomAlert(alertId, {
			hideCloseButton: true
		});
	}

	if( Url.HasHashGroup("Acct") && !urlInfo.queryVariables.hasOwnProperty("n") )
	{
		//hashKey = hash.maskOut("Acct(*)");
		hashKey = urlInfo.hashGroups.Acct;

		var service = new ApiServiceProxy();
		var getLocalAccount_Result = function(result)
		{
			var hasUserAccount = objectHasKey(result, "User");
			var hasLocalAccount = objectHasKey(result, "Local");
			if (!hasUserAccount && !hasLocalAccount) 
			{
				// No accounts found. Attempt to create a local account for HASHKEY
				//var service = new ApiServiceProxy();
				var CreateAccount_Result = function(result)
				{
					if (result) 
					{
						location.reload();
					}
					else
					{
						location.hash = "";
					}
				}
				service.setCallbackHandler(CreateAccount_Result);
				service.CreateLocalAffiliateAccount(hashKey);
			}
			else if (hasLocalAccount && result.LOCAL != hashKey)
			{
				// if a local account is found but the HASHKEY is different: replace hash
				var acctStr = "Acct(" + result.LOCAL + ")";
				if (!hash.listFindNoCase(acctStr)) 
				{
					//hash = hash.maskIn("Acct(*)", result.LOCAL);
					if (result.LOCAL.toLowerCase() != "www") 
					{
						//location.hash = hash;
						Url.SetHashGroup( "Acct", result.LOCAL );
					}
					else
					{
						location.hash = "";
					}
				}
			}
		}
		service.setCallbackHandler(getLocalAccount_Result);
		service.GetAffiliateAccounts();
		
		if(hashKey.toLowerCase() == "www")
		{
			location.hash = "";
		}
	}
	else
	{
		// HASHKEY not found
		// if there is a local account, add HASHKEY
		var localAccount = $("#AffiliateAccount");
		var localAccountKey = localAccount.val();
		if(localAccountKey != null && localAccountKey != "" && localAccountKey != "www")
		{
			var acctStr = "Acct(" + localAccountKey + ")";
			if (!hash.listFindNoCase(acctStr) && acctStr.toLowerCase() != "www") 
			{
				//hash = hash.maskIn("Acct(*)", localAccountKey);
				location.hash = acctStr + ";" + location.hash.replace(/#/ig, "");
			}
		}
		
		hashKey = localAccountKey;
	}
	
	if( hashKey == null || hashKey == undefined)
	{
		if( urlInfo.queryVariables.hasOwnProperty("account") )
		{
			hashKey = urlInfo.queryVariables.account;
		}
	}
	
	// ensure share links have account branding
	if (hashKey != null && hashKey != undefined && hashKey.toLowerCase() != "www") 
	{
		$("a.shareStoryWithFriendBtn[url]").each(function()
		{
			var currentUrl = $(this).attr("url");
			$(this).attr("url", currentUrl + "#Acct(" + hashKey + ");");
		});
	}
	
	// strip extra hashes from title
	var title = document.title;
	if (title.contains("#")) 
	{
		document.title = title.substring(0, title.findNoCase("#"));
	}
}


function initGlobalButtons(){
	$('#globalSignIn').live('click', globalSignIn_Click)
	$('#globalSignOut').live('click', function(){logMeOut();})
}

function globalSignIn_Click()
{
	var login_Result = function()
	{
		
	};
	executeRestrictedAction({afterSuccess: login_Result});
}


// Check that the confirm password field matches the first
function checkMatchingFields(form,field,value){
	var thisObj = $(this);
	var matchFieldObj = $('#' + thisObj.attr("matchedInput"));
	var alertText = "";
	
	if(thisObj.val() != matchFieldObj.val()){
		alertText += "The values for Password and Confirm Password must match.\r\n";
	}
	if(thisObj.val().length < 6 || matchFieldObj.val().length < 6){
		alertText += "Your password must be at least 6 characters and have at least 1 number and 1 letter.\r\n";
	}
	
	if(alertText.length > 0){
		alert(alertText);
		return false;
	}
	
}



		
function getCaptchaKey()
{
	return new Date().getTime() + location.hostname + ".jpgx";
}

/*
 * onComplete
 * 	onCompleteBeforeProcess
 * 	onTrue
 * 	onFalseBeforeChange
 * 	onFalse
 * onError
 * 
 * preventChange : boolean
 * 
 */
function testCaptcha(key, value, options)
{
	var asp = new ApiServiceProxy();
	var captchaTest_Result = function(result)
	{
		// pre complete-processing
		if (options.hasOwnProperty("onCompleteBeforeProcess")) 
		{
			options.onCompleteBeforeProcess.call(this, [result]);
		}
		// complete processing
		if (result) 
		{
			if(options.hasOwnProperty("onTrue"))
			{
				options.onTrue.call();
			}
		}
		else
		{
			// exec. pre funcion
			if(options.hasOwnProperty("onFalseBeforeChange"))
			{
				options.onFalseBeforeChange.call();
			}
			// change CAPTCHA image
			if (!options.hasOwnProperty("preventChange") || options.preventChange) 
			{
				var newKey = getCaptchaKey();
				$("img[IsCaptchaImage='true'][Key='"+ key +"']").attr({
					src: "http://www.opencaptcha.com/img/" + newKey,
					Key: newKey
				});
			}
			// exec. post function
			if(options.hasOwnProperty("onFalse"))
			{
				options.onFalse.call();
			}
		}
		// post complete-processing
		if (options.hasOwnProperty("onComplete")) 
		{
			options.onComplete.call(this, [result]);
		}
	}
	var captchaTest_Error = function()
	{
		if(options.hasOwnProperty("onError"))
		{
			options.onError.call();
		}
	}
	asp.setErrorHandler(captchaTest_Error);
	asp.setCallbackHandler(captchaTest_Result);
	
	asp.TestCaptcha(key, value);
}


/*
 * THIS function messes with the "processing..." message, use showVeil() and hideVeil() where appropirate

function toggleVeil(){
	
	if($('#pageVeil').hasClass('hidden')){
		showVeil();
	}
	else{
		hideVeil();
	}
}
*/

function showVeil()
{
	/*
	$('#pageVeil').show();
	$('#pageVeil').fadeTo(500, .5);
	$('#pageVeil').removeClass('hidden');
	$('#pageVeil').addClass('visible');
	*/
	showOverlay();
}

function hideVeil()
{
	/*
	$('#pageVeil').fadeOut('fast', function(){
		$('#pageVeil').removeClass('visible');
		$('#pageVeil').addClass('hidden');
	});	
	*/
	hideOverlay();
}


function quickHideVeil()
{
	
	$('#pageVeil').css(
		{
			opacity: 0,
			zIndex: 1001
		}
	);
	$('#pageVeil').hide()
	$('#pageVeil').removeClass('visible');
	$('#pageVeil').addClass('hidden');
}

function quickShowVeil()
{
	$('#pageVeil').css('height', $(document).height());
	$('#pageVeil').show();
	$('#pageVeil').css(
		{
			opacity: 0.5,
			zIndex: 1009
		}
	);
	$('#pageVeil').removeClass('hidden');
	$('#pageVeil').addClass('visible');
}


function showProcessing()
{
	quickShowVeil();
	$("#ProcessingMessage").show();
}

function hideProcessing()
{
	quickHideVeil();
	$("#ProcessingMessage").hide();
	
}

var result;
this.showSomeShareLinks = function(){	
	/* CONFIG */		
		xOffset = 0;
		yOffset = 10;
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result		
	/* END CONFIG */
	
	$(".shareStoryWithFriendBtn").click(function(e){
		var thisObj = $(this);
		thisObj.attr('opened', 'true');
		var stats = new StatisticsServiceProxy();
		
		e.preventDefault();
		checkS(e);
		var p = $(e.currentTarget);
		
		var linksContainer = $("#soMeLinksContainer");
		var linkTitle = p.attr('pageTitle');
		var url = p.attr('url');
		
		
		//replaces the starting url's ?key=val with &key=val, for appending
		var currentUrlVars = url.match(/\?.[^#Acct(.*)]+/);
		var urlVarsForAppend = '';
		if (currentUrlVars && currentUrlVars.length > 0) {
			urlVarsForAppend = currentUrlVars[0].replace(/\?/, '&');
			url = url.replace(/\?.[^#Acct(.*)]+/, "");
		}
		
		//replace account branding key with share friendly version:
		var account = url.match(/#Acct\(.*\);/);
		if (account && account.length > 0) {
			account[0] = account[0].replace(/#Acct\(/, "");
			account[0] = account[0].replace(/\);/, "");
			url = url.replace(/#Acct\(.*\);/,"?account="+account[0]);
			url = url + urlVarsForAppend;
			thisObj.attr('url', url);
			
		}
		
		
		
		
		//SET SOMELINKS
		// sets attr "url" to all SoMe links, this is used later for stat logging
		linksContainer.find("a.SoMeLink").attr("url", url);
		
		//set twitter
		$('#soMeMiddle .twitter').one('click', function()
		{
			postToTwitter(url, linkTitle);
		});
		
		//set facebook
		var facebookURL = 'http://www.facebook.com/sharer.php?u='+url+'&t='+linkTitle+'';
		linksContainer.find('.facebook').attr('href', facebookURL);
		
		//set delicious
		var deliciousURL = 'http://delicious.com/save?url='+url+'&title='+linkTitle+'';
		linksContainer.find('.delicious').attr('href', deliciousURL);
		
		//set digg
		var diggURL = 'http://digg.com/submit?url='+url+'&title='+linkTitle.replace(/ /g, '+')+'';
		linksContainer.find('.digg').attr('href', diggURL);
		
		//set email
		var emailBodyObj = $('#EmailAFriend_PersonalMessage');
		//////linksContainer.find('.email').attr('href', mailURL);
		$('#EmailAFriend_SendToEmail').val('');
		if($('#EmailAFriend').find('.isLoggedInDisplay').is(':visible')){
			$('EmailAFriend_FromEmail').val('');	
		}
		/*$('#EmailAFriend_PersonalMessage').val($('#EmailAFriend_PersonalMessage').html() + ': ' + linkTitle + ' ' + url);*/
		/*$('#EmailAFriend_PersonalMessage').val(EmailAFriendBody + ': ' + linkTitle + ' ' + url);*/
		$('#EmailAFriend_PersonalMessage').val(EmailAFriendBody + ': ' + linkTitle);
		var createHTMLLinkFromText = createLinkInText(url);
		//alert(createHTMLLinkFromText);
		$('#EmailAFriend_Link').val(createHTMLLinkFromText);
		$('#emailLinkLabel #linkText').html(url);
		
		var mailURL = 'mailto:?subject=Check this out on HMRdiet!&body=' + emailBodyObj.html() + linkTitle + ' ' + url;
		$('#EmailOptionsBox a').attr('href', mailURL);
		linksContainer.find('.email').attr('href', 'javascript:popUpAction("EmailAFriend");');
		
		
		var topPos =  posy - linksContainer.height() -yOffset;
		var leftPos = posx - (linksContainer.width() / 2) + xOffset;
		
		/*alert(thisObj.position().left);
		var topPos =  posy - thisObj.position().left;
		var leftPos = posx - thisObj.position().top;*/
		
		linksContainer.css("top", (topPos)+"px").css("left", leftPos+"px").fadeIn("fast", function(){
			$(document).one('click', function(e){
				$("#soMeLinksContainer").fadeOut("fast");
				thisObj.attr('opened', 'false');
			});
		});
	});
};


function externalLink_Click()
{
	var stat = new StatisticsServiceProxy();
	var sender = $(this);
	var dest = sender.attr("href");
	if(sender.attr("Destination") != null)
	{
		dest = sender.attr("Destination");
	}
	stat.LogExternalLinkClick(sender.attr("ExternalLinkType"), dest, location.href);
}


function someLink_Click()
{
	var stat = new StatisticsServiceProxy();
	var shareBtn = $("a.shareStoryWithFriendBtn[url='"+ $(this).attr("url") +"']");
	stat.LogShareClick($(this).attr("Source"), $(this).attr("url"), location.href, shareBtn.attr("PageTitle"));
}


function postToTwitter(url, linkTitle){
	url = encodeURIComponent(url);
	$.ajax({
		type: "GET",
		url: "http://api.bit.ly/v3/shorten?login=silverscape&apiKey=R_1acef17a361a1c29d3e397a438740991&format=json&longUrl="+url+"&callback=?",
		dataType: "json",
		success: function(result){
			var w = window.open();
		    w.document.location = 'http://twitter.com/home?status=Check this out on HMRdiet! '+ result.data.url;
			//window.open('http://twitter.com/home?status=Check this out on HMRdiet! '+ result.data.url);
			//window.location.href = 'http://twitter.com/home?status=Check this out on HMRdiet! '+ result.data.url;
		}
	});	
}

var posx = 0;
var posy = 0;
function checkS(e){
// capture the mouse position
	
	if (!e) var e = window.event;
		if (e.pageX || e.pageY){
			posx = e.pageX;
			posy = e.pageY;
		}
		else if (e.clientX || e.clientY){
			posx = e.clientX;
			posy = e.clientY;
		}
}





function initHMRFaces(){
	bindMiniProfile_ONLeftCol();
	$('#miniProfile_LeftCol_CloseBtn').bind('click', closeMiniProfile_LeftCol);
}

this.bindMiniProfile_ONLeftCol = function(){
	/*alert("Test");*/
	/* CONFIG */		
		xOffset2 = 303;
		yOffset2 = -135;
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result		
	/* END CONFIG */
	$('#HMRFaces_PhotoGalleryContainer .portrait').bind('click', function(e){
		e.preventDefault();
		//checkS(e);
		
		var HMRFaces_PhotoGallery = $("#HMRFaces_PhotoGalleryContainer");
		var PhotoGallery_Position = HMRFaces_PhotoGallery.position();
		var PhotoGallery_Yposition = PhotoGallery_Position.top;
		
		var p = $(e.currentTarget);
		var position = p.position();
		var topPos =  position.top + yOffset2 + PhotoGallery_Yposition;
		var leftPos = position.left + xOffset2;
		
		//alert(position.top + " | " + $("#miniProfileContainer_LeftCol").height() + " | " + yOffset2 + " | " + topPos + " | PhotoGallery_Yposition: " + PhotoGallery_Yposition);
		
		
		$("#miniProfileContainer_LeftCol").css("top", (topPos)+"px").css("left", leftPos+"px").fadeIn("fast");
	});
};
function closeMiniProfile_LeftCol(){	
	$('#miniProfileContainer_LeftCol').fadeOut('normal');
}

/*
function checkFieldValueMatched_KeyUp()
{
	var thisObj = $(this);
	var fieldToCheck = $(thisObj.attr("fieldToMatch"));
	if(thisObj.val() != fieldToCheck.val() || fieldToCheck.val() == "")
	{
		alert("The values for Email and Verify Email must match.");
		return false;
	}
}
*/

function checkMatchMinMaxLength_KeyUp()
{
	/*var thisObj = $(this);
	var minlength = $(thisObj.attr("minlength"));
	var maxlength = $(thisObj.attr("maxlength"));
	
	if(thisObj.val().length < 6 || thisObj.val().length > 20)
	{
		alert("Usernames must be between 6-20 characters in length.");
	}*/
}


function checkUserExistance_Blur(thisID, doNotDisplayAlert){
	if (thisID.length > 0) {
		var sender = $('#' + thisID);
	}
	else {
		var sender = $(this);
	}
	
	if (!doNotDisplayAlert) {
		var new_doNotDisplayAlert = sender.attr('doNotDisplayAlert');
	}
	else {
		doNotDisplayAlert = new_doNotDisplayAlert;
	}
	
	if (sender && sender.val()){
	
		if (sender.val().replace(/ /ig, "").length == 0) {
			return;
		}
	
	
		var type = sender.attr("existanceCheckType");
		var updateFieldName = sender.attr("existanceResultDiv");
		var updateFieldObj = $(updateFieldName);
		
		if (sender.attr("minlength") != null && sender.attr("maxlength") != null) {
			var minlength = parseInt(sender.attr("minlength"));
			var maxlength = parseInt(sender.attr("maxlength"));
			
			if (sender.val().length < minlength || sender.val().length > maxlength) {
				updateFieldObj.fadeIn(300);
				updateFieldObj.children(".userCheckText").html('<span style="color:#FF0000;">Sorry, this name is invalid!</span>');
				if (new_doNotDisplayAlert != true && new_doNotDisplayAlert != "true") {
					alert("Display Name must be between " + minlength + "-" + maxlength + " characters in length.");
				}
			}
			else {
				checkUserExistance(sender, type);
			}
		}
		else {
			checkUserExistance(sender, type);
		}
	}
}


function checkUserExistance(sender, type, callback, notAsync){
	var preData = {method: 'checkUserExistance', DisplayName: sender.val()};
	if(type.toLowerCase() == "email"){preData = {method: 'checkUserExistance', Email: sender.val()}}
	if(!notAsync || notAsync == false){
		$.ajax({
			type: "POST",
			url: "/_commongoal/API/QuickRegister/QuickRegister_Ajax.cfc",
			dataType: "json",
			data: preData,
		success: function(results){
				nonexistanceSuccess(results, sender, type); 
				if(callback != null)
					callback.call();
			}
		})
	}else if(notAsync){
		$.ajax({
			type: "POST",
			url: "/_commongoal/API/QuickRegister/QuickRegister_Ajax.cfc",
			dataType: "json",
			async: false,
			data: preData,
		success: function(results){nonexistanceSuccess(results, sender, type); callback.call()}
		})
	}
}


var global_errorText = "";

function nonexistanceSuccess(result, sender, type, inputToUpdate){
	var updateFieldName = sender.attr("existanceResultDiv");
	var updateFieldObj = $(updateFieldName);
	
	//alert("Add Attibute");
	//return false;
	if(result == true){
		if(type.toLowerCase() == "email"){
			//alert("The email address you entered is already in use, please provide another email address.");
			sender.attr('passedvalidation', 'false');
			//sender.val("");
			//sender.focus();
			//updateFieldObj.fadeIn();
			//callCustomAlert(13, {redirect:""});
		}
		else{
			updateFieldObj.children('.imgCheck').fadeOut();
			updateFieldObj.children('.userCheckText').html('<span style="color:#ff0000;">Sorry, this name is not available!</span>');
			sender.attr('passedValidation', 'false');
			updateFieldObj.fadeIn();
		}
	}
	else{
		if(type.toLowerCase() == "email"){
			updateFieldObj.fadeOut();
			sender.attr('passedvalidation', 'true');
		}
		else if($.trim(sender.val()) != "" && sender.val().length > 5)
		{
			//alert(type+':'+result);
			updateFieldObj.children('.imgCheck').fadeIn();
			updateFieldObj.children('.userCheckText').html("Congratulations, This Name is Available!");
			sender.attr('passedValidation', 'true');
			updateFieldObj.fadeIn();
		}
	}
}

function getLocationOnZipcode_KeyUp(){
	var sender = $(this);
	getLocationOnZipcode(sender);
}


function getLocationOnZipcode(target){
	var sender = target;
	if (sender) {
		var textToUpdateObj = sender.attr('texttoupdate');
		
		if (sender.val()) {
			var value = sender.val();
			if (value.length < 5) {
				$(textToUpdateObj).text("City, State");
				return;
			}
			
			$(textToUpdateObj).text("Fetching...");
			
			$.ajax({
				type: "POST",
				url: "/_commongoal/API/QuickRegister/QuickRegister_Ajax.cfc",
				dataType: "json",
				data: {
					method: 'getLocationInfo',
					ZipCode: value
				},
				error: function(){
					$(textToUpdateObj).text("City, State");
				//alert("Please provide a valid Zip Code.");
				},
				success: function(results){
					zipSuccess(results, sender)
				}
			});
		}
	}
}

function zipSuccess(results, sender){
	
	var zipcodeResult =  $(sender.attr('textToUpdate'));
	var cityFieldObj = $(sender.attr('cityField'));
	var stateFieldObj = $(sender.attr('stateField'));
	
	if(results.length > 0){
		var result = results[0];
		cityFieldObj.val(result.CITYNAME);
		stateFieldObj.val(result.STATEID);
		zipcodeResult.html(result.CITYNAME + ', ' + result.STATEABBREV);
	}
	else{
		cityFieldObj.val("");
		stateFieldObj.val(0);
		zipcodeResult.html('City, State');
	}
}



function initMiscPages(e){
	$('.expandMoreInfo').toggle(function(){
			$(this).parent().addClass('open');
			$(this).next('div').slideDown('fast');
			$(this).children('.cityState').hide();
		}, function () {
			$(this).parent().removeClass('open');
			$(this).next('div').slideUp('fast');
			$(this).children('.cityState').show();
	});
}

function showOrderPrograms(e){
	$('#moreProgramsInitP').hide();	
	$('#moreProgramsContainer').show();	
	$('#orderMoreProgramsGoBtn').hide();
}


function initNumericStepper(){
	$('.numericStepper .upArrow').bind('click', incrementStepper);	
	$('.numericStepper .downArrow').bind('click', decrementStepper);
	if($('.stepperValue').length >= 1){
		var stepperValue = $('.stepperValue').val();
		if(stepperValue.length >= 1 && stepperValue !== 0)
			presetStepperValue(stepperValue);
	}
}
var incrementStepper = function(e){
	var digitContainer = $(e.currentTarget).parent();
	var number = $(digitContainer).children('.numberWindow').children('.number');
	
	$('.numericStepper .upArrow').unbind('click');
	var currentPos = $(number).position();
	if(parseInt(currentPos.top) == -287)
		$(number).css('top', '-27px');
	
	$(number).animate(
		{top: '-=26px'}, 
		300, function(){
				$('.numericStepper .upArrow').bind('click', incrementStepper);	
				updateStepperNumber($(number));
				setStepperValue();
			}
	);
}
var decrementStepper = function(e){
	var digitContainer = $(e.currentTarget).parent();
	var number = $(digitContainer).children('.numberWindow').children('.number');
	var currentPos = $(number).attr('top');
	$('.numericStepper .downArrow').unbind('click');
	var currentPos = $(number).position();
	if(parseInt(currentPos.top) == -1)
		$(number).css('top', '-261px');
	
	$(number).animate(
		{top: '+=26px'}, 
		300, function(){
				$('.numericStepper .downArrow').bind('click', decrementStepper);
				updateStepperNumber($(number));
				setStepperValue();
			}
	);
}

function setStepperValue(){
	var stepper = $('.numericStepper');
	var val = parseInt(stepper.find('.firstDigit').children('.numberWindow').children('.number').html() + stepper.find('.secondDigit').children('.numberWindow').children('.number').html() + stepper.find('.thirdDigit').children('.numberWindow').children('.number').html(), 10);
	stepper.find('.stepperValue').val(val);
}

function presetStepperValue(num){
	var stepper = $('.numericStepper');
	num = num.toString();
	if(num.length == 0)
		num = '000';
	else if(num.length == 1)
		num = '00'+num;
	else if(num.length == 2)
		num = '0'+num;
	
	var firstDigit = num.charAt(0);
	var secondDigit = num.charAt(1);
	var thirdDigit = num.charAt(2);
	
	var firstDigObj = stepper.find('.firstDigit').children('.numberWindow').children('.number');
	firstDigObj.css('top', getStepperPosByNum(firstDigit)+'px');
	firstDigObj.html(firstDigit);
	
	var secondDigObj = stepper.find('.secondDigit').children('.numberWindow').children('.number');
	secondDigObj.css('top', getStepperPosByNum(secondDigit)+'px');
	secondDigObj.html(secondDigit);
	
	var thirdDigObj = stepper.find('.thirdDigit').children('.numberWindow').children('.number');
	thirdDigObj.css('top', getStepperPosByNum(thirdDigit)+'px');
	thirdDigObj.html(thirdDigit);
}

function getStepperPosByNum(num){
	var pos = '';
	switch(num){
		case '0':
			pos = '-27';
		break;
		case '1':
			pos = '-53';
		break;
		case '2':
			pos = '-79';
		break;
		case '3':
			pos = '-105';
		break;
		case '4':
			pos = '-131';
		break;
		case '5':
			pos = '-157';
		break;
		case '6':
			pos = '-183';
		break;
		case '7':
			pos = '-209';
		break;
		case '8':
			pos = '-235';
		break;
		case '9':
			pos = '-1';
		break;
	}
	return(pos);
}

function updateStepperNumber(number){
	pos = parseInt(number.css('top'));
	var num = '';
	switch(pos){
		case -27:
			num = '0';
		break;
		case -53:
			num = '1';
		break;
		case -79:
			num = '2';
		break;
		case -105:
			num = '3';
		break;
		case -131:
			num = '4';
		break;
		case -157:
			num = '5';
		break;
		case -183:
			num = '6';
		break;
		case -209:
			num = '7';
		break;
		case -235:
			num = '8';
		break;
		case -261:
			num = '9';
		break;
		case -1:
			num = '9';
		break;
		case -287:
			num = '0';
		break;
	}
	number.html(num);
}


var loginCheckPromptLink_Result = function(result){
	if(result){
		continueToPromptedUrl();
	}
	else{
		popUpAction('LoginPopUp');
		loginOptions = { afterSuccess: continueToPromptedUrl};	
	}
}
var loginCheckPromptLink_Error = function(status,msg,exceptionObj){
	
}

function continueToPromptedUrl(){
	window.location.href = promptedURL;
}

var requestedLoginRequiredUrl;
function LoginRequired_Click()
{
	requestedLoginRequiredUrl = $(this).attr("href");
	executeRestrictedAction({
		afterSuccess: function()
		{
			//$('#reDirectHiddenVal').val(senderHref);
			/*if(senderHref.length > 0){
				$.ajax({
					type: "POST",
					url: "/_commongoal/API/ReportActivity/ReportActivityPopUp_Ajax.cfc",
					dataType: "json",
					data: {
					   method: 'processRedirectSessionVar', 
					   URL: senderHref
					},
					success: function(){
						
					}
				})
			}*/
			
			
			isReloading = true;
			//alert(requestedLoginRequiredUrl);
			location.href = requestedLoginRequiredUrl;
		}
	});
	
	return false;
}



/*
 * available options:
 * 
 * 	afterSuccess: 			fires after successful login and fade out
	afterImmediateSuccess: 	fires after successful login before fade out
	afterFailure: 			fires after failure to login has been determined and displayed to the user
	afterImmediateFailure: 	fires after login failure is determined but before displayed to user
	  preventDefault:		(optional with afterImmediateFailure)
	  						if true, after the afterImmediateFailure function is fired the default message to the user is prevented
	onClose					fires after closed

 */
function executeRestrictedAction(options)
{
	// local handlers
	var proxy = new WebsiteUserProxy();
	var loginSubmit_Result = function(result)
	{
		if(result)
		{
			if(options != null && options.hasOwnProperty("afterSuccess"))
			{
				options.afterSuccess.call(this, [true]);
			}
		}
		else
		{
			var loginPopup_Open = function()
			{
				$("#Login_EmailAddress").focus();
			};
			if(options != null && options.hasOwnProperty("onClose"))
			{
				var loginOnClose = function()
				{
					options.onClose.call();
				};
				
				$(".popUpCloseBtn").one("click", loginOnClose);
			}
			popUpAction('LoginPopUp', {afterShow: loginPopup_Open});
		}
	}
	var loginSubmit_Error = function(status,msg,exceptionObj)
	{
		if(options != null && options.hasOwnProperty("afterFailure"))
		{
			options.afterFailure.call();
		}
	}
	
	loginOptions = options;
	
	proxy.setCallbackHandler(loginSubmit_Result);
	proxy.setErrorHandler(loginSubmit_Error);
	proxy.IsLoggedIn();
}



///////////////////////////////
//////  LOGGING IN/OUT   //////
///////////////////////////////

var loginOptions;


function isLoggedIn(options)
{
	// local handlers
	var proxy = new WebsiteUserProxy();
	var loginSubmit_Result = function(result)
	{
		if(options != null && options.hasOwnProperty("afterSuccess"))
		{
			options.afterSuccess.call(this, result);
		}
	}
	var loginSubmit_Error = function(status,msg,exceptionObj)
	{
		if(options != null && options.hasOwnProperty("afterFailure"))
		{
			options.afterFailure.apply(this, [status,msg,exceptionObj]);
		}
	}
	
	proxy.setCallbackHandler(loginSubmit_Result);
	proxy.setErrorHandler(loginSubmit_Error);
	proxy.IsLoggedIn();
}

function logIn()
{
	// local handlers
	var loginSubmit_Result = function(result){
		processLoginResult(result);
	}
	
	var loginSubmit_Error = function(result){
		emailSupport(result, "function.js | Function: logIn");
		alert("We are experiencing technical difficulties and are unable to log you in at this time.\n\nWe apologize for the inconvenience. Please try again later.");
	}
	
	// strip extra hashes in URL or will error upon login attempt
	var hrefNoHash = location.href;
	if (hrefNoHash.contains("#") && !Url.HasAnyHashGroups()) 
	{
		hrefNoHash = hrefNoHash.substring(0, hrefNoHash.findNoCase("#"));
	}
	
	if($("#Login_EmailAddress").val().length > 0 && $("#Login_Password").val().length > 0){
			var proxy = new WebsiteUserProxy();
			proxy.setCallbackHandler(loginSubmit_Result);
			proxy.setErrorHandler(loginSubmit_Error);
			proxy.LogIn($("#Login_EmailAddress").val(), $("#Login_Password").val(), hrefNoHash);
			
			//dim the login forms and show a please wait.
			$('#LoginPopUp .ContentBlock .innerContentBlock .row').fadeTo(300, .3, function(){
			$('#LoginPopUp .ContentBlock .innerContentBlock').append('<div id="loginWaitMsg" style="display:none; position: absolute; top: 104px; font-size: 14px; font-weight: bold; left: 137px;">Please wait while we log you in...</div>');																	   			$('#loginWaitMsg').fadeIn(200);
		});
	}
	else{
		alert('Please enter your email address and password.');
	}
}


function logOut()
{
	// local handlers
	var logout_Result = function(result){
		
		// let everyone listening know
		$(document.body).trigger(CGEvent.WebsiteUser.LOG_OUT, [result]);
		
		var logOut_AfterHide = function()
		{
			//var loc = location.href.replace("http:\/\/", "")
			//loc = loc.substring(loc.indexOf("/"))
			var loc = location.pathname;
			switch(loc.toLowerCase())
			{
				case "/inspire/out_and_about/submit_out_and_about":
				case "/inspire/hmr_success_stories/submit_your_story":
					location.href = "/Inspire";
				break;
				case "/enjoy/recipe_submit":
					location.href = "/Enjoy";
				break;
				case "/my_profile":
				case "/my_profile/accountinfo":
				case "/my_profile/personalinfo":
				case "/my_profile/successstory":
				case "/my_profile/preferences":
					location.href = "/";
				break;
				default:
					location.reload();
				break;
			}
		};
		
		callCustomAlert(5, {afterHide: logOut_AfterHide});
		$('#signInOutRegisterLinks').html('<a href="/My_Profile/Account_Register">Sign up</a> or <a href="javascript:;" id="globalSignIn">Sign in</a>');
	}
	
	
	var proxy = new WebsiteUserProxy();
	proxy.setCallbackHandler(logout_Result);
	//proxy.setErrorHandler(logout_Error);	
	proxy.LogOut();
}


/*
 * available options
 * 	afterSuccess
 * 	afterFailure
 */
function resetPassword(email, options)
{
	if(email == null)
	{
		return;
	}
	
	var passwordProxy = new WebsiteUserProxy();
	var passwordProxy_Success = function(result)
	{
		if(options != null && options.hasOwnProperty("afterSuccess"))
		{
			options.afterSuccess.call(result);
		}
	};
	var passwordProxy_Failure = function(code, msg)
	{
		if(options != null && options.hasOwnProperty("afterFailure"))
		{
			options.afterFailure.call(msg);
		}
	};
	
	passwordProxy.setErrorHandler(passwordProxy_Failure);
	passwordProxy.setCallbackHandler(passwordProxy_Success);
	passwordProxy.ResetPassword(email);
}


function processLoginResult(result)
{
	// login popup close handler
	var loginPopup_Close = function(){
		// complete handler to send to hideOverlay
		var afterSuccess = function()
		{
			// local handler for executing on complete of login hide or of custom action popup hide
			var afterSuccessInternal = function()
			{
				if (loginOptions != null && loginOptions.hasOwnProperty("afterSuccess")) 
				{
					
					loginOptions.afterSuccess.call();
					loginOptions = null;
				}
			}
			
			// local handler
			var checkProfile_Hide = function()
			{
				afterSuccessInternal.call();
			}
			
			var customAlertID;
			if(result.hasOwnProperty("NEEDSTOCOMPLETEPROFILE") && result.NEEDSTOCOMPLETEPROFILE)
			{
				//customAlertID = 10;
				Url.SetHashGroup("Alert", 10);
				requestedLoginRequiredUrl += Url.parse().hash;
				location.reload();
			}
			/*
			if(result.hasOwnProperty("NEEDSTOCOMPLETESUCCESSSTORY") && result.NEEDSTOCOMPLETESUCCESSSTORY)
			{
				customAlertID = 9;
			}
			*/
			
			
			if (customAlertID != null) 
			{
				callCustomAlert(customAlertID, {
					afterHide: checkProfile_Hide,
					hideCloseButton: true
				});
			}
			else
			{
				afterSuccessInternal.call();
			}
		};
		hideOverlay(afterSuccess);
	};
	
	if(result.RESULT)
	{
		// let everyone listening know
		$(document.body).trigger(CGEvent.WebsiteUser.LOG_IN, [result]);
		
		$('#LoginPopUp').fadeOut(300, loginPopup_Close);
		
		if(loginOptions != null && loginOptions.hasOwnProperty("afterImmediateSuccess")){
			loginOptions.afterImmediateSuccess.call();
			loginOptions = null;
		}
		
		// reload page if required
		if(result.RELOADPAGE)
		{
			//Uncomment once Report Activity is fixed!!!
			// timeout for enough time for the code to set isReloading if needed
			setTimeout( function(){ if(isReloading){ return; } location.reload();}, 2000);
		}
		
		$('#signInOutRegisterLinks').html('<a href="/My_Profile">My Profile</a> | <a href="javascript:;" id="globalSignOut">Sign Out</a>');
	}
	else{
		if(loginOptions != null && loginOptions.hasOwnProperty("afterImmediateFailure"))
		{
			loginOptions.afterImmediateFailure.call();
			if(loginOptions.hasOwnProperty("preventDefault") && loginOptions.preventDefault)
			{
				return;
			}
			loginOptions = null;
		}
		alert("The email and/or password you entered was incorrect. Please try again.");
		if(loginOptions != null && loginOptions.hasOwnProperty("afterFailure"))
		{
			loginOptions.afterFailure.call();
			loginOptions = null;
		}
	}
}



///////////////////////////////
//////    USER DATA      //////
///////////////////////////////


//hits current session - pass in a list of websiteuser attributes ex: name.firstname,email - specify callback function that receives the results
function getCurrentUserInfo(attributes, options){
	
	/*
	$.ajax({
		type: "POST",
		url: "/_commongoal/API/Users/WebsiteUser.cfc",
		dataType: "json",
		data: {
		   method: 'getCurrentUserInfo', 
		   attributes: attributes
		},
		success: function(results){
			if(options.hasOwnProperty("afterSuccess")){
				var afterFunc = options["afterSuccess"];
				afterFunc.apply(results, Array.prototype.slice.call(arguments, 0));
			}
		}
	});
	*/
	
	var info_Success = function(results)
	{
		if(options.hasOwnProperty("afterSuccess"))
		{
			options.afterSuccess.call(this, [results]);
		}
	};
	var user = new WebsiteUserProxy();
	user.setCallbackHandler(info_Success);
	user.getCurrentUserInfo(attributes);
	
}

function readCookie(sName) {
	// cookies are separated by semicolons
	var aCookie = document.cookie.split("; ");
	for (var i=0; i < aCookie.length; i++)
	{
		// a name/value pair (a crumb) is separated by an equal sign
		var aCrumb = aCookie[i].split("=");
		if (sName == aCrumb[0]) 
		return unescape(aCrumb[1]);
	}
	// a cookie with the requested name does not exist
	return null;
}


function emailSupport(Error, Source){
	var vSource = "";
	if(!Source){vSource = Source;}
	$.ajax({
		type: "POST",
		url: "/_commongoal/API/ErrorEmail/emailSupport.cfc",
		dataType: "json",
		data: {
			method: 'emailSupport'
			, Source: vSource
			, Error: Error.responseText
		},
		success: function(){/*alert("Support Email Sent.");*/},
		error: function(){/*alert("Error sending support email.");*/}
	});
}










