var maxEmailCount;
// JavaScript Document
/* 
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
	Function To Import Address in greybox
	Created By Ninad
	Date 08-01-09
	params  None
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
*/	


function importContacts(show_page){
	if(show_page === "invite") {			
		$("#addImportEmailFB").html("");
		$("#addImportPassFB").html("");		
		var email_box = $("#clientEmailAdd").val();		
		var password_box = $("#clientPasswordAdd").val();
		var provider_box = $("#providerBoxAdd").val();
		var hiddenDiv = "#importEmailListAdd";
	} else if (show_page === "ask") {			
		$("#askImportEmailFB").html("");
		$("#askImportPassFB").html("");		
		var email_box = $("#clientEmailAsk").val();		
		var password_box = $("#clientPasswordAsk").val();
		var provider_box = $("#providerBoxAsk").val();
		var hiddenDiv = "#importEmailListAsk";
	} else { // signup
		$("#email_service_address_error").html("");
		$("#email_service_password_error").html("");
		var email_box = $("#email_service_address").val();		
		var password_box = $("#email_service_password").val();
		var provider_box = $("#providerBoxSignup").val();		
	}
	document.body.style.cursor = 'wait';

	$.post("/ajax/import_contacts", { 
		   e: email_box,
		   ps: escape(password_box),
		   pr: provider_box
		},
		function(data){
			var err="";
			// check if it returns error
			if(data.slice(0,9) == 'ERROR :::'){
				err = data.replace('ERROR :::','');
				if(show_page == 'invite'){
					$("#addImportNotFoundFB").html("The email client login was not successful. Please check your email and password.");
					$("#clientEmailAdd").focus();
					$(".loading_gif_addImportEmail").css({"display":"none"});
				} else if (show_page == 'ask') {
					$("#askImportNotFoundFB").html("The email client login was not successful. Please check your email and password.");
					$("#clientEmailAsk").focus();				
					$(".loading_gif_askImportEmail").css({"display":"none"});
				} else {
					$("#import_contacts_error").html("The email client login was not successful. Please check your email and password.");
					$("#email_service_address").focus();
					$(".loading_gif_import_contacts").css({"display":"none"});
				}
				document.body.style.cursor = 'default';
			}
			else{
				j_string = data;
				document.body.style.cursor = 'wait';
				//if(j_string.indexOf('=') != -1) eval(j_string);

				// google event tracker call 
				AL.Tracker.track('/Imported'+provider_box+'.al');
				
				if(show_page == 'ask'){
					$("#askImportEmailSelect .importList").html("<div class='loading_gif loading_gif_import'></div>");
					$('.loading_gif_import').css({"display":"inline-block"});
					$("#askImportEmailSelect").css("display", "block");
					$("#askImportEmail").css("display", "none");
					$(".loading_gif_askImportEmail").css({"display":"none"});
					//var url = "/inviter_iframe.php"+"?"+"email_box="+email_box+"&password_box="+escape(pass)+"&provider_box="+provider_box;						
					$("#askImportEmailSelect .importList").html(data);
					document.body.style.cursor = 'default';
					return false;
				} else if(show_page == 'invite'){
					$("#addImportEmailSelect .importList").html("<div class='loading_gif loading_gif_import'></div>");
					$('.loading_gif_import').css({"display":"inline-block"});
					$("#addImportEmailSelect").css("display", "block");
					$("#addImportEmail").css("display", "none");
					$(".loading_gif_addImportEmail").css({"display":"none"});
					//var url = "/inviter_iframe.php"+"?"+"email_box="+email_box+"&password_box="+escape(pass)+"&provider_box="+provider_box;
					$("#addImportEmailSelect .importList").html(data);
					document.body.style.cursor = 'default';
					return false;
				} else {
					$("#inviter_content_email_services .importList").html("<div class='loading_gif loading_gif_import'></div>");
					$('.loading_gif_import').css({"display":"inline-block"});
					$("#email_service_select_contacts").css("display", "block");
					$("#email_service_form").css("display", "none");
					$(".loading_gif_import_contacts").css({"display":"none"});
					//var url = "/inviter_iframe.php"+"?"+"email_box="+email_box+"&password_box="+escape(pass)+"&provider_box="+provider_box;
					$("#inviter_content_email_services .importList").html(data);
					document.body.style.cursor = 'default';
					return false;
				
				}
				
			}

			document.body.style.cursor = 'default';
		}
	);
}


/*********************** Jasmine: below is legacy - not sure if needed elsewhere *******************/

function numFeedback(emailCount,maxEmailCount) {
	/* fix By Ninad for frogpond iframe bug 1428 */
	if(top.parent.window.document.getElementById('toEmailErr'))
		var accObj = top.parent.window.document;
	else if(top.frogbottom.document.getElementById('toEmailErr'))
		var accObj = top.frogbottom.document;
	/* fix By Ninad for frogpond iframe bug 1428 */

	accObj.getElementById('toEmailErr').innerHTML = emailCount+"/"+maxEmailCount+ " emails entered";
	accObj.getElementById('toEmailErr').style.color = "#8dc63f";
	return true;
//	if(emailCount > maxEmailCount) {
//		var removeNum =  emailCount - maxEmailCount;
//		accObj.getElementById('toEmailErr').innerHTML = "Oops, too many contacts. There is a maximum of "+maxEmailCount+" allowed. Please remove "+removeNum+" contacts.";
//		accObj.getElementById('toEmailErr').style.color = "#ff0000";
//		return false;
//	} else {
//		accObj.getElementById('toEmailErr').innerHTML = emailCount+"/"+maxEmailCount+ " emails entered";
//		accObj.getElementById('toEmailErr').style.color = "#8dc63f";
//		return true;
//	}
}

function checkForEmailCount() {
	/* fix By Ninad for frogpond iframe bug 1428 */
	if(top.parent.window.document.getElementById('CNST_MaxInviteEmailAllowed'))
		var accObj = top.parent.window.document;
	else if(top.frogbottom.document.getElementById('CNST_MaxInviteEmailAllowed'))
		var accObj = top.frogbottom.document;
	/* fix By Ninad for frogpond iframe bug 1428 */
	
	var maxEmailCount = accObj.getElementById('CNST_MaxInviteEmailAllowed').value;
	var selectedEmailCount = 0;
	var existingEmails = accObj.getElementById('copiedEmail').value;
	if(existingEmails == "") {
		var emailCount = 0;
	} else {
		existingEmails = str_replace( ";", ",",existingEmails);
		existingEmails = existingEmails.replace(/^\s+|\s+$/g,""); // trim whitespace from start and end	
		if(existingEmails.substr(strlen(existingEmails)-1,strlen(existingEmails)) == ",") {
			existingEmails = existingEmails.substr(0,strlen(existingEmails)-1);
		}
		var existingEmailsArr = explode( ",", existingEmails);
		var emailCount = count(existingEmailsArr);
	}
	return(numFeedback(emailCount,maxEmailCount));
}



function importContactsInvite(){

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

	replaceSemicolonsByComma();
	maxEmailCount = accObj.getElementById('CNST_MaxInviteEmailAllowed').value;
	var emailStr = "";
	var cntr = 0;
	var condition = true;
	var nameStr = "";
	
	var existingEmails = accObj.getElementById('copiedEmail').value;
	existingEmails = str_replace( ";", ",",existingEmails);
	existingEmails = existingEmails.replace(/^\s+|\s+$/g,""); // trim whitespace from start and end	
	if(existingEmails.substr(strlen(existingEmails)-1,strlen(existingEmails)) == ",") {
			existingEmails = existingEmails.substr(0,strlen(existingEmails)-1);
	}
	var existingEmailsArr = explode( ",", existingEmails);
	var emailCount = count(existingEmailsArr);
	
	var selectedEmailCount = 0;
	var maxEmailCountReached = false;
	while(condition == true){
		if(selectedEmailCount <= maxEmailCount){
			//if checkbox is checked
			//alert(cntr+" >> "+document.getElementById('email_'+cntr).value);
			if(document.getElementById('check_'+cntr).checked == true){
				// if email is already existing
				if(!in_array(document.getElementById('email_'+cntr).value, existingEmailsArr)){
					emailStr += document.getElementById('email_'+cntr).value + ", ";
					nameStr += document.getElementById('name_'+cntr).value + ", ";
				}
				selectedEmailCount++;
			}
			cntr++;
			if(document.getElementById('check_'+cntr)) {}
			else	condition = false;
		}
		else{
			condition = false;
			var maxEmailCountReached = true;
		}
	}//while
	
	emailStr = emailStr.substr(0,emailStr.lastIndexOf(","));
	if(trim(existingEmails) != '' && trim(existingEmails.substr(existingEmails.lastIndexOf(",")+1)) != ''){

		if( (existingEmails.substr(strlen(existingEmails)-1,strlen(existingEmails)) != ",") &&
		    (existingEmails.substr(strlen(existingEmails)-2,strlen(existingEmails)) != ", ") )
			accObj.getElementById('copiedEmail').value += ", "+emailStr+", ";
		else
			accObj.getElementById('copiedEmail').value += emailStr+", ";
	}
	else
		accObj.getElementById('copiedEmail').value += emailStr+", ";
	
	//alert("emailCount = "+emailCount+", selectedEmailCount = "+selectedEmailCount);
	var emailCount = emailCount + selectedEmailCount;
	
	var new_ec = emailCount - 1
	numFeedback(new_ec,maxEmailCount); // last comma counted so off-by-one //
	
	//activateSave();
	//parent.parent.GB_hide();
	$("#hidden2").css("display", "none");
	$("#inviteFormBoxes").css("display", "block");
	$("#askFormBoxes").css("display", "block");
	$("#ask_form").css("display", "block");
	show_div('email_services_images');
	checkUnique();
	//checkForEmailCount();
}


function checkInvite()
{
		if(document.getElementById('copiedEmail'))	obj = document;
		else if(top.parent.window.document.getElementById('copiedEmail'))	obj = top.parent.window.document;
	/* fix By Ninad for frogpond iframe bug 1428 */
		else if(top.frogbottom.document.getElementById('copiedEmail')) var obj = top.frogbottom.document;
	/* fix By Ninad for frogpond iframe bug 1428 */
		
		
		var condition = true;
		var existingEmails = obj.getElementById('copiedEmail').value;
		existingEmails = str_replace( ";", ",",existingEmails);
		var existingEmailsArr = explode( ",", existingEmails);

		if(in_array(document.getElementById('emailid').value, existingEmailsArr)){
			document.getElementById('toEmailErr1').innerHTML='You cannot invite yourself.';
			return false;
		}
		return true;
}

	
	function checkUnique(){
		replaceSemicolonsByComma();
		var cntr = 0;
		var str = document.getElementById('copiedEmail').value;
		//var emailArr = Array;
		var uniqueArr = Array();
		//emailArr = explode(",",str);
		var emailArr=document.getElementById('copiedEmail').value.split(',');
		//var uniqueArr = document.getElementById('copiedEmail').value.split(',');;
	
	//	emailArr = array_unique(emailArr);
		cnt = count(emailArr);
		var returnStr = "";
		for(i=0; i<cnt; i++){
			present_in_uniue_array = false;
			if(trim(emailArr[i]) != ""){
				for(j=0; j<i;j++){
					if(trim(uniqueArr[j]) == trim(emailArr[i])){
						present_in_uniue_array = true;
						j=i;
					}
				}
				if(!present_in_uniue_array){
					uniqueArr[cntr] = trim(emailArr[i]);
					cntr++;
					returnStr += trim(emailArr[i])+", " 
				}
			}
		}
		document.getElementById('copiedEmail').value = returnStr;
	}

	
	function validateInviteForm(){
		replaceSemicolonsByComma();
		if(!basicValidations()){
			return false
		}
		if(!inviteValidation()){
			return false;
		}
		if(!checkInvite()){
			return false;
		}
/*		if(!checkForEmailCount()){
			return false;
		}
*/
    // google event tracker call
    AL.Tracker.track('/inviteSendCompleted.al');
		return true;
	}
	

function inviteValidation(whichPage){
   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='Please enter valid email addresses separated by comma, semi-colon, space or &lt;enter&gt;.';
			return false;
		}

	}	
	else if(document.getElementById('copiedEmail').value==""){
		document.getElementById('toEmailErr').innerHTML='Enter your email address(es) in the box above.';
		return false;
	}
	return true;
}

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 setMaxEmailCount(){
	maxEmailCount = document.getElementById('CNST_MaxInviteEmailAllowed').value;
}


function chkEnterPress(e){
	var unicode=e.charCode? e.charCode : e.keyCode
	if (unicode==13){ //if the key isn't the backspace key (which we should allow)
		importContacts('invite');
	}
}//End of Function



function basicValidations(){
	document.getElementById('toEmailErr').innerHTML='';
	document.getElementById('subjectErr').innerHTML='';
	document.getElementById('messageErr').innerHTML='';
	if(trim(document.getElementById('copiedEmail').value) == ""){
		document.getElementById('toEmailErr').innerHTML='Enter your email address(es) in the box above.';
		document.getElementById('toEmailErr').style.color = "#f00";		
		$('.loading_gif_invite').css({'display':'none'});
		return false;
	}
	if(trim(document.getElementById('subject').value) == ""){
		document.getElementById('subjectErr').innerHTML='Please enter the subject.';
		document.getElementById('subjectErr').style.color = "#f00";
		$('.loading_gif_invite').css({'display':'none'});
		return false;
	}
	/*
	if(trim(document.getElementById('message').value) == ""){
		document.getElementById('messageErr').innerHTML='Please enter the Message.';
		document.getElementById('messageErr').style.color = "#ff0000";
		$('.loading_gif_invite').css({'display':'none'});
		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 */

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

		/*
		 * Added by Suhas for #843
		 * We will now have support for new line characters, and spaces as email separators
		*/
		var val = accObj.getElementById('copiedEmail').value;
		var regex = new RegExp('\b\s+\b');		//RegEx to replace multiple spaces between emails with a single space
		val = val.replace(regex, ' ');			//Apply the regex here
		val = str_replace(' ',',', val);		//Now replace that single space by a comma
		val = trim(str_replace('\n',',', val));	//Handle new lines here
		val = str_replace(',,',',', val);		//Now if there are any multiple commas, then replace them with a single comma

		accObj.getElementById('copiedEmail').value = val;
		/*
		 * Added by Suhas for #843
		*/
	}
}

function activateSave(){
	//alert(document.getElementById('invite_button').innerHTML);
	if(document.getElementById('copiedEmail'))
		obj = document;
	else if(top.parent.window.document.getElementById('copiedEmail'))
		obj = top.parent.window.document;
	else if(top.frogbottom.document.getElementById('copiedEmail'))
		obj = top.frogbottom.document;

	if(obj.getElementById('invite_button')){
		
		if(obj.getElementById('copiedEmail').value != ''){
			if(strstr(obj.getElementById('invite_button').innerHTML,"_disable")){
				//alert('a');
				obj.getElementById('invite_button').innerHTML = "<input type=\"image\" src=\"images/btn_invitefriendtojoin.jpg\" alt=\"search\" name=\"Submit\" border=\"0\" id=\"Submit\" onMouseOver=\"MM_swapImage('Submit','','images/btn_invitefriendtojoin_ovr.jpg',1)\" onMouseOut=\"MM_swapImgRestore()\" />";
			}
		}
		else{
			if(!strstr(obj.getElementById('invite_button').innerHTML,"_disable")){
				//alert('b');
				obj.getElementById('invite_button').innerHTML = "<img src=\"images/btn_invitefriendtojoin_disable.jpg\" />";		
			}
		}
	}
}

function cancelImport() {
	$("#hidden2").css("display", "none");
	$("#inviteFormBoxes").css("display", "block");
	$("#askFormBoxes").css("display", "block");
	$("#ask_form").css("display", "block");
	show_div('email_services_images');
}


