// $().ready(function() {
jQuery.fn.extend({
	// Chargement d'une page à afficher
	ajouteValidate : function() {
	 

		// chargement du script validator
		// $("body").append("<SCRIPT language='JavaScript'
		// type='text/javascript'
		// src='plugins/jeux/javascript/jquery.validate.js'></SCRIPT>");
		// chargement de tous les scripts positionnés dans la page
		$('.ScriptToLoad').each(function() {
			$("body")
					.append("<SCRIPT language='JavaScript' type='text/javascript' src='"
							+ $(this).text() + "' charset='UTF-8'></SCRIPT>");
		});

		// ajout des méthodes de contrôle au validator
		jQuery.validator.addMethod("texteATrou",
				function(value, element, param) {
					for (i = 0; i < param.length; i++) {
						if (param[i] == (value)) {
							return true;
						}
					}
					return false;
				}, "ERREUR");
		jQuery.validator.addMethod("Obligatoire", function(value, element,
						param) {
					return value.length > 0;
				}, "Entrez une valeur : ");
		jQuery.validator.messages.Obligatoire = "";

		// mise en place des contrôles sur les formulaires

		$("form").each(function() {
			var nom = $(this).attr("id");
			// on recherche tous les formulaires dont l'ID commence par trous
			if (nom.indexOf("trous") == 0) {
				var String2Eval = " // on interdit la soumission\n";
				String2Eval += "$(\"#" + nom
						+ "\").submit(function() { return false;});\n";
				String2Eval += "$(\"#" + nom + "\").validate({\n";
				String2Eval += "	onfocusout: false,\n";
				String2Eval += "  onkeyup: false,\n";
				String2Eval += "  submitHandler: function() {\n";
				String2Eval += "$(\"#" + nom + "\").calculeScore();";
				String2Eval += "	$(\"#" + nom
						+ " input.jeux_input\").each(function(){";
				String2Eval += "  var color = $(this).css(\"borderTopColor\");";
				String2Eval += "  $(this).css({\"color\":color});});\n";
				String2Eval += "    if ($(\"#" + nom
						+ "solution_solution[disabled]\").length == 0){\n";
				String2Eval += "    $(\"#"
						+ nom
						+ "_error\").html(\"<span style='color:	#B22222;'>BRAVO !</span>\");\n";
				String2Eval += "    $(\"#" + nom
						+ "_error\").show()};return false;}  ,\n";
				String2Eval += " 		rules: {\n";

				var cpt = 0;
				$("#" + nom + " input").each(function() {
					var nomInput = $(this).attr("id");
					if (nomInput.indexOf("var") == 0) {
						if (cpt > 0)
							String2Eval += ",";
						cpt++;
						String2Eval += "    " + nomInput + ": {\n";
						String2Eval += "         Obligatoire: true,\n";
						String2Eval += "         texteATrou: [";
						var cpt2 = 0;
						$("#" + nom + " .val_" + nomInput).each(function() {
									var liste = $(this).text().split(",");
									for (cpt2 = 0; cpt2 < liste.length; cpt2++) {
										if (cpt2 > 0)
											String2Eval += ",";
										String2Eval += "\"" + liste[cpt2]
												+ "\"";
									}
								});
						String2Eval += "]\n";
						String2Eval += "        }\n";
					}
				});
				String2Eval += "        },\n";
				String2Eval += "   errorPlacement: function(error, element) {\n";
				String2Eval += "     error.appendTo( element.prev());";
				String2Eval += "     }\n";
				String2Eval += "   });\n";
				String2Eval += "$(\"#"
						+ nom
						+ "\").bind(\"invalid-form.validate\", function(e, validator) {\n";
				String2Eval += "var errors = validator.numberOfInvalids()\n";
				String2Eval += "if (errors) {\n";
				String2Eval += "	var message = errors == 1\n";
				String2Eval += "		? '1 y a un champ vide ou en erreur'\n";
				String2Eval += "		: ' ' + errors + ' champs vides ou en erreur';\n";
				String2Eval += "	$(\"#" + nom + "_error\").html(message);\n";
				String2Eval += "	$(\"#"
						+ nom
						+ "_error\").html(\"<span style='color:red;'>\" + message + \"</span>\");\n";
				String2Eval += "	$(\"#" + nom + "_error\").show();\n";
				String2Eval += "    $(\"#" + nom + " input.jeux_input\").each(function(){";
        String2Eval += "  var color = $(this).css(\"borderTopColor\");";
				String2Eval += "  $(this).css({\"color\":color});});\n";
				String2Eval += "	$(\"#" + nom
						+ " input.error\").css({\"color\":\"black\"});\n";
				String2Eval += "} else {\n";
				String2Eval += "	$(\"#" + nom + "_error\").hide();\n";
				String2Eval += "}\n";
				String2Eval += "$(this).calculeScore(validator);";
				String2Eval += "});\n";
				var tmp = eval(String2Eval);
			}
			// ajout du traitement de la solution
			var $this = $(this);
			$(this).find("input.jeux_bouton").each(function() {
				var button = $(this);
				var buttonId = $this.attr("id") + "solution";
				$(this)
						.after("<input type=\"submit\" class=\"jeux_bouton\" id=\""
								+ buttonId
								+ "_solution\" value=\"Solution\"></input>");
				$("#" + buttonId + "_solution").each(function() {
					$(this).bind("click", function(e) {
						$(this).attr("disabled", "disabled");
						button.attr("disabled", "disabled");
						$this.find(".jeux_input").each(function() {
							var texte = $this
									.find(".val_" + $(this).attr("id")).text();
							$(this).val(texte.split(",")[0]);
							$(this).flip({
										dir : "bottom",
										endColor : $(this)
												.css("borderTopColor"),
										duration : 800,
										onEnd : function() {
										}
									});
						});
					});
				});

			});

		});
	},
	calculeScore : function(validator) { 
	 if (!scoreAAfficher)
	   return;
		var $this = $(this);
		var score = 0;
		if (validator) {
			var bons = validator.validElements();
			for (var i = 0; i < bons.length; i++) {
				score += $this.calculeScoreInput(bons[i].name);
			}
		} else {
			window.alert("tout bon");
			$(this).find("input.jeux_input").each(function() {
						window.alert($(this).attr("id"));
						score += $this.calculeScoreInput($(this).attr("id"));
					});
		}
		window.alert("score " + score);
	},
	calculeScoreInput : function(name) {
	 if (!scoreAAfficher)
	   return;
	 
		var score = 0
		$(this).find(".val_" + name).each(function() {
					var liste = $(this).text().split(",");
					var longueur = liste[0].length;
					if (longueur < 7)
						score = 10 * (longueur - 2);
					else
						score = 20 * (longueur - 7) + 60;
				});
		return score;
	}
});

	var scoreAAfficher = false;
jQuery.fn.flip = function(args){
        var borderConst = "border",
        widthConst = "Width",
        heightConst = "Height",
        topConst = "Top",
        rightConst = "Right",
        leftConst = "Left",
        bottomConst = "Bottom"
    ;
        var $helperNode = $("<div></div>");
        var $node = this, 
            s = $node[0].style,
            dims = null,
            hs = null, 
            pn = null,
            lightColor = args.lightColor || "#dddddd", 
            darkColor = args.darkColor || "#555555",
            bgColor = s["backgroundColor"], 
            endColor = args.endColor || bgColor,
            staticProps = {}, 
            anims = [],
            duration = args.duration ? args.duration / 2 : 250,
            dir = args.dir || "left", 
            pConst = 0.6, 
            transparentColor = "transparent"
            onEnd = args.onEnd || function(){},
            // IE6 workaround: IE6 doesn't support transparent borders
            convertColor = function(color){
                var re = new RegExp("#000000|#000|black|rgb(0,0,0)", "i");
                return re.test(color.replace(/ /, "")) ? "#000001" : color;
            };
        if($.browser.msie && parseInt($.browser.version) < 7){
            endColor = convertColor(endColor);
            lightColor = convertColor(lightColor);
            darkColor = convertColor(darkColor);
            bgColor = convertColor(bgColor);
            transparentColor = "black";
            $helperNode[0].style.filter = "chroma(color='#000000')";
        }
        var init = (function($n){
            return function(){
                var p = /*$n.position()*/ $n.offset();
                dims = {
                    top: p.top,
                    left: p.left,
                    width: /*parseInt($n.css("width"))*/ $n.width(),
                    height: /*parseInt($n.css("height"))*/ $n.height()
                };
            }
        })($node);
        init();
        hs = {
            position: "absolute",
            top: dims["top"] + "px",
            left: dims["left"] + "px",
            height: "0",
            width: "0",
            zIndex: args.zIndex || (s.zIndex || 0),
            border: "0 solid " + transparentColor,
            fontSize: "0"
        };
        dims["endHeight"] = dims["height"] * pConst; 
        dims["endWidth"] = dims["width"] * pConst; 
        var props = [ {}, 
            {
                top: dims["top"],
                left: dims["left"]
            }
        ];
        var dynProperties = {
            left: [leftConst, rightConst, topConst, bottomConst, widthConst, heightConst, "end" + heightConst, leftConst],
            right: [rightConst, leftConst, topConst, bottomConst, widthConst, heightConst, "end" + heightConst, leftConst],
            top: [topConst, bottomConst, leftConst, rightConst, heightConst, widthConst, "end" + widthConst, topConst],
            bottom: [bottomConst, topConst, leftConst, rightConst, heightConst, widthConst, "end" + widthConst, topConst] 
        }
        // property names
        pn = dynProperties[dir];

        staticProps[pn[5].toLowerCase()] = dims[pn[5].toLowerCase()] + "px";
        staticProps[pn[4].toLowerCase()] = "0";
        staticProps[borderConst + pn[1] + widthConst] = dims[pn[4].toLowerCase()] + "px";
        staticProps[borderConst + pn[1] + "Color"] = bgColor;

        var p0 = props[0];
        p0[borderConst + pn[1] + widthConst] = 0 + "px"; 
        p0[borderConst + pn[1] + "Color"] = darkColor; 
        p0[borderConst + pn[2] + widthConst] = (dims[pn[6]] / 2) + "px";
        p0[borderConst + pn[3] + widthConst] = (dims[pn[6]] / 2) + "px";
        p0[pn[2].toLowerCase()] = (dims[pn[2].toLowerCase()] - dims[pn[6]] / 8) + "px";
        p0[pn[7].toLowerCase()] = (dims[pn[7].toLowerCase()] + dims[pn[4].toLowerCase()] / 2) + "px";
        p0[pn[5].toLowerCase()] = (dims[pn[6]]) + "px";

        var p1 = props[1];
        p1[borderConst + pn[0] + "Color"] = endColor;
        p1[borderConst + pn[0] + widthConst] = dims[pn[4].toLowerCase()] + "px";
        p1[borderConst + pn[2] + widthConst] = 0 + "px";
        p1[borderConst + pn[3] + widthConst] = 0 + "px";
        p1[pn[5].toLowerCase()] = dims[pn[5].toLowerCase()];

        $.extend(hs, staticProps);
//        window.alert("ici 6 " + $.toJSON(hs));
        
        $helperNode.css(hs);

        $("body").append($helperNode);

        var finalize = function(){
            $helperNode.remove();
            s.visibility = "visible";
            onEnd();
        };
        $node.css("visibility", "hidden");
        $helperNode.animate(p0, duration).animate(p1, duration, null, finalize);
        return this;
};
 