/*---------------------------------------------------*/
/*			Pluck JS			      */
/*	Created 1.09 by Rich Rudzinski		      */
/*---------------------------------------------------*/

/* BEGIN: Pluck Functions */

/**
 * Load the login form from /Static/login_pluck.html
 * in to the Pluck Header Bar (#contentPluckBar).
 * Then animate the login in.
 * @returns {boolean}
 * @author Richard Rudzinski
 */
function login() {
	$.ajax({
		type:'GET',
		url:'/Static/login_pluck.html',
		data:'timestamp='+_now(),
		success: function(data){
			$('#contentPluckBar2').hide();
			$('#contentPluckBar').replaceWith(data);
			$('#loginForm').animate({opacity: 'show'}, 'slow');
		}
	});
	return false;
}

/**
 * Handle login via an "unskinned" AJAX call - so this can be called from wherever we want, firing off whatever callbacks we want.
 * @returns {void}
 * @param {hash} settings Configuration options.
 * @param {string} settings.username The username we wish to try logging in with.
 * @param {string} settings.password The password we wish to try logging in with.
 * @param {function} settings.success Callback for when we have a successful log in.
 * @param {function} settings.failure Callback for when we fail to log in.
 * @author Nick Davison
 */
function unskinnedAJAXLogin(settings) {
	settings=jQuery.extend({
		username: "",
		password: "",
		success: function() {
		},
		failure: function() {
		}
	}, settings);
	
	var dataStr = 'username=' + settings.username + '&password=' + settings.password;
	
	// Send the login info to /Handlers/Login.aspx
	$.ajax({
		type: 'GET',
		url: '/Handlers/Login.aspx',
		data: dataStr,
		dataType: 'json',
		success: function(data) { // If AHAX was successful
			if(data.processed == false) { // If they were unable to login, call the failure callback
				settings.failure();
			} else { // If they did login, update the system and then call the success callback
				// Store the response data in the cookie
				writeCookie(data);
				
				// Update the pluck bar
				loggedIn();
				
				// Fire the success callback.
				settings.success();
			}
		},
		error: function() { // If there is an error, send the failure callback.
			settings.failure();
		}
	});
}

/**
 * Provides in place (static) login functionality.
 * <p>Get the username and password from the login form and submit them to /Handlers/Login.aspx.</p>
 * <p>If the call was successful:<br/>
 * If the login wasn't recognized, display an error message.<br />
 * If the login was recognized, store the response in a cookie then go to either
 * the callback (?url=) if there is one or http://soundersfc.com/ is there is not.</p>
 * <p>If the call failed, notify the user by displaying #pluckFormError</p>
 * @returns {void}
 * @see writeCookie (calls)
 * @see Url.decode (calls)
 * @see loginStatic (very similar)
 * @author Richard Rudzinski
 */
function loginStatic() {
	var callback =  window.location.search.replace('?url=', '');
	callback = Url.decode(callback);
	var user = $('#user_pluck').val(); // Get the username form field value
	var pass = $('#pass_pluck').val(); // Get the password form field value
	var dataStr = 'username=' + user + '&password=' + pass; // Build it in to a data string.
	
	// Send the login info to /Handlers/Login.aspx
	$.ajax({
		type: 'GET',
		url: '/Handlers/Login.aspx',
		data: dataStr,
		dataType: 'json',
		success: function(data) { // If successful
			if(data.processed == false) { // If they were unable to login, inform them.
				$('#user_pluck').next("span").attr("class","errorIcon");
				$('#pass_pluck').next("span").attr("class","errorIcon");
				alert('Your user name or password are incorrect. Please try again.');
				return false;
			} else { // If they did login, 
				// Add the checkIcon class to the following spans for #user_pluck and #pass_pluck
				var userSpan = $('#user_pluck').next("span");
				var passSpan = $('#pass_pluck').next("span");
				$(userSpan).attr("class","checkIcon");
				$(passSpan).attr("class","checkIcon");
				// Store the response data in the cookie
				writeCookie(data);
				// If a callback was specified, go to it. Otherwise, go to the homepage.
				if(callback) window.location = callback;
				else window.location = 'http://soundersfc.com/';
			}
		},
		error: function() { // If there is an error, display the pre build Forgot your password? error area (#pluckFormError)
			$('#pluckFormError').css('display', 'block');
			return false;
		}
	});
	return false;
}
/**
 * Remove cookie.
 * <p>If the "at" cookie is set, erase it. 
 * Load the /Static/loggedout_pluck.html logged out bar.
 * Write it in to #wrapperPluckBar and then slowly display it.</p>
 * @returns {void}
 * @see readCookie (calls)
 * @see _now (calls)
 * @see eraseCookie (calls)
 * @see logoutStatic (almost identical)
 * @author Richard Rudzinski
 */
function logout() {
	if(readCookie("at") != undefined) eraseCookie(true);
	$.ajax({
		type:'GET',
		url:'/Static/loggedout_pluck.html',
		data:'timestamp='+_now(),
		success: function(data) {
			$('#wrapperPluckBar').css('display', 'none');
			$('#wrapperPluckBar').html(data);
			$('#wrapperPluckBar').animate({opacity: 'show'}, 'slow');	
		}
	});
	return false;
}
/**
 * Matches the functionality of logout()
 * but additionally redirects the user to http://soundersfc.com/ when complete.
 * @see logout (almost identical)
 * @see readCookie (calls)
 * @see eraseCookie (calls)
 * @see _now (calls)
 * @author Richard Rudzinski
 */
function logoutStatic() {
	if(readCookie("at") != undefined) eraseCookie(false);
	$.ajax({
		type:'GET',
		url:'/Static/loggedout_pluck.html',
		data:'timestamp='+_now(),
		success: function(data) {
			$('#wrapperPluckBar').css('display', 'none');
			$('#wrapperPluckBar').html(data);
			$('#wrapperPluckBar').animate({opacity: 'show'}, 'slow');
			window.location = 'http://soundersfc.com/';
		}
	});
	return false;
}
/**
 * Close error popover (#pluckErrorCont).
 * @returns {void}
 * @author Richard Rudzinski
 */
function closeError() {
	$('#pluckErrorCont').css('display', 'none');
}
/**
 * Authenticate user for Pluck.
 * Very similar to loginStatic.
 * <p>
 * Gets the username and password from #user_pluck and #pass_pluck.
 * Sends them to /Handlers/Login.aspx.
 * If there was a failure, display the prepopulated #pluckErrorCont
 * If it was successful, store the data in a cookie then call a page reload.
 * </p>
 * @returns {void}
 * @see _now (calls)
 * @see writeCookie (calls)
 * @see loginStatic (very similar)
 * @author Richard Rudzinski
 */
function authenticate() {
	//$('.error', '#contentPluckBar').remove();
	var user = $('#user_pluck').val();
	var pass = $('#pass_pluck').val();
	var dataStr = 'username=' + user + '&password=' + pass;
	$.ajax({
		type: 'GET',
		url: '/Handlers/Login.aspx',
		data: dataStr + '&timestamp='+_now(),
		dataType: 'json',
		success: function(data) {
			if(data.processed == false) { 
				$('#pluckErrorCont').css('display', 'block');
			} else {
				writeCookie(data);
				window.location.reload();
			}
		}
	});
	return false;
}
/**
 * Calls /Static/loggedin_pluck.html 
 * and writes its content in to #wrapperPluckBar,
 * animating its visibility in.
 * @returns {void}
 * @author Richard Rudzinski
 */
function loggedIn() {
	$.ajax({
		type:'GET',
		url:'/Static/loggedin_pluck.html',
		success: function(data) {
			$('#wrapperPluckBar').css('display', 'none');
			$('#wrapperPluckBar').html(data);
			$('#wrapperPluckBar').animate({opacity: 'show'}, 'slow');
		}
	});				
}
/**
 * Return current time 
 * @returns {string}
 * @see login (called by)
 * @see logout (called by)
 * @see logoutStatic (called by)
 * @see authenticate (called by)
 * @author Richard Rudzinski
 */
function _now(){
	return +new Date;
}
/**
 * Parse and create cookies from login data.
 * Stores userId (data.userId), userName (data.userName), at (data.cookie).
 * The cookies are then set to store for 14 days.
 * @returns {void}
 * @param {object} data AJAX response from the login form.
 * @see loginStatic (called by)
 * @see authenticate (called by)
 * @author Richard Rudzinski
 */
function writeCookie(data) {
	dataArray = ['userId=' + data.userId, 'userName=' + data.userName, 'at=' + data.cookie];
	var expiry = new Date();
	expiry.setDate(expiry.getDate() + 14);
	for(i=0; i<dataArray.length; i++) {
		var temp = dataArray[i].split(' : ');
		document.cookie = dataArray[i] + '; expires=' + expiry.toGMTString() + '; path=/; domain='+globalDomain;
	}
}
/**
 * Look for and return a cookie. Return false if it wasn't found.
 * @returns {string}
 * @param {string} name The name of the cookie to look for.
 * @see logout (called by)
 * @see logoutStatic (called by)
 * @see parseUser (called by)
 * @author Richard Rudzinski
 */
function readCookie(name) {
	var name = name + '=';
	var cookieArray = document.cookie.split(';')
	for(i=0; i<cookieArray.length; i++) {
		if(cookieArray[i].indexOf(name) != -1) {
			if(cookieArray[i] == undefined) return false;
			else return cookieArray[i].replace(name, '');
		}
	}
}
/**
 * Erase all pluck cookies
 * (userId, userName, at).
 * Then, if refresh is true, reload the page.
 * @returns {void}
 * @param {boolean} refresh True if you wish the page to reload afterwards.
 * @see logout (called by)
 * @see logoutStatic (called by)
 * @author Richard Rudzinski
 */
function eraseCookie(refresh) {
	var expire = new Date();
	expire.setDate(expire.getDate() - 1);
	document.cookie = 'userId=""; expires=' + expire.toGMTString() + '; path=/; domain=' + globalDomain;
	document.cookie = 'userName=""; expires=' + expire.toGMTString() + '; path=/; domain=' + globalDomain;
	document.cookie = 'at=""; expires=' + expire.toGMTString() + '; path=/; domain=' + globalDomain;
	if(refresh) window.location.reload();
}
/**
 * Parses User ID from cookie.
 * <p>
 * Will first attempt to look in window.location for userid.
 * If it can't find it there, it will look in the cookie.
 * If it can't find it there, it will return '' and pop up an alert asking the user to log in.
 * </p>
 * @returns {string}
 * @see readCookie (calls)
 * @author Richard Rudzinski
 */
function parseUser() {
	var query = window.location.search;
	if(!query || query.indexOf('userid') == -1) { // If there's no user id in the url
		if(readCookie("at") != undefined) { // If the 'at' cookie is set
			var user = readCookie("at");
			user = user.split('&')[0];
			user = user.replace(/(u=)|(\s)/g, '');
			window.location.search = 'userid=' +user + '&plckPersonaPage=PersonaHome';
		} else { // Ask the user to log in
			alert('Please log in to view your profile');
			user = '';
		}
	} else {// 
		var query = window.location.search;
		var user = query.split(/userid=/)[1]; // Get everything after the userid=
		if(user.match(/&|;|\,/)) user = user.split(/&|;|\,/)[0];
	}
	return user;
}
/**
 * Checks to see if user is a season ticket holder.
 * Does so by checking /Handlers/SeasonTickerHolder.aspx for processed == true.
 * If they are it appends a class of "ticketHolder" to the #personas container 
 * @returns {void}
 * @param {string} user The userId to check for.
 * @author Richard Rudzinski
 */
function seasonTicketHolder(user) {
	var container = $('#personas');
	var ticketHolder;
	$.ajax({
		type: 'GET',
		url: '/Handlers/SeasonTickerHolder.aspx',
		data: 'userId=' + user,
		dataType: 'json',
		success: function(data) {
			if(data.processed == true) { 
				container.addClass('ticketHolder');
			} 
		}
	}); 
}
/**
 * @namespace URL encode/decode 
 */
var Url = {
	/**
	 * Public method for url encoding
	 * @returns {string}
	 * @param {string} string The plain string you wish to UTF8 encode and then url escape.
	 * @author Richard Rudzinski
	 */
	encode : function (string) {
		return escape(this._utf8_encode(string));
	},
	/**
	 * public method for url decoding
	 * @returns {string}
	 * @param {string} string UTF8, URL escaped string you wish to decode.
	 * @see loginStatic (called by)
	 * @author Richard Rudzinski
	 */
	decode : function (string) {
		return this._utf8_decode(unescape(string));
	},
	/**
	 * Private method for UTF-8 encoding
	 * @returns {string}
	 * @param {string} string String of text you wish to UTF8 encode
	 * @author Richard Rudzinski
	 */
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
		for (var n = 0; n < string.length; n++) {
			var c = string.charCodeAt(n);
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
		}
		return utftext;
	},
	/**
	 * Private method for UTF-8 decoding.
	 * @returns {string}
	 * @param {string} utftext UTF8 encoded text you want to decode.
	 * @author Richard Rudzinski
	 */
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
		while ( i < utftext.length ) {
			c = utftext.charCodeAt(i);
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
		}
		return string;
	}
}
/* END: Pluck Functions */
