/**
 * 
 * @copyright (C) 2010 OnSite Media, LLC. All rights reserved.
 * @author Chris Koning <ckoning@on-site-media.com>
 */

/******************************************************************************
 * GLOBAL VARIABLES
 *****************************************************************************/

/**
 * A listing of the service url proxy to bypass AJAX security
 */
// var dataUrl = "http://@@host@@/proxy/";	// http://www.ethostream.com/CentralAuth/ for ethostream

var dataUrl = "http://"+top.location.host+"/proxy/";

/**
 * A flag to indicate whether or not a user has signed in
 */
var authenticated = false;

/**
 * Determines the mode of the display, either 'ad' for advertisement bubbles or 'dir' for directory display
 */
var mode = '';

/******************************************************************************
 * PANE CREATION AND BEHAVIOR
 *****************************************************************************/

/**
 * Show the category bubble listing pane. The pane produces a transparent 
 * overlay div to dark out the background page, and then shows the panel used 
 * to list all the bubbles. Takes two parameters, a UUID specifying the 
 * category, and a UUID specifying the kiosk. The category IDs are populated on
 * intial page load, but the kiosk ID must be passed to the page to identify 
 * where the kiosk is.
 * 
 * @param string cid - The UUID specifying the category
 * @return nothing
 * @todo Implement better AJAX failure handling
 */
function showPane()
{	// Fade in the overlay
	$('#osmOv').css('filter', 'alpha(opacity=90)');
	$('#osmOv').fadeIn('fast',function(){});
	// Fade in the page
	$('#osmPg').fadeIn('fast',function(){});
}

function showContent(catid, reset)
{	// If the page is not visible, show the pane
	if( !$('#osmPg').is(':visible') ) {
		showPane();
	}
	// Perform separate actions based on the mode
	switch(mode) {
		case 'reg':
			showRegister();
			break;
		case 'log':
			showLogin();
			break;
		case 'rec':
			showRecover();
			break;
	}
}


/**
 * Hides the category bubble listing from view. This method will be called when
 * the close buttong is clicked on the bubble listing window and when an ad is 
 * clicked to be shown.
 * 
 * @return nothing
 */
function hidePane()
{	// Hide the darkening overlay
	$('#osmOv').fadeOut('fast');
	// Fade in the page
	$('#osmPg').fadeOut('fast');
	// Set the title to neutral
	document.title = "OnSite Media";
}

/******************************************************************************
 * TERMS CREATION AND BEHAVIOR
 *****************************************************************************/

function showTerms()
{	// Show the pane
	showPane();
	// Hide the other panes
	hidePrivacy();
	hideLogin();
	hideRegister();
	hideRecover();
	// Show the loader
	$('#osmLoader').fadeIn('fast');
	// Get the ad information
	$.ajax({
		type:"POST",
		url: dataUrl+"getterms",
		data:"",
		success:function(msg) {
			// Check for JSON support
			if(!JSON) alert("JSON Not Supported");
			// Parse the response
			var results = JSON.parse(msg);
			// Decode the markup
			var markup = URLDecode(results.markup);
			// Add it to the page
			$('#osmTermsText').html(markup);
			// Hide the loader
			$('#osmLoader').fadeOut('fast');
			// Show the pane
			$('#osmTerms').fadeIn('fast');
		},
		error:function(xhr, status, error) {
			// NEED WAY BETTER ERROR HANDLING HERE
			alert('An error has occurred');
			// Hide the loading sections
			$('#osmLoader').fadeOut('fast');
		}
	});
}

function hideTerms()
{	// Hide the pane
	if( $('#osmTerms').is(':visible') ) $('#osmTerms').hide();
}

/******************************************************************************
 * PRIVACY CREATION AND BEHAVIOR
 *****************************************************************************/

function showPrivacy()
{	// Show the pane
	showPane();
	// Hide the other panes
	hideTerms();
	hideLogin();
	hideRegister();
	hideRecover();
	// Show the loader
	$('#osmLoader').fadeIn('fast');
	// Get the ad information
	$.ajax({
		type:"POST",
		url: dataUrl+"getprivacy",
		data:"",
		success:function(msg) {
			// Check for JSON support
			if(!JSON) alert("JSON Not Supported");
			// Parse the response
			var results = JSON.parse(msg);
			// Decode the markup
			var markup = URLDecode(results.markup);
			// Add it to the page
			$('#osmPrivacyText').html(markup);
			// Hide the loader
			$('#osmLoader').fadeOut('fast');
			// Show the pane
			$('#osmPrivacy').fadeIn('fast');
		},
		error:function(xhr, status, error) {
			// NEED WAY BETTER ERROR HANDLING HERE
			alert('An error has occurred');
			// Hide the loading sections
			$('#osmLoader').fadeOut('fast');
		}
	});
}

function hidePrivacy()
{	// Hide the pane
	if( $('#osmPrivacy').is(':visible') ) $('#osmPrivacy').hide();
}

/******************************************************************************
 * LOGIN CREATION AND BEHAVIOR
 *****************************************************************************/

function showLogin()
{	// Hide the other panes
	hideTerms();
	hidePrivacy();
	hideRegister();
	hideRecover();
	// Reset from values
	$('input[name=osmLoginFormEmail]').val('');
	$('input[name=osmLoginFormPassword]').val('');
	$('#osmLoginMsgBox').html('');
	// Show the loader
	$('#osmLogin').fadeIn('fast');
}

function hideLogin()
{	// Hide the pane
	if( $('#osmLogin').is(':visible') ) $('#osmLogin').hide();
}

function doLogin()
{	// Validate the login form
	$('#osmLoginForm').validate({
		errorLabelContainer: "#osmLoginMsgBox",
		wrapper: "li",
		messages: {
			osmLoginFormEmail: {
				required: "Please enter your email address",
				email: "Your email address must be a fully qualified address, such as name@domain.com"
			},
			osmLoginFormPassword: {
				required: "Please enter your password"
			}
		}
	});
	// If it passes validation, attempt to hit remote server
	if( $('#osmLoginForm').valid() ) {
		// Get the values
		var uname = $('input[name=osmLoginFormEmail]').val();
		var pword = $('input[name=osmLoginFormPassword]').val();
		$.ajax({
			type:"POST",
			url: dataUrl+"login",
			data:"uname="+uname+"&pword="+pword,
			success:function(msg) {
				// Check for JSON support
				if(!JSON) alert("JSON Not Supported");
				// Parse the response
				var results = JSON.parse(msg);
				// Set the authenticated flag
				authenticated = results.authenticated;				
				// Show a message if failed
				if( authenticated == false ) {
					$('#osmLoginMsgBox').append('<li style="display: block"><label for="osmLoginFormPassword" generated="true" class="error" style="display: block; ">Invalid email address/password</label></li>');
					$('#osmLoginMsgBox').show();
				} else {
					alert("User "+uname+"successfully logged in.");
					showContent(cid,true);
				}
			},
			error:function(xhr, status, error) {
				// NEED WAY BETTER ERROR HANDLING HERE
				alert('An error has occurred');
			}
		});
	}
}

/******************************************************************************
 * REGISTER CREATION AND BEHAVIOR
 *****************************************************************************/

function showRegister()
{	// Show the pane
	showPane();
	// Set the mode
	mode='reg';
	// Hide the other panes
	hideTerms();
	hidePrivacy();
	hideLogin();
	hideRecover();
	// Show the loader
	$('#osmRegister').fadeIn('fast');
}

function hideRegister()
{	// Hide the pane
	if( $('#osmRegister').is(':visible') ) $('#osmRegister').hide();
}

function doRegister()
{	// Empty the error messages
	$('#osmRegisterMsgBox').html('');
        // VALIDATE FORM
	// Init tracking
	var valid = true;
	var errmsg = '';
	// Validate First Name
	if( $('#osmRegisterFormFName').val() == '' || $('#osmRegisterFormFName').val() == null ) {
		valid = false;
		errmsg = errmsg + "-Please enter your first name\n";
	}
	// Validate Last Name
	if( $('#osmRegisterFormLName').val() == '' || $('#osmRegisterFormLName').val() == null ) {
		valid = false;
		errmsg = errmsg + "-Please enter your last name\n";
	}
	// Validate Email
	var eml_regex = /^(([^<>()[\]\\.,;:@\"]+(\.[^<>()[\]\\.,;:@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
	if( $('#osmRegisterFormEmail').val() == '' || $('#osmRegisterFormEmail').val() == null ) {
		valid = false;
		errmsg = errmsg + "-Please enter your email address\n";
	} else if( !eml_regex.test($('#osmRegisterFormEmail').val()) ) {
		valid = false;
		errmsg = errmsg + "-Your email address must be a fully qualified address, such as name@domain.com\n";
	}
	// Validate Address
	if( $('#osmRegisterFormAddr').val() == '' || $('#osmRegisterFormAddr').val() == null ) {
		valid = false;
		errmsg = errmsg + "-Please enter your street address\n";
	}
	// Validate City
	if( $('#osmRegisterFormCity').val() == '' || $('#osmRegisterFormCity').val() == null ) {
		valid = false;
		errmsg = errmsg + "-Please enter your city of residence\n";
	}
	// Validate State
	if( $('#osmRegisterFormState').val() == '' || $('#osmRegisterFormState').val() == null ) {
		valid = false;
		errmsg = errmsg + "-Please select your state\n";
	}
	// Validate Zip
	if( $('#osmRegisterFormZip').val() == '' || $('#osmRegisterFormZip').val() == null ) {
		valid = false;
		errmsg = errmsg + "-Please enter your postal code\n";
	}
	// Validate Phone
        var osm_phone = ''+$('input[name=osmRegisterFormArea]').val()+ $('input[name=osmRegisterFormExchange]').val() + $('input[name=osmRegisterFormExtension]').val();
        var osm_phone_regex = /\d{10}/;
        if( !osm_phone_regex.test(osm_phone) ) {
                valid = false;
                errmsg = errmsg + "-Please enter a valid phone number\n";
        }
        // Validate Birthday
        var osm_date = new Date();
        // Validate birth month
        if( 	$('input[name=osmRegisterFormBmonth]').val() == '' ||
                $('input[name=osmRegisterFormBmonth]').val() == null ||
                parseInt($('input[name=osmRegisterFormBmonth]').val(),10) > 12 ||
                parseInt($('input[name=osmRegisterFormBmonth]').val(),10) == 0
          ) {
                valid = false;
                errmsg = errmsg + "-Please enter a valid birth month\n";
        }
        // Validate birth day
        if(     $('input[name=osmRegisterFormBday]').val() == '' ||
                $('input[name=osmRegisterFormBday]').val() == null ||
                parseInt($('input[name=osmRegisterFormBday]').val(),10) > 31 ||
                parseInt($('input[name=osmRegisterFormBday]').val(),10) == 0
          ) {
                valid = false;
                errmsg = errmsg + "-Please enter a valid birth day\n";
        }
        // Validate birth years
        if( 	$('input[name=osmRegisterFormByear]').val() == '' ||
        		$('input[name=osmRegisterFormByear]').val() == null ||
                $('input[name=osmRegisterFormByear]').val().length < 4 ||
                parseInt($('input[name=osmRegisterFormByear]').val(),10) > osm_date.getFullYear() ||
                parseInt($('input[name=osmRegisterFormByear]').val(),10) < osm_date.getFullYear()-120 ||
                parseInt($('input[name=osmRegisterFormByear]').val(),10) == 0
          ) {
			valid = false;
			errmsg = errmsg + "-Please enter a valid birth year\n";
        } else if( 	parseInt($('input[name=osmRegisterFormByear]').val(),10) > osm_date.getFullYear()-18 ) {
			valid = false;
			errmsg = errmsg + "-You must be 18 to use the OnSite Media Concierge system\n";
        } else if( 	parseInt($('input[name=osmRegisterFormByear]').val(),10) == osm_date.getFullYear()-18 && 
        			parseInt($('input[name=osmRegisterFormBmonth]').val(),10) > osm_date.getMonth()+1 
        		 ) {
			valid = false;
			errmsg = errmsg + "-You must be 18 to use the OnSite Media Concierge system\n";
        } else if ( parseInt($('input[name=osmRegisterFormByear]').val(),10) == osm_date.getFullYear()-18 && 
    				parseInt($('input[name=osmRegisterFormBmonth]').val(),10) == osm_date.getMonth()+1 && 
    				parseInt($('input[name=osmRegisterFormBday]').val(),10) > osm_date.getDate()
    			  ) {
			valid = false;
			errmsg = errmsg + "-You must be 18 to use the OnSite Media Concierge system\n";
        }
	// Validate Password
	if( $('#osmRegisterFormPword').val() == '' || $('#osmRegisterFormPword').val() == null ) {
		valid = false;
		errmsg = errmsg + "-Please choose a password\n";
	}
	if( $('#osmRegisterFormConfirm').val() == '' || $('#osmRegisterFormConfirm').val() == null ) {
		valid = false;
		errmsg = errmsg + "-Please confirm your password\n";
	}
        if( $('#osmRegisterFormPword').val() != $('#osmRegisterFormConfirm').val() && $('#osmRegisterFormPword').val() != '') {
		valid = false;
		errmsg = errmsg + "-Passwords don't match\n";
        }
	// Validate Terms
	if( !$('#osmRegisterFormTerms').attr('checked') ) {
		valid = false;
		errmsg = errmsg + "-Please review and accept the Terms and Conditions and Privacy Policy\n";
	}

	// Check for form validity and act accordingly
	if( valid ) {
		// Form is valid, need to build data string to send to web service
		var fname = $('#osmRegisterFormFName').val();
		var lname = $('#osmRegisterFormLName').val();
		var email = $('#osmRegisterFormEmail').val();
		var address = $('#osmRegisterFormAddr').val();
		var city = $('#osmRegisterFormCity').val();
		var state = $('#osmRegisterFormState').val();
		var zip = $('#osmRegisterFormZip').val();
		var phone = osm_phone;
		var bdate = $('input[name=osmRegisterFormByear]').val()+'-'+$('input[name=osmRegisterFormBmonth]').val()+'-'+$('input[name=osmRegisterFormBday]').val();
		var pword = $('#osmRegisterFormPword').val();
		var news = ( $('#osmRegisterFormNewsletter').attr('checked') ) ? true : false;
		var incentives = ( $('#osmRegisterFormIncentives').attr('checked') ) ? true : false;
		var terms = ( $('#osmRegisterFormTerms').attr('checked') ) ? true : false;
		// Combine into query string
		var data = 'fname='+fname+'&lname='+lname+'&email='+email+'&address='+address+'&city='+city+'&state='+state+'&zip='+zip+'&phone='+phone+'&bdate='+bdate+'&pword='+pword+'&news='+news+'&incentives='+incentives+"&terms="+terms;
		// Make ajax call
		$.ajax({
			type:"POST",
			url: dataUrl+"register",
			data: ''+data,
			success:function(msg) {
				// Check for JSON support
				if(!JSON) alert("JSON Not Supported");
				// Parse the response
				var results = JSON.parse(msg);
				// Set the authenticated flag
				var success = results.success;
				// Show a message if failed
				if( success == false ) {
					alert(results.message);
					authenticated = false;
				} else {
					authenticated = true;
					alert(results.message);
				}
			},
			error:function(xhr, status, error) {
				// NEED WAY BETTER ERROR HANDLING HERE
				alert('An error has occurred');
			}
		});
	} else {
		// Otherwise errors found, display messages
                errmsg = errmsg.substring(0,errmsg.length-1);
                alert(errmsg);
	}
}

/******************************************************************************
 * PASSWORD RECOVERY CREATION AND BEHAVIOR
 *****************************************************************************/

function showRecover()
{	// Hide the other panes
	hideTerms();
	hidePrivacy();
	hideLogin();
	hideRegister();
	// Reset from values
	$('input[name=osmRecoverFormEmail]').val('');
	$('#osmRecoverMsgBox').html('');
	// Hide the paging
	$('#prv:visible').fadeOut('fast');
	$('#nxt:visible').fadeOut('fast');	
	// Hide the navigation
	if( $('#osmNavigation').is(':visible') ) $('#osmNavigation').hide();
	// Show the loader
	$('#osmRecover').fadeIn('fast');
}

function hideRecover()
{	// Hide the pane
	if( $('#osmRecover').is(':visible') ) $('#osmRecover').hide();
}

function doRecover()
{		$('#osmRecoverForm').validate({
			errorLabelContainer: "#osmRecoverMsgBox",
			wrapper: "li",
			messages: {
				osmRecoverFormEmail: {
					required: "Please enter your email address",
					email: "Your email address must be a fully qualified address, such as name@domain.com"
				}
			}
		});
		if( $('#osmRecoverForm').valid() ) {
			// Get the values
			var uname = $('input[name=osmRecoverFormEmail]').val();
			// Call data service to perform password reset
			$.ajax({
				type:"POST",
				url: dataUrl+"resetpassword",
				data:"uname="+uname,
				success:function(msg) {
					// Check for JSON support
					if(!JSON) alert("JSON Not Supported");
					// Parse the response
					var results = JSON.parse(msg);
					// Check for success
					if( results.success == false ) {
						$('#osmRecoverMsgBox').append('<li style="display: block"><label for="osmRecoverFormEmail" generated="true" class="error" style="display: block; ">'+results.message+'</label></li>');
						$('#osmRecoverMsgBox').show();
					} else {
						alert(results.message);
						showContent(cid,true);
					}
				},
				error:function(xhr, status, error) {
					// NEED WAY BETTER ERROR HANDLING HERE
					alert('An error has occurred');
				}
			});
		}
}

/******************************************************************************
 * USER MANAGEMENT INITIALIZATION
 *****************************************************************************/

function URLDecode( encoded )
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
   return plaintext;
};

function initLogin()
{	// Add the login button action
	$('#osmLoginBtn').click(function(){
		doLogin();
	});
	// Add the forgot button action
	$('#osmLoginRecBtn').click(function(){
		showRecover();
	});
	// Add the register button action
	$('#osmLoginRegBtn').click(function(){
		showRegister();
	});
}

function initRegister()
{	// Add the register button action
	$('#osmRegisterRegBtn').click(function(){
		doRegister();
	});
	// Add the cancel button behavior
	$('#osmRegisterCancelBtn').click(function(){
		hidePane();
	});
}

function initRecover()
{	// Add the register button action
	$('#osmRecoverBtn').click(function(){
		doRecover();
	});
	// Add the cancel button behavior
	$('#osmRecoverCancelBtn').click(function(){
		showLogin();
	});
}

/******************************************************************************
 * DISABLE BROWSER BEHAVIORS
 *****************************************************************************/

/**
 * Disables selection on the overlay panes. This is not functional, as it needs
 * to be enabled not for the document below, but for the panes in the overlay.
 * 
 * @return nothing
 * @todo - Work out all the problems with the document handling and IE specific
 * event.
 */
function disableSelection()
{	// Disable for IE
	if( document.getElementById('osmPg') != null ) document.getElementById('osmPg').onselectstart = function(){return false;};
	// Disable for Firefox
	if( document.getElementById('osmPg') != null ) document.getElementById('osmPg').style.MozUserSelect="none";
	// Disable for others
	$('#osmPg').onmousedown = function(){return false;}
}

function disableContextMenus()
{	// Disable for ad pane
	$("#osmPg").bind("contextmenu", function(e) {
	    return false;
	});
}
// enable use of enter key to submit forms
function checkEnter(e, frm)
{
	//e is event object passed from function invocation
	//formID is the id of the form to submit
	//var characterCode literal character code will be stored in this variable
	
	if(e && e.which)
	{
		e = e;
		characterCode = e.which;
	} else {
		e = event;
		characterCode = e.keyCode;
	}
	
	if(characterCode == 13)
	{
		if ( frm == "log" )
		{
			doLogin();
		} else {
			doRegister();
		}
		return false
	} else {
		return true
	}
}

/******************************************************************************
 * PAGE EVENT FUNCTIONS
 *****************************************************************************/

function initLegalLinks()
{	// Set up terms click behavior
	$('#osmTermsLink').click(function(){
		// Show the terms
		showTerms();
	});
	// Set up terms click behavior
	$('#osmPrivacyLink').click(function(){
		// Show the terms
		showPrivacy();
	});	
	// Set up go back behvaior
	$('#osmTermsBack').click(function(){
		showRegister();
	});
	$('#osmPrivacyBack').click(function(){
		showRegister();
	});
}

function positionInterface() 
{
    // Set the top position
    var voffset = Math.floor(Math.max((($(window).height()-$('#osmPg').height())/2),0));
    var hoffset = Math.floor(Math.max((($(window).width()-$('#osmPg').width())/2),42));
    
    $('#osmPg').css('top',voffset);
    $('#osmPg').css('left',hoffset);
    $('#osmPg').css('margin-left','0%');
    $('#osmPg').css('position','fixed');

}

function initAutoTab() {
	// Set up autotabbing for registration phone number
	$('#osmRegisterFormArea').autotab({ target: 'osmRegisterFormExchange', format: 'numeric' });
	$('#osmRegisterFormExchange').autotab({ target: 'osmRegisterFormExtension', format: 'numeric', previous: 'osmRegisterFormArea' });
	$('#osmRegisterFormExtension').autotab({ previous: 'osmRegisterFormExchange', format: 'numeric' });
	// Set up autotabbing for registration birthday
	$('#osmRegisterFormBmonth').autotab({ target: 'osmRegisterFormBday', format: 'numeric' });
	$('#osmRegisterFormBday').autotab({ target: 'osmRegisterFormByear', format: 'numeric', previous: 'osmRegisterFormBmonth' });
	$('#osmRegisterFormByear').autotab({ previous: 'osmRegisterFormBday', format: 'numeric' });
}

function initToolbar()
{	// Set the top of the window
	positionInterface();
	// Turn off selection
//	disableSelection();
	// Disable context menus
	disableContextMenus();
	// Set up the legal links before anything else for compliance reasons
	initLegalLinks();
	// Initialize login behaviors
	initLogin();
	// Initialize the registration behaviors
	initRegister();
	// Initialize the password recovery passwords
	initRecover();
	// Set close behavior
	$('#osmX').click(function(){
		hidePane();
	});
	// Set up autotabbing
	initAutoTab();
}

/**
 * The document.ready function executes when the page markup is finished 
 * loading. This can be used to set the initial position and visibility of 
 * elements contained therein. Also, tracking can be performed from here.
 * 
 * @return nothing
 */
$(document).ready(function(){
	initToolbar();
});

$(window).resize(function(){
	positionInterface();
});
