﻿// subscribe.js

// NOTE: requires isFbUser and isFbEmailAuth booleans to be defined

function submitSubscription()
{
	jQuery("#subscribe_message").html("");  // clear any previous messages

	if ( (jQuery("#sb_emailaddress").length == 0) || (jQuery("#sb_emailaddress").length && validEmail(jQuery("#sb_emailaddress").val())) )
	{
		promptFbEmailPermission();
	}
	else if (jQuery("#sb_emailaddress").length && !validEmail(jQuery("#sb_emailaddress").val()) )
	{
		jQuery("#subscribe_message").html("<strong>Error</strong> - please enter a valid E-mail address.");
		jQuery("#sb_emailaddress").focus();
		jQuery("#sb_emailaddress").select();
	}

	// return false to prevent the default action of the form	
	return false;
}

function promptFbEmailPermission() {

	if (isFbUser && !isFbEmailAuth) {
		FB.login(function(response) {
			if (response.session) {
				if (response.perms) {
					// user is logged in and granted some permissions.
					// perms is a comma separated list of granted permissions
					//alert('granted perms: '+response.perms);
					sendSubscriptionRequest(true);
					jQuery.ajax({
						url: "/facebook_update_email.php",
						type: 'GET',
						dataType: 'xml',
						error: function(){ },
						success: function () { }
					});
				
				} else {
					// user is logged in, but did not grant any permissions
					sendSubscriptionRequest(false);
				}
			} else {
				// user is not logged in
			}
		}, {perms:'email'});	
	} else {
		sendSubscriptionRequest(true);
	}
}


function sendSubscriptionRequest(hasEmailPermission) {

	jQuery("#subscribe_message").html("Please wait ... submitting subscription");

	if (hasEmailPermission) {
		
		//var urlstring = "buildingid=" + jQuery("#sb_building_id").val();
		var urlstring = "recordkey=" + jQuery("#sb_record_key").val() + "&itemtype=" + jQuery("#sb_item_type").val();

		if (jQuery("#sb_emailaddress").length) {
			urlstring += "&emailaddress=" + jQuery("#sb_emailaddress").val();
		}
		
		//alert("querystring: " + urlstring);
		
		jQuery.ajax({
		    url: "/subscribe_to.php?" + urlstring,
		    type: 'GET',
		    dataType: 'xml',
		    error: function(){ alert('Error adding subscription'); jQuery("#subscribe_message").html(""); },
		    success: refreshSubscription
		});
	} else {
		jQuery("#subscribe_message").html("");
		alert("We are unable to process your subscription without permission to send you Email.");
	}

}


function refreshSubscription(xml)
{
	
	var subscription_results  = "";
	var totalFavoritesLabel = "Favorites";
	var totalFavorites = 0;

	if (xml)
	{
		subscription_results  = jQuery(xml).find('results > subscription').text();
		totalFavorites  = parseInt(jQuery(xml).find('results > favorites > count').text(), 10);
	}

	jQuery("#subscribe_message").html(subscription_results);

	// blank out the email address
	if (jQuery("#sb_emailaddress").length) {
		jQuery("#sb_emailaddress").val("");
	}

	if (totalFavorites > 0) { totalFavoritesLabel += " (" + totalFavorites + ")";}
	jQuery("#favnav").html(totalFavoritesLabel);

	// if this is a building detail page then also update the favorite button
	var favlink= jQuery('#b'+jQuery("#sb_record_key").val());
	if (favlink.length > 0) {
		favlink.attr({href: "/favorites.php?mode=buildings"});
		favlink.html('<img class="addtour" src="/images/inmyfav.gif" />');
		favlink.unbind("click", addFavoriteListing);
	}
	
	// if this is a catchment detail page then also update the favorite button
	var favlink= jQuery('#c'+jQuery("#sb_record_key").val());
	if (favlink.length > 0) {
		favlink.attr({href: "/favorites.php?mode=catchments"});
		favlink.html('<img class="addtour" src="/images/inmyfav.gif" />');
		favlink.unbind("click", addFavoriteListing);
	}
}

function validEmail(email)
{
	var emailReg = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)*\.\w{2,8}$/;
	return emailReg.test(email); 
}

function isBlank(string)
{
	var regex = /\S/;  // match any non-white-space character
	var result = regex.test(string);
	
	return (!result);
}

