/*---------------------------------------------------*/
/*			Pluck JS			      */
/*	Created 1.09 by Rich Rudzinski		      */
/*---------------------------------------------------*/

/* BEGIN: Pluck Functions */


/**
 * 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
				//dataArray = ['userId=' + data.userId, 'userName=' + data.userName, 'at=' + data.cookie];
				// Store the response data in the cookie
				writeCookie("userId",data.userId);
				writeCookie("userName",data.userName);
				writeCookie("at",data.cookie);
				
				// Update the pluck bar
				loggedIn();
				
				// Fire the success callback.
				settings.success();
			}
		},
		error: function() { // If there is an error, send the failure callback.
			settings.failure();
		}
	});
}

/**
 * Handle login via a "flash" call - so this can be called from flash apps.
 * @returns {void}
 * @param {string} user The username we wish to try logging in with.
 * @param {string} pass The password we wish to try logging in with.
 * @author David Pett
 */
function loginFlash(user, pass) {
	
	var dataStr = 'username=' + user + '&password=' + pass;
	
	var logUrl="http://www.ussoccer.com/Handlers/Login.aspx";
	if (document.location.toString().indexOf("digitaria")!=-1) {
		logUrl="http://ussoccer.digitaria.com/Handlers/Login.aspx";
	}
	// Send the login info to /Handlers/Login.aspx
	$.ajax({
		type: 'GET',
		url: logUrl,
		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
				
			} else { // If they did login, update the system and then call the success callback
				//dataArray = ['userId=' + data.userId, 'userName=' + data.userName, 'at=' + data.cookie];
				// Store the response data in the cookie
				writeCookie("userId",data.userId);
				writeCookie("userName",data.userName);
				writeCookie("at",data.cookie);
				
				// Update the pluck bar
				loggedIn();
			}
		},
		error: function() { // If there is an error, send the failure callback.
		}
	});
}

/**
 * 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 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('?returnURL=', '');
	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({
		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
				//dataArray = ['userId=' + data.userId, 'userName=' + data.userName, 'at=' + data.cookie];
				writeCookie("userId",data.userId);
				writeCookie("userName",data.userName);
				writeCookie("at",data.cookie);
				// If a callback was specified, go to it. Otherwise, go to the homepage.
				if(callback) window.location = callback;
				else window.location = "/";
			}
		},
		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.</p>
 * @returns {void}
 * @see readCookie (calls)
 * @see eraseCookie (calls)
 * @see logoutStatic (almost identical)
 * @author Richard Rudzinski
 */
function logout() {
	if(readCookie("at") != undefined) eraseCookie(true);
	return false;
}
/**
 * Matches the functionality of logout()
 * but additionally redirects the user to home when complete.
 * @see logout (almost identical)
 * @see readCookie (calls)
 * @see eraseCookie (calls)
 * @author Richard Rudzinski
 */
function logoutStatic() {
	if(readCookie("at") != undefined) eraseCookie(false);
	window.location = 'http://'+document.domain+'/';
	return false;
}
/**
 * Matches the functionality of logout()
 * but additionally redirects the user to home when complete.
 * @see logout (almost identical)
 * @see readCookie (calls)
 * @see eraseCookie (calls)
 * @author Richard Rudzinski
 */
function logoutFlash() {
	if(readCookie("at") != undefined) eraseCookie(false);
	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();
	if(user == "USERNAME" || user == "" || pass == "PASSWORD" || pass == "") {
		$('#pluckErrorCont').css('display', 'block');
		return false;
	}
		
	var dataStr = 'username=' + user + '&password=' + pass;
	$.ajax({
		type: 'GET',
		url: '/Handlers/Login.aspx',
		data: dataStr,
		cache: false,
		dataType: 'json',
		success: function(data) {
			if(data.processed == false) { 
				$('#pluckErrorCont').css('display', 'block');
			} else {
				//dataArray = ['userId=' + data.userId, 'userName=' + data.userName, 'at=' + data.cookie];
				writeCookie("userId",data.userId);
				writeCookie("userName",data.userName);
				writeCookie("at",data.cookie);
				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() {
	//$("#footernav_login").css("background-position", "-541px -30px");
	$("#footernav_login").parent("li").replaceWith("<li class='first'><a href='/Social/Profile.aspx' id='footernav_myprofile'>My Profile</a></li><li><a href='#' onclick='logout()' id='footernav_logout'>Logout</a></li>");
	$("#footernav_login_box").remove();
}

/**
 * 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(doRefresh) {
	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;
	writeCookie("userId","",expire.toGMTString());
	writeCookie("userName","",expire.toGMTString());
	writeCookie("at","",expire.toGMTString());
	if(doRefresh) window.location.reload();
}
/*
 * Duplicated from jCore as it has to be available when the rest of Pluck runs, before jcore.js is ever included.
*/
function pluck_readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0; i < ca.length; i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0)
			return c.substring(nameEQ.length,c.length);
	}
	return false;
}
/**
 * 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>
 * <p>NOTE: Updated from userid to UID per Hunter Sinclair from SiteLife on 8/7/9.</p>
 * @returns {string}
 * @see readCookie (calls)
 * @author Richard Rudzinski
 */
function parseUser() {
	var query = window.location.search;
	var isStaging=false;
	if (document.location.toString().indexOf("http://local.ussoccer.pluck.digitaria.com:9004/")==0) {
		isStaging=true;
	}
	if(!query || query.toLowerCase().indexOf('uid') == -1) { // If there's no user id in the url
		if(pluck_readCookie("at") != false) { // If the 'at' cookie is set
			var user = pluck_readCookie("at");
			user = user.split('&')[0];
			user = user.replace(/(u=)|(\s)/g, '');
			window.location.search = 'UID=' +user + '&plckPersonaPage=PersonaHome';
		} else if ((isStaging) && (pluck_readCookie("hd") != false)) { // If the 'hd' cookie is set on staging
			var user = pluck_readCookie("hd");
			user = user.split('|')[0];
			window.location.search = 'UID=' +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.toLowerCase();
		var user = query.split(/uid=/)[1]; // Get everything after the uid=
		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;
	}
}

/**
 * Forgot password validation.
 * <p>
 * Check none of the fields are blank - adding error icons if they are.
 * Check the display name is valid via AJAX calling /handlers/forgotpassword.aspx
 * If everything's good, notify the user that the password's been mailed to their account and redirect them to the homepage.
 * Otherwise, prompt them to correct the form.
 * </p>
 * @returns {void}
 * @param {element} form The form we're performing this check on.
 * @author Richard Rudzinski
 */
function validateUser(form) {
	var el = document.getElementById("displayName");
	passForm = 0;
	var userCheck = true;
	var fail = false;
	//showCheckLink(el);
	$("input:text, input:password", form).each(function() {
		if(this.value == "") {
			$(this).next("span").attr("class","errorIcon");
			passForm++;
		} else {
			if(this.id=="displayName") {
				$.ajax({
					type: "GET",url: "/handlers/forgotpassword.aspx",dataType:"json",cache:false,data:"username="+el.value,async:false,
					error:function(err) {
						passForm++;
						fail = true;
						$(el).next("span").attr("class","errorIcon");
					},
					success:function(result) {
						if(result.processed) {
							var errorSpan = $(el).next("span");
							$(errorSpan).attr("class","checkIcon");							
						} else {
							passForm++;	
							userCheck = false;
							$(el).next("span").attr("class","errorIcon");
						}
					}
				});
			} 
		}
	});
	if(passForm > 0) {
		if(fail) {
			alert('An unknown error has occurred. Please try again later.');
		} else if(!userCheck) {
			alert('That username is not registered with our system. Please check for spelling errors.');
		} else {
			alert('Please fill in all fields.');
		}
	} else {
		alert('An email has been sent to the email account provided at registration. Please follow the instructions in the email to reset your password.');
		window.location = 'http://www.ussoccer.com/';
	}
	passForm = 0;
	return false;
}
/**
 * Reset Password.
 * <p>
 * Check validity of the password fields, adding error icons if there's an issue.
 * If everything looks good, attempt to send it to /handlers/resetpassword.aspx
 * If it's successful, notify the user and send them to the homepage.
 * If it's not successful, notify the user.
 * </p>
 * @returns {void}
 * @param {element} form The form we're performing this check on.
 * @author Richard Rudzinski
 */
function resetPassword(form) {
	var key = window.location.search.replace(/[?]/, '');
	var password = $('#password');
	var password2 = $('#password2');
	var passwordCheck = true;
	var fail = false;
	passForm = 0;
	//showCheckLink(el);
	$("input:text, input:password", form).each(function() {
		if(this.value == "") {
			$(this).next("span").attr("class","errorIcon");
			passForm++;
		} else if(this.id=='password' && $('#password').attr('value') != $('#password2').attr('value')) {
			password.next("span").attr("class","errorIcon");
			password2.next("span").attr("class","errorIcon");
			passForm++;
			passwordCheck = false;
		} else if(this.id=="password2") {	
			$.ajax({
				type: "GET",url: "/handlers/resetpassword.aspx",data:key+'&password='+password.attr('value'),async:false,
				error:function(err) {
					passForm++;
					fail = true;
					password.next("span").attr("class","errorIcon");
					password2.next("span").attr("class","errorIcon");	
				},
				success:function(result) {
					password.next('span').attr("class","checkIcon");
					password2.next('span').attr("class","checkIcon");			
				}
			});
		}
	});
	if(passForm > 0) {
		if(!passwordCheck) {
			alert("Please make sure both passwords match.");
		} else if(fail) {
			alert('An unknown error has occurred. Please try again later.');
		} else {
			alert("Please fill in all fields.");
		}
		return false;
	} else {
		alert('Your password has been reset.');
		window.location = 'http://www.ussoccer.com/';
	}
	passForm = 0;
}

/* END: Pluck Functions */
