// Global variables
// timerFlag is a global timer set to clear the share's message window
var timerShare;
// timerAjaxFlag is a global timer set to keep track of how long it is
// taking for the Geogad server to respond. If it is longer than some
// prefered value, the program redirects the user input to another operation.
var timerAjaxShare;
// Regex expression can only be created once. Otherwise it will error.
var emailRegexp = new RegExp("^[ \\t]*[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}[ \\t]*$");



function isAjaxSupportedShare() {
// Check if request can be created by is not used
   var request = null;
   if(typeof window.XMLHttpRequest != 'undefined')
   {
     request = new XMLHttpRequest();
   }
   else if(typeof window.ActiveXObject != 'undefined')
   {
     try { request = new ActiveXObject('Microsoft.XMLHTTP'); }
     catch(err) { request = null; }
   }
   if (request != null)
   	return(true); 
   else 
   	return(false); 
}

function shareSuccess(id) {
	window.clearTimeout(timerShare);
	var rt = document.getElementById(id);
	rt.innerHTML = '<div class="shareBox"><div style="text-align: center" ><span class="blueText">Message sent!</span></div></div>';
	timerShare = window.setTimeout('shareClearMessage("'+id+'")', 7000); 
}

function shareWaitMessage(id) {
	window.clearTimeout(timerShare);
	var rt = document.getElementById(id);
	rt.innerHTML = '<div class="shareBox"><div style="text-align: center" >Sending....</span></div></div>';
}

function shareProblemMessage(id) {
	window.clearTimeout(timerShare);
	var rt = document.getElementById(id);
	rt.innerHTML = '<div class="shareBox"><div style="text-align: center" ><span class="yellowBackground redfont">Problem sending message. Please try again later.</span></div></div>';
	timerShare = window.setTimeout('shareClearMessage("'+id+'")', 7000); 
}

function shareErroMessage(message, toText, messageText) {
	shareClearTimers();
	var rt = document.getElementById("dynamicMenuBox_error");
	rt.innerHTML = message;
	rt = document.getElementById("shareToBox");
	rt.innerHTML = toText;
	rt = document.getElementById("shareMessageBox");
	rt.innerHTML = messageText;
}


function shareClearMessage(id) {
	var rt = document.getElementById(id);
	rt.innerHTML = '';
}


function shareClearTimers() {
// free callback timer here
   window.clearTimeout(timerShare);
   window.clearTimeout(timerAjaxShare);
}



function ChangeFocusSelectShare(switchFocus2, value, nickname) {

   if (value != null) {
	// User has selected a valid value; Switch focus to switchFocus2
        setfocus(switchFocus2);
	if (isAjaxSupportedShare()) {

		if (value.indexOf("All") != -1) {
			JGetMessageInfo.getAllAddresses4UserJS(nickname, getAddressesShare);		
		} else if (value.indexOf("Friend") != -1) {
			JGetMessageInfo.getFriendNames4UserJS(nickname, getAddressesShare);		
		} if (value.indexOf("Email") != -1) {
			JGetMessageInfo.getEmailAddresses4UserJS(nickname, getAddressesShare);
		}
	}
   }

}

function add2ToBox(strValue, elem) {

   var box = document.getElementById(elem);
   var currentText = box.innerHTML;
   if (currentText == null) {
		// Add this value
		box.innerHTML = strValue;
		charCounter("shareToBox","shareToBoxcount", 200);
   } else if (currentText.length < 1) {
		// Add this value
		box.innerHTML = strValue;
		charCounter("shareToBox","shareToBoxcount", 200);
   } else {
	// Check if this value is already in the mix
	var addr=new Array();
	currentText = currentText.replace(/ /g, "");
	addr = currentText.split(",");
	var checkAddr;
	var x;
	for (x in addr) {
		checkAddr = addr[x].match(strValue);
		if (checkAddr != null) 
			break;
	}
	if (checkAddr == null) {
		// No match; Just add
		box.innerHTML += ", "+ strValue;
		charCounter("shareToBox","shareToBoxcount", 200);
	}		
   }

}



function sendShare(nickname, tID, ctID, tsID, profileID, box) { 

// set a error flag to false

	var form_error = false;
	var message = document.getElementById("dynamicMenuBox_error");
	message.innerHTML = "";

   var mailTo = document.getElementById("shareToBox");
   var mailToText = mailTo.value;


  if (mailToText == "") {
	message.innerHTML = "Enter an address to sent the message to.";
	form_error = true;
	setfocus(mailTo);
  } else {
	var i;
	var errorMsg = "";
	var myArray = mailToText.split(',');
	for (i in myArray) {
		if (myArray[i].indexOf("@") != -1) {
			if (!(emailRegexp.test(myArray[i]))){
				errorMsg += myArray[i]+" ";
			}
		}
	}
	if (errorMsg.length > 1) {
		message.innerHTML = "Not valid emails: "+errorMsg +"<br/>"
		form_error = true;
		setfocus(mailTo);
	} 
  }

   var mailMessage = document.getElementById("shareMessageBox");
   var mailMessageText = mailMessage.value;


  if (mailMessageText.indexOf('<') != -1) {  
	message.innerHTML += "&#60; is not an acceptable character.<br/>";
	form_error = true;
	setfocus(mailMessage);
  } 
  if (mailMessageText.indexOf('>') != -1) { 
	message.innerHTML += "&#62; is not an acceptable character.<br/>";
	form_error = true;
	setfocus(mailMessage);
  } 



 if (form_error)  {
// Problem with data;  send user back to form page to fix
	message.innerHTML += "<br/>";
   	return false;
  }
     else 
  {
   	if (isAjaxSupportedShare()) {
		window.clearTimeout(timerAjaxShare);
		var webpage = location.href;
   		JGetMessageInfo.createShareMessageJS(nickname, mailToText, mailMessageText, tID, ctID, tsID, profileID, webpage, print2DisplayShareBoxDynamic);
		timerAjaxShare = window.setTimeout('shareProblemMessage("'+box+'")', 30000); 
		shareWaitMessage(box);
		return false;
	} else { 
		return true ; 
	} 
  }


}


// Checks form but does not use AJAX to send info
function checkShare(nickname, tID, ctID, tsID, profileID, box) { 

// set a error flag to false

	var form_error = false;
	var message = document.getElementById("dynamicMenuBox_error");
	message.innerHTML = "";

   var mailTo = document.getElementById("shareToBox");
   var mailToText = mailTo.value;


  if (mailToText == "") {
	message.innerHTML = "Enter an address to sent the message to.";
	form_error = true;
	setfocus(mailTo);
  } else {
	var i;
	var errorMsg = "";
	var myArray = mailToText.split(',');
	for (i in myArray) {
		if (myArray[i].indexOf("@") != -1) {
			if (!(emailRegexp.test(myArray[i]))){
				errorMsg += myArray[i]+" ";
			}
		}
	}
	if (errorMsg.length > 1) {
		message.innerHTML = "Not valid emails: "+errorMsg +"<br/>"
		form_error = true;
		setfocus(mailTo);
	} 
  }

   var mailMessage = document.getElementById("shareMessageBox");
   var mailMessageText = mailMessage.value;


  if (mailMessageText.indexOf('<') != -1) {  
	message.innerHTML += "&#60; is not an acceptable character.<br/>";
	form_error = true;
	setfocus(mailMessage);
  } 
  if (mailMessageText.indexOf('>') != -1) { 
	message.innerHTML += "&#62; is not an acceptable character.<br/>";
	form_error = true;
	setfocus(mailMessage);
  } 



 if (form_error)  {
// Problem with data;  send user back to form page to fix
	message.innerHTML += "<br/>";
   	return false;
  } else   {
	return true ; 
  }


}

function print2DisplayShareBoxDynamic(data) {

   shareClearTimers();
// check for returned data
   if ((data == "") || (data == null)) {
	shareProblemMessage("dynamicMenuBox_error");
   }  else {
	if ((data.indexOf("Problem") != -1) || (data.indexOf("problem") != -1)) {
		shareProblemMessage("dynamicMenuBox");
	} else if (data.indexOf("reenter the addresses") != -1) {
		var str = eval( "(" + data + ")" );
		var thisNickname = str.nickname;
		var thisTID = str.tID;
		var thisCTID = str.ctID;
		var thisTSID = str.tsID;
		var error = str.ErrorMsg;
		var toInfo = str.toInfo;
		var messageInfo = str.messageInfo;

		DisplayShareBoxDynamic(thisNickname, thisTID, thisCTID, thisTSID, "dynamicMenuBox");
		shareErroMessage(error, toInfo, messageInfo);
	} else if (data.indexOf("Message sent!") != -1) {
		shareSuccess("dynamicMenuBox"); 
	}
   }

}



// Don't worry about AJAX timer
function DisplayShareBoxDynamic(thisNickname, thisTID, thisCTID, thisTSID, elem) {

   var box = document.getElementById(elem);

   var shareBoxInfo = "<div class='shareBox'>"+
                    "<div style='text-align: right' >(<a class='easyLink' title='Close this box' href='#' onclick='shareClearMessage(\"dynamicMenuBox\"); return false;' >Close</a>)</div>"+
                    "<div style='text-align: center' >"+
                    "<span class='shareTitle'>Share</span></div>"+
                    "<FORM  ENCTYPE='application/x-www-form-urlencoded' ACTION='./Share' METHOD=POST name='ShareForm' id='ShareForm' "+
                    " onsubmit='return sendShare(\""+thisNickname+"\", \""+thisTID+"\", \""+thisCTID+"\", \""+thisTSID+"\", \""+elem+"\");' >"+    
                    "<div  >"+
                    "<span id='dynamicMenuBox_error' name='dynamicMenuBox_error' class='loudred' style='text-align: center'> "+
                    "</span></div>"+
                    "<div class='leftShare'>"+
                    "<div class='smallShareTitle'>Send Message</div>"+
                    "<span class='smallShareTitle'>To:</span> (<span id='shareToBoxcount' name='shareToBoxcount' class='smallPrintShare'>200 characters maximum.</span>)"+               
                    "<div class='smallPrintShare'><textarea id='shareToBox' name='shareToBox' rows='4'  "+
                    "onLoad='charCounter(\"shareToBox\",\"shareToBoxcount\", 200);' " +
                    "onKeyDown='charCounter(\"shareToBox\",\"shareToBoxcount\", 200);' " + 
                    "onKeyUp='charCounter(\"shareToBox\",\"shareToBoxcount\", 200);' >"+
		    "</textarea></div><span class='smallPrintShare'>Separate names and emails with commas</span><br/><br/>"+    
                    "<span class='smallShareTitle'>Message:</span> <span class='smallPrintShare'>optional</span><br/>"+
                    "(<span id='shareMessageBoxcount' name='shareMessageBoxcount' class='smallPrintShare'>500 characters maximum.</span>)"+
                    "<div class='smallPrintShare'><textarea id='shareMessageBox' name='shareMessageBox' rows='3' "+
                    "onLoad='charCounter(\"shareMessageBox\",\"shareMessageBoxcount\", 500);' " +
                    "onKeyDown='charCounter(\"shareMessageBox\",\"shareMessageBoxcount\", 500);' " + 
                    "onKeyUp='charCounter(\"shareMessageBox\",\"shareMessageBoxcount\", 500);' ></textarea></div></div>"+          
               
                    "<div class='rightShare'>"+
                    "<div class='smallShareTitle'>Address Book</div>"+

                    "<select name='shareSelect' id='shareSelect' "+
                    "onChange='ChangeFocusSelectShare(shareAddressBox, this.value, \""+thisNickname+"\");' >"+
                    "<option value='All'>All Contacts</option>"+
                    "<option value=''></option>"+
                    "<option value=''></option>"+
                    "</select>"+
                    
                    "<div id='shareAddressBox' name='shareAddressBox' class='shareAddressBox'  >"+
                    "</div><span class='smallPrintShare'>Select names to send message to</span>"+    
                    "</div>"+     
                       
                    "<div style='clear:both; margin-left: auto; margin-right: auto; padding: 1em 1em 1em 1em;' >  "+ 
                    "<INPUT TYPE='submit' VALUE='Send Message' name='sendShareButton' id='sendShareButton' tabindex='50000' style='margin: 0em 1em 0em 0em;' />"+

                    "<INPUT TYPE='button' VALUE='Cancel' name='clearShareButton' id='clearShareButton' tabindex='50010' onclick='shareClearMessage(\"dynamicMenuBox\"); return false;' />"+
                    "</div>"+   
                    "<INPUT TYPE=hidden NAME='tidShare' id='tidShare' VALUE="+thisTID+">"+
                    "<INPUT TYPE=hidden NAME='ctidShare' id='ctidShare' VALUE="+thisCTID+">"+
                    "<INPUT TYPE=hidden NAME='tsidShare' id='tsidShare' VALUE="+thisTSID+">"+
                    "<INPUT TYPE=hidden NAME='cidShare' id='cidShare' VALUE='"+thisNickname+"'>"+
                    "</FORM> </div>";
		
   box.innerHTML = shareBoxInfo;
		
   JGetMessageInfo.getShareAddressSelectJS(thisNickname, getSelectShare);
   JGetMessageInfo.getAllAddresses4UserJS(thisNickname, getAddressesShare);

}

function getSelectShare(data) {

// check for returned data
   if ((data == "") || (data == null)) {
   	//Don't worry about it
	return;
   }  else {
	if (document.getElementById('shareSelect') != null) {
	   	var box = document.getElementById('shareSelect');
		lgth = box.options.length - 1;
		box.options[lgth] = null;
		if (box.options[lgth]) {
			// Not able to add options to the select box
		} else {
			box.options.length = 0;
			box.options[0] = new Option('All Contacts','All', true, false);

// data comes in as a JSON object
			var str = eval( "(" + data + ")" );
   			var i;
  			for (i in str.Results) {
   				var optionValue = str.Results[i].Value;
		   		var optionText = str.Results[i].Text;
				var position = parseInt(i, 10)+1;
                		box.options[position] = new Option(optionText, optionValue, false, false);

			//box.options.length = i+2;
			}

		}
	}	
   }
}


function getAddressesShare(data) {

// check for returned data
   if ((data == "") || (data == null)) {
   	//Don't worry about it
	return;
   }  else {
	if (document.getElementById('shareAddressBox') != null) {
	   	var box = document.getElementById('shareAddressBox');
		box.innerHTML = "";

// data comes in as a JSON object
		var str = eval( "(" + data + ")" );
   		var i;
  		for (i in str.Results) {
   			var address = str.Results[i];
			if (address != null)
				if (address.length > 0)
					box.innerHTML += "<span class='addressBoxText' onclick='add2ToBox(\""+address+"\", \"shareToBox\")'>"+address+"</span><br/>";
		}
	}	
   }
}