/*
CODE UNDER GNU PUBLIC LICENSE
see http://www.gnu.org/

Author:...Felix Eggmann, FLX Labs
Date:.....Feb 2011

*/
// Standard jQuery header
;(function($) {


    /* check if is mobile to handle content divs a different way */
    $.ismobiledevice = (navigator.userAgent.match(/iPhone/i) != null)+(navigator.userAgent.match(/iPod/i) != null)+(navigator.userAgent.match(/iPad/i) != null)+(navigator.userAgent.match(/android/i) != null)+(navigator.userAgent.match(/blackberry/i) != null)+(navigator.userAgent.match(/mobi/i) != null);
    // general settings
    $.cnconfig = {
	'mapMargin':12,
	'mapW':4000,
	'mapH':2000,
	'mapZoomSpeed':1500,
	'mapDotFadeSpeed':200,
	'subnavSlideSpeed':200,
	'slideshowSlideSpeed':300
    };
    var mapScale = .0;
    var mapScaleTarget = 1.0;
    var subnavHeight = 0;

    var mapDots = [];
    // ----------------------------------------------------
    // using hash info to display contents
    var checkPageHash = function(){
	if(document.location.hash){
	    $('#nav a').each(function(){
		if($(this).attr('href').indexOf(document.location.hash) != -1){
		    $(this).click();
		}
	    });
	}
    }
    // ----------------------------------------------------
    // loading pictures on a page (extract url from <a>, overwrite with img)
    var loadPicPage = function(el){
	var posDesc = function(el){
	    el
		.css({
		    'top':el.prev().position().top,
		    'left':el.prev().position().left
		})
		.width(el.prev().width()-40)
	    ;
	}
	
	el.find('.picture a').each(function(){
	    im = $('<img/>');
	    $(this).parent().prepend(im);
	    im
		.attr('src',$(this).attr('href'))
		.load(function(){posDesc($(this).next())})
	    ;
	});
	el.find('.picture a').remove();
	el.find('.picture > div').each(function(){
	    posDesc($(this));
	    $(this)
		.hide()
		.mouseout(
		    function(){$(this).fadeOut('slow')}
		)
		.prev().mouseover(
		    function(){$(this).next().fadeIn('slow')}
		)
	});
	el.find('.col2 .picture > div').css('left',0);
    }
    // ----------------------------------------------------
    // try to extract a page item link and open it
    var clickDirect = function(el){
	clickedId = el.attr('href');
	if(clickedId.indexOf('#')>-1){
	    clickedId = clickedId.substring(clickedId.indexOf('#'));
	}
	if($(clickedId).length){// found an element with the id, open up!
	    // move unused pages to bottom of stack
	    $('.page').css('z-index',0);
	    // put element with id to visible area and z-index 10
	    $(clickedId).show().css({'left':0,'z-index':10});
	    $('#content').css('top',$('#content').height()).animate({'top':0},'slow').addClass('open');
	    $('#content').show();
	}
    }
    // ----------------------------------------------------
    // dragging scrollbar
    /* set scrollbar */
    var scrollableHeight = function(){
	return $('#nav .act > ul').height();
	var liheights = 0;
	$('#nav .act li').each(function(){
	    liheights+=$(this).height();
	});
	return liheights;
    }
    var updateScrollable = function(maxY,posY){
		    // get width of scrollable area
		    var scrollH = scrollableHeight();
	scrTo = 1.*(scrollH - $('.scrollable.act').innerHeight()) / maxY * posY;
	scrTo = 1.*(scrollH - $('.scrollable.act').innerHeight()) / maxY * posY;
		    //$('#nav .scrollable ul').clearQueue().animate({'margin-top':-scrTo},10);
	$('#nav .scrollable ul').css({'margin-top':-scrTo});
    }
    var setScrollThumb = function(_diffX){
	var maxY = $('.scrollbar').innerHeight()-$('.scrollbar .thumb').height()-2;
	var posY = $('.scrollbar .thumb').position().top-_diffX;
	
	if(posY < 0)
	    posY = 0;
	if(posY > maxY)
	    posY = maxY;
	
	$('.scrollbar .thumb').css('top',posY);
	updateScrollable(maxY,posY);
    }
    var oldMX = 0;
    var oldMY = 0;
    var drag = function(e){
	setScrollThumb(oldMY-e.pageY);
	oldMX = e.pageX;
	oldMY = e.pageY;
    }
    var startdrag = function(e){
	oldMX = e.pageX;
	oldMY = e.pageY;
	$(document).bind('mousemove',drag);
	$(document).bind('mouseup',stopdrag);
    }
    var stopdrag = function(e){
	$(document).unbind('mousemove',drag);
	$(document).unbind('mouseup',stopdrag);
    }
    // ----------------------------------------------------
    // toggle subnav
    var viewSubnav = function(el){
	$('#nav .scrollbar').remove();
	
	var setScrollbarTop = function(){
	    //_parentH = $('#nav .scrollable.act').parent().find('a').height()+7;
	    //h = $('#nav .scrollable.act').position().top-_parentH;
	    t = $('#nav .scrollable.act').position().top - ($('#nav .scrollable.act').parent().height() - $('#nav .scrollable.act').height())
	    h = el.height()+$('#nav .scrollable.act').parent().find('a').height()+4;
	    if($('#nav .scrollable.act > ul')[0].className == 'story'){
		t-=4;
		h+=4;
	    }
	    $('#nav .scrollbar').css('top',t-4).height(h);
	};

	el.find('ul').css('margin-top',0);
	// close all to measure unfilled space
	$('#nav .act').removeClass('act').slideUp($.cnconfig['subnavSlideSpeed'],function(){
	    setScrollbarTop();
	});
	el.css({'margin-top':0,'height':'auto','max-height':subnavHeight}).addClass('act').slideDown($.cnconfig['subnavSlideSpeed'],function(){
	    // check if scrollbars needed
	    var liheights = scrollableHeight();
	    if(liheights > parseInt($('#nav .act').height())+1+($.browser.msie?3:0)){
		$('#nav').prepend('<div class="outerscrollbar"><div class="scrollbar"><div class="thumb"></div></div></div>');
		//el.before('<div class="outerscrollbar"><div class="scrollbar"><div class="thumb"></div></div></div>');
		
		// prepare scrollbar
		// -----------------
		$('.scrollbar .thumb')
		    .click(function(e){e.stopPropagation();})
		    .mousedown(startdrag)/* thumb mousedown begins */;
		$('.scrollbar ')
		    .click(function(e){
			// is it above thumb?
			if(e.pageY < $('.scrollbar .thumb').offset().top){
			    setScrollThumb($('#nav .scrollbar .thumb').height());
			}
			else{
			    setScrollThumb(-$('#nav .scrollbar .thumb').height());
			}
		    });
		// enable scrollbar
		$('#nav .scrollbar').hide()
		    .css({'left':el.width()+11})
		    .height(el.height()+$('#nav .scrollable.act').parent().find('a').height()+4)
		    .fadeIn();
	    //$('#nav .scrollbar').css('top',12)
	    setScrollbarTop();
		diff = $('#nav .act').height() / liheights * $('#nav .act').height();
		//diff = liheights / $('#nav .act').height() * $('#nav .act').height();
		//$('#nav .scrollbar .thumb').css({'height':diff,'top':0});
		$('#nav .scrollbar .thumb').css({'height':20,'top':0});
		//
	    }
	});
	
    }
    // ----------------------------------------------------
    // function to zoom in/out world
    var zoomMapIn = function(cX,cY){
	mapScaleTarget = 1.;
	//$('#mappic .dot.act div').stop().fadeOut($.cnconfig['mapDotFadeSpeed']);//hide dotname
	$('#mappic .dot').hide();
	    //.stop().fadeOut($.cnconfig['mapDotFadeSpeed']);//hide dot
	$('#mappic').stop().animate({//.delay($.cnconfig['mapDotFadeSpeed'])
		'left':-cX+$('#map').width()*.5,
		'top':-cY+$('#map').height()*.5
	},$.cnconfig['mapZoomSpeed']);
	$('#mappic img').stop().animate(//.delay($.cnconfig['mapDotFadeSpeed'])
	    {
		'width':$.cnconfig['mapW']*mapScaleTarget,
		'height':$.cnconfig['mapH']*mapScaleTarget
	    },$.cnconfig['mapZoomSpeed'],
	    function(){// map animation ends
		mapScale=mapScaleTarget;
		positionDots();
		$('#mappic .dot.act div').show();//show dotname
		$('#mappic .dot.act').removeClass('small').stop().fadeTo($.cnconfig['mapDotFadeSpeed'],0.8,positionDots);//show dot
	    })
    }
    var zoomMapOut = function(){
	mapScale = $('#map').width()/$.cnconfig['mapW'];
	$('#mappic .dot.act').stop().fadeOut($.cnconfig['mapDotFadeSpeed'],function(){$('#mappic .dot > div').hide();/*hide names*/});
	//$('#mappic .dot').fadeOut($.cnconfig['mapDotFadeSpeed']);
	$('#mappic').stop().animate({
		'left':0,
		'top':($.cnconfig['mapH']*mapScale-$('#map').height())*-.5
	},$.cnconfig['mapZoomSpeed']);
	$('#mappic img').stop().animate(
	    {
		'width':$.cnconfig['mapW']*mapScale,
		'height':$.cnconfig['mapH']*mapScale 
	    },$.cnconfig['mapZoomSpeed'],
	    function(){// map animation ends
		positionDots();
		//$('#mappic .dot').addClass('small').show().fadeIn($.cnconfig['mapDotFadeSpeed']);// make all dots small and show
		$('#mappic .dot').addClass('small').show();
//.stop().fadeTo($.cnconfig['mapDotFadeSpeed'],0.8,positionDots);// make all dots small and visible
	    });
    }
    // ----------------------------------------------------
    // createDots
    var createDots = function(el){
	    mapDots = new Array();
	    var i=0;
	    $('#nav li').each(function(){
		if(!($(this).attr('posX') || $(this).attr('posY')))
		    return;
		$(this)
		    .data('name',$(this).attr('name')+'')
		    .data('posX',parseInt($(this).attr('posX'))+0)
		    .data('posY',parseInt($(this).attr('posY'))+0)
		    .data('i',i);
		var dot = {'name':$(this).data('name'),'posX':$(this).data('posX'),'posY':$(this).data('posY')};
		mapDots[i] = dot;
		d = $('<div class="dot"/>').addClass('small').css({'left':dot['posX'],'top':dot['posY']-28}).data('i',i).append($('<div><span>'+dot['name']+'<br/><br/></span></div>').hide());
		$('#mappic').append(d);
		i++;
	    });
	
	if($.browser.msie){
	    $('#mappic .dot').css({'min-height':'40px','min-width':'12px','width':'auto','height':'auto'});
	}
    }
    // positionDots
    var positionDots = function(el){
	// position all of them if none is act
	if(!$('#mappic .dot.act')[0]){
	    for(i=0;i<mapDots.length;i++){
		dot = mapDots[i];
		$('#mappic .dot').eq(i).css({'left':dot['posX']*mapScale-6,'top':(dot['posY'])*mapScale-6-28});
	    }
	}
	else{
	    dot = mapDots[$('#mappic .dot.act').data('i')];
	    $('#mappic .dot.act').css({'left':dot['posX']*mapScale-6,'top':(dot['posY'])*mapScale-6-28});
	}
    }
    // ----------------------------------------------------
    // function to reposition all elements
    var resizeElems = function(){
	var h = $(window).height();
	var w = $(window).width();
	if(h < 600)
	    h=680;
	// ie6
	//if(($.browser.msie && parseInt($.browser.version)<=6)){
	    $('#main').css({'width':w,'height':h});
	//}
	//resize map div
	$('#map')
	    .height(h-2*$.cnconfig['mapMargin']).width(w-2*$.cnconfig['mapMargin']);
	$('#map .framer')
	    .height(h-2*$.cnconfig['mapMargin']-10).width(w-2*$.cnconfig['mapMargin']-10);
	
	// calc map scale
	if(mapScale != 1.0){
	    mapScale = $('#map').width()/$.cnconfig['mapW'];
	    // resize map pic
	    $('#mappic img').width($.cnconfig['mapW']*mapScale).height($.cnconfig['mapH']*mapScale);
	    // repos dots
	    positionDots();
	    $('#mappic')
		.css('top',($('#mappic img').height()-$('#map').height())*-.5);
	}
	
	//resize nav
	$('#nav').css('max-height',$('#map').height()-40);
	// calc max possible subnav height
	subnavHeight = $('#map').height()-40-$('#nav').height()-$('#nav .act').height();
	
	//move #content to bottom
	$('#content').not('.open').css('top',h);
	$('#content, #content .page').css({'width':w,'height':h});
	// vertical align canvas min height:667
	$('#content .canvas').css('margin-top',(h-500)*.5);
    }
    
    $(document).ready(function() {
	//$('html').bind('dragstart.jsp selectstart.jsp', function() { return false; });

	if(!$.ismobiledevice){
	    // load huge map
	    $('#mappic img').attr('src','themes/flurinarothenberger/img/map_huge.png');
	}
	// disable text selection
	document.onmousedown = function (e) { return false; }
	document.onselectstart = function(e) {return false;} // ie
	
	// hide content 
	$('#content').hide();
	
	$('#nav > ul > li:last').css('border',0);
	
	// prepare pages
	$('.page').each(function(){
	    $(this).append('<div class="nav"><div class="prev"></div><div class="close"></div><div class="next"></div></div>');
	    if($(this).prev('.page').length==0)
		$(this).find('.prev').addClass('prevblock').removeClass('prev');
	    if($(this).next('.page').length==0)
		$(this).find('.next').addClass('nextblock').removeClass('next');
	});
	
	// navigate through page panels, click left right or close
	// left (prev)
	$('.page .nav .prev').click(function(){
	    if($('.page.intransition')[0])
		return;
	    
	    var p = $(this).parents('.page');
	    p.width($('#content').width());
	    if(p.prev('.page').length){
		loadPicPage(p.prev('.page'));
		p.prev('.page').show().css({'left':0,'z-index':1});
		// move out from screen (to the right)
		$(this).parents('.page').addClass('intransition').animate({'left':$('#content').width()},$.cnconfig['slideshowSlideSpeed'],function(){
		    $(this).removeClass('intransition');
		    p.css('z-index',0).prev('.page').css('z-index',10);
		});
	    }
	});

	// right (next)
	$('.page .nav .next').click(function(){
	    if($('.page.intransition')[0])
		return;
	    
	    p = $(this).parents('.page');
	    p.width($('#content').width());
	    if(p.next('.page').length){
		loadPicPage(p.next('.page'));
		p.next('.page').css({'left':0,'z-index':1}).show();
		// move out from screen (to the left)
		$(this).parents('.page').addClass('intransition').animate({'left':-$('#content').width()},$.cnconfig['slideshowSlideSpeed'],function(){
		    $(this).removeClass('intransition');
		    p.hide().css('z-index',0).next('.page').css('z-index',10);
		});
	    }
	});
	
	
	// close content panel
	$('.page .nav .close').click(function(){
	    $('#content').animate({'top':$('#content').height()},'fast',function(){$(this).find('.page').hide(); window.scrollTo(0,0);}).removeClass('open');
	});

	// hover buttons and links
	$('.page .nav > div, .page a').hover(
	    function(e){$(this).fadeTo('fast',.6)},
	    function(e){$(this).fadeTo('fast',1.)}
	);
	
	// hide content
	//$('#content').hide();
	//css('top',$('#content').height());
	
	// close all subnavs
	$('#nav > ul > li > .scrollable').height(0);
	// prepare navigation for subnav toggle
	$('#nav > ul > li > a').click(function(e){
	    if($(this).parent().find('.scrollable').length){
		e.preventDefault();
		viewSubnav($(this).parent().find('.scrollable'));
	    }
	    else{// direct link
		e.preventDefault();
		clickDirect($(this));
		$(this).addClass('visited');
	    }
	});
	// click on subnav
	$('#nav > ul ul > li > a').click(function(e){
	    e.preventDefault();
	    // direct link?
	    clickDirect($(this));
	    $(this).addClass('visited');
	});
	// map navigation
	$('#nav .scrollable > ul > li > a').hover(
	    function(e){
		if($(this).parent().data('posY') && !$(this).hasClass('.act')){
		    e.preventDefault();
		    // remove act class from others and add to actual
		    $('#mappic .dot').removeClass('act').eq($(this).parent().data('i')).addClass('act');
		    zoomMapIn($(this).parent().data('posX'),$(this).parent().data('posY'))
		}
	    },
	    function(e){
		if($('#mappic .dot').eq($(this).parent().data('i')).hasClass('open'))
		    return e;
		e.preventDefault();
		zoomMapOut();
		$('#mappic .dot.act').removeClass('act');
	    }
	).click(function(){
		$('#mappic .dot').eq($(this).parent().data('i')).addClass('open');
	});

	// dots
	createDots();

	// scrollbars
	//$('#scrollbar1').tinyscrollbar();
	$('#nav .scrollbar').hide();
    });
    
    $(window).load(function() {
	
	// resize callback
	// ----------------------------------------
	$(window).bind("resize", function(){
	    resizeElems();
	    return;
	}); // end resize callback
	$(window).resize();
	
	$('#overlay').fadeOut('slow');

	checkPageHash();
	
    }); // end window load
})(jQuery);
