
String.prototype.endsWith = function(str) {
	return (this.match(str+"$")==str);
}

String.prototype.startsWith = function(str) {
	return (this.match("^"+str)==str)
}

String.prototype.contains = function(str) {
	return (this.search(str)>-1)
}

function callJavascript(str) {
	var overlay = $('#Overlay');
	//$('.MainHolder').show();
	$('html,body').removeClass('Flash');
	overlay.remove();
	showOverlay = false;
}
var list;
var pageFactory = null;
var firstTime = true;
var clickedSubmenu = false;

function scrollToTop() {
	$.scrollTo('300px', 1500, {easing:'easeOutCubic'});
}

function replaceH() {
	list = $('h1.Title[turned!=true]').each(function() {
		$(this).attr('turned', true);
		var url = $(this).attr('data:background');
		if ( url ) {
			$(this).css('background-image', "url('"+url+"')");
			var width = $(this).width();
			var height = $(this).height();
			var txt = $(this).text();
			var img = new Image();
			img.src = AbsPath + 'includes/ttm.php?t=' + $.base64Encode(txt) + '&w=' + width + '&h=' + height;
			$(this).html(img);
		}
//		if ( $.browser.msie && $.browser.version.substr(0,1)<7 ) {
//			$(this).parent().pngFix(); // TODO: Wellicht weer aanzetten?
//		}
	});
}

function replaceUrls() {
	// TODO: Check for SSL.
	var basePath = 'http://' + document.domain + AbsPath; 
	var absPathLength = AbsPath.length;
	var basePathLength = basePath.length;
	$('a[href][turned!=true][rel!=NoReplace][target!=_blank]').each(function() {
		var lnk = $(this).attr('href'); 
		// Do not match uploads
		if ( lnk.match(/\/upload\//) == null ) {
			if ( lnk.substr(0, basePathLength) == basePath || lnk.substr(0, absPathLength) == AbsPath ) {
				if ( lnk.substr(0, basePathLength) == basePath ) {
					var link = lnk.substr(basePathLength);
				} else {
					var link = lnk.substr(absPathLength);
				}
						
				$(this).attr('href', '#' + link).bind('click', function() {
					//handleRequest(link);
					return true;
				});
			}
			$(this).attr('turned', true);
		} // else: matched so don't change the url.
	});
	photoGalleries();
	setLinksActive(); // the urls are replaced, so now check for the links which should be active.
}

function replaceSearch() {
	var submit = $('#Search input[type=submit]');
	var action = $(submit.attr('form')).attr('action');
	var anchor = $(document.createElement('A'));
	
	$("input[type=text][value]").each(function() {
		$(this).attr('defaultValue', $(this).attr('value'));
	});
	
	$('#searchInput').bind('focus', function() {
		if ( $(this).attr('value') == $(this).attr('defaultValue') ) {
			$(this).attr('value', '');
		}	
	}).bind('blur', function() {
		if ( $(this).attr('value') == '') {
			$(this).attr('value', $(this).attr('defaultValue') );
		}
	}).autocomplete(AbsPath + 'includes/autocomplete.php', {
		multiple: false,
		matchContains : false,
		dataType: 'json',
		parse: function(data) {
            return $.map(data, function(row) {
                return {
                    data: row,
                    value: row.Naam,
                    result: row.Naam
                }
            });
        },
        formatItem: function(data, i, n, value) {
            return data.Naam;
        }        
	}).result(function(e, item) {
        //handleRequest(item.Location);
		//alert('Goto: ' + item.Location);
		window.location.href = '#' + item.Location;
    });
	
	var loc = action.substr(AbsPath.length);
	
	anchor.attr('href', action);
	anchor.click(function(ev) {
		//handleRequest($(this).attr('href'));
		if ( $('#searchInput').attr('value') == $('#searchInput').attr('defaultValue') )
			return false;
		
		$('.Menu li').removeClass('Active');
		$(this).addClass('SearchActive');
		
		window.location.href = '#' + loc + '?q=' + $('#searchInput').attr('value');
		ev.preventDefault();
		return false;
	});
	anchor.text(submit.attr('value'));
	submit.replaceWith(anchor);
	
	
}

/**
 * Fix IE6 problem with Fixed position
 * TODO: Remember the old XY coordinate and calculate with this
 * @return
 */
function fixFixed() {
	$('div').each(function() {
		try {
			if ( $(this).css('position') == 'fixed' ) {
				alert('in');
				$(this).css('position', 'absolute').css('left', 0).css('top', 0);
				$(this).css('width', $(window).width()).css('height', $(window).height() + "px");
				alert($(window).height());
				var old = $(this);
				$(document).bind('scroll', function() {
					$(old).css('left', $(document).scrollLeft());
					$(old).css('top', $(document).scrollTop());
				});
				alert('out');
			} // else not interested..
		} catch ( e ) {
			alert('Error in fixFixed();');
		}	
	});
}

function showPic(gallery, picNo) {
	var pics = gallery.data('imgs');
	for ( var i = 0; i < pics.length; i++ ) {
		if ( i == picNo ) {
			$(pics[i]).addClass('Show');
		} else {
			$(pics[i]).removeClass('Show');			
		}
	}
	var display = $(gallery).data('display');
	if ( display != undefined ) {// if undefined then we probably are creating a new gallery.
		//alert(parseInt(picNo)+1);
		$(gallery).data('display').text(translate('GALLERY_CURRENT_IMAGE',parseInt(picNo)+1,pics.length));
	}
	$(gallery).attr('currentPic', picNo);
}

function loadGallery(gallery, picture) {
	var picNum = $(picture).attr('picNum');
	$(gallery).attr('currentPic', picNum);
	
	var bg = $(document.createElement('div'));
	var container = $(document.createElement('div'));
	var content = $(document.createElement('div'));
	var navigation = $(document.createElement('div'));
	var images = $(document.createElement('div'));
	
	var pics = gallery.data('pics');
	var picCount = pics.length;
	var imgs = new Array(picCount);
	for ( var i = 0; i < picCount; i++ ) {
		var img = document.createElement('img'); // new Image();
		img.src = pics[i].attr('href');
		img.alt = pics[i].attr('title');
		img.setAttribute('picNum', i);
		img.className = "Picture";
		images.append(img);
		imgs[i] = $(img);//.attr('href', img.src).attr('title', img.alt);
	}
	$(gallery).attr('picCount', picCount);
	gallery.data('imgs', imgs);
	showPic(gallery, picNum);
	
	var callback = gallery.data('closeCallback');
	var close = $(document.createElement('a'));
	close.click(callback);
	close.addClass('Close');
	close.attr('href', '#');
	close.text(translate('GALLERY_CLOSE'));	
	
	navigation.addClass('navigation');
	
	navigation.append($(document.createElement('a')).attr('class', 'prev').text(translate('GALLERY_PREVIOUS_IMAGE')).click(function(ev){
		var picNum = parseInt(gallery.attr('currentPic'));
		var picCount = parseInt(gallery.attr('picCount'));
		var prev = picNum == 0 ? picCount - 1 : picNum - 1;
		showPic(gallery, prev);
		ev.preventDefault();
		return false;
	}).attr('href', '#'));	
	
	var display =$(document.createElement('span')).attr('class', 'display').text(translate('GALLERY_CURRENT_IMAGE',parseInt(picNum)+1,picCount));
	navigation.append(display);
	gallery.data('display', display);
	
	navigation.append($(document.createElement('a')).attr('class', 'next').text(translate('GALLERY_NEXT_IMAGE')).click(function(ev) {
		
		var picNum = parseInt(gallery.attr('currentPic'));
		var picCount = parseInt(gallery.attr('picCount'));
		var next = picNum + 1 < picCount ? picNum+1 : 0;
		showPic(gallery, next);
		ev.preventDefault();
		return false;
	}).attr('href', '#'));
	
	navigation.append(close);
	
	
	
	container.addClass('GalleryContainer');
	bg.addClass('Background');
	content.addClass('Content');
	navigation.append('<span class="Title">'+translate('GALLERY_TITLE')+'</span>');
	content.append(navigation);
	//content.append(close);
	content.append(images);
	container.append(bg);
	container.append(content);
	container.css('height', GetScreenHeight() + "px");
	container.hide();
	$(document.body).append(container);
	$(content).css('top', ($(document).scrollTop() + parseInt($(content).css('top'))) + "px");
	$(bg).css('opacity', 0.95);
	container.show();
}

function photoGalleries() {
	$('.PhotoGallery[turned!=true]').each(function() {
		var gallery = $(this);
		var pics = new Array();
		$(this).find('a.Picture').each(function(i, n) {
			$(this).click(function(ev) {
				ev.preventDefault();
				loadGallery(gallery, $(this));
				return false;
			}).attr('picNum', i);
			pics.push($(this));
		});
		$(this).data('pics', pics);
		$(this).data('closeCallback', function(ev) { 
			ev.preventDefault();
			$('.GalleryContainer').remove();
			return false;
		});
		$(this).attr('turned', true);
	});
}

function replaceMenus() {
	$('.Menu li a').click(function() {
		$('.Menu li').removeClass('Active');
		$('.SearchActive').removeClass('SearchActive');
		$(this).parent().addClass('Active');
		return true;
	}).mouseover(function(){
		$(this).parent().addClass('Hover');
	}).mouseout(function(){
		$(this).parent().removeClass('Hover');
	});
}

function replaceSubmenu() {
	$('#Submenu li a').click(function() {
		$('#Submenu li').removeClass('xActive');
		$(this).parent().addClass('xActive');
		clickedSubmenu = true;
		return true;
	}).mouseover(function(){
		$(this).parent().addClass('Hover');
	}).mouseout(function(){
		$(this).parent().removeClass('Hover');
	});
}

/**
 * Set the links related to the currect location active.
 * @return null
 */
function setLinksActive() {
	var url = location.hash.substr(1);
	var seperator = '/';
	var segments = url.split(seperator);
	var amount = segments.length; // possibilities
	var urls = [];
	for ( var i = 0; i < amount; i++ ) {
		var url = '';
		for ( var x = 0; x <= i; x++ )
			if ( segments[x].length > 0 )
				url += segments[x] + '/';
		if ( url.length > 0 )
			urls.push(url);
	}
	$('li a[target!=_blank][href]').each(function() {
		$(this).parent().removeClass('URLActive');
		$(this).parent().removeClass('Active'); // buh.. vies TODO: Remove the whole Active thing.
		for ( var i = 0; i < urls.length; i++) {
			if ( $(this).attr('href').endsWith(urls[i]) ) {
				$(this).parent().addClass('URLActive');
				break; // goto the next anchor, this one is already active.
			}
		}		
	});
		
}

$(document).ready(function() {

	pageFactory = new HttpPageFactory();
	
	replaceH();
	
	replaceUrls();
	
	replaceMenus();
	
	replaceSearch();
	
	$(window).bind( 'hashchange', function(){
		doGetPage(location.hash.substr(1));
	})

	// Indien er een hash gezet is dan laten we de flash animatie niet zien.. :-)
	if ( location.hash.substr(1).length > 2 ) {
		callJavascript(null);
		doGetPage(location.hash.substr(1));
	}
	
	//alert(fixer.getHash());
	//alert(location.hash.substr(1));
	
	$(document).mousemove(function(ev) {
		list.each(function() {
			var screenWidth = $(document).width();
			var width = $(this).width();
			var ratio = screenWidth / width + 35;
			var left = width - ev.pageX / ratio;
			$(this).css('background-position', left + 'px center');
		});
	});
	
	
	if ( showOverlay ) {
		//$('.MainHolder').hide();
	}
	photoGalleries();
	
	// set the menu item active.
	$('.Menu li a').each(function() {
		try {
			// check if our url ocurres in our text.. and set active
			if ( location.hash.substr(1).startsWith($(this).attr('href').substr(1)) ) {
				//alert('found!: ' + $(this).attr('href'));
				$(this).parent().addClass('Active');
			} else { // else: not the one..
				$(this).parent().removeClass('Active');
			}
		} catch ( e  ) { }
	});
	//alert(fixer.getHash());
	
	// Disable images
    $('img').live("contextmenu",function(e){return false;});
	
    setLinksActive();
    
});


function handleRequest(url) {

	var state = 1;
	if ( firstTime == true )
		state = 1;
	else if ( clickedSubmenu == true )
		state = 0;
	else
		state = 1;
		//alert(clickedSubmenu + " : " + state);
	clickedSubmenu = false;
	firstTime = false;
	
	var page = pageFactory.CreatePage(url, state, firstTime);
	if ( page ) {
		page.show();
	} else {
		// page could not be created..
	}
}


function GetScreenHeight(){
	var Body = document.getElementsByTagName( 'body' ).item( 0 );
	var HTML = document.getElementsByTagName( 'html' ).item( 0 );
	return Math.max( HTML.offsetHeight, Body.offsetHeight );
}



//-- Downloaded

function doGetPage(href) {
	//href = jQuery.param.querystring(href, 'a=3&newValue=100');
	handleRequest(href);
	firstTime = false;
}

function translate(key) {
	var text = translations[key];
	var argv = Array.apply(null, arguments);
	argv[0] = text;
	//for ( var x in argv )
		//alert("Key: " + text + " value var: " + x);
	return $.sprintf.apply(this, argv);
}
