/**
 * fuMan - developped by fugu GmbH, Bern, Switzerland, www.fugu.ch
 * Please see licence.txt in the root directory for further information.
 *
 * $Id: datauser.js,v 1.46 2009-03-05 09:34:40 higi Exp $
 * $Date: 2009-03-05 09:34:40 $
 * $Revision: 1.46 $
 */

if (document.fumanLoginKeyListener) {
	document.onkeypress = fumanLoginKeyListener;
}
function fumanLoginKeyListener (evt) {
	var evt = evt ? evt : event;
	var evtSrc = evt.srcElement ? evt.srcElement : evt.target; 
	var keyCode = evt.keyCode ? evt.keyCode : (evt.which ? evt.which : evt.keyCode);
	if (evt.shiftKey && evt.ctrlKey) {
		// <ctrl> <shift> <e>
		if (keyCode == 101 || keyCode == 69 || keyCode == 5) {
			if (!document.fumanLoggedIn) {
				fumanLogin ();
			}
			else {
				fumanLogout ();
			}
		}
	}
}

function fumanLogin () {
	var h = 120, w = 408;
	var url = document.fumanHttpRoot + '?fumandatauserlogin=true&fumancallerurl=' + escape (location.href) + '&fuman_popup=true&fuman_callback=' + escape ('fumanReload();');
	var win = window.open (url, 'fumanadminwindow', 'width=' + w + ',height=' + h + ',resizable=yes,scrollbars=yes,status=yes,toolbar=no,menubar=no');
	if (win != null) win.focus ();
}

function fumanLogout () {
	if (document.fumanHttpRoot != null) {
		// Send server logout
		if (!AJS.getElement ('fumanlogout')) {
			var body = AJS.getElementsByTagAndClassName ('body')[0];
			var div = AJS.DIV ();
			div.id = 'fumanlogout';
			body.insertBefore (div, body.firstChild);
			centerElement (div);
			ajaxCall (document.fumanHttpRoot + 'gateway.php?gateway=fumanlogout');
		}
	}
}

// can be used to login to fuMan administration from whereever
// the result is a javascript variable "var fumanLoginStatus = true|false;"
// use the callbackFunction to query the fumanLoginStatus and react apropriate
// ex:
//  fumanDirectLogin ('<?= $fumanUser->getVar ('urlprefix') ?>', un, pw, authenticateCallback);
//  function authenticateCallback (data) {
//    eval (data);
//    if (fumanLoginStatus == true) {
//      location.href = location.href;
//    }
//    else {
//      if (AJS.getElement ('username') && AJS.getElement ('passwd')) {
//        AJS.getElement ('username').value = '';
//        AJS.getElement ('passwd').value = '';
//        AJS.getElement ('username').focus ();
//      }
//    }
//  }

function fumanDirectLogin (urlPrefix, username, passwd, callbackFunction) {
	// load script from admin/ directory
	var req = AJS.getRequest (urlPrefix + 'admin/gateway.php?gateway=fumanlogin&username=' + username + '&passwd=' + passwd);
	// alert (urlPrefix + 'admin/gateway.php?gateway=fumanlogin&username=' + username + '&passwd=' + passwd);
	req.addCallback (callbackFunction);
	req.sendReq ();
}

function fumanReload () {
	// Get status from server
	if (document.fumanHttpRoot != null) {
		fumanCloseIFrameContent ();
		fumanReloadCallback ();
	}
}

function fumanReloadCallback () {
	if (document.fumanHttpRoot != null) {
		var url = location.href;
		if (document.fumanactionscripturl != null) {
			if (url.indexOf ('?') > -1) {
				url = url.substring (0, url.indexOf ('?'));
			}
			if (url.lastIndexOf ('/') != url.length - 1) {
				url += '/';
			}
			url += document.fumanactionscripturl;
		}
		location.href = url;
	}
}

function fumanOpenContent (url, tableUID, contentId) {
	var h = 100, w = 800;
	// Extend url
	if (document.fumanLoggedIn) {
		fumanCloseIFrameContent ();
		url += (url.indexOf ('?') > -1 ? '&' : '?') + 'fuman_popup=true&fuman_callback=' + escape ('fumanReload()');
		var inline = document.getElementById ('fumanmenu_inline_'+tableUID+(contentId?'_'+contentId:''));
		if (inline != null) {
			var iframe = null;
			var div = null;
			if (inline.childNodes.length == 0) {
				//Rearrange inline if menu is an addon
				if (inline.parentNode.parentNode.className=='fumanmenu_addons') {
					var fm = inline.parentNode;
					while(fm!=null && fm.className!='fumanmenu'){
						fm = fm.parentNode;
					}
					if(fm){
						inline.parentNode.removeChild(inline);
						fm.appendChild(inline);
					}
				}
				
				div = AJS.DIV ();
				div.style.position = 'absolute';
				div.style.zIndex = 100000;
				inline.appendChild (div);
				var header = AJS.DIV ();
				header.className = 'header';
				header.innerHTML = '<a href="javascript:fumanCloseIFrameContent()">X</a>';
				div.appendChild(header); 
				var content = AJS.DIV();
				div.appendChild (content);
				iframe = AJS.IFRAME ();
				content.appendChild (iframe);
			}
			else {
				var div = AJS.getFirst (inline.childNodes);
				if (div != null) {
					iframe = AJS.getFirst (div.getElementsByTagName ('iframe'));
				}
			}
			document.fumanCurrentInlineContent = div;
			div.style.display = 'block';
			if (iframe != null) {
				iframe.src = url;
			}
		}
		else {
			var win = window.open (url, 'fumanadminwindow', 'width=' + w + ',height=' + h + ',resizable=yes,scrollbars=yes,status=yes,toolbar=no,menubar=no');
			if (win != null) {
				win.focus ();
			}
		}
	}
	else {
		fumanLogin ();
	}
}

function fumanCloseIFrameContent () {
	if (document.fumanCurrentInlineContent != null) {
		var iframe = AJS.getFirst (document.fumanCurrentInlineContent.getElementsByTagName ('iframe'));
		if (iframe != null) {
			iframe.src = '';
			document.fumanCurrentInlineContent.style.display = 'none';
		}
	}
}

function setActionScriptURL (url) {
	document.fumanactionscripturl = url;
}

function openImgWindow (table, column, id, title) {
	var url = 'imgwindow.php?table=' + table + '&column=' + column + '&id=' + id + '&title=' + title;
	var win = window.open (document.fumanHttpRoot + url, name, 'width=160,height=45,resizable=yes,scrollbars=yes,status=yes,toolbar=no,menubar=no');
}

function fumanTogglePreview (preview) {
	if (preview != null) {
		setFumanVar ('fumanpreview', preview, 'fumanReloadCallback ();');
	}
}

function fumanToggleShowOffline (showOffline) {
	if (showOffline != null) {
		setFumanVar ('fumanshowoffline', showOffline, 'fumanReloadCallback ();');
	}
}

function fumanToggleWebStatus(tableUID,contentId,status){
	if (tableUID != null && contentId != null && status != null) {
		ajaxCall (document.fumanHttpRoot+'gateway.php?gateway=fumandatauser&action=webstatus&tableuid=' + tableUID + '&contentid=' + contentId + '&status=' + status);
	}
}

//Dir true=down
function fumanMenuMove(obj,dir,id,colUID,tableUID){
  obj.onmouseout();
  var div = AJS.getParentBytc(obj, 'div', 'fumanlistmenu');
  if(div==null)
    return;
  var n = div.id.substring(0,div.id.lastIndexOf('_'));
  var menues = AJS.getElementsByTagAndClassName ('div','fumanlistmenu');
  var sDiv = null;
  var bDiv = null;
  var found = false;
  for(var i in menues){
    if(found && dir && bDiv!=null){
      sDiv = bDiv;
      break;
    }
    if(menues[i]==div)
      found = true;
    if(found){
      if(dir){
        bDiv = null;
      }
      else {
        sDiv = bDiv;
        break;
      }
    }
    if(menues[i]!=div && menues[i].id.substring(0,menues[i].id.lastIndexOf('_'))==n)
      bDiv = menues[i];
  }
  if(found && dir && bDiv!=null)
    sDiv = bDiv;
  if(sDiv==null)
    return;
  
  var relId = sDiv.id.substring(sDiv.id.lastIndexOf('_')+1,sDiv.id.length);
  if(relId==null)
    return;
  
  divMC = AJS.getParentBytc(div, 'div', 'fumanmenucontainer');
  sDivMC = AJS.getParentBytc(sDiv, 'div', 'fumanmenucontainer');
  if(divMC==null || sDivMC==null)
    return;
  
  //Move internally
  if(divMC==sDivMC){
    if(dir){
      var d = sDiv;
      sDiv = div;
      div = d;
    }
    AJS.insertBefore(div.parentNode,sDiv.parentNode);
  }
  //Move from one container to an other
  else {
    var nDiv = AJS.DIV();
    nDiv.className = divMC.className;
    if(divMC.style.backgroundImage!=null && divMC.style.backgroundImage.length>0)
      nDiv.className = divMC.style.backgroundImage;
    nDiv.innerHTML = divMC.innerHTML;
    AJS.insertAfter(nDiv,sDivMC);
    
    var nDiv = AJS.DIV();
    nDiv.className = sDivMC.className;
    if(sDivMC.style.backgroundImage!=null && sDivMC.style.backgroundImage.length>0)
      nDiv.className = sDivMC.style.backgroundImage;
    nDiv.innerHTML = sDivMC.innerHTML;
    AJS.insertAfter(nDiv,divMC);
    divMC.parentNode.removeChild(divMC);
    sDivMC.parentNode.removeChild(sDivMC);
  }
  
  var url = document.fumanHttpRoot + 'gateway.php?gateway=sequenceselector&orderrow='+id+'&orderrowrelative='+relId+'&insertposition='+(dir?'after':'before')+'&ordercol='+colUID+'&tableuid='+tableUID+'&noreload=true';
  ajaxCall (url);
}

function initFumanMenu () {
	if (document.fumanLoggedIn) {
		// create main menu
		ajaxCall (document.fumanHttpRoot + 'gateway.php?gateway=fumandatauser&action=mainmenu&inframeset='+(window.top==window?'false':'true'));

		//We are running in a frameset
		if(window.top!=window){
			//Hide all
			var menus = AJS.getElementsByTagAndClassName ('div', 'fumanmenu');
			for(var i=0;i<menus.length;i++){
				menus[i].style.display = 'none';
			}
			return;
		}
		
		// show data menus
		var menuData = null;
		while ((menuData = AJS.getFirst (AJS.getElementsByTagAndClassName ('ins', 'fumanlistmenudata'))) != null) {
			// Are we an addon
			var data = menuData.parentNode;
			if (data != null) {
				// Are we an addon
				var isAddOn = data.className == 'fumanmenu_addons';
				if (isAddOn) {
					data = data.parentNode.parentNode.parentNode;
				}
				if (data.nodeName.toLowerCase () == 'a') {
					data = data.parentNode;
				}
				if (data != null) {
					var html = AJS.DIV();
					html.innerHTML = menuData.innerHTML;
					var htmlString = '';
					if (html.childNodes.length > 0) {
						htmlString = html.childNodes[0].nodeValue;
					}
					if (menuData.parentNode != null) {
						if (isAddOn) {
							var div = AJS.DIV ();
							div.innerHTML = htmlString;
							if (div.childNodes.length > 0) {
								AJS.insertBefore (div.childNodes[0], menuData);
							}
						}
						menuData.parentNode.removeChild (menuData);
					}
					if (isAddOn) {
						htmlString = '';
					}
					if(htmlString==null)
						htmlString = '';
					
					var div = AJS.DIV();
					div.className = 'fumanmenucontainer' + ((menuData.title != null && menuData.title.toLowerCase () == 'offline') ? ' fumanmenucontainer_offline' : '');
					div.innerHTML = htmlString + '<div class="fumanmenucontent"></div>';
					var menuContent = AJS.getFirst(AJS.getElementsByTagAndClassName('div','fumanmenucontent',div));
					while(data.childNodes.length>0){
						var n = data.childNodes[0];
						if(n!=null){
							data.removeChild(n);
							menuContent.appendChild(n);
						}
					}
					data.innerHTML = '';
					// Firefox bug with display table;
					if (data.style.display == 'table') {
						data.style.display = 'block';
					}
					AJS.replaceChildNodes (data, div);
				}
			}
		}
		// Reset bg image for menues which are already in a menu
		var menues = AJS.getElementsByTagAndClassName ('div', 'fumanlistmenu');
		for (var i = 0; i < menues.length; i++) {
			var c = AJS.getParentBytc (menues[i], 'div', 'fumanmenucontainer');
			if (c) {
				if (AJS.getParentBytc (c, 'div', 'fumanmenucontainer') != null) {
					//c.style.backgroundImage = 'none';
				}
			}
		}
		// Check sequence
		var elms = new Object ();
		var menues = AJS.getElementsByTagAndClassName ('div', 'fumanlistmenu');
		for (var i in menues) {
			var n = menues[i].id.substring (0, menues[i].id.lastIndexOf ('_'));
			var arr = elms[n];
			if (arr == null) {
				arr = new Array ();
			}
			arr.push (menues[i].id);
			elms[n] = arr;
		}
		for (var i in elms) {
			if (elms[i] != null && elms[i].length < 2) {
				for (var j in elms[i]) {
					// Hide sequence
					var div = document.getElementById (elms[i][j]);
					if (div != null) {
						var seqs = AJS.getElementsByTagAndClassName ('div', 'fumanmenu_sequence', div);
						for (var k in seqs) {
							seqs[k].style.display = 'none';
						}
					}
				}
			}
		}
	}
}
AJS.AEV (window, 'load', initFumanMenu);

function unscrambleLink (id, sUrl, sText, isEmail) {
	var obj = document.getElementById (id);
	if (obj == null) {
		alert ('unscrambleLink: Object not found (' + id + ')');
		return;
	}
	var parent = obj.parentNode;
	if (parent == null) {
		alert ('unscrambleLink: Parent object not found');
		return;
	}

  if (parent.nodeName.toLowerCase () == 'span') {
    parent = parent.parentNode;
  }

	// to create standards compliant xhtml, use <div><a></a><-- scramble --></div>
	if (parent.nodeName.toLowerCase () == 'div') parent = parent.firstChild;
	if (parent.nodeName.toLowerCase () != 'a') {
		alert ('unscrambleLink: Parent object is not an anchor tag');
		return;
	}
	if (sUrl != null && sUrl.length > 0) {
		eval ('var txt = String.fromCharCode(' + sUrl + ');');
		parent.href = txt;
	}
	if (sText != null && sText.length > 0) {
		var firstChild = parent.firstChild;
		//First node is a text node with input
		if (firstChild && firstChild.nodeType == 3 && firstChild.nodeValue != null && firstChild.nodeValue.replace (' ', '').length > 0) return;
		eval ('var txt = String.fromCharCode (' + sText + ');');
		txt = txt.replace (/&amp;/g, '&');
    
    var elm = parent.getElementsByTagName('noscript');
    
    var realParent = elm[0].parentNode;
    
    realParent.replaceChild(document.createTextNode(txt), elm[0]);
    
    elm = realParent.getElementsByTagName('script');
    realParent.removeChild(elm[0]);

		if (parent.title != null && parent.title.length == 0) {
			parent.title = txt;
		}
	}
}

function setFumanStatus (key, value) {
  var status = document.getElementById('fumanstatus');
	if (status == null) return;
	// Remove
	var id = status.id + '_' + key;
	var o = document.getElementById (id);
	if (o != null && !value) status.removeChild (o);
	else if (value) {
		if (o == null) {
			o = document.createElement ('div');
			o.id = id;
			status.appendChild (o);
		}
		o.innerHTML = value;
	}
}

/**
 * Calls fumanDataUser->setVar (key, value)
 * callback is javascript code to be executed on return (optional)
 */
function setFumanVar (key, value, callback) {
	ajaxCall (document.fumanHttpRoot + 'gateway.php?gateway=fumandatauservar&action=set&key=' + key + '&value=' + value + (callback != null ? '&fuman_callback=' + escape (callback) : ''));
}
