var nbBoxItem = 0;
var nbCol = 3;
var objCol = Array();

var boxItemArray = new Array();
var boxObjArray = new Array();
var indicBox;
var dragBoxItem = false;
var mouseX = 0;
var mouseY = 0;
var dragItemX = 0;
var dragItemY = 0;
var antilag = -1;
var bordersize = 2;
var okToMove = true;


// getBoxPos
function getBoxCol(id) {
	return objPosition[id]?objPosition[id]:1;
}

/*
** Fonction qui initialise les evenements 
*/
function initEvents() {
	document.body.onmousemove = moveBoxItem;
	document.body.onmouseup = stopDragBoxItem;
	document.body.onselectstart = cancelSelectionEvent;
	document.body.ondragstart = new Function("return false");
}

function cancelSelectionEvent(e) {
	if(document.all)e = event;
	if (e.target) source = e.target;
		else if (e.srcElement) source = e.srcElement;
		if (source.nodeType == 3) // defeat Safari bug
			source = source.parentNode;
	if(source.tagName.toLowerCase()=='input')return true;
	if(antilag>=0) return false; else return true;	
}

/*
** Fonction qui stop le dragging
*/
function stopDragBoxItem() {
	if(dragBoxItem) {
		antilag = -1;
		if(indicBox.parentNode!=document.body) {
			indicBox.parentNode.insertBefore(dragBoxItem,indicBox);
			indicBox.style.display='none';
			document.body.appendChild(indicBox);
			dragBoxItem.style.position = '';	
			dragBoxItem.style.textAlign = '';
			dragBoxItem.style.width = '';
			saveCook();
		}
		dragBoxItem.style.filter = null;
		dragBoxItem.style.opacity = null;
		dragBoxItem = false;

	}
}

/*
** Retourne la distance entre l'objet et le haut de l'ecran
*/
function getTopPos(inputObj) {		
	var returnValue = inputObj.offsetTop;
	while((inputObj = inputObj.offsetParent) != null) {
		if(inputObj.tagName!='HTML')returnValue += inputObj.offsetTop;
	}
	return returnValue;
}

/*
** Retourne la distance entre l'objet et la gauche de l'ecran
*/
function getLeftPos(inputObj) {
	var returnValue = inputObj.offsetLeft;
	while((inputObj = inputObj.offsetParent) != null) {
		if(inputObj.tagName!='HTML')returnValue += inputObj.offsetLeft;
	}
	return returnValue;
}

/*
** Fonction qui crée le rectangle indicateur
*/
function createIndicBox() {
	var objBody = document.getElementsByTagName("body").item(0);
	indicBox = document.createElement("DIV");
	indicBox.setAttribute('id','indic');
	objBody.insertBefore(indicBox, objBody.firstChild);
}

/*
** Fonction qui crée les colonnes
*/
function createColumns() {
	var area = document.getElementById('floatingBoxParentContainer');
	area.innerHTML='';
	var width = Math.round(100/nbCol);
	for(i=1;i<=nbCol;i++) {
		var col = document.createElement("div");
		col.className = 'column';
		col.id = 'column'+i;
		col.innerHTML = '<hr style="display: none;"><hr>';
		col.style.width = width+'%';
		area.appendChild(col);
	}
}

/*
** Fonction appelée lorsqu'on clique sur un boxItem
*/
function selectBoxItem(e) {
	if(document.all)e = event;
	if (e.target) source = e.target;
			else if (e.srcElement) source = e.srcElement;
			if (source.nodeType == 3) // defeat Safari bug
				source = source.parentNode;
	if(source.tagName.toLowerCase()=='a' || source.tagName.toLowerCase()=='input') return;
	dragBoxItem = this.parentNode;
	mouseX = e.clientX;
	mouseY = e.clientY;
	dragItemX = getLeftPos(dragBoxItem)/1;
	dragItemY = getTopPos(dragBoxItem)/1 - document.documentElement.scrollTop;
	antilag = 0;
	antiLag();
	return false;
}

/*
** Ajouter un Evenement une fois la page et le script chargé
*/
function addLoadEvent(func) {	
	var oldonload = window.onload;
	if (typeof window.onload != 'function'){
    	window.onload = func;
	} else {
		window.onload = function(){
		oldonload();
		func();
		}
	}
}

/*
** Fonction antiLag
*/
function antiLag() {
		if(antilag>=0 && antilag<10){
			antilag++;
			setTimeout('antiLag()',10);
			return;
		}
}

/*
** Bouge les elements
*/
function moveBoxItem(e) {
	
	
	if(document.all)e = event;
	if(!antilag || antilag<10) return;
	if(dragBoxItem.parentNode!=document.body) {
		dragBoxItem.style.width = (dragBoxItem.offsetWidth - (2 * bordersize)) + 'px';
		dragBoxItem.style.position = 'absolute';	
		dragBoxItem.style.textAlign = 'left';
		dragBoxItem.style.filter = 'alpha(opacity=80)';
		dragBoxItem.style.opacity = '0.8';
		dragBoxItem.parentNode.insertBefore(indicBox,dragBoxItem);
		indicBox.style.height = (dragBoxItem.offsetHeight - (2 * bordersize)) + 'px';
		indicBox.style.display='block';
		document.body.appendChild(dragBoxItem);
	}
	if(dragBoxItem) {
		dragBoxItem.style.left = (e.clientX - mouseX + dragItemX) + 'px';
		dragBoxItem.style.top = (dragItemY - mouseY + e.clientY + document.documentElement.scrollTop) + 'px';
	}
	
	if(!okToMove)return;
	okToMove = false;
	var leftPos = e.clientX;
	var topPos = e.clientY + document.documentElement.scrollTop;
	var found = false;
	var tmpX = getLeftPos(indicBox);
	var tmpY = getTopPos(indicBox);
	if ((leftPos>tmpX && leftPos<(tmpX + indicBox.offsetWidth) && topPos>tmpY && topPos<(tmpY + indicBox.offsetHeight))) {
		setTimeout('okToMove=true',100);
		return;
	}
	for(i=0 ; i < nbBoxItem ; i++) {
		if(boxItemArray[i]==dragBoxItem || boxItemArray[i]==null) continue;
		var tmpX = getLeftPos(boxItemArray[i]);
		var tmpY = getTopPos(boxItemArray[i]);
		if(leftPos>tmpX && leftPos<(tmpX + boxItemArray[i].offsetWidth) && topPos>tmpY && topPos<(tmpY + (boxItemArray[i].offsetHeight/2))){
			boxItemArray[i].parentNode.insertBefore(indicBox,boxItemArray[i]);
			indicBox.style.display = 'block';
			found = true;
			break;
		}
		if(leftPos>tmpX && leftPos<(tmpX + boxItemArray[i].offsetWidth) && topPos>=(tmpY + (boxItemArray[i].offsetHeight/2)) && topPos<(tmpY + boxItemArray[i].offsetHeight)){
			//	boxItemArray[i].nextSibling.parentNode.insertBefore(indicBox,boxItemArray[i].nextSibling);
			boxItemArray[i].nextSibling.parentNode.insertBefore(indicBox,boxItemArray[i]);
			indicBox.style.display = 'block';
			found = true;
			break;					
		}
	}
	if(!found) for(var no=1;no<=nbCol;no++){
		var obj = document.getElementById('column' + no);			
		var left = getLeftPos(obj)/1;	
		if(leftPos>left && leftPos<(left+obj.offsetWidth)) {
			if(topPos<(getTopPos(obj)+obj.firstChild.offsetHeight)) {
				try{
					obj.insertBefore(indicBox,obj.firstChild.nextSibling);
				}catch(err) {}
			} else {
				obj.insertBefore(indicBox,obj.lastChild);
			}
			indicBox.style.display='block';
			break;	
		}	
	}		
	setTimeout('okToMove=true',100);
}

/*
** Fonction cookies
*/
function saveCook(wait) {
	if(wait) {
		setTimeout('saveCook()',wait);
		return;
	}
	objpos = '';
	firstcol = true;

	for(var no=1;no<=nbCol;no++) {
		if(firstcol) firstcol = false; else objpos += '|';

		var alldiv = document.getElementById('column' + no).getElementsByTagName("DIV");
		if(alldiv.length==0)continue;

		firstbox = true;

		for(i = 0 ; i < alldiv.length ; i++) { 
			if(alldiv[i].className=='boxItem') {
				if(firstbox) firstbox = false; else objpos += ',';
				boxId = alldiv[i].id.replace(/[^0-9]/g,'');
				objpos += boxObjArray[boxId].id;
			}	
		}
	}

	var ajaxObj = new Ajax();
	ajaxObj.request("/save.php?action=savepos&pos=" + objpos, {method: 'GET'});
}


function LoadCook() {
	var ajaxObj = new Ajax();

	ajaxObj.onsuccess = function() { 
		if(ajaxObj.responseText.length > 0) {
			eval(ajaxObj.responseText);
		} else {
			new FeedReader({url: 'http://www.ebb.com/blogue/?feed=rss2', col: 1});
			new Module({url: 'http://www.jaide.ca/modules/meteo.html', col: 2});
			new Module({url: 'http://www.jaide.ca/modules/welcome.html', col: nbCol});
			saveCook(500);
		}
	}
	ajaxObj.request("/load.php", {method: 'GET'});
}


getCookie = function(name) { 
	var start = document.cookie.indexOf(name+"="); 
	var len = start+name.length+1; 
	if ((!start) && (name != document.cookie.substring(0,name.length))) return null; 
	if (start == -1) return null; 
	var end = document.cookie.indexOf(";",len); 
	if (end == -1) end = document.cookie.length; 
	return unescape(document.cookie.substring(len,end)); 
} 

setCookie = function(name,value,expires,path,domain,secure) { 
	expires = expires * 60*60*24*1000;
	var today = new Date();
	var expires_date = new Date( today.getTime() + (expires) );
	var cookieString = name + "=" +escape(value) + 
	   ( (expires) ? ";expires=" + expires_date.toGMTString() : "") + 
	   ( (path) ? ";path=" + path : "") + 
	   ( (domain) ? ";domain=" + domain : "") + 
	   ( (secure) ? ";secure" : ""); 
	document.cookie = cookieString; 
} 

/*
** Initialisation du script
*/
addLoadEvent(createColumns);
addLoadEvent(createIndicBox);
addLoadEvent(initEvents);
addLoadEvent(LoadCook);