var AJAX = '/ajax/ajax.php';
var GALERIA_AJAX = '/ajax/galeria.php';
var AGENDA_AJAX = '/ajax/agenda.php';
var ARTICLE_AJAX = '/ajax/article.php';

//if( location.href.match(/#(c-\d+)$/) )
//{
//	$("#"+RegExp.$1+">:first").css("border-style","double").css("border-width","3px")
//}

$(document).ready(function(){
	$('#ipt-cerca').example('Search...');
	$('#email-titulars').example('Email');
});

function avis_legal()
{
	if( $("#avis_legal").is(":hidden") )
		$("#avis_legal").fadeIn('slow');
	else
		$("#avis_legal").fadeOut('slow');
}

function les_noticies( lloc ) {

	if( lloc == 'comentaris' )
	{
		$("#mes_comentat").slideDown();
		$("#mes_llegit").slideUp();
		
		$("#comentaris_tag").removeClass("plantilla_actualitat_tag_inactiu");
		$("#comentaris_tag").addClass("plantilla_actualitat_tag_actiu");
		$("#noticies_tag").removeClass("plantilla_actualitat_tag_actiu");
		$("#noticies_tag").addClass("plantilla_actualitat_tag_inactiu");
	}
	else
	{
		$("#mes_comentat").slideUp();
		$("#mes_llegit").slideDown();
		
		$("#noticies_tag").removeClass("plantilla_actualitat_tag_inactiu");
		$("#noticies_tag").addClass("plantilla_actualitat_tag_actiu");
		$("#comentaris_tag").removeClass("plantilla_actualitat_tag_actiu");
		$("#comentaris_tag").addClass("plantilla_actualitat_tag_inactiu");
	}
}

function votar()
{
	var enq = $("input[@name='enq']:checked").attr("value");
  	if( enq )
	{
		$.getJSON( AJAX, { id_enquesta_opcio: enq, accio: 'votar' },
		function( resposta )
		{
			var vots = 0;
			vots = parseInt( vots );
				
 			$('#enquesta-opcions').fadeOut("slow", function()
 			{
				$(this).empty();

				for(var i = 0; i < resposta.opcions.length; i++)
				{
					tmp = parseInt( resposta.opcions[i].vots );
					vots = tmp + vots;
					afegeixOpcio(resposta.opcions[i].id_element, resposta.opcions[i].titol, resposta.opcions[i].width1, resposta.opcions[i].percentatge, enq, i);
				}

				html = '<div class="lila"><img src="img/icones/vots.png" alt="Vots" /> <span id="enquesta-vots">'+ vots +'</span> vots&nbsp;&nbsp;<a href="enquesta/'+ resposta.uri  +'#comentaris"><img src="img/icones/comentari.png" alt="Comentaris" /> '+ resposta.comentaris +'</a></div></div>';

				$('#enquesta-opcions').append( html );
				$('#enquesta-opcions').fadeIn("slow",function(){animateResults();});
			});
		});
	}
	else
	{
		alert("Has de seleccionar una opció!");
		return false;
	}
}

function afegeixOpcio(id, titol, width1, percentatge, enq, i)
{
	var html = '';

	if( id == enq )
		html += '<label for="enq_opt'+id+'"><strong>'+titol+'</strong></label><br />\n';
	else
		html += '<label for="enq_opt'+id+'">'+titol+'</label><br />\n';
		
	html += '	<div class="enq_barra" style="width: 0%;"></div>\n';
	html +=	'	<div class="enq_percent">'+percentatge+'%</div>\n';
	html +=	'<br class="p" /><br />\n';

	$('#enquesta-opcions').append( html );
}

function animateResults()
{
  $("#enquesta-opcions div.enq_barra").each(function()
  {
      var percentage = $(this).next().text();
      $(this).css({width: "0%"}).animate({width: percentage}, 'slow');
  });
}


function inscriure( accio )
{

	var email = $("#email-titulars").val();

	if( accio == 'alta' )
		accio = 'inscriure_alta';
	else
		accio = 'inscriure_baixa';
		
	if( email )
	{
		if( !echeck( email ) )
		{
			alert('The e-mail address you entered is incorrect');
			return false;
		}
		
		if( accio == 'alta' ) accio = 'inscriure_alta';

		if( accio == 'baixa' ) accio = 'inscriure_baixa';

				
		$.getJSON( AJAX, { email: email, accio: accio },
		function( resposta )
		{
			if( resposta.exit == 'true' ) $("#inscriure-formulari").empty();
			$("#inscriure-text").html( resposta.text );
		});
	}
	else
	{
		alert('Your e-mail is missing');
		return false;
	}
}

function comprovaCamp ( id_camp, color )
{

	if( $("#"+id_camp).val() == "" )
	{
		$("#"+id_camp).addClass("comentari-error");
		$("#"+id_camp).removeClass("comentari-"+color);
	}
	else
	{
		$("#"+id_camp).addClass("comentari-"+color);
		$("#"+id_camp).removeClass("comentari-error");
	}
}

function comprovaMail ( id_camp, color )
{
	if ( $("#"+id_camp).val() == "" || !echeck( $("#"+id_camp).val() ) )
	{
		$("#"+id_camp).addClass("comentari-error");
		$("#"+id_camp).removeClass("comentari-"+color);
	}
	else
	{
		$("#"+id_camp).addClass("comentari-"+color);
		$("#"+id_camp).removeClass("comentari-error");
	}
}


function enviar_comentari()
{
	var error = false;
	var error_text = '';
	var id_article;
	var facebook_uid = 0;
	var facebook_foto = '';
	var nom = '';
	var ae = '';
	var comentari;
	var poblacio = '';
	var notifica = '';

	if( $("#email").val() ) return false;

	$("#comentari-error").html();
	$("#comentari-error").hide();
	var id_article = $("#id_article").val();
	var lloc = $("#lloc").val();
	var color = $("#color").val();

	if( $('#notifica').is(':checked') )
		notifica = 'si';
	else
		notifica = 'no';

	if( $("#facebook_uid").val() )
	{
		var facebook_uid = $("#facebook_uid").val();
		var facebook_foto = $("#facebook_foto").val();
	}
	
	if( $("#nom").val() )
	{
		$("#nom").removeClass("comentari-error");
		$("#nom").addClass("comentari-"+color);
		var nom = $("#nom").val();
	}
	else if( !facebook_uid )
	{
		$("#nom").addClass("comentari-error");
		$("#nom").removeClass("comentari-"+color);
		error_text += "<li>Has de posar el teu nom</li>\n";
		error = true;
	}

	if( $("#poblacio").val() )
		var poblacio = $("#poblacio").val();
		
	if( $("#ae").val() )
		var ae = $("#ae").val();


	//if( $("#ae").val() )
	//{
	//	var ae = $("#ae").val();
	//	if( echeck( ae ) )
	//	{
	//		$("#ae").removeClass("comentari-error");
	//		$("#ae").addClass("comentari-"+color);
	//	}
	//	else
	//	{
	//		$("#ae").addClass("comentari-error");
	//		$("#ae").removeClass("comentari-"+color);
	//		error_text += "<li>El correu elctrònic que has posat és erroni</li>\n";
	//		error = true;
	//	}
	//}
	//else
	//{
	//	$("#ae").addClass("comentari-error");
	//	$("#ae").removeClass("comentari-"+color);
	//	error_text += "<li>Has de posar el correu electrònic</li>\n";
	//	error = true;
	//}
	
	if( $("#comentari").val() )
	{
		var comentari = $("#comentari").val();
		$("#comentari").removeClass("comentari-error");
		$("#comentari").addClass("comentari-"+color);
	}
	else
	{
		$("#comentari").addClass("comentari-error");
		$("#comentari").removeClass("comentari-"+color);
		error_text += "<li>Has d'escriure un comentari</li>\n";
		error = true;
	}

	
 	if( error )
	{
		$("#comentari-error").fadeIn("slow");
		$("#comentari-error").html( '<ul class="error">' + error_text + '</ul>' );
	}
	else
	{
		$.post( AJAX, { accio: 'controlar_spam_comentaris' },
		function( resposta )
		{
			if( resposta == 'true' )
			{
				error_text += "<li>S'han detectat masses enviaments a través d'aquesta ip, torna-ho a provar d'aquí una estona</li>";
				$("#comentari-error").fadeIn("slow");
				$("#comentari-error").html( '<ul class="error">' + error_text + '</ul>' );
			}
			else
			{
				$("#comentari-formulari").html( '<img src="/img/icones/loading.gif" alt="loader" style="margin: 100px 0px 100px 250px" />' );
				$.getJSON( AJAX, { id_article: id_article, facebook_uid: facebook_uid, facebook_foto: facebook_foto, lloc: lloc, nom: nom, poblacio: poblacio, email: ae, comentari: comentari, notifica: notifica, accio: 'enviar_comentari' },
				function( resposta )
				{
					$("#comentari-error").show();
					$("#comentari-formulari").fadeOut("slow");
					
					if( !resposta.recarregar )
					{
						var message = resposta.comentari;
						var attachment = {
								'name': resposta.titol,
								'href': resposta.url,
								'caption': resposta.subtitol,
								'media': [{
									'type': 'image',
									'src': resposta.imatge,
									'href': resposta.url
									}] };
						var action_links = [{'text':resposta.titol, 'href':resposta.url}];
						FB.Connect.streamPublish(message, attachment, action_links);
						
						$("#comentari-enviat").fadeIn("slow");
					}
					else
						window.location.reload()
						//window.location.href = resposta.url_llarga;
				});
			}
		});
	}
}


function genera_comentaris( pagina, id_article, lloc )
{
 	if( pagina && id_article )
	{
		$("#comentaris-cnt").html( '<img src="/img/icones/loading.gif" alt="loader" style="margin: 100px 0px 100px 250px" />' );
		$.post( AJAX, { id_article: id_article, pagina: pagina, lloc: lloc, accio: 'genera_comentaris' },
		function( resposta )
		{
			$("#comentaris-cnt").html( resposta );
		});
	}
	else
	{
		alert("Error");
	}
}

function veure_comentari( id_comentari, lloc )
{
 	if( id_comentari )
	{
		$.getJSON( AJAX, { id_comentari: id_comentari, lloc: lloc, accio: 'veure_comentari' },
		function( resposta )
		{
			$("#comentari-cnt-" + resposta.id_comentari ).html( resposta.text );
		});
	}
	else
	{
		alert("Error");
	}
}

function limitacio( numero, id_article, lloc )
{
 	if( numero && id_article && lloc )
	{
		$("#comentaris-cnt").html( '<img src="/img/icones/loading.gif" alt="loader" style="margin: 100px 0px 100px 250px" />' );
		$.post( AJAX, { numero: numero, accio: 'limitacio' },
		function()
		{
			genera_comentaris( "1", id_article, lloc );
		});
	}
	else
	{
		alert("Error");
	}
}





function echeck(str)
{
	var at="@";
	var dot=".";
	var lat=str.indexOf(at);
	var lstr=str.length;
	var ldot=str.indexOf(dot);
	
	if (str.indexOf(at)==-1)
		return false;

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr)
		return false;

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr)
		return false;

	if (str.indexOf(at,(lat+1))!=-1)
		return false;

	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot)
		return false;

	if (str.indexOf(dot,(lat+2))==-1)
		return false;

	if (str.indexOf(" ")!=-1)
		return false;

	return true;
}





function comparteix( url )
{
	if ($("#comparteix").length === 0) {
		var html = '<a href="http://latafanera.cat/submit.php?url=' + url + '" title="Envia a La Tafanera" target="_blank"><img src="img/icones/tafanera.png" alt="La Tafanera" /></a> ';
		html += '<a href="http://www.facebook.com/share.php?u=' + url + '" title="Comparteix a Facebook" target="_blank"><img src="img/icones/facebook.png" alt="Facebook" /></a> ';
		html += '<a href="http://www.google.com/bookmarks/mark?op=edit&bkmk=' + url + '" title="Comparteix a Google" target="_blank"><img src="img/icones/google.png" alt="Google" /></a> ';
		html += '<a href="http://twitter.com/home?status=' + url + '" title="Comparteix a Twitter" target="_blank"><img src="img/icones/twitter.png" alt="Twitter" /></a> ';
		html += '<a href="http://www.google.com/reader/link?url=' + url + '" title="Envia a Google Buzz" target="_blank"><img src="img/icones/buzz.png" alt="google buzz" /></a> ';
		
		if( $(".llegenda_dreta") )
			$(".llegenda_dreta").append('<span id="comparteix">'+ html +'</span>');
		if( $(".llegenda_dret") )
			$(".llegenda_dret").append('<span id="comparteix">'+ html +'</span>');
		
		$("#comparteix").fadeIn("slow");
	}
}


function cerca_avancada()
{
	$('#cerca_avancada').show();
}

function entre_data()
{
	document.cercador.dia_inici.disabled = !document.cercador.dia_inici.disabled;
	document.cercador.mes_inici.disabled = !document.cercador.mes_inici.disabled;
	document.cercador.any_inici.disabled = !document.cercador.any_inici.disabled;
	document.cercador.dia_fi.disabled = !document.cercador.dia_fi.disabled;
	document.cercador.mes_fi.disabled = !document.cercador.mes_fi.disabled;
	document.cercador.any_fi.disabled = !document.cercador.any_fi.disabled;
}



function actualitzar_usuari()
{
	$('#div-facebook').html( "<fb:profile-pic uid='loggedinuser' facebook-logo='true'></fb:profile-pic>"
	+ "<br />Benvingut/da, <fb:name uid='loggedinuser' useyou='false'></fb:name>. T'has identificat/da amb el teu compte de Facebook. "
	+ "<a href=\"#\" onclick=\"FB.Connect.logout(function() { window.location.reload(); netejar_usuari(); }); return false;\">Sortir</a>" );
	
	FB.XFBML.Host.parseDomTree();

	$('#div-nom').hide();
	$('#div-ae').hide();
	$('#div-poblacio').hide();
	$('#div-notifica').hide();

	var api = FB.Facebook.apiClient;
	var uid = [api.get_session().uid]
	$('#facebook_uid').val( uid );

	$.getJSON( FB_AJAX, { uid: uid, accio: 'actualitzar_usuari' },
	function( resposta )
	{
		$('#facebook_foto').val( resposta.foto );
		$('#nom').val( resposta.nom );
		$('#poblacio').val( resposta.poblacio );
		$('#ae').val( resposta.ae );
	});
}

function netejar_usuari ()
{
	$('#facebook_foto').val('');
	$('#nom').val('');
	$('#poblacio').val('');
	$('#ae').val('');
	$('#facebook_uid').val('');
}

function votar_comentari( id_comentari, vot, lloc)
{
	$.post( AJAX, { id_comentari: id_comentari, vot: vot, lloc: lloc, accio: 'votar_comentari' },
	function( resposta )
	{
		$("#comentari-vots-" + id_comentari ).hide();
		$("#comentari-vots-" + id_comentari ).html( resposta );		
		$("#comentari-vots-" + id_comentari ).fadeIn('slow');
	});
}

function comentari_replica( id )
{
	ref = '#' + id + ' ';
	textarea = $('#comentari');
	if (textarea.length == 0 ) return;
	var re = new RegExp(ref);
	var oldtext = textarea.val();
	if (oldtext.match(re)) return;
	if (oldtext.length > 0 && oldtext.charAt(oldtext.length-1) != "\n") oldtext = oldtext + "\n";
	textarea.val(oldtext + ref);
	textarea.get(0).focus();
}


function selecciona_municipi()
{
	var id_comarca = $('#ipt-comarca').val();

	$('#div-municipi').html('<img src="img/icones/loading.gif" alt="loader" />');
	
	$.post( AJAX, { id_comarca: id_comarca, accio: 'selecciona_municipi' },
	function( resposta )
	{
		$('#div-municipi').html( resposta );
	});
}

function selecciona_comarca()
{
	var id_zona = $('#ipt-zona').val();

	$('#div-comarca').html('<img src="imatges/loading_gros.gif" alt="loader" />');
	
	$.post( AJAX, { id_zona: id_zona, accio: 'selecciona_comarca' },
	function( resposta )
	{
		$('#div-comarca').html( resposta );
		$('#div-municipi').html( '' );
	});
}


// Variables
var ratings_mouseover_image = new Image();
ratings_mouseover_image.src = "/img/icones/valora_over.png";

// When User Mouse Over Ratings
function valora_actual(rating, id_article, rating_text)
{
	for(i = 1; i <= rating; i++)
		document.images['valora_' + id_article + '_' + i].src = eval("ratings_mouseover_image.src");

	$('#valora_text').html( rating_text );
	$('#valora_text').css("display", "inline");
}


// When User Mouse Out Ratings
function valora_off(id_article, rating_score, insert_half)
{
	for(i = 1; i <= 5; i++)
	{
		if(i <= rating_score)
			document.images['valora_' + id_article + '_' + i].src = 'img/icones/valora_on.png';
		else if(i == insert_half)
			document.images['valora_' + id_article + '_' + i].src = 'img/icones/valora_meitat.png';
		else
			document.images['valora_' + id_article + '_' + i].src = 'img/icones/valora_off.png';
	}
	
	$('#valora_text').html( '' );
	$('#valora_text').css("display", "inline");
}


function valora_article( lloc, id_article, valor, multiple )
{
	if( multiple )
	{
		$('#valora_estrelles_'+id_article).css("display", "none");
		$('#valora_loading_'+id_article).css("display", "inline");
	}
	else
	{
		$('#valora_estrelles').css("display", "none");
		$('#valora_loading').css("display", "inline");		
	}

	$.getJSON( AJAX, { lloc: lloc, valor: valor, id_article: id_article, accio: 'valorar' },
	function( resposta )
	{
		if( multiple )
		{
			$('#valora_estrelles_'+id_article).css("display", "inline")
			$('#valora_loading_'+id_article).css("display", "none")
			$('#valora_estrelles_'+id_article).html( '' );
		}
		else
		{
			$('#valora_estrelles').css("display", "inline")
			$('#valora_loading').css("display", "none")
			$('#valora_estrelles').html( '' );
		}
		
		var html = '';
		
		var textos=['','Molt dolent','Fluix','Interessant','Molt bo','Excepcional'];
	
		for( var i = 1; i <= 5; i++ )
		{
			if( resposta.mitja >= i )
				html += '<img src="img/icones/valora_on.png" alt="estrella" /> ';
			else if( resposta.meitat == i )
				html += '<img src="img/icones/valora_meitat.png" alt="estrella" /> ';
			else
				html += '<img src="img/icones/valora_off.png" alt="estrella" /> ';
		}
		
		if( resposta.vots == 1 )
			html += ' <br />hi ha <span>1</span> vot';
		else
			html += ' <br />hi ha <span>'+ resposta.vots +'</span> vots';
		
		if( multiple )
			$('#valora_estrelles_'+id_article).html( html );
		else
			$('#valora_estrelles').html( html );
		
	});
}


function formulari_article_enviar()
{
	var email = $("#email_e").val();
	var nom = $("#nom_e").val();
	var r_email = $("#r_email").val();
	var r_nom = $("#r_nom").val();
	var comentari = $("#comentari").val();
	var id_article = $("#id_article").val();
	var lloc = $("#lloc").val();

	if( email != '' )
	{
		$.post( ARTICLE_AJAX, { email: email, nom: nom, r_email: r_email, r_nom: r_nom, id_article: id_article, lloc: lloc, comentari: comentari, accio: 'enviar_article' },
		function( resposta )
		{
			$("#popup").fadeOut('slow');
			$("#popup_ok").fadeIn('slow');
			setTimeout('$.prettyPhoto.close()',3000)
		});
	}
}

$(document).ready(function(){
	$("a[rel^='prettyPhoto']").prettyPhoto({animation_speed:'fast',slideshow:10000});
	$('textarea').prettyComments();
	
	//Set Default State of each portfolio piece
	$(".portada_pagina").show();
	$(".portada_pagina a:first").addClass("actiu");
		
	//Get size of images, how many there are, then determin the size of the image reel.
	var imageWidth = $(".finestra").width();
	var imageSum = $(".imatge_real img").size();
	var imageReelWidth = imageWidth * imageSum;

	//Adjust the image reel to its new size
	$(".imatge_real").css({'width' : imageReelWidth});
	
	//portada_pagina + Slider Function
	rotate = function(){	
		var triggerID = $actiu.attr("rel") - 1; //Get number of times to slide

		if( triggerID == 0 )
			anterior = $(".imatge_real img").size();
		else
			anterior = triggerID;
			
		if( triggerID == $(".imatge_real img").size() - 1)
			seguent = 1;
		else
			seguent = parseInt(triggerID) + 2;

		$(".boto_esquerra a").attr("rel", anterior );
		$(".boto_dreta a").attr("rel", seguent );
		var imatge_realPosition = triggerID * imageWidth; //Determines the distance the image reel needs to slide

		$(".portada_pagina a").removeClass('actiu'); //Remove all actiu class
		$actiu_pag.addClass('actiu'); //Add actiu class (the $actiu is declared in the rotateSwitch function)
		
		//Slider Animation
		$(".imatge_real").animate({ 
			left: -imatge_realPosition
		}, 500 );
		
	}; 
	
	//Rotation + Timing Event
	rotateSwitch = function(){
		play = setInterval(function(){ //Set timer - this will repeat itself every 3 seconds
			$actiu = $('.portada_pagina a.actiu').next();
			if ( $actiu.length === 0) //If portada_pagina reaches the end...
				$actiu = $('.portada_pagina a:first'); //go back to first
			
			$actiu_pag = $actiu;
			rotate(); //Trigger the portada_pagina and slider function
		}, 7000); //Timer speed in milliseconds (3 seconds)
	};
	
	rotateSwitch(); //Run function on launch
	
	//On Hover
	$(".imatge_real a").hover(function() {
		clearInterval(play); //Stop the rotation
	}, function() {
		rotateSwitch(); //Resume rotation
	});	
	
	//On Click
	$(".portada_pagina a").click(function() {	
		$actiu = $(this); //Activate the clicked portada_pagina
		$actiu_pag = $actiu;
		//Reset Timer
		clearInterval(play); //Stop the rotation
		rotate(); //Trigger rotation immediately
		rotateSwitch(); // Resume rotation
		return false; //Prevent browser jump to link anchor
	});
	
	$(".boto_esquerra a").click(function() {
		$actiu = $(this); //Activate the clicked portada_pagina
		
		$actiu_pag = $('.portada_pagina a.actiu').prev();
		
		if ( $actiu_pag.length === 0 ) 
			$actiu_pag = $('.portada_pagina a:last'); //go back to last
			
		//Reset Timer
		clearInterval(play); //Stop the rotation
		rotate(); //Trigger rotation immediately
		rotateSwitch(); // Resume rotation
		return false; //Prevent browser jump to link anchor
	});
	
	$(".boto_dreta a").click(function() {	
		$actiu = $(this); //Activate the clicked portada_pagina
		
		$actiu_pag = $('.portada_pagina a.actiu').next();
		if ( $actiu_pag.length === 0) 
			$actiu_pag = $('.portada_pagina a:first'); //go back to first

		//Reset Timer
		clearInterval(play); //Stop the rotation
		rotate(); //Trigger rotation immediately
		rotateSwitch(); // Resume rotation
		return false; //Prevent browser jump to link anchor
	});
});

(function(A){A.fn.example=function(E,C){var D=A.isFunction(E);var B=A.extend({},C,{example:E});return this.each(function(){var F=A(this);if(A.metadata){var G=A.extend({},A.fn.example.defaults,F.metadata(),B)}else{var G=A.extend({},A.fn.example.defaults,B)}if(!A.fn.example.boundClassNames[G.className]){A(window).unload(function(){A("."+G.className).val("")});A("form").submit(function(){A(this).find("."+G.className).val("")});A.fn.example.boundClassNames[G.className]=true}if(A.browser.msie&&!F.attr("defaultValue")&&(D||F.val()==G.example)){F.val("")}if(F.val()==""&&this!=document.activeElement){F.addClass(G.className);F.val(D?G.example.call(this):G.example)}F.focus(function(){if(A(this).is("."+G.className)){A(this).val("");A(this).removeClass(G.className)}});F.blur(function(){if(A(this).val()==""){A(this).addClass(G.className);A(this).val(D?G.example.call(this):G.example)}})})};A.fn.example.defaults={className:"example"};A.fn.example.boundClassNames=[]})(jQuery);

/* ------------------------------------------------------------------------
	Pretty Comments
	
	Developped By: Stephane Caron (http://www.no-margin-for-errors.com)
	Inspired By: The facebook textarea :)
	Version: 1.4
	
	Copyright: Feel free to redistribute the script/modify it, as
			   long as you leave my infos at the top.
------------------------------------------------------------------------- */

	$.fn.prettyComments = function(settings) {
		settings = jQuery.extend({
					animate: false, /* If you set it to true, cursor will dissapear in FF3 */
					animationSpeed: 'fast', /* fast/slow/normal */
					maxHeight : 500,
					alreadyAnimated: false, /* DONT CHANGE */
					init: true /* DONT CHANGE */
				}, settings);

		// Create the div in which the content will be copied
		$('body').append('<div id="comment_hidden"></div>');

		var setCSS = function(which){
			// Init the div for the current textarea
			$("#comment_hidden").css({
				'position':'absolute',
				'top': -10000,
				'left': -10000,
				'width': $(which).width(),
				'min-height': $(which).height(),
				'font-family': $(which).css('font-family'),
				'font-size': $(which).css('font-size'),
				'line-height': $(which).css('line-height')
			});
			
			if($.browser.msie && parseFloat($.browser.version) < 7){
				$("#comment_hidden").css('height',$(which).height());
			};
		};
		
		var copyContent = function(which){
			// Convert the line feeds into BRs
			theValue = $(which).attr('value') || "";
			theValue = theValue.replace(/\n/g,'<br />');
			
			$("#comment_hidden").html(theValue + '<br />');
			
			if(!settings.init){
				if($("#comment_hidden").height() > $(which).height()){
					if($('#comment_hidden').height() > settings.maxHeight){
						$(which).css('overflow-y','scroll');
					}else{
						$(which).css('overflow-y','hidden');
						expand(which);
					};
				}else if($("#comment_hidden").height() < $(which).height()){
					if($('#comment_hidden').height() > settings.maxHeight){
						$(which).css('overflow-y','scroll');
					}else{
						$(which).css('overflow-y','hidden');
						shrink(which);
					};
				};
			};
		};
		
		var expand = function(which){
			if(settings.animate && !settings.alreadyAnimated){
				settings.alreadyAnimated = true;
				$(which).animate({'height':$("#comment_hidden").height()},settings.animationSpeed,function(){
					settings.alreadyAnimated = false;
				});
			}else if(!settings.animate && !settings.alreadyAnimated){
				$(which).height($("#comment_hidden").height());
			};
		};
		
		var shrink = function(which){
			if(settings.animate && !settings.alreadyAnimated){
				settings.alreadyAnimated = true;
				$(which).animate({'height':$("#comment_hidden").height()},settings.animationSpeed,function(){
					settings.alreadyAnimated = false;
				});
			}else{
				$(which).height($("#comment_hidden").height());
			};
		};
		
		$(this).each(function(){
			$(this).css({
				'overflow':'hidden'
			})
			.bind('keyup',function(){
				copyContent($(this));
			});
			
			// Make sure all the content in the textarea is visible
			setCSS(this);
			copyContent($(this));
			
			if($("#comment_hidden").height() > settings.maxHeight){
				$(this).css({
					'overflow-y':'scroll',
					'height':settings.maxHeight
				});
			}else{
				$(this).height($("#comment_hidden").height());
			};
			
			settings.init = false;
		});
	};



/* ------------------------------------------------------------------------
	Class: prettyPhoto
	Use: Lightbox clone for jQuery
	Author: Stephane Caron (http://www.no-margin-for-errors.com)
	Version: 3.1
------------------------------------------------------------------------- */


(function($){$.prettyPhoto={version:'3.1'};$.fn.prettyPhoto=function(pp_settings){pp_settings=jQuery.extend({animation_speed:'fast',slideshow:5000,autoplay_slideshow:false,opacity:0.60,show_title:true,allow_resize:true,default_width:500,default_height:344,counter_separator_label:'/',theme:'light_rounded',horizontal_padding:20,hideflash:true,wmode:'opaque',autoplay:true,modal:false,overlay_gallery:true,keyboard_shortcuts:true,changepicturecallback:function(){},callback:function(){},ie6_fallback:true,markup:'<div class="pp_pic_holder"> \
      <div class="ppt">&nbsp;</div> \
      <div class="pp_top"> \
       <div class="pp_left"></div> \
       <div class="pp_middle"></div> \
       <div class="pp_right"></div> \
      </div> \
      <div class="pp_content_container"> \
       <div class="pp_left"> \
       <div class="pp_right"> \
        <div class="pp_content"> \
         <div class="pp_loaderIcon"></div> \
         <div class="pp_fade"> \
          <a href="#" class="pp_expand" title="Expand the image">Expand</a> \
          <div class="pp_hoverContainer"> \
           <a class="pp_next" href="#">next</a> \
           <a class="pp_previous" href="#">previous</a> \
          </div> \
          <div id="pp_full_res"></div> \
          <div class="pp_details"> \
           <div class="pp_nav"> \
            <a href="#" class="pp_arrow_previous">Previous</a> \
            <p class="currentTextHolder">0/0</p> \
            <a href="#" class="pp_arrow_next">Next</a> \
           </div> \
           <p class="pp_description"></p> \
           <a class="pp_close" href="#">Close</a> \
          </div> \
         </div> \
        </div> \
       </div> \
       </div> \
      </div> \
      <div class="pp_bottom"> \
       <div class="pp_left"></div> \
       <div class="pp_middle"></div> \
       <div class="pp_right"></div> \
      </div> \
     </div> \
     <div class="pp_overlay"></div>',gallery_markup:'<div class="pp_gallery"> \
        <a href="#" class="pp_arrow_previous">Previous</a> \
        <div> \
         <ul> \
          {gallery} \
         </ul> \
        </div> \
        <a href="#" class="pp_arrow_next">Next</a> \
       </div>',image_markup:'<img id="fullResImage" src="{path}" />',flash_markup:'<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="{width}" height="{height}"><param name="wmode" value="{wmode}" /><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="{path}" /><embed src="{path}" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="{width}" height="{height}" wmode="{wmode}"></embed></object>',quicktime_markup:'<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" height="{height}" width="{width}"><param name="src" value="{path}"><param name="autoplay" value="{autoplay}"><param name="type" value="video/quicktime"><embed src="{path}" height="{height}" width="{width}" autoplay="{autoplay}" type="video/quicktime" pluginspage="http://www.apple.com/quicktime/download/"></embed></object>',iframe_markup:'<iframe src ="{path}" width="{width}" height="{height}" frameborder="no"></iframe>',inline_markup:'<div class="pp_inline">{content}</div>',custom_markup:''},pp_settings);var matchedObjects=this,percentBased=false,pp_dimensions,pp_open,pp_contentHeight,pp_contentWidth,pp_containerHeight,pp_containerWidth,windowHeight=$(window).height(),windowWidth=$(window).width(),pp_slideshow;doresize=true,scroll_pos=_get_scroll();$(window).unbind('resize.prettyphoto').bind('resize.prettyphoto',function(){_center_overlay();_resize_overlay();});if(pp_settings.keyboard_shortcuts){$(document).unbind('keydown.prettyphoto').bind('keydown.prettyphoto',function(e){if(typeof $pp_pic_holder!='undefined'){if($pp_pic_holder.is(':visible')){switch(e.keyCode){case 37:$.prettyPhoto.changePage('previous');e.preventDefault();break;case 39:$.prettyPhoto.changePage('next');e.preventDefault();break;case 27:if(!settings.modal)
$.prettyPhoto.close();e.preventDefault();break;};};};});}
$.prettyPhoto.initialize=function(){settings=pp_settings;if(settings.theme=='pp_default')settings.horizontal_padding=16;if(settings.ie6_fallback&&$.browser.msie&&parseInt($.browser.version)==6)settings.theme="light_square";theRel=$(this).attr('rel');galleryRegExp=/\[(?:.*)\]/;isSet=(galleryRegExp.exec(theRel))?true:false;pp_images=(isSet)?jQuery.map(matchedObjects,function(n,i){if($(n).attr('rel').indexOf(theRel)!=-1)return $(n).attr('href');}):$.makeArray($(this).attr('href'));pp_titles=(isSet)?jQuery.map(matchedObjects,function(n,i){if($(n).attr('rel').indexOf(theRel)!=-1)return($(n).find('img').attr('alt'))?$(n).find('img').attr('alt'):"";}):$.makeArray($(this).find('img').attr('alt'));pp_descriptions=(isSet)?jQuery.map(matchedObjects,function(n,i){if($(n).attr('rel').indexOf(theRel)!=-1)return($(n).attr('title'))?$(n).attr('title'):"";}):$.makeArray($(this).attr('title'));set_position=jQuery.inArray($(this).attr('href'),pp_images);_build_overlay(this);if(settings.allow_resize)
$(window).bind('scroll.prettyphoto',function(){_center_overlay();});$.prettyPhoto.open();return false;}
$.prettyPhoto.open=function(event){if(typeof settings=="undefined"){settings=pp_settings;if($.browser.msie&&$.browser.version==6)settings.theme="light_square";pp_images=$.makeArray(arguments[0]);pp_titles=(arguments[1])?$.makeArray(arguments[1]):$.makeArray("");pp_descriptions=(arguments[2])?$.makeArray(arguments[2]):$.makeArray("");isSet=(pp_images.length>1)?true:false;set_position=0;_build_overlay(event.target);}
if($.browser.msie&&$.browser.version==6)$('select').css('visibility','hidden');if(settings.hideflash)$('object,embed').css('visibility','hidden');_checkPosition($(pp_images).size());$('.pp_loaderIcon').show();if($ppt.is(':hidden'))$ppt.css('opacity',0).show();$pp_overlay.show().fadeTo(settings.animation_speed,settings.opacity);$pp_pic_holder.find('.currentTextHolder').text((set_position+1)+settings.counter_separator_label+$(pp_images).size());$pp_pic_holder.find('.pp_description').show().html(unescape(pp_descriptions[set_position]));movie_width=(parseFloat(grab_param('width',pp_images[set_position])))?grab_param('width',pp_images[set_position]):settings.default_width.toString();movie_height=(parseFloat(grab_param('height',pp_images[set_position])))?grab_param('height',pp_images[set_position]):settings.default_height.toString();if(movie_height.indexOf('%')!=-1){movie_height=parseFloat(($(window).height()*parseFloat(movie_height)/100)-150);percentBased=true;}
if(movie_width.indexOf('%')!=-1){movie_width=parseFloat(($(window).width()*parseFloat(movie_width)/100)-150);percentBased=true;}
$pp_pic_holder.fadeIn(function(){(settings.show_title&&pp_titles[set_position]!=""&&typeof pp_titles[set_position]!="undefined")?$ppt.html(unescape(pp_titles[set_position])):$ppt.html('&nbsp;');imgPreloader="";skipInjection=false;switch(_getFileType(pp_images[set_position])){case'image':imgPreloader=new Image();nextImage=new Image();if(isSet&&set_position<$(pp_images).size()-1)nextImage.src=pp_images[set_position+1];prevImage=new Image();if(isSet&&pp_images[set_position-1])prevImage.src=pp_images[set_position-1];$pp_pic_holder.find('#pp_full_res')[0].innerHTML=settings.image_markup.replace(/{path}/g,pp_images[set_position]);imgPreloader.onload=function(){pp_dimensions=_fitToViewport(imgPreloader.width,imgPreloader.height);_showContent();};imgPreloader.onerror=function(){alert('Image cannot be loaded. Make sure the path is correct and image exist.');$.prettyPhoto.close();};imgPreloader.src=pp_images[set_position];break;case'youtube':pp_dimensions=_fitToViewport(movie_width,movie_height);movie='http://www.youtube.com/embed/'+grab_param('v',pp_images[set_position]);if(settings.autoplay)movie+="?autoplay=1";toInject=settings.iframe_markup.replace(/{width}/g,pp_dimensions['width']).replace(/{height}/g,pp_dimensions['height']).replace(/{wmode}/g,settings.wmode).replace(/{path}/g,movie);break;case'vimeo':pp_dimensions=_fitToViewport(movie_width,movie_height);movie_id=pp_images[set_position];var regExp=/http:\/\/(www\.)?vimeo.com\/(\d+)/;var match=movie_id.match(regExp);movie='http://player.vimeo.com/video/'+match[2]+'?title=0&amp;byline=0&amp;portrait=0';if(settings.autoplay)movie+="&autoplay=1;";vimeo_width=pp_dimensions['width']+'/embed/?moog_width='+pp_dimensions['width'];toInject=settings.iframe_markup.replace(/{width}/g,vimeo_width).replace(/{height}/g,pp_dimensions['height']).replace(/{path}/g,movie);break;case'quicktime':pp_dimensions=_fitToViewport(movie_width,movie_height);pp_dimensions['height']+=15;pp_dimensions['contentHeight']+=15;pp_dimensions['containerHeight']+=15;toInject=settings.quicktime_markup.replace(/{width}/g,pp_dimensions['width']).replace(/{height}/g,pp_dimensions['height']).replace(/{wmode}/g,settings.wmode).replace(/{path}/g,pp_images[set_position]).replace(/{autoplay}/g,settings.autoplay);break;case'flash':pp_dimensions=_fitToViewport(movie_width,movie_height);flash_vars=pp_images[set_position];flash_vars=flash_vars.substring(pp_images[set_position].indexOf('flashvars')+10,pp_images[set_position].length);filename=pp_images[set_position];filename=filename.substring(0,filename.indexOf('?'));toInject=settings.flash_markup.replace(/{width}/g,pp_dimensions['width']).replace(/{height}/g,pp_dimensions['height']).replace(/{wmode}/g,settings.wmode).replace(/{path}/g,filename+'?'+flash_vars);break;case'iframe':pp_dimensions=_fitToViewport(movie_width,movie_height);frame_url=pp_images[set_position];frame_url=frame_url.substr(0,frame_url.indexOf('iframe')-1);toInject=settings.iframe_markup.replace(/{width}/g,pp_dimensions['width']).replace(/{height}/g,pp_dimensions['height']).replace(/{path}/g,frame_url);break;case'ajax':doresize=false;pp_dimensions=_fitToViewport(movie_width,movie_height);doresize=true;skipInjection=true;$.get(pp_images[set_position],function(responseHTML){toInject=settings.inline_markup.replace(/{content}/g,responseHTML);$pp_pic_holder.find('#pp_full_res')[0].innerHTML=toInject;_showContent();});break;case'custom':pp_dimensions=_fitToViewport(movie_width,movie_height);toInject=settings.custom_markup;break;case'inline':myClone=$(pp_images[set_position]).clone().append('<br clear="all" />').css({'width':settings.default_width}).wrapInner('<div id="pp_full_res"><div class="pp_inline"></div></div>').appendTo($('body')).show();doresize=false;pp_dimensions=_fitToViewport($(myClone).width(),$(myClone).height());doresize=true;$(myClone).remove();toInject=settings.inline_markup.replace(/{content}/g,$(pp_images[set_position]).html());break;};if(!imgPreloader&&!skipInjection){$pp_pic_holder.find('#pp_full_res')[0].innerHTML=toInject;_showContent();};});return false;};$.prettyPhoto.changePage=function(direction){currentGalleryPage=0;if(direction=='previous'){set_position--;if(set_position<0){set_position=$(pp_images).size()-1;};}else if(direction=='next'){set_position++;if(set_position>$(pp_images).size()-1){set_position=0;}}else{set_position=direction;};if(!doresize)doresize=true;$('.pp_contract').removeClass('pp_contract').addClass('pp_expand');_hideContent(function(){$.prettyPhoto.open();});};$.prettyPhoto.changeGalleryPage=function(direction){if(direction=='next'){currentGalleryPage++;if(currentGalleryPage>totalPage){currentGalleryPage=0;};slide_speed=settings.animation_speed;}else if(direction=='previous'){currentGalleryPage--;if(currentGalleryPage<0){currentGalleryPage=totalPage;};slide_speed=settings.animation_speed;}else{currentGalleryPage=direction;slide_speed=0;};slide_to=currentGalleryPage*(itemsPerPage*itemWidth);itemsToSlide=(currentGalleryPage==totalPage)?pp_images.length-((totalPage)*itemsPerPage):itemsPerPage;$pp_gallery.find('ul').animate({left:-slide_to},slide_speed);};$.prettyPhoto.startSlideshow=function(){if(typeof pp_slideshow=='undefined'){$pp_pic_holder.find('.pp_play').unbind('click').removeClass('pp_play').addClass('pp_pause').click(function(){$.prettyPhoto.stopSlideshow();return false;});pp_slideshow=setInterval($.prettyPhoto.startSlideshow,settings.slideshow);}else{$.prettyPhoto.changePage('next');};}
$.prettyPhoto.stopSlideshow=function(){$pp_pic_holder.find('.pp_pause').unbind('click').removeClass('pp_pause').addClass('pp_play').click(function(){$.prettyPhoto.startSlideshow();return false;});clearInterval(pp_slideshow);pp_slideshow=undefined;}
$.prettyPhoto.close=function(){if($pp_overlay.is(":animated"))return;$.prettyPhoto.stopSlideshow();$pp_pic_holder.stop().find('object,embed').css('visibility','hidden');$('div.pp_pic_holder,div.ppt,.pp_fade').fadeOut(settings.animation_speed,function(){$(this).remove();});$pp_overlay.fadeOut(settings.animation_speed,function(){if($.browser.msie&&$.browser.version==6)$('select').css('visibility','visible');if(settings.hideflash)$('object,embed').css('visibility','visible');$(this).remove();$(window).unbind('scroll.prettyphoto');settings.callback();doresize=true;pp_open=false;delete settings;});};function _showContent(){$('.pp_loaderIcon').hide();$ppt.fadeTo(settings.animation_speed,1);projectedTop=scroll_pos['scrollTop']+((windowHeight/2)-(pp_dimensions['containerHeight']/2));if(projectedTop<0)projectedTop=0;$pp_pic_holder.find('.pp_content').animate({height:pp_dimensions['contentHeight'],width:pp_dimensions['contentWidth']},settings.animation_speed);$pp_pic_holder.animate({'top':projectedTop,'left':(windowWidth/2)-(pp_dimensions['containerWidth']/2),width:pp_dimensions['containerWidth']},settings.animation_speed,function(){$pp_pic_holder.find('.pp_hoverContainer,#fullResImage').height(pp_dimensions['height']).width(pp_dimensions['width']);$pp_pic_holder.find('.pp_fade').fadeIn(settings.animation_speed);if(isSet&&_getFileType(pp_images[set_position])=="image"){$pp_pic_holder.find('.pp_hoverContainer').show();}else{$pp_pic_holder.find('.pp_hoverContainer').hide();}
if(pp_dimensions['resized']){$('a.pp_expand,a.pp_contract').show();}else{$('a.pp_expand').hide();}
if(settings.autoplay_slideshow&&!pp_slideshow&&!pp_open)$.prettyPhoto.startSlideshow();settings.changepicturecallback();pp_open=true;});_insert_gallery();};function _hideContent(callback){$pp_pic_holder.find('#pp_full_res object,#pp_full_res embed').css('visibility','hidden');$pp_pic_holder.find('.pp_fade').fadeOut(settings.animation_speed,function(){$('.pp_loaderIcon').show();callback();});};function _checkPosition(setCount){(setCount>1)?$('.pp_nav').show():$('.pp_nav').hide();};function _fitToViewport(width,height){resized=false;_getDimensions(width,height);imageWidth=width,imageHeight=height;if(((pp_containerWidth>windowWidth)||(pp_containerHeight>windowHeight))&&doresize&&settings.allow_resize&&!percentBased){resized=true,fitting=false;while(!fitting){if((pp_containerWidth>windowWidth)){imageWidth=(windowWidth-200);imageHeight=(height/width)*imageWidth;}else if((pp_containerHeight>windowHeight)){imageHeight=(windowHeight-200);imageWidth=(width/height)*imageHeight;}else{fitting=true;};pp_containerHeight=imageHeight,pp_containerWidth=imageWidth;};_getDimensions(imageWidth,imageHeight);if((pp_containerWidth>windowWidth)||(pp_containerHeight>windowHeight)){_fitToViewport(pp_containerWidth,pp_containerHeight)};};return{width:Math.floor(imageWidth),height:Math.floor(imageHeight),containerHeight:Math.floor(pp_containerHeight),containerWidth:Math.floor(pp_containerWidth)+(settings.horizontal_padding*2),contentHeight:Math.floor(pp_contentHeight),contentWidth:Math.floor(pp_contentWidth),resized:resized};};function _getDimensions(width,height){width=parseFloat(width);height=parseFloat(height);$pp_details=$pp_pic_holder.find('.pp_details');$pp_details.width(width);detailsHeight=parseFloat($pp_details.css('marginTop'))+parseFloat($pp_details.css('marginBottom'));$pp_details=$pp_details.clone().addClass(settings.theme).width(width).appendTo($('body')).css({'position':'absolute','top':-10000});detailsHeight+=$pp_details.height();detailsHeight=(detailsHeight<=34)?36:detailsHeight;if($.browser.msie&&$.browser.version==7)detailsHeight+=8;$pp_details.remove();$pp_title=$pp_pic_holder.find('.ppt');$pp_title.width(width);titleHeight=parseFloat($pp_title.css('marginTop'))+parseFloat($pp_title.css('marginBottom'));$pp_title=$pp_title.clone().appendTo($('body')).css({'position':'absolute','top':-10000});titleHeight+=$pp_title.height();$pp_title.remove();pp_contentHeight=height+detailsHeight;pp_contentWidth=width;pp_containerHeight=pp_contentHeight+titleHeight+$pp_pic_holder.find('.pp_top').height()+$pp_pic_holder.find('.pp_bottom').height();pp_containerWidth=width;}
function _getFileType(itemSrc){if(itemSrc.match(/youtube\.com\/watch/i)){return'youtube';}else if(itemSrc.match(/vimeo\.com/i)){return'vimeo';}else if(itemSrc.match(/\b.mov\b/i)){return'quicktime';}else if(itemSrc.match(/\b.swf\b/i)){return'flash';}else if(itemSrc.match(/\biframe=true\b/i)){return'iframe';}else if(itemSrc.match(/\bajax=true\b/i)){return'ajax';}else if(itemSrc.match(/\bcustom=true\b/i)){return'custom';}else if(itemSrc.substr(0,1)=='#'){return'inline';}else{return'image';};};function _center_overlay(){if(doresize&&typeof $pp_pic_holder!='undefined'){scroll_pos=_get_scroll();contentHeight=$pp_pic_holder.height(),contentwidth=$pp_pic_holder.width();projectedTop=(windowHeight/2)+scroll_pos['scrollTop']-(contentHeight/2);if(projectedTop<0)projectedTop=0;if(contentHeight>windowHeight)
return;$pp_pic_holder.css({'top':projectedTop,'left':(windowWidth/2)+scroll_pos['scrollLeft']-(contentwidth/2)});};};function _get_scroll(){if(self.pageYOffset){return{scrollTop:self.pageYOffset,scrollLeft:self.pageXOffset};}else if(document.documentElement&&document.documentElement.scrollTop){return{scrollTop:document.documentElement.scrollTop,scrollLeft:document.documentElement.scrollLeft};}else if(document.body){return{scrollTop:document.body.scrollTop,scrollLeft:document.body.scrollLeft};};};function _resize_overlay(){windowHeight=$(window).height(),windowWidth=$(window).width();if(typeof $pp_overlay!="undefined")$pp_overlay.height($(document).height()).width(windowWidth);};function _insert_gallery(){if(isSet&&settings.overlay_gallery&&_getFileType(pp_images[set_position])=="image"&&(settings.ie6_fallback&&!($.browser.msie&&parseInt($.browser.version)==6))){itemWidth=52+5;navWidth=(settings.theme=="facebook"||settings.theme=="pp_default")?50:30;itemsPerPage=Math.floor((pp_dimensions['containerWidth']-100-navWidth)/itemWidth);itemsPerPage=(itemsPerPage<pp_images.length)?itemsPerPage:pp_images.length;totalPage=Math.ceil(pp_images.length/itemsPerPage)-1;if(totalPage==0){navWidth=0;$pp_gallery.find('.pp_arrow_next,.pp_arrow_previous').hide();}else{$pp_gallery.find('.pp_arrow_next,.pp_arrow_previous').show();};galleryWidth=itemsPerPage*itemWidth;fullGalleryWidth=pp_images.length*itemWidth;$pp_gallery.css('margin-left',-((galleryWidth/2)+(navWidth/2))).find('div:first').width(galleryWidth+5).find('ul').width(fullGalleryWidth).find('li.selected').removeClass('selected');goToPage=(Math.floor(set_position/itemsPerPage)<totalPage)?Math.floor(set_position/itemsPerPage):totalPage;$.prettyPhoto.changeGalleryPage(goToPage);$pp_gallery_li.filter(':eq('+set_position+')').addClass('selected');}else{$pp_pic_holder.find('.pp_content').unbind('mouseenter mouseleave');}}
function _build_overlay(caller){$('body').append(settings.markup);$pp_pic_holder=$('.pp_pic_holder'),$ppt=$('.ppt'),$pp_overlay=$('div.pp_overlay');if(isSet&&settings.overlay_gallery){currentGalleryPage=0;toInject="";for(var i=0;i<pp_images.length;i++){if(!pp_images[i].match(/\b(jpg|jpeg|png|gif)\b/gi)){classname='default';img_src='';}else{classname='';img_src=pp_images[i];}
toInject+="<li class='"+classname+"'><a href='#'><img src='"+img_src+"' width='50' alt='' /></a></li>";};toInject=settings.gallery_markup.replace(/{gallery}/g,toInject);$pp_pic_holder.find('#pp_full_res').after(toInject);$pp_gallery=$('.pp_pic_holder .pp_gallery'),$pp_gallery_li=$pp_gallery.find('li');$pp_gallery.find('.pp_arrow_next').click(function(){$.prettyPhoto.changeGalleryPage('next');$.prettyPhoto.stopSlideshow();return false;});$pp_gallery.find('.pp_arrow_previous').click(function(){$.prettyPhoto.changeGalleryPage('previous');$.prettyPhoto.stopSlideshow();return false;});$pp_pic_holder.find('.pp_content').hover(function(){$pp_pic_holder.find('.pp_gallery:not(.disabled)').fadeIn();},function(){$pp_pic_holder.find('.pp_gallery:not(.disabled)').fadeOut();});itemWidth=52+5;$pp_gallery_li.each(function(i){$(this).find('a').click(function(){$.prettyPhoto.changePage(i);$.prettyPhoto.stopSlideshow();return false;});});};if(settings.slideshow){$pp_pic_holder.find('.pp_nav').prepend('<a href="#" class="pp_play">Play</a>')
$pp_pic_holder.find('.pp_nav .pp_play').click(function(){$.prettyPhoto.startSlideshow();return false;});}
$pp_pic_holder.attr('class','pp_pic_holder '+settings.theme);$pp_overlay.css({'opacity':0,'height':$(document).height(),'width':$(window).width()}).bind('click',function(){if(!settings.modal)$.prettyPhoto.close();});$('a.pp_close').bind('click',function(){$.prettyPhoto.close();return false;});$('a.pp_expand').bind('click',function(e){if($(this).hasClass('pp_expand')){$(this).removeClass('pp_expand').addClass('pp_contract');doresize=false;}else{$(this).removeClass('pp_contract').addClass('pp_expand');doresize=true;};_hideContent(function(){$.prettyPhoto.open();});return false;});$pp_pic_holder.find('.pp_previous, .pp_nav .pp_arrow_previous').bind('click',function(){$.prettyPhoto.changePage('previous');$.prettyPhoto.stopSlideshow();return false;});$pp_pic_holder.find('.pp_next, .pp_nav .pp_arrow_next').bind('click',function(){$.prettyPhoto.changePage('next');$.prettyPhoto.stopSlideshow();return false;});_center_overlay();};return this.unbind('click.prettyphoto').bind('click.prettyphoto',$.prettyPhoto.initialize);};function grab_param(name,url){name=name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");var regexS="[\\?&]"+name+"=([^&#]*)";var regex=new RegExp(regexS);var results=regex.exec(url);return(results==null)?"":results[1];}})(jQuery);



