var mess_non_lu=-1;var en_cours_move=false;var en_cours_action=false;

function requete_ajax(url){var myRequest = new Ajax.Request(url,{asynchronous:true,method:'get',evalScripts:true});}

function update_ajax(url,div){
	var myRequest = new Ajax.Request(url,{
	asynchronous:true,
	method:'get',
	evalScripts: true,
	onComplete: function(requester){
		if (requester.status==200)$(div).innerHTML = requester.responseText;
		$('loading').hide();
	},
	onLoading: function (requester){
		$('loading').show();
	}
	});
}

function popup_url(mon_form,str_prompt_url,str_prompt_nom) {
	var url= prompt(str_prompt_url,"http://");
	if(url != null && url !=''){
		var nom = prompt(str_prompt_nom);
		if(nom != null && nom != ''){
			$(mon_form).contenu.value +='[url='+url+']'+nom+'[/url]';
		}	
	}
}

function popup_img(mon_form,str_prompt_url,str_prompt_nom) {
	var img=prompt(str_prompt_url,"http://");
	if(img != null && img !=''){
		$(mon_form).contenu.value += '[img]'+img+'[/img]';	
	}
}

function fermer_infobulle(){
$('infobulle').style.display="none";
$('infobulle').innerHTML="";
$('filter').style.display="none";
}

function MyFormHelp(){}
MyFormHelp.prototype = {
    show : function(message){
	$('filter').style.display="block";
	$('infobulle').style.display="block";
	$('infobulle').style.top=(document.body.clientHeight/2-20)+"px";
	$('infobulle').style.left=(document.body.clientWidth/2-200)+"px";
	$("infobulle").innerHTML = message+'<br/><a onclick="fermer_infobulle();">ok</a>';
	}
}

function MyErrorDecorator(){}
MyErrorDecorator.prototype = {
    start : function(){ 
    },
    addError : function(control, messageType){
        var message='';
        if(messageType == 1){
            message = control.errRequired;
        }else if(messageType == 2){
            message = control.errInvalid;
        }else{
            message = "Error on '"+control.label+"' field";
        }
        var item = document.createElement("li");
        $("infobulle").innerHTML =message;
    },
    end : function(){
		$('filter').style.display="block";
		$('infobulle').style.display="block";
		$('infobulle').style.top=(document.body.clientHeight/2-20)+"px";
		$('infobulle').style.left=(document.body.clientWidth/2-200)+"px";
		$("infobulle").innerHTML += '<br/><a onclick="fermer_infobulle();">ok</a>';
	}
}
	
function inverse_selection(formulaire){
	temp = document.forms[formulaire].elements;
	for (i=0; i < temp.length; i++)
	{
		if(temp[i].id!='checkbox_envoi' && temp[i].id!='checkbox_reception')
		temp[i].checked=!temp[i].checked;
	}
}

function lancement_affichage_news(){
$('filter').style.display="block";
$('last_news').style.top="20px";
$('last_news').style.left=(document.body.clientWidth/2-320)+"px";
}

function fermer_last_news(url) {
$('last_news').style.display="none";
$('filter').style.display="none";
requete_ajax(url);
}

function compte_a_rebours(secondes,id_div){ 
	var h=Math.floor(secondes/3600);
	secondes=secondes-(h*3600);
	var m=Math.floor(secondes/60); 
	secondes=secondes -(m*60);
	var s=Math.floor(secondes);
	
	function decompte(){
		if (s>0) s--;
		else {	
			s=59;
			if (m>0)m--;
			else {pe.stop(); s=0;}
		}
		
		m=parseInt(m);
		h=parseInt(h);
		
		if (s<10) s='0'+s.toString();
		if (m<10) m='0'+m.toString();
		if (h<10) h='0'+h.toString();
		
		s_string=s.toString();
		s_string=s_string.substring(s_string.length-2,s_string.length);
		
		m_string=m.toString();
		m_string=m_string.substring(m_string.length-2,m_string.length);			
		
		h_string=h.toString();
		if(h<100)h_string=h_string.substring(h_string.length-2,h_string.length);	
			
		if ($(id_div)) $(id_div).innerHTML=h_string+":"+m_string+":"+s_string;
	}
	var pe = new PeriodicalExecuter(decompte, 1);
} 

function decompte_cooldown_decremente(){
	var tab_chrono=new Array;
	if($('barre_fixe_chrono_attaque')) tab_chrono.push('attaque');
	if($('barre_fixe_chrono_attaque_2')) tab_chrono.push('attaque_2');
	if($('barre_fixe_chrono_potion')) tab_chrono.push('potion');
	
	for(var i=0;i<tab_chrono.length;i++){
		chrono=parseInt($('barre_fixe_chrono_'+tab_chrono[i]).innerHTML);
		chrono--;
		if(chrono>0){
			$('barre_fixe_chrono_'+tab_chrono[i]).innerHTML=chrono.toString();
		}
		else{
			$('barre_fixe_chrono_'+tab_chrono[i]).innerHTML="";
			if(tab_chrono.length==1 && typeof(pe_decompte_cooldown)!='undefined')
			pe_decompte_cooldown.stop();
			delete pe_decompte_cooldown;
		}
	}
}

function decompte_cooldown(){
	if($('barre_fixe_chrono_attaque') || $('barre_fixe_chrono_attaque_2') || $('barre_fixe_chrono_potion')){
		pe_decompte_cooldown=new PeriodicalExecuter(decompte_cooldown_decremente, 1);
	}
	else{
		if(typeof(pe_decompte_cooldown)!='undefined')
		pe_decompte_cooldown.stop();
		delete pe_decompte_cooldown;
	}
}

function deplace_clavier(e){
var code;
if (!e) var e = window.event;
if (Prototype.Browser.IE && e.keyCode)code = e.keyCode;
else if (e.which)code = e.which;
switch(String.fromCharCode(code)){
		case 'q':
		case 'Q':
		if (clavier_type == "azerty") action_map(url_move_to_gauche,'move'); 
		break;
		case 'a':
		case 'A':
		if (clavier_type == "qwerty") action_map(url_move_to_gauche,'move'); 
		break;
		case 'z':
		case 'Z':
		if (clavier_type == "azerty") action_map(url_move_to_haut,'move');
		if (clavier_type == "qwertz") action_map(url_move_to_gauche,'move');
		break;
		case 'w':
		case 'W':
		if (clavier_type == "qwerty" || clavier_type == "qwertz") action_map(url_move_to_haut,'move'); 
		break;
		case 'd':
		case 'D':
		action_map(url_move_to_droite,'move'); 
		break; 
		case 's':
		case 'S':
		action_map(url_move_to_bas,'move'); 
		break;
		default:null;
		}
}

function action_map(url,type){
	if(type==undefined)type='action';
	if(Ajax.activeRequestCount<2 && 
	(!Prototype.Browser.Gecko || (action_map.caller && (action_map.caller.name=="onclick" || action_map.caller.name=="deplace_clavier"))))
	{
		if((type=='action' && en_cours_action==false) || (type=='move' && en_cours_move==false))
		{
		window['en_cours_'+type]=true;
		Event.stopObserving(window,'keypress',deplace_clavier);
		hide_popup();
		var myRequest = new Ajax.Request(url,{
			asynchronous:true,
			method:'get',
			evalScripts: true,
			onComplete: function (requester){
					if (requester.status==200){
						myArray = requester.responseJSON;
						if(myArray!=null){
							for(var tpl in myArray.tpl){
								$(tpl).innerHTML = myArray.tpl[tpl];
							}
						
							$('pa_texte').innerHTML=number_format(myArray.pa,0,'.',' ');
							$('pm_texte').innerHTML=number_format(myArray.pm,0,'.',' ');
							$('or_texte').innerHTML=number_format(myArray.po,0,'.',' ');
							affiche_barre('rouge',myArray.longueur_vie);
							affiche_barre('verte',myArray.longueur_mana);
							
							if(myArray.tpl_zone_log!=null){
								$('zone_log').innerHTML= myArray.tpl_zone_log;
								$('zone_log').show();
							}else $('zone_log').hide();
							
							
							if(myArray.tab_diff_pv!=null){
								tab_diff_pv=myArray.tab_diff_pv;
								affiche_tab_diff_pv();
							}
							if(typeof(pe_decompte_cooldown)=='undefined' && $('barre_fixe_chrono_sec'))
							decompte_cooldown();
							
							if(myArray.lvl_up!=null)affiche_lvl_up();
							
							if(mess_non_lu>0 && mess_non_lu<myArray.mess_non_lu)
							new Effect.Highlight('img_messagerie');
							mess_non_lu=myArray.mess_non_lu;
							
							if(myArray.error_log!=null)alert(myArray.error_log);
							
						}
					}
					else{
						//Element.show('failure');
					}
						$('loading').hide();
						window['en_cours_'+type]=false;
						Event.observe(window, 'keypress', deplace_clavier);
				},
			 onLoading: function (requester)
				{
					$('loading').show();
				}
			});
			}
		}
		return false;
}
function affiche_type_sac(type){	
	$("arme").style.display = 'none';
	$("objet").style.display = 'none';
	$("potion").style.display = 'none';
	if($("objetquete"))$("objetquete").style.display = 'none';
	$('onglet_arme').removeClassName('selected');
	$('onglet_objet').removeClassName('selected');
	$('onglet_potion').removeClassName('selected');
	if($("objetquete"))$('onglet_objetquete').removeClassName('selected');
	$(type).style.display = 'block';
	$('onglet_'+type).addClassName('selected');
	return false;
}

function switch_barre_skill(url){
	Effect.toggle('barre_fixe_skills_1', 'slide', {duration: 0.5});
	Effect.toggle('barre_fixe_skills_2', 'slide', {duration:0.5});
	requete_ajax(url);
}

function number_format( number, decimals, dec_point, thousands_sep ){
	var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
	var d = dec_point == undefined ? "," : dec_point;
	var t = thousands_sep == undefined ? "." : thousands_sep, s = n < 0 ? "-" : "";
	var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}

function affiche_barre(couleur,longueur){
	if(longueur>0)
	{
		$('jauge_'+couleur+'_bord1').show();
		$('jauge_'+couleur+'_bord2').show();
	}
	else
	{
		$('jauge_'+couleur+'_bord1').hide();
		$('jauge_'+couleur+'_bord2').hide();
	}
	$('jauge_'+couleur).style.width=longueur+"px";
}

function affiche_tab_diff_pv(){
	for (var i=0;i<tab_diff_pv.size();++i)
	{
		var item = tab_diff_pv[i];
		new Effect.Move(item,{duration:0.5,x: 0, y:-15});
		new Effect.Opacity(item,{duration:3.0,to:0.0});
	}
}

function affiche_lvl_up(){
	$('lvl_up').show();
	new Effect.Puff('lvl_up');
}

function show_popup(titre,message,top) {tooltip.show('<p>'+titre+'</p>'+message);}
function hide_popup(){tooltip.hide();}

var tooltip=function(){
var id = 'popup';
 var top = 3;
 var left = 3;
 var maxw = 300;
 var speed = 10;
 var timer = 20;
 var endalpha = 95;
 var alpha = 0;
 var tt,t,c,b,h;
 var ie = document.all ? true : false;
 return{
  show:function(v,w){
   if(tt == null){
    tt = document.createElement('div');
    tt.setAttribute('id',id);
    t = document.createElement('div');
    t.setAttribute('id',id + 'top');
    c = document.createElement('div');
    c.setAttribute('id',id + 'cont');
    b = document.createElement('div');
    b.setAttribute('id',id + 'bot');
    tt.appendChild(t);
    tt.appendChild(c);
    tt.appendChild(b);
    document.body.appendChild(tt);
    tt.style.opacity = 0;
    tt.style.filter = 'alpha(opacity=0)';
    document.onmousemove = this.pos;
   }
   if(tt != null){
		tt.style.display = 'block';
		c.innerHTML = v;
		tt.style.width = w ? w + 'px' : 'auto';
		if(!w && ie){
			t.style.display = 'none';
			b.style.display = 'none';
			tt.style.width = tt.offsetWidth;
			t.style.display = 'block';
			b.style.display = 'block';
		}
		if(tt.offsetWidth > maxw){tt.style.width = maxw + 'px'}
		h = parseInt(tt.offsetHeight) + top;
		 
		
		clearInterval(tt.timer);
		tt.timer = setInterval(function(){tooltip.fade(1)},timer);
	 }
  },
  pos:function(e){
  if(tt != null){
   var u = ie ? event.clientY + document.documentElement.scrollTop : e.pageY;
   var l = ie ? event.clientX + document.documentElement.scrollLeft : e.pageX;
   var pos_top=(u - h);
   if(pos_top<0)	pos_top=0;
   tt.style.top = pos_top + 'px';
   var pos_left=(l + left);
   if(pos_left<0)	pos_left=0;
   tt.style.left = pos_left + 'px';
   }
  },
  fade:function(d){
  if(tt != null){
   var a = alpha;
   if((a != endalpha && d == 1) || (a != 0 && d == -1)){
    var i = speed;
   if(endalpha - a < speed && d == 1){
    i = endalpha - a;
   }else if(alpha < speed && d == -1){
     i = a;
   }
   alpha = a + (i * d);
   tt.style.opacity = alpha * .01;
   tt.style.filter = 'alpha(opacity=' + alpha + ')';
  }else{
    clearInterval(tt.timer);
     if(d == -1){tt.style.display = 'none'}
  }
  }
 },
 hide:function(){
 if(tt != null){
  clearInterval(tt.timer);
  tt.timer = setInterval(function(){tooltip.fade(-1)},timer);
 }
  } 
 };
}();

/* js/jforms_light.js*/
var jForms = {
    _forms: {},

    tForm: null,
    frmElt: null,

    declareForm : function(aForm){
        this._forms[aForm.name]=aForm;
        if(window.jQuery)
            jQuery('#'+aForm.name).bind('submit',function (ev) { jQuery(ev.target).trigger('jFormsUpdateFields'); return jForms.verifyForm(ev.target); });
        else{
            var elem = document.getElementById(aForm.name);
            if (elem.addEventListener) {
                elem.addEventListener("submit", function (ev) { if(!jForms.verifyForm(elem)) {ev.preventDefault(); ev.stopPropagation(); return false;} return true; }, false);
            } else if (elem.attachEvent) {
                elem.attachEvent("onsubmit", function (ev) { if(!jForms.verifyForm(elem)) { window.event.cancelBubble = true ; window.event.returnValue = false; return false;} return true;});
            }
        }
    },

    getForm : function (name) {
        return this._forms[name];
    },

    verifyForm : function(frmElt){
        this.tForm = this._forms[frmElt.attributes.getNamedItem("id").value]; // we cannot use getAttribute for id because a bug with IE
        this.frmElt = frmElt;
        var msg = '';
        var valid = true;
        this.tForm.errorDecorator.start();
        for(var i =0; i < this.tForm.controls.length; i++){
            var c = this.tForm.controls[i];
            if(typeof c.getValue == 'function')
                var val = c.getValue();
            else{
                var elt = frmElt.elements[c.name];
                if (!elt) continue; // sometimes, all controls are not generated...
                var val = this.getValue(elt);
            }
            if(val === null || val === false){ 
                if(c.required){
                    this.tForm.errorDecorator.addError(c, 1);
                    valid = false;
                }
            }else{
                if(!c.check(val, this)){
                    this.tForm.errorDecorator.addError(c, 2);
                    valid = false;
                }
            }
        }
        if(!valid)
            this.tForm.errorDecorator.end();
        return valid;
    },

    trim : function (str) {
        if(str.replace)
            return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
        else return str;
    },

    getValue : function (elt){
        if(elt.nodeType) { // this is a node
            switch (elt.nodeName.toLowerCase()) {
                case "input":
                    if(elt.getAttribute('type') == 'checkbox')
                        return elt.checked;
                case "textarea":
                    var val = this.trim(elt.value);
                    return val!==''?val:null; 
                case "select":
                    if (!elt.multiple)
                        return (elt.value!==''?elt.value:null);
                    var values = [];
                    for (var i = 0; i < elt.options.length; i++) {
                        if (elt.options[i].selected)
                            values.push(elt.options[i].value);
                    }
                    if(values.length) 
                        return values; 
                    return null;
            }
        } else if(this.isCollection(elt)){
            // this is a NodeList of radio buttons or multiple checkboxes
            var values = [];
            for (var i = 0; i < elt.length; i++) {
                var item = elt[i];
                if (item.checked)
                    values.push(item.value);
            }
            if(values.length) {
                if (elt[0].getAttribute('type') == 'radio')
                    return values[0];
                return values; 
            }
        }
        return null;
    },

    hasClass: function (elt,clss) {
        return elt.className.match(new RegExp('(\\s|^)'+clss+'(\\s|$)'));
    },
    addClass: function (elt,clss) {
        if (this.isCollection(elt)) {
            for(var j=0; j<elt.length;j++) {
                if (!this.hasClass(elt[j],clss)) {
                    elt[j].className += " "+clss;
                }
            }
        } else {
            if (!this.hasClass(elt,clss)) {
                elt.className += " "+clss;
            }
        }
    },
    removeClass: function (elt,clss) {
        if (this.isCollection(elt)) {
            for(var j=0; j<elt.length;j++) {
                if (this.hasClass(elt[j],clss)) {
                    elt[j].className = elt[j].className.replace(new RegExp('(\\s|^)'+clss+'(\\s|$)'),' ');
                }
            }
        } else {
            if (this.hasClass(elt,clss)) {
                elt.className = elt.className.replace(new RegExp('(\\s|^)'+clss+'(\\s|$)'),' ');
            }
        }
    },
    setAttribute: function(elt, name, value){
        if (this.isCollection(elt)) {
            for(var j=0; j<elt.length;j++) {
                elt[j].setAttribute(name, value);
            }
        } else {
            elt.setAttribute(name, value);
        }
    },
    removeAttribute: function(elt, name){
        if (this.isCollection(elt)) {
            for(var j=0; j<elt.length;j++) {
                elt[j].removeAttribute(name);
            }
        } else {
            elt.removeAttribute(name);
        }
    },
    isCollection: function(elt) {
        if (typeof HTMLCollection != "undefined" && elt instanceof HTMLCollection) {
            return true;
        }
        if (typeof NodeList != "undefined" && elt instanceof NodeList) {
          return true;
        }
        if (elt instanceof Array)
            return true;
        if (elt.length != undefined && (elt.localName == undefined || elt.localName == 'SELECT' || elt.localName != 'select'))
            return true;
        return false;
    }
};

/**
 * represents a form
 */
function jFormsForm(name){
    this.name = name;
    this.controls = [];
    this.errorDecorator =  new jFormsErrorDecoratorAlert();
};

jFormsForm.prototype={
    addControl : function(ctrl){
        this.controls.push(ctrl);
        ctrl.formName = this.name;
    },

    setErrorDecorator : function (decorator){
        this.errorDecorator = decorator;
    },

    getControl : function(aControlName) {
        var ctrls = this.controls;
        for(var i=0; i < ctrls.length; i++){
            if (ctrls[i].name == aControlName) {
                return ctrls[i];
            }
        }
        return null;
    }
};


/**
 * control with string
 */
function jFormsControlString(name, label) {
    this.name = name;
    this.label = label;
    this.required = false;
    this.errInvalid = '';
    this.errRequired = '';
    this.minLength = -1;
    this.maxLength = -1;
};
jFormsControlString.prototype.check = function (val, jfrm) {
    if(this.minLength != -1 && val.length < this.minLength)
        return false;
    if(this.maxLength != -1 && val.length > this.maxLength)
        return false;
    return true;
};

/**
 * control for secret input
 */
function jFormsControlSecret(name, label) {
    this.name = name;
    this.label = label;
    this.required = false;
    this.errInvalid = '';
    this.errRequired = '';
    this.minLength = -1;
    this.maxLength = -1;
};
jFormsControlSecret.prototype.check = function (val, jfrm) {
    if(this.minLength != -1 && val.length < this.minLength)
        return false;
    if(this.maxLength != -1 && val.length > this.maxLength)
        return false;
    return true;
};

/**
 * confirm control
 */
function jFormsControlConfirm(name, label) {
    this.name = name;
    this.label = label;
    this.required = false;
    this.errInvalid = '';
    this.errRequired = '';
    this._masterControl = name.replace(/_confirm$/,'');
};
jFormsControlConfirm.prototype.check = function(val, jfrm) {
    if(jfrm.getValue(jfrm.frmElt.elements[this._masterControl]) !== val)
        return false;
    return true;
};

/**
 * control with boolean
 */
function jFormsControlBoolean(name, label) {
    this.name = name;
    this.label = label;
    this.required = false;
    this.errInvalid = '';
    this.errRequired = '';
};
jFormsControlBoolean.prototype.check = function (val, jfrm) {
    return (val == true || val == false);
};

/**
 * control with Decimal
 */
function jFormsControlDecimal(name, label) {
    this.name = name;
    this.label = label;
    this.required = false;
    this.errInvalid = '';
    this.errRequired = '';
};
jFormsControlDecimal.prototype.check = function (val, jfrm) {
    return ( -1 != val.search(/^\s*[\+\-]?\d+(\.\d+)?\s*$/));
};

/**
 * control with Integer
 */
function jFormsControlInteger(name, label) {
    this.name = name;
    this.label = label;
    this.required = false;
    this.errInvalid = '';
    this.errRequired = '';
};
jFormsControlInteger.prototype.check = function (val, jfrm) {
    return ( -1 != val.search(/^\s*[\+\-]?\d+\s*$/));
};

/**
 * control with Hexadecimal
 */
function jFormsControlHexadecimal(name, label) {
    this.name = name;
    this.label = label;
    this.required = false;
    this.errInvalid = '';
    this.errRequired = '';
};
jFormsControlHexadecimal.prototype.check = function (val, jfrm) {
  return (val.search(/^0x[a-f0-9A-F]+$/) != -1);
};

/**
 * control with Datetime
 */
function jFormsControlDatetime(name, label) {
    this.name = name;
    this.label = label;
    this.required = false;
    this.errInvalid = '';
    this.errRequired = '';
    this.minDate = null;
    this.maxDate = null;
    this.multiFields = false;
};
jFormsControlDatetime.prototype.check = function (val, jfrm) {
    var t = val.match(/^(\d{4})\-(\d{2})\-(\d{2}) (\d{2}):(\d{2})(:(\d{2}))?$/);
    if(t == null) return false;
    var yy = parseInt(t[1],10);
    var mm = parseInt(t[2],10) -1;
    var dd = parseInt(t[3],10);
    var th = parseInt(t[4],10);
    var tm = parseInt(t[5],10);
    var ts = 0;
    if(t[7] != null && t[7] != "")
        ts = parseInt(t[7],10);
    var dt = new Date(yy,mm,dd,th,tm,ts);
    if(yy != dt.getFullYear() || mm != dt.getMonth() || dd != dt.getDate() || th != dt.getHours() || tm != dt.getMinutes() || ts != dt.getSeconds())
        return false;
    else if((this.minDate !== null && val < this.minDate) || (this.maxDate !== null && val > this.maxDate))
        return false;
    return true;
};
jFormsControlDatetime.prototype.getValue = function(){
    if(!this.multiFields){ 
	var val = document.getElementById(this.formName+'_'+this.name).value.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); 
	return val!==''?val:null; 
    } 
    var controlId = this.formName+'_'+this.name;
    var v = document.getElementById(controlId+'_year').value + '-'
        + document.getElementById(controlId+'_month').value + '-'
        + document.getElementById(controlId+'_day').value + ' '
        + document.getElementById(controlId+'_hour').value + ':'
        + document.getElementById(controlId+'_minutes').value;

    var secondsControl = document.getElementById(this.formName+'_'+this.name+'_seconds');
    if(secondsControl.getAttribute('type') !== 'hidden'){
        v += ':'+secondsControl.value;
        if(v == '-- ::')
            return null;
    }
    else if(v == '-- :')
        return null;
    return v;
};

/**
 * control with Date
 */
function jFormsControlDate(name, label) {
    this.name = name;
    this.label = label;
    this.required = false;
    this.errInvalid = '';
    this.errRequired = '';
    this.multiFields = false;
    this.minDate = null;
    this.maxDate = null;
};
jFormsControlDate.prototype.check = function (val, jfrm) {
    var t = val.match(/^(\d{4})\-(\d{2})\-(\d{2})$/);
    if(t == null) return false;
    var yy = parseInt(t[1],10);
    var mm = parseInt(t[2],10) -1;
    var dd = parseInt(t[3],10);
    var dt = new Date(yy,mm,dd,0,0,0);
    if(yy != dt.getFullYear() || mm != dt.getMonth() || dd != dt.getDate())
        return false;
    else if((this.minDate !== null && val < this.minDate) || (this.maxDate !== null && val > this.maxDate))
        return false;
    return true;
};
jFormsControlDate.prototype.getValue = function(){
    if(!this.multiFields){ 
	var val = document.getElementById(this.formName+'_'+this.name).value.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); 
	return val!==''?val:null; 
    } 

    var controlId = this.formName+'_'+this.name;
    var v = document.getElementById(controlId+'_year').value + '-'
        + document.getElementById(controlId+'_month').value + '-'
        + document.getElementById(controlId+'_day').value;
    if(v == '--')
        return null;
    return v;
};

/**
 * control with time
 */
function jFormsControlTime(name, label) {
    this.name = name;
    this.label = label;
    this.required = false;
    this.errInvalid = '';
    this.errRequired = '';
};
jFormsControlTime.prototype.check = function (val, jfrm) {
    var t = val.match(/^(\d{2}):(\d{2})(:(\d{2}))?$/);
    if(t == null) return false;
    var th = parseInt(t[1],10);
    var tm = parseInt(t[2],10);
    var ts = 0;
    if(t[4] != null)
        ts = parseInt(t[4],10);
    var dt = new Date(2007,05,02,th,tm,ts);
    if(th != dt.getHours() || tm != dt.getMinutes() || ts != dt.getSeconds())
        return false;
    else
        return true;
};

/**
 * control with LocaleDateTime
 */
function jFormsControlLocaleDatetime(name, label) {
    this.name = name;
    this.label = label;
    this.required = false;
    this.errInvalid = '';
    this.errRequired = '';
    this.lang='';
};
jFormsControlLocaleDatetime.prototype.check = function (val, jfrm) {
    var yy, mm, dd, th, tm, ts;
    if(this.lang.indexOf('fr_') == 0) {
        var t = val.match(/^(\d{2})\/(\d{2})\/(\d{4}) (\d{2}):(\d{2})(:(\d{2}))?$/);
        if(t == null) return false;
        yy = parseInt(t[3],10);
        mm = parseInt(t[2],10) -1;
        dd = parseInt(t[1],10);
        th = parseInt(t[4],10);
        tm = parseInt(t[5],10);
        ts = 0;
        if(t[7] != null)
            ts = parseInt(t[7],10);
    }else{
        //default is en_* format
        var t = val.match(/^(\d{2})\/(\d{2})\/(\d{4}) (\d{2}):(\d{2})(:(\d{2}))?$/);
        if(t == null) return false;
        yy = parseInt(t[3],10);
        mm = parseInt(t[1],10) -1;
        dd = parseInt(t[2],10);
        th = parseInt(t[4],10);
        tm = parseInt(t[5],10);
        ts = 0;
        if(t[7] != null)
            ts = parseInt(t[7],10);
    }
    var dt = new Date(yy,mm,dd,th,tm,ts);
    if(yy != dt.getFullYear() || mm != dt.getMonth() || dd != dt.getDate() || th != dt.getHours() || tm != dt.getMinutes() || ts != dt.getSeconds())
        return false;
    else
        return true;
};

/**
 * control with localedate
 */
function jFormsControlLocaleDate(name, label) {
    this.name = name;
    this.label = label;
    this.required = false;
    this.errInvalid = '';
    this.errRequired = '';
    this.lang='';
};
jFormsControlLocaleDate.prototype.check = function (val, jfrm) {
    var yy, mm, dd;
    if(this.lang.indexOf('fr_') == 0) {
        var t = val.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);
        if(t == null) return false;
        yy = parseInt(t[3],10);
        mm = parseInt(t[2],10) -1;
        dd = parseInt(t[1],10);
    }else{
        //default is en_* format
        var t = val.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);
        if(t == null) return false;
        yy = parseInt(t[3],10);
        mm = parseInt(t[1],10) -1;
        dd = parseInt(t[2],10);
    }
    var dt = new Date(yy,mm,dd,0,0,0);
    if(yy != dt.getFullYear() || mm != dt.getMonth() || dd != dt.getDate())
        return false;
    else
        return true;
};

/**
 * control with Url
 */
function jFormsControlUrl(name, label) {
    this.name = name;
    this.label = label;
    this.required = false;
    this.errInvalid = '';
    this.errRequired = '';
};
jFormsControlUrl.prototype.check = function (val, jfrm) {
    return (val.search(/^[a-z]+:\/\/((((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9])))|((([A-Za-z0-9\-])+\.)+[A-Za-z\-]+))((\/)|$)/) != -1);
};

/**
 * control with email
 */
function jFormsControlEmail(name, label) {
    this.name = name;
    this.label = label;
    this.required = false;
    this.errInvalid = '';
    this.errRequired = '';
};
jFormsControlEmail.prototype.check = function (val, jfrm) {
    return (val.search(/^((\"[^\"f\n\r\t\b]+\")|([\w\!\#\$\%\&\'\*\+\-\~\/\^\`\|\{\}]+(\.[\w\!\#\$\%\&\'\*\+\-\~\/\^\`\|\{\}]+)*))@((\[(((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9])))\])|(((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9])))|((([A-Za-z0-9\-])+\.)+[A-Za-z\-]+))$/) != -1);
};


/**
 * control with ipv4
 */
function jFormsControlIpv4(name, label) {
    this.name = name;
    this.label = label;
    this.required = false;
    this.errInvalid = '';
    this.errRequired = '';
};
jFormsControlIpv4.prototype.check = function (val, jfrm) {
    var t = val.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
    if(t)
        return (t[1] < 256 && t[2] < 256 && t[3] < 256 && t[4] < 256);
    return false;
};

/**
 * control with ipv6
 */
function jFormsControlIpv6(name, label) {
    this.name = name;
    this.label = label;
    this.required = false;
    this.errInvalid = '';
    this.errRequired = '';
};
jFormsControlIpv6.prototype.check = function (val, jfrm) {
    return (val.search(/^([a-f0-9]{1,4})(:([a-f0-9]{1,4})){7}$/i) != -1);
};

/**
 * choice control
 */
function jFormsControlChoice(name, label) {
    this.name = name;
    this.label = label;
    this.required = false;
    this.errInvalid = '';
    this.errRequired = '';
    this.items = {};
};
jFormsControlChoice.prototype = {
    addControl : function (ctrl, itemValue) {
        if(this.items[itemValue] == undefined)
            this.items[itemValue] = [];
        this.items[itemValue].push(ctrl);
    },
    check : function (val, jfrm) {
        if(this.items[val] == undefined)
            return false;

        var list = this.items[val];
        var valid = true;
        for(var i=0; i < list.length; i++) {
            var val2 = jfrm.getValue(jfrm.frmElt.elements[list[i].name]);

            if (val2 == '') {
                if (list[i].required) {
                    jfrm.tForm.errorDecorator.addError(list[i], 1);
                    valid = false;
                }
            } else if (!list[i].check(val2, jfrm)) {
                jfrm.tForm.errorDecorator.addError(list[i], 2);
                valid = false;
            }
        }
        return valid;
    },
    activate : function (val) {
        var frmElt = document.getElementById(this.formName);
        for(var j in this.items) {
            var list = this.items[j];
            for(var i=0; i < list.length; i++) {
                var elt = frmElt.elements[list[i].name];
                if (val == j) {
                    jForms.removeAttribute(elt, "readonly");
                    jForms.removeClass(elt, "jforms-readonly");
                } else {
                    jForms.setAttribute(elt, "readonly", "readonly");
                    jForms.addClass(elt, "jforms-readonly");
                }
            }
        }
    }
};

/**
 * Decorator to display errors in an alert dialog box
 */
function jFormsErrorDecoratorAlert(){
    this.message = '';
};

jFormsErrorDecoratorAlert.prototype = {
    start : function(){
        this.message = '';
    },
    addError : function(control, messageType){
        if(messageType == 1){
            this.message  +="* "+control.errRequired + "\n";
        }else if(messageType == 2){
            this.message  +="* "+control.errInvalid + "\n";
        }else{
            this.message  += "* Error on '"+control.label+"' field\n";
        }
    },
    end : function(){
        if(this.message != ''){
            alert(this.message);
        }
    }
};

