/*
* Treeview 1.5pre - jQuery plugin to hide and show branches of a tree
* 
* http://bassistance.de/jquery-plugins/jquery-plugin-treeview/
* http://docs.jquery.com/Plugins/Treeview
*
* Copyright (c) 2007 Jörn Zaefferer
*
* Dual licensed under the MIT and GPL licenses:
*   http://www.opensource.org/licenses/mit-license.php
*   http://www.gnu.org/licenses/gpl.html
*
* Revision: $Id: jquery.treeview.js 5759 2008-07-01 07:50:28Z joern.zaefferer $
*
*/

var $j = jQuery.noConflict();

; (function ($) {

	// TODO rewrite as a widget, removing all the extra plugins
	$j.extend($j.fn, {
		swapClass: function (c1, c2) {
			var c1Elements = this.filter('.' + c1);
			this.filter('.' + c2).removeClass(c2).addClass(c1);
			c1Elements.removeClass(c1).addClass(c2);
			return this;
		},
		replaceClass: function (c1, c2) {
			return this.filter('.' + c1).removeClass(c1).addClass(c2).end();
		},
		hoverClass: function (className) {
			className = className || "hover";
			return this.hover(function () {
				$j(this).addClass(className);
			}, function () {
				$j(this).removeClass(className);
			});
		},
		heightToggle: function (animated, callback) {
			animated ?
				this.animate({ height: "toggle" }, animated, callback) :
				this.each(function () {
					jQuery(this)[jQuery(this).is(":hidden") ? "show" : "hide"]();
					if (callback)
						callback.apply(this, arguments);
				});
		},
		heightHide: function (animated, callback) {
			if (animated) {
				this.animate({ height: "hide" }, animated, callback);
			} else {
				this.hide();
				if (callback)
					this.each(callback);
			}
		},
		prepareBranches: function (settings) {
			if (!settings.prerendered) {
				// mark last tree items
				this.filter(":last-child:not(ul)").addClass(CLASSES.last);
				// collapse whole tree, or only those marked as closed, anyway except those marked as open
				this.filter((settings.collapsed ? "" : "." + CLASSES.closed) + ":not(." + CLASSES.open + ")").find(">ul").hide();
			}
			// return all items with sublists
			return this.filter(":has(>ul)");
		},
		applyClasses: function (settings, toggler) {
			// TODO use event delegation
			this.filter(":has(>ul):not(:has(>a))").find(">span").unbind("click.treeview").bind("click.treeview", function (event) {
				// don't handle click events on children, eg. checkboxes
				if (this == event.target)
					toggler.apply($j(this).next());
			}).add($j("a", this)).hoverClass();

			if (!settings.prerendered) {
				// handle closed ones first
				this.filter(":has(>ul:hidden)")
						.addClass(CLASSES.expandable)
						.replaceClass(CLASSES.last, CLASSES.lastExpandable);

				// handle open ones
				this.not(":has(>ul:hidden)")
						.addClass(CLASSES.collapsable)
						.replaceClass(CLASSES.last, CLASSES.lastCollapsable);

				// create hitarea if not present
				var hitarea = this.find("div." + CLASSES.hitarea);
				if (!hitarea.length)
					hitarea = this.prepend("<div class=\"" + CLASSES.hitarea + "\"/>").find("div." + CLASSES.hitarea);
				hitarea.removeClass().addClass(CLASSES.hitarea).each(function () {
					var classes = "";
					$.each($j(this).parent().attr("class").split(" "), function () {
						classes += this + "-hitarea ";
					});
					$j(this).addClass(classes);
				})
			}

			// apply event to hitarea
			this.find("div." + CLASSES.hitarea).click(toggler);
		},
		treeview: function (settings) {

			settings = $.extend({
				cookieId: "treeview"
			}, settings);

			if (settings.toggle) {
				var callback = settings.toggle;
				settings.toggle = function () {
					return callback.apply($j(this).parent()[0], arguments);
				};
			}

			// factory for treecontroller
			function treeController(tree, control) {
				// factory for click handlers
				function handler(filter) {
					return function () {
						// reuse toggle event handler, applying the elements to toggle
						// start searching for all hitareas
						toggler.apply($j("div." + CLASSES.hitarea, tree).filter(function () {
							// for plain toggle, no filter is provided, otherwise we need to check the parent element
							return filter ? $j(this).parent("." + filter).length : true;
						}));
						return false;
					};
				}
				// click on first element to collapse tree
				$j("a:eq(0)", control).click(handler(CLASSES.collapsable));
				// click on second to expand tree
				$j("a:eq(1)", control).click(handler(CLASSES.expandable));
				// click on third to toggle tree
				$j("a:eq(2)", control).click(handler());
			}

			// handle toggle event
			function toggler() {
				$j(this)
					.parent()
				// swap classes for hitarea
					.find(">.hitarea")
						.swapClass(CLASSES.collapsableHitarea, CLASSES.expandableHitarea)
						.swapClass(CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea)
					.end()
				// swap classes for parent li
					.swapClass(CLASSES.collapsable, CLASSES.expandable)
					.swapClass(CLASSES.lastCollapsable, CLASSES.lastExpandable)
				// find child lists
					.find(">ul")
				// toggle them
					.heightToggle(settings.animated, settings.toggle);
				if (settings.unique) {
					$j(this).parent()
						.siblings()
					// swap classes for hitarea
						.find(">.hitarea")
							.replaceClass(CLASSES.collapsableHitarea, CLASSES.expandableHitarea)
							.replaceClass(CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea)
						.end()
						.replaceClass(CLASSES.collapsable, CLASSES.expandable)
						.replaceClass(CLASSES.lastCollapsable, CLASSES.lastExpandable)
						.find(">ul")
						.heightHide(settings.animated, settings.toggle);
				}
			}
			this.data("toggler", toggler);

			function serialize() {
				function binary(arg) {
					return arg ? 1 : 0;
				}
				var data = [];
				branches.each(function (i, e) {
					data[i] = $j(e).is(":has(>ul:visible)") ? 1 : 0;
				});
				$.cookie(settings.cookieId, data.join(""), settings.cookieOptions);
			}

			function deserialize() {
				var stored = $.cookie(settings.cookieId);
				if (stored) {
					var data = stored.split("");
					branches.each(function (i, e) {
						$j(e).find(">ul")[parseInt(data[i]) ? "show" : "hide"]();
					});
				}
			}

			// add treeview class to activate styles
			this.addClass("treeview");

			// prepare branches and find all tree items with child lists
			var branches = this.find("li").prepareBranches(settings);

			switch (settings.persist) {
				case "cookie":
					var toggleCallback = settings.toggle;
					settings.toggle = function () {
						serialize();
						if (toggleCallback) {
							toggleCallback.apply(this, arguments);
						}
					};
					deserialize();
					break;
				case "location":

				var current = this.find("a").filter(function() {

//Cas d'un LinkRetourUrl : 
var checkLRU = (location.search.toLowerCase().match("(linkretoururl){1}","ig"))?true:false; 
//Cas de ?
var checkInterogationMENU = (this.href.toLowerCase().match("[?]{1}","ig"))?true:false;
var checkInterogationURL = (location.href.toLowerCase().match("[?]{1}","ig"))?true:false;
//Cas de Clef_SITESMAPS :
var checkClefSitesmapsURL = (location.search.toLowerCase().match("(Clef_SITESMAPS=){1}([0-9]+)","ig"))?true:false;
var checkClefSitesmapsMENU = (this.href.toLowerCase().match("(Clef_SITESMAPS=){1}([0-9]+)","ig"))?true:false;
//Cas de l'administration :
var checkAdministrationURL = (location.pathname.toLowerCase().indexOf('administration'))?true:false;
var checkAdministrationMENU = (this.href.toLowerCase().indexOf('administration'))?true:false;

//Variables qui vont servir de teste pour la fin : 
var CheckAutorisation = null;


if (location.pathname.toLowerCase().indexOf('administration') != 1) {
			return $(this).attr("rel") == $(this).attr("sitemap_url").split(',').slice(-1);
		}
		/******************** * Pas de REWRITING * ********************/
		else{
		/**** Pour l'ADMINISTRATION : ***/
		if(checkAdministrationURL == 1){
		/**** Cas avec un LinkRetourURL :***/
			if(checkLRU){
				/* L'URL */
				var RecupStringLRU = location.href.toLowerCase().substring(location.href.toLowerCase().indexOf("linkretoururl",0)+14 ,location.href.length);
				//On vérifie si il y a un & : 
				if(RecupStringLRU.indexOf("&", 0) != -1)
					RecupStringLRU = RecupStringLRU.substring(0,RecupStringLRU.indexOf("&", 0));
					//On vérifie si l'url contient des "%2f", dans ce cas on les replace par des "/"
				if(RecupStringLRU.indexOf("%2f",0) != -1){
					var CheckPercent = true;
					while(CheckPercent){
						if(RecupStringLRU.indexOf("%2f",0)==-1)
							CheckPercent = false;
						else
							RecupStringLRU = RecupStringLRU.replace("%2f", "/"); 
						}
					}
					/* Le MENU */
					var IndexDebutForLRU = this.href.toLowerCase().indexOf("/",7);
					var IndexFinForLRU = null;
					//Si il y a un ?, on récupère la position où il se trouve, sinon l'url entier :
					if(checkInterogationMENU)
						IndexFinForLRU = this.href.toLowerCase().indexOf("?",0);
					else
						IndexFinForLRU = this.href.toLowerCase().length;
						
					var MenuHrefForLRU = this.href.toLowerCase().substring(IndexDebutForLRU, IndexFinForLRU);
					//On compare l'URL et le Menu :
					if(MenuHrefForLRU == RecupStringLRU)
						CheckAutorisation = true;
					else
						CheckAutorisation = false;
					}else if(checkAdministrationMENU && checkAdministrationURL && CheckAutorisation == null){
						var RegexDetectFileForMENU = new RegExp("[/]{1}[a-zA-Z0-9\\.\\-\\_]+.(aspx|ascx){1}", "ig");
						var RegexDetectFileForURL = new RegExp("[/]{1}[a-zA-Z0-9\\.\\-\\_]+.(aspx|ascx){1}", "ig");
						
						/**** Construction de l'url du MENU : ***/
						var indexAdminDebutMENU = this.href.toLowerCase().toString().indexOf("/administration",0);
						var indexAdminFinMENU = null;
						if(checkInterogationMENU){ 
							var NameFileForMENU = this.href.toLowerCase().match(RegexDetectFileForMENU).toString().toLowerCase();
							indexAdminFinMENU = this.href.toLowerCase().indexOf(NameFileForMENU);
						}else	indexAdminFinMENU = this.href.toLowerCase().lastIndexOf("/");
						
						var pathNameAdminMENU = this.href.toLowerCase().substring(indexAdminDebutMENU, indexAdminFinMENU);
						
						/**** Construction de l'URL :***/
						var indexAdminDebutURL = location.pathname.toLowerCase().indexOf("/administration",0);
						var indexAdminFinURL = null;
						if(checkInterogationURL){
							var NameFileForURL = location.pathname.match(RegexDetectFileForURL).toString().toLowerCase();
							indexAdminFinURL = location.pathname.toLowerCase().indexOf(NameFileForURL);
						}else
							indexAdminFinURL = location.pathname.toLowerCase().lastIndexOf("/");							
							var pathNameAdminURL = location.pathname.toLowerCase().substring(indexAdminDebutURL, indexAdminFinURL); 
						if(pathNameAdminMENU.toLowerCase() == pathNameAdminURL.toLowerCase())
							CheckAutorisation = true;
						}
					}
					/**** Plusieurs cas possibles avec le "?"***/
					if(checkInterogationURL && CheckAutorisation == null){
					/**** Cas avec des Clef_SITESMAPS : ***/
					if(checkClefSitesmapsMENU && checkClefSitesmapsURL){
					//La regex Clef_SITESMAPS... : 
					var RegexForClefSitesmaps = new RegExp("((Clef_SITESMAPS=){1}([0-9]+))+","ig");
					
					/**** Pour l'URL [-location.href...-]***/
					//Contiendra : Clef_SITESMAPS=123123...,Clef_SITESMAPS=123121212... :
					var tableauDeClefSitesmapsSansRewritingForURL = null;
					
					//Contiendra : 123123...,12312121212... :
					var tableauOnlyClefSansRewritingForURL = null;
					
					//Contiendra : 1,2,3 ou ... : 
					var niveauHierarchiqueSansRewritingForURL = null;
					var RecupStringAllClefSitesmapsForURL = location.search.toLowerCase().match(RegexForClefSitesmaps).toString();
					tableauOnlyClefSansRewritingForURL = RecupStringAllClefSitesmapsForURL.match("[0-9]+","g");
					tableauDeClefSitesmapsSansRewritingForURL = RecupStringAllClefSitesmapsForURL.split("&");
					niveauHierarchiqueSansRewritingForURL = tableauDeClefSitesmapsSansRewritingForURL.length;
					
					/**** Pour le MENU [-this.href...-]***/
					
					//Contiendra : Clef_SITESMAPS=123123...,Clef_SITESMAPS=123121212... :
					var tableauDeClefSitesmapsSansRewritingForMENU = null;
					
					//Contiendra : 123123...,12312121212... :
					var tableauOnlyClefSansRewritingForMENU = null;
					
					//Contiendra : 1,2,3 ou ... : 
					var niveauHierarchiqueSansRewritingForMENU = null;
					var RecupStringAllClefSitesmapsForMENU = this.href.toLowerCase().match(RegexForClefSitesmaps).toString();
					tableauOnlyClefSansRewritingForMENU = RecupStringAllClefSitesmapsForMENU.match("[0-9]+","g");
					tableauDeClefSitesmapsSansRewritingForMENU = RecupStringAllClefSitesmapsForMENU.split("&");
					niveauHierarchiqueSansRewritingForMENU = tableauDeClefSitesmapsSansRewritingForMENU.length;
					
					/**** Comparaison des deux Tableau de Clef Recupéré ***/
					//On teste si les deux niveau hiérarchique sont identiques : 
					if(niveauHierarchiqueSansRewritingForMENU == niveauHierarchiqueSansRewritingForURL){
					
						//On va vérifier que chaque clef correspond :
						var CheckCompareNiveauHierarchiqueSansREWRITING = true;
						for(var ICompare = 0; ICompare <= niveauHierarchiqueSansRewritingForURL-1; ICompare++){
							if(tableauDeClefSitesmapsSansRewritingForMENU[ICompare] == tableauDeClefSitesmapsSansRewritingForURL[ICompare])
								continue;
							else{
								CheckCompareNiveauHierarchiqueSansREWRITING = false;
								break;
							}
						}
						
						//On récupère le booléen nous indiquant si les clefs correspondent : 
						if(CheckCompareNiveauHierarchiqueSansREWRITING)
							CheckAutorisation = true;
						else
						CheckAutorisation  = false;
						}else
						CheckAutorisation  = false;
					}
				}
			}
			/**** Cas juste avec une adresse sans indications particulière : ***/ 
			if((checkInterogationURL || !checkInterogationURL) && CheckAutorisation == null){
			
			/*** CONSTRUCTION DE L'URL :**/
			var UrlSansClef = location.pathname.toLowerCase();
			
			/*** CONSTRUCTION DE L'URL MENU : **/
			var IndexDebutForNothing = this.href.toLowerCase().indexOf("/",7);
			var IndexFinForNothing = null;
			
			//Définition de la taille de l'url a comparé : 
			//Si il y a un ?, on récupère la position où il se trouve, sinon l'url entier :
			if(checkInterogationMENU){
				if(checkClefSitesmapsMENU)
					IndexFinForNothing = this.href.toLowerCase().length;
				else
					IndexFinForNothing = this.href.toLowerCase().indexOf("?",0);
			}
			else
				IndexFinForNothing = this.href.toLowerCase().length;
				
				var MenuHrefForNothing = this.href.toLowerCase().substring(IndexDebutForNothing, IndexFinForNothing);
				
				if(MenuHrefForNothing == UrlSansClef)
					CheckAutorisation = true;
				else
					CheckAutorisation = false; 
			}
			/* FINAL */
			if(CheckAutorisation)
			return true;

				});

				if ( current.length ) {
					// TODO update the open/closed classes
					var items = current.addClass("selected").parents("ul, li").add( current.next() ).show();
					if (settings.prerendered) {
						// if prerendered is on, replicate the basic class swapping
						items.filter("li")
							.swapClass( CLASSES.collapsable, CLASSES.expandable )
							.swapClass( CLASSES.lastCollapsable, CLASSES.lastExpandable )
							.find(">.hitarea")
								.swapClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea )
								.swapClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea );
					}
				}
					break;
			}

			branches.applyClasses(settings, toggler);

			// if control option is set, create the treecontroller and show it
			if (settings.control) {
				treeController(this, settings.control);
				$j(settings.control).show();
			}

			return this;
		}
	});

	// classes used by the plugin
	// need to be styled via external stylesheet, see first example
	$.treeview = {};
	var CLASSES = ($.treeview.classes = {
		open: "open",
		closed: "closed",
		expandable: "expandable",
		expandableHitarea: "expandable-hitarea",
		lastExpandableHitarea: "lastExpandable-hitarea",
		collapsable: "collapsable",
		collapsableHitarea: "collapsable-hitarea",
		lastCollapsableHitarea: "lastCollapsable-hitarea",
		lastCollapsable: "lastCollapsable",
		lastExpandable: "lastExpandable",
		last: "last",
		hitarea: "hitarea"
	});

})(jQuery);
