var thumbs = [];
var type = "home";

var rowWidth = 9;
var imageTotal = $('#content ul li').length;
var imageCount = 0;

var currentPage = '';
var currentPhoto = '';
var currentXMLHttpRequest = null;
var timeoutID = -1;
var isInited = false;

var contact;
var senja_logo;
var IS_ON_BOTTOM = true;
var PASS = true;

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera",
			versionSearch: "Version"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};

function checkAndChangeLogoPosition(){                
    contact = document.getElementById("contact");
    senja_logo = document.getElementById("senja_logo");
    if (contact != null){
        var bottom_con = contact.offsetHeight + getTopPosition(contact);
        var right_con = contact.offsetWidth + getLeftPosition(contact);
        var top_logo = getTopPosition(senja_logo);
        
        // if still on bottom
        if (IS_ON_BOTTOM){
            if ((bottom_con + 10) >= top_logo){
                document.getElementById("senja_logo").className = document.getElementById("senja_logo").className.replace(/\bsenja_float_bottom\b/,"class_x")
                IS_ON_BOTTOM = false;
                PASS = false;
            }
        }
        if ((!IS_ON_BOTTOM) && PASS){
            if ((bottom_con + 10) < top_logo){
                document.getElementById("senja_logo").className = document.getElementById("senja_logo").className.replace(/\bclass_x\b/,"senja_float_bottom")
                IS_ON_BOTTOM = true;
            }
        }
        $('#senja_logo').css('opacity', '0');
        $('#senja_logo').stop().animate({opacity: 1.0}, {duration:300});
        PASS = true;
        
        // debug
        //$('#message').html("ON_BOTTOM: " + IS_ON_BOTTOM);
    }
}

function getTopPosition(obj){
    var topValue= 0;
    while(obj){
        topValue+= obj.offsetTop;
        obj= obj.offsetParent;
    }
    return topValue;
}

function getLeftPosition(obj){
    var leftValue= 0;
    while(obj){
        leftValue+= obj.offsetLeft;
        obj= obj.offsetParent;
    }
    return leftValue;
}

function onFancyboxClose(){
	prevPhoto = currentPhoto = '';
	var h = currentPage;
	//alert('close '+currentPage);
	window.location.hash = h;
}

function menuLoad(id, type, url) {
	if (currentPage == id){ 
		if (currentPhoto != prevPhoto){
			if (currentPhoto != ''){
				//alert('click '+currentPhoto+' '+prevPhoto);
				$('#photo_'+currentPhoto).trigger('click');
			} else {
				//alert('close '+currentPhoto+' '+prevPhoto);
				if (prevPhoto && prevPhoto != ''){
					$.fancybox.close();
				} else {
					onFancyboxClose();
				}
			}
		}
		return;	
	}
	
	// abort the ongoing request if any
	if (currentXMLHttpRequest != null) currentXMLHttpRequest.abort();
	
	if (currentPage != '') {
		$('#nav-'+currentPage).removeClass('current');
	}
	currentPage = id;
	$('#nav-'+currentPage).addClass('current');
	
	$('#content').html('');

	//document.location.href = document.URL.split("#")[0] + "#" + currentPage;
	if (currentPhoto == ''){
		if (prevPhoto && prevPhoto != ''){
			$.fancybox.close();
		} else {
			onFancyboxClose();
		}
	}
	
	if (type == 'general') {
		$('#load-animation').css('display', 'block');
		$.ajax({
			type: 'GET',
			url: url,
			dataType: 'text',
			beforeSend : function(XMLHttpRequest) {
				currentXMLHttpRequest = XMLHttpRequest;
			},			
			error: function(request, error) {
			},
			success: function(data) {
				currentXMLHttpRequest = null;
				$('#load-animation').css('display', 'none');
				$('#content').append($(data));
                $('#content').css('opacity', '0');
                $('#content').stop().animate({opacity: 1.0}, {duration:300});
                
                // create LOGO SENJA
                
                checkAndChangeLogoPosition();
                window.onresize = function(event) {
                    checkAndChangeLogoPosition();
                    // check again
                    if (IS_ON_BOTTOM){
                        checkAndChangeLogoPosition();
                    }
                }
			}
		});	
	} else if (type == 'gallery') {
		$('#load-animation').css('display', 'block');
		$.ajax({
			type: 'GET',
			url: url,
			dataType: 'text',
			beforeSend : function(XMLHttpRequest) {
				currentXMLHttpRequest = XMLHttpRequest;
			},			
			error: function(request, error) {
				// alert(request + ' ' + error);
			},
			complete: function (xhr, status) {
				// alert(status);
			},
			success: function(data) {
				currentXMLHttpRequest = null;
				setGallery(data);
			}
		});	
	}
}

function setGallery(data) {
	// xml fixed on IE
	var xml = null;
	if( window.DOMParser ) {
		parser = new DOMParser();
        xml = parser.parseFromString(data ,"text/xml" ) ;
	} else { // Internet Explorer
		xml = new ActiveXObject( "Microsoft.XMLDOM" ) ;
		xml.async = "false" ;
		xml.loadXML(data);
	}
	
	// $('#content').html('');
	$('#content').html('<ul>');
	$(xml).find('img').each(function(index){
		var thumb = $(this).attr('thumb');
		var image = $(this).attr('image');
		var slug = $(this).attr('slug');
		var type = $(this).attr('type');
		var newDiv = document.createElement("li");
		newDiv.innerHTML = '<a id="photo_'+slug+'" rel="group" href="' + image + '" type="' + type + '"><img src="' + thumb + '" alt="thumb" height="75" width="75" /></a>';
		// $('#content ul').append($('<li><a href="' + image + '"><img src="' + thumb + '" alt="thumb" /></a></li>'));
		$('#content ul').append(newDiv);
	});
	galleryInit();
}

function galleryInit() {
	// make all images invisible before fully loaded
	$('#content ul li').each(function (index) {
		$(this).css('display', 'none');
	});

	// variables re-init
	thumbs = [];
	imageTotal = $('#content ul li').length;
	// alert(imageTotal);
	imageCount = 0;        
	
	isInited = false;
	
	// images loading counter
	$('#content ul li a img').each(function(index){
		if (this.complete || this.readyState === 4) {
			if (++imageCount == imageTotal) {
				init();
			}
		} else {
			$(this).bind('load', function(e){	
				if (++imageCount == imageTotal) {
					init();
				}
			});
		}
	});
	
	setTimeout(init, 4000);
}

// gallery actual init, called after all images have been loaded
function init() {
	if (isInited) return;
	
	isInited = true;

	$('#load-animation').css('display', 'none');
	
	thumbs = [];
	$('#content ul li').each(function (index) {
		thumbs.push($(this));
		$(this).css('display', 'block');
		var rowIndex = Math.floor(thumbs.length / rowWidth);
		var columnIndex = (thumbs.length % rowWidth == 0) ? rowWidth : thumbs.length % rowWidth;
		$(this).delay((rowIndex + columnIndex) * 100).animate({opacity: 1.0}, {duration:100});
	});
	setTimeout(activateThumbs, (rowWidth + Math.floor(thumbs.length / rowWidth) - 1) * 100);
	
	BrowserDetect.init();
	var uagent = navigator.userAgent.toLowerCase();
	
	// init the fancybox
	$("#content ul li a").each(function() {
		if($(this).attr("type") == "image"){
			if(uagent.search("iphone") > -1 || uagent.search("ipad") > -1 || uagent.search("android") > -1){
				var anchor = this;
				$(this).fancybox({
					cyclic: true,
					padding: 0,
					margin: 0,
					hideOnOverlayClick: true,
					hideOnContentClick: true,
					overlayOpacity: 1,
					overlayColor: '#FFF',
					// centerOnScroll: true,
					autoScale: true,
					titleFormat: formatTitle,
					showCloseButton: false,
					showNavArrows: false,
					changeSpeed: 100,
					changeFade: 100,
					titlePosition: 'over',
					centerOnScroll: true,
					onComplete: function(){
						prevPhoto = currentPhoto = $(anchor).attr('id').replace('photo_','');
						var h = currentPage + "/" + currentPhoto;
						//alert('complete '+h);
						window.location.hash = h;
					},
					onClosed: onFancyboxClose
				});
			}
			else{
				var anchor = this;
				$(this).fancybox({
					cyclic: true,
					padding: 0,
					margin: 0,
					hideOnOverlayClick: true,
					hideOnContentClick: true,
					overlayOpacity: 1,
					overlayColor: '#FFF',
					// centerOnScroll: true,
					autoScale: true,
					titleFormat: formatTitle,
					showCloseButton: false,
					showNavArrows: false,
					changeSpeed: 100,
					changeFade: 100,
					titlePosition: 'over',
					centerOnScroll: true,
					onComplete: function(){
						prevPhoto = currentPhoto = $(anchor).attr('id').replace('photo_','');
						var h = currentPage + "/" + currentPhoto;
						//alert('complete '+h);
						window.location.hash = h;
					},
					onClosed: onFancyboxClose
				});
			}
		}
		else{
			if($(this).attr("href").match(/vimeo/) == "vimeo"){
				var anchor = this;
				var vim = this.href.split("/");
				var url = "http://vimeo.com/moogaloop.swf?clip_id="+vim[3]+"&amp;fullscreen=1";
				var mov = '<object width="560" height="340"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id='+vim[3]+'&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=1&amp;color=ffffff&amp;fullscreen=1&amp;autoplay=0&amp;loop=0" /><embed src="http://vimeo.com/moogaloop.swf?clip_id='+vim[3]+'&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=1&amp;color=ffffff&amp;fullscreen=1&amp;autoplay=0&amp;loop=0" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="560" height="340"></embed></object>';
				$(this).fancybox({
					cyclic: true,
					padding: 0,
					margin: 0,
					'width'	: 560,
					'height' : 340,
					hideOnOverlayClick: true,
					hideOnContentClick: true,
					overlayOpacity: 1,
					overlayColor: '#FFF',
					// centerOnScroll: true,
					autoScale: false,
					titleFormat: formatTitle2,
					showCloseButton: false,
					showNavArrows: false,
					//changeSpeed: 100,
					//changeFade: 100,
					'href'			: url,
					'type'			: 'swf',
					'swf'			: {
						'wmode'		: 'transparent',
						'allowfullscreen'	: 'true'
					},
					onComplete: function(){
						$('#fancybox-content').width(560);
						$('#fancybox-content').height(340);
						$('#fancybox-wrap').css({'left' : '400px', 'top' : '150px', 'width' : '560px', 'height' : '340px'});
						$('#fancybox-title').css({'left' : '580px'});
						$('#text_bottom').hide();
						$('.fancybox-ie #fancybox-content').html('');
						$('.fancybox-ie #fancybox-content').html(mov);
						$('.fancybox-ie #fancybox-wrap').css({'left' : '400px', 'top' : '150px', 'width' : '560px', 'height' : '340px'});
						$('.fancybox-ie #fancybox-outer').css({'width' : '560px', 'height' : '340px'});
						$('.fancybox-ie #fancybox-content').css({'width' : '560px', 'height' : '340px'});
						$('.fancybox-ie #fancybox-title').css({'left' : '580px'});
						$('.fancybox-ie #text_bottom').hide();
						prevPhoto = currentPhoto = $(anchor).attr('id').replace('photo_','');
						var h = currentPage + "/" + currentPhoto;
						//alert('complete '+h);
						window.location.hash = h;
					},
					onClosed: onFancyboxClose
				});
				//$('#fancybox-wrap').width(560);
			}
			else{
				var anchor = this;
				var vim = this.href.replace(new RegExp("watch\\?v=", "i"), 'v/').split("/");
				var mov = '<object width="560" height="340" data="http://www.youtube.com/v/'+vim[4]+'" type="application/x-shockwave-flash"><param name="src" value="http://www.youtube.com/v/'+vim[4]+'" /></object>';
				$(this).fancybox({
					cyclic: true,
					padding: 0,
					margin: 0,
					'width'	: 560,
					'height' : 340,
					hideOnOverlayClick: true,
					hideOnContentClick: true,
					overlayOpacity: 1,
					overlayColor: '#FFF',
					// centerOnScroll: true,
					autoScale: false,
					titleFormat: formatTitle2,
					showCloseButton: false,
					showNavArrows: false,
					//changeSpeed: 100,
					//changeFade: 100,
					'href'			: this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
					'type'			: 'swf',
					'swf'			: {
						'wmode'		: 'transparent',
						'allowfullscreen'	: 'true'
					},
					onComplete: function(){
						$('#fancybox-content').width(560);
						$('#fancybox-content').height(340);
						$('#fancybox-wrap').css({'left' : '400px', 'top' : '150px', 'width' : '560px', 'height' : '340px'});
						$('#fancybox-title').css({'left' : '580px'});
						$('#text_bottom').hide();
						$('.fancybox-ie #fancybox-content').html('');
						$('.fancybox-ie #fancybox-content').html(mov);
						$('.fancybox-ie #fancybox-wrap').css({'left' : '400px', 'top' : '150px', 'width' : '560px', 'height' : '340px'});
						$('.fancybox-ie #fancybox-outer').css({'width' : '560px', 'height' : '340px'});
						$('.fancybox-ie #fancybox-content').css({'width' : '560px', 'height' : '340px'});
						$('.fancybox-ie #fancybox-title').css({'left' : '580px'});
						$('.fancybox-ie #text_bottom').hide();
						prevPhoto = currentPhoto = $(anchor).attr('id').replace('photo_','');
						var h = currentPage + "/" + currentPhoto;
						//alert('complete '+h);
						window.location.hash = h;
					},
					onClosed: onFancyboxClose
				});
				//$('#fancybox-wrap').width(560);
			}
		}
		
		if (currentPhoto != prevPhoto){
			if (currentPhoto != ''){
				//alert('click2 '+currentPhoto+' '+prevPhoto);
				$('#photo_'+currentPhoto).trigger('click');
			} else {
				//alert('close2 '+currentPhoto+' '+prevPhoto);
				if (prevPhoto && prevPhoto != ''){
					$.fancybox.close();
				} else {
					onFancyboxClose();
				}
			}
		}
	});
};

function formatTitle(title, currentArray, currentIndex, currentOpts) {
    // return '<div id="tip7-title"><span><a href="javascript:;" onclick="$.fancybox.prev();"><img src="/data/closelabel.gif" /></a></span>' + (title && title.length ? '<b>' + title + '</b>' : '' ) + 'Image ' + (currentIndex + 1) + ' of ' + currentArray.length + '</div>';
	return 	'<div id="prigge-fancybox-panel">'+
			'<a href="javascript:;" onclick="$.fancybox.close();"><div id="prigge-fancybox-button-close"></div></a>'+
			'<a href="javascript:;" onclick="$.fancybox.next();"><div id="prigge-fancybox-button-next"></div></a>'+
			'<a href="javascript:;" onclick="$.fancybox.prev();"><div id="prigge-fancybox-button-prev"></div></a>'+
			'</div>';
}

function formatTitle2(title, currentArray, currentIndex, currentOpts) {
    // return '<div id="tip7-title"><span><a href="javascript:;" onclick="$.fancybox.prev();"><img src="/data/closelabel.gif" /></a></span>' + (title && title.length ? '<b>' + title + '</b>' : '' ) + 'Image ' + (currentIndex + 1) + ' of ' + currentArray.length + '</div>';
	return 	'<div id="prigge-fancybox-panel">'+
			'<a href="javascript:;" onclick="$.fancybox.close();"><div id="prigge-fancybox-button-close"></div></a>'+
			'</div>';
}

function activateThumbs() {
	$('#content ul li').not('.current').mouseover(function() {
		for (i = 0; i<thumbs.length; i++) {
			thumbs[i].stop().animate({opacity: 0.7}, {duration:300});
		}
		$(this).stop().animate({opacity: 1.0}, {duration:400});
	});
	$('#content ul li').not('.current').mouseout(function() {
		for (i = 0; i<thumbs.length; i++) {
			thumbs[i].stop().animate({opacity: 1.0}, {duration:300});
		}
	});
}

$('#navigation ul li a').focus(function(){
     $(this).blur();
});

