// Initialize JavaScript
if (Array.prototype.find) {
	Array.prototype.find = null;
}
if (!Array.prototype.find) {
	function ArrayFind(value) {
		// simply add the element to the end of the array changing the arrays length by +1
		var index = -1;
		for (var i = 0; i < this.length; i++) {
			if (this[i] == value) {
				index = i;
				break;
			}
		}
		return index;
	}
	// set the Arrays push method equal to our ArrayPush function
	Array.prototype.find = ArrayFind;
} 

String.prototype.toBool = function() {
	return (/^true$/i).test(this);
}

// Initialize namespaces
var ISHEDD = ISHEDD || {};

// ISHEDD JavaScript toolkit
ISHEDD.Forms = ISHEDD.Forms || {};
ISHEDD.Forms.Tables = ISHEDD.Forms.Tables || {};
ISHEDD.Layout = ISHEDD.Layout || {};
ISHEDD.Tools = ISHEDD.Tools || {};
ISHEDD.Util = ISHEDD.Util || {};
ISHEDD._viewport = null;

ISHEDD.Initialize = function() {
	ISHEDD._viewport = $("#viewport-body");
}

ISHEDD.Util.Cookies = {
	/** Get a cookie's value
	 *
	 *  @param integer      key             The token used to create the cookie
	 *  @return void
	 */
	get: function(key, defaultValue) {
		// Still not sure that "[a-zA-Z0-9.()=|%/_]+($|;)" match *all* allowed characters in cookies
		tmp =  document.cookie.match((new RegExp(key +'=[a-zA-Z0-9.()=|%/_]+($|;)','g')));
		if(!tmp || !tmp[0]) return defaultValue ? defaultValue : null;
		else return unescape(tmp[0].substring(key.length+1,tmp[0].length).replace(';','')) || (defaultValue ? defaultValue : null);
	},      
	/** Set a cookie
	 *
	 *  @param integer      key             The token that will be used to retrieve the cookie
	 *  @param string       value   The string to be stored
	 *  @param integer      ttl             Time To Live (hours)
	 *  @param string       path    Path in which the cookie is effective, default is "/" (optional)
	 *  @param string       domain  Domain where the cookie is effective, default is window.location.host (optional)
	 *  @param boolean      secure  Use SSL or not, default false (optional)
	 * 
	 *  @return setted cookie
	 */
	set: function(key, value, ttl, path, domain, secure) {
		cookie = [key + '=' + escape(value)];
		if (!!path) cookie.push('path=' + path);
		if (!!domain) cookie.push('domain='+ domain);
		if (!!ttl) cookie.push(Cookie.hoursToExpireDate(ttl));
		if (!!secure) cookie.push('secure');
		return document.cookie = cookie.join('; ');
	},
	/** Unset a cookie
	 *
	 *  @param integer      key             The token that will be used to retrieve the cookie
	 *  @param string       path    Path used to create the cookie (optional)
	 *  @param string       domain  Domain used to create the cookie, default is null (optional)
	 *  @return void
	 */
	unset: function(key, path, domain) {
		path   = (!path   || typeof path   != 'string') ? '' : path;
		domain = (!domain || typeof domain != 'string') ? '' : domain;
		if (Cookie.get(key)) Cookie.set(key, '', 'Thu, 01-Jan-70 00:00:01 GMT', path, domain);
	},
	/** Return GTM date string of "now" + time to live
	 *
	 *  @param integer      ttl             Time To Live (hours)
	 *  @return string
	 */
	hoursToExpireDate: function(ttl) {
		if (parseInt(ttl) == 'NaN') return '';
		else {
			now = new Date();
			now.setTime(now.getTime() + (parseInt(ttl) * 60 * 60 * 1000));
			return now.toGMTString();                       
		}
	}
}

// Prints the current window
ISHEDD.Tools.PrintThisPage = function() {
	self.print();
}

// Scrolls the current window to its top-left corner
ISHEDD.Tools.ScrollToTop = function() {
	self.scroll(0, 0);
}

ISHEDD.Tools.HandleSearchTool = function() {
	$("#application-search .input-text").addClass("input-text-blurred");

	$("#application-search .input-text").focus(function() {
		if (this.value == this.defaultValue) {
			this.value = '';
			$(this).removeClass("input-text-blurred");
		}
		$(this).blur(function() {
			if (this.value == '') {
				$(this).addClass("input-text-blurred");
				this.value = this.defaultValue;
			}
		});
	});
	$("#application-search .input-submit").click(function() {
		$("#application-search form").submit();
	});
	$("#application-search form").submit(function() {
		var text = $("#application-search .input-text")[0];
		return (text.value != text.defaultValue);
	});
}

// TOC object
ISHEDD.Tools.TOC = {
	_initialize: function($toc_content, $toc_container, exclude) {
		$container = $($toc_container || "#toc");
		$headers = $(":header", $toc_content).not(exclude);
		// Only if there's both a container and headers
		if ($container.length == 0 || $headers.length == 0) return;
		
		var idx = 0;
		var lastLevel = -1;
		var $currentParent = $container;
		
		$headers.each(function() {
			$header = $(this);
			var level = parseInt($header[0].tagName.match(/([\d]*)$/)[0]);
			// created a nested unordered list..
			if (level > lastLevel) {
				var $ul = $("<ul />");
				$currentParent.append($ul);
				$currentParent = $ul;
			} else if (level < lastLevel) {
				for (i = 0; i < (lastLevel - level); i++) {
					$currentParent = $currentParent.parent();
				}
			}
			// add the new TOC entry
			if (!$header.attr("id")) {
				$header.attr("id", "toc_gen_" + idx);
			}
			var $li = ISHEDD.Tools.TOC._makeEntry($header.text(), $header.attr("id"));
			$currentParent.append($li);
			// Add backlink to TOC
			$header.append('<div class="toc-backlink" title="Haut de la page" />');
			// keep track of where we are
			lastLevel = level;
			idx++;
		});
	},
	_makeEntry: function(Caption, Anchor, Class) {
		return $("<li />")
			.addClass(Class)
			.append(
				$("<a />").attr("href", '#' + Anchor).text(Caption)
			);
	},
	Initialize: function($toc_content, $toc_container, title, exclude) {
		title = title || "Table des matières :";
		// Create the subtree from the main header
		ISHEDD.Tools.TOC._initialize($toc_content, $toc_container, exclude);
		// Display the TOC title
		var $toc_caption = $("<strong />")
			.addClass("toc-caption")
			.click(function() {
				$("> ul", $toc_container).slideToggle("fast", function() {
					ISHEDD.Util.Cookies.set("show_toc", $(this).is(":visible"));
				});
			})
			.text(title);
		$toc_container.prepend($toc_caption);
		$toc_container.wrap('<div class="toc-container" />');
		$('<div class="clear" />').insertAfter($toc_container);
		// Get the toc itself
		var $ul_toc = $(">ul", $toc_container).eq(0);
		$ul_toc.localScroll({
			duration: 100,
			hash: true
		});
		$("div.toc-backlink").click(function() {
			$.scrollTo(0, 100);
		});
		// Hide the TOC
		if (!ISHEDD.Util.Cookies.get("show_toc", "true").toBool()) {
			$ul_toc.hide();
		}
		// Display the TOC itself
		//$toc_container.fadeIn();
	}
}

ISHEDD.Layout.InitZebraTables = function(what) {
	$("table > tbody[class*='striping-l']", what || document).each(function() {
		$this = $(this);
		var matches = (this.className).match(/striping-l([0-9]+)/);
		if (!matches || !matches[1]) return;
		var level = parseInt(matches[1]);
		
		for (var i = 1; i <= level; i++) {
			$("> tr", $this).removeClass("nth-" + i);
			$("> tr:not(.template)", $this).filter(":nth-child(" + level + "n+" + i + ")").addClass("nth-" + i);
		}
	});
}

ISHEDD.Layout.FixThinSpaces = function() {
	if ($.browser.msie) {
		if (parseFloat($.browser.version) < 7) return;
	}
	
	var $body = $("#viewport-body");
	$("ul, ol", $body).find(" > li:contains(' ;')").each(function() {
		$this = $(this);
		$this.html($this.html().replace(/ ;\s*$/, "&thinsp;;"));
	});
	$("p, :header, dt", $body).filter(":contains(' :')").each(function() {
		$this = $(this);
		$this.html($this.html().replace(/ :\s*$/, "&thinsp;:"));
	});
	$("form label", $body).filter(":contains(' :')").each(function() {
		$this = $(this);
		$this.html($this.html().replace(/((\xa0:)|(&nbsp;:))/, "&thinsp;:"));
	});
}

ISHEDD.Layout.InitExternalLinks = function() {
	// Strip the host name down, removing subdomains or www.
	var host = window.location.host.replace(/^(([^\/]+?\.)*)([^\.]{4,})((\.[a-z]{1,4})*)$/, '$3$4');
	var subdomain = window.location.host.replace(/^(([^\/]+?\.)*)([^\.]{4,})((\.[a-z]{1,4})*)$/, '$1');
	
	// Determine what subdomains are considered internal.
	var subdomains = (subdomain == 'www.' || subdomain == '')
		? "(www\.)?"
		: subdomain.replace(".", "\.");
	
	// Build regular expressions that define an internal link.
	var internal_link = new RegExp("^https?://" + subdomains + host, "i");
	
	// Find all links which are NOT internal and begin with http (as opposed
	// to ftp://, javascript:, etc. other kinds of links.
	// When operating on the 'this' variable, the host has been appended to
	// all links by the browser, even local ones.
	// In jQuery 1.1 and higher, we'd us a filter method here, but it is not
	// available in jQuery 1.0 (Drupal 5 default).

	var $external_links = $("a[href]:parent").filter(function() {
		var url = $(this).attr("href").toLowerCase();
		return (url.indexOf('http') == 0 && !url.match(internal_link)) || ($(this).hasClass("external-link"));
	});
	
	var $mailto_links = $("a[href^='mailto']:parent");

	// Apply the "ext" class to all links not containing images.
	$external_links.not($external_links.find('img').parents('a')).addClass("extlink-link");
	$mailto_links.not($mailto_links.find('img').parents('a')).addClass("extlink-mailto");
	
	// Apply the target attribute to all links.
	$external_links.attr('target', "_blank");
}

ISHEDD.Layout.InitializeUI = function() {
}

ISHEDD.Forms.Initialize = function() {
	$("form :input", ISHEDD._viewport).each(function() {
		$this = $(this);
		$this.addClass("input-type-" + $this.attr("type"));
	});
	ISHEDD.Forms.InitializeEffects();
	ISHEDD.Forms.Tables.Initialize();
}

ISHEDD.Forms.InitializeEffects = function() {
	$("form label[for]", ISHEDD._viewport).hover(function() {
		o_this = $(this);
		o_this.addClass("hovered");
		$("#" + o_this.attr("for")).not(":checkbox, :radio").addClass("hovered");
	}, function() {
		o_this = $(this);
		o_this.removeClass("hovered");
		$("#" + o_this.attr("for")).not(":checkbox, :radio").removeClass("hovered");
	});
	$("form :input", ISHEDD._viewport)
		.bind("focus", function() { $(this).addClass("focused"); })
		.bind("blur", function() { $(this).removeClass("focused"); });
}

ISHEDD.Forms.Tables.Initialize = function() {
	ISHEDD.Forms.Tables.Update();
}

ISHEDD.Forms.Tables.AddEntry = function(what) {
	$tbody = $("> tbody > tr.template", $(what).prev("table.form-table"));
	ISHEDD.Forms.Tables.Update($tbody, true);
}

ISHEDD.Forms.Tables.DeleteEntry = function(what) {
	$tbody = $(what).closest("tbody");
	$(what).closest("tr").remove();
	ISHEDD.Forms.Tables.Update($tbody);
	ISHEDD.Layout.InitZebraTables($tbody.parents("fieldset").eq(0));
}

ISHEDD.Forms.Tables.Update = function(what, addone) {
	if (what) {
		// Update one table
		$tbody = $(what).closest("table.form-table > tbody");
	} else {
		// Update all tables
		$tbody = $("table.form-table > tbody:has(>tr.template)", ISHEDD._viewport);
	}
	$tbody.each(function() {
		$this = $(this);
		$template = $(">tr.template", $this);
		$table = $(what).closest("table.form-table");

		var matches = ($template.get(0).className).match(/max-row-count-([0-9]+)/);
		var tcount = (!matches || !matches[1]) ? false : parseInt(matches[1]);
		var rcount = $(">tr:not(.template)", $this).length;

		switch (true) {
			// Empty table... add one...
			case $(">tr", $this).not(".template").length == 0:
			// Asked addition
			case addone === true && (tcount ? rcount < tcount : true):
				$this.append($template.clone(true).removeClass("template" + (tcount ? " " + matches[0]: "")));
				ISHEDD.Layout.InitZebraTables($table.parent());
		}
	});
}

// Initialization
$(function() {
	ISHEDD.Initialize();
	ISHEDD.Layout.InitializeUI();
	ISHEDD.Layout.InitExternalLinks();
	ISHEDD.Layout.FixThinSpaces();
	ISHEDD.Layout.InitZebraTables();
	ISHEDD.Forms.Initialize();
	ISHEDD.Tools.HandleSearchTool();
});

