//VTProject javascripts - author pavel.krusek@gmail.com

function ajaxLightboxCallback(){
	$('ul.tabs').tabs('div.panes > div');
	
	if ($("#gallery").length > 0){
		$("#gallery").css("visibility","hidden");
		$('#gallery img').imgpreload({
			all:function(){
				$("#gallery").css("visibility","visible");
				var apiBig = $('.scrollable.big').scrollable({size:1, circular:true, mousewheel:true, easing:'easeOutSine', speed:800, api:true});
  				var apiThumbs = $('.scrollable.thumbs').scrollable({size:1, circular:false, mousewheel:true, api:true});
				
				$(".big-left").fadeOut(0);
  				$(".big-right").fadeOut(0);
  
  				$('.scrollable.big').hover(function(){
    				$(".big-left").fadeIn(500);
    				$(".big-right").fadeIn(500);
  				},function(){
    				$(".big-left").fadeOut(200);
    				$(".big-right").fadeOut(200);
  				});
				
				if(apiThumbs){
  					$('.paging.gallery').html('strana 1 / ' + apiThumbs.getSize());
	
					apiThumbs.onSeek(function(){
    					$('.paging.gallery').html('strana ' + (this.getIndex() + 1) +' / ' + this.getSize());
  					});
	
					$("img",".thumbs").click(function(){
						apiBig.seekTo(parseInt($(this).attr("alt"))); 
  					});
  				}
			}
  		});
	}
}

//onload - document ready
$(function(){
	//navigation menu
	$('#menu').accordion({autoHeight:false, active:false, animated:'slide', event:'click', collapsible:true});
	//MVC pattern pro deeplink handling
	// model
	var Model = {
		pages:[],
		names:[],
        currentLevel:0,
		setPage:function(level, page, name, isUserAction){
			if(page == this.pages[level]){
				//return;
            	//$("#menu").accordion("option", "disabled", true);
			}else{
				//$("#menu").accordion("option", "disabled", false);
			}
			this._updateState(level, page);
			this._updateNames(level, name);
			if(isUserAction){
				$.history.load(page);//spousti restore a nahrava URL
			}else{
				render();
			}
		},
		_updateState:function(level, page){
			var pages = [];
			for(var i = 0; i < level; i++){
				pages[i] = this.pages[i];
            }
            pages[level] = page;
            this.pages = pages;
            this.currentLevel = level;
		},
		_updateNames:function(level, name){
			var names = [];
			for(var i = 0; i < level; i++){
				names[i] = this.names[i];
            }
            names[level] = name;
            this.names = names;
		},
		restore:function(hash){
			if(hash != this.pages[this.currentLevel]){//reload browseru, bookmark, browser back / forward button
				if(hash.split('/')[1] == 'detail'){//uprava hashe pokud jde zvenku detail (vykresleni listu pod detail boxem)
					hash = '/' + hash.split('/')[2] + '/' + hash.split('/')[3] + '/' + hash.split('/')[4] + '/' + hash.split('/')[5];
				}
				var menu;
				var level = (hash.split('/').length - 1)/2 - 1;
				level == 0 ? menu = hash : menu = '/' + hash.split('/')[1] + '/' + hash.split('/')[3];
				$('#menu').accordion("activate", $("#menu").children('li').index($("li:has(a[href=" + menu +"])")));
				$('#menu > li > ul > li > a').removeClass('active');
				if(level == 1){
					this.names[0] = $('a[href*=/' + hash.split('/')[1] + '/' + hash.split('/')[3] + ']').attr('rel');
					$('#menu li a[href*='+hash+']').addClass('active');
				}
				var name = $('a[href*='+hash+']').attr('rel');
				this.setPage(level, hash, name, false);
			}
			if(!ModelDetail.isBox){
				_gaq.push(['_trackPageview', hash]);
				render();
			}else{
				ModelDetail.isBox = false;
			}
		}
	}
	
	var ModelDetail = {
		detail:'',
		isBox:false,
		setPage:function(page){
			this.isBox = true;
			$.history.load('/detail/' + page);
		},
		restore:function(hash){
			_gaq.push(['_trackPageview', hash]);
			if(this.isBox){			
				this.detail = hash.split('/')[6];
				renderDetail();
			}else{
				this.detail = hash.split('/')[6];
				Model.restore(hash);
				renderDetail();
			}
		}
	}
	
	//view
	function render(){
		if(Model.pages[Model.currentLevel]){
			deleteBox();
			var title = '';
			for(var i = Model.currentLevel; i >= 0 ; i--){
				title += Model.names[i] + ' | ';
            }
			document.title = title + "VT PROJECT";
			$.ajax({
				url: 'list.php',  
				type: 'GET',
				data: 'id=' + Model.pages[Model.currentLevel].split('/')[Model.currentLevel + 1],
				cache: false,
				success: function(html){
					//_gaq.push(['_trackPageview', hash]);
					$('#main').html(html);
					$("#mas").masonry({
	    				columnWidth:200,
	 					itemSelector:'.box:not(.invis)',
	    				animate:true,
	    				animationOptions:{
	        				duration:300,
	        				easing:'linear',
	        				queue:false
	    				}
					});
					$('.box').each(function(i){
						$(this).fadeOut(0);
						$(this).delay(50 * i).fadeIn(300);
					});
				}
			});
		}
	}
	
	function renderDetail(){
		var detail = 'detail.php?id=' +  ModelDetail.detail;
		$dialog = $('#detailLoader').load(detail + ' #lightbox', null, ajaxLightboxCallback).dialog({
			autoOpen: false,
                  	  title: '',
                  	  //position: [225,10],
                  	  modal: true,
                  	  closeText: '',
                  	  width: 590,
                  	  height: 700,
					  show: 'fade',
                  	  hide: 'fade',
					  closeOnEscape: false,
                  	  draggable: false
        });
		$dialog.dialog('open');	
	}
	
	//controller
	$('a', 'ul#menu').live('click', listHandler);
	$('.logo').live('click', listHandler);
	$('.box_content > h2 > a').live('click', addBoxLink);
	$("div[id*='link']").live('click', detailHandler);
	$('.ui-widget-overlay, #header > img').live('click', detailOutHandler);
	$("a", "#links").live("click",function(){
		ModelDetail.isBox = false;
		ModelDetail.restore($(this).attr("href"));
		return false;
	});
	
	function addBoxLink(e){
		$(this).addClass('nestedLink');
	}
	
	function listHandler(e){
		var page = $(this).attr('href');
		var name = $(this).attr('rel');
		var level;
		if($(this).parents('ul').length > 0)
			level = $(this).parents('ul').length - 1;	
		else
			level = 0;
		Model.setPage(level, page, name, true);
		return false;
	}
	
	function detailHandler(e){
		if($(this).find(".nestedLink").size() == 0){
			var page = $(this).attr('id').split('_')[3] + '/' +  $(this).attr('id').split('_')[4] + '/' + $(this).attr('id').split('_')[5] + '/' +  $(this).attr('id').split('_')[6] + '/' + $(this).attr('id').split('_')[1] + '/' + $(this).attr('id').split('_')[2];
			ModelDetail.setPage(page);
			return false;
		}else{
			$('.nestedLink').removeClass('nestedLink');	
		}
	}
	
	function detailOutHandler(e){
		$.history.load(Model.pages[Model.currentLevel]);
		deleteBox();
	}
	
	function deleteBox(){
		if($(".ui-dialog-content").length > 0){
			$('.ui-dialog-content').empty();
			$('.ui-dialog-content').remove();
			$dialog.dialog('close');
			$dialog.dialog('destroy');
			$('body').append('<div id="detailLoader"></div>');
		}
	}
	
	$('#menu > li > ul > li > a').click(function(){
		$('#menu > li > ul > li > a').removeClass('active');
		$(this).addClass('active');
	});
	
	//init history
	$.history.init(function(hash){
		if(hash == ''){
			hash = '/52/home';
		}
		if(hash.split('/')[1] == 'detail'){
			ModelDetail.restore(hash);
		}else{
			Model.restore(hash);	
		}
	},{unescape: "/"});
	
});
