
// http://ejohn.org/blog/javascript-micro-templating/
// Simple JavaScript Templating
// John Resig - http://ejohn.org/ - MIT Licensed
(function(){
  var cache = {};
 
  this.tmpl = function tmpl(str, data){
    // Figure out if we're getting a template, or if we need to
    // load the template - and be sure to cache the result.
    var fn = !/\W/.test(str) ?
      cache[str] = cache[str] ||
        tmpl(document.getElementById(str).innerHTML) :
     
      // Generate a reusable function that will serve as a template
      // generator (and which will be cached).
      new Function("obj",
        "var p=[],print=function(){p.push.apply(p,arguments);};" +
       
        // Introduce the data as local variables using with(){}
        "with(obj){p.push('" +
       
        // Convert the template into pure JavaScript
        str
          .replace(/[\r\t\n]/g, " ")
          .split("<%").join("\t")
          .replace(/((^|%>)[^\t]*)'/g, "$1\r")
          .replace(/\t=(.*?)%>/g, "',$1,'")
          .split("\t").join("');")
          .split("%>").join("p.push('")
          .split("\r").join("\\'")
      + "');}return p.join('');");
   
    // Provide some basic currying to the user
    return data ? fn( data ) : fn;
  };
})();

function roundNumber(num, decimal) {
	return parseFloat(Math.round(num * Math.pow(10, decimal)) / Math.pow(10, decimal));
}

var Message;

$(document).ready( function () {

	var identification = ( function () {

		// form identification
		if ($("form#connexion-espace").length > 0) {

			var url = Registry.url.base + Registry.locale + "/extranet/connexion/";

			$("form#connexion-espace input#login").focus( function () {
				if ($(this).val() === Registry.form.default_connexion_login) {
					$(this).val('');
				}
			});
			$("form#connexion-espace input#password").focus( function () {
				if ($(this).val() === Registry.form.default_connexion_password) {
					$(this).val('');
				}
			});
			$("form#connexion-espace input#login").blur( function () {
				if ($(this).val() === "") {
					$(this).val(Registry.form.default_connexion_login);
				}
			});
			$("form#connexion-espace input#password").blur( function () {
				if ($(this).val() === "") {
					$(this).val(Registry.form.default_connexion_password);
				}
			});
			$("form#connexion-espace").submit( function () {

				var datas = {};
				datas.login = $("form#connexion-espace input#login").val();
				datas.password = $("form#connexion-espace input#password").val();

				$('#ajax-loader-connexion').css("visibility", 'visible');
				$('#btn-connexion').attr("disabled", "disabled");

				$.ajax({
					type    : 'POST',
					url     : url,
					data    : datas,
					success : function(json) {

						$('#ajax-loader-connexion').css("visibility", 'hidden');
						$('#btn-connexion').removeAttr("disabled");
						
						if (json.status === 200) {
							document.location.href = Registry.url.base + Registry.locale + "/extranet/";
						}
						else {
							Message.update(json.message, 6000);			
						}
					}
				});
				return false;
			});
		}
	}());
	
	var motdepasse = ( function () {
		
		var url = Registry.url.base + Registry.locale + "/extranet/motdepasseperdu/";
		
		// form mot de passe perdu
		if ($("form#mdp-perdu").length > 0) {

			$("form#mdp-perdu input#email").focus( function () {
				if ($(this).val() === Registry.form.default_forget_email) {
					$(this).val('');
				}
			});
			$("form#mdp-perdu input#email").focus( function () {
				if ($(this).val() === Registry.form.default_forget_email) {
					$(this).val('');
				}
			});
			
			$("form#mdp-perdu").submit( function () {

				var datas = {};
				datas.email = $("form#mdp-perdu input#email").val();
				
				$('#ajax-loader').css("visibility", 'visible');
				$('#btn-envoyer').attr("disabled", "disabled");

				$.ajax({
					type    : 'POST',
					url     : url,
					data    : datas,
					success : function(json) {

						$('#ajax-loader').css("visibility", 'hidden');
						$('#btn-envoyer').removeAttr("disabled");
						
						Message.update(json.message);			
					}
				});
				return false;
			});
			
		}
	}());
	
	// messages
	Message = ( function () {
		
		var timer = null,
			height = 0, 
			delay = 0,
			defaultDelay = 4000,
			duration = 400,
			isHide = true
			style = "";
		
		function update (content, time, css) {
			
			delay = (time !== undefined) ? time : 4000;
			style = (css !== undefined) ? css : "";
			
			$('#custom-message-content').empty();
			$('#custom-message-content').append(content);
			
			if (style !== "") {
				if (!$("#custom-message").hasClass(style)) {
					$("#custom-message").addClass(style);
				}
			}
			
			height = $("#custom-message").outerHeight() + 1;
			
			show();
		}
		
		function show () {
			
			if (isHide) {
				
				$('#custom-message').animate({
					top : "0px"
				}, duration, onShow);				
			}
		}
		
		function onShow () {
			
			isHide = false;
			
			if (delay > 0) {
				
				timer = window.setTimeout(hide, delay);	
			}			
		}
	
		function hide () {

			if (!isHide) {
				
				if (timer !== null) {
					clearTimeout(timer);
				}
				
				$('#custom-message').animate({
					top : "-" + height + "px"
				}, duration, onHide);
			}
		}
		
		function onHide () {
			
			isHide = true;
		}
		
		function init () {
			
			$('body').append($('<div id="custom-message"><span id="custom-message-content"></span><a href="javascript:;" id="custom-message-close">x</a></div>'));
			
			height = $("#custom-message").outerHeight() + 1 + 20;
			
			//console.log(height);
			
			$("#custom-message").css("top", "-" + height + "px");

			$("#custom-message-close").click(hide);
		}
		
		init();
		
		return {
			update : update,
			show : show,
			hide : hide
		};
		
	}());
	
	// menu
	var Menu = function(element_id) {

		var button,
			panel,
			timer,
			isOver = false,
			isOpen = false,
			duration = 200,
			hOpen = 0,
			hClose = 0;

		if (element_id === undefined) {
			return;
		}

		if ($('#' + element_id).length === 0 || $('#ss-menu-' + element_id).length === 0) {
			return;
		}

		function onOpen() {
			isOpen = true;
		}

		function open() {
			$('#ss-menu-' + element_id).css("visibility", "visible");
			$('#ss-menu-' + element_id).animate({
				height : hOpen + "px"
			}, duration, onOpen);
		}

		function onClose() {
			$('#ss-menu-' + element_id).css("visibility", "hidden");
			isOpen = false;
		}

		function close() {
			$('#ss-menu-' + element_id).animate({
				height : hClose + "px"
			}, duration, onClose);
		}

		function overHandler() {

			isOver = true;
			clearTimeout(timer);

			if (!isOpen) {
				open();
			}
		}

		function outHandler() {

			isOver = false;
			timer = window.setTimeout( function () {
				if (isOpen && !isOver) {
					close();
				}
			}, 400);
		}

		function init() {
			
			$('#ss-menu-' + element_id).css("height", "0").css("visibility", "hidden");
			
			$('#' + element_id).bind("mouseover", overHandler);
			$('#ss-menu-' + element_id).bind("mouseover", overHandler);

			$('#' + element_id).bind("mouseout", outHandler);
			$('#ss-menu-' + element_id).bind("mouseout", outHandler);

			$('#ss-menu-' + element_id + ' > li').each( function () {
				hOpen += $(this).outerHeight();
			});
		}

		init();
	};
	var menu1 = new Menu("societe");
	var menu2 = new Menu("services");
	
	var links = $("a.afg-conseils"), i = 0;
	for (i = 0; i < links.length; i++){		
		$(links[i]).click(function(){						
			var num = this.id;
			var url = Registry.url.base + Registry.locale + "/conseils.html?num=" + num;
			window.open(url, 'conseils', 'width=500, height=200');			
			return false;
		});
	}
	//console.log(links);
	// affiche le mode de compatibilité de IE
	//alert(document.documentMode);
});
