// IMPLEMENT
// Addtional function & object to mootools

// Find all element in a form by name.
function $FS(selector, filter){
	var elArr = new Array();
	var form = filter ? $(filter) : false;
	for (var i = 0; i<document.forms.length; i++){
		if (!form || form == document.forms[i]) {
			for (var j = 0; j < document.forms[i].elements.length; j++) {
				if (selector == document.forms[i].elements[j].name) {
					elArr.push(document.forms[i].elements[j]);
				}
			}
		}
	}
	return elArr;
}

// find the first element in a form
function $F(selector, filter){
	return $FS(selector, filter)[0] || false;
}

// init basic mask frame
function getFrames(){
    var opacity = 0.8;
    var frameColor = "#000000";
	var maskIframe = $("maskIframe");
	var docBody = document.body;

    // create mask iframe
    if (!maskIframe) {
        maskIframe = new IFrame({
			"id": "maskIframe",
			"src": "javascript:false;",
			"frameBorder": 0,
			"scrolling": "no",
			"styles": {
				"width": Math.max(window.getWidth(), docBody.offsetWidth) + "px",
				"height": Math.max(window.getHeight(), docBody.offsetHeight) + "px",
				"z-index": 0,
				"display": "none",
				"position": "absolute",
				"margin": 0,
				"padding": 0,
				"top": 0,
				"left": 0,
				"opacity": opacity,
				"visibility": "hidden"
			}
		}).inject(docBody);

		// color mask Iframe
		var doc = maskIframe.contentDocument;
		if (doc == undefined || doc == null) {
			doc = maskIframe.contentWindow.document;
		}
		doc.open();
		doc.write("<html><body bgColor='" + frameColor + "'></body></html>");
		doc.close();
    }

	return maskIframe;
};

// show mask function
function showMask(){
	getFrames().set("styles", {
		"display": "block",
		"z-index": 990
	});
};

// hide mask
function hideMask(){
	getFrames().set("styles", {
		"display": "none"
	});
};

// implements
Element.implement({
	isChildOf: function(el) {
		var e = this;
		while (e && typeof(e.getParent) != "undefined" && e.tagName.toLowerCase() != "body") {
			if (e == el) {
				return true;
			}
			e = e.getParent();
		}
		return false;
	},

	isVisible: function(){
		var el = this.getParent();
	    while (el) {
	        if (el.getStyle("display") == "none" || el.getStyle("visibility") == "hidden") { return false; }
	        el = el.getParent();
	    }
	    return true;
	},

	ieFixLayerShow: function(){
		if (!Browser.Engine.trident4) {
			return;
		}
		var dim = this.getCoordinates();
		if (!this.iframeFx) {
			this.iframeFx = new IFrame({
				"id": this.id+"iframeFx",
				"src": "javascript:false;",
				"frameBorder": 0,
				"scrolling": "no",
				"styles": {
					"border": "0 none",
					"margin": 0,
					"padding": 0,
					"z-index": 998,
					"display": "none",
					"position": "absolute",
					"filter": "progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)"
				}
			}).inject(this, "before");
		}
		//
		this.iframeFx.set("styles", {
			"visibility": "visible",
			"display": "block",
			"top": dim.top,
			"left": dim.left,
			"width": dim.width,
			"height": dim.height,
			"z-index": 998
		});
	},

	ieFixLayerHide: function(){
		if (!Browser.Engine.trident4) {
			return;
		}
		if (this.iframeFx) {
			this.iframeFx.set("styles", {
				"visibility": "hidden",
				"display": "none"
			});
		}
	},

	dragClone: function(){
		return this.clone().setStyles(this.getCoordinates()).setStyles({
			"opacity": 0.7,
			"position": "absolute"
		}).store("el", this).inject(document.body);
	},

	swapClass: function(oldClass, newClass){
		this.removeClass(oldClass).addClass(newClass);
	}
});

// add more function to event
Event.implement({
	getCharCode: function(){
		return (typeof(this.event.charCode) != "undefined") ? this.event.charCode : this.event.keyCode;
	},

	getCharKey: function(){
		var code = this.getCharCode();
		return (code == 0) ? "" : String.fromCharCode(code);
	}
});



// String
String.implement({
	quoteStr: function(s1, s2){
		return this.substring(this.indexOf(s1) + s1.length, this.indexOf(s2));
	},

	isBlank: function(){
		return (this.trim() == "");
	},

	isEmails: function(){
		var re = new RegExp("[;,]");
	    var arr = this.split(re);
	    for (var i = 0; i < arr.length; i++) {
	        if (!arr[i].trim().isEmail()) {
				return false;
			}
	    }
	    return true;
	},

	isEmail: function(){
		var re = new RegExp("^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]{2,4}$");
		return (this.search(re) != -1);
	},

	isImage: function(){
		var re = new RegExp("\\.(png|gif|bmp|jpg|jpeg|jpe)$", "i");
		return (this.search(re) != -1);
	},

	isPhone: function(){
		var re = new RegExp("^[ ()-.0-9]{3,}$");
		return (this.search(re) != -1);
	},

	isDate: function(format){
		var re = new RegExp("[.\/-]");
	    var arr = this.split(re);
	    if (arr.length != 3) {
			return false;
		}
	    var y = parseInt(arr[format.indexOf("y")]);
	    var m = parseInt(arr[format.indexOf("m")]);
	    var d = parseInt(arr[format.indexOf("d")]);
	    var date = new Date(y, m - 1, d);
	    return (y == date.getFullYear() && m == date.getMonth() + 1 && d == date.getDate());
	},

	compareDate: function(format, otherDate){
		var re = new RegExp("[.\/-]");
	    var a1 = this.split(re);
	    var y1 = parseInt(a1[format.indexOf("y")]);
	    var m1 = parseInt(a1[format.indexOf("m")]);
	    var iDate1 = parseInt(a1[format.indexOf("d")]);
	    if (otherDate) {
	        var a2 = otherDate.split(re);
	        var y2 = parseInt(a2[format.indexOf("y")]);
	        var m2 = parseInt(a2[format.indexOf("m")]);
	        var iDate2 = parseInt(a2[format.indexOf("d")]);
	    }
	    else {
	        var otherDate = new Date();
	        var y2 = otherDate.getFullYear();
	        var m2 = otherDate.getMonth() + 1;
	        var iDate2 = otherDate.getDate();
	    }
	    //
	    if (y2 > y1) { return 1; }
	    else if (y2 < y1) { return -1; }
	    else {
	        if (m2 > m1) { return 1; }
	        else if (m2 < m1) { return -1; }
	        else {
	            if (iDate2 > iDate1) { return 1; }
	            else if (iDate2 < iDate1) { return -1; }
	            else { return 0; }
	        }
	    }
	},

	isCreditCard: function(cardname){
		// Define the cards we support. You may add addtional card types.
	    // Name:      As in the selection box of the form - must be same as user's
	    // Length:    List of possible valid lengths of the card number for the card
	    // prefixes:  List of possible prefixes for the card
	    // checkdigit Boolean to say whether there is a check digit
	    var cards = new Array({
	        name: "Visa",
	        length: "13,16",
	        prefixes: "4",
	        checkdigit: true
	    }, {
	        name: "MasterCard",
	        length: "16",
	        prefixes: "51,52,53,54,55",
	        checkdigit: true
	    }, {
	        name: "DinersClub",
	        length: "14,16",
	        prefixes: "300,301,302,303,304,305,36,38,55",
	        checkdigit: true
	    }, {
	        name: "CarteBlanche",
	        length: "14",
	        prefixes: "300,301,302,303,304,305,36,38",
	        checkdigit: true
	    }, {
	        name: "AmEx",
	        length: "15",
	        prefixes: "34,37",
	        checkdigit: true
	    }, {
	        name: "Discover",
	        length: "16",
	        prefixes: "6011,650",
	        checkdigit: true
	    }, {
	        name: "JCB",
	        length: "15,16",
	        prefixes: "3,1800,2131",
	        checkdigit: true
	    }, {
	        name: "enRoute",
	        length: "15",
	        prefixes: "2014,2149",
	        checkdigit: true
	    }, {
	        name: "Solo",
	        length: "16,18,19",
	        prefixes: "6334, 6767",
	        checkdigit: true
	    }, {
	        name: "Switch",
	        length: "16,18,19",
	        prefixes: "4903,4905,4911,4936,564182,633110,6333,6759",
	        checkdigit: true
	    }, {
	        name: "Maestro",
	        length: "16,18",
	        prefixes: "5020,6",
	        checkdigit: true
	    }, {
	        name: "VisaElectron",
	        length: "16",

	        prefixes: "417500,4917,4913",
	        checkdigit: true
	    });
	    // Establish card type
		var cardnumber = this;
	    var cardType = -1;
	    for (var i = 0; i < cards.length; i++) {
	        // See if it is this card (ignoring the case of the string)
	        if (cardname.toLowerCase() == cards[i].name.toLowerCase()) {
	            cardType = i;
	            break;
	        }
	    }
	    // If card type not found, report an error
	    if (cardType == -1) { return false; }
	    // Ensure that the user has provided a credit card number
	    if (cardnumber.length == 0) { return false; }
	    // Now remove any spaces from the credit card number
	    var re1 = new RegExp("\\s", "g");
	    cardnumber = cardnumber.replace(re1, "");
	    // Check that the number is numeric
	    var cardNo = cardnumber;
	    var cardexp = new RegExp("^[0-9]{13,19}$");
	    if (!cardexp.exec(cardNo)) { return false; }
	    // Now check the modulus 10 check digit - if required
	    if (cards[cardType].checkdigit) {
	        var checksum = 0; // running checksum total
	        var mychar = ""; // next char to process
	        var j = 1; // takes value of 1 or 2
	        // Process each digit one by one starting at the right
	        var calc;
	        for (i = cardNo.length - 1; i >= 0; i--) {
	            // Extract the next digit and multiply by 1 or 2 on alternative digits.
	            calc = Number(cardNo.charAt(i)) * j;
	            // If the result is in two digits add 1 to the checksum total
	            if (calc > 9) {
	                checksum = checksum + 1;
	                calc = calc - 10;
	            }
	            // Add the units element to the checksum total
	            checksum = checksum + calc;
	            // Switch the value of j
	            if (j == 1) {
	                j = 2;
	            }
	            else {
	                j = 1;
	            }
	                        }
	        // All done - if checksum is divisible by 10, it is a valid modulus 10.
	        // If not, report an error.
	        if (checksum % 10 != 0) { return false; }
	    }
	    // The following are the card-specific checks we undertake.
	    var LengthValid = false;
	    var PrefixValid = false;
	    // We use these for holding the valid lengths and prefixes of a card type
	    var prefix = new Array();
	    var lengths = new Array();
	    // Load an array with the valid prefixes for this card
	    prefix = cards[cardType].prefixes.split(",");
	    // Now see if any of them match what we have in the card number
	    for (i = 0; i < prefix.length; i++) {
	        var exp = new RegExp("^" + prefix[i]);
	        if (exp.test(cardNo)) PrefixValid = true;
	    }
	    // If it isn't a valid prefix there's no point at looking at the length
	    if (!PrefixValid) { return false; }
	    // See if the length is valid for this card
	    lengths = cards[cardType].length.split(",");
	    for (j = 0; j < lengths.length; j++) {
	        if (cardNo.length == lengths[j]) LengthValid = true;
	    }
	    // See if all is OK by seeing if the length was valid. We only check the
	    // length if all else was hunky dory.
	    if (!LengthValid) { return false; };
	    // The credit card is in the required format.
	    return true;
	}
});


// FORM CLASS VALIDATION
var htmlform = new Class({
	options: {
		alertType: "layer",
		layerWidth: 200,
		layerOffset: "0, 0",
		fadeContent: true,
		hideInterval: 3000,

		// variables
		waitInterval: Class.empty,
		errorElement: Class.empty,
		alertLayer:Class.empty,

		// events
		onAlertShow: Class.empty,
		onAlertHide: Class.empty,
		onAfterChange: Class.empty,
		onSubmit: Class.empty
	},

	initialize: function(form, data, options){

		var frm = $(form);
		if (!frm) {
			return;
		}
		
		// set options
		this.setOptions(options);
		if (options.onSubmit) {
			this.options.onSubmit = options.onSubmit;
		}

		// call functions
		this.initLayer(frm);
		this.initForm(frm, data);
	},

	initLayer: function(form){
		var fn = this;
		var layerName = form.id || form.name || "alert";

		// check & create for alert layer
		this.options.alertLayer = new Element("div", {
			"id": layerName+"Layer",
			"class": "formMessage"
		}).inject(document.body);

		//
		/*var closeBtn = new Element("a", {
			"href": "javascript:;",
			"html": "x",
			"events": {
				"click": function(e){
					fn.hideAlertLayer();
				}
			}
		}).inject(this.options.alertLayer);*/

		var display = new Element("p").inject(this.options.alertLayer);
	},

	initForm: function(form, data){
		var fn = this;
	//print_r(form);
	    for (var i = 0; i < data.length; i++) {
	    	
	        // init elements
	        for (var j = 0; j < form.elements.length; j++) {
	            var el = $(form.elements[j]);
	           // alert(form.elements[j]);
	          //  alert(i);
				if(data[i])
				{
					//alert(el.name + '  ' + data[i].field);
	            if (el.name == data[i].field) {

	                this.initElement(el, data[i]);
	            }
				}
	        }
	    }

	    // valid form on submit
	    form.addEvent("submit", function(e){
			if (!fn.isValidForm(form)) {
				e.stop();
			} else {
				// call back
				if ($type(fn.options.onSubmit) != false) {
					e.stop();
					fn.fireEvent("onSubmit");
				}
				
				if($('ChooseMealDeal'))
					{
						e.stop();
						valideMenu();
					}
			}
	    });

		// add reset buttons
		var resetBtn = form.getElement("input.reset");
		if (resetBtn) {
			resetBtn.addEvent("click", function(e){
				e.stop();
				fn.hideAlertLayer();
				fn.resetForm(form);
			});
		}
	},

	initElement: function(el, data){
		var fn = this;

	    // add new properties
		el.store("data", data);
		el.store("validated", true);
		
	    // init options
	    if (typeof(data.init) != "undefined") {

	        // if the input has its initialized value
			if (el.type == "text" || el.type == "textarea" || el.type == "password") {
				el.value = data.init;
				el.addEvents({
					"focus": function(){
		                if (this.value == this.retrieve("data").init) {
		                    this.value = "";
		                }
					},
					"blur": function(){
		                if (this.value.trim() == "") {
		                    this.value = this.retrieve("data").init;
		                }
		            }
				});
			}

			if (el.type == "select-one" || el.type == "select-multiple") {
				el.selectedIndex = Number(data.init);
			}

			if (el.type == "radio") {
				el.form[el.name][Number(data.init)].checked = true;
			}
	    }

		// apply maxlength to textarea
		if (typeof(data.maxLength) != "undefined" && (el.type == "textarea" || el.type == "text" || el.type == "password")) {
			// maximum input characters
			if (el.type == "textarea"){
				el.addEvent("keypress", function(e){
		            var evt = new Event(e);
		            var code = evt.getCharCode();
		            if (this.value.length >= this.retrieve("data").maxLength && code != 0) { evt.stop(); }
		        });
			} else {
				el.maxLength = data.maxLength;
			}
		}

		// restrict input characters
	    if (typeof(data.restrict) != "undefined" && (el.type == "textarea" || el.type == "text" || el.type == "password")) {
			el.addEvent("keypress", function(e){
	            var evt = new Event(e);
				var key = evt.getCharKey();
	            var re = new RegExp(this.retrieve("data").restrict);
	            if (key != "" && !re.test(key)) { evt.stop(); }
	        });
	    }

		// hide alert & execute call back functions
		el.addEvents({
			"click": function(e){
				this.store("validated", fn.validFormElement(this));
				fn.onAfterChange(this);
				fn.hideAlertLayer();
			},
			"keyup": function(e){
				this.store("validated", fn.validFormElement(this));
				fn.onAfterChange(this);
				fn.hideAlertLayer();
			},
			"change": function(e){
				this.store("validated", fn.validFormElement(this));
				fn.onAfterChange(this);
				fn.hideAlertLayer();
			}
		});

		// add events
		if (data.events) {
			el.addEvents(data.events);
		}
		//print_r(data);
		
	},

	resetForm: function(form){
		form.reset();
	},

	isValidForm: function (form){
	    for (var i = 0; i < form.elements.length; i++) {
			var isValid = this.validFormElement(form.elements[i]);
			$(form.elements[i]).store("validated", isValid);
	        if (!isValid) {
	            this.showAlertLayer(form.elements[i]);
	            return false;
	        }
	    }
	    return true;
	},

	validFormElement: function(el){
		var fn = this;
		var data = el.retrieve("data");
		var value = el.value ? el.value.trim() : "";

		// if not valid
		if ($type(data) == false) {
			return true;
		}

		// valid types
	    switch (typeof(data.valid)) {
	        case "function":
	            return data.valid();
	            break;

	        case "string":
	            var validTag = data.valid.trim();

				var optionPass = (validTag.indexOf("[") != -1 && validTag.indexOf("]") != -1 && (el.value.isBlank() || (data.init && value == data.init)));

	            // no valid needed
	            if (typeof(data.valid) == "undefined" || data.valid == null || validTag == "" || validTag == "none") {
					return true;
				}

	            // compare to other input's value
	            if (validTag.indexOf("=") != -1 && validTag.indexOf(">") == -1 && validTag.indexOf("<") == -1) {
	                if (el.type == "text" || el.type == "password") {
	                    var target = $F(validTag.replace("=", ""), el.form);
	                    return !target || value == target.value.trim();
	                }

	                // other type
	                return true;
	            }
	            if (validTag.indexOf(">") != -1) {
	                if (el.type == "text" || el.type == "password") {
	                    var target = $F(validTag.replace("=", ""), el.form);
	                    if (validTag.indexOf("=") != -1) { return !target || Number(value) >= Number(target.value.trim()); }
	                    else { return !target || Number(value) > Number(target.value.trim()); }
	                }

	                // other type
	                return true;
	            }
	            if (validTag.indexOf("<") != -1) {
	                if (el.type == "text" || el.type == "password") {
	                    var target = $(validTag.replace("=", ""));
	                    if (validTag.indexOf("=") != -1) { return !target || Number(value) <= Number(target.value.trim()); }
	                    else { return !target || Number(value) < Number(target.value.trim()); }
	                }

	                // other type
	                return true;
	            }

	            // required value
	            if (validTag.indexOf("required") != -1) {
					if (el.type != "text" && el.type != "textarea" && el.type != "password" && el.type != "file") {
						return true;
					}
					if (!data.init || data.init == "") {
						return value.length >= Math.max(Number(validTag.quoteStr("(", ")")), 1);
					} else {
						return value.length >= Math.max(Number(validTag.quoteStr("(", ")")), 1) && value != data.init;
					}

	                // other type
	                return true;
	            }

	            // range value
	            if (validTag.indexOf("range") != -1) {
	                if (el.type == "text") {
	                    var range = validTag.quoteStr("(", ")").trim().split(";");
						if (range[0].trim() == "" && range[1].trim() == "") return true;
						if (range[0].trim() == "") return Number(value) <= Number(range[1].trim());
						if (range[1].trim() == "") return Number(value) >= Number(range[0].trim());
	                    return Number(value) >= Number(range[0].trim()) && Number(value) <= Number(range[1].trim());
	                }

	                // other type
	                return true;
	            }

	            // email value
	            if (validTag.indexOf("email") != -1) {

	                if (el.type == "text" || el.type == "textarea") {

	                    // if optional input & value is null or value = init value
	                    if (optionPass) {
							return true;
						}

	                    // validate email(s)
						if (validTag.indexOf("emails") != -1) {
							return value.isEmails();
						}
						
						return value.isEmail();
	                }

	                // other type
	                return true;
	            }

	            if (validTag == "checkusername")
	            {
	            	
					if(!value.isEmail())
					{
						
						el.store("data",
						{	'alert':"Veuillez renseigner votre email",
							'field': "username",
	    					'valid': "checkusername"}

						);
						//el.alert="putin met ton foutu email bordel";
						return false;
					}else{
						
						var url = "/ajax.php?module=verifyemail&val="+$('username').value;
						new Request(
						{
							url:url, method: 'get',
							onSuccess: function(txt) {
								if(txt=="exist"){$('checkvalue').value=0;}else{$('checkvalue').value=1;}
							}
						}).send();

					}
					
					if($('checkvalue').value==1)
					{
						el.store("data",
						{	'alert':"Cet email est déjà enregistré",
							'field': "username",
	    					'valid': "checkusername"}

						);
						return true;
					}else{
						el.store("data",
						{	'alert':"Cet email est déjà enregistré",
							'field': "username",
	    					'valid': "checkusername"}

						);
						return false;
					}

	            }
	            
	            
	            
	            
	            if (validTag == "validateOnChange")
	            {
					var form = document.forms['josForm'];
					
						if(document.forms['formulairecp']){
							var formcp = document.forms['formulairecp'];
						}else{
							return true;
						}
	            	
	            	
	            	form.name.value = form.firstname.value+' '+form.lastname.value;
	            	var form = document.forms['josForm'];

	            	if(document.forms['formulairecp'])
	            	{
	            		var formcp = document.forms['formulairecp'];
	            	}
	            	
	            	if($('sms').checked==true && $('smsnumberli').style.display!='none' && $('smsnumber').value.length < 10 )
	            	{
	            		el.store("data",{
	            		'alert':"précisez votre numéro de sms pour recevoir les messages",
	            		'field': "username",
	            		'valid': "validateOnChange"
	            		});return false;
	            	}
	            	
	            	if($('cptext'))
	            	{
	            		$('infoBulle').style.display='none';
	            		el.store("data",{
	            		'alert':"Veuillez renseigner votre code postal et cliquer sur le bouton \"ok\"",
	            		'field': "username",
	            		'valid': "validateOnChange"
	            		});return false;
	            	}else if(formcp && !$('cptext') && $('ville'))
	            	{
	            		form.cp_nl.value = formcp.cp.value;
	            		form.posid_nl.value = formcp.phid.value;
	            		form.sid_nl.value = formcp.sid.value;
	            		form.num_voie_nl.value = formcp.num_voie.value;
	            		if(formcp.num_voie &&  formcp.num_voie.value.length < 1 )
	            		{
	            			$('infoBulle').style.display='none';
							el.store("data",{
		            		'alert':"précisez votre numéro de voie",
		            		'field': "username",
		            		'valid': "validateOnChange"
		            		});return false;
	            		}
	            	}


	            		if($('type_voie') && $('type_voie').style.display!='none' ){
	            			var typedevoie = formcp.type_voie.options[formcp.type_voie.selectedIndex].text;
	            			if (typedevoie=="Selection"){
	            				$('infoBulle').style.display='none';
	            				el.store("data",{
			            		'alert':"précisez votre type de voie",
			            		'field': "username",
			            		'valid': "validateOnChange"
			            		});return false;
	            			}
	            		}

	            		if($('nom_voie'))form.nom_voie_nl.value = formcp.nom_voie.value;
	            		if($('nom_voie') &&  !$('cptext') && formcp.nom_voie.value.length < 1 )
	            		{
	            			$('infoBulle').style.display='none';
							el.store("data",{
		            		'alert':"précisez votre nom de voie",
		            		'field': "username",
		            		'valid': "validateOnChange"
		            		});return false;
	            		}
	            		if(formcp &&  !$('cptext'))
	            		{
	            			
	            		
	            		if( $('type_voie'))form.type_voie_nl.value = formcp.type_voie.value;
	            		$('userinfo_user_address_postal_code').innerHTML=form.cp_nl.value;
	            		if($('ville'))$('userinfo_user_address_town_name').innerHTML=formcp.ville.value;
	            		$('userinfo_user_address_number').innerHTML=form.num_voie_nl.value;
	            		if(form.user_address_labelid.options[form.user_address_labelid.selectedIndex].value == 0)
	            		{
	            			form.user_address_labelid.selectedIndex = 1;
	            		}
	            		
	            		
	            		$('userinfo_user_address_type_label').innerHTML=formcp.type_voie.options[formcp.type_voie.selectedIndex].text;
	            		$('userinfo_user_address_street').innerHTML=form.nom_voie_nl.value;
	            		if($('log1'))$('log1').innerHTML='';
	            		}
	            		

	            	
	            	/*el.store("data",
	            	{	
	            	'alert':"checkusername",
	            	'field': "username",
	            	'valid': "validateOnChange"}

	            	);*/
	            	//return false;
	            }

	            
	            
	            
	            
	            
	            // phone value
	            if (validTag.indexOf("date") != -1) {

	                if (el.type == "text") {

						var fmt = validTag.trim().quoteStr("(", ")");

	                    // if optional input & value is null or value = init value
	                    if (optionPass) {
							return true;
						}

	                    // validate phone
	                    return value.isDate(fmt);
	                }

	                // other type
	                return true;
	            }

				// phone value
	            if (validTag.indexOf("phone") != -1) {

	                if (el.type == "text") {

	                    // if optional input & value is null or value = init value
	                    if (optionPass) {
							return true;
						}

	                    // validate phone
	                    return value.isPhone();
	                }

	                // other type
	                return true;
	            }

	            // image value
	            if (validTag.indexOf("image") != -1) {

	                if (el.type == "text" || el.type == "file") {

	                    // if optional input & value is null or value = init value
	                    if (optionPass) {
							return true;
						}

	                    // validate image
	                    return value.isImage();
	                }

	                // other type
	                return true;
	            }

	            // "future" compare date
	            if (validTag.indexOf("future") !== -1) {

	                if (el.type == "text") {

	                    // if optional input & value is null or value = init value
	                    if (optionPass) {
							return true;
						}

	                    var range = validTag.quoteStr("(", ")").split(",");
	                    if (range.length == 0) {
							return true;
						}

	                    if (!value.isDate(range[0].trim()) || (range[1] && $F(range[1].trim(), el.form) && !$F(range[1].trim(), el.form).value.trim().isDate(range[0].trim()))) {
							return false;
						}
	                    if (range[1] && $F(range[1].trim(), el.form)) {
							return (value.compareDate(range[0].trim(), $F(range[1].trim(), el.form).value.trim()) == -1);
						} else {
							return (value.compareDate(range[0].trim()) == -1);
						}
	                }

	                // other type
	                return true;
	            }

	            // "checked" for checkbox & radio button
	            if (validTag == "checked") {

	                if (el.type == "checkbox") { return el.checked; }

	                if (el.type == "radio") {
	                    var radioGroup = el.form[el.name];

	                    // contain 1 radio button
	                    if (radioGroup && !radioGroup.length) { return radioGroup.checked; }

	                    // more than 1 radio button
	                    for (var i = 0; i < radioGroup.length; i++) {
	                        if (radioGroup[i].checked) { return true; }
	                    }
	                    return false;
	                }

	                // other type
	                return true;
	            }

	            // "selected" for combo box
	            if (validTag == "selected") {

	                if (el.type == "select-one" || el.type == "select-multiple") {
	                    if (typeof(el.retrieve("data").init) != "undefined") { return el.selectedIndex != Number(el.retrieve("data").init); }
	                    else { return el.selectedIndex != 0; }
	                }

	                // other type
	                return true;
	            }

	            return true;
	            break;

	        default:
	            return true;
	            break;
	    }
	    //print_r(data.valid);
	},

	showAlertLayer: function(el){
	    try {

	        var fn = this;
			var form = el.form;
			var data = el.retrieve("data");
			var alertLyr = this.options.alertLayer;
	        this.options.errorElement = el;

			// call back functions
			//this.onAlertShow(el);

	        // display alert message

	        //alertLyr.removeChild('topInfoBulleDiv');
			alertLyr.empty();
			if(!alertLyr.hasChild('topInfoBulleDiv'))
			{
				//alert('ok');
				//alertLyr.removeChild('topInfoBulleDiv');
				//alertLyr.removeChild('bottomInfoBulleDiv');
				var alertImageTop  = new Element('div', {id: 'topInfoBulleDiv'});
				var alertImageBottom  = new Element('div', {id: 'bottomInfoBulleDiv'});
				var alertP  = new Element('p', {id: 'bottomInfoBulleP'});
				alertImageTop.inject(alertLyr, 'top');
				alertP.inject(alertLyr, '');
				alertImageBottom.inject(alertLyr, 'bottom');
			}/**/
			alertLyr.getElement("p").set("html", data.alert);
	        // show alert
	        var alertType = data.alertType || this.options.alertType;
	        var offset = data.layerOffset ? data.layerOffset.split(",") : ["0", "0"];
			var lyrW = data.layerWidth || this.options.layerWidth;
			//alert(form.id + "  =>  " +data.field);
			
			switch (alertType) {
	            case "layer":
	            var coords = el.getCoordinates();
					var alertCoords = alertLyr.getCoordinates();
	            if(data.decalageV )
	            {
	            	decalageV=data.decalageV;
	            }else{
	            	decalageV=0;
	            }
	            
	            if(data.decalageH )
	            {
	            	decalageH=data.decalageH;
	            }else{
	            	decalageH=0;
	            }
	            
	            	alertLyr.set("styles", {
						"visibility": "visible",
						"display": "block",
						"top": (coords.top  - alertCoords.height + decalageH) + "px",
						"left": (coords.left + Number(offset[0].trim()) + decalageV - 110 ) + "px",
						"width": lyrW + "px",
						"z-index": 8
					}).addClass("formLayer");
	            
					 alertLyr.ieFixLayerShow();
	                el.focus();
	                break;
	            case "layer_startPurchaseSubmit":
					var coords = $('startPurchaseSubmit').getCoordinates();
					var alertCoords = alertLyr.getCoordinates();
					alertLyr.set("styles", {
						"visibility": "visible",
						"display": "block",
						"top": (coords.top  - alertCoords.height) + "px",
						"left": (coords.left + Number(offset[0].trim()) - 110) + "px",
						"width": lyrW + "px",
						"z-index": 8
					}).addClass("formLayer");

	                // set Iframe to hide combo box in IE
	                alertLyr.ieFixLayerShow();
	                $('startPurchaseSubmit').focus();
	                break;

	            case "popup":
					var coords = alertLyr.getCoordinates();
					alertLyr.set("styles", {
						visibility: "visible",
						display: "block",
						top: (window.getScrollTop() + window.getHeight() / 2 - coords.height / 2 + Number(offset[1].trim())) + "px",
						left: (window.getWidth() / 2 - lyrW / 2 + Number(offset[0].trim())) + "px",
						width: lyrW + "px",
						zIndex: 999
					}).addClass("formpopup");

	                // fade HTML content
	                if (data.fadeContent == true) {
	                    showMask();
	                }
					el.focus();
	                break;

				case "classic":
					alert(data.alert);
					el.focus();
	                break;


	            default:
					el.focus();
	                break;
	        }
	        // set focus


			// autohide alert
			clearInterval(fn.options.waitInterval);
			fn.options.waitInterval = setInterval(function(){
				fn.hideAlertLayer();
			}, fn.options.hideInterval);
	    } catch (err) {
		}
	},

	hideAlertLayer: function(){
		clearInterval(this.options.waitInterval);
	    try {
			var alertLyr = this.options.alertLayer;
			var el = this.options.errorElement;
			if (el) {
				this.onAlertHide(el);
			}

			// hide frame
			alertLyr.setStyle("visibility", "hidden");
			alertLyr.ieFixLayerHide();
			hideMask();

	    } catch (err) {
		}
	},

	onAlertShow: function(el){
		this.fireEvent("onAlertShow", el);
	},

	onAlertHide: function(el){
		this.fireEvent("onAlertHide", el);
	},

	onAfterChange: function(el){
		this.fireEvent("onAfterChange", el);
	},

	onSubmit: function(el){
		this.fireEvent("onSubmit", el);
	}
});

htmlform.implement(new Options, new Events);