function getSignInAndSignUpStatus(result, node_name) {
	if(result) {
		var root;
		for(var i = 0; i < result.childNodes.length; ++i) {
			root = result.childNodes[i];
			
			if(root.nodeType == 1) {
				if(root && root.childNodes) {
					for(var i = 0; i < root.childNodes.length; ++i) {
						var sub_node = root.childNodes[i];
				
						if(sub_node.nodeName == node_name) {
							return sub_node.firstChild ? sub_node.firstChild.data : "";
						}
					}
				}
			}
		}
	}
	return -1;
}

function showRegistrationStatus(result) {
	var status = getSignInAndSignUpStatus(result, "status");
	
	var redirect_url = "";
	if(partner_id == 3) {
		redirect_url = "/events/";
	}
	else {
		var url = document.location;
		if(url) {
			url = url.toString();
			var pos = url.indexOf("#");
			if(pos > 0) {
				url = url.substring(0, pos);
			}
			
			if(partner_id == 19) {
				pos = url.indexOf("?");
				url += (pos > 0 ? "&" : "?") + "callconversion=1";
			}
			
			if(partner_id == 43) {
				pos = url.indexOf("?");
				url += (pos > 0 ? "&" : "?") + "msconversion=1";
			}
		}
		var stampDate = new Date();
		var stampVal = stampDate.getTime();
		redirect_url = url + "?time=" + stampVal;
		// if (window.location.host.toLowerCase().indexOf('staging') > 0)
		// alert('URL will be ' + redirect_url);
	}
	
	if(status == 1) {
		window.location.href = redirect_url;
		// document.location = redirect_url;
	}
	else if(status == -1) {// sf
		window.location.href = redirect_url;
		// window.setTimeout("document.location='"+redirect_url+"';", 3000);
		// document.location = redirect_url;
	}
	else {
		var error = getSignInAndSignUpStatus(result, "error");
		
		var message = false;
		switch(error) {
			case "UNDER_AGE": 
				message = "You must be "+(ISUK ? 18 : 21)+" or older to join the Patron Social Club."; 
				underAgeRedirect(true);
				break;
			case "INVALID_AGE_DATE": 
				message = "You must select a valid birth date."; 
				break;
			case "ALREADY_EXISTS": 
				message = "Email already exists! Please try another email."; 
				break;
			case "EMAIL_AND_SCREEN_NAME_ARE_EMPTY": 
				message = "You must enter your Email."; 
				break;
			case "WRONG_EMAIL_FORMAT": 
				message = "You must enter a correct email format."; 
				break;
			case "GENDER_EMPTY": 
				message = "You must select your gender."; 
				break;
			case "ZIP_INVALID": 
				message = "If you are in the United States, you must enter a valid 5-digit ZIP code."; 
				break;
			case "COUNTRY_INVALID": 
				message = "Please select a country."; 
				break;
			case "EMAIL_ALREADY_EXISTS": 
				message = "Email already exists! Please try another email."; 
				break;
			case "SCREENNAME_ALREADY_EXISTS": 
				message = "Username already exists! Please try another username."; 
				break;
			case "INVALID_REGISTRATION_CASE":
				message = "Invalid selection: Please choose to create a new account or link to an existing account"; 
				break;
			default: 
				message = "Looks like your registration was unsuccessful! "; 
		}
		
		document.getElementById('sign-message').innerHTML = message;
		$('#loaderimg').css('display','none');
		
		if(error == -1) {// segmentation fault from the servers
			window.location.href = redirect_url;
			// window.setTimeout("document.location='"+redirect_url+"';", 3000);
		}
		
		var registration_submit_button = document.getElementById('registration_submit_button');
		if(registration_submit_button) {
			registration_submit_button.disabled = false;
		}
	}
}

function showLoginStatus(result) {
	//alert(result);
	var status = getSignInAndSignUpStatus(result, "status");
	var promkey = getSignInAndSignUpStatus(result, "promkey");
	
	var redirect_url = "";
	
	if (document.location.toString().indexOf('hfga7afc') != -1) {
		redirect_url = 'http://' + document.location.host + '/promotions/accept/hfga7afc/' + promkey;
	}
	else if(partner_id == 3) {
		redirect_url = "/events/";
	}
	else {
		var url = document.location;
		if(url) {
			url = url.toString();
			var pos = url.indexOf("#");
			if(pos > 0) {
				url = url.substring(0, pos);
			}
		}
		var stampDate = new Date();
		var stampVal = stampDate.getTime();
		redirect_url = url + "?time=" + stampVal;
		// if (window.location.host.toLowerCase().indexOf('staging') > 0)
		// alert('URL will be ' + redirect_url);
	}
	
	if(status == 1) {
		window.location.href = redirect_url;
		// document.location = redirect_url;
	}
	else if(status == -1) {// sf typically
		window.location.href = redirect_url;
		// window.setTimeout ( 'document.location = redirect_url', 3200 );
	} else {
		var error = getSignInAndSignUpStatus(result, "error");
		var fbemail = getSignInAndSignUpStatus(result, "fbemail");
		var fbzip = getSignInAndSignUpStatus(result, "fbzip");
		var fbsex = getSignInAndSignUpStatus(result, "fbsex");
		var fts = "ZDY"; // field flags to guide display
		/* P: display password field when creating a new account
		 * Z: display ZIP field when creating a new account 
		 *  C: display radio buttons for new account vs. link w/account
		 *  N: set default radio button selection to be create new account 
		*/
		
		
		// preset ZIP if we have it
		if (typeof fbzip == 'string')
			if (fbzip.length > 0)
				document.getElementById('fbregistration_provided_zip').value = fbzip;
			
		// preset gender if we have it
		if (typeof fbsex == 'string')
			if (fbsex.length == 1) {
				document.getElementById('fbregistration_gender').selectedIndex = fbsex == 'm' ? 1 : 0;
			}
			else {
				fts = fts + 'G';
			}
		
		
		var message = false;
		var regularLogin = false;
		switch(error) {
			case "INVALID_PASSWORD": 
				message = "Username/password combination not found";
				regularLogin = true; 
				break;
			case "USER_DOES_NOT_EXIST": 
				message = "User does not exist yet!";
				regularLogin = true; 
				break;
			case "NO_FB_USER": 
				message = "Facebook User Not Linked to any PSC account"; 
				break;
			case "FB_NO_EMAIL": 
				// example - "Facebook User Not Linked to any PSC account - But
				// we couldn't get an e-mail address from the facebook session
				// :( ";
				message = "We couldn't get your email address from Facebook, which is why we're asking you for it here.";
				FB_userinfo(fts + 'NCE', '');
				break;
			case "FB_NO_LINKED_USER": 
				// example - "Facebook User Not Linked to any PSC account - and
				// the facebook-linked e-mail is not tied to any PSC account";
				message = "If you happen to have an existing PSC account you can link your Facebook account with it here. Otherwise you can just  a new account.";
				FB_userinfo(fts + 'NC', fbemail);
				break;
			case "FB_LINKED_EMAIL": 
				// example - "Facebook User Not Linked to any PSC account - and
				// the facebook-linked e-mail is already associated with a PSC
				// account";
				message = "Looks like the email address you use with Facebook is already in our system!<br/>You can either link your Facebook account with your existing PSC account or<br/>create a new PSC account with a different email address.";
				FB_userinfo(fts + 'CEP', fbemail);
				break;
			default: 
				message = ""; 
		}
		if (regularLogin){
			document.getElementById('sign-message').innerHTML = message;
			$('#loaderimg').css('display','none');
		} else {
			document.getElementById('fb-sign-message').innerHTML = message;
			$('#loaderimg').css('display','none');
		}
		
		var login_submit_button = document.getElementById('login_submit_button');
		if(login_submit_button) {
			login_submit_button.disabled = false;
		}
	}
}

// BAD PRACTICE: TEMPORARY LIBRARY
/**
 * Function : dump() Arguments: The data - array,hash(associative array),object
 * The level - OPTIONAL Returns : The textual representation of the array. This
 * function was inspired by the print_r function of PHP. This will accept some
 * data as the argument and return a text that will be a more readable version
 * of the array/hash/object that is given.
 */
function dump(arr,level) {
var dumped_text = "";
if(!level) level = 0;

// The padding given at the beginning of the line.
var level_padding = "";
for(var j=0;j<level+1;j++) level_padding += "    ";

if(typeof(arr) == 'object') { // Array/Hashes/Objects
for(var item in arr) {
var value = arr[item];

if(typeof(value) == 'object') { // If it is an array,
dumped_text += level_padding + "'" + item + "' ...\n";
dumped_text += dump(value,level+1);
} else {
dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
}
}
} else { // Stings/Chars/Numbers etc.
dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
} 
// BAD PRACTICE: TEMPORARY LIBRARY TODO: REMOVE!

function breakText(inText) {
	if (window.location.host.toLowerCase().indexOf('staging') > 0) alert(inText);
}

function FB_checkAndShow_Username() {
	FB.getLoginStatus(function(response) {
					 console.log(">FB_Connect getLoginStatus response: " +
					 dump(response));
					if (response.session) {
						 console.log(">FB_Connect user logged in - worked.: " + response.status);
		               try {
						if (!MyLib) console.log(">FB_Connect MyLib does not exist!");
						else if (!MyLib.FormHandler) console.log(">FB_Connect MyLib.FormHandler does not exist!");
						else if (!document.forms['FBDummyLogin']) console.log(">FB_Connect FBDummyLogin form does not exist!");
						MyLib.FormHandler.checkAndSubmitForm(document.forms['FBDummyLogin'], {'callback_func' : showLoginStatus, 'ajax_result_type' : 1});
		               }
		               catch (e) {
		            	    console.log(">FB_Connect exception / error occurred attempting to submit dummy form: " + dump(e));
		               }
	            }
				else {
					// console.log(">FB_Connect user clicked cancel: " +
					// dump(response) + "," + dump(response.perms) + ", " +
					// dump(response.status));
	                // user clicked cancel, so do nothing i guess.
	            }
	        });
}


function FB_userinfo(fbco, fbem){
	document.getElementById('signin').style.display = 'none';
	document.getElementById('fb_userinfo').style.display = 'block';
	document.getElementById('FB_fbco').value = fbco;
	document.getElementById('FB_fbem').value = fbem;
	document.getElementById('fbregistration_provided_email').value = fbem;
	// show/hide choice
	FB_prettyform(fbco);
}

function FB_prettyform(fbco) {
	if (fbco.indexOf('C') == -1) {// hide radio buttons
		document.getElementById('FB_user_link_choice').style.display = 'none';
	}
	else {
		document.getElementById('FB_user_link_choice').style.display = 'block';
	}
	
	// If Link Account selected, set attributess to validate only E-mail and
	// password
	if (document.getElementById('fbregistration_type_choice1').checked) {// begin

		if (fbco.indexOf('E') == -1) {// hide email field
			document.getElementById('FB_email_block').style.display = 'none';
			document.getElementById('FB_fbem').setAttribute('checkallownull', 'true');
		}
		else {
			document.getElementById('FB_email_block').style.display = 'block';
			document.getElementById('FB_fbem').setAttribute('checkallownull', 'false');
		}

		if (fbco.indexOf('P') == -1) {// hide password field
			document.getElementById('FB_password_block').style.display = 'none';
			document.getElementById('fbregistration_provided_password').setAttribute('checkallownull', 'true');
		}
		else {
			document.getElementById('FB_password_block').style.display = 'block';
			document.getElementById('fbregistration_provided_password').setAttribute('checkallownull', 'false');
		}

		// hide otherwise-required fields
		// TODO only hide ZIP and country if we get them from FB
		if (fbco.indexOf('Z') != -1) {
			document.getElementById('FBzipShow').style.display = 'block';
			document.getElementById('fbregistration_provided_zip').setAttribute('checkallownull', 'false');			
		}
		if (fbco.indexOf('Y') != -1) document.getElementById('FBcountryShow').style.display = 'block';
		document.getElementById('FB_optin_block').style.display = 'none';
	}// end user chose create new PSC account
	else if (document.getElementById('fbregistration_type_choice2').checked) {// begin

		//show e-mail field (required for all "linking to existing account" cases)
		document.getElementById('FB_email_block').style.display = 'block';
		document.getElementById('FB_fbem').setAttribute('checkallownull', 'false');
		
		
		//show password field (required for all "linking to existing account" cases)
		document.getElementById('fbregistration_provided_password').setAttribute('checkallownull', 'false');
		document.getElementById('FB_password_block').style.display = 'block';
		
		// hide otherwise-required fields
		document.getElementById('fbregistration_provided_zip').setAttribute('checkallownull', 'true');
		document.getElementById('fbregistration_country').setAttribute('checkallownull', 'true');
		document.getElementById('FBzipShow').style.display = 'none';
		document.getElementById('FBcountryShow').style.display = 'none';
		document.getElementById('FB_optin_block').style.display = 'none';
	}// end user chose link existing PSC account
	else if (fbco.indexOf('N') == -1) {//nothing's checked; for default, choose link to existing PSC accont
		document.getElementById('fbregistration_type_choice2').checked = 'true';
	}
	 else {//nothing's checked; for default, choose new account
		 document.getElementById('fbregistration_type_choice1').checked =
	 'true';
	 }
}

function checkDOBAndShowRegistration() {
	var dob_year = document.getElementById('dobYear');
	var dob_month = document.getElementById('dobMonth');
	var dob_day = document.getElementById('dobDay');
	
	var dob = dob_year.options[dob_year.selectedIndex].value + "" + dob_month.options[dob_month.selectedIndex].value + "" + dob_day.options[dob_day.selectedIndex].value;
	
	var current_date = new Date();
	var current_year = current_date.getFullYear();
	var current_month = current_date.getMonth() + 1;
	var current_day = current_date.getDate();
	
	if(current_month < 10) current_month = "0" + current_month;
	if(current_day < 10) current_day = "0" + current_day;
	
	var current_time = current_year + "" + current_month + "" + current_day;
	
	var minimum_age = (ISUK ? 18 : getMinimumAgeByCountry(document.getElementById('registration_country0').options[document.getElementById('registration_country0').selectedIndex].value)) * 10000;
	var is_dob_valid = parseInt(current_time) - parseInt(dob) >= minimum_age ? true : false;
	
	if(is_dob_valid) {
		//document.getElementById('signin').style.display = 'none';
		//document.getElementById('signup').style.display = 'block';
		$('#signin').css('display','none');
		$('#signup').css('display','block');
		document.getElementById('registration_dob_year').selectedIndex = dob_year.selectedIndex;
		document.getElementById('registration_dob_month').selectedIndex = dob_month.selectedIndex;
		document.getElementById('registration_dob_day').selectedIndex = dob_day.selectedIndex;
		document.getElementById('registration_country').selectedIndex = document.getElementById('registration_country0').selectedIndex;
	}
	else {
		document.getElementById('sign-message').innerHTML = "You must be "+(ISUK ? 18 : 21)+" or older to join the Patron Social Club.";
		underAgeRedirect(true);
	}
}

function getMinimumAgeByCountry(countryID) {
	var defaultAge = 21;
	var ageToCountry = new Array();
	ageToCountry[25] = ["IN","SE"];
	ageToCountry[20] = ["IS","JP","PY"];
	ageToCountry[19] = ["CA","NI","KR"];
	ageToCountry[18] = ["DZ","AR","AU","BS","BB","BY","BZ","BM","BO","BW","BR","BV","VG","BG","CM","CV","CF","CL","CN","CO","CG","CD","CR","HR","CZ","DK","DO","EC","EG","SV","ER","EE","ET","FI","FR","GT","GY","HU","ID","IE","IL","JM","KZ","KE","LV","LS","LT","MW","MU","MX","MD","MN","MZ","NA","NZ","NE","NG","PA","PG","PE","PH","RU","WS","SC","SG","SK","ZA","ES","MF","TH","TT","TR","TM","UG","UA","GB","UY","VU","VE","ZM","ZW"];
	ageToCountry[17] = ["CY"];
	ageToCountry[16] = ["AG","BE","GE","DE","GR","LU","MT","NO","PL","PT"];
	ageToCountry[0] = ["AL","AM","AZ","KM","GQ","FJ","GA","GH","GW","KG","MA","SB","SZ","TG","TO","VN"];
	
	
	if (typeof countryID != 'string') {
		return (defaultAge);
	}
	else if (!countryID.match(/^[A-Z][A-Z]$/i)) {
		return (defaultAge);
	}
	for (countryAge in ageToCountry) {
		for (cid in ageToCountry[countryAge]) {
			if (countryID.toUpperCase() == ageToCountry[countryAge][cid].toUpperCase()) return (countryAge);
		}
	}
	return (defaultAge);
}

function checkFBDOB() {
	var fbdob_year = document.getElementById('fbregistration_dob_year');
	var fbdob_month = document.getElementById('fbregistration_dob_month');
	var fbdob_day = document.getElementById('fbregistration_dob_day');
	
	var fbdob = fbdob_year.options[fbdob_year.selectedIndex].value + "" + fbdob_month.options[fbdob_month.selectedIndex].value + "" + fbdob_day.options[fbdob_day.selectedIndex].value;
	
	var current_date = new Date();
	var current_year = current_date.getFullYear();
	var current_month = current_date.getMonth() + 1;
	var current_day = current_date.getDate();
	
	if(current_month < 10) current_month = "0" + current_month;
	if(current_day < 10) current_day = "0" + current_day;
	
	var current_time = current_year + "" + current_month + "" + current_day;
	
	var minimum_age = (ISUK ? 18 : getMinimumAgeByCountry(document.getElementById('fbregistration_country').options[document.getElementById('fbregistration_country').selectedIndex].value)) * 10000;
	var is_dob_valid = (parseInt(current_time) - parseInt(fbdob)) >= minimum_age ? true : false;
	
	if(!is_dob_valid){
		document.getElementById('sign-message').innerHTML = "You must be "+(ISUK ? 18 : getMinimumAgeByCountry(document.getElementById('fbregistration_country').options[document.getElementById('fbregistration_country').selectedIndex].value))+" or older to join the Patr&oacute;n Social Club.";
		//underAgeRedirect(true);
		return false;
	}
	return true;
}
