function showTab(tab,tab_content){
	$(".tab").removeClass('selected');
	$(".tab-content").hide();
	
	$("#" + tab).addClass('selected');
	$("#" + tab_content).show();
}

/*
function showDiv(tab,tab_content){
	//alert("inside");
	document.getElementById('tab1_content').style.display = 'none';
	document.getElementById('tab2_content').style.display = 'none';
	document.getElementById('tab3_content').style.display = 'none';
	document.getElementById('tab4_content').style.display = 'none';
	document.getElementById('tab5_content').style.display = 'none';
	document.getElementById('tab6_content').style.display = 'none';
	$('#tab1').removeClass('selected');
	$('#tab2').removeClass('selected');
	$('#tab3').removeClass('selected');
	$('#tab4').removeClass('selected');
	$('#tab5').removeClass('selected');
	$('#tab6').removeClass('selected');
	
	document.getElementById(tab_content).style.display = 'block';
	$('#'+tab).addClass('selected');
} 
*/

function submitForm(element){ 
	document.getElementById(element).click();
} 


function portfolioFilters(key,value){
    key = escape(key); value = escape(value);
    var kvp = document.location.search.substr(1).split('&');
    var i=kvp.length; var x; while(i--)  {
        x = kvp[i].split('=');

        if (x[0]==key){
                x[1] = value;
                kvp[i] = x.join('=');
                break;
        }
    }

    if(i<0) {kvp[kvp.length] = [key,value].join('=');}

    //this will reload the page, it's likely better to store this until finished
    document.location.search = kvp.join('&'); 
}

//Filters 
function setFilters(key,value){
    key = escape(key); value = escape(value);
    var kvp = document.location.search.substr(1).split('&');
    var i=kvp.length; var x; while(i--)  {
        x = kvp[i].split('=');

        if (x[0]==key){
                x[1] = value;
                kvp[i] = x.join('=');
                break;
        }
    }

    if(i<0) {kvp[kvp.length] = [key,value].join('=');}
    document.location.search = kvp.join('&'); 
}


function submitForm(element){ 
	document.getElementById(element).click();
} 


function regclick() {
	document.getElementById("addusersub").click();
}

function editclick() {
	document.getElementById("updateuser").click();
}


function addTag(slug, name) {
    var temp = $("#tags").val(); 
	temp += (slug + ","); 
	$("#tags").val(temp);
	
	$("#show_tags").append('<span class="'+ slug +' fl fs121 mr5 top">' + name + '&nbsp;<img class="no-border cursor" onclick="deleteTag(&quot;' + slug + '&quot;,&quot;' + name + '&quot;)" src="/wp-content/themes/pandora/img/delete.png">&nbsp;</span>');
}


function deleteTag(slug, name) {
	var Tags = $("#tags").val();
	Tags = Tags.replace(slug+",", "");
	$("#tags").val(Tags);

	var i = 1;
	$('.'+slug+":visible").each(function(){
		if(i == 1){ $(this).hide(); i++;}	
	});
	
}


function show_city_n(region, n){

	for(var i = 100; i < 2600; i++){
		if ($("#user_city" + n + " option[id='"+i+"']").length){$("#user_city" + n + " option[id='"+i+"']").appendTo($("#user_city_hidden"+n));}
	}
	
	for(var i = String(region) + "01"; i < String(region) + "99"; i++){
		if ($("#user_city_hidden" + n + " option[id='"+i+"']").length){$("#user_city_hidden" + n + " option[id='"+i+"']").appendTo($("#user_city"+n));}
	}
	if(region != ""){$("#user_city" + n + " option[id=blank_city]").text("-n/a-");}
}


function show_city(region){
	for(var i = 100; i < 2600; i++){
		if ($("#user_city option[id='"+i+"']").length){$("#user_city option[id='"+i+"']").appendTo($("#user_city_hidden"));}
	}
	
	for(var i = String(region) + "01"; i < String(region) + "99"; i++){
		if ($("#user_city_hidden option[id='"+i+"']").length){$("#user_city_hidden option[id='"+i+"']").appendTo($("#user_city"));}
	}
	
	if(region != ""){$("#user_city option[id=blank_city]").text("-n/a-");}
}



$(document).ready(function() { 
	$('#show-hide-upload-images').click(function() { // toggles the slickbox on clicking the noted link  
		$('#add-more-images-div').toggle(400);
		return false;
	});
	
	$('#show-hide-auth').click(function() { // Show hide auth div
		$('#auth-div').slideToggle("slow");
		return false;
  	});
	
	$.each( ['1','2','3','4','5','6','7','8','9','10','11','12'], function(i){ // Show hide festivals
		$('#show-hide-fest' + i).click(function() {
			$('#fest-div-month' + i).slideToggle("slow");
			return false;
 	 	});
  	});
	
	$(".checkbox-row").change(function() {
    	if($(this).is(':checked')) $(this).parent().addClass('selected'); 
    	else $(this).parent().removeClass('selected');
	});
	
	
	// find closeable boxes and add a "close" action
	$('.closeable').each(function(index){
		$(this).prepend( 
			$('<a></a>')
			.attr({href: '#', title: 'Close'})
			.addClass('close')
			.text('x')
			.click(function() {
				$(this).parent().fadeOut();
				return false;
			})
		);
	});
	
	
	$(".show_login_menu").toggle(function() {
 		$("#user_top_menu").slideDown('fast').css('z-index', 1000); 
	}, function() {
  		$("#user_top_menu").fadeOut('fast');
	});


	
	$(".login_menu").bind('mouseleave',function(){
		$("#user_top_menu").fadeOut('fast');
	});
	
});


var began_loading = (new Date()).getTime();

function done_loading() {
	document.getElementById("loadpage").innerHTML += (((new Date()).getTime() - began_loading) / 1000);
}


function navigation() {
	var $menu = $('.top_menu');		
	$menu.children('li').each(function(){
		var $this = $(this);

		var submenu = $this.find('.sub-menu');
		if (submenu.length) {
			submenu.parents('ul').css('z-index', 2000); // z-index hack for IE7
			$this.bind('click',function(){
				submenu.slideDown('fast').css('z-index', 1000); // z-index hack for IE7
			}).bind('mouseleave',function(){
				submenu.fadeOut('fast');
			});
		}		
	});
}

/* Other JS *******************************************************************************************/



var $j = jQuery.noConflict();

$j(function() {
	// comment next lines to disable features
	lightBox(); // initialize & configure lightbox script
	navigation(); // dynamic light selection in the menu (windows7-like)
	startTimers(); // start slidefader & newsticker timers
	if ($j("form#contact").length > 0) contactForm(); // initialize javascript validators for the contact form
	if ($j("#folio").length > 0) folio(500, 0.6); // portfolio sleek image shade (timer, opacity)
	if ($j("div.item p.tags a", "#folio").length > 0) folioFilter(); // portfolio item filter
});



// functions
function getMeta($name) {
	return $j("meta[name=" + $name + "]").attr('content');
}

function contactForm() {
	$j(".input", "form#contact").blur(function() { validateInput($j(this)); }); // validate when unfocus
	$j("#submit", "form#contact").click(function() { // validate on submit
	$j(".input", "form#contact").each(function() { validateInput($j(this)); })
		if (!isFormValid())
			return false;
	});
}


function isFormValid() {
	return $j(".input.incorrect", "form#contact").length > 0 ? false : true;
}

function validateInput(obj) {
	var id = obj.attr("id");
	var correct = false;
	if (id == "email") { // email validator
		if (obj.val().match(/^[a-zA-Z0-9_\.\-]+\@([a-zA-Z0-9\-]+\.)+[a-zA-Z0-9]{2,4}$/))
			correct = true;
	}

	else if (id == "message") { // message validator
		if (obj.val().replace(/(^\s+)|(\s+$)/g, "") != "")
			correct = true;
	}

	obj.removeClass("correct incorrect"); // clearing
	if (correct) {obj.addClass("correct");}
	else {obj.addClass("incorrect");	}
}

//
var faderId, newstickerId;
function startTimers() {
	if ($j("#slides img").length > 1) {faderId = setInterval("slides()", getMeta("pandora.1"));}
	if ($j("#newsline").length > 0) {newstickerId = setInterval("newsline()", getMeta("pandora.2"));}
}

function stopTimers() {
	if (faderId) clearInterval(faderId); // clear slide fader timer
	if (newstickerId) clearInterval(newstickerId); // clear newsticker timer
}




//
function lightBox() {
	$j("a[rel^='lightbox']").prettyPhoto({
		animationSpeed: 'fast', /* fast/slow/normal */
		padding: 40, /* padding for each side of the picture */
		opacity: 0.5, /* Value betwee 0 and 1 */
		showTitle: true, /* true/false */
		allowresize: true, /* true/false */
		counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
		theme: 'dark_rounded', /* light_rounded / dark_rounded / light_square / dark_square */
		hideflash: false, /* Hides all the flash object on a page, set to TRUE if flash appears over prettyPhoto */
		modal: false, /* If set to true, only the close button will close the window */
		changepicturecallback: function() { stopTimers(); },
		callback: function() { startTimers(); }
	});
}

//
function folio(time, opacity) {
	$j("img", "#folio")
		.css("opacity", 1)
		.hover(
			function() {$j(this).stop().animate({ opacity: opacity }, time);},
			function() {$j(this).stop().animate({ opacity: 1 }, time);}
		);
}

function folioFilter() {
	var tags = getAllTags();
	var ph = $j(".placeholder", "#filter");
	$j(tags).each(function(i, tag) {ph.append(', <a href="#'+tag+'">' + tag + '</a>');});

	$j(".placeholder a", "#filter").click(function() {
		$j(".placeholder a.active", "#filter").removeClass("active");
		$j(this).addClass("active");
		folioClick($j(this));
		return false;
	});

	$j("#filter", "#folio").show();

	// select by the #hash in the url
	var hash = trim(window.location.hash.substring(1));
	if (hash.length > 0) { $j(".placeholder a:contains('" + hash + "'):first", "#filter").click();
	}
}

{ // folioFilter functions:
	function folioClick(obj) {
		var tag = obj.text();
		var rel = obj.attr("rel");
		folioHideAll();
		
		if (rel == "Start") folioShow();
		else folioShow(tag);



		folioClearer();

	}



	function folioClearer() {

		var visibleItems = $j("div.item:visible", "#folio");

		var lastIndex = visibleItems.length - 1;

		visibleItems.each(function(i, item) {

			if (i % 3 == 2 && i != lastIndex) $j('<div class="clear"> </div>').insertAfter(item);

		});

	}



	function folioShow(tag) {

		if (tag)

			$j("div.item:has(p.tags a:contains('" + tag + "'))", "#folio").show();

		else

			$j("div.item", "#folio").show();

	}



	function folioHideAll() {

		$j("div.item", "#folio").hide();

		$j("#folio > div.clear:not(:last)").remove();

	}



	function getAllTags() {

		var tags = [];

		$j("div.item p.tags a", "#folio").each(function() { tags.push(trim($j(this).text())); });

		return tags.unique().sort();

	}



}



//



function slides() {



	if (ie6 || jQuery.browser.msie) {

		return; // ie6 fails to animate overall opacity of the transparent PNGs

	}



	var $active = $j("#slides img.active");



	if ($active.length == 0) {

		$active = $j("#slides img:last");

	}



	var $next = $active.next().length ?

			$active.next() :

			$j("#slides img:first");



	$active.

		addClass("pre-active");





	$next.

		css({ opacity: 0 }).

		addClass("active").

		animate({ opacity: 1 }, 1000, function() {

			$active.animate({ opacity: 0 }, 1000, function() { $active.removeClass("active pre-active"); });

		});



}



//



function newsline() {

	var $ph = $j("#newsline a.ph");



	if ($ph.length == 0) { // prepare basement

		var $first = $j("#newsline a:first");

		$j("#newsline p").append("<br />").append($first.clone());

		$ph = $first.addClass("ph");

	}



	var $active = $j("#newsline a.active");



	if ($active.length == 0) {

		$active = $j("#newsline a:last");

	}



	var $next = $active.next().next().length ?

			$active.next().next() :

			$j("#newsline a:not(.ph):first");



	$next.addClass("active");

	$active.removeClass("active");



	if (ie6) { // bha! another ie6 opacity fail

		$ph.html($next.html());

		$ph.attr("href", $next.attr("href"));

	}

	else {

		$ph.animate({ opacity: 0 }, 500, function() { // hiding

			$ph.html($next.html());

			$ph.attr("href", $next.attr("href"));

			$ph.animate({ opacity: 1 }, 300); // revealing

		});

	}

}



//



var ie6 = jQuery.browser.msie && parseInt(jQuery.browser.version) < 7;



// JS helpers:



{

	function trim(str) {

		return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');

	}



	// Array.indexOf( value, begin, strict )

	Array.prototype.indexOf = function(v, b, s) {

		for (var i = +b || 0, l = this.length; i < l; i++) {

			if (this[i] === v || s && this[i] == v) { return i; }

		}

		return -1;

	};

	// Array.unique( strict )

	Array.prototype.unique = function(b) {

		var a = [], i, l = this.length;

		for (i = 0; i < l; i++) {

			if (a.indexOf(this[i], 0, b) < 0) { a.push(this[i]); }

		}

		return a;

	};

	// Array1.intersect( Array2 )

	Array.prototype.intersect = function(b) {

		var as, al, a = [];

		if (b.length < this.length) { as = b; al = this }

		else { as = this; al = b }

		$j.each(as, function(i, user) {

			if (al.indexOf(user) >= 0)

				a.push(user);

		});

		return a;

	}

}
