
try { var SELF = (document.location+'').match(/.*\/([^\/]+\.php)\??.*/i)[1]; } catch(e) { var SELF = 'index.php'; }

function elem(id) {
  var o = document.getElementById(id); if (!o) return null;
  return o;
}

function send(address, request, ctype) {
	var obj = getHTTPObject();
	obj.open("POST", address, false);
	obj.setRequestHeader("Content-Type", (ctype)? ctype : 'application/x-www-form-urlencoded');
  obj.setRequestHeader("Connection", 'close');
  request = (request)? request : '';
  var i = address.indexOf('?');
  //if (i>-1) { request += address.substring(i+1); address = address.substring(0,i); }
  obj.send(request);
  var r = obj.responseText;
  if (r.substring(0,5)=='error') { alert(r); }
  return obj;
}
function send_sync(address, request, ctype) {
  return send(address, request, ctype);
}
function send_async(address, request, ctype, callBack) {
  var obj = getHTTPObject();
  obj.open("POST", address, true);
  obj.setRequestHeader("Content-Type", (ctype)? ctype : 'application/x-www-form-urlencoded');
  if (callBack) obj.onreadystatechange = callBack;
  request = (request)? request : ''
  obj.send(request);
  return obj;
}

function get_query(location, unit, tpl, display) {
  if (!location) location = srcwin.location+'';
  var query = location.match(/\?(.*)$/ig)+'';
  if (unit) query = query.replace(/unit=[^&]*/i, 'unit='+unit);
  if (tpl) query = query.replace(/tpl=[^&]*/i, 'tpl='+tpl);
  if (display) query = query.replace(/display=[^&]*/i, 'display='+display);
  return query;
}

function sendRequest(url, request, behavior) { // Envoie une requete au serveur
  if (behavior=='async') {
    var obj = send_async(APP_PATH + url, request);
    return;
  }
  var obj = send(APP_PATH + url, request);
  if (obj.responseText!='') alert(obj.responseText);

  if (behavior=='none' || behavior==null) return;
  if (behavior=='reload') { srcwin.location.href = APP_PATH + SELF + srcwin.location.search; return; }
  window.setTimeout("srcwin.location.reload(true)");
}


function unlinkUnit(parent, unit, link, confirmation, label, reload) {
  if (confirmation==null) conf = true;
  if (label==null) label = 'confirm-unit-unlink';
  if (reload==null) reload = true;
  if (confirmation) { var r = confirm(labels[label]); if (!r) return; }
  var query = 'parent='+parent+'&unit='+unit+'&link='+link;
  var obj = send(APP_PATH + 'lib/units/unlink.php', query);
  if (reload) srcwin.location.reload(true);
}

function linkUnit(parent, unit, link, order, parentlink, behavior, datebegin, dateend) {
  var dom = getDom('<data/>');
  var node = dom.documentElement;
    node.setAttribute('parent', parent);
    node.setAttribute('unit', unit);
    node.setAttribute('link', link);
    if (order) node.setAttribute('order', order);
    if (parentlink) node.setAttribute('parent-link', parentlink);
    if (datebegin) node.setAttribute('date-begin', datebegin);
    if (dateend) node.setAttribute('date-end', dateend);
  var obj = send(APP_PATH + 'lib/units/link.php', dom);
  if (obj.responseText!='') alert(obj.responseText);

  if (behavior=='none' || behavior==null) return;
  if (behavior=='goto') { srcwin.location.href = APP_PATH + SELF+"?unit="+guid; return; }
  if (behavior=='parent') { srcwin.location.href = APP_PATH + SELF+"?unit="+parent; return; }
  if (behavior=='reload') { srcwin.location.href = APP_PATH + SELF + srcwin.location.search; return; }
  window.setTimeout("srcwin.location.reload(true)");
}

// Charge une Unit depuis le serveur
function loadUnit(guid) {
  var obj = send(APP_PATH + 'lib/units/load.php', 'guid='+guid);
  if (obj.responseXML.xml!='') { return obj.responseXML; }
  alert(obj.responseText);
  return null;
}

// Charge le modèle xml d'une Unit
function loadUnitModel(type) {
  var obj = send(APP_PATH + 'lib/units/model.php', 'type='+type);
  if (obj.responseXML.xml!='') { return obj.responseXML; }
  alert(obj.responseText);
  return null;
}

// Transforme un GUID en MD5
function toMD5(guid) {
  guid = guid.toUpperCase()
  return guid.replace(/[\{\-\}]/gi, '')
}
function toGUID(md5) {
  md5 = md5.toUpperCase();
  if (md5.length==38) return md5;
  return '{'+md5.substring(0,8)+'-'+md5.substring(8,12)+'-'+md5.substring(12,16)+'-'+md5.substring(16,20)+'-'+md5.substring(20)+'}';
}

// Supprime une Unit
function deleteUnit(guid, back, reload) {
  var t0 = new Date();
  r = confirm(labels['confirm-unit-delete']); if (!r) return;
	var obj = send(APP_PATH + 'lib/units/delete.php', "guid="+guid);
  if (isNaN(obj.responseText)) { alert(obj.responseText); return; }

  back = (back)? back : srcwin.guidParent;
  back = back.replace(/[\{\-\}]*/ig, '');

  if (reload) {
    try { parent.refreshDIV(reload); } catch(e) { alert("error: Object '"+reload+"' does not exist."); }
    return;
  }
  if (guid!=unit) last_querystring = self_querystring;
  window.setTimeout("srcwin.location.href = '" +APP_PATH+SELF+last_querystring+ "'", 10);
}

// Supprime une Unit (qui n'est pas une page)
function deleteItem(guid, back) {
  var t0 = new Date()
  r = confirm(labels['confirm-item-delete']); if (!r) return;
	var obj = send(APP_PATH + 'lib/units/delete.php', "guid="+guid);
  if (isNaN(obj.responseText)) { alert(obj.responseText); return; }
}

function moveUnit(path, parent, unit, link, order, move) {
  var t0 = new Date();
  post = '';
  if (path) post += 'path='+path;
  post += '&parent='+parent;
  post += '&unit='+unit;
  post += '&link='+link;
  post += '&order='+order;
  move += '';
  if (move.substring(0,1)=='+' || move.substring(0,1)=='-') {
    post += '&move='+move;
  } else {
    if (move.substring(0,3)=='id:') {
      post += '&swap-with='+move.substring(3);
    } else { //exemple : pos:-1
      post += '&new-order='+move.substring(move.indexOf(':')+1);
    }
  }
  var obj = send(APP_PATH + 'lib/units/reorder.php', post);
  var t1 = new Date();
  if (obj.responseText!='') alert(obj.responseText);
  var href = srcwin.location.href;
  srcwin.location = href.replace(/&delcache=area-left/i,'')+'&delcache=area-left';
}
function moveBlock(parent, unit, link, order, move) {
  return moveUnit(null, parent, unit, link, order, move);
}


function copyPath(path, bConfirm) {
  var obj = send(APP_PATH + 'lib/session.php', "clipboard[copied-path]="+path);
  if (bConfirm) {
    if (obj.responseText=='') {
      alert(labels['unit-path-copied']);
    } else {
      alert(obj.responseText);
    }
  }
}

function moveToPath(newPath) {
  var oldPath = clipboard['copied-path'];
  var s = oldPath.substring(oldPath.length-38)
	if (oldPath==newPath) return; // on tente de copier dans la m�me unit� d'information
  if (newPath.indexOf(oldPath)==0) return // on tente de copier une info vers un de ses descendants;
  var r = confirm(labels['confirm-unit-move']); if (!r) return;
  var obj = send(APP_PATH + 'lib/units/move.php', "oldpath="+oldPath+"&newpath="+newPath);
	srcwin.location.reload(true);
}


function checkUnit4Update(guid) {
  if (window.checking) return
  window.checking = send_async(APP_PATH + 'lib/units/check.php', 'guid='+guid, null, checkUnit4Update2)
}
function checkUnit4Update2() {
  var obj = window.checking; if (!obj) return
  if (obj.readyState!=4) return
  var node = obj.responseXML.documentElement
  window.checking = null
  if (srcwin.updated==node.getAttribute('updated')) return
  srcwin.location.reload(true)
}


function querystring(key, search) {
  if ((key=='')||(key==null)) { return ''; };
  search = (search)? search : document.location.search.toString()
  if (search.substring(0,1)=='?') { search = search.substring(1,search.length); };
  var pos0 = search.indexOf(key + '='); if (pos0==-1) { return ''; };
    pos0 += key.length + 1
  var pos1 = search.indexOf('&', pos0); if (pos1==-1) { pos1 = search.length; };
  var value = search.substring(pos0, pos1)
  return unescape(value)
}

function getFileName(value) {
	var reg = /(?:[\/\\])([^\/\\]+)$/i
	var r = value.match(reg)
	if (r.length>0) return r[1]
}


function encode(text) {
  try { var s = encodeURIComponent(text) }
  catch(e) { var s = text }
  return s
}
function decode(text) {
  try { var s = decodeURIComponent(text) }
  catch(e) { var s = text }
  return s
}


// Retourne une date au format dd/mm/YYYY[ HH:MM[:SS]]
function formatDate(timestamp, notime, noseconds) {
  if (timestamp==0) return '';
	var dg = function (val) { var s = val + '';
			if (s.length==0) return '00';
			if (s.length==1) return '0'+s;
			return s;
		}
	var d = new Date(timestamp*1000);
	var s = dg(d.getUTCDate()) + '/' + dg(d.getUTCMonth()+1) + '/' + d.getUTCFullYear();
	if (notime) return s;
	s += ' ' + dg(d.getUTCHours()) + ':' + dg(d.getUTCMinutes());
	if (noseconds) return s;
	s += ':' + dg(d.getUTCSeconds());
	return s;
}

// Retourne une date au format YYYY-mm-dd[ HH:MM[:SS]]
function stringDate(timestamp, notime, noseconds) {
	var dg = function (val) { var s = val + '';
			if (s.length==0) return '00';
			if (s.length==1) return '0'+s;
			return s;
		}
	var d = new Date(timestamp*1000);
	var s = d.getUTCFullYear() + '-' + dg(d.getUTCMonth()+1) + '-' + dg(d.getUTCDate());
	if (notime) return s;
	s += '_' + dg(d.getUTCHours()) + dg(d.getUTCMinutes());
	if (noseconds) return s;
	s += dg(d.getUTCSeconds());
	return s;
}


function getHTTPObject() {
  var xmlhttp = false;
  /* Compilation conditionnelle d'IE */
  /*@cc_on
  @if (@_jscript_version >= 5)
     try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
		 catch (e) {
        try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
				catch (E) { xmlhttp = false; }
     }
  @else
     xmlhttp = false;
  @end @*/

  /* on essaie de créer l'objet si ce n'est pas déjà fait */
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
     try { xmlhttp = new XMLHttpRequest(); }
     catch (e) { xmlhttp = false; }
  }

	return xmlhttp;
  if (xmlhttp) {
     /* on définit ce qui doit se passer quand la page répondra */
     xmlhttp.onreadystatechange = function()
     {
        if (xmlhttp.readyState == 4) { /* 4 : état "complete" */
           if (xmlhttp.status == 200) { /* 200 : code HTTP pour OK */
              /*
              Traitement de la réponse.
              Ici on affiche la réponse dans une boîte de dialogue.
              */
              alert(xmlhttp.responseText);
           }
        }
     }
  }
  return xmlhttp;
}

