/*
 * Textbox, basée sur :
 * Thickbox 3.1 - One Box To Rule Them All.
 * By Cody Lindley (http://www.codylindley.com)
 * Copyright (c) 2007 cody lindley
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
 */

var tb_pathToImage = "/images/loadingAnimation.gif";


//on page load call tb_init
$(document).ready(function(){   
	tbx_init_all();
});

function tbx_init_all(containerId) {
	var domChunk = (containerId) ? $('#'+containerId).find('a.textbox, area.textbox, input.textbox') : 'a.textbox, area.textbox, input.textbox';
	tbx_init(domChunk);//pass where to apply textbox
	imgLoader = new Image();// preload image
	imgLoader.src = tb_pathToImage;
	
	// si on veut afficher sur le onload de la page une thickbox, donner l'id "box_shownOnload" a l'element declencheur
	if ($('#box_shownOnload').length) {
		$('#box_shownOnload').click();
	}
}

//add textbox to href & area elements that have a class of .textbox
function tbx_init(domChunk){
	$(domChunk).click(function(){
	var t = this.title || this.name || null;
	var a = this.href || this.alt;
	if (window.tbx_onshow) // traitement eventuel avant tbx_show
		tbx_onshow(this);
	tbx_show(t,a);
	this.blur();
	// Xiti
	//try {xitiClick(xitiCi[this.id]['type'], xitiCi[this.id]['lib'], false);} catch(e){};
	try {
		var queryString = a.replace(/^[^\?]+\??/,'');
		var params = tbx_parseQuery( queryString);
		var xitiId = this.id;
		if (params['type_contact'] != undefined)
			xitiId = params['type_contact'];
		xt_med('C',xitin2,xitiCi[xitiId]['lib'],xitiCi[xitiId]['type']);
	} catch(e){};
	return false;
	});
}
function tbx_show(caption, url) {//function called when the user clicks on a textbox link

	//try {
		var defaultLocale = 'fr_FR';
		var localizedTexts = new Array();
		localizedTexts['fr_FR'] = {'altClose':'Fermer'};
		localizedTexts['en_EN'] = {'altClose':'Close'};

		if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
			$("body","html").css({height: "100%", width: "100%"});
			$("html").css("overflow","hidden");
			if (document.getElementById("box_hideSelect") === null) {//iframe to hide select elements in ie6
				$("body").append("<iframe id='box_hideSelect'></iframe><div id='box_overlay'></div><div id='box_window'></div>");
				$("#box_overlay").click(tbx_remove);
			}
		}else{//all others
			if(document.getElementById("box_overlay") === null){
				$("body").append("<div id='box_overlay'></div><div id='box_window'></div>");
				$("#box_overlay").click(tbx_remove);
			}
		}

		if(tb_detectMacXFF()){
			$("#box_overlay").addClass("box_overlayMacFFBGHack");//use png overlay so hide flash
		}else{
			$("#box_overlay").addClass("box_overlayBG");//use background and opacity
		}
		
		if(caption===null){caption="";}
		$("body").append("<div id='box_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
		$('#box_load').show();//show loader
		
		var baseURL;
	   if(url.indexOf("?")!==-1){ //ff there is a query string involved
			baseURL = url.substr(0, url.indexOf("?"));
	   }else{ 
	   		baseURL = url;
	   }
			   
	   //code to show html
		var queryString = url.replace(/^[^\?]+\??/,'');
		var params = tbx_parseQuery( queryString );

		//TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
		//TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
		TB_WIDTH = (params['width']*1) || 598; //598
		TB_HEIGHT = (params['height']*1) || ((url.indexOf('TB_inline') != -1) ? 160 : 440);
		//contentW = TB_WIDTH - 30;
		contentW = (params['width']*1) || 598;
		contentH = TB_HEIGHT - 45;
	
		// @todo : gerer ca avec des styles
		iframeW = params['TB_style'] ? contentW : contentW - 35;

		var altClose = params['locale'] ? localizedTexts[params['locale']]['altClose'] : localizedTexts[defaultLocale]['altClose'];
		$("#box_window").append("<div id='box_title'><div id='box_caption'>"+caption+"</div><div id='box_close'><a href='#' title='"+altClose+"'><img src='/images/bt-textbox-fermer.gif' alt='"+altClose+"'/></a></div></div>");

		if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window		
				urlNoQuery = url.split('TB_');
				$("#box_iframeContent").remove();
				//iframe no modal
				var scrolling = 'auto';
				if(params['TB_style']=='simple_noscrolling')
					scrolling = 'no';
				// force du scrolling uniquement pour IE6
				if(params['TB_iescrolling']=='true' && typeof document.body.style.maxHeight === "undefined")
					scrolling = 'yes';
				$("#box_window").append("<div id='box_content' style='width:"+contentW+"px;height:"+contentH+"px;'><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='box_iframeContent' scrolling='"+scrolling+"' name='box_iframeContent"+Math.round(Math.random()*1000)+"' onload='tbx_showIframe()' style='width:"+iframeW+"px;height:99%;"+(params['TB_style']?"":"margin-left:35px;")+"' > </iframe></div>");
				if(params['TB_style'])
					$("#box_window").addClass(params['TB_style']);
		}else{// not an iframe, ajax
				if($("#box_window").css("display") != "block"){
					$("#box_window").append("<div id='box_content' style='width:"+contentW+"px;height:"+contentH+"px;'></div>");
				}else{//this means the window is already up, we are just loading new content via ajax
					$("#box_content")[0].style.width = contentW +"px";
					$("#box_content")[0].style.height = contentH +"px";
					$("#box_content")[0].scrollTop = 0;
					$("#box_caption").html(caption);
				}
		}
		$("#box_close a").click(tbx_remove);
		
		if(url.indexOf('TB_inline') != -1){			 
			$("#box_content").append($('#' + params['inlineId']).children());
			$("#box_window").unload(function () {
				$('#' + params['inlineId']).append( $("#box_content").children() ); // move elements back when you're finished
			});
			tbx_position();
			$("#box_load").remove();
			$("#box_window").css({display:"block"}); 
		}else if(url.indexOf('TB_iframe') != -1){
			tbx_position();
//			if($.browser.safari){//safari needs help because it will not fire iframe onload
				$("#box_load").remove();
				$("#box_window").css({display:"block"});
//			}
		}else{
			$("#box_content").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
				tbx_position();
				$("#box_load").remove();
				tbx_init("#box_content a.textbox");
				$("#box_window").css({display:"block"});
			});
		}
			
		

		if(!params['modal']){
			document.onkeyup = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tbx_remove();
				}	
			};
		}

/*	} catch(e) {
		//nothing here
	}
*/
}

//helper functions below
function tbx_showIframe(){
	$("#box_load").remove();
	$("#box_window").css({display:"block"});
}

function tbx_remove() {
 	$("#TB_imageOff").unbind("click");
	$("#box_close").unbind("click");
	$("#box_window").fadeOut("fast",function(){$('#box_window,#box_overlay,#box_hideSelect').trigger("unload").unbind().remove();});
	$("#box_load").remove();
	if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
		$("body","html").css({height: "auto", width: "auto"});
		$("html").css("overflow","");
	}
	document.onkeydown = "";
	document.onkeyup = "";
	return false;
}

function tbx_position() {
$("#box_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
		$("#box_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
	}
}

function tbx_parseQuery ( query ) {
   var Params = {};
   if ( ! query ) {return Params;}// return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

function tb_getPageSize(){
	var de = document.documentElement;
	var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
	arrayPageSize = [w,h];
	return arrayPageSize;
}

function tb_detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}

function tbx_changeContent(url, caption) {
    $("#box_iframeContent",parent.document).attr('src',url);
    if (caption != null && caption.length > 0) 
    	$("#box_caption",parent.document).text(caption);
}


