// JavaScript Document
/*
Written By Ninad
Date 07 -07 -09
JS library for invite flow from social networks

function update_user_box() {
	var user_box = document.getElementById("fb-content-left");
	//			var user_box = document.getElementById("user");
	// add in some XFBML. note that we set useyou=false so it doesn't display "you"
	//			user_box.innerHTML = "<span>" + "<fb:profile-pic uid=loggedinuser facebook-logo=true></fb:profile-pic>" + "Welcome, <fb:name uid=loggedinuser useyou=false></fb:name>. You are signed in with your Facebook account." + "</span>";
	user_box.innerHTML = "<fb:profile-pic uid=loggedinuser facebook-logo=true></fb:profile-pic><span style='display:none'><fb:name uid=loggedinuser useyou=false></fb:name></span>";
	// because this is XFBML, we need to tell Facebook to re-process the document
	FB.XFBML.Host.parseDomTree();
}

function call_ajax(vars) {

	url = "ajax.php"
	var request = new XMLHttpRequest();
	request.open("POST", url, true);
	request.setRequestHeader("Content-Type",
			"application/x-www-form-urlencoded");

	request.onreadystatechange = function() {
		if (request.readyState == 4 && request.status == 200) {
			if (request.responseText) {
				alert('refreshing the page');
				refresh_page();
			}
		}
	};
	request.send(vars);
}

function 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 null;
}

function insertSocialRecord(uid, page, register) {
	var xmlreload = initxmlhttp();
	var url = "/ajax/insertSocialRecord/sn/facebook";
	if (document.getElementById('iuid'))
		url += "/iuid/" + document.getElementById('iuid').value;
	xmlreload.open("GET", url, true);
	xmlreload.onreadystatechange = function() {
		if (xmlreload.readyState == 4) {
			if (xmlreload.responseText == "true") {
				if (page == 'header') {
					if (register == 'register') {
						parent.parent.document.location = "/social/facebook_invite";
					} else {
						document.location = "/social/facebook_invite";
					}
				} else {
					document.getElementById('signin_uid').value = uid;
					//document.getElementById('signup_uid').value = uid;
					if (document.getElementById('signin_div'))
						document.getElementById('signin_div').style.display = '';
					if (document.getElementById('signup_div'))
						document.getElementById('signup_div').style.display = '';
				}
			} else {
				if (xmlreload.responseText == "Already Associated")
					if (register == 'register') {
						parent.parent.document.location = "/home";
					} else {
						document.location = "/home";
					}
				else if (register == 'register') {
					parent.parent.document.location = "/social/facebook_invite";
				} else {
					document.location = "/social/facebook_invite";
				}
				///alert("continue browsing");
			}
		}
	}
	xmlreload.send(null);
}

function submitForm(frmId) {
	//alert('in');
	//alert(frmId);
	if (document.getElementById('flow')) {
		if (document.getElementById('flow').value == "signup") {
			AL.Tracker.track('/FBNewUserRegister.al');
		} else {
			AL.Tracker.track('/FBUserAssociate.al');
		}
	}
	document.getElementById(frmId).submit();
}

function importContactsSocial(show_page) {
	var xmlreload = initxmlhttp();
	var email_box = document.getElementById('email_box').value;
	var pr = email_box.substr(email_box.indexOf("@") + 1, email_box
			.indexOf("."));
	var password_box = document.getElementById('password_box').value;
	var provider_box = document.getElementById('provider_box').value;
	if (provider_box == "") {
		provider_box = pr;
		document.getElementById('provider_box').value = pr;
	}

	if (password_box == "" && email_box == "") {
		submitForm('jumpD');
	} else {
		var str = "e=" + email_box + "&ps=" + escape(password_box) + "&pr="
				+ provider_box + "&response=count";
		var url = "/ajax/import_contacts";//+"?"+str;
		//return GB_showPage('Flower', url)
		document.body.style.cursor = 'wait';
		xmlreload.open("POST", url, true);
		xmlreload.onreadystatechange = function() {
			if (xmlreload.readyState == 4) {
				var res = '';
				j_string = xmlreload.responseText;
				document.body.style.cursor = 'wait';
				if (j_string.indexOf('=') != -1)
					eval(j_string);
				if (typeof res == "string" && res == "true") {
					submitForm('frmImportContact');

				} else {
					if (j_string.indexOf('Login failed') > 0)
						j_string = "Please check the email and password you have provided and try again.";
					document.getElementById('import_error').innerHTML = "<b>"
							+ j_string + "</b>";
					hideDiv('loading');
				}
				document.body.style.cursor = 'default';
			}
		}
		xmlreload.setRequestHeader("Content-type",
				"application/x-www-form-urlencoded");
		xmlreload.setRequestHeader("Content-length", str.length);
		xmlreload.setRequestHeader("Connection", "close");
		xmlreload.send(str);
	}// else patrt
}

function chkEnterPress(e, fnName) {
	var unicode = e.charCode ? e.charCode : e.keyCode
	if (unicode == 13) { //if the key isn't the backspace key (which we should allow)
		if (fnName) {
			setTimeout(fnName, 1);
		} else {
			showDiv('loading');
			importContactsSocial('invite');
		}
	}
}//End of Function

function toggleAll(element) {
	//	alert(form.name);
	var form = document.forms.openinviter;
	var z = 0;
	for (z = 0; z < form.length; z++) {
		if (form[z].type == 'checkbox')
			form[z].checked = element.checked;
	}
}

function hideDiv(divId) {
	document.getElementById(divId).style.display = 'none';
}

function showDiv(divId) {
	document.getElementById(divId).style.display = 'block';
}

function inviteValidation() {
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	if (document.getElementById('copiedEmail').value != "") {
		var str = document.getElementById('copiedEmail').value;
		if ($.trim(str.substr(str.lastIndexOf(",") + 1)) == '') {
			document.getElementById('copiedEmail').value = str.substr(0, str
					.lastIndexOf(","));
		}
		check = checkCopyPasteEmails(reg);
		if (!check) {
			document.getElementById('toEmailErr').innerHTML = 'One or more email addresses are invalid.';
			return false;
		}

	}
	return true;
}

function replaceSemicolonsByComma() {

	// fix By Ninad for frogpond iframe bug 1428 
	if (top.parent.window.document.getElementById('copiedEmail'))
		var accObj = top.parent.window.document;
	else if (top.frogbottom.document.getElementById('copiedEmail'))
		var accObj = top.frogbottom.document;
	// fix By Ninad for frogpond iframe bug 1428 

	var str = accObj.getElementById('copiedEmail').value;
	str = str_replace(";", ",", str);
	if (accObj.getElementById('copiedEmail').value != str)
		accObj.getElementById('copiedEmail').value = str;
}

function validateCopiedEmails() {
	replaceSemicolonsByComma();
	var res = inviteValidation();
	//alert(res);
	if (res) {
		document.getElementById('copiedEmailClone').value = document
				.getElementById('copiedEmail').value;
		submitForm('jumpD');
	} else {
		hideDiv('loading');
		return false;

	}
}

function checkCopyPasteEmails(reg) {
	replaceSemicolonsByComma();
	var existingEmails = document.getElementById('copiedEmail').value;
	existingEmails = str_replace(";", ",", existingEmails);
	var eAddrStr = existingEmails.split(',');
	var invalid = 0;
	for (index in eAddrStr) {
		if (reg.test($.trim(eAddrStr[index])) == false) {
			invalid++;
		}
	}
	return (invalid > 0) ? false : true;
}

function trackSearchEvent() {
	var searchfor = document.getElementById("searchfor").value;
	if (searchfor != '' && searchfor != 'Restaurants, Dentist, etc') {
		pageTracker._trackEvent('Searched Category', 'Click', searchfor, 2);
	}
}

function ajax_checkIfUserExists(s) {
	var xmlreload = initxmlhttp();

	if (document.getElementById('signin_email')) {
		var signin_email_str = document.getElementById('signin_email').value;
		if ($.trim(signin_email_str).length > 6) {
			var url = "/ajax/checkUserExist/email/" + signin_email_str;
			xmlreload.open("GET", url, true);
			xmlreload.onreadystatechange = function() {
				if (xmlreload.readyState == 4) {
					j_string = xmlreload.responseText;

					if (j_string == 'exists') {
						document.getElementById('flow').value = "signin";
						document.getElementById('signin-password').style.display = "block";
						$('#loading_gif_invite').hide();
						if (document.getElementById('signin_pass').value != "")
							submitForm('inviteSignIn');
						else
							return false;
					} else {
						document.getElementById('flow').value = "signup";
						document.getElementById('signin-password').style.display = "none";
						if (document.getElementById('city').value == ""
								&& document.getElementById('signup-city').value == "") {
							document.getElementById('signup-location').style.display = "";
							return false;
						} else {
							//check city logic comes here
							checkFBCity(
									document.getElementById('signup-city').value,
									'inviteSignIn')
						}
					}
				}
			}
			xmlreload.send(null);
		}
	}
}

function checkFBCity(location, frm) {
	var xmlreload = initxmlhttp();
	var city = location.substr(0, location.indexOf(","));
	var state = location.substr(location.indexOf(",") + 2);

	var url = "/ajax/check_city/" + location;
	xmlreload.open("GET", url, true);
	xmlreload.onreadystatechange = function() {
		if (xmlreload.readyState == 4) {
			// Split for delimeter
			j_string = xmlreload.responseText;
			if (j_string == "1") {
				document.getElementById('city').value = city;
				document.getElementById('state').value = state;
				submitForm(frm);
			} else {
				alert("City entered is invalid. Please enter or select valid city.");
				return false;
			}
		}
	}
	xmlreload.send(null);
}

function checkMaxAllowedInvites() {
	var maxAllowed = $("#CNST_MaxInviteEmailAllowed").val();
	var totalImportedContacts = $("#totalImportedContacts").val();
	var cntr = 0;
	for (i = 0; i < totalImportedContacts; i++) {
		if ($("#check_" + i).attr("checked"))
			cntr++;
	}
	if (cntr > maxAllowed)
		return false;
	else
		return true;
}

// ~~N~~ Ninad 02 April 2010 - 
// copied function from one of removed file (invites.js) - beta 1007 branch
// needed for facebook flow.
function validateImportContacts()
{
	document.getElementById('openWarning').innerHTML='';
	var sizeFriends = document.getElementById('frndSize').value;
	
	var friendCounter = 0;
	var checkCounter=0;
	for(var i=0; i<sizeFriends; i++){		
		if(document.getElementById("check_"+i).checked==false)
		{
			friendCounter++;			
		}
		else if(document.getElementById("check_"+i).checked==true) 
		{
			checkCounter++;						
		}
	}
	
	if(checkCounter>0)
	{
		return true;			
	}
	else if((friendCounter == (sizeFriends-1)) && checkCounter==0)
	{
		document.getElementById('openWarning').innerHTML='Please select friend(s) to invite.';
		return false;		
	}
	return true;	
}
*/