var languageDB = [];
var contentDB = null; // Loaded from XML
var currentMenuCategory = -1;
var THUMB_HEIGHT = 50;
var currentCategory = -1;
var currentArticleIndex = -1;

/**
 * Init Application 
 */
jQuery( function($) {
	
	$("#viewerContainer").hide();
	$("#viewerContainer").find("#background").click( 
		function(){
			$("#viewerContainer").hide();
		}
	)
	$("#viewerContainer").find("#close").click( 
		function(){
			$("#viewerContainer").hide();
		}
	)
	$("#pageNext").click( 
		function(){
			navigate(1);
		}
	)
	$("#pagePrev").click( 
		function(){
			navigate(-1);
		}
	)

	
	// $.get("_assets/language.txt",{},initLanguageDB);
	/*	
	$(window).bind('resize', function() {
		scaleBackground();
	});	
	
	$("#bgContainer").animate({opacity: 0}, 10);
	
	$("#bgContainer img").ready( function() {
		scaleBackground();
		$("#bgContainer").animate({opacity: 1}, 1000);
	});
	*/
	
	// $("#content").hide();
	// Testing:
	// $("#title").html("Test title");
	// $("#description").html("Test description<br/>Test description<br/>Test description<br/>Test description<br/>Test description<br/>Test description<br/>Test description<br/>Test description<br/>Test description<br/>");
	
	/*
	$("#introContainer").animate({opacity: 0}, 10);
	$("#introContainer").animate({opacity: 1}, 1000);

	$(".intro", "#introContainer").click( 
		function() {
			$("#introContainer").animate({opacity: 0}, 1000, introComplete); 
		}
	);
	*/
	introComplete();
	
}); // JQUERY

function hideAll(){
	$("#viewerContainer").hide();
	$("#gallery").hide();
}

function scaleBackground(){

	var imgWidth = 1200;
	var imgHeight = 1150;
	var ratio = imgWidth / imgHeight;
	
	var w = $(window).width();
	var h = $(window).height();
	var windowRatio = w/h; 
	if(windowRatio > ratio){
		$("#bgContainer img").width(w);
		$("#bgContainer img").height(w*ratio);
	}else{
		$("#bgContainer img").width(h*ratio);
		$("#bgContainer img").height(h);
	}
	
}


/**
 * Called when animating the intro is complete.
 * @return
 */
function introComplete(){
	var currentTime = new Date();
	var timeStamp = currentTime.getTime();
	$.get("_assets/published_categories_oldstyle_embed_text.xml?"+timeStamp,{},initDatabase,"xml");
}

/**
 * Init Language Database 
 * @param inputXLM
 * @param strStatus
 * @return
 */
function initLanguageDB(inputXML, strStatus){
	// alert("Init Language")
}

/**
 * Init Database
 * @param inputXLM
 * @param strStatus
 * @return
 */
function initDatabase( inputXML, strStatus ){

	$("#content").show();
	$("#content").animate({opacity: 1}, 1000);
	
	// convert input data to jQuery XML object model
	contentDB = $( inputXML );
	// initMenu();
	// alert("Init Database: " + contentDB);
	
	// var baseCategory = contentDB.find("CATEGORIES").attr("");
	// var category = contentDB.find( "CATEGORY[ id = '" + id + "' ]");
	contentDB.find("CATEGORY").each( 
		function(){
			var category = $(this);
			var mode = category.children("MODE").clone().text();
			// PORTFOLIO
			if(mode == "1"){
				loadGallery( category.attr('id') );
			}
			// CONTACT:
			if(mode == "2"){
				loadContactInfo( category.attr('id') );
			}
		}
	)
}

function loadContactInfo( id ){
	var category = contentDB.find( "CATEGORY[ id = '" + id + "' ]");
	var headerInfo = $("#contact");
	var description = category.children("DESC").clone().text();
	headerInfo.html( description );
	var footerInfo = $("#copyright");
	var xtra = category.children("XTRA").clone().text();
	footerInfo.html( xtra );
}

function loadGallery( id ){

	// $("#categoryImage").animate({opacity: 0}, 1000);
	var category = contentDB.find( "CATEGORY[ id = '" + id + "' ]");

	var targetDiv = $("#gallery");
	targetDiv.empty();
	targetDiv.show();
	
	var infoBox = $("#infoBox");
	var infoTitle = $("#infoBox").find("#title");
	var infoDescription = $("#infoBox").find("#description");
	
	// alert("Load gallery: " + [id, category.children().length]);
	
	// Show thumbs:
	category.children().each(
		function(inSelectionIndex){
			var child = $( this );
			if(child[0].nodeName == "CATEGORY"){
				var galleryName = child.children("NAME").clone().text();
				var galleryDesc = child.children("DESC").clone().text(); // .toUpperCase();
				var galleryMode = child.children("MODE").clone().text();
				var galleryXtra = child.children("XTRA").clone().text();
				var categoryId = child.attr("id");
				var asset = child.children("ASSET");
				var assetName = asset.text();
				var assetUrl = "_assets/images/th_"+ assetName;
				if(assetName == ""){
					// continue;
					assetUrl = "images/defaultThumb2.gif";
				}
				// <a class='image' href='#'>javascript:showGalleryImage(" + categoryId + ");</a>
				var thumb = $("<div class='thumb'><img src='" + assetUrl + "' border='0' width='270' height='190' /></div>");
				thumb.hover( 
					function(){
						var offset = thumb.offset(); // var position = thumb.position();
						
						infoBox.stop();
						
						// infoBox.css('top', 0).css('left', -300);
						infoBox.hide().animate({opacity: 0}, 100, function(){
							infoBox.show().css('top', offset.top).css('left', offset.left);
							infoBox.animate({opacity: 1}, 500);
							}
						);
						// infoBox.css('top', offset.top).css('left', offset.left);
						infoTitle.html(galleryName);
						infoDescription.html(galleryDesc);
						
						
						infoBox.unbind();
						infoBox.click( function(){ 
							if(galleryMode == "4"){
								// alert("Go shopping!");
								// document.URL = galleryXtra;
								window.location = galleryXtra;
							}else{
								showGalleryImage( categoryId );
								infoBox.css('top', 0).css('left', -300);
							}
						} );
						
						// hover seems to work here better than mouseout!!
						infoBox.hover( function(){}, function(){ 
							infoBox.css('top', 0).css('left', -300);
							infoBox.animate({opacity: 0}, 1); // .css('top', 0).css('left', -300);
						} );
						
						
					}, 
					function(){
						// infoBox.css('top', 0).css('left', -300);
					} 					
				);
				
				targetDiv.append(thumb);
				
			}
		});	
	
}

function navigate( direction ){
	showGalleryImage(currentCategory, currentArticleIndex + direction);
}

function showGalleryImage(categoryId, articleIndex){
	
	articleIndex = (articleIndex==null) ? 0 : articleIndex;
	
	// var mode = currentMode;
	// hideAll();
	var category = contentDB.find( "CATEGORY[ id = '" + categoryId + "' ]");
	var articles = category.children("ARTICLES");
	
	if(articleIndex >= articles.children().length) articleIndex = 0;
	if(articleIndex < 0) articleIndex = articles.children().length - 1;
	
	currentCategory = categoryId;
	currentArticleIndex = articleIndex;
	
	// alert( articles.children().length );
	var article = $(articles.children()[articleIndex]);
	// DATA:
	var mode = category.children("MODE").clone().text();
	var categoryAsset = category.children("ASSET").clone().text();
	// alert(categoryAsset);
	var title = article.children("NAME").clone().text();
	var asset = article.children("ASSET").clone().text();
	var articleName = article.children("NAME").clone().text();
	var articleXtra = article.children("XTRA").clone().text();
	var articleDesc = article.children("DESC").clone().text(); // css  .toUpperCase();
	var pageNum = (articleIndex+1);
	var pageLength = articles.children().length;

	if(pageLength == 0){
		articleName = "No articles!";
		articleDesc = "There are no articles in the current category yet.";
	}

	
	var targetDiv = $("#viewerContainer"); 
	targetDiv.show();
	
	$("#imageCategory").hide();
	$("#textCategory").hide();
	
	var categoryType = "#imageCategory";
	if(mode == "3") {
		categoryType = "#textCategory";
		var mainImageDiv = $(categoryType).find("#mainImage");
		mainImageDiv.empty();
		loadImageInDiv( mainImageDiv, '_assets/images/th_'+ categoryAsset );
	}
	
	$(categoryType).show();
	
	// Target's depend on category mode!!!
	var imageDiv = $(categoryType).find("#image");
	var infoTitle = $(categoryType).find("#title");
	var infoDescription = $(categoryType).find("#description");
	

	imageDiv.empty();
	loadImageInDiv( imageDiv, '_assets/images/'+ asset );
	imageDiv.unbind();
	imageDiv.click( function(){ showGalleryImage(categoryId, (articleIndex+1) ); } );

	infoTitle.html("<div class='left'>" + articleName + "</div><div class='xtra'>" + articleXtra + "</div>");
	infoDescription.html(articleDesc);
	
	var pageInfo = $("#viewerContainer").find("#pageInfo");
	var numPad = (pageNum < 10) ? "0" : "";
	var lenPad = (pageLength < 10) ? "0" : "";
	pageInfo.html( numPad + pageNum + "/" + lenPad + pageLength);
	
	
	
	
}


function loadImageInDiv( div, fileName ){

	div.addClass("loading");
	/*
	 */
	var img=new Image();
	  // wrap our new image in jQuery, then:
	  $(img)
	    // once the image has loaded, execute this code
	    .load(function  ()  {
	      // set the image hidden by default
	      $(this).hide();
	      // with the holding div #loader, apply:
	      div
	        // remove the loading class (so no background spinner),
	        .removeClass('loading')
	        // then insert our image
	        .append(this);
	      // fade our image in to create a nice effect
	      $(this).fadeIn(); // slideDown(); // 
	    })
	    // if there was an error loading the image, react accordingly
	    .error(function  ()  {
	      // notify the user that the image could not be loaded
	    })
	    // *finally*, set the src attribute of the new image to our image
	    .attr('src',  fileName); 	
	
	
}




//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////










/**
 * Init Menu
 * @return
 */
function initMenu(  ){
	
	var items = contentDB.find("CATEGORIES");
	var targetDiv = $("#menu");
	targetDiv.empty();
	
	var menuHTML = $( "<UL class='pageList'></UL>" );
	var menuContent = "";
		
	items.children().each(
			function(inSelectionIndex){
				var item = $(this);
				var title = item.children("NAME").text().toUpperCase();
				var mode = item.children("MODE").text()
				var id = item.attr("id");
				var activeHTML = "";
				if(id == currentMenuCategory){
					// activeHTML = "<div class='active'>&nbsp;*</div>"; // or use float: left;
					activeHTML = "<div class='active'>&nbsp;<img src='images/pallo.gif' width='10' height='9' border='0' /></div>"; // or use float: left;
				}
				// menuContent += mode;
				var menuLinkMode = "";
				if(mode == "1"){
					menuLinkMode = "Normal";
				}else if(mode == "2"){
					menuLinkMode = "Normal";
				}else if(mode == "3"){
					menuLinkMode = "SubArticles";
				}else if(mode == "4"){
					menuLinkMode = "Gallery";
				}else{
					menuLinkMode = "Unknown";
				}
				var menuItemHTML = "<LI id='menuItem" + menuLinkMode +  "-" + id + "' class='clearElement pageItem left'><div class='clickable'><a href='#' class='menu'>"+title+"</a></div>"+activeHTML+"</LI>";
				menuContent += menuItemHTML;
				
			}
	)
	
	menuHTML.html(menuContent);
	targetDiv.append( menuHTML );
	
	$('.clickable', '#menu').click(  function(event) {
		var category_name = jQuery(this).parent().get(0).id;
		var mode = category_name.split("-")[0];
		var category_id   = category_name.split("-")[1];
		// alert(mode);
		if(mode == "menuItemGallery"){
			loadGallery(category_id);
		}else if(mode == "menuItemSubArticles"){
			hideAll();
			loadCategory(category_id);
			loadSubArticlesInCategory(category_id);
		}else{
			loadCategory(category_id);
		}
	}); // Stop 'Click' Menu
	
}



/**
 * Load a simple descriptions (image, description) from a selected category from the Menu.
 * @param id
 * @return
 */
function loadCategory( id ){
	
	hideAll();
	
	$("#categoryImage").animate({opacity: 0}, 10);
	
	currentMenuCategory = id;
	// initMenu();
	
	// hideAll();
	$("#simpleContainer").show();
	var category = contentDB.find( "CATEGORY[ id = '" + id + "' ]");
	// <image>
	var imageDiv = $("#categoryImage");
	imageDiv.empty();
	var asset = category.children("ASSET").clone().text();
	// alert(asset.text());
	imageDiv.html("<img src='_assets/images/"+ asset +"' width='598' height='496' />" );
	
	// <description>
	var descriptionDiv = $("#description");
	descriptionDiv.empty();
	var description = category.children("DESC");
	descriptionDiv.html( description.clone().text() ); // duplicate!! 

	// <title>
	var titleDiv = $("#title");
	titleDiv.empty();
	var title = category.children("NAME");
	titleDiv.html( title.clone().text() ); // duplicate!! 

	// wait?
	$("#categoryImage").animate({opacity: 1}, 1000);
	
}


function loadSubArticlesInCategory( id, articleIndex ){
	
	articleIndex = (articleIndex==null) ? 0 : articleIndex; 

	var category = contentDB.find( "CATEGORY[ id = '" + id + "' ]");

	var titleDiv = $("#title");
	var descriptionDiv = $("#description");
	titleDiv.empty();
	descriptionDiv.empty();
	
	var articleLinks = "";
	
	// Now get articles:
	var articles = category.children("ARTICLES");
	var counter = 0;
	articles.children().each(
			function(inSelectionIndex){
				var article = $(this);
				
				var title = article.children("NAME");
				var description = article.children("DESC");
				articleLinks += "<a href='javascript:loadSubArticlesInCategory(" + id + "," + counter + ");' >" + title.clone().text() + "</a> | ";

				if(counter == articleIndex){

					var xtra = article.children("XTRA").clone().text();
					// contains images?
					if(xtra.indexOf(".") > -1){
						descriptionDiv.append( "<img src='images/" + xtra + "' style='float: right;'/>" ); // duplicate!!
					}

					descriptionDiv.append( title.clone().text() + "<br/><br/>" ); // duplicate!!
					descriptionDiv.append( description.clone().text() ); // duplicate!!
					
				}
				counter++;
			}
	);
	
	descriptionDiv.append( "<br/><br/>" + articleLinks ); // duplicate!!
}


