/*
 * @author: Bert Van Hauwaert <becoded.be> 
 * */
var Obumex = {};

Obumex.Site = function (options)
{
	this.options = options;
	
	this.loadedContent = null;
	this.loadedBackground = null;
	this.contentVisible = false;
	this.fadeSpeed = 'slow';
	this.splashVisible = true;
	this.initUriInfo = null;
	this.imageBasePath = '/upload/attach/';
	this.background = null;
	this.skipBackground = false;
	this.l18n = {
		nl_BE : { moreNavigation: 'Meer navigatie', lessNavigation: 'Minder navigatie'},
		fr_BE : { moreNavigation: 'Plus de navigation', lessNavigation: 'Moins de navigation'},
		en_GB : { moreNavigation: 'More navigation', lessNavigation: 'Less navigation'}
	};
	this.locale = 'nl_BE';
	this.firstPage = true;
	
	this.init = function ()
	{
		var me = this;
		
		me.initUriInfo = me.parseUrl(window.location.href);
		
		$(function() {
			me.setupLocale();
			me.setupAddress();
			me.setupForms();
			me.splashFadeIn();
			me.setupBackground();
		});
	};
	
	this.setupLocale = function()
	{
		var me = this;
		$('.locale a').unbind('click').bind('click', function (event) {
			var anchor = $(event.currentTarget);
			var locale = anchor.attr('rel');
			
			me.setFooter(locale);

			$.ajax({
				type: 'POST',
				async: false,
				url: '/ajax/ajax-set-lang.php',
				data: "lang=" + locale,
				dataType: "html",
				success: function(data) {
					var dummy = '';
				}
			});	
		});
	}
	
	this.setFooter = function (locale)
	{
		if (locale != "")
		{
			var me = this;
			$('#footer').html($('#footer_' + locale).html());
			
			me.setLocale(locale);
			me.setupMenu();
			me.setupLocale();
		}
	};
	
	this.setLocale = function (locale)
	{
		this.locale = locale;
	};
	
	this.setupMenu = function ()
	{
		var me = this;
		
		me.toggleSubNavigation();
		// me.toggleExtraMenu();
	};
	
	this.toggleSubNavigation = function ()
	{
		var subMenus = $('.mainNavigation ul:parent');
		subMenus.prev().bind('click', function(event) {
			var anchor = $(this);
			var ul = anchor.next();
			subMenus.each(function() {
				var subUl = $(this);
				if (subUl.prev().attr('href') !== anchor.attr('href')) {
					subUl.fadeOut();
				}
			});
			ul.fadeToggle();
		});
		
		var noSubmenu = $('.mainNavigation > li > a:only-child');
		noSubmenu.bind('click', function() {
			subMenus.each(function() {
				var subUl = $(this);
				subUl.fadeOut();
			});
		});
	};
	
/*
	this.toggleExtraMenu = function ()
	{
		var me = this;
		var lessMore = $('.mainNavigation span.lessMore');
		lessMore.bind('click', function(event){
			var footer = $('#footer');
			var type = 'hide';
			if (footer.height() === 70){
				type = 'show';
			}
			var fadeDuration = 400;
			if (type === 'show') {
				me.showExtraMenu(footer, lessMore, fadeDuration);
			} else {
				me.hideExtraMenu(footer, lessMore, fadeDuration);
			}
		});
	};
	
	this.showExtraMenu = function (footer, lessMore, fadeDuration)
	{
		var me = this;
		footer.animate(
				{height: 110},
				'slow',
				function () {
					$('ul.subNavigation').fadeIn(fadeDuration);
				}
			);
			
			lessMore.fadeOut(fadeDuration, function() {
				lessMore.html(me.l18n[me.locale].lessNavigation).fadeIn(fadeDuration);
			});
	};
	
	this.hideExtraMenu = function (footer, lessMore, fadeDuration)
	{
		var me = this;
		$('ul.subNavigation').fadeOut(fadeDuration, function () {
			footer.animate(
				{height: 70},
				'slow'
			);
		});
		
		lessMore.fadeOut(fadeDuration, function() {
			lessMore.html(me.l18n[me.locale].moreNavigation).fadeIn(fadeDuration);
		});
	};
*/
	
	this.determineActiveMenu = function (url)
	{
		var me = this;
		$('#footer .navigation a').removeClass('active');
		
		console.log(url);
		
		// Om menu item actief te zetten, alles na '?' niet gebruiken bij de check om te kijken welke URL actief staat...
		var use_url = (url.indexOf('?') > -1) ? url.substring(0, url.indexOf('?')) : url;
		var anchor = $('#footer .navigation a').filter(function ()
		{
			var cur_url = $(this).attr("href");
			var cur_use_url = (cur_url.indexOf('?') > -1) ? cur_url.substring(0, cur_url.indexOf('?')) : cur_url;
			return (cur_use_url == use_url);
		});
		anchor.parentsUntil('.navigation').children('a').addClass('active');
		anchor.parents('ul').each(function() {
			var ul = $(this);
			if (ul.css('display') === 'none') {
				// if (ul.hasClass('subNavigation')) {
				// 	me.showExtraMenu($('#footer'), $('.mainNavigation span.lessMore'), 400);
				// } else {
					ul.fadeIn();
				// }
			}
		});
		
		// if (url != '/contact')
		{
			$(".navigation li ul:visible").each(function ()
			{
				if (!($(this).parent().find("a").hasClass("active")))
				{
					$(this).hide();
				}
			})
		}
		
		if (me.firstPage) {
			me.firstPage = false;
			var children = anchor.parent().children('ul');
			if (children.length > 0) {
				$(children.get(0)).fadeIn();
			}
		}
	};
	
	this.setupBackground = function ()
	{
		var me = this;
		me.background = $("#background");
		me.background.css("visibility", "hidden");
		
		$(window).load(function() {
			me.resizeBackground();
		});
		
		$(window).bind("resize", function() {
			me.resizeBackground();
		});
			
		$('#background img').unbind('load').bind('load', function() {
			$('#background img').attr("ratio", "");
			$('#background img').css({
				width: 'auto',
				height: 'auto'
			});
			
			$('#background').show();
			me.resizeBackground();
			$('#background').hide();
			
			$('#background').hide().fadeIn(me.fadeSpeed, function ()
			{
				// me.resizeBackground();
			});
		});
	};
	
	this.resizeBackground = function ()
	{
		var me = this;
		if (me.background === null) {
			return;
		}
		
		var center = true;
		
		var windowWidth = $(window).width();
		var windowHeight = $(window).height();
		
		var bRatio = windowWidth / windowHeight;
		
		me.background.css({
			"width": windowWidth + "px",
			"height": windowHeight + "px"
		});
		
		var img = me.background.children('img');
		
		var iw = img.width();
		var ih = img.height();
		
		if (iw == 0 || ih == 0)
		{
			return;
		}
		var fRatio = img.attr("ratio");
		if (fRatio == undefined || fRatio == "")
		{
			fRatio = iw / ih;
			img.attr("ratio", fRatio);
		}
		
		if (bRatio < fRatio){
		    img.css({ height: '100%' });
		    img.css({ width: 'auto' });
		} else {
		    img.css({ width: '100%' });
		    img.css({ height: 'auto' });
		}

		me.background.css("visibility", "visible");
		
		// Center BG Image
		if (center) {
			img.css('position', 'relative');
			if (bRatio < fRatio)
			{
				img.css('top', 0);
				img.css('left', (windowWidth - img.width())/2);
			}
			else
			{
				img.css('left', 0);
				img.css('top', (windowHeight - img.height())/2);
			}
		}
		
	};
	
	this.splashFadeIn = function ()
	{
		var me = this;
		if (me.initUriInfo.path !== '/') {
			window.location.href = me.initUriInfo.scheme + '://' + me.initUriInfo.host + '/#' + me.initUriInfo.path;
		}
		
		if (me.initUriInfo.path === '/' && ( typeof me.initUriInfo.fragment !== 'string' || me.initUriInfo.fragment.length === 0 )) {
			$('#splash div').fadeIn(1000);
		} else {
			this.splashVisible = false;
			$('#splash').hide();
		}
	};
	
	this.splashSlide = function ()
	{
		var me = this;
		
		me.skipBackground = true;
		
		$('#background img').one('load', function() {
			$('#splash div').fadeOut(1000, function() {
				me.contentVisible = true;
				$('#splash').effect('slide', {direction: "down", mode: 'hide'}, 1500, function() {
						me.contentVisible = false; 
						me.fadeInContent();
						me.splashVisible = false; 
						
						$('.navigation li a').each(function () {
							if ($(this).attr("href").match(/^\/news/i))
							{
								$(this).addClass("active");
							}
						});
					});
				});
		});
		
		$('#background img')
			.attr('src', me.imageBasePath + me.options.backgroundImage[me.locale].path)
			.css({'width' : me.options.backgroundImage[me.locale].width, 'height' : me.options.backgroundImage[me.locale].height});
		
		me.resizeBackground();
	};
	
	this.setupAddress = function ()
	{
		var me = this;
		var $list = $('a[target!="_blank"]:not(.special-arrows)');
		$list.address(); 
		
		$.address.change(function(event) {
			if (event.value !== '/' && event.value.indexOf("mailto:") == -1) {
				me.processRequest(event.value);
			}
			else if (event.value.indexOf("mailto:") > -1)
			{
				location.href = event.value.substring(event.value.indexOf("mailto:"));
			}
		});
	};

	this.processRequest = function (url, type, data)
	{
		var me = this;
		
		// $(".sub-ul-menu").hide();
		
		me.determineActiveMenu(url);
		
		type = type || 'get';
		data = data || {};
		
		//Load content
		me.loadedContent = null;
		me.loadedBackground = null;
		
		//Fade out content or hide splash screen
		if (me.splashVisible) {
			me.splashSlide();
		} else {
			me.fadeOutContent();
		}
		
		$.ajax({
			url: url,
			data: data,
			type: type,
			dataType: 'json',
			success: function(data){
				me.loadedContent = data.body;
				me.loadedBackground = data.background;
				if (!me.splashVisible) {
					me.fadeInContent();
				}
			}
		});
	};
	
	this.setupForms = function ()
	{
		var me = this;
		$('form').live('submit', function(event) {
			event.preventDefault();
			var form = $(this);
			var action = form.attr('action');
			if (action.length === 0) {
				var parts = me.parseUrl(window.location.href);
				if (parts.fragment) {
					action = parts.fragment;
				} else {
					action = parts.path;
				}
			}
			
			var method = form.attr('method').toLowerCase();
			if (method !== 'post') {
				method = 'get';
			}
			
			var data = form.serialize();
			
			me.processRequest(action, method, data);
		});
	};
	
	this.fadeOutContent = function ()
	{
		var me = this;
		me.contentVisible = true;
		$('#main').fadeOut(me.fadeSpeed, function() { 
			me.contentVisible = false; 
			me.fadeInContent();
			});
		$('#background').fadeOut(me.fadeSpeed);
	};
	
	this.fadeInContent = function ()
	{
		var me = this;
		if (me.loadedContent !== null && me.contentVisible === false) {
			me.changeBodyClass();
			var main = $("#main");
			main.html(me.loadedContent);
			
			if (me.loadedBackground.s === null) {
				me.loadedBackground.s = 'spacer.png';
			}
			
			if (!me.skipBackground) {
				var d = new Date();
				$('#background img')
					.attr('src', me.imageBasePath + me.loadedBackground.s + '?t=' + d.valueOf())
					.css({'width' : me.loadedBackground.w, 'height' : me.loadedBackground.h});
				me.resizeBackground();
			}
			me.skipBackground = false;
			main.fadeIn(me.fadeSpeed, function () {
				me.contentVisible = true;
				me.loadedContent = null;
				me.bindScrollPane();
				me.bindGallery();
				me.bindProdGallery();
			});
		}
	};
	
	this.changeBodyClass = function()
	{
		var info = this.parseUrl(window.location.href);
		if (info.fragment) {
			var bodyClass = info.fragment.replace(/\/|-/gi, '_').substr(1);
			$('body').removeClass().addClass(bodyClass);
		}		
	};
	
	this.parseUrl = function(str, component)
	{
		var o = {
			strictMode : false,
			key : [ "source", "protocol", "authority", "userInfo", "user",
					"password", "host", "port", "relative", "path",
					"directory", "file", "query", "anchor" ],
			q : {
				name : "queryKey",
				parser : /(?:^|&)([^&=]*)=?([^&]*)/g
			},
			parser : {
				strict : /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
				loose : /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/\/?)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/

			}
		};

		var m = o.parser[o.strictMode ? "strict" : "loose"].exec(str), uri = {}, i = 14;
		while (i--) {
			uri[o.key[i]] = m[i] || "";
		}

		switch (component) {
			case 'PHP_URL_SCHEME':
				return uri.protocol;
			case 'PHP_URL_HOST':
				return uri.host;
			case 'PHP_URL_PORT':
				return uri.port;
			case 'PHP_URL_USER':
				return uri.user;
			case 'PHP_URL_PASS':
				return uri.password;
			case 'PHP_URL_PATH':
				return uri.path;
			case 'PHP_URL_QUERY':
				return uri.query;
			case 'PHP_URL_FRAGMENT':
				return uri.anchor;
			default:
				var retArr = {};
				if (uri.protocol !== '') {
					retArr.scheme = uri.protocol;
				}
				if (uri.host !== '') {
					retArr.host = uri.host;
				}
				if (uri.port !== '') {
					retArr.port = uri.port;
				}
				if (uri.user !== '') {
					retArr.user = uri.user;
				}
				if (uri.password !== '') {
					retArr.pass = uri.password;
				}
				if (uri.path !== '') {
					retArr.path = uri.path;
				}
				if (uri.query !== '') {
					retArr.query = uri.query;
				}
				if (uri.anchor !== '') {
					retArr.fragment = uri.anchor;
				}
				return retArr;
		}
	};
	
	this.bindScrollPane = function () {
		$('.scroll-pane').jScrollPane(
			{
				showArrows: true,
				horizontalGutter: 10,
				verticalGutter: 10
			}
		);
		
		// Na binden van scrollpane mogen alle div's met INDEX verborgen worden (subpaginas)
		// Dit gebeurd NA het binden van de scrollpane omdat jScrollPane niet werkt als deze divs Hidden staan in het begin...
		$(".data div[index]").each(function ()
		{
			$(this).css({
				display: ($(this).attr("index") == 0) ? "block" : "none",
				visibility: "visible"
			});
		});
	};

	this.bindGallery = function () {
		$('div.gallery').galleryScroll(
			{
				step:1,
				duration:300,
				funcOnclick:function(){
					$('p.margin').html($('ul',this).css('marginLeft'));
				}
			}
		);
	};

	this.bindProdGallery = function () {
		$('div.prodgallery').galleryScroll(
			{
				step:1,
				duration:300,
				funcOnclick:function(){
					$('p.margin').html($('ul',this).css('marginLeft'));
				}
			}
		);
	};

	this.init();
};

function fn_tplsub_content_prev()
{
	var $items = $(".data div[index]");
	var item_count = $items.length;
	var visible_index = parseFloat($items.filter(":visible").attr("index"));
	
	$(".data div[index="+visible_index+"]").fadeOut();
	visible_index = (visible_index - 1 < 0) ? item_count - 1 : visible_index - 1;
	$(".data div[index="+visible_index+"]").fadeIn();
}

function fn_tplsub_content_next()
{
	var $items = $(".data div[index]");
	var item_count = $items.length;
	var visible_index = parseFloat($items.filter(":visible").attr("index"));
	
	$(".data div[index="+visible_index+"]").fadeOut();
	visible_index = (visible_index + 1 >= item_count) ? 0 : visible_index + 1;
	$(".data div[index="+visible_index+"]").fadeIn();
}
