var selectedLocation = 'none';
var highlightedItem = 'none';

$(document).ready(function() {	
	getMediaList();
	$("#descriptionNav").click(function() {selectDescription()});
	$("#creditsNav").click(function() {selectCredits()});
	$('.gallery').hide();
	$('#content').hide();
	$("#leftContentText div div").click(function(){alert("hello")});
	$(".subTitle DIV").hover(function(){							  
		if ($(this).css("color") == "rgb(255, 255, 255)") {
			$(this).css({"color":"yellow"});
		}
	},function(){
		if ($(this).css("color") == "yellow") {
			$(this).css({"color":"rgb(255, 255, 255)"});
		}
	});
});

function highlightItem(id) {
	if (highlightedItem != 'none')
		$('#'+highlightedItem).css({"color" : "white"});
	$('#'+id).css({"color" : "yellow"});
	highlightedItem = id;
}

function matchHeight() {
	var left = $("#leftContentText").height();
	var right = $("#rightContent").height();
	//alert(left +" "+right);
	//alert("leftContent:"+leftContent+"px\r\nleft:"+left+"px");
	if (left > right) {
		$("#innerLeftContent").height(left+102);	
		$("#description").height(left-350);
		$("#credits").height(left-350);
	} else if (right > left) {
		$("#description").css({"height" : "auto"});
		$("#credits").css({"height" : "auto"});
		right = $("#rightContent").height();
		$("#innerLeftContent").height(right-40);
	}
}

function getUrlParameters() {
	var selLocation = getUrlParam('loc');
	if (selLocation != "") {
		selectLocation(selLocation);
	}
	var selType = getUrlParam('type');
	if (selType == "Gallery") {
		var selId = getUrlParam('id');
		getGallery(selId);	
	} else if (selType == 'video') {
		var selId = getUrlParam('id');
		getMedia(selId,'youTube');
	}
	if (selLocation == "" && selType == "") {
		selectLocation('SUMMERPASTURE');
		getMedia('XvfUA0_EnoA','youTube');
		highlightItem(193);
	}
}

function selectDescription() {
	$("#credits").hide();
	$("#description").show();
	$("#creditsNav").css({"color" : "rgb(255, 255, 255)"});
	$("#descriptionNav").css({"color" : "#eaff95"});
	matchHeight();
}

function selectCredits() {
	$("#description").hide();
	$("#credits").show();
	$("#creditsNav").css({"color" : "#eaff95"});
	$("#descriptionNav").css({"color" : "rgb(255, 255, 255)"});
	matchHeight();
}

function getMediaList() {
	$.ajax({
		url: './php/mediaList.php',
		type: 'GET',
		dataType: 'html',
		timeout: 2000,
		error: function(){
			//alert('There was a problem loading the media list. Please try back later.');
			getMediaList();
		},
		success: function(html){
			$("#leftContentText").html(html);
			getGalleryLocations();
		}
	});
		
}

function getGalleryLocations() {
	$.ajax({
		url: './php/getGalleryLocations.php',
		type: 'GET',
		dataType: 'XML',
		timeout: 2000,
		error: function() {
			//alert('The server is not responding. Please try again in a few minutes.')
		},
		success: function(xml) {
			var data;
			if (jQuery.browser.msie) {
				data = new ActiveXObject('Microsoft.XMLDOM');
				data.async = false;
				data.loadXML(xml);
			} else {
				data = xml;
			}
			$(data).find('location').each(function() {
				var location = $(this).find("name").text();
				var id = $(this).find("id").text();
				var locationCleaned = location.replace(/ /g,"").replace("'","");
				//alert("location: " + location + "\r\ncleaned: " + locationCleaned);
				if ($("#"+locationCleaned+"List").length > 0) {
					$("#"+locationCleaned+"List").prepend("<div class=\"mediaItem\" id=\"" + locationCleaned + "Gallery\" onclick=\"highlightItem('"+locationCleaned+"Gallery');getGallery('"+id+"');\">Photo Gallery</div>");
				} else {
					$("#leftContentText").append("<div id=\""+locationCleaned+"\" class=\"mediaTitle\" onclick=\"highlightItem('"+locationCleaned+"Gallery');selectLocation('"+locationCleaned+"');\">"+location+"</div><div id=\""+locationCleaned+"List\" style=\"display: none;\"><div id=\"" + locationCleaned + "Gallery\" class=\"mediaItem\" onclick=\"getGallery("+id+");\">Photo Gallery</div></div>");
				}
			});
			getUrlParameters();
		}
	});
}

function selectLocation(location) {
	selectLocationList(location+"List");

	$("#contentTitle").html($("#"+location).html());
	$('#main_image').html("<img src=\"./media/mediaDefault"+location+".jpg\" />");
	$(".gallery").fadeOut(300,function(){
		selectDescription();
		$('#content').fadeIn(function(){matchHeight();});
	});
	if (location == "SUMMERPASTURE") {
		getContent("documentaryContent","description");
		getContent("documentaryCredits","credits");
	} else if (location == "YAKGALLERY") {
		getContent("yakGalleryContent","description");
		getContent("yakGalleryCredits","credits");
		highlightItem('YAKGALLERYGallery');
	} else {
		getContent("pv"+location+"Content","description");
		getContent("pv"+location+"Credits","credits");
	}

}

function getContent(name,container) {
	$.ajax({
		url: './php/getContent.php',
		data: {'name' : name},
		type: 'GET',
		dataType: 'html',
		timeout: 2000,
		error: function() {
			//alert('The server is not responding. Please try again in a few minutes.')
		},
		success: function(html) {
			html = html.replace(new RegExp("^[\\s]+", "g"), "");
			$("#"+container).html(html);
			matchHeight();
		}
	});
}

function selectLocationList(location) {
	if (selectedLocation != 'none') {
		$("#" + selectedLocation).slideUp(200);
	} 
	
	if (selectedLocation != location) {
		$("#" + location).slideDown(300,function(){matchHeight();});
		selectedLocation = location;
	} else {
		selectedLocation = 'none';
	}
}

function getUrlParam(name) {
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );
	if(results == null)
		return "";
	else
		return results[1];
}

function getGallery(id) {
	$.ajax({
		url: 'php/getGallery.php',
		data: {'id' : id},
		type: 'GET',
		dataType: 'html',
		timeout: 2000,
		error: function() {
			//alert('The server is not responding. Please try again in a few minutes.')
		},
		success: function(html) {
			//alert(html);
			$(".gallery_demo").html(html);
			$('#movie').fadeOut();
			$('#content').fadeOut(300,function(){$('#main_image').html("").fadeIn();processGallery();$('.gallery').fadeIn();matchHeight();});
		}
	});
}

function getMedia(filename,type) {
	$('#main_image').html("").fadeOut();
	$('.gallery').fadeOut();
	$('#movie').html("").fadeIn();
	$('#content').fadeIn();
	if (type == 'youTube') {
		$('#movie').html('<object width="560" height="345"><param name="movie" value="http://www.youtube.com/v/' + filename + '&hl=en&fs=1&color1=0x3a3a3a&color2=0x999999&ap=%2526fmt%3D18"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/' + filename + '&hl=en&fs=1&color1=0x3a3a3a&color2=0x999999&ap=%2526fmt%3D18" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="560" height="345"></embed></object>');
	}
}

function processGallery() {
	$('.gallery_demo_unstyled').addClass('gallery_demo'); // adds new class name to maintain degradability
	$('ul.gallery_demo LI:first').addClass("active");
	$('ul.gallery_demo').galleria({
		history   : true, // activates the history object for bookmarking, back-button etc.
		clickNext : true, // helper for making the image clickable
		insert    : '#main_image', // the containing selector for our main image
		onImage   : function(image,caption,thumb) { // let's add some image effects for demonstration purposes
			
			// fade in the image & caption
			image.css('display','none').fadeIn(1000);
			caption.css('display','none').fadeIn(1000);
			
			// fetch the thumbnail container
			var _li = thumb.parents('li');
			
			// fade out inactive thumbnail
			_li.siblings().children('img.selected').fadeTo(500,0.3);
			
			// fade in active thumbnail
			thumb.fadeTo('fast',1).addClass('selected');
			
			// add a title for the clickable image
			image.attr('title','Next image >>');
		},
		onThumb : function(thumb) { // thumbnail effects goes here
			
			// fetch the thumbnail container
			var _li = thumb.parents('li');
			
			// if thumbnail is active, fade all the way.
			var _fadeTo = _li.is('.active') ? '1' : '0.3';
			
			// fade in the thumbnail when finnished loading
			thumb.css({display:'none',opacity:_fadeTo}).fadeIn(1500);
			
			// hover effects
			thumb.hover(
				function() { thumb.fadeTo('fast',1); },
				function() { _li.not('.active').children('img').fadeTo('fast',0.3); } // don't fade out if the parent is active
			)
		}
	});
}

