/*
 @fileoverview Este archivo es la base del ajax implementado en Minrel
 @author Basilio Cáceres, Max Villegas
 @version 0.1
*/

var porid = {
	global : new Array(),
	idname : function(e){
		if(e.target.id){
			if(eval("this."+e.target.id)!=undefined){
				eval("this."+e.target.id)(e.target);
				}
			}
	},
	volv : function(e){
		history.back();
	},
	claseBody : function(){
		$("#tools").show();
		if(document.cookie.match(/size/) && porclass.readCookie("size")!="12"){
			var size = porclass.readCookie("size");
			$("body").addClass("size-"+size);
		}
		else{
			if(porclass.readCookie("size")=="12") document.cookie = "size=12; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/";
			$("body").addClass("size-12");
		}
	},
	aumentar : function(e){
		claseBody = document.body.className;
		if(claseBody != "size-16"){
			clase = claseBody.split("size-");
			size = eval(clase[1]) + 1;
			$("body").removeClass(claseBody);
			$("body").addClass("size-"+size);
			porclass.setCookie(size);
		}
	},
	disminuir : function(e){
		claseBody = document.body.className;
		if(claseBody != "size-11"){
			clase = claseBody.split("size-");
			size = eval(clase[1]) - 1;
			$("body").removeClass(claseBody);
			$("body").addClass("size-"+size);
			porclass.setCookie(size);
		}
	},
	imprimir : function(e){
		window.print();
	},
	amigo : function(){
		$("#comparteLink").before("<img src='http://chileabroad.gov.cl/wp-content/themes/imag/auxi/auxiLoad.gif' alt='Loading' />");
		var n = $("#comparteLink").attr("title");
		var n = n.split(" | ");
		var str = "tools=true&url="+n[0]+"&title="+n[1];
		jQuery.get("/", str, function(data){
			$("#comparteLink").prev().remove();
			$('.oculShar').html(data);
			if(document.getElementById('red') && navigator.userAgent.match(/MSIE/)) {
				$(".red").css("z-index","100");
				$("#red").css("cursor","pointer");
			}
			$('#red').bind("click", function(){ porid.red(); return false;});
			$('#enviar').bind("click", function(e){ return false;});
			$('#enviar').bind("click", function(e){ porid.comprobar(e); return false;});
			$('#cerrComp').bind("click", function(e){porid.share(e); return false;});
		});
	},
	enviar_amigo : function(e){
		$("#boxShar").toggle();
	},
	close_amigo : function(e){
		$("#boxShar").hide();
	},
	comprobar : function(e){
		boton = e.target.id;
		comp = $("#form").serialize();
		str = $("#form").serializeArray();
		var filtro = new RegExp(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);
  		jQuery.each(str, function(i, field){
			if ((field.value=="" || (field.name=="email" && filtro.test(field.value)==false) || (field.name=="emailamigo" && filtro.test(field.value)==false)) && field.name!="mensaje"){
				$('#'+field.name).addClass('alert');
				if(!document.getElementById(''+field.name+'req')) $('#'+field.name).prev().after("<p class='req' id='"+field.name+"req'>error</req>");
			}
			else{
				var req = field.name+"req";
				$('#'+field.name).removeClass('alert');
				if(document.getElementById(req)){
					$('#'+field.name).prev().remove();
				}
			}
		});
		var total = comp+"&total=true";
		jQuery.get("/", total, function(data){
			if(data=="ok"){
				comp = $("#form").serialize();
				str = $("#form").serializeArray();
				if(boton == "enviar"){
					$("#comparteLink").before("<img src='http://chileabroad.gov.cl/web/wp-content/themes/imag/auxi/auxiLoad.gif' alt='Loading' />");
					var comp = comp;
					jQuery.getJSON("/", comp, function(data){
						porid.enviar(data);
					});
				}
			}
		});
	},
	enviar : function (data){
		$('#form').html(data.texto);
		$('.js').bind("click", function(e){porid.idname(e); return false;});
	}
}

var changeByClass = {
	consulados : function(e){
		valor = e.target.value;
		jQuery.getJSON("/",{query:"consulado", pais: valor }, function(datos){
			infos = datos;
			consulado = ""; consulado += '<option value="">'+datos[1]+'</option>';
			for(i = 0 ; i < datos[0].length ; i++){
				consulado  += '<option value="'+datos[0][i].url+'">'+datos[0][i].ciudad+'</option>';
			}
			jQuery("#consulado").html(consulado).attr('disabled', false).val("0").removeClass("inac");

		});
	},
	openSite : function(e){
 		if ($("#"+e.target.id).val()=="") return;
 		window.open($("#"+e.target.id).val() + "/","_self","");
	}
}

var porclass = {
	/***********************************************************************************  Mapas home ***/
	linkEmbajada : function(e){
		$('.linkEmbajada').unbind("click");
		var newid = e.target.href.split("#");
		$("#loading").show();
		jQuery.getJSON("/",{get:"pais", continente:newid[1], tipo:"embajada"}, function(datos){
			$("#loading").hide();
			paises = "";
			for(i = 0 ; i < datos.length ; i++){
				last = datos.length==parseInt(i+1) ?' class="last"':'';
				first = i==0 ?' class="first"':'';
				paises  += '<li'+last+first+'><a href="'+datos[i].path+'" title="'+datos[i].pais+'">'+datos[i].pais+'</a></li>';
			}
			elements_mapa = jQuery(".mapaCont").children();
			for(i = 0 ; i < elements_mapa.length ; i++){
				id = elements_mapa[i].childNodes[0].id;
				$("#mapaConti_"+id).html('<a href="#'+id+'" title="'+elements_mapa[i].childNodes[0].title+'" class="linkEmbajada">'+elements_mapa[i].childNodes[0].title+'</a>').removeClass("acti");
				if ( newid[1] == id ) conti = elements_mapa[i].childNodes[0].title;
			}
			$("#mapaConti_"+newid[1]).html('<strong>'+conti+'</strong><ul>'+paises+'</ul>').addClass("acti");
			$(".mapaCont li").removeClass("acti");
			$("#"+newid[1]).parent().addClass("acti");
			$('.linkEmbajada').bind("click", function(e){porclass.linkEmbajada(e); return false;});
			if (location.pathname.replace(/^\//,'') == e.target.pathname.replace(/^\//,'') && location.hostname == e.target.hostname) {
				var $target = $(e.target.hash);
				$target = $target.length && $target || $('[name=' + e.target.hash.slice(1) +']');
				if ($target.length) {
					var targetOffset = $target.offset().top;
					$('html,body').animate({scrollTop: targetOffset}, 1000);
					return false;
				}
			}
		});
	},
	linkConsulado : function(e){
		$('.linkConsulado').unbind("click");
		var newid = e.target.href.split("#");
		$("#loading").show();
		jQuery.getJSON("/",{get:"pais", continente:newid[1], tipo:"consulado"}, function(datos){
			$("#loading").hide();
			paises = "";
			consulados = "";
			if(datos){
				for(i = 0 ; i < datos.length ; i++){
					first = i == 0 ?' style="display:show"':' style="display:none"';
					acti = i == 0 ?' class="acti"':'';
					paises  += '<li'+acti+'><a title="'+datos[i].pais+'" href="#listPais" class="linkPaisCons" id="Pais_'+i+'">'+datos[i].pais+'</a></li>';

					consulados += '<ul class="listFloat" id="boxPais_'+i+'" '+first+'>';
					for(n = 0 ; n < datos[i].info.length ; n++){
						consulados += '<li><a href="'+datos[i].info[n].url+'" title="'+datos[i].info[n].nombre+'">'+datos[i].info[n].nombre+'</a></li>';
					}
					consulados += '</ul>';
				}
				if(!$.id("#listConsulados")){
					$(".mapaCont").after('<div id="listConsulados" class="linkRela cf linkBox"><ul id="listPais">'+paises+'</ul>'+consulados+'</div>');
				} else {
					$(".linkRela").html('<ul id="listPais">'+paises+'</ul>'+consulados);
				}
			}
			else{
				if($.id("#listConsulados")) $("#listConsulados").remove();
			}
			$(".mapaCont li").removeClass("acti");
			$("#"+newid[1]).parent().addClass("acti");
			$('.linkConsulado').bind("click", function(e){porclass.linkConsulado(e); return false;});
			$('.linkPaisCons').bind("click", function(e){porclass.paisConsulado(e); return false;});
			if (location.pathname.replace(/^\//,'') == e.target.pathname.replace(/^\//,'') && location.hostname == e.target.hostname) {
				var $target = $(e.target.hash);
				$target = $target.length && $target || $('[name=' + e.target.hash.slice(1) +']');
				if ($target.length) {
					var targetOffset = $target.offset().top;
					$('html,body').animate({scrollTop: targetOffset}, 1000);
					return false;
				}
			}
		});
	},
	paisConsulado : function(e){
		$('#listPais li').removeClass("acti");
		$('.listFloat').hide();
		$('#box'+e.target.id).show();
		$('#'+e.target.id).parent().addClass("acti");
	},
	ocultar_boton : function(){
		$('.boxHome input').hide();
		$('.boxHome').height(200);
	},
	/***********************************************************************************  Cookies tamanos de tipografia ***/
	setCookie : function(size){
		var date = new Date();
		date.setTime(date.getTime()+(5*24*60*60*1000));
		document.cookie = "size="+size+"; expires="+date.toGMTString()+"; path=/";
	},
	readCookie : function(nombre){
		var nameEQ = nombre + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	},
	/***********************************************************************************  Pestanas ***/
	pestanas : function (e){
		var url = e.target.href.split("#");
		var padre = e.target.parentNode;
		var id = url[1];
		$(".menuPest li").removeClass('acti');
		padre.className = 'acti';
		$(".boxColo").hide();
		$("#"+id).show();
	},
	pestana_activa : function(){
		$(".boxColo").hide();
		$("#menuPest li").removeClass("acti");
		if(document.URL.match(/#/)){
			url = document.URL.split("#");
			$("#"+url[1]).show();
			$("#link_"+url[1]).parent().addClass("acti");
		}
		else{
			elements_divs = $(".xplicaCont");
			id_xplica = elements_divs[0].id;
			$("#"+id_xplica).show();
			$("#menuPest li:first-child").addClass("acti");
		}
	},
	/***********************************************************************************  Box Noticias - Encuestas ***/
	toggle_box : function(e){
		if(!navigator.userAgent.match(/MSIE/)) {

			if(document.getElementById("box_novedades"))
				$("#box_novedades").toggle("slow");
			
			if(document.getElementById("box_novedades_carrousel"))
				$("#box_novedades_carrousel").toggle("slow");				
		} else {

			if(document.getElementById("box_novedades"))
				$("#box_novedades").toggle();	
				
			if(document.getElementById("box_novedades_carrousel"))
				$("#box_novedades_carrousel").toggle();
		} 
		
		if(!navigator.userAgent.match(/MSIE/))  {
			$("#box_encuestas").toggle("slow");	
		} else {
			$("#box_encuestas").toggle();	
		}

		$("#link_novedades").toggleClass("acti");
		$("#link_encuestas").toggleClass("acti");
	}
}

$(document).ready( function() {
	jQuery.each(changeByClass, function (i) { //detecta eventos al cambiar un select
		if (jQuery.isFunction(changeByClass[i])  && jQuery('*').hasClass(changeByClass[i]) ){
			jQuery('.'+i).change(function(e){eval("changeByClass."+i+"(e)");});
		}
	});
	if(document.getElementById("menuPest")){
		porclass.pestana_activa();
		$('.pestanas').click(function(e){porclass.pestanas(e); return true;});
	}
	if ($.id('#tools')) porid.claseBody();
	if ($.id('#home') && $('.boxHome')) porclass.ocultar_boton();
	if ($.id('#select_pais_script')) $('#select_pais_script').show();
	$('.hide').hide();
	$('.show').show();
	$('.js').bind("click", function(e){porid.idname(e); return false;});
	$('.toggle_box').bind("click", function(e){porclass.toggle_box(e); return false;});
	//$('.linkEmbajada').bind("click", function(e){porclass.linkEmbajada(e); return false;});
	//$('.linkConsulado').bind("click", function(e){porclass.linkConsulado(e); return false;});
	$('.linkPaisCons').bind("click", function(e){porclass.paisConsulado(e); return false;});
	$('#enviar').bind("click", function(e){porid.comprobar(e); return false;});
	$('#enviaramigo').bind("click", function(e){porid.comprobar(e); return false;});
});

jQuery.extend({
	id : function(id) {
		var id = id.split("#");
		return document.getElementById(id[1])?true:false;
	}
});


/*
 * 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 = "http://chileabroad.gov.cl/web/wp-content/themes/imag/auxi/auxiThic.gif";

/*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/

//on page load call tb_init

$(document).ready(function(){
	tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
	imgLoader = new Image();// preload image
	imgLoader.src = tb_pathToImage;
});

//add thickbox to href & area elements that have a class of .thickbox
function tb_init(domChunk){
	$(domChunk).click(function(){
	var t = this.title || this.name || null;
	var a = this.href || this.alt;
	var g = this.rel || false;
	tb_show(t,a,g);
	this.blur();
	return false;
	});
}

function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link

	try {
		if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
			$("body","html").css({height: "100%", width: "100%"});
			$("html").css("overflow","hidden");
			if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
				$("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(tb_remove);
			}
		}else{//all others
			if(document.getElementById("TB_overlay") === null){
				$("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(tb_remove);
			}
		}

		if(tb_detectMacXFF()){
			$("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
		}else{
			$("#TB_overlay").addClass("TB_overlayBG");//use background and opacity
		}

		if(caption===null){caption="";}
		$("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
		$('#TB_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;
	   }

	   var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
	   var urlType = baseURL.toLowerCase().match(urlString);

		if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images

			TB_PrevCaption = "";
			TB_PrevURL = "";
			TB_PrevHTML = "";
			TB_NextCaption = "";
			TB_NextURL = "";
			TB_NextHTML = "";
			TB_imageCount = "";
			TB_FoundURL = false;
			if(imageGroup){
				TB_TempArray = $("a[@rel="+imageGroup+"]").get();
				for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) {
					var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
						if (!(TB_TempArray[TB_Counter].href == url)) {
							if (TB_FoundURL) {
								TB_NextCaption = TB_TempArray[TB_Counter].title;
								TB_NextURL = TB_TempArray[TB_Counter].href;
								TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>";
							} else {
								TB_PrevCaption = TB_TempArray[TB_Counter].title;
								TB_PrevURL = TB_TempArray[TB_Counter].href;
								TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>";
							}
						} else {
							TB_FoundURL = true;
							TB_imageCount = "Image " + (TB_Counter + 1) +" of "+ (TB_TempArray.length);
						}
				}
			}

			imgPreloader = new Image();
			imgPreloader.onload = function(){
			imgPreloader.onload = null;

			// Resizing large images - orginal by Christian Montoya edited by me.
			var pagesize = tb_getPageSize();
			var x = pagesize[0] - 150;
			var y = pagesize[1] - 150;
			var imageWidth = imgPreloader.width;
			var imageHeight = imgPreloader.height;
			if (imageWidth > x) {
				imageHeight = imageHeight * (x / imageWidth);
				imageWidth = x;
				if (imageHeight > y) {
					imageWidth = imageWidth * (y / imageHeight);
					imageHeight = y;
				}
			} else if (imageHeight > y) {
				imageWidth = imageWidth * (y / imageHeight);
				imageHeight = y;
				if (imageWidth > x) {
					imageHeight = imageHeight * (x / imageWidth);
					imageWidth = x;
				}
			}
			// End Resizing

			TB_WIDTH = imageWidth + 30;
			TB_HEIGHT = imageHeight + 60;
			$("#TB_window").append("<a href='' id='TB_ImageOff' title='Cerrar'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Cerrar ventana'>Cerrar</a> o presione Escape</div>");

			$("#TB_closeWindowButton").click(tb_remove);

			if (!(TB_PrevHTML === "")) {
				function goPrev(){
					if($(document).unbind("click",goPrev)){$(document).unbind("click",goPrev);}
					$("#TB_window").remove();
					$("body").append("<div id='TB_window'></div>");
					tb_show(TB_PrevCaption, TB_PrevURL, imageGroup);
					return false;
				}
				$("#TB_prev").click(goPrev);
			}

			if (!(TB_NextHTML === "")) {
				function goNext(){
					$("#TB_window").remove();
					$("body").append("<div id='TB_window'></div>");
					tb_show(TB_NextCaption, TB_NextURL, imageGroup);
					return false;
				}
				$("#TB_next").click(goNext);

			}

			document.onkeydown = function(e){
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tb_remove();
				} else if(keycode == 190){ // display previous image
					if(!(TB_NextHTML == "")){
						document.onkeydown = "";
						goNext();
					}
				} else if(keycode == 188){ // display next image
					if(!(TB_PrevHTML == "")){
						document.onkeydown = "";
						goPrev();
					}
				}
			};

			tb_position();
			$("#TB_load").remove();
			$("#TB_ImageOff").click(tb_remove);
			$("#TB_window").css({display:"block"}); //for safari using css instead of show
			};

			imgPreloader.src = url;
		}else{//code to show html

			var queryString = url.replace(/^[^\?]+\??/,'');
			var params = tb_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
			ajaxContentW = TB_WIDTH - 30;
			ajaxContentH = TB_HEIGHT - 45;

			if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window
					urlNoQuery = url.split('TB_');
					$("#TB_iframeContent").remove();
					if(params['modal'] != "true"){//iframe no modal
						$("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Cerrar ventana'>Cerrar</a> o presione Escape</div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>");
					}else{//iframe modal
					$("#TB_overlay").unbind();
						$("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>");
					}
			}else{// not an iframe, ajax
					if($("#TB_window").css("display") != "block"){
						if(params['modal'] != "true"){//ajax no modal
						$("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>Cerrar</a> o presione Escape</div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
						}else{//ajax modal
						$("#TB_overlay").unbind();
						$("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>");
						}
					}else{//this means the window is already up, we are just loading new content via ajax
						$("#TB_ajaxContent")[0].style.width = ajaxContentW +"px";
						$("#TB_ajaxContent")[0].style.height = ajaxContentH +"px";
						$("#TB_ajaxContent")[0].scrollTop = 0;
						$("#TB_ajaxWindowTitle").html(caption);
					}
			}

			$("#TB_closeWindowButton").click(tb_remove);

				if(url.indexOf('TB_inline') != -1){
					if(url.match(/xplica/)) {
						section = url.split("#");
						section = section[0].split("/");
						section = section.reverse();
						section = section[0];
						$.get("/", "name_xplica="+section, function(data){
							$("#TB_ajaxContent").append(data);
							$("#TB_window").unload(function () {
								$('#' + params['inlineId']).append( $("#TB_ajaxContent").children() ); // move elements back when you're finished
							});
							porclass.pestana_activa();
							$('.pestanas').click(function(e){porclass.pestanas(e); return true;});
						});
					} else if(url.match(/embajada/) || url.match(/consulado/)) {
						section = url.split("#");
						section = section[0].split("/");
						section = section.reverse();
						var continente = section[0];
						var tipo = section[1];
						var leng = section[2];
						$("#TB_ajaxContent").append('<div id="loading_thickbox">Loading...</div>');
						$.get("/", "tipo_map="+tipo+"&continente_map="+continente+"&leng_map="+leng, function(data){
							$("#loading_thickbox").remove();
							$("#TB_ajaxContent").append(data);
							// funciones mapa
							$('#selectCountry a, #mapa li', '#mapBox').click( function(e) { countryInfo(this) } );
							$('.officeTab a', '#selCouWrap').click( function(e) { changeTab(this) });
							$('div.back a', '#selCouWrap').click( function(e){ hideCountry(this) } );
							$('#contSelector a').click( function(e){ changeMap(this); return false; });
							if (msie6) {
								$('img.inactive', '#mapa').each( function(e){ fixImgAlpha(this) } );
								$('a', '#selectCountry').each( function(e){ mapHoverIE6(this) } );
								$('li', '#mapa').each( function(e){ mapHoverIE6(this) } );
							} else {
								$('a', '#selectCountry').each( function(e){ remoteHover(this) } );
								$('li', '#mapa').each( function(e){ remoteHover(this) } );								
							}
							$("#TB_window").unload(function () {
								$('#' + params['inlineId']).append( $("#TB_ajaxContent").children() ); // move elements back when you're finished
							});
						});
					} else {
						$("#TB_ajaxContent").append($('#' + params['inlineId']).children());
						$("#TB_window").unload(function () {
							$('#' + params['inlineId']).append( $("#TB_ajaxContent").children() ); // move elements back when you're finished
						});
					}
					tb_position();
					$("#TB_load").remove();
					$("#TB_window").css({display:"block"});
				}else if(url.indexOf('TB_iframe') != -1){
					tb_position();
					if($.browser.safari){//safari needs help because it will not fire iframe onload
						$("#TB_load").remove();
						$("#TB_window").css({display:"block"});
					}
				}else{
					$("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
						tb_position();
						$("#TB_load").remove();
						tb_init("#TB_ajaxContent a.thickbox");
						$("#TB_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
					tb_remove();
				}
			};
		}

	} catch(e) {
		//nothing here
	}
}

//helper functions below
function tb_showIframe(){
	$("#TB_load").remove();
	$("#TB_window").css({display:"block"});
}

function tb_remove() {
 	$("#TB_imageOff").unbind("click");
	$("#TB_closeWindowButton").unbind("click");
	$("#TB_window").fadeOut("fast",function(){$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});
	$("#TB_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 tb_position() {
$("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
		$("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
	}
}

function tb_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;
  }
}

/**
 * jCarouselLite - jQuery plugin to navigate images/any content in a carousel style widget.
 * @requires jQuery v1.2 or above
 *
 * http://gmarwaha.com/jquery/jcarousellite/
 *
 * Copyright (c) 2007 Ganeshji Marwaha (gmarwaha.com)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * Version: 1.0.1
 * Note: Requires jquery 1.2 or above from version 1.0.1
 */

(function($) {                                          // Compliant with jquery.noConflict()
$.fn.jCarouselLite = function(o) {
    o = $.extend({
        btnPrev: null,
        btnNext: null,
        btnGo: null,
        mouseWheel: false,
        auto: null,

        speed: 200,
        easing: null,

        vertical: false,
        circular: true,
        visible: 3,
        start: 0,
        scroll: 1,

        beforeStart: null,
        afterEnd: null
    }, o || {});

    return this.each(function() {                           // Returns the element collection. Chainable.

        var running = false, animCss=o.vertical?"top":"left", sizeCss=o.vertical?"height":"width";
        var div = $(this), ul = $("ul", div), tLi = $("li", ul), tl = tLi.size(), v = o.visible;

        if(o.circular) {
            ul.prepend(tLi.slice(tl-v-1+1).clone())
              .append(tLi.slice(0,v).clone());
            o.start += v;
        }

        var li = $("li", ul), itemLength = li.size(), curr = o.start;
        div.css("visibility", "visible");

        li.css({overflow: "hidden", float: o.vertical ? "none" : "left"});
        ul.css({margin: "0", padding: "0", position: "relative", "list-style-type": "none", "z-index": "1"});
        div.css({overflow: "hidden", position: "relative", "z-index": "2", left: "0px"});

        var liSize = o.vertical ? height(li) : width(li);   // Full li size(incl margin)-Used for animation
        var ulSize = liSize * itemLength;                   // size of full ul(total length, not just for the visible items)
        var divSize = liSize * v;                           // size of entire div(total length for just the visible items)

        li.css({width: li.width(), height: li.height()});
        ul.css(sizeCss, ulSize+"px").css(animCss, -(curr*liSize));

        div.css(sizeCss, divSize+"px");                     // Width of the DIV. length of visible images

        if(o.btnPrev)
            $(o.btnPrev).click(function() {
                return go(curr-o.scroll);
            });

        if(o.btnNext)
            $(o.btnNext).click(function() {
                return go(curr+o.scroll);
            });

        if(o.btnGo)
            $.each(o.btnGo, function(i, val) {
                $(val).click(function() {
                    return go(o.circular ? o.visible+i : i);
                });
            });

        if(o.mouseWheel && div.mousewheel)
            div.mousewheel(function(e, d) {
                return d>0 ? go(curr-o.scroll) : go(curr+o.scroll);
            });

        if(o.auto)
            setInterval(function() {
                go(curr+o.scroll);
            }, o.auto+o.speed);

        function vis() {
            return li.slice(curr).slice(0,v);
        };

        function go(to) {
            if(!running) {

                if(o.beforeStart)
                    o.beforeStart.call(this, vis());

                if(o.circular) {            // If circular we are in first or last, then goto the other end
                    if(to<=o.start-v-1) {           // If first, then goto last
                        ul.css(animCss, -((itemLength-(v*2))*liSize)+"px");
                        // If "scroll" > 1, then the "to" might not be equal to the condition; it can be lesser depending on the number of elements.
                        curr = to==o.start-v-1 ? itemLength-(v*2)-1 : itemLength-(v*2)-o.scroll;
                    } else if(to>=itemLength-v+1) { // If last, then goto first
                        ul.css(animCss, -( (v) * liSize ) + "px" );
                        // If "scroll" > 1, then the "to" might not be equal to the condition; it can be greater depending on the number of elements.
                        curr = to==itemLength-v+1 ? v+1 : v+o.scroll;
                    } else curr = to;
                } else {                    // If non-circular and to points to first or last, we just return.
                    if(to<0 || to>itemLength-v) return;
                    else curr = to;
                }                           // If neither overrides it, the curr will still be "to" and we can proceed.

                running = true;

                ul.animate(
                    animCss == "left" ? { left: -(curr*liSize) } : { top: -(curr*liSize) } , o.speed, o.easing,
                    function() {
                        if(o.afterEnd)
                            o.afterEnd.call(this, vis());
                        running = false;
                    }
                );
                // Disable buttons when the carousel reaches the last/first, and enable when not
                if(!o.circular) {
                    $(o.btnPrev + "," + o.btnNext).removeClass("disabled");
                    $( (curr-o.scroll<0 && o.btnPrev)
                        ||
                       (curr+o.scroll > itemLength-v && o.btnNext)
                        ||
                       []
                     ).addClass("disabled");
                }

            }
            return false;
        };
    });
};

function css(el, prop) {
    return parseInt($.css(el[0], prop)) || 0;
};
function width(el) {
    return  el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight');
};
function height(el) {
    return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom');
};

})(jQuery);

