/**
 * OOR.nl main js file
 * @author Max Meinders & Stef van den Ham
 * @version 0.1
 * @link http://www.noprotocol.nl
 */

var Settings = {
    speed: 700,
    slideAmount: 4,
    debug: false
};

$(function() {
	
	var cache = {};
	var templates = {};
	
	// Init jScrollPane	
	
	var init_jScroll = function(target) {
		return $(target + ' .scroll-pane').jScrollPane({
			showArrows: false,
			maintainPosition: true,
			autoReinitialise: true,
			verticalGutter: 30,
			hideFocus: true			
		}).data('jsp');
	}
	
	var article_scroll = init_jScroll('#article');
	var footer_scroll = init_jScroll('#footer'); // For specials aswell
	
	var content = {
		article: {
			albums: "Album review",
			concerts: "Concert review",	
			news: "Nieuws"
		},
		footer: {
			footer: "&nbsp;",
			specials: "More"			
		}
	}
	
	$('#logo a').click(function(ev) {
		ev.stopPropagation();
		console.log('asdf');
	});
	
	// What to load on hashchange

	$(window).bind('hashchange', function(e) {
		
		var hash = $.param.fragment();
		if (hash == '' || hash == undefined) hash = 'home/';
		_gaq.push(['_trackPageview', hash]); // Google analytics
		var path = hash.split('/');
		if (path[0] != 'empty') 
			$('#tabs .tab.empty a').attr('href','#empty/');;	
		
		switch(path[0]) {
			
			
			case 'search':
				
				$.publish('search-update');
			
			case 'home':
			
				if (path[0] == 'search')
					populateCovers('/covers/load/' + hash, true);
				else
					populateCovers('/covers/load/all/', false);
								
				$.publish('slide-in', ['home']);
				$.publish('slide-out', ['article', 'up']);
				$.publish('slide-out', ['footer', 'down']);
				
				$('#article .back > a').attr('href' , '#' + hash);
				
				break;
			
			case 'news':
			case 'reviews':

				var part_a = 0;
				var part_b = 1;
				if(path[0] == 'reviews') {
					++part_a;
					++part_b;
				}
				
				$('#article').attr('class', 'slide ' + path[0]);
				$('#article .slide-header .tag').html(content.article[path[part_a]] != undefined ? content.article[path[part_a]] : "type error");
				
				article_scroll.getContentPane().empty();
				article_scroll.getContentPane().load(
					'/'+path[part_a]+'/view/'+path[part_b]+'/'+path[(++part_b)],
					function() {
						article_scroll.reinitialise();
						$('#article .content a[href^="http://"], #article .content a[href^="https://"]').attr('target','_blank');
					}
				);	
				--part_b;
				populateNavigation('/' + path[part_a] + '/related/' + path[part_b]);	
								
				$.publish('slide-in', ['article']);
				$.publish('slide-out', ['home', 'down']);
				$.publish('slide-out', ['footer', 'down']);	
					
				break;
			
			case 'specials':	
			case 'footer':
				
				$('#footer').attr('class', 'slide ' + path[0]);
				$('#footer .slide-header .tag').html(content.footer[path[0]] != undefined ? content.footer[path[0]] : "type error");
				
				footer_scroll.getContentPane().empty();
				footer_scroll.getContentPane().load(
					'/'+hash,
					function() {
						footer_scroll.reinitialise();
						$('#footer .content a[href^="http://"]').attr('target','_blank');
					}
				);
				
				$.publish('slide-in', ['footer']);
				$.publish('slide-out', ['home', 'up']);
				$.publish('slide-out', ['article', 'up']);
				
				break;
				
			case 'empty':
			
				$.publish('slide-out', ['home', 'left']);
				$.publish('slide-out', ['article', 'left']);
				$.publish('slide-out', ['footer', 'left']);
				
				$('#tabs .tab.empty a').attr('href','#home/');
				
				break;
				
			default:
			
				$.publish('error', ['notice', 'De opgevraagde adres bestaat niet!']);
		}
	});
	
	// Load and render home covers
	
	var populateCovers = function(url, search) {
	
		var directive = {
			'li': {
				'listi <- list': {
					'.@id' : 'listi.id',
					'img@src' : 'listi.img',  
					'a@href+':'#{listi.id}/#{listi.slug}',
					'.title':'listi.title',
					'.subtitle':'listi.subtitle'
				}
			}
		};
	
		var directive_reviews = {
			'li': {
				'listi <- list': {
					'.@class+':' #{listi.type}',
					'.@id' : 'listi.id',
					'img@src' : 'listi.img',  
					'a@href+':'#{listi.type}/#{listi.id}/#{listi.slug}',
					'.title':'listi.title',
					'.subtitle':'listi.subtitle',
					'.review-type@class+':' #{listi.type}'
				}
			}
		};
		
		var hash = $.param.fragment();
		if (hash == '' || hash == undefined) hash = 'home/';
		
		var callback = function() {
			$('li.block img').load(function() {
				$(this).css('display','block');
			}).error(function() {});
			
			$('#home a.arrow.left').each(function() {
		    	$.publish("home-arrow-update", [this, 0]);
		    });	    
		   
    		$('#home a.arrow.left').click( function() { $.publish('home-left', [this]); });
			$('#home a.arrow.right').click( function() { $.publish('home-right', [this]); });		
		}
		
		if (cache.previous != hash) {	
		
			if (Settings.debug) console.log(hash + ' is not cached, retrieving from server..');
		
			$.get(url, function(data) {
			
				$('#home.slide').html(templates.blocks);
				if (search) $('#home .search-info').show().find('.value').text( $('input#search-field').val() );
						
				$('.nav.news ol').render(data.body.news, directive);
				$('.nav.reviews ol').render(data.body.reviews, directive_reviews);
				$('.nav.specials ol').render(data.body.specials, directive);
				
				callback();
				
				cache.previous = hash;
			    
			},'json');	
		} 
	}
	
	// Load navigation
	
	var populateNavigation = function(url) {
	
		var directive = {
			'div.ui-shadow': {
				'bodyi <- body': {
					'h3': 'bodyi.title',
					'a.item': {
						'listi <- bodyi.list': {
							'.@class+': ' #{listi.align}',
							'.@href':'listi.link',
							'.info .title': 'listi.title',
							'img@src': 'listi.img'
						}
					}
				}
			}	
		};
		
		var callback = function() {
			$('li.block img').load(function() {
				$(this).css('display','block');
			});	
			
			var elm = $('#article .navigation');
			elm.find('div.ui-shadow').each(function() {
				$(this).before( $(this).find('h3') );
			});
			
			elm.accordion({autoHeight: false});
		}
		
		if (Settings.debug) console.log(url);
		$('#article .navigation-wrapper').empty();
		
		$.get(url, function(data) {
		
			if (Settings.debug) console.log(data);
		
			$('#article .navigation-wrapper')
				.html(templates.navigation)
				.find('.navigation')
				.render(data, directive);			
				
			callback();
		    
		},'json');	
	}
	
	// Search
	
	var search = function() {
		document.location.hash = 'search/q:' + encodeURI( $('#search-field').val() );
		$.publish("tab-toggle", [$('#tabs .search a.button')]);
	}
	    
    // attach triggers
    
    // background image navigation
    $('#tabs a.arrow.left').click(function() { $.publish('bg-left', [this]); return false; });
    $('#tabs a.arrow.right').click(function() { $.publish('bg-right', [this]); return false; });
    $('#tabs a.arrow.left').each(function() { $.publish("bg-arrow-update", [this, 0]); });
    
    // blackscreen
    $('#shadow').click(function() { $.publish("black-close"); });
	
    // tab buttons
    $('.tab a.button').click(function() { $.publish('tab-toggle', [this]); });
	
	// search events
	$('#search-form').submit(function() { search(); return false; });
	$('#search-button').click(function() { search(); return false; });
    
    $(document).ajaxError(function(event, xhr, ajaxOptions, errorThrown) {
	    $.publish('error', ['notice', 'Fout bij het ophalen van de pagina!<br>' + errorThrown]);
	});
	
	// cache templates
	
	templates.blocks = $('#home.slide').html();
	$('#home.slide').empty();
	
	templates.navigation = $('#article .navigation-wrapper').html();
	$('#article .navigation-wrapper').empty();
	
    // Select new background image
    
    $('.slide').click(function(e) { 
    	e.cancelBubble = true; /* Microsoft */
	    if (e.stopPropagation)
	        e.stopPropagation(); /* W3C */
    });
    
	var switchbg = function(clickelm, activebg, newbg) {
		activebg.remove();
		newbg.attr('class','active');
		clickelm.parents('ol').find('a.active').removeClass('active').removeClass('ui-shadow');
		clickelm.addClass('active').addClass('ui-shadow').find('.loader-gif').remove();
		$('#tabs .selectbg .expanded:visible').prev().click();
	}
	
	$('.selectbg li a').click(function() {
		var a = $(this),
			img = a.find('img'),
			imgurl = img.attr('src').split('/');
			bgclick = img.attr('linkto');

		a.append('<div class="loader-gif"></div>');
		imgurl = imgurl[imgurl.length-1];
		//$('div#bg').append('<img class="load" src="/uploads/wallpapers/' + imgurl + '?' + Math.random() + '" />');
		$('div#bg').append('<img class="load" src="/uploads/wallpapers/' + imgurl + '" />');

		// bind ad click
		$('div#slides-container').unbind('click').click(function() { window.open(bgclick); });
		$('div#bg').unbind('click').click(function() { window.open(bgclick); });

		// fade prvious bg when new bg is loaded
		$('div#bg img.load').load(function() {
			var loaded = $(this),
				active = $('div#bg img.active');
			
			if (active.size() > 0) {
				active.fadeOut(300, function() { switchbg(a, active, loaded); });
			} else {
				switchbg(a, active, loaded);
			}
		});
	});
    
    // Render UI elements
    
    $('input').checkBox();
    
    var count = $('#tabs .selectbg li').size();
    var pick = Math.floor( Math.random() * (count) ) + 1;
    $('#tabs .selectbg li:nth-child(' + pick + ') a').click();

	// trigger hash on load
	
	$(window).trigger('hashchange');
	
  
});

/**
 * Error events
 */
 
$.subscribe("error", function(type, txt) {
	$('#shadow').fadeIn('fast');
	$('#main').append('<div class="error-message ui-shadow ' + type +'">' + txt + '</div>');  
});

$.subscribe("black-close", function() {
	$('.error-message').remove();
});

/**
 * Slide navigation
 */

$.subscribe("slide-in", function(content) {
	$('#' + content).animate({ marginTop: "-280px", marginLeft: "-425px"}, Settings.speed );  
});

$.subscribe("slide-out", function(content, direction) {
	var location = {};
	switch(direction) {
		case 'left': location = { marginLeft: "-2425px"}; break;
		case 'right': location = { marginLeft: "1575px"}; break;
		case 'up': location = { marginTop: "-1810px"}; break;
		case 'down': location = { marginTop: "1190px"}; break;
	}
	$('#' + content).animate(location, Settings.speed );  
});

/**
 * Home block navigation
 */

$.subscribe("home-left", function(elm) {
	var ol = $(elm).parents('.nav').find('.blocks ol');
	var pos = ol.attr('pos') * 1;
	var n = ol.children('li').size();
	if (pos < 0) {
		$.publish("home-arrow-update", [elm, 1]);
		var move = (pos + Settings.slideAmount <= 0 ? Settings.slideAmount : -pos);
		ol.attr('pos', pos + move);
		ol.animate({ marginLeft: "+=" + (move * 200) + "px"}, Settings.speed, 'swing');
	} else {
		ol.effect('bounce', {distance: 60, direction: 'right', times: 1}, 300 );
	}
});

$.subscribe("home-right", function(elm) {
	var ol = $(elm).parents('.nav').find('.blocks ol');
	var pos = ol.attr('pos') * 1;
	var n = ol.children('li').size();
	if (pos + n > 4) {
		$.publish("home-arrow-update", [elm, -1]);
		var move = (pos + n - 4 >= 4 ? Settings.slideAmount : pos + n - 4);
		ol.attr('pos', pos - move);
		ol.animate({ marginLeft: "-=" + (move * 200) + "px"}, Settings.speed, 'swing');
	} else {
		ol.effect('bounce', {distance: 60, direction: 'left', times: 1}, 300 );	
	}
});

$.subscribe("home-arrow-update", function(elm, direction) {
	var ol = $(elm).parents('.nav').find('.blocks ol');
	var pos = (ol.attr('pos') * 1) + Settings.slideAmount * direction;
	var n = ol.children().size();
	var buttons = $(elm).parent();
	if (pos >= 0) {
		buttons.removeClass('none').removeClass('both').removeClass('left').removeClass('right');
		if (n < 5) buttons.addClass('none');
		else buttons.addClass('right');
	} else if (pos + n <= 4) {
		buttons.removeClass('none').removeClass('both').removeClass('left').removeClass('right');
		if (n < 5) buttons.addClass('none');
		else buttons.addClass('left');
	} else {
		buttons.removeClass('none').removeClass('both').removeClass('left').removeClass('right');
		if (n < 5) buttons.addClass('none');
		else buttons.addClass('both');
	}
});

/**
 * Background select events
 */

$.subscribe("bg-left", function(elm) {
	var ol = $(elm).parents('.expanded').find('ol');
	var pos = ol.attr('pos') * 1;
	var n = ol.children('li').size();
	if (pos < 0) {
		$.publish("bg-arrow-update", [elm, 1]);
		var move = (pos + Settings.slideAmount <= 0 ? Settings.slideAmount : -pos);
		ol.attr('pos', pos + move);
		ol.animate({ marginLeft: "+=" + (move * 128) + "px"}, Settings.speed, 'swing');
	} else {
		ol.effect('bounce', {distance: 60, direction: 'right', times: 1}, 300 );
	}	
});

$.subscribe("bg-right", function(elm) {
	var ol = $(elm).parents('.expanded').find('ol');
	var pos = ol.attr('pos') * 1;
	var n = ol.children('li').size();
	if (pos + n > 4) {
		$.publish("bg-arrow-update", [elm, -1]);
		var move = (pos + n - 4 >= 4 ? Settings.slideAmount : pos + n - 4);
		ol.attr('pos', pos - move);
		ol.animate({ marginLeft: "-=" + (move * 128) + "px"}, Settings.speed, 'swing');
	} else {
		ol.effect('bounce', {distance: 60, direction: 'left', times: 1}, 300 );	
	}
});

$.subscribe("bg-arrow-update", function(elm, direction) {
	var ol = $(elm).parents('.expanded').find('ol');
	var pos = (ol.attr('pos') * 1) + Settings.slideAmount * direction;
	var n = ol.children().size();
	var buttons = $(elm).parent();
	if (pos >= 0) {
		buttons.removeClass('none').removeClass('both').removeClass('left').removeClass('right');
		if (n < 5) buttons.addClass('none');
		else buttons.addClass('right');
	} else if (pos + n <= 4) {
		buttons.removeClass('none').removeClass('both').removeClass('left').removeClass('right');
		if (n < 5) buttons.addClass('none');
		else buttons.addClass('left');
	} else {
		buttons.removeClass('none').removeClass('both').removeClass('left').removeClass('right');
		if (n < 5) buttons.addClass('none');
		else buttons.addClass('both');
	}
});

$.subscribe("black-close", function() {
	$('#shadow').fadeOut('fast');
});

/**
 * Tab events
 */

$.subscribe("tab-toggle", function(elm) {
	var tab = $(elm).parents('.tab')
	var expand = tab.find('.expanded');
	if (expand.is(':hidden')) { 
		$('#shadow').fadeIn('fast');
		$(elm).addClass('active');
	} else {
		$(elm).removeClass('active');
		if ($('.tab a.button.active').size() == 0)
			$.publish("black-close");
	}	
	expand.animate({width: 'toggle'}, 200, function() {
		if (!$('.tab .expanded').is(':visible')) 
			$('#shadow').hide();
		else
			$('#shadow').show();
	});
});

$.subscribe("black-close", function() {
	$('.tab a.button.active').click();
	
});
 
$.subscribe('search-update', function() {
	var path = $.param.fragment().split('/');
	if (path[0] == 'search' && path[1] != undefined) {
		var params = path[1].split(':');
		if (params[0] == 'q')
			$('input#search-field').val( decodeURIComponent(params[1]) );
			return true;
	}
	$('input#search-field').val('');
});

/**
 * Navigation
 */

$.subscribe('build-next', function(elm) {
	
});

$.subscribe('build-previous', function(elm) {
	
});


/**
 * Cookies
 */

function createCookie(name, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

