var _logMsg, _logTtl, lastHistoryState, tipBox;

var PROXIMITY 	= 300.0;
var MENU_INIT 	= {'x':156, 'width':500, 'mouseLeft':0, 'mouseRight':500, 'maxWidth':600, 'addWidth':200, 'show':5, 'first':0, 'total':8};	
var ICONS_INIT  = {'width':100, 'height':100, 'y':40, 'addX':20};
var ICONS_OVER 	= {'width':140, 'height':140};

var tipTxt  	= new Array();
var urlPattern 	= /^(http|https):\/\/[A-Za-z0-9\-\.\ä\ö\ü]+(\/)/i;
var hashPattern = /(\#)?(\#\/)?(\/\/)?/i;
var isFlash 	= false;
var _groups 	= ['agentur', 'arbeit', 'neues', 'kontakt'];

var STRIP_FIRST = 0;
var STRIP_LAST  = 1;
var STRIP_BOTH  = 2;

function log(msg, title){
	if($('#log').length > 0 && msg != _logMsg || title != _logTtl){
		_logMsg = msg;
		_logTtl = title;
		if(msg != undefined && title != undefined){
			$('#log > div')
			.prepend('<br /><p><b>'+title+'</b> <span>'+msg+'</span></p>')
			.attr({scrollTop: $('#log').attr('scrollHeight')})
			.find('p:nth-child(even)').addClass('even');
		} else {
			$('#log')
			.append(msg.replace(/^([^:]*):(.*)$/, '<p><b>$1:</b> <span class="$1">$2</span></p>'))
			.attr({scrollTop: $('#log').attr('scrollHeight')})
			.find('p:nth-child(even)').addClass('even');
		}
	}
}

jQuery.fn.aPosition = function(){
	thisLeft = this.offset().left;
	thisTop = this.offset().top;
	thisParent = this.parent();
	parentLeft = thisParent.offset().left;
	parentTop = thisParent.offset().top;
	return {
		left: thisLeft-parentLeft,
		top: thisTop-parentTop
	}
}

function mergeUri(uri, addHash){
	var ret = '';
	ret = uri.replace(urlPattern, '');
	ret = (addHash==true) ? baseAdd + '/' + ret : ret;
	log(ret, "mergeUri");

	return ret;
}

function pushHistory(uri, logTitle){
	var newUri = '';
	if(uri != "" && uri.indexOf('.jpg')==-1 && uri.indexOf('.gif')==-1 && uri.indexOf('.png')==-1){
		newUri = mergeUri(uri, false);
		history.pushState(null, "", newUri);
		log(newUri, logTitle);
	}
}

function stripHash(uri){
	uri = uri.replace(hashPattern, "");
	//uri = stripSlashes(uri, STRIP_LAST);
	return uri;
}

function stripSlashes(uri, mode){
	var old_uri = uri;
	if(mode == STRIP_FIRST || mode == STRIP_BOTH){
		if( uri.substr(0, 2) == "//" ){
			uri = uri.substr(2);
		}
		if( uri.substr(0, 1) == "/" ){
			uri = uri.substr(1);
		}
	}
	if(mode == STRIP_LAST || mode == STRIP_BOTH){
		if( uri.substr((uri.length - 2), 2) == "//" ){
			uri = uri.substr(0, (uri.length - 2));
		}
		if( uri.substr((uri.length - 1), 1) == "/" ){
			uri = uri.substr(0, (uri.length - 1));
		}
	}
	return uri;
}

function initUrlListeners(isDevMode){
  
  if(window.location.href.indexOf('#') == -1){
	var newUri = mergeUri(window.location.href, true);
	//history.replace(baseUrl + newUri);
	window.location.href = newUri;
  } else {
	  if(isDevMode == true){
	  	$('body').prepend('<div id="log"><button id="bt_reload" onclick="top.location.href=\'{{ baseUrl }}\'">Reload</button><br /><div></div></div>');
	  }
	  // Event handlers
	  // pushHistory(window.location.href, 'initUrlListeners');
	  $.address.init(function(event) {
		pushHistory(event.value, 'initUrlListeners');
		//$('a').address(function() {
		//return $(this).attr('href').replace(baseUrl, '');
		//});
	  }).change(function(event) {
		  log(event.value, 'change');
	      //event.preventDefault();
	  }).internalChange(function(event) {
		  log(event.value, 'internalChange');
		  //pushHistory(event.value, 'internalChange');
	  }).externalChange(function(event) {
		  log(event.value, 'externalChange');
		  //pushHistory(event.value, 'externalChange');
	  });
  }
}

function tellAFriend()
{
	var subject = "Thielker+Team";
	var body_message = "Schau mal: \n\n"+location.href; 
	var myWindow = window.open("mailto:?subject="+subject+"&body="+body_message);
	myWindow.close();
}

function addToFavorites()
{
	if(window.external && document.all){
		//ie
		window.external.AddFavorite(location.href, "Thielker+Team");
	} else {
		showAddToFavoritesInfo();
	}
}

function showAddToFavoritesInfo()
{
	alert("Bitte benutzen Sie die Bookmark-Funktion Ihres Browsers, um die Seite zu Ihren Favoriten hinzuzufuegen.\n\nIhr Thielker+Team\n");
}

/**
* Update tooltip text and position
* @return true
*/
function updateTooltip(tipItem, mouseX)
{
	var first = MENU_INIT.first;
	var show  = MENU_INIT.show;
	
	var i     = tipItem.data('i');
	var id	  = tipItem.attr('id');
	
	if(i >= first && i <= (first + show))
	{
		tipBox.css('left', mouseX + 5);
		tipBox.html(tipTxt[id]);
		tipBox.show();
	}	
}

/**
* Navigate icons (prev/next )
* @return true
*/
function dockSlide(direction)
{
	var mnu   = $('.iconmenu');
	var first = MENU_INIT.first;
	var total = MENU_INIT.total;
	var show  = MENU_INIT.show;
	var posX  = parseInt(mnu.css("marginLeft"));

	if(direction == "left" && first > 0){
		MENU_INIT.first = first - 1;
		
	} else if(direction == "right" && (first < total - show)){
		MENU_INIT.first = first + 1;
	}
	
	var newX = MENU_INIT.x - (MENU_INIT.first * (ICONS_INIT.width + ICONS_INIT.addX + 2));
	mnu.animate({"marginLeft":newX + "px"}, "medium");
	
	updateDockIcons();
}

/**
* Init Dock items (set position)
* @return true
*/
function initDockIcons()
{
	var num = 0;
	var dock_boxes = $(".iconmenu").find("li");
	
	// find active icon
	$.each(dock_boxes, function(){
		if( $(this).attr('id') == 'current' ){ MENU_INIT.first = num; }
		num++;
	});
	
	for(var j=0; j<MENU_INIT.show; j++){
		if(MENU_INIT.first > (MENU_INIT.total - MENU_INIT.show)){
			MENU_INIT.first -= 1;
		}
	}
	
	if(MENU_INIT.first < 0){
		MENU_INIT.first = 0;
	}
	
	if(MENU_INIT.total - 1 > MENU_INIT.show)
	{			
		var btMoveLeft  = $('<div id="moveLeft"><div></div></div>').prependTo('body');
		var btMoveRight = $('<div id="moveRight"><div></div></div>').prependTo('body');
		
		btMoveLeft.bind("click",function(event) {
			dockSlide("left");
		});
		
		btMoveRight.bind("click",function(event) {
			dockSlide("right");
		});
		
		dockSlide(null);
		
	} else {
				
		var newX = MENU_INIT.x + (MENU_INIT.maxWidth - (MENU_INIT.total * (ICONS_INIT.width + ICONS_INIT.addX)))/2;
		$('.iconmenu').css("marginLeft", newX + "px");
		
		updateDockIcons();
	}
}

/**
* Update dock items (set transparency) and enable/disable prev/next
* @return true
*/
function updateDockIcons()
{
	
	var first = MENU_INIT.first;
	var total = MENU_INIT.total;
	var show  = MENU_INIT.show;
	
	var i = 0;
	var dock_boxes = $(".iconmenu").find("li");
	
	$.each(dock_boxes, function() {
		var a = 1;
		if(i < first){ a = 0;}
		if(i > first + (show-1)){ a = 0;}
		$(this).fadeTo("medium", a);
		i++;
	});

	if(total > show){
		if(first == 0){
			$("#moveLeft").hide();
			$("#moveRight").show();
		} else if((first + show) == total) {
			$("#moveLeft").show();
			$("#moveRight").hide();
		} else {
			$("#moveLeft").show();
			$("#moveRight").show();
		}
	}
}

/**
* Calculate the height of an icon based upon its position from the mouse
* @param icon
* @param mouse position (x only)
* @return new width/height
*/
function calculateDockIconSize(icon, mousePosX, mousePosY) {
	// get the distance in x from the mouse to the icon
	var oldW = parseInt(ICONS_INIT.width);
	var oldH = parseInt(ICONS_INIT.height);
	var oldY = parseInt(ICONS_INIT.y);
	
	var newW = parseInt(ICONS_OVER.width);
	var newH = parseInt(ICONS_OVER.height);
	
	var xProximity 	= Math.abs(mousePosX - $(icon).offset().left - (newW/2.0));
	
	// if we need to vary the height because the mouse is within range
	if (xProximity<PROXIMITY) {
		// get the percentage height the icon needs to be
		var newRatio = ((PROXIMITY-xProximity)/PROXIMITY);
		
		var addW = newRatio * (newW-oldW);
		var addH = newRatio * (newH-oldW);
		var addY = newRatio * oldY;
		
		// add the additional percentage to the icon
		return [(oldW + addW), (oldH + addH), (oldY - addY)];
	} else {
		// otherwise, return the original icon size
		return [oldW, oldH, oldY];
	}
}

function initStatic()
{	
	tipBox  = $('<div id="dynTooltip"></div>').prependTo('body');
	
	// Add 'external' CSS class to all external links
	$("a").filter(function() {
    	return (this.hostname && location.hostname !== this.hostname);
	}).attr('rel', 'external');
	
	$("a").each(function(i) {
		if( $(this).attr('rel') == 'external' ){
			$(this).attr('target', '_blank');
		}
	});
	
	$('.gotoTop').click(function(){
		$('html, body').animate({scrollTop:0}, 'slow');
		return false;
	});
	
	$('#bookmark').click(function(){
		addToFavorites();
	});
	
	$('#recommend').click(function(){
		tellAFriend();
	});
	
	$(".tooltip").each(function(i) {
		
		var tipItm = $(this);
		var tipImg = $(this).find("img");
		var newId  = '#tooltip_'+i;
		
		tipItm.attr('id', newId);
		tipItm.data('i', i);
		
		if(tipItm.attr('title')){
			tipTxt[newId] = tipItm.attr('title');
			tipItm.removeAttr('title');
		} else if(tipImg.attr('alt')){
			tipTxt[newId] = tipImg.attr('alt');
			tipImg.removeAttr('alt');
			tipImg.attr('valign', 'bottom');
		}

		tipItm.bind("mouseleave", function(event) {
			tipBox.hide();
		});
		
		tipItm.bind("mouseenter", function(event) {
			updateTooltip($(this), event.pageX);
		});
		
		tipItm.bind("mousemove", function(event) {
			updateTooltip($(this), event.pageX);
			//var itemPosY = $(this).offset().top - 60;
			//tipBox.css('top', itemPosY);
			//tipBox.css('left', event.pageX + 5);
			//tipBox.show();
		});
	});
	
	if($('.iconmenu').length > 0)
	{
		$(".iconmenu").hide().each(function(i) {
			// private variables
			var dock = $(this);
			var dock_icons = dock.find("li a img");
			
			var dock_width = (dock_icons.length * (parseInt(ICONS_INIT.width)+parseInt(ICONS_INIT.addX))) + parseInt(MENU_INIT.addWidth);
			dock.css('width', dock_width);
			dock.css('marginLeft', parseInt(MENU_INIT.x) + "px");
			
			MENU_INIT.width = dock_width;
			MENU_INIT.first = 0;
			MENU_INIT.total = dock_icons.length;
			
			//event handlers
			dock.bind("mouseleave",function(event) {			
				$.each(dock_icons, function() {
					$(this).animate({
						"width": parseInt(ICONS_INIT.width) + "px",
						"height": parseInt(ICONS_INIT.height) + "px",
						"marginTop": parseInt(ICONS_INIT.y) + "px"
					},"fast");
				});
			});
			
			dock.bind("mousemove", function(event) {			
				$.each(dock_icons, function() {
					var newSize = calculateDockIconSize($(this), event.pageX, event.pageY);
					
					$(this).stop();
					$(this).width(newSize[0]);
					$(this).height(newSize[1]);
					$(this).css("marginTop", newSize[2]);
				});
			});
			
			initDockIcons();
		}).fadeIn();
	} else {
		$('#content').css('marginTop', '-270px');
	}
}
