/*
(C) AEwebworks Software Development Ltd., 2002-2003
IMPORTANT: This is a commercial software product and any kind of using it must agree
to the AEwebworks Software Development Ltd. license agreement. It can be found at
http://www.aewebworks.com/license.htm
This notice may not be removed from the source code.
*/

/*
 * iPhone                    iphone
 * Nokia N900                rx-51 n900
 * Nokia N96                 nokian96-1
 * HTC Diamond               htc_diamond
 * HTC Dream                 htc_dream
 * HTC Android               android dev phone 1
 * Motorolla A3100           mot-a3100
 * HTC Pro                   iemobile
 *
 */
var agent=navigator.userAgent.toLowerCase();
var tinymceIsSupported = true;
var mobilePhoneReg = new RegExp("(iphone|rx-51 n900|nokian96-1|htc_diamond|htc_dream|android dev phone 1|mot-a3100|iemobile)");
if (mobilePhoneReg.test(agent)) {
  tinymceIsSupported = false;
}
//var tinymceIsSupported = false; //For testing purposes only

function removeNode(nodeId) {
	if (dojo.byId(nodeId)) {
		node = dojo.byId(nodeId);
		parent = node.parentNode;
		parent.removeChild(node);
	}
	return true;
}

function preserveLineBreaks(txt,obj) {
	var lines = txt.split("\n");
	if (lines.length > 0) {
		for (var i=0; i<lines.length; i++) {
			if (lines[i].length > 0) {
				obj.appendChild(document.createTextNode(lines[i]));
			}
			if (i + 1 < lines.length) {
				obj.appendChild(document.createElement("br"));
			}
		}
	} else {
		obj.appendChild(document.createTextNode(txt));
		//alert('we have no lines');
	}
}

function setNumberOfChars(textfield, displayfield, max) {
	if (document.getElementById) { // DOM3 = IE5, NS6
		document.getElementById(displayfield).value = document.getElementById(textfield).value.length;
		if (document.getElementById(displayfield).value > max) {
			return false;
		}
	}	else {
		if (document.layers) { // Netscape 4
			document.displayfield.value = document.displayfield.value.length;
			if (document.displayfield.value > max) {
				return false;
			}
		} else { // IE 4
			document.all.displayfield.value = document.all.textfield.value.length;
			if (document.all.displayfield.value > max) {
				return false;
			}
		}
	}
	return true;
}

function toggleCheckboxes(prefix,force) {
	var retval = false;
	var count = 0;
	dojo.query('input[id^="'+prefix+'"]').forEach(function(x,idx) {
		if (count === 0) {
	  	if (force !== undefined) {
				retval = force;
			} else {
				retval = (x.checked)?false:true;
			}
		}
		x.checked = retval;
		count++;
	});
	return retval;
} 


var win = "width=400,height=500,left=100,top=100,copyhistory=no,directories=no,menubar=no,location=no,resizable=no,scrollbars=yes";
var win_s = "width=400,height=420,left=100,top=100,copyhistory=no,directories=no,menubar=no,location=no,resizable=no,scrollbars=yes";

function ShowHideFaq(id,idimg,openimg,closeimg) {
	if (document.getElementById(id)) {
		if (document.getElementById(id).style.display == 'none')	{
			document.getElementById(id).style.display = 'block';
			document.getElementById(idimg).src = openimg;
		} else {
			document.getElementById(id).style.display = 'none';
			document.getElementById(idimg).src = closeimg;
		}
	}
}

//Use this function to automatically show/hide an inline element
//In other words, if you do NOT want it to collapse/expand
function ShowHideInline(name) {
	var vista = '';
	if (document.layers) {
		vista = (document.layers[name].visibility == 'hide') ? 'show' : 'hide';
		document.layers[name].visibility = vista;
	}	else if (document.all) {
		vista = (document.all[name].style.visibility == 'hidden') ? 'visible'	: 'hidden';
		document.all[name].style.visibility = vista;
	} else if (document.getElementById)	{
		vista = (document.getElementById(name).style.visibility == 'hidden') ? 'visible' : 'hidden';
		document.getElementById(name).style.visibility = vista;
	}
}

//Use this function to manually show/hide an inline element
//In other words, if you do NOT want it to collapse/expand
function ShowHideInlineMan(name,doit) {
	var vista = '';
	if (document.layers) {
		vista = (doit == 'hidden') ? 'hide' : 'show';
		document.layers[name].visibility = vista;
	}	else if (document.all) {
		vista = (doit == 'hidden') ? 'hidden' : 'visible';
		document.all[name].style.visibility = vista;
	} else if (document.getElementById)	{
		vista = (doit == 'hidden') ? 'hidden' : 'visible';
		document.getElementById(name).style.visibility = vista;
	}
}


//Use this function to manually show/hide an inline element
//if you do want it to collapse/expand
function ShowHideSpan(id) {
	var obj = document.getElementById(id);
	if (obj) {
		if (obj.style.display == 'none') {
			obj.style.display = 'inline';
		} else {
			obj.style.display = 'none';
		}
	}
}
	
//Use this function to show/hide a block element (div, tr etc)
//In other words, if you want it to collapse/expand
//Params: blockId (the id of the element)
//        display ('none' or 'block')
//If 'display' is omitted the element will open if it's closed and vise-versa
function ShowHideBlock(blockId,display) {
  if (!dojo.byId(blockId)) {
		return false;
	}
	var obj = dojo.byId(blockId);
  var tagName = obj.tagName.toLowerCase();

  //Just do the uppersite if display is omitted
  if (display === undefined) {
    display = (obj.style.display == 'none')?'block':'none';
  }
  
  if (display == 'none') {
    obj.style.display = 'none';
  } else if (display == 'block' && tagName != 'tr') {
    obj.style.display = 'block';
  } else {
    try {
      //Some browsers do not understand 'block' for table rows
      obj.style.display = 'table-row';        
    } catch(e) {
      obj.style.display = 'block';
    }
  }
  return obj.style.display;
}


function blockShiftMulti() {
  if (!arguments.length) {
	 	return false;
	}
	var i;
	//Show the first and hide the others
	ShowHideBlock(arguments[0],'block');
	for (i=0; i<arguments.length; i++) {
		if (i > 0) {
			ShowHideBlock(arguments[i],'none');
		}
	}
	return true;
}

//This function will tell if a block is going to be visible or not
function IsVisibleBlock(id) {
	var vista = '';
	if (document.getElementById) { // DOM3 = IE5, NS6
		vista = (document.getElementById(id).style.display == 'block') ? 'none' : 'block';
	}	else {
		if (document.layers) { // Netscape 4
			vista = (document.id.display == 'block') ? 'none' : 'block';
		} else { // IE 4
			vista = (document.all.id.style.display == 'block') ? 'none' : 'block';
		}
	}
	return vista;
}

//DEPRECATED: use ShowHideBlock() instead
//Use this to manually show or hide a table row
function ShowHideRowMan(id,doit) {
	var body;
 	body=document.getElementById(id);
  if (body) {
 		if (doit == 'none') {
      body.style.display='none';
		} else if (doit == 'block') {
    	try {
      	body.style.display='table-row';
				
      } catch(e) {
      	body.style.display = 'block';
      }
    }
  }
	return true;
}

//This function show/hide a table row automatically
function ShowHideRow(id) {
	var isOpen = 0;
	var body;
 	body=document.getElementById(id);
  if (body) {
 		if (body.style.display == 'none') {
			isOpen = 1;
    	try {
      	body.style.display='table-row';
				
      } catch(e) {
      	body.style.display = 'block';
      }
    } else {
			isOpen = 0;
      body.style.display = 'none';
    }
  }
	return isOpen;
}
 
//Move rows around in a table
//See examples of use on page 78 and 90
function moverow(x,row) {
  if (x=='up' && row.previousSibling) {
    row.parentNode.insertBefore(row, row.previousSibling);
  } else if (x=='down' && row.nextSibling) {
    row.parentNode.insertBefore(row.nextSibling,row);
  } else if (x=='first') {
    row.parentNode.insertBefore(row, row.parentNode.firstChild);
  } else if (x=='last') {
    row.parentNode.insertBefore(row,null);
	}
}

//This function will select all options in a multiple select box
function multipleBoxSelectAll(id) {
	var obj = document.getElementById(id);
	if (obj.options.length > 0) {
		for (var i=0; i<obj.options.length; i++) {
			obj.options[i].selected=true;
		}
	}
}

//Equivalent to PHP's nl2br();
function nl2br(obj,text){
	var re_nlchar;
	var lines;
	var linetext;
	var breakNode;

  if (text.indexOf("\r\n") > -1) { 
  	re_nlchar = "\r\n";
  } else if (text.indexOf("\r") > -1) {
    re_nlchar = "\r";
  } else if(text.indexOf("\n") > -1) {
    re_nlchar = "\n";
  }
	
  if (re_nlchar !== '') {
		lines = text.split(re_nlchar);
		for (var i = 0; lines.length > i; i++) {
			linetext = document.createTextNode(lines[i]);
			breakNode = document.createElement("BR");
			obj.appendChild(linetext);
			obj.appendChild(breakNode);
		}
	}
}

function docOpen(text) {
	var newWindow=window.open('','','toolbar=no,resizable=yes,scrollbars=yes,width=400,height=300');
	newWindow.document.open("text/html");
	newWindow.document.write(unescape(text));
	newWindow.document.close();
}

//Get height of browser
function getWindowHeight() {
	var windowHeight = 0;
	if (typeof(window.innerHeight) == 'number') {
		windowHeight = window.innerHeight;
	} else {
		if (document.documentElement && document.documentElement.clientHeight) {
			windowHeight = document.documentElement.clientHeight;
		}	else {
			if (document.body && document.body.clientHeight) {
				windowHeight = document.body.clientHeight;
			}
		}
	}
	return windowHeight;
}

var IE = document.all?true:false;
if (!IE) { document.captureEvents(Event.MOUSEMOVE); }
document.onmousemove = getMouseXY;
var mouseX;
var mouseY;
function getMouseXY(e) {
  if (IE) { // grab the x-y pos.s if browser is IE
		mouseX = event.clientX + document.documentElement.scrollLeft;
		mouseY = event.clientY + document.documentElement.scrollTop;
	} else {  // grab the x-y pos.s if browser is NS
	  mouseX = e.pageX;
	  mouseY = e.pageY;
	}  
	// catch possible negative values in NS4
	if (mouseX < 0){ mouseX = 0; }
	if (mouseY < 0){ mouseY = 0; }  
	// show the position values in the form named Show
	// in the text fields named MouseX and MouseY
	var position = new Object();
	position.x = mouseX;
	position.y = mouseY;
	return position;
}
		
function positionAboveOrBelow(opener, box,vPos) {
	box.style.display = 'block';
  //Get the position of the opener
	var position = getPosition(opener);
	var x  = position.x;
	var y  = position.y;
	
	//Get width of opener and box
	var openerWidth = opener.offsetWidth;
	var openerHeight = opener.offsetHeight;
	var boxWidth = box.offsetWidth;
	var boxHeight = box.offsetHeight;

	//x position of start and end of visible area
	var winStart = document.body.scrollTop;
	var winEnd   = winStart + getWindowHeight();

	//Number of pixels above and below the opener
	var above = y - winStart;
	var below = winEnd - y;

	if (above > below) {
		box.style.top = (y - boxHeight - 10) + 'px';
	} else {
		box.style.top = (y + openerHeight + 10) + 'px';
	}
	//Set vertical position
	if (vPos == 'center') {
		//Center the box over/below the opener
		if (openerWidth > boxWidth) {
			box.style.left = x + ((openerWidth - boxWidth) / 2) + 'px';
		} else {
			box.style.left = x - ((boxWidth - openerWidth) / 2) + 'px';
		}
	} else if (vPos == 'left') {
		//The left y value of box and opener must be equal
		box.style.left = x + 'px';
	} else if (vPos == 'right') {
		//The y value of the right side of box and opener must be equal
		box.style.left = (x + openerWidth - boxWidth)+'px';
	}
}

/***************************************
 *    PROFILE THUMBNAIL FUNCTIONS      *
 ***************************************/
 
function showProfileThumb(element,picture,adjust) {
  thumber = document.getElementById('thumb_pop');
  thumber_img = document.getElementById('thumb_pop_img');
	thumber_img.src = picture;
	thumber.style.top = mouseY + "px";
	thumber.style.left = (mouseX - 130) + "px";
	thumber.style.display = "block";
}

function hideProfileThumb() {
	thumber = document.getElementById('thumb_pop');
  thumber_img = document.getElementById('thumb_pop_img');
	thumber_img.src = "/images/loading.gif";
	thumber.style.display = "none";
}


function getPosition(element) {
	/* This funtion was grapped from http://js-tut.aardon.de/js-tut/tutorial/position.html */
	/* der Aufruf dieser Funktion ermittelt die absoluten Koordinaten	des Objekts element */

  var elem=element,tagname="",x=0,y=0;
  
	/* solange elem ein Objekt ist und die Eigenschaft offsetTop enthaelt
  wird diese Schleife fuer das Element und all seine Offset-Eltern ausgefuehrt */
  
	while (elem && (typeof(elem)=="object") && (typeof(elem.tagName)!="undefined")) {
    y+=elem.offsetTop;     /* Offset des jeweiligen Elements addieren */
    x+=elem.offsetLeft;    /* Offset des jeweiligen Elements addieren */
    tagname=elem.tagName.toUpperCase(); /* tag-Name ermitteln, Grossbuchstaben */

		/* wenn beim Body-tag angekommen elem fuer Abbruch auf 0 setzen */
    if (tagname=="BODY") {
      elem=0;
		}

		/* wenn elem ein Objekt ist und offsetParent enthaelt
   	Offset-Elternelement ermitteln */
   	if (typeof(elem)=="object") {
     	if (typeof(elem.offsetParent)=="object") {
       	elem=elem.offsetParent;
			}
		}
	}
	/* Objekt mit x und y zurueckgeben */
  position=new Object();
  position.x=x;
  position.y=y;
  return position;
}


/*********************************
 * Functions for inbox data tree *
 *********************************/

function showMailboxFolderDialog(element) {
	var pos = getPosition(element);
  var form = document.getElementById('mailboxFolderDialog');
	form.style.top = (pos.y + 15) + "px";
	form.style.left = (pos.x - 18) + "px";
	form.style.display = "block";
}

function hideMailboxFolderDialog() {
  var form = document.getElementById('mailboxFolderDialog');
	form.style.display = 'none';
}

function toggleMailbox(img) {
	var obj = document.getElementById('inboxParent');
	var cur = obj.style.display;
	if (cur == 'none') {
		obj.style.display = 'block';
		img.src="images/menu_minus.gif";
	} else {
		obj.style.display = 'none';
		img.src="images/menu_plus.gif";
	}
}

//Adding a new item
function addItem(newName) {
	if (!newName || newName.length < 1) { 
		return true;
	}
	args = {"action":"create","folderName":dojo.byId('folderName').value};
	jsnResult = elementCall({"action":"inbox_folder","args":args});
	if (jsnResult !== undefined && jsnResult.success == 1) {
		var folderId = jsnResult.result.folderId;
		//Get the last row
		var tbody=document.getElementById('folderTbody');
		var tbodyRows = tbody.getElementsByTagName('TR');
		var lastRow = tbodyRows[tbodyRows.length-1];
		var spacerRow = tbodyRows[tbodyRows.length-2];

		//Change the dotted beam icon of the last row
		var firstTd = lastRow.getElementsByTagName('TD')[0];
		var img = firstTd.firstChild;
		img.src = 'images/l_dot.gif';
					
		//Clone it for the new row (include children)
		var newRow = lastRow.cloneNode(true);
		//Clone the row for extra space
		var newSpacerRow = spacerRow.cloneNode(true);

		//**** Make necessary changes to the new row **** //
				
		//New id for the tr tag
		newRow.id = 'iftr_'+folderId;
		//New id for the td tag
		firstTd = newRow.getElementsByTagName('TD')[0];
		firstTd.id = 'iftd_'+folderId;
		//New dotted beam on td's first child
		img = firstTd.firstChild;
		img.src = 'images/l_dot_h.gif';
		img.id = 'ifimg_'+folderId;
		//New folder icon on td's second child
		img = firstTd.childNodes[1];
		img.src = 'images/closedfolderTree.gif';
		//New link on second td
		var secondTd = newRow.getElementsByTagName('TD')[1];
		secondTd.innerHTML = '<a class="noaccess" href="'+'/?p=inbox&folderId='+folderId+'">'+newName+' (0)</a>';
		tbody.appendChild(newSpacerRow);
		tbody.appendChild(newRow);
		location.href='/?p=inbox';	
	}
	return true;
}

function addStandbyProfile(nickname) {
  var jsnResult = ajaxCall({"action":"standby_handler","task":"add","nickname":nickname});
	//alert(dumpObj(jsnResult, 'jsnResult', "", 2));
	if (jsnResult.error == 1) {
		alert(jsnResult.message);
		return;
	}

	var tbody = dojo.byId('profile_table');
	var table = tbody.parentNode;
	table.style.display = 'block';
	var tr = document.createElement('tr');
	tr.id = 'trProfile'+jsnResult.result.profileId;
	tr.className = 'cont_even';
	var tdName = document.createElement('td');
	var tdBtn = document.createElement('td');
	var imgBtn = document.createElement('img');
	imgBtn.src = 'images/delete.gif';
	imgBtn.onclick = function () { removeStandbyProfile(jsnResult.result.profileId); };
	var text = getTranslation(36,'remove_profile');
	imgBtn.alt = text;
	imgBtn.title = text;
	tdName.appendChild(document.createTextNode(nickname));
	tdBtn.appendChild(imgBtn);
	tr.appendChild(tdName);
	tr.appendChild(tdBtn);
	tbody.appendChild(tr);
  var tbodyRows = tbody.getElementsByTagName('tr');
	var firstRow = tbodyRows[0];
	if (tbodyRows[1]) {
		tr.className = (tbodyRows[1].className == 'cont_even') ? 'cont_odd' : 'cont_even';
	}
	moverow('first',tr);
	moverow('first',firstRow);
}

function removeStandbyProfile(id) {
	var jsnResult = ajaxCall({"action":"standby_handler","task":"remove","id":id});
	if (jsnResult.error == 1) {
		alert(jsnResult.message);
		return;
	}
	var tbody = dojo.byId('profile_table');
	if (dojo.byId('trProfile'+id)) {
		tbody.deleteRow(dojo.byId('trProfile'+id).rowIndex);
	}
	var tbodyRows = tbody.getElementsByTagName('tr');
	if (!tbodyRows[1]) {
		tbody.parentNode.style.display = 'none';
	}
}

function handleStandbyList(box) {
  var value = (box.checked) ? 1 : 0;
  var objResult = dojo.byId(box.id+'_result');
	var jsnResult = ajaxCall({"action":"standby_handler","task":"box","name":box.id, "value":value});
	var text = jsnResult.message;
	if (jsnResult.error == 1) {
		objResult.className = 'err';
	} else {
		objResult.className = 'msg';
	}
	objResult.innerHTML = text;
	objResult.style.display = 'inline';
	blinkText(objResult.id, 500, 3);
}

function ajaxCall(jsnParams) {
  var jsnResult,
      strUrl = 'ajax.php',
      strHandle = 'json';
 
  jsnResult = dojo.rawXhrPost({
    url: strUrl,
    sync: true,
    handleAs: strHandle,
    postData: dojo.toJson(jsnParams),
    load: function(data,ioArgs) {
      return data;
    },
    error: function(data,ioArgs) { return data; }
  });
	//alert(dumpObj(jsnResult.results[0], 'jsnResult', "", 2));
  return eval(jsnResult.results[0]);
}

var fileuploadDeferred = false;
function fileupload(formId,functionName) {
	if (fileuploadDeferred) {
		fileuploadDeferred.cancel();
	}
	//Tell user to wait
	if (dojo.byId('modalFileUploadSubmit') && dojo.byId('modalFileUploadWait')) {
		ShowHideBlock('modalFileUploadSubmit','none');
		ShowHideBlock('modalFileUploadWait','block');
	}
	var fileuploadDeferred = dojo.io.iframe.send({
		form: formId,
		handleAs: 'json',
		timeout:30000,
		load: function(data) { return data; },
    error: function(data,ioArgs) { 
			alert(data.message);
			if (data.message === 'Deferred Cancelled') {
				return data;
			}
		}
	});

	fileuploadDeferred.addCallback (
		function (data) {
			//Reset the field
			if (dojo.byId('modalFileUploadField')) {
				dojo.byId('modalFileUploadField').value = '';
			}
			//Give the button back
			if (dojo.byId('modalFileUploadSubmit') && dojo.byId('modalFileUploadWait')) {
				ShowHideBlock('modalFileUploadSubmit','block');
				ShowHideBlock('modalFileUploadWait','none');
			}
			//Call another function
			eval(functionName+'(data)');
		}
	);

	fileuploadDeferred.addErrback (
		function (data) {
			alert('error: '+data.message);
		}
	);
}

function elementCall(jsnParams) {
  var jsnResult,
      strUrl = 'element.php',
      strHandle = 'json';
 
	jsnResult = dojo.rawXhrPost({
    url: strUrl,
    sync: true,
    handleAs: strHandle,
    postData: dojo.toJson(jsnParams),
    load: function(data,ioArgs) {
      return data;
    },
    error: function(data,ioArgs) { return data; }
  });
	//alert(dumpObj(jsnResult.results[0], 'jsnResult', "", 4));
  return eval(jsnResult.results[0]);
}

function getIframe() {
	var box = document.createElement('iframe');
	box.allowtransparency = 'true';
	box.frameborder = '0';
	box.scrolling = 'no';

	document.body.appendChild(box);

  box.doc = null;
  if(box.contentDocument) { 
    // Firefox, Opera  
    box.doc = box.contentDocument;  
  } else if(box.contentWindow)   {
    // Internet Explorer  
    box.doc = box.contentWindow.document;  
  } else if(box.document) {
    // Others?  
    box.doc = box.document;  
	}
  if (box.doc === null) { return false; }

  //Put the iframe in a state where we can use appendChild
  box.doc.open();  
  box.doc.close();

  box.doc.body.style.margin = '0';
  box.doc.body.style.backgroundColor = 'transparent';
	return box;
}


function modalDialogFatal(error_text,error_from,alpha,title_text,title_from) {
	//If error_from is not set, it means we have translated text
	if (error_from === undefined || error_from === false || error_from === null) {
		//alert('error_from is undefined:');
		url = {'error_text':error_text};
	} else {
		//alert('error_from is defined: '+error_from);
		url = {'error_text':error_text,'error_from':error_from};
	}
	if (title_text !== undefined && title_from !== undefined) {
		url['title_text'] = title_text;
		url['title_from'] = title_from;
	}
	modalDialog('modalError','modalFatal',url,alpha);
}

function modalDialogSuccess(msg_text,msg_from,alpha,title_text,title_from) {
	url = {'msg_text':msg_text,'msg_from':msg_from};
	if (title_text !== undefined && title_from !== undefined) {
		url['title_text'] = title_text;
		url['title_from'] = title_from;
	}
	modalDialog('modalSuccess','modalSuccess',url,alpha);
}

function modalDialogConfirm(confirm_text,confirm_from,confirm_function,alpha,title_text,title_from) {
	//If confirm_from is not set, it means we have translated text
	if (confirm_from === undefined || confirm_from === false || confirm_from === null) {
		url = {'confirm_text':confirm_text};
	} else {
		url = {'confirm_text':confirm_text,'confirm_from':confirm_from};
	}
	if (title_text !== undefined && title_from !== undefined) {
		url['title_text'] = title_text;
		url['title_from'] = title_from;
	}
	url['function'] = confirm_function;
	modalDialog('modalConfirm','modalConfirm',url,alpha);
}

function modalDialog(dialogId,action,url,alpha) {
	var dim = getViewportDimensions();
	alpha = (alpha === undefined)?80:alpha; 
	if (typeof url == 'object') {
		url.w = dim.width;
		url.h = dim.height;
	} else {
		url = url+'&w='+dim.width+'&h='+dim.height;
	}
	content = getContent(0,action,url);
	TINY.box.show(content.result,0,0,0,0,0,1,alpha);
}

function modalImageLoad(w,h,n,p) {
	var img = dojo.byId('modalImage');
	var title = dojo.byId('modalTitle');
	img.src = p;
	img.style.width = w+'px';
	img.style.height = 'auto';
	title.innerHTML = n;
}

function getPageDimensions() {
	var dim = getViewportDimentions();
	var scroll = (document.all)?document.documentElement.scrollTop:window.pageYOffset;
}

function getViewportDimensions() {
  var intH = 0, intW = 0;
    
  if (self.innerHeight) {
    intH = window.innerHeight;
    intW = window.innerWidth;
  } else {
    if (document.documentElement && document.documentElement.clientHeight) {
      intH = document.documentElement.clientHeight;
      intW = document.documentElement.clientWidth;
    } else {
      if(document.body) {
        intH = document.body.clientHeight;
        intW = document.body.clientWidth;
      }
    }
  }
  return {
    height: parseInt(intH, 10),
    width: parseInt(intW, 10)
  };
}

function centerElement(elem) {
  var viewport = getViewportDimensions();
  var left = (viewport.width === 0) ? 50 : parseInt((viewport.width - elem.offsetWidth) / 2, 10);
  var top = (viewport.height === 0) ? 50 : parseInt((viewport.height - elem.offsetHeight) / 2, 10);

	var scroll = (document.all)?document.documentElement.scrollTop:window.pageYOffset;
  elem.style.left = left + 'px';
  elem.style.top = top + scroll + 'px';
}

function dialogClose(className) {
	var elmts = getElementsByClassName(className,'div',false);
  for(var i=0; i<elmts.length; i++) {
    elmts[i].style.display = 'none';
  }
}

function getElementsByClassName(className, tag, elm){
	var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
	if (tag === undefined || tag === false) { tag = "*"; }
	if (elm === undefined || elm === false) { elm = document; }
	var elements = new Array();
	if (tag == "*" && elm.all) {
		elements = elm.all;
	} else {
		elements = elm.getElementsByTagName(tag);
	}
	var returnElements = [];
	var current;
	var length = elements.length;
	for(var i=0; i<length; i++){
		current = elements[i];
		if(testClass.test(current.className)){
			returnElements.push(current);
		}
	}
	return returnElements;
}

//Function to display tooltips over active mutual icons
function tooltipMutual(type,id,no,date,doit) {
	//Close all other simpleDialogs on the page by className
	dialogClose("simpleDialog");
	var opener = dojo.byId(id+'_'+type);
	var boxId = id+'_'+type+'Tooltip';
	if (doit == 1) {
		var box = document.createElement('div');
		box.className = 'simpleDialog';
		box.style.padding = '10px';
		box.id = boxId;
		var txtTop = mutualTxt[type.replace('img','txt')];
    var txtNo = mutualTxt[type.replace('img','txtNo')];
    var txtLatest = mutualTxt[type.replace('img','txtLatest')];
		box.appendChild(document.createTextNode(txtTop));
		box.appendChild(document.createElement('br'));
		box.appendChild(document.createTextNode(txtNo+'\u00A0'+no));
		box.appendChild(document.createElement('br'));
		box.appendChild(document.createTextNode(txtLatest+'\u00A0'+date));
		document.body.appendChild(box);
		positionAboveOrBelow(opener,box,'right');
	}
}

//Create blinking text. The text must be hidden initially
//Parameters:
//  id				The value of the elements id attribute
//  interval	Blinking interval in milliseconds
//  limit     Maximum number of times to blink
//            An even number will hide the text the last time
//            An uneven number will leave the text displayed
function blinkText(id, interval, limit) {
	var count = 0;
	var sid = setInterval (doBlick, interval);
	function doBlick() {
		count++;
		ShowHideInline(id);
		if (count == limit) {
			clearInterval(sid);
		}
	}
}

function isFormChanged(formId) {
	var formObj = dojo.byId(formId);
	if (!formObj) {
		return false;
	}
	var max = formObj.elements.length;
	for(var i=0; i< max; i++) {
		var field = formObj.elements[i];
		//Text fields
		if (field.type == "textarea" || field.type =="text") {
			if(field.value != field.defaultValue) {
				return true;
			}
		}
		//Select boxes
		if (field.type == "select-one" || field.type == "select-multiple") {
			for (var k=0; k<field.options.length; k++) {
				if (field.options[k].selected != field.options[k].defaultSelected) {
					return true;
				}
			}
		}
		//Checkboxes and radios
		if (field.type =="checkbox" || field.type =="radio") {
			if(field.checked != field.defaultChecked) {
				return true;
			}
		}
	}
	return false;
}

var translatedText = new Array();
function getTranslation(page, txt,html) {
	html = (html === undefined)?0:1;
	if (translatedText[page+txt+html] != undefined) {
		return translatedText[page+txt+html];
	}
	var translation =	dojo.xhrGet({
			url: 'translationJs_handler.php',
			sync:true,
			content: {
								page: page,
								txt: txt,
								html: html
							 },
			load: function(data,ioArgs) {
					return data;
			},
			error: function(data,ioArgs) { return data; },
			handleAs: "text"
		});
	//alert(dumpObj(translation, 'translation', "", 2));
	var retval =  eval(translation.results[0]);
	translatedText[page+txt+html] = retval;
	return retval;
}

function url2json(url) {
  if (url.indexOf("?") == -1) {
    return false;
  } 
  var query = url.substr(url.indexOf("?")+1);
  var vars = query.split("&");
  var jsonUrl = '{';
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0].length > 0 && pair[1]) {
      jsonUrl = jsonUrl + '"'+pair[0]+'":"'+pair[1]+'"';
      if (i+1 < vars.length) {
        jsonUrl = jsonUrl + ',';
      }
    }
  }
  jsonUrl = jsonUrl + '}';
  if (jsonUrl == '{}') {
    return false;
  } else {
		return eval('('+jsonUrl+')');
  }
} 

function groupIsForbidden(url) {
  var args = url2json(url);
	if (!args) {
		return false;
	}
	var forbidden = dojo.xhrGet({
			url: 'access_group_handler.php',
			sync:true,
			content: args,
			load: function(data,ioArgs) {
				if (data.substring(0,1) == '0') {
					return false;
				} else {
					return "'"+data+"'";
				}
			},
			error: function(data,ioArgs) { return data; },
			handleAs: "text"
		});
	return eval(forbidden.results[0]);
}

function profileIsForbidden(url) {
  var args = url2json(url);
	if (!args) {
		return false;
	}
	var forbidden = dojo.xhrGet({
			url: 'access_profile_handler.php',
			sync:true,
			content: args,
			load: function(data,ioArgs) {
				if (data.substring(0,1) == '0') {
					return false;
				} else if (!data) {
					return 'fatal_error';
				} else {
					return "'"+data+"'";
				}
			},
			error: function(data,ioArgs) { return data; },
			handleAs: "text"
		});
	return eval(forbidden.results[0]);
}

function openLink(type,url,popup) {
  var args = url2json(url);
	var jsnResult = ajaxCall({"action":"access_control","type":type,"args":args});
	var text = jsnResult.message;
	if (jsnResult.error == 1) {
		alert(text);
	} else if (jsnResult.success == 1) {
	  if (popup === false || popup === '0' || popup === 0 || popup == 'false') {
			location.href = url;
		} else {
			window.open(url,'',popup);
		}
	}
}

function getContent(boxId,action,url) {
	var args;
	args = (typeof url == 'string')?url2json(url):url;
	var jsnResult = elementCall({"action":action,"args":args});
	var text = jsnResult.message;
	if (jsnResult.error == 1) {
		alert(text);
	} else if (jsnResult.success == 1) {
	  if (dojo.byId(boxId) && boxId !== 0 && boxId !== '0') {
			dojo.byId(boxId).innerHTML = jsnResult.result;
		} else {
			return jsnResult;
		}
	}
	return false;
}

function toolTipBoxIframe (width,position,opener,id,page,txt) {
	var box = document.getElementById(id);
	if (box) {
		box.style.display = 'block';
		return true;
	}
  box = document.getElementById('tooltipFrame').cloneNode(true);
	box.style.display = 'block';
	box.id = id;
	document.body.appendChild(box);

  box.doc = null;
  if(box.contentDocument) {
    // Firefox, Opera  
    box.doc = box.contentDocument;  
  } else if(box.contentWindow) {
    // Internet Explorer  
    box.doc = box.contentWindow.document;  
  } else if(box.document) { 
    // Others?  
    box.doc = box.document;  
	}
  if (box.doc === null) { return false; } 

  //Put the iframe in a state where we can use appendChild
  box.doc.open();  
  box.doc.close();

  box.doc.body.style.margin = '0';
  box.doc.body.style.backgroundColor = 'transparent';
	var bws = navigator.userAgent.toLowerCase();
	var safari = 0;
  var txtBox = box.doc.createElement('div');
  var imgBox = box.doc.createElement('div');
  var img = box.doc.createElement('img');
  var imgBoxWidth;
  var openerPos;
  var arrowDir;
	var boxWidth;
	var boxHeight;

	//Detect safari browser
	if (bws.indexOf("safari") != -1) { safari = 1; }

	if (position == 'left') {
		arrowDir = 'right';
	} else if (position == 'right') {
		arrowDir = 'left';
	} else if (position == 'above') {
		arrowDir = 'down';
	} else if (position == 'below') {
		arrowDir = 'up';
	}

  img.src = 'images/tooltipConnector'+arrowDir.substr(0, 1).toUpperCase() + arrowDir.substr(1)+'.gif';
  imgBox.appendChild(img);
  
  openerPos = getPosition(opener);

  txtBox.style.borderWidth = '1px';
  txtBox.style.borderStyle = 'solid';
  txtBox.style.borderColor = '#7EABCD';
  txtBox.style.backgroundColor = '#FFFFFF';
  txtBox.style.backgroundImage = "url(images/tooltipBg.gif)";
  txtBox.style.backgroundRepeat = 'repeat-x';
  txtBox.style.backgroundPosition = 'bottom';
	txtBox.style.fontSize = '12px';
	txtBox.style.fontFamily = 'Geneva, Arial, Helvetica, sans-serif';
  txtBox.style.padding = '6px';
  txtBox.style.width = width+'px';
  txtBox.style.overflow = 'hidden';
	var strTxt = getTranslation(page,txt,1);
	//strTxt = strTxt.replace(new RegExp( "\\n", "g"),"<br>");
	txtBox.innerHTML = strTxt;
  imgBox.style.position = 'relative';
  
  if (arrowDir == 'right') {
    box.doc.body.appendChild(txtBox);
    imgBoxWidth = txtBox.offsetWidth + 16 - 2;
    imgBox.style.width = imgBoxWidth+'px';
    imgBox.style.textAlign = 'right';
    imgBox.style.top = 0-txtBox.offsetHeight+10+'px';
    box.doc.body.appendChild(imgBox);
    //alert(txtBox.offsetWidth+'px');
		boxWidth = txtBox.offsetWidth+14;
    box.style.width = boxWidth+'px';
    box.style.height = txtBox.offsetHeight+'px';
		box.style.top = openerPos.y-8+'px';
		box.style.left = openerPos.x-boxWidth+'px';
  } else if (arrowDir == 'left') {
    box.doc.body.appendChild(txtBox);
    imgBox.style.width = '14px';
    txtBox.style.marginLeft = '14px';
    imgBox.style.top = 0-txtBox.offsetHeight+10+'px';
    //imgBox.style.top = '-23px';
    box.doc.body.appendChild(imgBox);
    box.style.width = txtBox.offsetWidth+14+'px';
    box.style.height = txtBox.offsetHeight+'px';
		box.style.top = openerPos.y-8+'px';
		box.style.left = openerPos.x+opener.offsetWidth+5+'px';
		//alert("x = "+openerPos.x+" and y = "+openerPos.y);
  } else if (arrowDir == 'up') {    
    imgBox.style.top = '1px';
    imgBox.style.left = '5px';
    box.doc.body.appendChild(imgBox);
    box.doc.body.appendChild(txtBox);  
    box.style.width = width + 1 + 'px';
    box.style.width = txtBox.offsetWidth+'px';
    box.style.height = txtBox.offsetHeight+16+'px';
		box.style.top = openerPos.y+opener.offsetHeight+'px';
		box.style.left = openerPos.x+'px';
  } else if (arrowDir == 'down') {
    box.doc.body.appendChild(txtBox);
    imgBox.style.top = '-1px';
    imgBox.style.left = 5+'px';
    box.doc.body.appendChild(imgBox);
		boxHeight = txtBox.offsetHeight+16;
    box.style.width = txtBox.offsetWidth+2+'px';
    box.style.height = boxHeight+'px';
		box.style.top = openerPos.y-boxHeight+'px';
		box.style.left = openerPos.x+'px';
  }
  //alert("x = "+clickX+" and y = "+clickY);
	return true;
}

function emailinvalid_confirm(resultObjId) {
  var resultObj = dojo.byId(resultObjId);
	var jsnResult = ajaxCall({"action":"emailinvalid_confirm"});
	//alert(dumpObj(jsnResult, 'jsnResult', "", 2));
	if (jsnResult.error == 1) {
		alert(jsnResult.message);
		resultObj.className = 'err';
	} else {
		resultObj.className = 'msg';
	}
	resultObj.innerHTML = jsnResult.message;
	resultObj.style.display = 'block';
}

 var MAX_DUMP_DEPTH = 10;

function dumpObj(obj, name, indent, depth) {
	if (depth > MAX_DUMP_DEPTH) {
		return indent + name + ": <Maximum Depth Reached>\n";
  }
  if (typeof obj == "object") {
		var child = null;
    var output = indent + name + "\n";
    indent += "\t";
    for (var item in obj) {
    	try {
				child = obj[item];
      } catch (e) {
        child = "<Unable to Evaluate>";
      }
	    if (typeof child == "object") {
	      output += dumpObj(child, item, indent, depth + 1);
      } else {
        output += indent + item + ": " + child + "\n";
      }
    }
    return output;
  } else {
    return obj;
  }
}

function strip_tags (str, allowed_tags) {
	// Strips HTML and PHP tags from a string  
  // 
  // version: 909.322
  // discuss at: http://phpjs.org/functions/strip_tags    
  var key = '', allowed = false;
  var matches = [];    var allowed_array = [];
  var allowed_tag = '';
  var i = 0;
  var k = '';
  var html = ''; 
  var replacer = function (search, replace, str) {
    return str.split(search).join(replace);
  };
  // Build allowes tags associative array
  if (allowed_tags) {
    allowed_array = allowed_tags.match(/([a-zA-Z0-9]+)/gi);
  }
  str += '';
 
  // Match tags
  matches = str.match(/(<\/?[\S][^>]*>)/gi);
  // Go through all HTML tags
  for (key in matches) {
    if (isNaN(key)) {
      // IE7 Hack
      continue;        
		}
 
    // Save HTML tag
    html = matches[key].toString();
    // Is tag not in allowed list? Remove from str!
    allowed = false;
 
    // Go through all allowed tags
    for (k in allowed_array) {            
			// Init
      allowed_tag = allowed_array[k];
      i = -1;
 
      if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+'>');}            
			if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+' ');}
      if (i != 0) { i = html.toLowerCase().indexOf('</'+allowed_tag)   ;}
 
      // Determine
      if (i == 0) {                
			  allowed = true;
        break;
      }
    }
    if (!allowed) {
			str = replacer(html, "", str); // Custom replace. No regexing
    }
  }
  return str;
}

function disableGroup(group) {
  if (!group.length) {
    group.disabled = true;
  } else {
    for (var b = 0; b < group.length; b++) {
      group[b].disabled = true;
    }
  }
}

function enableGroup(group) {
  if (!group.length) {
    group.disabled = false;
  } else {
    for (var b = 0; b < group.length; b++) {
      group[b].disabled = false;
    }
  }
}
