
/**
 *	Page loading
 *	@deps jQuery
 *	@author Nicolas Wozniak
 */
$(document).ready (function () {
	/**
	 *	Manage the language menu (Track1.5)
	 */
	$ ('.right-menu').css ({ display : "none" });
	$ ('.languages').mouseover (function () {
		$ ('.right-menu').css ({ display : "block" });
	});
	$ ('.languages').mouseout (function () {
		$ ('.right-menu').css ({ display : "none" });
	});
	
	/**
	 *	Load the stats & the downloads
	 */
	//stats.loadClicks ();
	stats.loadDownloads ();
});

/**
 *	UnrollSubMenu ()
 *	Create the menu
 *	@version 2 
 *	@recursive
 */
function getTree (item) {
	tree = '';
	for (var i = 0; i < item.length; i++) {
		/**
		 *	Check if this is the active menu
		 */
		if (isActive (item [i].link))
			tree += "<li class='active'><a href='" + item [i].link + "'>" + item [i].title + "</a></li>";
		else
			tree += "<li><a href='" + item [i].link + "'>" + item [i].title + "</a></li>";	
	
		/**
		 *	Go deeper if we can
		 *	@recursive
		 */
		if (item [i].childs) {
			if (isActivePath (item [i].link))
				tree += "<ul class='active'>" + getTree (item [i].childs) + "</ul>";
			else
				tree += "<ul>" + getTree (item [i].childs) + "</ul>";
		}
	}
	
	return tree;
}

/**
 *	isActive ()
 *	Check if this is the active page
 */
function isActive (link) {
	/**
	 *	First we need to define where we currently are
	 */
	var currentPage = location.pathname;
	
	if (link == currentPage) return true;
	return false;
}

/**
 *	isActivePath ()
 *	Check if this page is active
 */
function isActivePath (link) {
	var currentPage = location.pathname;
	var currentPagen = currentPage.replace (".htm", "");
	var linkn = link.replace (".htm", "");
	
	/**
	 *	We can be either in a page or in a deeper sublevel
	 */
	if (linkn == currentPagen || getPath (currentPage).indexOf (linkn) > -1) {
		return true;
	}
	return false;
}

/**
 *	getPath ()
 *	Remove the filename if we have one
 */
function getPath (path) {
	if (!path.search ('.htm')) return path;		//No page specified return the path
	
	var ex = path.split ("/");
	var newPath = "";
	for (var j=0; j < ex.length - 1; j++) {
		newPath += ex [j] + "/";
	}
	return newPath;
}

/**
 *	Class news 
 *	Manages the news v2
 *	@author Nicolas Wozniak
 *	@version 1.0 // 05/11/2008
 *	@deps jQuery
 */
var news = {
	/**
	 *	Maximum/minimum values
	 */
	SIZE_MAX: 16,
	SIZE_MIN: 8,
	
	/**
	 *	enlargeText ()
	 *	Enlarge the text if not already at max
	 */
	enlargeText: function () {
		var size = Math.ceil (parseInt ($ ('#news-detail>p').css ("font-size"))) + 1;
		if (size < this.SIZE_MAX) $ ('#news-detail>p').css ("font-size", size + "px");
		return false;
	},
	/**
	 *	reduceText ()
	 *	Reduce the text if not already at max
	 */
	reduceText: function () {
		var size = Math.ceil (parseInt ($ ('#news-detail>p').css ("font-size"))) - 1;
		if (size > this.SIZE_MIN) $ ('#news-detail>p').css ("font-size", size + "px");
		return false;
	},
	/**
	 *	print ()
	 *	Print the news text
	 */
	print: function () {
		window.print ();
		return false;
	},
	/**
	 *	mail ()
	 *	Send an email with the news content (by ThickBox)
	 *	@not implemented yet
	 */
	mail: function () {}
};

/**
 *	Class stats
 *	Record statistics actions according to the t1 framework
 */
var stats = {

	/**
	 *	download ()
	 *	Record a document download
	 *	@param {String} _filename : the doc's filename
	 *	@deprecated DOcuments are loaded on load time now. Keep for compatibility
	 */
	download: function(_filename) {},
	
	/**
	 *	imagePreview ()
	 *	Click on an image
	 */
	imagePreview: function (_filename) {
		if (typeof xt_med != 'undefined') xt_med ('C', '', 'imagePreview::' + _filename, 'T');		//XiTi
		if (typeof urchinTracker != 'undefined') urchinTracker ('/image/' + _filename);		//Google Analytics
		if (typeof pageTracker  != 'undefined') pageTracker._trackPageview ('/image/' + _filename);	//GA v2
	},
	
	/**
	 *	zip ()
	 *	Download a zip file (imageBank v2)
	 */
	zip: function () {
		if (typeof xt_med != 'undefined') xt_med ('C', '', 'zip::imageBank', 'T');		//XiTi
		if (typeof urchinTracker != 'undefined') urchinTracker ('/zip/imageBank');		//Google Analytics
		if (typeof pageTracker  != 'undefined') pageTracker._trackPageview ('/zip/imageBank');	//GA v2
	},
	
	/**
	 *	video ()
	 *	Record a video's viewing
	 *	@param {String} _flv : the FLV's filename
	 */
	video: function(_flv) {
		if (typeof xt_med != 'undefined') xt_med ('C', '', 'video::' + _flv, 'T');		//XiTi
		if (typeof urchinTracker != 'undefined') urchinTracker ('/video/' + _flv);		//Google Analytics
		if (typeof pageTracker  != 'undefined') pageTracker._trackPageview ('/video/' + _flv);	//GA v2
	},
	
	/**
	 *	loadDownloads ()
	 *	Load the <a href> in <ul class="file">
	 */
	loadDownloads: function () {
		$ ('ul.file > li > a').click (function () {
			var _link = basename (this.getAttribute ("href"));
			if (typeof xt_med != 'undefined') 
				xt_med ('C', '', 'file::' + _link, 'N');		//XiTi
			if (typeof urchinTracker != 'undefined') 	
				urchinTracker ('/file::' + _link);			//Google Analytics
			if (typeof pageTracker  != 'undefined') 
				pageTracker._trackPageview ('/file/' + _link);	//GA v2
		});
	},
	/**
	 *	loadClicks ()
	 *	Load the <a href> <ith class="read-more" and assign the stats.onclick function 
	 */
	loadClicks: function () {
		$ ('.read-more').click (function () {
			var _link = this.getAttribute ("href");
			if (typeof xt_med != 'undefined') 
				xt_med ('C', '', 'link::' + _link, 'N');		//XiTi
			if (typeof urchinTracker != 'undefined') 	
				urchinTracker ('/link::' + _link);			//Google Analytics
			if (typeof pageTracker  != 'undefined') 
				pageTracker._trackPageview ('/link/' + _link);	//GA v2
		});
	}
};

/**
 *	Deprecated, for compatibility. Use the jquery loader instead.
 */
function addOnload (f) {
	var oldOnload = window.onload;
	if (typeof oldOnload == "function") {
		window.onload = function() {
			if (oldOnload) oldOnload();
			f ();
		}
	} else window.onload = f;
}

/**
 *	basename ()
 *	Return the basename of a file
 *	@author Nicolas Wozniak
 */
function basename (path) {
	var ex = path.split ("/");
	return (ex.length > 0) ? ex [ex.length -1] : path;
}

/**
 *	form_getImages ()
 *	Get the selected images from the Image Bank v2 template 
 */
function form_getImages () {
	var _form = document.forms ['image_bank'];
	var _selected = [];
	for (var i=0; i < _form.elements.length; i++) {
		if (_form.elements [i].checked) _selected.push (_form.elements [i].name);
	}
		
	/**
	 *	Check that at least one image is selected
	 */
	if (_selected == '') {
		lang.get ("selectOnePic", function (v) {
			showMessage (v);
		 });
		return false;
	}
	stats.zip ();	//Stat it!	
	return true;
}

/**
 *	form_sendImages ()
 *	Send the selected images by email
 *	@author Nicolas Wozniak
 */
function form_sendImages () {
	/**
	 *	Get the selected images and put them into a chain seprated by comas
	 */
	var _form = document.forms ['image_bank'];
	var _selected = '';
	var email = document.getElementById ('emailv').value;
	for (var i=0; i < _form.elements.length; i++) {
		if (_form.elements [i].checked) _selected += _form.elements [i].name + ',';
	}
	
	/**
	 *	Check that at least one image is selected
	 */
	if (_selected == '') {
		lang.get ("selectOnePic", function (v) {
			showMessage (v);
		 });
		return false;
	}

	/**
	 *	Check that the e-mail is valid
	 */
	var verif = /[a-zA-Z0-9_-]+@[a-zA-Z0-9-]{2,}[.][a-zA-Z.]{2,}$/;
	if (verif.exec (email) == null) {
		lang.get ("emailIncorrect", function (v) {
			showMessage (v);
		 });
		return false;
	}
	
	loader.show ();
	
	/**
	 *	Now send a call to the class.imagebank.php to send the package by email
	 *	@note POST ['sendemail'] has to be set
	 */
	$.ajax ({
	   type: "POST",
	   url: "/jp/lib/class.imagebank.php",
	   data: "sendemail=true&email=" + email + "&images=" + _selected,
	   success: function (msg) {
	   	loader.hide ();
	   	showMessage (msg);
	   }
	 });
	 
	 /*lang.get ("emailSent", function (v) {
	 	showMessage (v + " " + email);
	 });*/
}

/**
 *	showMessage ()
 *	Display a message in a black box in overlay
 *	@author Nicolas Wozniak
 *	@deps jQuery 
 */
function showMessage (txt) {
	var box = document.createElement ('div');
	$ (box).css ({ "position": "absolute", "display": "none", "width": "500", "padding": "10px", "top": "0", "left": "0", "text-align": "center",
			"background-color": "#333", "color": "#fff", "font-weight": "bold", "font-size": "13px", "-moz-border-radius": "2px"});
	$ (box).html (txt);
	
	/**
	 *	Center it
	 */
	var scrolled = (jQuery.browser ['msie']) ? document.body.scrollTop : window.pageYOffset;
	$ (box).css ({"left": ($(document).width ())/2  - 250} );
	$ (box).css ({"top": "50%"} );
	$ (box).css ({"margin-top":  (scrolled - 40) + "px"} );
	
	document.body.appendChild (box);
	
	/**
	 *	Show it in fade in for 2secs and fade it out
	 */
	$ (box).fadeIn ("slow", function  () {
				setTimeout (function () { 
					$(box).fadeOut ("slow", function () { 
						document.body.removeChild (box) 
					}); 
				}, 2000); 
			});
}
/**
 *	Loader
 *	Create a loading animation
 *	@author Nicolas Wozniak
 *	@deps jQuery
 */
var loader = {
	_animation: null,
	
	/**
	 *	show ()
	 *	Show the 208*13px animation
	 */
	show: function () {
		if (!this._animation) this._animation = new Image ();
		this._animation.src = "/img/millea/loadinganimation_tcm157-126911.gif";
		this._animation.style.position = "absolute";
		document.body.appendChild (this._animation);
		
		/**
		 *	Center it
		 */
		var scrolled = (jQuery.browser ['msie']) ? document.body.scrollTop : window.pageYOffset;
		$ (this._animation).css ({"left": ($(document).width ())/2  - 104} );
		$ (this._animation).css ({"top": "50%"} );
		$ (this._animation).css ({"margin-top":  (scrolled - 25) + "px"} );
		
	},
	/**
	 *	hide ()
	 *	Remove and hide it
	 */
	hide: function () {
		if (!this._animation) return false;
		
		document.body.removeChild (this._animation);
		this._animation = null;
	}
};

/**
 *	Class lang
 *	Manage the different languages
 *	Based on the /%lang/lib/lang.xml
 *	@deps lib.xml
 */
var lang = {
	/**
	 *	get ()
	 *	Get a value from the xml
	 */
	get: function (v, onload) {
		var myxml = xml.load ("/" + getLang () + "/lib/lang.xml", function (_xml) {
			//Get the value from the xml
			var _value = _xml.getElementsByTagName (v) [0].firstChild.nodeValue;
			onload (_value);
		});
	}
};

/**
 *	getLang ()
 *	Return the current language (fr/en/es/etc)
 */
function getLang () {
	return (document.location.pathname).split ("/") [1];
}

/**
 *	Class xml
 *	xml is a class used to load XML files. Cross-browser and easy to use.
 *	This class could go to the utils as it is not very complex... (utils.xml)
 *	More functions could be created within this class
 *	@author Nicolas Wozniak
 *	@version 1.0 - 05.23.2008
 */
var xml = {
	/**
	 *	load ()
	 *	Open an XML file asynchronously
	 *	@param {String} filename : the file name
	 *	@param {Function} onload : a function to call a load. The result will be given in param.
	 */
	load: function (filename, onload) {
		var _xml = null;
		try {
			if (document.all) _xml = new ActiveXObject ("Microsoft.XMLDOM");
			else _xml = document.implementation.createDocument ("", "", null);
		} catch (e) {
			return false;
		}
		
		if (document.all) {
			_xml.onreadystatechange = function () {		//IE
				if (_xml.readyState == 4) {
					if (onload) onload (_xml);
				}
			}
		} else {
			_xml.onload = function () {			// Mozilla
				if (onload) onload (_xml);
			}
		}
		_xml.load (filename);
	}
}

/* pop up function */
function winPop(url,wTitle,tb,mb,wWidth,wHeight) {
	newsWindow = window.open (url,wTitle,"copyhistory=no,location=no,directories=no,status=yes,resize=yes,resizable=yes,scrollbars=yes,toolbar="+tb+",menubar="+mb+",width="+wWidth+",height="+wHeight);
	newsWindow.focus();
}

		  var browserVer = parseInt (navigator.appVersion)
		  var browserName = (navigator.appVersion)
		  var codeName = (navigator.appCodeName)
		  var applicationName = (navigator.appName)
		  var n6=(applicationName.indexOf("Netscape")!=-1 && browserVer>=5)?1:0
		  var msieBrowser=(!n6&&document.all)?1:0
		  var n = (document.layers) ? 1:0
		
		  /*Netscape refresh*/
		  if(!n6 && !window.saveInnerWidth) {
		      window.onresize = resizeIt;
		      window.saveInnerWidth = window.innerWidth;
		      window.saveInnerHeight = window.innerHeight;
		    }
		  function resizeIt() {
		      if (saveInnerWidth < window.innerWidth || saveInnerWidth > window.innerWidth || saveInnerHeight > window.innerHeight || saveInnerHeight < window.innerHeight ){
		        window.history.go(0);
		      }
		  }
		
		  timSpeed=100;
		  var scrollTim;
		  var active=0;
		  var tikWidth;
		  var direction = 1;
		  speed = -1;
		  /* use this if you want to control the scrolling with buttons */
		  /*contHeight=50*/
		
		  function init(){
		   oScroll=new Array();
		   oScroll[0]=new makeScrollObj('aaScrollBox','aaControlScroll');
		  }
		  // End initialization
		
		  // object creation
		  function makeScrollObj(obj,nest){
		    nest = (!nest) ? '':'document.'+nest+'.'; // determins wether or not the var nest is sent to the function.
		    this.css = (n) ?eval(nest+'document.'+obj) : (n6) ? eval("document.getElementById('"+obj+"').style") : eval("document.all."+obj+".style");
		    this.scrollHeight = (n)?eval(nest+'document.'+obj+'.document.height' ): (n6) ? eval("document.getElementById('"+obj+"').offsetHeight") : eval(obj+".offsetHeight");
		    this.top=this.css.top;
		    this.pos = 0;
		    tikHeight = this.scrollHeight;
		    return this;
		  }
		
		
		  function scroll(){
		
		   if(parseInt(oScroll[active].css.top) + tikHeight <= 0){
		    oScroll[active].pos = 60;
		   }
		    way=speed>0?1:0;
		      /* us this if you want to control the scrolling with buttons */
		      /*if((!way && oScroll[active].pos>-oScroll[active].scrollHeight+contHeight) || (oScroll[active].pos<0 && way)){*/
		      if((!way && oScroll[active].pos > -oScroll[active].scrollHeight) || (oScroll[active].pos<0 && way)){
		        oScroll[active].css.top = oScroll[active].pos + speed;
		        oScroll[active].pos = oScroll[active].pos + speed;
		        oScroll[active].css.visibility= "visible";
		
		      }
		
		    }
		
		  function tik(){
		   scroll();
		   ticker1 = setTimeout("tik()", timSpeed);
		  }
		
		  function positionScroll(){
		      /*
		      winW = width of the browser window
		      siteW= width of the site
		      */
		
		      this.css =    (msieBrowser)?document.all["aaControlScroll"].style:(n6)?document.getElementById("aaControlScroll").style:document.aaControlScroll
		      winW =        (n)?window.innerWidth:document.body.offsetWidth;
		      siteW=774
		      topPosition = (msieBrowser||n6)?document.getElementById("newsimage").offsetTop:document.height - 127
		
		      if(winW > siteW){
		        if(browserName.indexOf("Mac")!=-1 && msieBrowser){
		          leftPosition=(winW/2) - 118
		        }else{
		          leftPosition=(msieBrowser)?(winW/2) - 126:(n6)?(winW/2) - 116:(winW/2) - 125
		        }
		      }else{
		        leftPosition=271
		      }
		
		      this.css.left = leftPosition
		      this.css.top = topPosition
		      this.css.visibility = "visible"
		
		    }