var DynamicTable = new Class({

	initialize: function(table, options) 
	{
		this.table = table;
		this.readMoreLength = 100;
		this.readMoreFunc = null;
		this.readMoreLabel = "suite"
		this.cellValue = null;
		
		if (options.rowModel != null)
			rowModel = options.rowModel;
		else
			this._model();
			
		if (options.readMore != null)
		{
			this.readMoreLength = options.readMore.max;
			this.readMoreFunc = options.readMore.func;
			this.readMoreLabel = options.readMore.label;
		}
			
		if (options.cellValue != null)
			this.cellValue = options.cellValue;
	},
	
	setData: function(data)
	{
		this.data = data;
		this._display();
	},
	
	_model: function()
	{
		this.rowModel = $$("table[id="+this.table+"] tbody")[0].get("html");
	},
	
	_display: function()
	{
		var content = "";
		
		if (data instanceof Array)
		{
			for (var i = 0; i < data.length; i++)
			{
				content += this._buildRow(i);
			}
		}
		else
		{
			for (var i in data)
			{
				content += this._buildRow(i);
			}
		}
		
		$$("table[id="+this.table+"] tbody")[0].set("html", content);
	},
	
	_buildRow: function(rowId)
	{
		var rowContent = this.rowModel;
		
		for (var f in data[rowId])
		{
			var reg = new RegExp("(@"+f+"@)", "g");
			var cell = (this.cellValue != null) ? this.cellValue(rowId, f, data[rowId][f]):data[rowId][f];
			
			if (data[rowId][f] != null && this.readMoreLength[f] != null && data[rowId][f].length > this.readMoreLength[f])
				rowContent = rowContent.replace(reg, this._readMore(cell, rowId, f));
			else
				rowContent = rowContent.replace(reg, cell);
				
		}
		
		//replace reserved keywords
		rowContent = rowContent.replace(/(@row_index@)/g, rowId);
		
		//replace unused
		rowContent = rowContent.replace(new RegExp("(@.+@)", "g"), "");
		
		return rowContent;
	},
	
	_readMore: function(cell, i, f)
	{
		return cell.substring(0, (cell.length < this.readMoreLength[f]) ? cell.length:this.readMoreLength[f])+" <a href=\"javascript:"+this.readMoreFunc+"("+i+", '"+f+"')\">("+this.readMoreLabel+")</a>";
	}
});

var Pagination = new Class({

	Implements: Options,
	options: {
	
		first_id: "",
		prev_id: "",
		numbers_id: "",
		next_id: "",
		last_id: "",
		page: 0,
		pageSize: 20,
		maxResults: 1000,
		maxPage: Math.ceil(1000/20),
		callback: null
	},

	initialize: function(instance, options)
	{
		this.instance = instance;
		this.setOptions(options);
		this._init();
		this._display();
	},
	
	_init: function()
	{
		$(this.options.first_id).addEvent('click', this.first.bindWithEvent(this));
				
		$(this.options.prev_id).addEvent('click', this.previous.bindWithEvent(this));
		
		$(this.options.next_id).addEvent('click', this.next.bindWithEvent(this));
		
		$(this.options.last_id).addEvent('click', this.last.bindWithEvent(this));
	
	},
	
	_display: function()
	{
		$(this.options.first_id).setStyle("visibility", (this.options.page <= 0) ? "hidden":"visible");
		$(this.options.prev_id).setStyle("visibility", (this.options.page <= 0) ? "hidden":"visible");
		$(this.options.next_id).setStyle("visibility", (this.options.page >= this.options.maxPage-1) ? "hidden":"visible");
		$(this.options.last_id).setStyle("visibility", (this.options.page >= this.options.maxPage-1) ? "hidden":"visible");
		
		//génération des numéros de page
		var numbersCount = 5;
		var firstIndex = this.options.page-numbersCount+2;
		firstIndex = (firstIndex < 0 ? 0:firstIndex)+1;
		
		//set numbers content
		var content = "";
		for (var i = 0; i < numbersCount; i++)
		{
				
			if (this.options.page == i+firstIndex-1)
				content += "<span>"+(i+firstIndex)+"</span>";
			else
				content += "<a href=\"javascript:"+this.instance+".goTo("+(i+firstIndex-1)+")\">"+(i+firstIndex)+"</a>";
				
			if (i+firstIndex >= this.options.maxPage)
				break;
			
			if (i < numbersCount-1)
				content += "<span> | </span>";
		}
		
		$(this.options.numbers_id).set("html", content);
		
	},
	
	setMaxResults: function (maxResults)
	{
		this.options.maxPage = Math.ceil((this.options.maxResults = maxResults)/this.options.pageSize);
		this._display();
	},
	
	setPageSize: function (pageSize)
	{
		if (this.options.pageSize != pageSize)
			this.options.page = 0;
			
		this.options.pageSize = pageSize;
		this._display();
	},
	
	setPage: function (page)
	{
		this.options.page = page;
		this._display();
	},
	
	getLimit: function()
	{
		return "limit "+this.options.page*this.options.pageSize+", "+this.options.pageSize;
	},
	
	getPage: function()
	{
		return this.options.page;
	},
	
	getPageSize: function()
	{
		return this.options.pageSize;
	},
	
	first: function(event)
	{
		this.goTo(0);
	},
	
	previous: function(event)
	{
		this.goTo(this.options.page-1);
	},
	
	next: function(event)
	{
		this.goTo(this.options.page+1);
	},
	
	last: function(event)
	{
		this.goTo(this.options.maxPage-1);
	},
	
	goTo: function(page)
	{
		this.options.page = page;
		this._display();
		this.options.callback();
	}

});

var Hoover = new Class({


	initialize: function()
	{
		this.elements = {};
	},
	
	store: function(target)
	{
		this.target = target;
		this.elements[target] = $$(target)[0].get("html");
		$$(target)[0].set("html", "");
	},
	
	restore: function(target, options)
	{
		
		if (this.elements[target] == null)
			throw "Unknown target";
		
		var data = options.data;
		
		var content = this.elements[target];
		
		if (data != null)
		{
			for (var f in data)
			{
				var reg = new RegExp("(@"+f+"@)", "g");
				
				content = content.replace(reg, data[f] != null ? m_htmlEncode(data[f]).replace(/\s/g, "&#160;"):"");
			}

			//remove unused
			content = content.replace(new RegExp("(@[\\w\\d\\.]+@)", "g"), "");
			content = content.replace(new RegExp("\\w+=\\s", "g"), ""); //hack for ie , remove value= 

			var reg2 = new RegExp("(@\\{([^\}@]+)\\}@)", "g");
			var toEval = content.match(reg2);
			
			for (var i = 0; toEval != null && i < toEval.length; i++)
			{
				toEval[i] = toEval[i].replace("@{", "");
				toEval[i] = toEval[i].replace("}@", "");
				
				var out;
				
				out = eval("(function () { return "+toEval[i]+";})()");
				
				content = content.replace("eval=\"@{"+toEval[i]+"}@\"", out);
				content = content.replace("@{"+toEval[i]+"}@", out);
			}
			
		}
		
		return content;
	}


});

function m_postObjectToUrl(path, params, method) {
    
    method = method || "post"; // Set method to post by default, if not specified.

    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    for(var key in params) {
        var hiddenField = document.createElement("input");
        hiddenField.setAttribute("type", "hidden");
        hiddenField.setAttribute("name", key);
        hiddenField.setAttribute("value", params[key]);

        form.appendChild(hiddenField);
    }

    document.body.appendChild(form); 
    form.submit();
}

//retourne la date au format américain sous forme de chaine
function m_getYmd(date)
{
	var date = (typeof date == "undefined") ? new Date():date;
	
	var m = ((date.getMonth()+1 < 10) ? "0":"")+(date.getMonth()+1);
	
	var d = ((date.getDate() < 10) ? "0":"")+date.getDate();
	
	return ""+date.getFullYear()+m+d;
}

function m_getUniqueID() 
{ 
	var uniqueID = new Date();
	return uniqueID.getTime();
}


function m_formToJSON(target)
{
	var hm = $$("form[id="+target+"]")[0].toQueryString();
    hm = '{"'+hm+'"}'; 
    hm = hm.replace(/&/g, '","');
    hm = hm.replace(/=/g, '":"');
   
    return JSON.decode(hm);
}

function m_formToJSON2(target)
{
	var data = {};

	var inputs = $$("form[id="+target+"] input[type=text]")
		.concat($$("form[id="+target+"] input[type=hidden]"))
		.concat($$("form[id="+target+"] input[type=password]"))
		.concat($$("form[id="+target+"] textarea"))
		.concat($$("form[id="+target+"] select"));
		
	for (var i = 0; i < inputs.length; i++)
	{
		data[inputs[i].get("name")] = inputs[i].get("value");
	}

	return data;
}

function m_formToSQLCriteria(target, options)
{
	options = options || {};

	var inputs = $$("form[id="+target+"] input[type=text]")
		.concat($$("form[id="+target+"] input[type=hidden]"))
		.concat($$("form[id="+target+"] textarea"));
	
	criteria = "";
	
	for (var i = 0; i < inputs.length; i++)
	{
		if (inputs[i].get("value") != "")
			criteria += inputs[i].name+" like '"+(options.fulllike == true ? '%':'')+inputs[i].get("value")+"%' AND ";
	}
	
	if (criteria != "")
	{
		criteria = criteria.substring(0, criteria.length-4);
	}
	
	if (options.limit != null)
		criteria += " limit "+options.limit.page*options.limit.pageSize+", "+options.limit.pageSize;
	
	return criteria;

}

function m_urlParser(key ,url)
{
    if(arguments.length < 2) url = location.href;
    if(arguments.length > 0 && key != ""){
        if(key == "#"){
            var regex = new RegExp("[#]([^$]*)");
        } else if(key == "?"){
            var regex = new RegExp("[?]([^#$]*)");
        } else {
            var regex = new RegExp("[?&]"+key+"=([^&#]*)");
        }
        var results = regex.exec(url);
        return (results == null )? "" : results[1];
    } else {
        url = url.split("?");
        var results = {};
            if(url.length > 1){
                url = url[1].split("#");
                if(url.length > 1) results["hash"] = url[1];
                url[0].split("&").each(function(item,index){
                    item = item.split("=");
                    results[item[0]] = item[1];
                });
            }
        return results;
    }
}

/* string utils */

function m_escapeSingleQuotes(s)
{
	return s.replace(/([^\\])(\')/g, "$1\\'");
}

function m_escapeDoubleQuotes(s)
{
	return s.replace(/([^\\])(\")/g, "$1\\\"");
}

function m_htmlEncode(s)
{
	s = s.replace(/é/g, "&eacute;");
	s = s.replace(/è/g, "&eagrave;");
	s = s.replace(/à/g, "&agrave;");
	s = s.replace(/'/g, "&#39;");
	s = s.replace(/"/g, "&quot;");

	return s;
}

