//------------ AJAX FUNCTIONS ------------//

function GetXmlHttpObject()
{
var xmlHTTP=null;
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHTTP=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHTTP=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    xmlHTTP=new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
return xmlHTTP;
}

//------------ GENERIC AJAX ------------//

function genAJAX(elem,url)
{
var xmlHTTP;
var err_msg=1;
var err_msg_txt='';
	if(elem.indexOf("_noerr") > 0)
	{
		elem=elem.replace(/_noerr/,"");
		var err_msg=0;
	}
	xmlHTTP=GetXmlHttpObject();
		if (xmlHTTP==null)
		{
			alert ("This web site requires AJAX and your browser does not currently support it.\n\nPlease upgrade your browser or email contact.us@spacemail.com for assistance.");
			return;
		}
		else
		{
			xmlHTTP.onreadystatechange= function()
			{
				if (xmlHTTP.readyState==4)
				{
					if (xmlHTTP.status==200)
					{
						if(elem != 'hdnJOB'){document.getElementById(elem).innerHTML=xmlHTTP.responseText}
					}
					else
					{
						if (err_msg==1)
						{
							if(elem != 'hdnJOB'){document.getElementById(elem).innerHTML="Apologies some data was not retrieved successfully.<br />Please try again or email contact.us@spacemail.com for assistance."}
							//window.location.replace('/error.cfm?ajax='+elem);
							// pass out the error details to admin
							$('err_content').innerHTML=xmlHTTP.responseText;
							err_msg_txt=$('err_content').innerHTML.replace(/(<([^>]+)>)/ig,"");
							err_msg_txt=err_msg_txt.replace(/[^a-zA-Z0-9]+/g,'');
							err_msg_txt=err_msg_txt.replace('ThewebsiteyouareaccessinghasexperiencedanunexpectederrorPleasecontactthewebsiteadministratorThefollowinginformationismeantforthewebsitedeveloperfordebuggingpurposes','');
							err_msg_txt=err_msg_txt.substring(0,500);
							// toggle the below to see error on screen rather than via email
							errorAJAX(elem,err_msg_txt);
							// document.getElementById(elem).innerHTML=xmlHTTP.responseText;
						}
					}
				}
			}
		}
	xmlHTTP.open("GET",url,true);
	xmlHTTP.send(null);
}

//------------ CALLBACK AJAX ------------//

function cbAJAX(elem,url,cb)
{
var xmlHTTP;
var err_msg=1;
var err_msg_txt='';
	if(elem.indexOf("_noerr") > 0)
	{
		elem=elem.replace(/_noerr/,"");
		var err_msg=0;
	}
	xmlHTTP=GetXmlHttpObject();
		if (xmlHTTP==null)
		{
			alert ("This web site requires AJAX and your browser does not currently support it.\n\nPlease upgrade your browser or email contact.us@spacemail.com for assistance.");
			return;
		}
		else
		{
			xmlHTTP.onreadystatechange= function()
			{
				if (xmlHTTP.readyState==4)
				{
					if (xmlHTTP.status==200)
					{
						//--- return the response ---//
						if(elem != 'hdnJOB'){document.getElementById(elem).innerHTML=xmlHTTP.responseText}
						//--- perform the subsequent call back functions ---//
						if(cb == 1){cb1()}
						if(cb == 2){cb2()}
						// if(cb == 3){cb3(elem,getQuerystring(url,'bb_pos'))}
						if(cb == 3){cb3(elem)}
						if(cb == 4){cb4()}
						if(cb == 5){cb5()}
						if(cb == 6){cb6()}
						if(cb == 7){cb7()}
						if(cb == 8){cb8()}
						if(cb == 9){cb9(url)}
						if(cb == 10){cb10()}
						if(cb == 11){cb11()}
						if(cb == 12){cb12()}
					}
					else
					{
						if (err_msg==1)
						{
							if(elem != 'hdnJOB'){document.getElementById(elem).innerHTML='Apologies some data was not retrieved successfully.<br />Please try again or email contact.us@spacemail.com for assistance.'}
							if(cb == 1){$('reset_error_to').style.display='block'};
							if(cb == 2){$('reset_error_cc').style.display='block'};
							// pass out the error details to admin
							$('err_content').innerHTML=xmlHTTP.responseText;
							err_msg_txt=$('err_content').innerHTML.replace(/(<([^>]+)>)/ig,"");
							err_msg_txt=err_msg_txt.replace(/[^a-zA-Z0-9]+/g,'');
							err_msg_txt=err_msg_txt.replace('ThewebsiteyouareaccessinghasexperiencedanunexpectederrorPleasecontactthewebsiteadministratorThefollowinginformationismeantforthewebsitedeveloperfordebuggingpurposes','');
							err_msg_txt=err_msg_txt.substring(0,500);
							// toggle the below to see error on screen rather than via email
							errorAJAX(elem,err_msg_txt);
							// document.getElementById(elem).innerHTML=xmlHTTP.responseText
						}
					}
				}
			}
		}
	xmlHTTP.open("GET",url,true);
	xmlHTTP.send(null);
}

//--- THE CALLBACKS ---//

//--- 1. refocus the to field inside a mail on change (focus change and timeout used for IE) ---//
function cb1(){
	// $('sendSUBJECT').focus();
	if($('ADD_TO')){
		var cbT1=setTimeout("$('ADD_TO').focus();",100);
		}
}

//--- 2. refocus the cc field inside a mail on change ---//
function cb2(){
	// $('sendSUBJECT').focus();
	if($('ADD_CC')){
	var cbT2=setTimeout("$('ADD_CC').focus();",100);
	}
}

//--- 3. all calls after the header ajax deposits ---//
// BB_POS NOW DECOMISSIONED
// function cb3(depo_area,spare_var){
//	if(depo_area=='email_inbox'){
//		if($('bucket_bar') && spare_var > 0){$('bucket_bar').scrollTop=spare_var}
//	}
//	if(depo_area=='space_inbox'){
//		if($('bucket_bar') && spare_var > 0){$('bucket_bar').scrollTop=spare_var}
//	}
// }
function cb3(depo_area){
	if(depo_area=='email_inbox'){
	}
	if(depo_area=='space_inbox'){
	}
}

//--- 4. loading of ckeditor in new email ---//
function cb4(){
	CKEDITOR.replace('sendBODY',{customConfig : '/scripts/ckeditor_config.js'});
}

//--- 5. changing the title after nav refresh to indicate if new email ---//
function cb5(){
	if($('clURrefr')){document.title='! New Mail @Spacemail.com'}
}

//--- 6. offer up folder link options after a move from smail to inbox ---//
function cb6(){
	if($('LINK_MOVE') && $('LINK_OPTIONS')){$('LINK_MOVE').style.display='none';$('LINK_OPTIONS').style.display='block';}
}

//--- 7. action after floatbook listener refresh ---//
function cb7(){
	if($('book_listing') && $('fb_alert')){genAJAX('book_listing','/includes/modules/floatbook/dsp_book.cfm');}
}

//--- 8. animate name after floatbook user select ---//
function cb8(){
	$('fb_throbber').style.display='block';
	animateName();
}

//--- 9. redirect user back to space inbox after removal of self ---//
function cb9(url){
	if(url.indexOf("compact") > 0){
		window.location.replace('/myspaces/?compact=1&success=16');
	}else{
		window.location.replace('/myspaces/?success=16');
	}
}

//--- 10. focus the reply box on email preview ---//
function cb10(){
	$('QUICK_REPLY').focus();
}


//------------ END CALLBACK AJAX ------------//

//------------ AJAX ERROR REPORTING ------------//

function errorAJAX(elem,err)
{
var xmlHTTP;
	xmlHTTP=GetXmlHttpObject();
	xmlHTTP.open("GET","/error.cfm?ajax="+elem+"&err="+err,true);
	xmlHTTP.send(null);
}

//------------ END AJAX FUNCTIONS ------------//


//------------ MARK INBOX ITEMS AS READ OR UNREAD ------------//

function returnSelected(mFrm) { 
	var loopstr = "[START]"
	if(mFrm.checked){loopstr=loopstr+','+mFrm.value}
	for (i = 0; i < mFrm.length; i++){
		if(mFrm[i].checked == true){
			loopstr=loopstr+','+mFrm[i].value
		}
	}
	loopstr=loopstr.replace("[START],","");
	loopstr=loopstr.replace("[START]","");
	return loopstr;
}

function checkSelected(mFrm) { 
	var loopid = 0
	if(mFrm.checked){loopid=1}
	for (i = 0; i < mFrm.length; i++){
		if(mFrm[i].checked == true){
			loopid=loopid+1
		}
	}
	return loopid;
}

function markMail(mTyp,uid) { 
	var mFrm=document.emailinbox.SELECT_MAIL
	var mStr='START'
	var iid = 0
	var loopid = 0
	for (i = 0; i < mFrm.length; i++){
		if(mFrm[i].checked == true){
			loopid=loopid+1
			// get the incremental inbox id
			iid = $('hdnExt'+mFrm[i].value).value;
			// check if already read before marking UNread
			if(mTyp==2 && $('hdnUR'+iid).value==1){
			  // build up the eid string for the ajax
			  mStr=mStr+','+mFrm[i].value;
			  // gui update
			  $(mFrm[i].value).style.fontWeight='bold';
			  $('hdnUR'+iid).value=0;
			  updateUR(0,0-mTyp);
			}
			// check if already UNread before marking read
			if(mTyp==1 && $('hdnUR'+iid).value==0){
			  // build up the eid string for the ajax
			  mStr=mStr+','+mFrm[i].value;
			  // gui update
			  $(mFrm[i].value).style.fontWeight='normal';
			  $('hdnUR'+iid).value=1;
			  updateUR(0,0-mTyp);
			}
		}
	}
	mStr=mStr.replace('START,','');
	if(mStr=='START'){
		if(mFrm.checked){
			loopid=1
			// only one email in the inbox
			iid = $('hdnExt'+mFrm.value).value;
			// check if already read before marking UNread
			if(mTyp==2 && $('hdnUR'+iid).value==1){
			  // markUNread 
			  mStr=mFrm.value;
			  $(mFrm.value).style.fontWeight='bold';
			  $('hdnUR'+iid).value=0;
			  updateUR(0,0-mTyp);
			  genAJAX('hdnJOB','/includes/modules/myemail/act_markread.cfm?u='+uid+'&gu=' + mStr);
			}
			// check if already UNread before marking read
			if(mTyp==1 && $('hdnUR'+iid).value==0){
			  // markread
			  mStr=mFrm.value;
			  $(mFrm.value).style.fontWeight='normal';
			  $('hdnUR'+iid).value=1;
			  updateUR(0,0-mTyp);
			  genAJAX('hdnJOB','/includes/modules/myemail/act_markread.cfm?u='+uid+'&gr=' + mStr);
			}
		}else{
		  if(loopid==0){alert('Please select some emails using the checkboxes')};
		}
	}else{
		// alert(mStr);
		if(mTyp==2){
		  genAJAX('hdnJOB','/includes/modules/myemail/act_markread.cfm?u='+uid+'&gu=' + mStr);
		}else{
		  genAJAX('hdnJOB','/includes/modules/myemail/act_markread.cfm?u='+uid+'&gr=' + mStr);
		}
	}
}

var mF

function markFiles(frid){
	clearTimeout(mF);
	mF=setTimeout("$('dl"+frid+"').innerHTML='&darr;&nbsp;Downloaded';genAJAX('hdnJOB','/mygeneral/markread.cfm?ibox=3&frid="+frid+"');",1000);
}

//------------ PREVIEW EMAILS ------------//

var preS
var preT
var preO

function previewON(vFLD,vM,vBID,vEID,vIID,vLID,vFRM){
	preS=setTimeout("previewGO(" + vFLD + "," + vM + "," + vBID + "," + vEID + "," + vIID + "," + vLID + ",'" + vFRM + "')",500)
}

function previewGO(vFLD,vM,vBID,vEID,vIID,vLID,vFRM){
	$('mailPreViewer').style.display='block';
	$('mailPreViewer').innerHTML="<div style='float:left;width:556px;height:250px;padding-top:150px;text-align:center;font-size:110%'>One moment, loading preview</div>";
	// preT=setTimeout("genAJAX('mailPreViewer','/myemail/previewmail.cfm?fld=" + vFLD + "&m=" + vM + "&bid=" + vBID + "&eid=" + vEID + "&iid=" + vIID + "&lid=" + vLID + "&preview=1&fr='+vFRM)",500);
	cbAJAX('mailPreViewer','/myemail/previewmail.cfm?fld='+vFLD+'&m='+vM+'&bid='+vBID+'&eid='+vEID+'&iid='+vIID+'&lid='+vLID+'&preview=1&fr='+vFRM,10);
}

function previewOFF(){
	clearTimeout(preS);
	// clearTimeout(preT);
	// $('mailPreViewer').style.display='none';
	// $('mailPreViewer').innerHTML='';
}


//------------ CLOCK (refresh every minute) ------------//

function activClock(){
	genAJAX('dspClock','/includes/dsp_clock.cfm');
	cT=setTimeout('activClock()',60000);
}

//------------ MEDIA PLAYER ------------//

function viewPlayer(CLIP_UUID,n,u,p,div,file,type,media_url,thumb_url) {new Ajax.Updater(div, file, {parameters: {n:n,u:u,p:p},onComplete:function(request){callPlayer(type,CLIP_UUID,type,media_url,thumb_url);},onLoading:function(request){}});}
//this function top call the video player
function callPlayer(type,UUID,mediatype,mediaurl,thumburl){
		if(mediaurl != ''){
		var jsclippath=mediaurl;
		var jsthumbpath=thumburl;
		}
    else if(mediatype=='audio')
    {
    		var jsclippath = 'http://store.filepipes.com/dgate/archive/'+UUID+'/video_f7.flv';
		var jsthumbpath = 'http://store.filepipes.com/dgate/archive/'+UUID+'/audio_f7.jpg';
    }
    else
    {
		var jsclippath = 'http://store.filepipes.com/dgate/archive/'+UUID+'/'+type+'_f7.flv';
		var jsthumbpath = 'http://store.filepipes.com/dgate/archive/'+UUID+'/'+type+'_f7.jpg';}
		
		if(mediatype=='audio'){
		var so3 = new SWFObject("/flash/music_player.swf", "flashStandAlone", "326", "117", "8", "##000000", true);
		so3.addParam("allowScriptAccess","sameDomain");
		so3.addVariable("filePath", jsclippath);
		so3.addVariable("title", 'Audio Track');
		so3.addVariable("autoPlay", 1);
		so3.write("standAlonePlayer_content");
		}else{
		var so3 = new SWFObject("/flash/customPlayer_f9_326x271_v02.swf", "flashStandAlone", "326", "271", "9", "##000000", true);
		so3.addVariable("filePath", jsclippath);
		so3.addVariable("thumb", jsthumbpath);
		so3.addVariable("autoPlay", 1);
		so3.addVariable("color1", "0x000000");
		so3.addVariable("color2", "0xC2D023");
		so3.addVariable("logo", "/images/header/vid_logo_av.png");
		so3.addVariable("logoX", 5);
		so3.addVariable("logoY", 5);
		so3.addParam("allowScriptAccess","sameDomain");
		so3.addParam("allowFullScreen", "true");
		so3.write("standAlonePlayer_content");
		}}


//------------ FLOATBOOK ------------//
//------------ action=1 toggle view ------------//
//------------ action=2 expand only ------------//
//------------ action=3 collapse only ------------//

function callFloatbook(action,contact){
	//FLOATBOOK CANNOT BE TRIGGERED IN POPUP MODE
	if(vCompact==1){
		alert("Sorry your floatbook cannot be viewed in popup mode, there is not enough room here!")
	}
	else{
		if(action==1){
			if($('floatbook_content')){
				//--- BOOK OPEN SO CLOSE IT ---//
				collapseFloatbook();
			}
			else{
				//--- BOOK CLOSED SO OPEN IT ---//
				expandFloatbook(contact);
			}
		}
		if(action==2){
			if($('floatbook_content')){
				//--- IF BOOK ALREADY OPEN JUST ACTIVATE CONTACT ---//
				expandFloatbook(contact);
			}
			else{
				//--- IF BOOK NEEDS OPENING ---//
				expandFloatbook(contact);
			}
		}
		if(action==3){
			if($('floatbook_content')){
				//--- BOOK OPEN SO CLOSE IT ---//
				collapseFloatbook()
			}
		}
	}
}

function expandFloatbook(contact){
	$('structure').style.width='';
	$('fb_tab').style.right='295px';
	$('fb_tab').style.background='url(/images/backgrounds/fb_tab_close.png) top right no-repeat';
	$('fb_tray').style.display='block';
	if($('fb_throbber')){$('fb_throbber').style.display='block'};
	cbAJAX('fb_tray','/includes/modules/floatbook/dsp_default.cfm?a=2&fbu=' + contact,8);
}

function collapseFloatbook(){
	$('structure').style.width='997px';
	$('fb_tab').style.right='0px';
	$('fb_tab').style.background='url(/images/backgrounds/fb_tab_open.png) top right no-repeat';
	$('fb_tray').style.display='none';
	$('fb_tray').innerHTML='<img src=/images/icons/21-1.gif width=32 height=32>';
	genAJAX('hdnJOB','/includes/modules/floatbook/act_show.cfm?a=3');
}

function setActiveUser(contact,active_contact){
	$('fb_throbber').style.display='block';
	$('cl_act_uid').value=contact;
	$('ActiveUserName').style.marginTop="-30px";
	if($('fb_list_tr'+contact)){$('fb_list_tr'+contact).style.background='url(/images/backgrounds/book_name_highlight.png) top left no-repeat';}
	if($('fb_list_tr'+active_contact) && active_contact!=contact){$('fb_list_tr'+active_contact).style.background='url(/images/backgrounds/book_name.png) top left no-repeat';}
	cbAJAX('active_user','/includes/modules/floatbook/dsp_activeuser.cfm?a=2&fbu=' + contact,8);
}

var v1=30
var T2

function animateName(){
	if($('ActiveUserName')){
		if(v1==-2){
			clearTimeout(T2);
			$('ActiveUserName').style.marginTop="0px";
			$('fb_throbber').style.display='none';
			v1=30
		}
		else{
			$('ActiveUserName').style.marginTop= + v1 + "px";
			v1=v1-1;
			T2=setTimeout("animateName();",20);
		}
	}
}

function moveFloatbook(){
var Win = getInnerWindow();
	if(document.getElementById('floatbook_content') && Win[1] > 650){
		var scrollY
		var fbY
		if (document.all){
			scrollY=document.documentElement.scrollTop+20;
        		}
    			else{
    			scrollY=window.pageYOffset+20;
        		}
        	if(document.getElementById('floatbook').style.marginTop==''){
        		fbY=20
        	}
        	else{
        		fbY=document.getElementById('floatbook').style.marginTop
        	}
		document.getElementById('floatbook').style.marginTop=scrollY+'px';
	}
}

var TC

function activateChat(uid,uname){
	if(document.getElementById('chat_return')){
	TC = setInterval("if(document.getElementById('chat_return')){genAJAX('chat_return','/includes/modules/floatbook/act_chat_return.cfm?fbu=" + uid + "&uName=" + uname + "');}", 20000);
	}
}

function deactivateChat(){
	clearInterval(TC);
}

//------------ END FLOATBOOK STUFF ------------//



//------------ MISCELLANEOUS FUNCTIONS ------------//

function showFaqItem(id){
var el = null;
for(var i=0; (el = document.getElementById('faq_'+i)); i++){
var show = (el.id == id && el.style.display == 'none');
el.style.display = (show) ? 'block' : 'none' ;
}
}

// Limit textareas
function textareaLimit(field,limit){
	if (field.value.length>limit){
		field.value=field.value.substr(0,limit)
	}
}

function togglediv(toggleVal,toggleindex){
if(toggleVal==1)
{
	document.getElementById('calview'+toggleindex).style.display='block';
}
else if(toggleVal==2)
{
	document.getElementById('calview'+toggleindex).style.display='none';
}
else
{
	document.getElementById('calview'+toggleindex).style.display='none';
}
}
	
function togglediv2(toggleVal,toggleindex){
if(toggleVal==1)
{
	document.getElementById('calview2'+toggleindex).style.display='block';
}
else if(toggleVal==2)
{
	document.getElementById('calview2'+toggleindex).style.display='none';
}
else
{
	document.getElementById('calview2'+toggleindex).style.display='none';
}
}			

// Show/Hide the pitch rating facility 
function toggleform(toggleVal, toggleID){
	if(toggleVal==1){
		document.getElementById('form_ref_' + toggleID).style.display='block';
		document.getElementById('circle_ref_' + toggleID).style.display='none';
	}
	if(toggleVal==2){
		document.getElementById('form_ref_' + toggleID).style.display='none';
		document.getElementById('circle_ref_' + toggleID).style.display='block';
	}
	if(toggleVal==3){
		if(document.getElementById('circle_ref_' + toggleID).style.display=='block'){
		document.getElementById('form_ref_' + toggleID).style.display='block';
		document.getElementById('circle_ref_' + toggleID).style.display='none';
		}
		else{
		document.getElementById('form_ref_' + toggleID).style.display='none';
		document.getElementById('circle_ref_' + toggleID).style.display='block';
		}
	}
}

function toggleAnyDiv(DIV){
	if(document.getElementById(DIV).style.display=='block'){
	document.getElementById(DIV).style.display='none';
	}
	else{
	document.getElementById(DIV).style.display='block';
	}
}

function toggleAnyDivInline(DIV){
	if(document.getElementById(DIV).style.display=='none'){
	document.getElementById(DIV).style.display='inline';
	}
	else{
	document.getElementById(DIV).style.display='none';
	}
}

function toggleOverflow(DIV,flowSTYLE){
	var flowY = document.getElementById(DIV).style.overflowY;
	
	if(flowY=='hidden'){
		document.getElementById(DIV).style.overflowY=flowSTYLE;
	}else{
		document.getElementById(DIV).style.overflowY='hidden';
	}
}

function closeMediaViewer(){
	document.getElementById('mediaViewer').innerHTML='';
	document.getElementById('mediaViewer').style.display='none';
}

function getInnerWindow() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return [ myWidth, myHeight ];
}

function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}

function toggleMsgForm(){
    if(document.getElementById('formCORE').style.display=='block'){
    	if(document.getElementById('MESSAGE_BOX').value.replace(new RegExp(' ','g'),'').length){
    		if(confirm('Are you sure you want to hide the form?\nYou have text in the reply box')){document.getElementById('formCORE').style.display='none';}
    	} else {
    		document.getElementById('formCORE').style.display='none';
    	}
    } else {
    	document.getElementById('formCORE').style.display='block';document.getElementById('MESSAGE_BOX').focus();
    }
}

function jsDateFormat(date){
   if( isDate(date))   return 'new Date(#year(date)#, #(month(date)-1)#, #day(date)#, #hour(date)#, #minute(date)#, #second(date)#)';
   else return "null";
}

function toggleCheckAll(formVAL) {
  for (i = 0; i < formVAL.length; i++){
  	if($('check_all').checked == false){
  		formVAL[i].checked = false;
  	}
  	else{
  		formVAL[i].checked = true;
  	}
  }
}

function toggleEmail(mailID){
	//CLOSING MAIL
	if(document.getElementById('email' + mailID).style.display=='block'){
		document.getElementById('email' + mailID).style.display='none';
		}
	else{
    	//OPENING MAIL
		document.getElementById('email' + mailID).style.display='block';
    		//window.location = '#' + mailID;
    		//document.getElementById('divEmailInbox').scrollTop = document.getElementById('a' + mailID).offsetTop;
    		//alert(document.getElementById('a' + mailID).offsetTop)
	}
}

function showLoader(elem){
	document.getElementById(elem).innerHTML="<img src='/images/icons/21-1.gif' id='ajax_indicator' alt='busy' /> One moment, loading..."
}

function trim(str)
{
  return str.replace(/^\s+|\s+$/, '');
}

function validateEmail(fld) {
    var error="";
    var tfld = trim(fld.value);
    var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
    var illegalChars= /[\(\)\<\>\,\;\#\&\!\%\'\?\:\\\"\[\]]/ ;

    if (fld.value == "") {
        error = 1;					// DID NOT ENTER ANYTHING
    } else if (!emailFilter.test(tfld)) {
        error = 2;					// INVALID EMAIL
    } else if (fld.value.match(illegalChars)) {
        error = 3;					// ILLEGAL CHARS
    } else if (fld.value.match(' ')) {
        error = 4;					// WHITESPACE
    } else {
        error = 0;
    }
    return error;
}

function validateSpacemail(fld) {

	// CAPTURE WHAT THE USER ENTERED AND SET THE VARS
	var mailStr = trim(fld.value);
	var validateStr = "";
	var finalStr = "";
	var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
	var illegalChars= /[\(\)\<\>\,\;\#\&\!\%\'\?\:\\\"\[\]]/ ;
	var error=0;

	// USER ENTERED ANYTHING
	if (fld.value == "") {
		error = 1;
	} else {
    	
	    // GET THE STRING IN TO A COMMA DELIM ARRAY
	    mailStr = mailStr.replace(/ /g,"");
	    mailStr = mailStr.replace(/;/g,",");
	    mailStr = mailStr.replace(/,;/g,",");
	    mailStr = mailStr.replace(/,,/g,",");
	    mailStr = mailStr + "ENDOFSTR"
	    mailStr = mailStr.replace(",,ENDOFSTR","");
	    mailStr = mailStr.replace(",ENDOFSTR","");
	    mailStr = mailStr.replace("ENDOFSTR","");
	    mailStr = mailStr.split(",");

	    // LOOP THROUGH AND VALIDATE EACH MAIL
	    for(i = 0; i < mailStr.length; i++){
		validateStr = mailStr[i]
		// CHECK IF IS A SHORTHAND ALIAS AND CREATE A FULL ADDRESS
		if(validateStr.match("@")==null){validateStr = validateStr + "@spacemail.com"}
		// CHECK FOR REMOTE ADDRESSES AND REPLACE WITH NORMAL
		if(validateStr.match("\\*") && validateStr.match("@spacemail.com")){
			validateStr = validateStr.replace("@spacemail.com","");
			validateStr = validateStr.replace("*","@");
		}
		// VALIDATE EACH ADDRESS
		if(validateStr.match(illegalChars)){error = error + 1}
		if(!emailFilter.test(validateStr)){error = error + 1}
		// CAPTURE OUR REPLACE STRING
		finalStr = finalStr + validateStr + ", "
	    }
	}
	
	// RETURN THE RESULTS
	if(error==0){
		finalStr = finalStr + "ENDOFSTR"
		finalStr = finalStr.replace(", ENDOFSTR","");
		finalStr = finalStr.replace("ENDOFSTR","");
		fld.value = finalStr
		//alert(finalStr);
	}
	return error;
	
}

function WarningON(msg,msg1,msg2){
	document.getElementById('ACCOUNT_HELP').style.background='#FFFFCC';
	document.getElementById('ACCOUNT_HELP').style.border='2px solid #D0D0D0';
	document.getElementById('ACCOUNT_HELP').style.color='#333333';
	if(msg==1){
		document.getElementById('ACCOUNT_HELP').innerHTML = "<span class='red' style='font-size:140%'>Warning!</span><br /><br />Are you sure you want to change your name? This will immediately change your Spacemail&reg; Connection Point:<br/><br/><strong>" + msg1 + "</strong><br/><br />This old Connection Point will be quarantined for 3 months before being made available to the public again.<br /><br /><span class='red'><strong>Email sent to the old Connection Point will be stopped unless you run a secondary (see tip below).</strong></span><br /><br />To continue, update your name and hit submit to save the changes below.<br /><br /><strong>Tip:</strong> You may want run your old Connection Point in parallel to your new one for a while - see the <strong>Secondary Connection Points</strong> section in your Email Settings to see how to set this up.<br /><br />";
	}
	if(msg==2){
		document.getElementById('ACCOUNT_HELP').innerHTML = "FYI<br /><br />when you submit your new remote email account it will not appear here immediately.<br/><br/>A verification email will be sent to the new address to be added and once you say a quick hello back to us it will update here.";
	}
	if(msg==3){
		document.getElementById('ACCOUNT_HELP').innerHTML = "<span style='font-size:140%'>FYI</span><br /><br />Changing your secret name will customize your anonymous Smail&reg; address - however you will still be able to receive anonymous mail on both the custom Smail&reg; you set up and your default Smail&reg; number (below):<br/><br/><strong>" + msg1 + "</strong><br/><br />To remove your custom Smail&reg; at any point just clear the secret name field and hit submit to save.<br /><br /><span class='red'><strong>If you give up a previously used custom Smail&reg; address it is immediately released for use again, so make sure you do not have email being sent to it that you are bothered about!</strong></span><br /><br />";
	}
}

function updateUR(fldr,styl){
	var currUR = parseInt($('urVar').innerHTML);
	if(styl==-2){
	  var newUR = currUR + 1
	}else{
	  var newUR = currUR - 1
	}
	$('urVar').innerHTML = newUR;
	//if(newUR == 0){
	//  if(fldr==-2){
	//    if(Right($('nav_email').src,9)=='_flgC.png'){
	//      $('nav_email').src='/images/header/nav_' + styl + '_email_on_flgA.png'
	//    }else{
	//      $('nav_email').src='/images/header/nav_' + styl + '_email_on.png'
	//    }
	//  }else{
	//    if(Right($('nav_email').src,9)=='_flgC.png'){
	//      $('nav_email').src='/images/header/nav_' + styl + '_email_on_flgB.png'
	//    }else{
	//      $('nav_email').src='/images/header/nav_' + styl + '_email_on.png'
	//    }
	//  }
	//}
}

function Left(str, n){
    if (n <= 0)
        return "";
    else if (n > String(str).length)
        return str;
    else
        return String(str).substring(0,n);
}

function Right(str, n){
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}

function getQuerystring(url,qvar) { 
  var qStr = url.split("&"); 
  for (var i=0;i<qStr.length;i++) { 
    var pair = qStr[i].split("="); 
    if (pair[0] == qvar) { 
      return pair[1]; 
    } 
  } 
}

function previewCP(){
	// get values
	var FN = $('FIRSTNAME').value;
	var MN = $('MIDDLENAME').value;
	var SN = $('SURNAME').value;
	// format
	FN=FN.replace(/[^a-zA-Z0-9\s]+/g,'');
	MN=MN.replace(/[^a-zA-Z0-9\s]+/g,'');
	SN=SN.replace(/[^a-zA-Z0-9\s]+/g,'');
	FN=FN.replace(/\s+/g,'');
	MN=MN.replace(/\s+/g,'');
	SN=SN.replace(/\s+/g,'');
	// form address
	if(MN.length>0){
		var AD=FN+'.'+MN+'.'+SN+'@spacemail.com'
	}else{
		var AD=FN+'.'+SN+'@spacemail.com'
	}
	// output
	$('cp_addr').innerHTML=AD.toLowerCase();
}

function previewAM(SID){
	// get values
	var AM = $('ANAME').value;
	// format
	AM=AM.replace(/[^a-zA-Z0-9\s]+/g,'');
	AM=AM.replace(/\s+/g,'');
	// form address
	if(AM.length>0){
		var AD='smail.'+AM+'@spacemail.com'
	}else{
		var AD='smail.'+SID+'@spacemail.com'
	}
	// output
	$('am_addr').innerHTML=AD.toLowerCase();
}

var imgTDL
var imgBOX
var imgFRM

function previewImgIN(imgDIR,imgURL){
	if(document.getElementById('image_pop')){
		imgBOX=document.getElementById('image_pop');
		imgFRM=document.getElementById('image_pop_holder');
	} else {
		imgBOX=window.parent.document.getElementById('image_pop');
		imgFRM=window.parent.document.getElementById('image_pop_holder');
	}
	if(imgDIR==1){
		imgURL='/storage/email/attachments/inbox/'+imgURL
	}
	if(imgDIR==2){
		imgURL='/storage/email/attachments/outbox/'+imgURL
	}
	if(imgDIR==3){
		imgURL='/storage/files/'+imgURL
	}
	
	imgFRM.innerHTML='<img src="'+imgURL+'" width="400" alt="Image Preview" title="Image Preview" />';
	imgTDL=setTimeout("imgBOX.style.display='block'",500);
}

function previewImgOUT(){
	var imgBOX
	var imgFRM
	if(document.getElementById('image_pop')){
		imgBOX=document.getElementById('image_pop');
		imgFRM=document.getElementById('image_pop_holder');
	} else {
		imgBOX=window.parent.document.getElementById('image_pop');
		imgFRM=window.parent.document.getElementById('image_pop_holder');
	}
	imgBOX.style.display='none';
	imgFRM.innerHTML='One moment, rendering image...<br /><br /><img src="/images/icons/21-1.gif" width="20" height="20" alt="Rendering..." />';
	clearTimeout(imgTDL);
}

function myTest(){
	myT=setTimeout("alert('hi')",1000);
}

//------------ SAVING MAIL AS DRAFT UPDATER ------------//

var drT
var stopper=0

function saveDraftUpdater(u){
	setTimeout("exeUpdater(" + u + ")",5000);
}

function exeUpdater(u){
	if(stopper==2){
		cancelUpdater();
	}
	else{
		genAJAX('save_draft','/includes/modules/myemail/act_savedraft.cfm?updater=' + stopper + "&u=" + u + "&drID=" + $('drID').value + "&drTO=" + $('drTO').value + "&drCC=" + $('drCC').value + "&drSUBJECT=" + $('sendSUBJECT').value.replace(/[^a-zA-Z 0-9]+/g,'') + "&drBODY=" + $('sendBODY').value.replace(/[^a-zA-Z 0-9]+/g,''));
		drT=setTimeout("exeUpdater(" + u + ")",10000);
		stopper=stopper+1;
		//alert(stopper);
	}
}

function cancelUpdater(){
	clearTimeout(drT);
	stopper=0
}


//------------ GENERIC FILTER LIST ------------//

function search_list(TYPE_BOX) {
  $$('.search_row').each(
	function(elm) {
	  var search_elm = Element.down(elm, '.search_elm').innerHTML;
	  if (search_elm.toLowerCase().include($F(TYPE_BOX).toLowerCase())) {
		elm.show();
	  } else {
		elm.hide();
	  }
	}
  );
}


//------------ CLICK ANYWHERE DOCUMENT FUNCTION CALLS (UNDER CONSTRUCTION) ------------//

var ShiftBtn=false;

function createListener(elem){
	document.getElementById(elem).addEventListener('click', function(e){alert('yes')}, true);
}
function removeListener(elem){
	document.getElementById(elem).removeEventListener('click', function(e){alert('yes')}, true);
}

function genClick(){
	if(document.getElementById("genClickCall")){genClickActivate(document.getElementById("genClickCall").innerHTML)}
}

function genClickActivate(Fn){
	//---CLOSE EMAIL WHEN CLICKING OUTSIDE THE BOX---//
	if(Fn=="F1"){
		//if(document.getElementById('mailViewer').style.display=='block'){document.getElementById('mailViewer').style.display='none'}
		//alert("test");
	}
}

function captureKeyAction(evt) {
	var keyID;
	if(window.event){
		keyID = window.event.keyCode;
	}else if(evt){
		keyID = evt.which;
	}else{
		return false;
	}
	if(keyID==16){ShiftBtn=true};
	return true;
}

function MakeFalse(){
	ShiftBtn=false;
}

function ShiftSelect(boxID,totalBoxes){
	if(ShiftBtn){
		for (i = 1; i <= totalBoxes; i++)
		{
		if(document.getElementById("SELECT_MAIL" + i).checked==true){
			for (i = i; i <= boxID; i++)
				document.getElementById("SELECT_MAIL" + i).checked=true;
			}
		}
  	}
}


//ADD THIS DIV IN YOUR PAGE TO ACTIVATE CLICK ANYWHERE
//<div id="genClickCall" style="float:left;display:none">F1</div>

document.onkeydown = captureKeyAction;
document.onkeyup = MakeFalse;
//document.onclick=genClick;


//------------ END CLICK ANYWHERE ------------//
