
var popUpID;
var popUp_ThankYou;
var currPopUpID;
var currCustomAlertID;
var popUpStack_Arr;
var handlingPopUpSubmission = false;
var leavingHMR_PopUp;
var continueBtnLink;
var selectSubscribedTopic_TopicID = 0;
var selectSubscribedTopic_Type = "";

var followViaEmail;
var followViaEmail_Label;
var followViaRSS_Input;
var followViaRSS_Label;
var hasResetPassword = 0;

var _global_popUpOptions;

$(document).ready(function(){
	popUpStack_Arr = new Array();
	$('.popUpOpenBtn').live("click", popUpAction);
	$('.popUpCloseBtn').click(popUpAction);
	$('.CloseBtn').click(popUpAction);
	// for links in custom popup copy -- NEEDS TO BE IN LOWER CASE DUE TO FCKEDITOR
	$("*[iscustomalertcloser='true']").live("click", customAlertCloser_Click);
	// for consistency throughout custom attributes on non-FCKEditor elements
	$("*[IsCustomAlertCloser='true']").live("click", customAlertCloser_Click);
	$("*[rssLogin='true']").click(rssLogin_click);
	$('Form[isPopUpForm="true"]').ajaxForm({
		beforeSubmit: isPopUpForm_Submit
	});
	
	$('#Overlay').animate({opacity:0.4});
	$('#loginBtn').click(login_click);
	
	$('#quickRegAlreadyHaveAnAccount').live('click', quickRegAlreadyHaveAnAccount_click);
	
	$('#Login_forgotPassword').click(forgotPassword_click);
	/*$('#ResetPassword').find('.ResetPasswordBtn').click(submitEmailForPasswordReset_click);*/
	$('#ResetPassword').find('.ResetPasswordBtn').click(submitPasswordReset_click);
	leavingHMR_PopUp = $('#leavingHMR_PopUp');
	continueBtnLink = $('#continueBtnLink');
	
	followViaEmail = $('#followViaEmail');
	followViaEmail_Label = $('#followViaEmail_Label');
	followViaRSS_Input = $('#followViaRSS_Input')
    followViaRSS_Label = $('#followViaRSS_Label');
	
	/*
	$("form#ReportActivityPopUp_PopUpForm").ajaxForm({
		success: ReportActivityPopUp_PopUpForm_Success,
		beforeSubmit: ReportActivityPopUp_PopUpForm_Validate
	});
	*/
	//callCustomAlert(8);
});

function submitPasswordReset_click(){
	var proxy = new WebsiteUserProxy();
	proxy.setCallbackHandler(resetPassword_Success);
	proxy.setErrorHandler(resetPassword_Error);
	var email = $('#ResetPassword_EmailAddress').val();
	proxy.ResetPassword(email);
}

var resetPassword_Success = function(result){
	if(result.ERRORMSG != ''){
		alert(result.ERRORMSG);
	}
	else{
		$('#ResetPassword').fadeOut('fast', function(){
			$('#ResetPassword_ThankYou').fadeIn('fast');								  
		});
	}
}
var resetPassword_Error = function(){
	alert("The service is experiencing some difficulties, please try again later.");
}

function rssLogin_click(){
	var thisObj = $(this);
	var afterLoginPopUp_Val = "";
	var afterLoginAction_Val = "";
	
	if(thisObj.attr("popUpOptions")){
		_global_popUpOptions = thisObj.attr("popUpOptions");
	}
	
	if(thisObj.attr("afterLoginPopUp"))
	{
		afterLoginPopUp_Val = thisObj.attr("afterLoginPopUp");
	}
	
	if(thisObj.attr("afterLoginAction"))
	{
		afterLoginAction_Val = thisObj.attr("afterLoginAction");
	}
	
	var rssLoginComplete = function(){
		var feedPopUpComplete = function(){
			feedSubscription();
		}
		if(afterLoginAction_Val != "" && afterLoginAction_Val != null){
			popUpAction(afterLoginPopUp_Val, {afterShow: afterLoginAction_Val});
		}
		else{popUpAction(afterLoginPopUp_Val);}
	}
	executeRestrictedAction({afterSuccess: rssLoginComplete});
}

function leavingHMRPopUp(destinationURL,featured,target, unEncodedURL){
	popUpAction('leavingHMR_PopUp');
	
	if(unEncodedURL){
		continueBtnLink.attr("href", unEncodedURL);
	}else{
		continueBtnLink.attr("href", destinationURL);
	}
	
	continueBtnLink.attr("target", target);
	
	/*var newURL = 'http://' + url;
	$('#continueBtnLink').attr('href', newURL);*/
	
	continueBtnLink.unbind('click');
	continueBtnLink.click(function(){
		//popUpAction('leavingHMR_PopUp');
		/*if (featured) {
			pageTracker._trackPageview('/ORDERONLINEFEATURED/' + url);
		} else {
			pageTracker._trackPageview('/ORDERONLINREFERRAL/' + url);
		}*/
		setTimeout(runFunc,500);
	});
}

var runFunc = function(){popUpAction('leavingHMR_PopUp');};


/*
 * available options:
 * 
 * 	afterShow:		fires after popup is fully displayed
 *  afterHide:		fires after popup is fully hidden
 */
var customAlertOptions;

function callCustomAlert(AlertID, options, currPopUp){
	hideProcessing();
	//Init custom alert object & options
	popUp_Obj = $('#customAlert_PopUp');
	customAlertOptions = options;
	
	if(currPopUp){
		var currPopUpObj = $('#' + currPopUp);
		currPopUpObj.fadeOut(0);
	}
	
	//init reDirection variable
	var reDirect = "";
	//check for existance of redirect in function options
	if(options != null && options.hasOwnProperty("redirect")){
		reDirect = options.redirect;
	}
	if(reDirect.length > 0){
		popUp_Obj.attr('redirect', reDirect);
	}
	
	//retrieve custom alert data and populate custom alert with new content
	getCustomAlertContent(popUp_Obj, AlertID);
	//display/hide popup, handle 'afterShow' and 'afterHide' properties
	if(popUp_Obj.css("display") == 'block'){
		// I DON'T THINK THIS IS EVER CALLED -- WHEN CUSTOM ALERTS ARE CLOSED THE CLOSE IN popUpAction IS CALLED!!
		hideOverlay();
		popUp_Obj.fadeOut(300, function(){
			if(customAlertOptions != null){
				if(customAlertOptions.hasOwnProperty("afterHide")){
					customAlertOptions.afterHide.call();
					customAlertOptions = null;
				}
			}
			// removing the HideCloseButton class is done in popUpAction
		});
	}
	else{
		showOverlay();
		if(options != null && options.hasOwnProperty("hideCloseButton") && options.hideCloseButton){
			popUp_Obj.addClass("HideCloseButton");
		}
		
		popUp_Obj.fadeIn(300, function(){
			if(customAlertOptions != null){
				if(customAlertOptions.hasOwnProperty("afterShow")){
					customAlertOptions.afterShow.call();
					customAlertOptions = null;
				}
			}
		});
	}
}

function getCustomAlertContent(popUp_Obj, customAlert_ID){
	// local handlers
	var customAlertSuccess = function(results){
		var results = eval(results);
		var currPopUp_PopUpHeading = $(currPopUpID + ' #popUp_PopUpHeading');
		var currPopUp_MainContent = $(currPopUpID + ' #popUp_MainContent');
		
		var PopUpHeadingText = "";
		var MainContentText = "";
		$.each(results, function(i, currentApplication) {
			PopUpHeadingText += currentApplication.POPUPHEADING;
			MainContentText += currentApplication.MAINCONTENT;
		});
		currPopUp_PopUpHeading.html(PopUpHeadingText);
		currPopUp_MainContent.html(MainContentText);
	}
	
	currPopUpID = '#' + popUp_Obj.attr('ID');
	
	$.ajax({
		type: "POST",
		url: "/_commongoal/API/CustomAlerts/CustomAlerts_Ajax.cfc",
		dataType: "text",
		data: {
		   method: 'processCustomAlert', 
		   customAlertID: customAlert_ID
		},
		success: customAlertSuccess
	})
}


/*
 * available options:
 * 
 * 	afterShow:		fires after popup is fully displayed
 *  afterHide:		fires after popup is fully hidden
 */

function handlePopUpLogin(popUpObj, bolVal){
	//alert("Is Logged in..." + bolVal);
	var thisLoggedInDisplay = $('.isLoggedInDisplay');
	if(bolVal == true){
		thisLoggedInDisplay.hide();
	
		// check prepopulations
		var prePopulations = popUpObj.attr("PrePopulations");
		prePopulations = eval("({"+ prePopulations +"})");
		if(prePopulations != null)
		{
			getUserInfo_FromProxy( prePopulations );
		}
	}
	else{
		// check prepopulations
		var prePopulations = popUpObj.attr("PrePopulations");
		prePopulations = eval("({"+ prePopulations +"})");
		if(prePopulations != null)
		{
			clearPrePopulationFields( prePopulations );
		}
		thisLoggedInDisplay.show();
	}
}

function clearPrePopulationFields(options){
	for(var objID in options){$("#" + objID).val("");}
}

/*function forumReply_Reload(){
	alert("TESTing new URL");
}*/

function popUpAction(IDString, options){
	
	hideProcessing();
	// options are based off of global variable because of native calls i.e. through a link having a popupID attribute
	// options are always set first in the callCustomAlert function
	if (options != null){
		customAlertOptions = options;
	}
	//init variable used to check if requires data to pass to a function
	var feedSubscription_Data;
	
	//IDString - PopID (string, no #), used to call popups with locally ie. onclick...
	if(IDString.length > 0){
		var popUpID = '#' + IDString;
		var popUpObj = $(popUpID);
	}
	else{
		var popUpID = $(this).attr('popUpID');
		customAlert_ID = $(this).attr('customAlertID');
		
		var popUpObj = $(popUpID);
		
		if(customAlert_ID){
			getCustomAlertContent(popUpObj, customAlert_ID);
		}
	}
	
	if(popUpObj.attr("popUpInitFunction") && popUpObj.css("display") != 'block'){
		
		var funcCall = popUpObj.attr("popUpInitFunction");
		if(typeof(funcCall) == "string"){
			funcCall = window[funcCall];
		}
		funcCall.call();
	}
	
	if(popUpObj.attr("popUpInitFunction") && popUpObj.attr('id') == 'customAlert_PopUp' && popUpObj.css("display") == 'block'){
		var funcCall = popUpObj.attr("popUpInitFunction");
		if(typeof(funcCall) == "string"){
			funcCall = window[funcCall];
		}
		funcCall.call();
	}
	
	if(options && options.fromForum) {
		$('#ReportActivityFormPopUp_messageId').val(options.messageId);
		$('#ReportActivityFormPopUp_topicId').val(options.topicId);
	}
	
	if(popUpObj.attr("isLoggedIn")){
		//getUserInfo_FromProxy();
		var handlePopUpLogin_Success = function(result){
			handlePopUpLogin(popUpObj, result);
		}
		isLoggedIn({afterSuccess: handlePopUpLogin_Success});
	}
	
	if(popUpObj.css("display") == 'block'){
		if(popUpObj.attr('id') == "Forum_replyToATopicPopUp" || popUpObj.attr('id') == "Forum_NewTopicPopUp"){
			hide_ForumOverlay();
		}
		else{
			hideOverlay();
		}
		
		popUpObj.fadeOut(300, function(){
			if(popUpObj.attr('redirect')){
				location.href = popUpObj.attr('redirect');
			}
			
			if(customAlertOptions != null)
			{
				if(customAlertOptions.hasOwnProperty("afterHide"))
				{
					customAlertOptions.afterHide.call();
					customAlertOptions = null;
				}
			}
			
			popUpObj.removeClass("HideCloseButton");
		});
		
		if(popUpObj.attr("reloadOnClosing") != null && popUpObj.attr("reloadOnClosing") != false && popUpObj.attr("reloadOnClosing") != 'undefined'){
			setTimeout(function(){location.href = popUpObj.attr("reloadOnClosing");}, 2000);
		}
		
	}
	else{
		if(popUpObj.attr('id') == "Forum_replyToATopicPopUp" || popUpObj.attr('id') == "Forum_NewTopicPopUp"){
			show_ForumOverlay();
		}
		else{
			showOverlay();
		}
		
		popUpObj.fadeIn(300, function()
		{
			if(customAlertOptions != null && customAlertOptions.hasOwnProperty("afterShow"))
			{
				if(typeof(customAlertOptions.afterShow) == "string"){
					customAlertOptions.afterShow = window[customAlertOptions.afterShow];
				}
				if(customAlertOptions.afterShow){
					customAlertOptions.afterShow.call();
					customAlertOptions = null;
				}
			}
			if($('#QuickRegisterPopUp').is(':visible')){
				$('#LoginPopUp').css('display','none');
			}
		});
		
		// create captcha
		var captchas = popUpObj.find("img[IsCaptchaImage='true']");
		captchas.each(function()
		{
			var img = $(this);
			var key = getCaptchaKey();
			/*img.attr(
				{
					src: "http://www.opencaptcha.com/img/" + key,
					Key: key
				}
			);
			ContactUsFormPopUp_CaptchaImage
			alert(img.attr("id"));*/
			newCaptcha(popUpObj.attr('id'), img.attr("id"));
		});
	}
}

function newCaptcha(parentID, img){
	$.ajax({
		type: "POST",
		url: "/_commongoal/API/Captcha/Captcha_Ajax.cfc",
		dataType: "json",
		data: {
		   method: 'getNewCaptcha'
		   , popUpID: parentID
		   , imgID: img
		},
	success: newCaptchaSuccess,
	error: newCaptchaError
	})
}

var newCaptchaSuccess = function(result){
	$('#' + result.POPUPID + ' #' + result.IMGID).attr(
		{
			Key: result.KEY
			, src: 'graphics/shim.gif'
			, width: '1'
			, height: '1'
		}
	);
	$('#' + result.POPUPID + ' .newCaptchaArea').html(result.IMAGE);
}

var newCaptchaError = function(result){
	//alert("jqXHR : " + jqXHR + " | textStatus: " + textStatus);
	alert("We're sorry, an error ocurred while creating a new captcha image.");
}

function initThisThreadSubcriptions(options){
	var isSubscribedToThread = false;
	var isSubscribedToForumCategory = false;
	var subscribedTopics = [];
	var subscribedTopics_Types = [];
	
	followViaEmail.removeAttr("checked");
	followViaEmail_Label.children('.customCheckboxHolder').removeClass("selected");
	
	followViaRSS_Input.removeAttr("disabled");
	followViaRSS_Label.children('.customCheckboxHolder').removeClass("disabled");
	followViaRSS_Label.children('.customCheckboxHolder').removeClass("selected");
	
	var userProxy = new WebsiteUserProxy();
	var getUserInfo_FromProxy_Success = function(result){
		isSubscribedToForumCategory = result.SUBSCRIPTIONS.FORUMCATEGORY.contains(thisCategoryID);
		
		$(result.SUBSCRIPTIONS.FORUMTOPIC).each(
		function(){
			subscribedTopics.push(this.ID);
			subscribedTopics_Types.push(this.NOTIFICATIONTYPE);
		});
		//alert(thisCategoryID);
		isSubscribedToThread = subscribedTopics.contains(thisTopicID);
		
		if(isSubscribedToForumCategory == true)
		{
			followViaRSS_Input.removeAttr("disabled");
			followViaRSS_Label.children('.customCheckboxHolder').removeClass("disabled");
			
			if(subscribedTopics_Types.length > 0 && subscribedTopics_Types[subscribedTopics.indexOf(thisTopicID)].findNoCase("rss"))
			{
				followViaRSS_Label.children('.customCheckboxHolder').addClass("selected");
				followViaRSS_Input.attr("checked", "checked");
			}
		}else
		{
			//followViaRSS_Input.attr("disabled", "disabled");
			followViaRSS_Input.removeAttr("checked");
			//followViaRSS_Label.children('.customCheckboxHolder').addClass("disabled");
			followViaRSS_Label.children('.customCheckboxHolder').removeClass("selected");
		}
		
		if(isSubscribedToThread == true && subscribedTopics_Types[subscribedTopics.indexOf(thisTopicID)].findNoCase("email"))
		{
			$('#reply_rssSubscribe').attr("checked", "checked");
			$('#reply_rssSubscribe_Label').children('span').addClass("selected");
			
			followViaEmail.attr("checked", "checked");
			followViaEmail_Label.children('.customCheckboxHolder').addClass("selected");
		}else
		{
			$('#reply_rssSubscribe').removeAttr("checked");
			$('#reply_rssSubscribe_Label').children('span').removeClass("selected");
			
			followViaEmail.removeAttr("checked");
			followViaEmail_Label.children('.customCheckboxHolder').removeClass("selected");
		}
		
		/*--- Select Forum Subscription RSS ---*/
		if(subscribedTopics_Types.length > 0 && subscribedTopics_Types[subscribedTopics.indexOf(thisTopicID)].findNoCase("rss"))
		{
			followViaRSS_Label.children('.customCheckboxHolder').addClass("selected");
			followViaRSS_Input.attr("checked", "checked");
		}
	}
	userProxy.setCallbackHandler(getUserInfo_FromProxy_Success);
	userProxy.getCurrentUserInfo("SUBSCRIPTIONS.ForumTopic,SUBSCRIPTIONS.ForumCategory");
	
	/*var userProxy_RSSSubscription_Success = function(result){
		var blogSubscriptions = result.SUBSCRIPTIONS.FORUMTOPIC;
		var forumSubscriptions = result.SUBSCRIPTIONS.FORUMCATEGORY;
		
		for(var i = 0; i < blogSubscriptions.length; i++){
			
		}
		for(var i = 0; i < forumSubscriptions.length; i++){
			
		}
	}
	
	userProxy.setCallbackHandler(userProxy_RSSSubscription_Success);
	userProxy.getCurrentUserInfo("Subscriptions");*/
}

function getUserInfo_FromProxy(options){
	var userProxy = new WebsiteUserProxy();
	var getUserInfo_FromProxy_Success = function(result){
		for(var objID in options)
		{
			var dataValue = eval( "result." + options[objID].toUpperCase() );
			//console.log(objID + " " + dataValue)
			$("#" + objID).val( dataValue );
		}
	}
	
	// make attributes list
	var attrs = [];
	for(var objID in options)
	{
		attrs.push(options[objID].toUpperCase());
	}
	if (attrs.length > 0) 
	{
		userProxy.setCallbackHandler(getUserInfo_FromProxy_Success);
		//userProxy.getCurrentUserInfo("email,name.FULLNAME");
		userProxy.getCurrentUserInfo(attrs.toString());
	}
}

function feedSubscription(optionData){
	//alert("optionData: " + optionData);
	var getMyFeedObj = $('#GetMyFeedPopUp');
	var optionObj = $('*[selectFeed]');
	var optionData = optionObj.attr("selectFeed");
	
	var thisOption = $(".GetMyFeed_ContentBlock .Row[selectedFeed='" + optionData + "']");
	var thisOptionInput = $(".GetMyFeed_ContentBlock .Row[selectedFeed='" + optionData + "'] input");
	var thisOption_customCheckboxHolder = $(".GetMyFeed_ContentBlock .Row[selectedFeed='" + optionData + "'] .customCheckboxHolder");
	
	thisOptionInput.attr('ischecked', 'true');
	thisOption_customCheckboxHolder.addClass("selected");
	thisOptionInput.attr("checked", "checked");
	
	var userProxy = new WebsiteUserProxy();
	var userProxy_RSSSubscription_Success = function(result){
		var blogSubscriptions = result.SUBSCRIPTIONS.BLOGCATEGORY;
		var forumSubscriptions = result.SUBSCRIPTIONS.FORUMCATEGORY;
		var podcastSubscriptions = result.SUBSCRIPTIONS.PODCAST;
		
		for(var i = 0; i < blogSubscriptions.length; i++){
			var thisIDName = "blogCategory_" + blogSubscriptions[i];
			selectUserFeeds(thisIDName);
		}
		for(var i = 0; i < forumSubscriptions.length; i++){
			var thisIDName = "ForumCategory_" + forumSubscriptions[i];
			selectUserFeeds(thisIDName);
		}
		for(var i = 0; i < podcastSubscriptions.length; i++){
			selectUserFeeds("HMRPodcast");
		}
	}
	userProxy.setCallbackHandler(userProxy_RSSSubscription_Success);
	userProxy.getCurrentUserInfo("Subscriptions");
	thisOption.addClass('Selected');
	
	selectedFeedPulse(thisOption);
}

function selectUserFeeds(feedCategoryID){
	var this_OptionInput = $("#" + feedCategoryID);
	var thisOption_customCheckboxHolder = this_OptionInput.next().children('.customCheckboxHolder');
	
	this_OptionInput.attr('ischecked', 'true');
	this_OptionInput.attr("checked", "checked");
	thisOption_customCheckboxHolder.addClass("selected");
}

function selectedFeedPulse(feedObj){
	feedObj.queue("feedPulseFX");
	feedObj.animate({opacity: 0.5}, 250);
	feedObj.animate({opacity: 1.0}, 250);
	feedObj.animate({opacity: 0.5}, 250);
	feedObj.animate({opacity: 1.0}, 250);
	feedObj.animate({opacity: 0.5}, 250);
	feedObj.animate({opacity: 1.0}, 250);
	feedObj.animate({opacity: 0.5}, 250);
	feedObj.animate({opacity: 1.0}, 250);
	feedObj.animate({opacity: 0.5}, 250);
	feedObj.animate({opacity: 1.0}, 250, function(){feedObj.removeClass("Selected");});
}



function showOverlay(){
	$('#Overlay').fadeIn(300);
}

function hideOverlay(complete){
	$('#Overlay').fadeOut(300, complete);
	$('#pageVeil').fadeOut('fast');
}



function isPopUpForm_Submit(formData, $form, options){
	if(_CF_error_exists){
		return
	}
	
	var sender = $form;
	
	popUpID = sender.attr('popUpID');
	popUp_ThankYou = sender.attr('thankYouPopUp');
	var popUpObj = $(popUpID);
	
	switch(popUpID){
	case '#EmailAFriend':
		submitFormData_EmailAFriend(sender, popUpObj);
		break;
	case '#ContactUs':
	  
		break;
		/*case '#LoginPopUp':
		submitFormData_Login(sender, popUpObj);
		break;*/
	case '#ContactPopUp':
		submitFormData_ContactPopUp(sender, popUpObj);
		break;
	case '#ResetPassword':
		submitFormData_ResetPassword(sender, popUpObj);
		break;
	case '#FollowThisThread':
		submitFormData_FollowThisThreadPopUp(sender, popUpObj);
		break;
	case '#GetMyFeedPopUp':
		submitFormData_GetMyFeedPopUp(sender, popUpObj);
		break;
	case '#QuickRegisterPopUp':
		submitFormData_QuickRegisterPopUp(sender, popUpObj);
		break;
	case '#ReportInappropriateActivity':
		submitFormData_ReportActivityPopUp(sender, popUpObj);
		break;
	default:
		alert('Form did not pass validation');
	}
	
	return false;
}


function ReportActivityPopUp_PopUpForm_Success()
{
	alert("submit")
	return false;
}


function ReportActivityPopUp_PopUpForm_Validate()
{
	alert("validate");
}

function submitFormData_FollowThisThreadPopUp(formObj, popUpObj){
	var getSelectedFields = $("#FollowThisThread input:checked");
	var arrIDS = [];
	var arrTypes = [];
	
	if($('#newReplyThreadID').val() != 0){
		getSelectedFields.each(function(){
			var currObjVal = $(this).val();
			arrIDS.push($('#newReplyThreadID').val());
			arrTypes.push(currObjVal);
		});
	}
	else{
		getSelectedFields.each(function(){
			var currObjVal = $(this).val();
			
			arrIDS.push(thisTopicID);
			arrTypes.push(currObjVal);
		});
	}
	
	if(arrIDS.length == 0 && arrTypes.length == 0){
		alert("Please select a thread subscription option to subscribe.");
	}
	else{
		if(arrIDS[0]){
			subscribeToTopic(arrIDS.toString(), arrTypes.toString());
			
			if(popUpObj.attr("reloadOnClosing") != null && popUpObj.attr("reloadOnClosing") != false && popUpObj.attr("reloadOnClosing") != 'undefined'){
				$('#FollowThisThread').fadeOut(500, function(){callCustomAlert(16);});
				$('#customAlert_PopUp .popUpCloseBtn').unbind('click');
				$('#customAlert_PopUp .CloseBtn').unbind('click');
				
				if(popUpObj.attr("newForumThreadURL")){
					$('#customAlert_PopUp .popUpCloseBtn').bind('click', function(){location.href = popUpObj.attr("newForumThreadURL");});
					$('#customAlert_PopUp .CloseBtn').bind('click', function(){location.href = popUpObj.attr("newForumThreadURL");});
				}
				else{
					$('#customAlert_PopUp .popUpCloseBtn').bind('click', function(){forumReply_Reload();});
					$('#customAlert_PopUp .CloseBtn').bind('click', function(){forumReply_Reload();});
				}
			}
			else{
				closePopUp(0, "GetMyFeedPopUp_ThankYou");
			}
		}
		else{
			unSubscribeToTopic();
			if(popUpObj.attr("reloadOnClosing") != null && popUpObj.attr("reloadOnClosing") != false && popUpObj.attr("reloadOnClosing") != 'undefined'){
				
				$('#FollowThisThread').fadeOut(500, function(){callCustomAlert(16);});
				$('#customAlert_PopUp .popUpCloseBtn').unbind('click');
				$('#customAlert_PopUp .CloseBtn').unbind('click');
				
				$('#customAlert_PopUp .popUpCloseBtn').bind('click', function(){forumReply_Reload();});
				$('#customAlert_PopUp .CloseBtn').bind('click', function(){forumReply_Reload();});
			}
			else{
				closePopUp(0, "GetMyFeedPopUp_ThankYou");
			}
		}
	}
}

function unSubscribeToTopic(id, type){
	$.ajax({
		type: "POST",
		url: "/_commongoal/API/FollowThisThread/FollowThisThread_Ajax.cfc",
		dataType: "json",
		data: {
		   method: 'unSubscribeFromThread', 
		   Source: "Topic",
		   ItemID: selectSubscribedTopic_TopicID,
		   SubscriptionTypeMap: selectSubscribedTopic_Type
		},
	success: updateFeedLinks
	})
}

function subscribeToTopic(id, type){
	$.ajax({
		type: "POST",
		url: "/_commongoal/API/FollowThisThread/FollowThisThread_Ajax.cfc",
		dataType: "json",
		data: {
		   method: 'threadSubscription', 
		   Source: "Topic",
		   ItemID: id,
		   SubscriptionTypeMap: type
		},
	success: updateFeedLinks
	})
}

function submitFormData_GetMyFeedPopUp(formObj, popUpObj){
	
	var getSelectedFields = $("#getMyFeedTable input[ischecked='true']");
	
	//rssSubscription_#VCHCATEGORYNAME#
	var selectedCatForumCategories = $('#getMyFeedTable input[source="ForumCategory"]:checked');
	var forumCategoryIDs = [];
	selectedCatForumCategories.each(function(){
		forumCategoryIDs.push($(this).val());
	});
	subscribeToFeedSuccess("ForumCategory", forumCategoryIDs.toString());
	
	var selectedBlogCategories = $('input[source="BlogCategory"]:checked');
	var blogCategoryIDs = [];
	selectedBlogCategories.each(function(){
		blogCategoryIDs.push($(this).val());
	});
	subscribeToFeedSuccess("BlogCategory", blogCategoryIDs.toString());
	
	
	var selectedPodcast = $('input[source="Podcast"]:checked');
	var podcastIDs = [];
	selectedPodcast.each(function(){
		podcastIDs.push(1);
	});
	subscribeToFeedSuccess("Podcast", podcastIDs.toString());/**/
	closePopUp(12);
}

function subscribeToFeedSuccess(source, ids){
	//subscribeToFeed_Results = subscribeToFeed_Results + 1;
	var CategorySubscriptionType = 0;
	if($('.CategorySubscriptionType').val().length > 0){
		CategorySubscriptionType = $('.CategorySubscriptionType').val();
	}
	
	$.ajax({
		type: "POST",
		url: "/_commongoal/API/GetMyFeedPopUp/GetMyFeedPopUp_Ajax.cfc",
		dataType: "json",
		data: {
		   method: 'processRSSFeed', 
		   Source: source,
		   ItemIDs: ids,
		   CategorySubscriptionType: CategorySubscriptionType
		},
	success: updateFeedLinks
	})
}


var updateFeedLinks = function(){
	var wsu = new WebsiteUserProxy();
	
	var wsu_Result = function(result){
		var websiteUserID = result.ID;
	
		var getMyFeedLinks = $('.getMyFeedLinks');
		var hrefToUpdate = getMyFeedLinks.attr("href");
		
		var newHref = hrefToUpdate.replace("[websiteuserid]", websiteUserID);
		getMyFeedLinks.html(newHref);
		getMyFeedLinks.attr("href", newHref);
		
		updateRSSLock();
	}
	wsu.setCallbackHandler(wsu_Result);
	wsu.getCurrentUserInfo("ID");
}

function updateRSSLock(){
	var wsu = new WebsiteUserProxy();
	
	var wsu_Result = function(result){
		var rssLock = encodeURI(result.SECRETKEY);
	
		var getMyFeedLinks = $('.getMyFeedLinks');
		var hrefToUpdate = getMyFeedLinks.attr("href");
		
		var newHref = hrefToUpdate.replace("[rssLock]", rssLock);
		getMyFeedLinks.html(newHref);
		getMyFeedLinks.attr("href", newHref);
	}
	wsu.setCallbackHandler(wsu_Result);
	wsu.getCurrentUserInfo("SecretKey");
}

function toggleIscheckedAttr_true(){
	var thisObj = $(this);
	var thisObj_customCheckboxHolder = thisObj.next().children('.customCheckboxHolder');
	thisObj.attr('ischecked', 'true');
	thisObj.attr("checked", "checked");
	thisObj_customCheckboxHolder.addClass("selected");
}

function toggleIscheckedAttr_false(){
	var thisObj = $(this);
	var thisObj_customCheckboxHolder = thisObj.next().children('.customCheckboxHolder');
	thisObj.attr('ischecked', 'false');
	thisObj.removeAttr("checked");
	thisObj_customCheckboxHolder.removeClass("selected");
}



function submitFormData_EmailAFriend(formObj, popUpObj){
	var EmailAFriend_Captcha;
	 if(popUpObj.attr("isLoggedIn") == "true"){
		var EmailAFriend_Captcha = $('#EmailAFriend_Captcha').val();
	}
	else{
		var EmailAFriend_Captcha = 0;
	}
	
	var email_Complete = function()
	{
		var linkVal = "";
		if($('#EmailAFriend_Link').val().length > 0){
			var linkVal = $('#EmailAFriend_Link').val();
		}
		$.ajax({
			type: "POST",
			url: "/_commongoal/API/EmailAFriend/EmailAFriend_Ajax.cfc",
			dataType: "json",
			data: {
				method: 'processEmailAFriend', 
		   		SendToEmail: $('#EmailAFriend_SendToEmail').val(),
		   		FromEmail: $('#EmailAFriend_FromEmail').val(),
		   		PersonalMessage: $('#EmailAFriend_PersonalMessage').val(),
				Link: linkVal,
		   		Captcha: $('#EmailAFriend_Captcha').val()
			},
			success: function(){
				$('#EmailAFriend_SendToEmail').val('');
				$('#EmailAFriend_Captcha').val('');
				if(popUpObj.attr("isLoggedIn") == "false"){
					$('#EmailAFriend_FromEmail').val('');
				}
				emailFriendSuccess.call();
			}
		})
	};
	
	if($('#EmailAFriend_Captcha').is(":visible")){
		
		// check captcha value
		var captchaTrue = function()
		{
			email_Complete();
		};
		var captchaFalse = function()
		{
			alert("The code input did not match the security image. Please re-try.");
			$("#EmailAFriend_Captcha").select();
		}
		
		var cKey = $("#EmailAFriend_CaptchaImage").attr("Key");
		var cAnswer = $('#EmailAFriend_Captcha').val();
		if(cKey == cAnswer){
			email_Complete();
		}else{
			/*captchaFalse;
			alert("No - cKey:" + cKey + " cAnswer: " + cAnswer);*/
			alert("The code input did not match the security image. Please re-try.");
			newCaptcha(popUpObj.attr("ID"), "EmailAFriend_CaptchaImage");
			$("#ContactUsFormPopUp_Captcha").select();
		}
		/*testCaptcha(cKey,cAnswer, {
			onTrue: captchaTrue,
			onFalse: captchaFalse
		});*/
	}
	else
	{
		email_Complete();
	}
	/*$.ajax({
		type: "POST",
		url: "/_commongoal/API/EmailAFriend/EmailAFriend_Ajax.cfc",
		dataType: "json",
		data: {
		   method: 'processEmailAFriend', 
		   SendToEmail: $('#EmailAFriend_SendToEmail').val(),
		   FromEmail: $('#EmailAFriend_FromEmail').val(),
		   PersonalMessage: $('#EmailAFriend_PersonalMessage').val(),
		   Captcha: $('#EmailAFriend_Captcha').val()
		},
	success: emailFriendSuccess
	})*/
}

function submitFormData_ContactPopUp(formObj, popUpObj){
	
	var ContactUs_CaptchaUserVal = $('#ContactUsFormPopUp_Captcha').val();
	var ContactUsFormPopUp_FullName = $('#ContactUsFormPopUp_FullName').val();
	var ContactUsFormPopUp_Email = $('#ContactUsFormPopUp_Email').val();
	var ContactUsFormPopUp_Phone = $('#ContactUsFormPopUp_Phone').val();
	var ContactUsFormPopUp_Comments = $('#ContactUsFormPopUp_Comments').val();
	
	if(popUpObj.attr("isLoggedIn") == "true"){
		var ContactUsFormPopUp_Captcha = $('#ContactUsFormPopUp_Captcha').val();
	}
	else{
		var ContactUsFormPopUp_Captcha = 0;
	}
	
	var contactUs_Complete = function()
	{
		$.ajax({
			type: "POST",
			url: "/_commongoal/API/ContactPopUp/ContactPopUp_Ajax.cfc",
			dataType: "json",
			data: {
			   method: 'processContactPopUp', 
			   FullName: ContactUsFormPopUp_FullName,
			   Email: ContactUsFormPopUp_Email,
			   Phone: ContactUsFormPopUp_Phone,
			   Comments: ContactUsFormPopUp_Comments
			},
			success: function(){
				$('#ContactUsFormPopUp_FullName').val('');
				$('#ContactUsFormPopUp_Captcha').val('');
				$('#ContactUsFormPopUp_Phone').val('');
				$('#ContactUsFormPopUp_Comments').val('');
				if(popUpObj.attr("isLoggedIn") == "false"){
					$('#ContactUsFormPopUp_Email').val('');
				}
				emailFriendSuccess.call();
			}
		})
	};
	
	if($('#ContactUsFormPopUp_Captcha').is(":visible")){
		
		// check captcha value
		var captchaTrue = function()
		{
			contactUs_Complete();
		};
		var captchaFalse = function()
		{
			alert("The code input did not match the security image. Please re-try.");
			$("#ContactUsFormPopUp_Captcha").select();
		}
		
		var cKey = $("#ContactUsFormPopUp_CaptchaImage").attr("Key");
		var cAnswer = ContactUs_CaptchaUserVal;
		
		if(cKey == cAnswer){
			contactUs_Complete();
		}else{
			/*captchaFalse;
			alert("No - cKey:" + cKey + " cAnswer: " + cAnswer);*/
			alert("The code input did not match the security image. Please re-try.");
			newCaptcha(popUpObj.attr("ID"), "ContactUsFormPopUp_CaptchaImage");
			$("#ContactUsFormPopUp_Captcha").select();
		}
		/*testCaptcha(cKey,cAnswer, {
			onTrue: captchaTrue,
			onFalse: captchaFalse
		});*/
	}
	else
	{
		contactUs_Complete();
	}
}

function submitFormData_ResetPassword(formObj, popUpObj){
	/*if(hasResetPassword == 0){
		hasResetPassword = 1;
		var proxy = new WebsiteUserProxy();
		proxy.setCallbackHandler(reset_Success);
		proxy.setErrorHandler(reset_Error);
		var email = $('#ResetPassword_EmailAddress').val();
		proxy.ResetPassword(email);
		
		$('#ResetPassword').fadeOut('fast', function(){
			$('#ResetPassword_ThankYou').fadeIn('fast');								  
		});
	}
	else{
		alert("A confirmation email has already been sent to your address.");
		//window.location.reload();
	}*/
}

function submitFormData_QuickRegisterPopUp(formObj, popUpObj){
	//alert("Quick Registered");
}

function submitFormData_ReportActivityPopUp(formObj, popUpObj){
	
	if ($('#ReportActivityFormPopUp_topicId').val() != "") var topicId = $('#ReportActivityFormPopUp_topicId').val()
	if ($('#ReportActivityFormPopUp_messageId').val() != "") var messageId = $('#ReportActivityFormPopUp_messageId').val()
	
	if (topicId && messageId) {
		var sendData = { method: 'processReportPopUp', Email: $('#ReportActivityFormPopUp_Email').val(), Problem: $('#ReportActivityFormPopUp_Problem').val(), topicId: topicId, messageId: messageId, issueURL: location.href }
	} else {
		var sendData = { method: 'processReportPopUp', Email: $('#ReportActivityFormPopUp_Email').val(), Problem: $('#ReportActivityFormPopUp_Problem').val(), issueURL: location.href
			 }
	}
	
	var reportActivity_Complete = function()
	{
		$.ajax({
			type: "POST",
			url: "/_commongoal/API/ReportActivity/ReportActivityPopUp_Ajax.cfc",
			dataType: "json",
			data: sendData,
			success: function(){
				$('#ReportActivityFormPopUp_Problem').val('');
				$('#ReportActivityFormPopUp_Captcha').val('');
				if(popUpObj.attr("isLoggedIn") == "false"){
					$('#ReportActivityFormPopUp_Email').val();
				}
				emailFriendSuccess.call();
			}
		})
		
	};
	
	// check captcha value
	if($("#ReportActivityFormPopUp_CaptchaImage").is(":visible"))
	{
		var captchaTrue = function()
		{
			reportActivity_Complete();
		};
		var captchaFalse = function()
		{
			alert("The code input did not match the security image. Please re-try.");
			$("#ReportActivityFormPopUp_Captcha").select()
		};
		
		var cKey = $("#ReportActivityFormPopUp_CaptchaImage").attr("Key");
		var cAnswer = $("#ReportActivityFormPopUp_Captcha").val();
		if(cKey == cAnswer){
			reportActivity_Complete();
		}else{
			/*captchaFalse;
			alert("No - cKey:" + cKey + " cAnswer: " + cAnswer);*/
			alert("The code input did not match the security image. Please re-try.");
			newCaptcha(popUpObj.attr("ID"), "ReportActivityFormPopUp_CaptchaImage");
			$("#ContactUsFormPopUp_Captcha").select();
		}
		
		/*testCaptcha(cKey, cAnswer, {
			onTrue: captchaTrue,
			onFalse: captchaFalse
		});*/
	}
	else
	{
		reportActivity_Complete();
	}
}

var emailFriendSuccess = function(result){
	closePopUp();
}

function closePopUp(customAlertID, thankYouPopUp, options){
	$(popUpID).fadeOut(300, function(){
		if(thankYouPopUp){
			var thankYouPopUp = $("#" + thankYouPopUp);
			thankYouPopUp.fadeIn(300);
		}
		else{
			if(popUp_ThankYou){
				$(popUp_ThankYou).fadeIn(300);
			}
			else{
				if(customAlertID){
					if(options){
						callCustomAlert(customAlertID, options);
					}
					else{
						callCustomAlert(customAlertID);
					}
				}
				else{
					hideOverlay();
				}
			}
		}
	});
	
}

function login_click(){
	// calls core function
	logIn();
}

function logMeOut(){
	// calls core function
	logOut();
}



function quickRegAlreadyHaveAnAccount_click(){
	$('#QuickRegisterPopUp').fadeOut('fast');
	$('#LoginPopUp').fadeIn('fast');
	//popUpAction('LoginPopUp', {});
}


function showImageUpload_click(){
	var quickRegContainer = $('#QuickRegisterPopUp');
	quickRegContainer.find('.photoCropContainer').css('display', 'block');
	quickRegContainer.find('.yourAccountStepOne').css('display', 'none');
}


function customAlertCloser_Click()
{
	popUpAction("customAlert_PopUp");
}

function customAlertOpener_Click()
{
	popUpAction("customAlert_PopUp");
}

function closeQuickReg_click(){
	$('#LoginPopUp').css('display','none');	
}


function forgotPassword_click(){
	$('#LoginPopUp').fadeOut('fast', function(){
		$('#ResetPassword').fadeIn('fast');								  
	});
}




