/*! 
 *	studio tandem website UI
 *	copyright (c) 2009 Boris Jerenec, http://studiotandem.si
 *	
 *	powered by jQuery 1.3.2 
 */

doLog = false;
jsonCache = new Object(); // cache data for views

currentBlock = 0;

// scrolling
oldScrollPoition = 0;
currentScrollPosition = 0;
scrollDirection = 0;
scrollElement = 'html';
scrollBound = false;
autoScrollDelay = 500;
scrollTimeout = null; // ?? setTimeout ID

function STLog(obj) {
	if (window.console && doLog) window.console.log(STLog.caller.name, obj);
}

function startEngine(bindScroll) {
	STLog('START');
		
	// globals
	if ($.browser.safari) scrollElement = 'body';

	root = document.getElementsByTagName('base')[0].href;
//	currentViewId = location.href.substr(root.length).replace(/\//g,"-");
//	STLog('currentViewId = ' + currentViewId);
	// todo - cache view?

//  IE dies here
//	intro = $("#intro");
//	slider = $("#slider");
	
	// google analytics tracking
	$('a').track({skip_internal:false});
	
	// events
	$("#mainmenu a").click(mainMenuClick);
	$("#tagmenu a").click(tagMenuClick);		
		
	$("#next").click(navigationNextClick);
	$("#prev").click(navigationPrevClick);

	// add _blank target to links with rel="external"
	$("a[rel='external']").attr("target","_blank");
	
	$("#twitter").hover(
		function() {
			$("#twitter h3 span").fadeIn("fast");
		},
		function() {
			$("#twitter h3 span").fadeOut("fast");
		});
		
		
	// bind scroll if set to portfolio
	if (bindScroll) {
		scrollBound = true;
		bindWindowScroll();		
	}
	
	resetNavigationMenu();
	
	$(window).load( function () { 
	    $(window).scrollTop(0);
	 } );
	 
	$(".morelist .moreinfo").css({display:"none"});
	$(".morelist a.moretrigger").live('click', moreListClick);

}


function resetNavigationMenu()
{
		
	if ($("#mainmenu li.selected a[rel='portfolio']").length > 0) {

		$('#navigation').fadeIn('fast');
	
	    var totalBlocks = $(".block").length;
	    STLog("totalBlocks " + totalBlocks);
	    
		if (totalBlocks > 1) {
		  	  var height = $(window).height() - $("#block"+currentBlock).outerHeight(true);
		      //STLog("window height: "+$(window).height()+" calculated heigth: " + height);
		      if (height > 0) {       	  
		  	      $("#slider").css({paddingBottom:height+"px"});
			}
		}
  	
	  	if (totalBlocks == 1) {
			$("#next").fadeTo("fast", 0.1);
			$("#prev").fadeTo("fast", 0.1);
	  	}
	    else if (currentBlock <= 0) {
			$("#prev").fadeTo("fast", 0.1);
			$("#next").fadeTo("fast", 1.0);
	    }
	    else if ((currentBlock+1) >= totalBlocks) {
			$("#next").fadeTo("fast", 0.1);
			$("#prev").fadeTo("fast", 1.0);
	    }
	    else {
	    	$("#next").fadeTo("fast", 1.0);
	    	$("#prev").fadeTo("fast", 1.0);
	    }  	 
        
    
	    if (totalBlocks > 0 ) {   
			$("#numbering").html((currentBlock+1) + " / " + totalBlocks );
		}
		else {
			$("#numbering").html( "0 / 0" );
		}
			
	}
	else {
	 	$('#navigation').fadeOut(0);
	}

	$(".morelist .moreinfo").css({display:"none"});
	


}


// bindings
function bindWindowScroll() {
	scrollBound = true;


	$(window).scroll(windowScroll);	
}

function unbindWindowScroll() {
	scrollBound = false;
	$(window).unbind('scroll');
	
	if(typeof scrollTimeout == "number") {
	  clearTimeout(scrollTimeout);
	} 
}


function autoScroll() {
	STLog('and now ... autoScroll!!!');
	var targetY = $("#block"+currentBlock).offset().top;	
	unbindWindowScroll();
	$(scrollElement).stop().animate({scrollTop:targetY}, 300); // html - firefox, opera, body - safari
	
	$(".block").removeClass("clue");

	setTimeout(bindWindowScroll, 400); // bind scroll a bit later to prevent mess
}


// events
function moreListClick(e) {
	e.preventDefault();
	
	var target = $(this).attr('href');
	target = target.substring(target.indexOf('#'));
	STLog("Click "+target);
	
	$(target).toggle("fast");
}


function windowScroll(e) {
	e.preventDefault();
	
	oldScrollPosition = currentScrollPosition;
	currentScrollPosition = $(document).scrollTop(); // works with $(window) too
	scrollDirection = oldScrollPosition - currentScrollPosition;
	
	// find closest block
	var blocks = $(".block");
	
//	var str = "block heights:";
//	for (var i=0; i < blocks.length; i++) {
//		 str = str + "; "+ i+":"+ $("#block"+i).outerHeight(true);
//	}
//	STLog(str);	
	
	if (blocks.length > 1) {
		var blockHeight = $("#block0").outerHeight(true);		
		var blockPosition = Math.round(currentScrollPosition / blockHeight);
		
//		STLog(blocks.length + " / position: " + blockPosition);

		$("#block"+currentBlock).removeClass("clue");

				
		if (blockPosition != currentBlock) {

			// TEST!
			if (blockPosition >= blocks.length) {
				currentBlock = blocks.length-1;	
//				STLog("!! overflow! - reset to: "+currentBlock);	
			}
			else {	
				currentBlock = blockPosition;
			}
			
			resetNavigationMenu();
		}
		
		$("#block"+currentBlock).addClass("clue");

		
	}
		
	if(typeof scrollTimeout == "number") {
	  clearTimeout(scrollTimeout); // clear old
	}
	scrollTimeout = setTimeout(autoScroll, autoScrollDelay);
}


function navigationNextClick(e) {
	e.preventDefault();
	STLog('Clicked.');
	scrollWithDirection(+1);
}

function navigationPrevClick(e) {
	e.preventDefault();
	STLog('Clicked.');
	scrollWithDirection(-1);
}


function showLoadingDiv() {

	if ($("#loading").length == 1) $("#loading").fadeIn(0);
	else $("body").append('<div id="loading"></div>');
	
	var xOffset = Math.round(Math.random()*2) * 100;
	$("#loading").css("background-position", "-"+xOffset+"px 0px");
}

function mainMenuClick(e) {
	e.preventDefault();
	var target = $(this).attr('href');
	STLog("Clicked on " + target);
	
	if (!$(this).parent().hasClass("selected")) {
		$("#mainmenu li").removeClass('selected');
		$(this).parent().addClass('selected');
		
	    // bind or unbind scroll event    
	    if ($(this).attr('rel') == 'portfolio') {
	        bindWindowScroll();
	      //  initPrevNext();
          
			// if not set selected .. set first
	       	if ($("#tagmenu li.selected").length == 0) {
	       		$("#tagmenu li:first").addClass("selected");
	       	}
	    }
	    else {
	   		unbindWindowScroll();
	       	$("#slider").css({paddingBottom:"0px"});
	       	$('#navigation').hide();
	    }
	    
		$("#intro").html('<div id="wait"><span>loading...</span></div>');
		
		loadAndCacheView(target);
		
		
	}
}


function tagMenuClick(e) {
	e.preventDefault();
	var target = $(this).attr('href');
	
	STLog("Clicked " + target);
	if (!$(this).parent().hasClass("selected")) {
		$("#tagmenu li").removeClass('selected');
		$(this).parent().addClass('selected');
		
		// remove additional / tag search stuff
		$("#tagmenu li.additional").remove();
		
		// update href to target in mainmenu
		$('#mainmenu li a[rel="portfolio"]').attr('href', target);
		
		loadAndCacheView(target);
	}
}

// window & view manipulation
function loadAndCacheView(target) {
	var cacheId = target.replace(/\//g,"-");
	if (jsonCache[cacheId] == undefined) {
	
			showLoadingDiv();

			// fetch data from backend server
			var noCache = Date();
			$.getJSON(root+"ajax.php?url="+target,
				{ "noCache": noCache },
	        	   function(data, status) {
	        			if (status == "success") {
			        		STLog('ajax load and cache '+cacheId);
							jsonCache[cacheId] = data;
							updateView(cacheId);
	        			}
	        	   });
		}
		else {
			STLog('update view from cache '+cacheId);
			updateView(cacheId);
		}
}




function scrollWithDirection(direction) {	
	if( !$(scrollElement).is(':animated') ) {
		var totalBlocks = $(".block").length;
		/*
		currentBlock = (currentBlock + direction) % totalBlocks; // hmm it allows negative values
		if (currentBlock < 0) currentBlock = totalBlocks-1;
		*/
		
		newBlock = currentBlock + direction;
		if (newBlock <= 0) {
			newBlock = 0;
		}
		else if (newBlock >= totalBlocks) {
			newBlock = totalBlocks - 1;
		}
		
		if (newBlock != currentBlock) {
			currentBlock = newBlock;
			$("#block"+currentBlock).addClass("clue");
  
			resetNavigationMenu();
			unbindWindowScroll(); // unbind scroll event, ff, opera workaround,
	
			STLog("new current: "+currentBlock+" of total: "+totalBlocks+" after direction: "+direction);
			var targetY = $("#block"+currentBlock).offset().top;	
			$(scrollElement).stop().animate({scrollTop:targetY}, 1000, function() { $(".block").removeClass("clue");} ); // html - firefox, opera, body - safari
			setTimeout(bindWindowScroll, 1100); // bind scroll a bit later to prevent mess
		}
	}
}

function updateView(id) {
	document.title = 'Studio Tandem – '+jsonCache[id].title;
	// location.pathname = 'hmhmhm';
    
    $("#loading").fadeOut(100);
    
	$("#intro").html(jsonCache[id].left);
	
    $("#slider").animate({top:"-300px", opacity: 0.0}, "fast", function() {	
	$("#slider").html(jsonCache[id].slider);
    $("#slider").css({top:"1000px"}); // TODO: višina okna!
	$("#slider").animate({top:"0", opacity: 1.0}, "fast");
        
        // reset scroll
        //$(scrollElement).css({scrollTop:0});
        currentBlock = 0;
        currentScrollPosition = 0;
        
    if (scrollBound) {
        	unbindWindowScroll();
			$(window).scrollTop(0); // starts scroll event!
			bindWindowScroll();
		}
		else {
			$(window).scrollTop(0); // starts scroll event!
		}
		resetNavigationMenu();
	});
}


function portfolio() {
	
}