/*
 * createTables(	{"tableID,TableClass":
							{"line1ID,line1Class": 
										{"cell1ID": DOMElement}
										{"cell2ID,cell2Class": null}
										{"cell3ID": DOMElement}
							}
							{"line2ID": 
										{"cell1ID": null}
										{",cell2Class": null}
										{"cell3ID": [DOMElement,DOMElement]}
							}
				}
 *            );
 */
function createTables(contentObject,dest){
	var result=Array();
	
	for(var tableDeno in contentObject){
		var E_table = document.createElement("table");
		var E_tbody = document.createElement("tbody");
		E_table.appendChild(E_tbody);
		
		var idClass = tableDeno.split(",");
		if(idClass[0]!==undefined && idClass[0]!=null && idClass[0]!=""){
			E_table.id=idClass[0];
			E_tbody.id=idClass[0]+"Body";
		}
		if(idClass[1]!==undefined && idClass[1]!=null && idClass[1]!=""){
			E_table.className=idClass[1];
			E_tbody.className=idClass[1]+"Body";
		}
			
		for(var lineDeno in contentObject[tableDeno]){
			var E_tr = document.createElement("tr");
			var idClass = lineDeno.split(",");
			if(idClass[0]!==undefined && idClass[0]!=null && idClass[0]!="")
				E_tr.id=idClass[0];
			if(idClass[1]!==undefined && idClass[1]!=null && idClass[1]!="")
				E_tr.className=idClass[1];
				
			for(var cellDeno in contentObject[tableDeno][lineDeno]){
				var E_td = document.createElement("td");
				var idClass = cellDeno.split(",");
				if(idClass[0]!==undefined && idClass[0]!=null && idClass[0]!="")
					E_td.id=idClass[0];
				if(idClass[1]!==undefined && idClass[1]!=null && idClass[1]!="")
					E_td.className=idClass[1];
					
				if(contentObject[tableDeno][lineDeno][cellDeno] instanceof Array){
					for(var i=0; i<contentObject[tableDeno][lineDeno][cellDeno].length; i++){
						E_td.appendChild(contentObject[tableDeno][lineDeno][cellDeno][i]);
					}
				}
				else if(contentObject[tableDeno][lineDeno][cellDeno]!=null){
					E_td.appendChild(contentObject[tableDeno][lineDeno][cellDeno]);
				}
				
				E_tr.appendChild(E_td);
			}
			
			E_tbody.appendChild(E_tr);
		}
		
		if(dest !==undefined)
			dest.appendChild(E_table)
		result.push(E_table);
	}
	
	return result;
}

function createButton(id,urlOrFunc,imgPath,activeImgPath,title,number,notNullCond,dest){
	if(notNullCond===undefined || notNullCond != null){
		var button;
		if(imgPath!==undefined){
			button = document.createElement('img');
			button.className = "buttonImg";
			button.src = imgPath;
			button.title = title;
		}
		else{
			button = document.createElement('a');
			button.appendChild(document.createTextNode(title));
			button.className = "a";
		}		
		
		button.id = id;
		
		if(imgPath && activeImgPath){
			customAddEventListener(button,"mouseover",function(){button.src = activeImgPath;});
			customAddEventListener(button,"mouseout",function(){button.src = imgPath;});
		}
		
		if(urlOrFunc instanceof Array)
			customAddEventListener(button, "click", urlOrFunc[0], urlOrFunc[1]);
		else
			customAddEventListener(button, "click", urlOrFunc);
		
		if(number!==undefined){
			//TODO create a small number on top of img. Must encapsulate img and text in another tag.
		}
		
		if(dest!==undefined)
			dest.appendChild(button);			
			
		button.style.cursor = "pointer";
			
		return button;
	}
	return null;
}

function applyToTags(element, tag, expression){
	var elements = element.getElementsByTagName(tag);
	for(var i=0; i<elements.length; i++){
		eval("elements[i]."+expression);
	}
}

function blinkImg(image){
	imgPath=image.src.split("/");
	imgName=imgPath[imgPath.length-1];
	if(imgName==graphique['section'][image.id]){
		image.setAttribute('src', tpath+graphique['section_active'][image.id]);
	}
	else{
		image.setAttribute('src', tpath+graphique['section'][image.id]);
	}
	
	if(image.title!=txt_section[7] || imgName!=graphique['section_active'][image.id]){
		setTimeout(function(){blinkImg(image)},500);
	}
}

//cross browsers addeventlistener
//returns the handler attached to the element /!\ the function passed is NOT added to the element, it is the returned function.
function customAddEventListener(element, event, func, params, capture){
	if(typeof capture === "undefined")
		capture = false;
		
	var shell = {};
		
	shell.sParams = params;
		
	if(typeof params === "undefined")
		shell.sHandler = function(e){func.apply(element,[e])}
	else
		shell.sHandler = function(e){func.apply(element,[e].concat(shell.sParams))}
		
	var handler = shell.sHandler;

	
	if (element.addEventListener){ //Firefox and cool browsers
		if(event === "mouseenter"){
			handler = mouseEnter(handler);
			event = "mouseover";
		}
		else if(event === "mouseleave"){
			handler = mouseEnter(handler);
			event = "mouseout";
		}			

		element.addEventListener(event,handler,false);
	}
	else if (element.attachEvent) { //IE
  	element.attachEvent("on"+event, handler); 
	}
	else{ //Old browsers
		element["on"+event] = handler;
	}
	
	return handler;
}

function customRemoveEventListener(element, event, func){
	if (element.removeEventListener){
		element.removeEventListener(event,func,false);
	}
	else if (element.detachEvent) { 
  	element.detachEvent("on"+event, func); 
	}
	else{
		element["on"+event] = null;
	}
}

function mouseEnter(fn){
	return function(event){
		var relTarget = event.relatedTarget;
		if(typeof relTarget != undefined && relTarget != null && (this === relTarget || isAChildOf(this, relTarget)))
			return;
		fn.call(this, event);
	}
}

function isAChildOf(parent, child){
	if(parent === child)
		return false;
	while(child && child !== parent)
		child=child.parentNode;
		
	return child === parent;
}

function createXMLHTTPRequest(){
	var xhr;
	if(window.XMLHttpRequest) // Firefox
	   xhr = new XMLHttpRequest();
	else if(window.ActiveXObject) // Internet Explorer
	   xhr = new ActiveXObject("Microsoft.XMLHTTP"); // Msxml2.XMLHTTP
	   
	return xhr;
}

function xhrPostAsync(xhr, url, func, data){	
	xhr.open("POST", url, true);	// asynchrone
	xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xhr.onreadystatechange = function(){if(this.readyState == 4) func();};
	xhr.send(data);
}

xhrMutex=false;
function xhrPostSync(xhr, url, func, data, onFail){
	if(xhrMutex==false){
		xhrMutex=true;
		document.body.className = 'wait';	
		xhr.open("POST", url, true);	// asynchrone
		xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xhr.onreadystatechange = function(){if(this.readyState == 4) {func(); xhrMutex=false; document.body.className = ''; document.body.style.cursor = "auto";}};
		xhr.send(data);
		return true;
	}
	return false;
}

function bar(amount, maxAmount, bonus, barImages, barHeight){
	var barLength = 0;
	for(var barIm in barImages){
		barLength += barImages[barIm];
	}
	
	var div = document.createElement('div');
	div.style.position='relative';
	div.style.width=barLength+2+"px";
	div.style.height=barHeight+2+"px";
	div.style.zIndex = 1;
	div.title=amount+'/'+maxAmount;
	
	var frame = document.createElement('img');
	frame.src=ipath+'bandeau.gif';
	frame.style.position = "absolute";
	frame.style.top = 0+"px";
	frame.style.left = 0+"px";
	frame.style.width=barLength+2+"px";
	frame.style.height=barHeight+2+"px";
	div.appendChild(frame);
	
	var barImagesAdjusted = {};
	var actualBarSize = 0;
	
	for(var barIm in barImages){
		barImagesAdjusted[barIm] = Math.floor(Math.min(amount*barLength/maxAmount - actualBarSize, barImages[barIm]));
		actualBarSize += barImages[barIm];
	}
	var imgOffset = 1;
	for(var barImageA in barImagesAdjusted){
		if( barImagesAdjusted[barImageA] > 0){
			var img = document.createElement('img');
			img.src=ipath+barImageA;
			img.style.width=barImagesAdjusted[barImageA]+"px";
			img.style.height=barHeight+"px";
			img.style.position = "absolute";
			img.style.top = 1+"px";
			img.style.left = imgOffset+"px";
			imgOffset += barImagesAdjusted[barImageA];
			div.appendChild(img);
		}
	}
	
	if(barHeight>=GLOBAL_MinFontSize){
		var text = document.createElement('div');
		text.style.position='absolute';
		text.style.left = 1+"px";
		if(GLOBAL_ie == 6 || GLOBAL_ie == 7)
			text.style.top = 0+"px";
		else
			text.style.top = 0+"px";
		text.style.width = barLength+"px";
		text.style.height = barHeight+"px";
		text.style.zIndex = 5;
		text.style.fontSize=barHeight+"px";
		text.innerHTML = amount+'/'+maxAmount;
		if(bonus !== undefined && bonus!=null)
			ajout_bonus(text, bonus)
		text.className="barText";
		div.appendChild(text);
	}
	
	return div;
}

function ajout_bonus(element, bonus){
	if(bonus){
	  var bonusImg = document.createElement('img');
	  bonusImg.src=ipath+"bonus.png";
	  bonusImg.title = "+"+bonus;
	  bonusImg.alt = "+"+bonus;
	  bonusImg.style.height="1em";
	  bonusImg.style.marginLeft="3px";
	  element.appendChild(bonusImg);
	}
}

function trace_packs(dest,tab_packs)
{
	if( tab_packs.length-1 == 0)
	{
		var ligne = document.createElement('tr');
		dest.appendChild(ligne);
		var boite = document.createElement('td');
		ligne.appendChild(boite);
		boite.align='center';
		boite.appendChild(document.createTextNode(txt_packs[2]));
	}
	else
	{

		ligne = document.createElement('tr');
		dest.appendChild(ligne);

		boite = document.createElement('td');
		bold = document.createElement('b');
		bold.appendChild(document.createTextNode(txt_packs[12]));
		boite.appendChild(bold);
		ligne.appendChild(boite);

		boite = document.createElement('td');
		bold = document.createElement('b');
		bold.appendChild(document.createTextNode(txt_packs[8]));
		boite.appendChild(bold);
		ligne.appendChild(boite);

		boite = document.createElement('td');
		bold = document.createElement('b');
		bold.appendChild(document.createTextNode(txt_packs[10]));
		boite.appendChild(bold);
		ligne.appendChild(boite);

		boite = document.createElement('td');
		bold = document.createElement('b');
		bold.appendChild(document.createTextNode(txt_packs[15]));
		boite.appendChild(bold);
		ligne.appendChild(boite);

		boite = document.createElement('td');
		boite.appendChild(document.createTextNode(' '));
		ligne.appendChild(boite);


		for(var i=0;i<tab_packs.length;i++){
			if(tab_packs[i] == 0)
				continue;
			if(i%2==0)
				couleur=graphique['fond']['clair'];
			else
				couleur=graphique['fond']['normal'];				

			ligne = document.createElement('tr');
			ligne.style.backgroundColor=couleur;
			dest.appendChild(ligne);

			boite = document.createElement('td');
			ligne.appendChild(boite);
			img = document.createElement('img');
			img.className="timgr";
			if( tab_packs[i]['utilise'] == 1)
				img.setAttribute('src', ipath+'/packs/'+pack[tab_packs[i]['type']][2]+'_a.gif');
			else
				img.setAttribute('src', ipath+'/packs/'+pack[tab_packs[i]['type']][2]+'.gif');
			boite.appendChild(img);
			bold = document.createElement('b');
			bold.appendChild(document.createTextNode(pack[tab_packs[i]['type']][0]));
			boite.appendChild(bold);

			boite = document.createElement('td');
			ligne.appendChild(boite);
			if(tab_packs[i]['date'] != null)
			{
				boite.appendChild(document.createTextNode(tab_packs[i]['date']));
			}

			boite = document.createElement('td');
			ligne.appendChild(boite);
			if( tab_packs[i]['utilise'] == 1)
			{
				bold = document.createElement('b');
				bold.appendChild(document.createTextNode(txt_packs[13]));
				boite.appendChild(bold);
			}
			else
			if(tab_packs[i]['duree'] != null)
					boite.appendChild(document.createTextNode(tab_packs[i]['duree']));

			boite = document.createElement('td');
			ligne.appendChild(boite);
			if(tab_packs[i]['valeur'] != 0)
			{
				boite.appendChild(document.createTextNode(tab_packs[i]['valeur']));
			}

			boite = document.createElement('td');
			ligne.appendChild(boite);
			boite.align="right";

			if(tab_packs[i]['poser'] != null && tab_packs[i]['poser'] == 1)	{
				createButton('deposer',[function(event, pack){get_tab({},{"poser_pack":pack})},tab_packs[i]['numero']],ipath+'deposer.jpg',ipath+'a_deposer.jpg',txt_packs[3],undefined,undefined,boite);
			}
			if(tab_packs[i]['stocker'] != null && tab_packs[i]['stocker'] == 1)	{
				createButton('stocker',[function(event, pack){get_tab({},{"rendre_pack":pack})},tab_packs[i]['numero']],ipath+'stocker.jpg',ipath+'a_stocker.jpg',txt_packs[4],undefined,undefined,boite);
			}
			if(tab_packs[i]['donner'] != null && tab_packs[i]['donner'] == 1)	{
				createButton('donner',[function(event, ind){don_pack(ind);},i],ipath+'donner.jpg',ipath+'a_donner.jpg',txt_packs[5],undefined,undefined,boite);
			}
			if(tab_packs[i]['utiliser'] != null && tab_packs[i]['utiliser'] == 1)	{
				createButton('utiliser',[function(event, pack){get_tab({},{"utiliser_pack":pack})},tab_packs[i]['numero']],ipath+'utiliser.jpg',ipath+'a_utiliser.jpg',txt_packs[6],undefined,undefined,boite);
			}
			if(tab_packs[i]['destocker'] != null && tab_packs[i]['destocker'] == 1)	{
				createButton('destocker',[function(event, pack){get_tab({},{"attribuer_pack":pack})},tab_packs[i]['numero']],ipath+'destocker.jpg',ipath+'a_destocker.jpg',txt_packs[7],undefined,undefined,boite);
			}
		}
	}
}

function maj_pa_stock()
{
	if(typeof tab_stock !== "undefined" && tab_stock !== null)
	{
		for(i=0;i<tab_stock.length;i++){
			if(!(tab_stock[i] instanceof Object))
				continue;
			pastock = document.getElementById('pastock'+i);
			remove(pastock);
			pa = Math.floor((curr_date-tab_stock[i]['action'])/pa_len);
			if( pa > pa_max)
				pa = pa_max;
			pastock.appendChild(document.createTextNode(pa));
		}
	}

}

function compagnie(sessionid,nom){
  if (nom=="")
    lien = fichier_compagnie+'?PHPSESSID='+sessionid;
  else
    lien = fichier_compagnie+'?PHPSESSID='+sessionid+'&compagnie='+escape(nom);
    
  fenetreCompagnie=window.open(lien,'compagnie');
  fenetreCompagnie.document.close();
  fenetreCompagnie.focus();
}

function remove(elt){
	// Suppression
	if(elt){
		while(elt.hasChildNodes())
			elt.removeChild(elt.firstChild);
	}
}

function remove_filtre(elt, exclus){
	var trouve = false;
	// Suppression
	if(elt.hasChildNodes())
	{
		max = elt.childNodes.length;
		for(i = max-1; i>=0; i--)
		{
			trouve = false;
			for(e = 0; e < exclus.length; e++)
				if( elt.childNodes[i].id==exclus[e])
					trouve = true;
			if( trouve == false)
		  		elt.removeChild(elt.childNodes[i]);
		}
	}
}

function clear(src, elt){
	if( (id_elt = document.getElementById(elt)))
	document.getElementById(src).removeChild(id_elt);
}

function clear_id(src_id, elt)
{
	if( (id_elt = document.getElementById(elt)))
		src_id.removeChild(id_elt);
}

function hx(x)
{
	if( x > 0xFF)
		return '00';
	if( x >= 0x10)
		return x.toString(16);
	else
		return '0'+x.toString(16);
}

function removeByClassName(cla, tag, source){
	var elements = getElementsByClassName(cla,tag,source);
	for(var i=0, length=elements.length; i<length; i++){
		elements[i].parentNode.removeChild(elements[i]);
	}
}

/*
	Developed by Robert Nyman, http://www.robertnyman.com
	Code/licensing: http://code.google.com/p/getelementsbyclassname/
*/
if (document.getElementsByClassName) {
	getElementsByClassName = function (className, tag, elm) {
		elm = elm || document;
		var elements = elm.getElementsByClassName(className),
			nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
			returnElements = [],
			current;
		for(var i=0, il=elements.length; i<il; i+=1){
			current = elements[i];
			if(!nodeName || nodeName.test(current.nodeName)) {
				returnElements.push(current);
			}
		}
		return returnElements;
	};
}
else if (document.evaluate) {
	getElementsByClassName = function (className, tag, elm) {
		tag = tag || "*";
		elm = elm || document;
		var classes = className.split(" "),
			classesToCheck = "",
			xhtmlNamespace = "http://www.w3.org/1999/xhtml",
			namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
			returnElements = [],
			elements,
			node;
		for(var j=0, jl=classes.length; j<jl; j+=1){
			classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
		}
		try	{
			elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
		}
		catch (e) {
			elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
		}
		while ((node = elements.iterateNext())) {
			returnElements.push(node);
		}
		return returnElements;
	};
}
else {
	getElementsByClassName = function (className, tag, elm) {
		tag = tag || "*";
		elm = elm || document;
		var classes = className.split(" "),
			classesToCheck = [],
			elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
			current,
			returnElements = [],
			match;
		for(var k=0, kl=classes.length; k<kl; k+=1){
			classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
		}
		for(var l=0, ll=elements.length; l<ll; l+=1){
			current = elements[l];
			match = false;
			for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
				match = classesToCheck[m].test(current.className);
				if (!match) {
					break;
				}
			}
			if (match) {
				returnElements.push(current);
			}
		}
		return returnElements;
	};
}
//end licenced code

function deleteElement(element){
	if(element!=null)
		element.parentNode.removeChild(element);
}

function getTotalOffset(element){
		var offtop =0;
		var offleft =0;
		
		var offEl = element;
		while(offEl!=null){
			offleft+=parseInt(offEl.offsetLeft);
			offtop+=parseInt(offEl.offsetTop);
			offEl=offEl.offsetParent;
		}
		return [offleft,offtop];
}

function faire_option(nom, tab)
{
	switch(tab[0])
	{
	case 'lien':
		var lien = document.createElement('a');
		lien.href= tab[1];
		lien.className="a";
		lien.appendChild(document.createTextNode(txt_info[nom]));
		return lien;
		break;

	case 'case':
		var form = document.createElement('form');
		var box = document.createElement('input');
		box.type='checkbox';
		if( tab[1] != 0)
			box.defaultChecked = true;
		box.setAttribute("onclick",tab[2]);

		form.appendChild(box);
		form.appendChild(document.createTextNode(txt_info[nom]));
		return form;
		break;

	case 'bouton':
		var box = document.createElement('input');
		box.type='button';
		box.setAttribute("onclick",tab[1]);
		box.className="boite";
		box.value=txt_info[nom];
		return box;
		break;

	case 'saisie':
		var form = document.createElement('form');
		form.appendChild(document.createTextNode(txt_info[nom][0]));
		form.method='POST';
		form.action=tab[2];
		form.appendChild(document.createElement('br'));

		var box = document.createElement('input');
		box.type='text';
		box.name=nom;
		box.className="boite";
		box.value=tab[1];
		form.appendChild(box);

		box = document.createElement('input');
		box.className="boite";
		box.type='submit';
		box.value=txt_info[nom][1];
		form.appendChild(box);
		return form;
		break;
	case 'liste':
		var form = document.createElement('form');
		form.appendChild(document.createTextNode(txt_info[nom][0]));
		form.method='POST';
		form.name = 'form'+nom;
		form.action="javascript:get_tab({},{'"+nom+"':"+"document.forms['form"+nom+"']."+nom+".value})";
		form.appendChild(document.createElement('br'));

		var box = document.createElement('select');
		box.name=nom;
		box.className="boite";
		for(var j in tab)
		{
			if( j != 0 )
			{
				var option = document.createElement('option');
				option.value=j;
				option.appendChild(document.createTextNode(tab[j]));
				box.appendChild(option);
			}
		}
		form.appendChild(box);

		box = document.createElement('input');
		box.className="boite";
		box.type='submit';
		box.value=txt_info[nom][1];
		form.appendChild(box);
		return form;
		break;

	default:
		return document.createTextNode('ERREUR');
		break;
	}
}

function chg_doc(lien)
{
	window.location = lien;
}

getDocumentWidth = function(){
	return Math.max(document.documentElement.scrollWidth,document.width || 0);
};

getDocumentHeight = function(){
	return Math.max(document.documentElement.scrollHeight,document.documentElement.offsetHeight);
};

function HTLMconfirm(title, question, yes, no, action){
	var background = document.createElement("img");
	background.style.position = "absolute";
	background.id = "popupBackground";

	background.style.height = getDocumentHeight()+"px";
	background.style.width = getDocumentWidth()+"px";	
	
	background.style.top = 0+"px";
	background.style.left = 0+"px";
	background.src = "./View/js/blackOp60.png";
	background.style.zIndex = 99;
	
	document.body.appendChild(background);
	
	var conf = new Block("confirm");
	conf.setTitle(title);
	
	createTables(
		{"questionTable":
			{"questionLine":
				{"question":document.createTextNode(question)}
			},
		 "answerTable":
			{"answerLine":
				{"empty1,confEmpty":null,
				 "confYes":createButton('yes_txt',
				 												[
					 												function(event, elem, bg, ac){
					 													elem.parentNode.removeChild(elem); 
					 													bg.parentNode.removeChild(bg); action.call()},[conf.HTMLelement,background,action]
				 												],
				 												undefined,
				 												undefined,
				 												yes),
				 "empty2,confEmpty":null,
				 "confNo":createButton('no_txt',
				 											 [
					 											 function(event, elem, bg){
						 											 elem.parentNode.removeChild(elem); 
						 											 bg.parentNode.removeChild(bg)},
						 											 [conf.HTMLelement,background]
				 											 ],
				 											 undefined,
				 											 undefined,
				 											 no),
				 "empty3,confEmpty":null
				}
			}
		}
	,conf.content);
	
	conf.HTMLelement.style.position = "absolute";
	conf.HTMLelement.style.width = GLOBAL_BlocWidth;
	conf.HTMLelement.style.backgroundColor=graphique['fond']['normal'];
	
	var wSize = getwindowSize();
	
	conf.HTMLelement.style.top=(wSize[1]-conf.HTMLelement.offsetHeight)/2+"px";
	conf.HTMLelement.style.left=(wSize[0]-parseInt(conf.HTMLelement.style.width))/2+"px";
	
	conf.HTMLelement.style.zIndex = 100;
	
	document.body.appendChild(conf.HTMLelement);
}

function getwindowSize(){
	var myWidth = 800, myHeight = 500;
	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 fcal(numero) {
	var url = url_cal+'&numero='+numero;
	if( PHPSESSID != null)
		url += '&PHPSESSID='+PHPSESSID;
	top.hof=window.open(url,'calepin','width=410,height=520,menubar=0,toolbar=0,status=0,scrollbars=1,resizable=1');
	top.hof.document.close();
	top.hof.focus();
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function areArraysEqual(array1, array2) {
   var temp = new Array();
   if ( (!array1[0]) || (!array2[0]) ) { // If either is not an array
      return false;
   }
   if (array1.length != array2.length) {
      return false;
   }
   // Put all the elements from array1 into a "tagged" array
   for (var i=0; i<array1.length; i++) {
      key = (typeof array1[i]) + "~" + array1[i];
   // Use "typeof" so a number 1 isn't equal to a string "1".
      if (temp[key]) { temp[key]++; } else { temp[key] = 1; }
   // temp[key] = # of occurrences of the value (so an element could appear multiple times)
   }
   // Go through array2 - if same tag missing in "tagged" array, not equal
   for (var i=0; i<array2.length; i++) {
      key = (typeof array2[i]) + "~" + array2[i];
      if (temp[key]) {
         if (temp[key] == 0) { return false; } else { temp[key]--; }
      // Subtract to keep track of # of appearances in array2
      } else { // Key didn't appear in array1, arrays are not equal.
         return false;
      }
   }
   // If we get to this point, then every generated key in array1 showed up the exact same
   // number of times in array2, so the arrays are equal.
   return true;
}

function functionName(fn){
	var name=/\W*function\s+([\w\$]+)\(/.exec(fn);
	if(!name)return 'No name';
	return name[1];
}



function beginBlock(title){
  var block=new Block(title);
  block.setTitle(title);  
  block.content.innerHTML="CONTENT_HERE";
  block.content.style.backgroundColor="#EADD80";
  
  var begEndBlock = block.HTMLelement.innerHTML.split("CONTENT_HERE");
  endBlockHTML=begEndBlock[1];

  document.write(begEndBlock[0]);
}

var endBlockHTML="";
function endBlock(){
  document.write(endBlockHTML); //will not work if beginBlock is not called before
}

