var desktop;
$(document).ready(function() {
	desktop = loadDesktop('console');
	animateNavigation(); // after desktop!
	initDesktopBookmarks();
});


var myFileName = "index.html" // !!!! must be correct!!

var baseUrl = "";
var openWindows = new Array(); // saves alle the window to be opened
var openWindowsIndex = 0;
var openWindowsPositions = new Object(); // if saved in cookie --> positions

var redirectionUri = '';

var activeId;
var windowId = 0;

var openingAnimationDivCreated = false;

// window to parent object
var togetherness		 = new Array();
// to block new opening save the basic togetherness
var togethernessBasic	 = new Array();
// main window to icon
var togethernessToIcon	 = new Array();
// all opened windows
var openedWindows		 = new Array();
// opened by
var windowOpenedBy 		 = new Array();

// cookie life
var cookieDays = 360;




// better browser detection
var b = navigator.userAgent.toLowerCase();
	// Figure out what browser is being used
	jQuery.browser = {
		safari: /webkit/.test(b),
		opera: /opera/.test(b),
		msie: /msie/.test(b) && !/opera/.test(b),
		msie6: /msie 6.0/.test(b) && !/opera/.test(b),
		msie5: /msie 5/.test(b) && !/opera/.test(b),
		mozilla: /mozilla/.test(b) && !/(compatible|webkit)/.test(b)
	};

var useAjax = true;

function initDesktopBookmarks()
{
	
	// IE --> AJAX test
	if($.browser.msie)
	{
		var ajaxTest = new ActiveXObject("Msxml2.XMLHTTP") 
		if(typeof ajaxTest != 'object' )
		{
			useAjax = false;
		}
	}
	
	// ajax ok!
	if(useAjax)
	{
	
		var uri = document.location + ''; //making a string
		uri = uri.replace("%23","#"); // replacing encoding
		uri = uri.replace("%23","#"); // replacing encoding
		
		//  bookmarked ? 
		if(uri.indexOf(myFileName) != -1)
		{
			baseUrl = uri.substr(0,uri.indexOf(myFileName));
		}
		else if(uri.indexOf("##") != -1)
		{
			baseUrl = uri.substr(0,uri.indexOf("#"));
		}
		else
		{
			baseUrl = uri;
		}
	
		//--------- windows ---------------
		// bookmarked before cookie - after all redirection in front!

		// save redirection uri
		if((uri.indexOf("###") != -1))
		{
			redirectionUri = uri;
		} 

		// openBookmarkedWindow has to be started
		startOpenBookmarkedWindow = false;

		// bookmark before cookie !
		// bookmark and not an redirection (bookmark : ## / redirection: ###)
		if((uri.indexOf("##") != -1) && (uri.indexOf("###") == -1)) 
		{
			uri = uri.split("#");
			if(uri[2].split("?").length > 1)
			{
				openWindows = uri[2].split("?");

				
			}
			
			startOpenBookmarkedWindow = true;
			
			// open!
			openBookmarkedWindow();	
		}
		else
		{ // cookie
			if(readCookie("vi-press-windows"))
			{
				var cookieValues = readCookie("vi-press-windows").split("#");
				
				for(var i = 0; i < cookieValues.length; i++)
				{
					// insert only once
					if(!openWindows.contains(cookieValues[i].split("?")[0]))
					{
						openWindows.push(cookieValues[i].split("?")[0]);
						if(typeof cookieValues[i].split("?")[1] != "undefined")
						{
							openWindowsPositions[baseUrl + cookieValues[i].split("?")[0]] = cookieValues[i].split("?")[1];
						}
					}
				}
				
				startOpenBookmarkedWindow = true;
				// open!
				openBookmarkedWindow();
			}
		}

		
		// redericted and not yet started ?
		if(!startOpenBookmarkedWindow)
		{
			// reset
			openWindows = new Array();
			openWindowsIndex = 0;
			uri = uri.split("#");
			if(uri.length >= 4)
			{
				if(uri[3].split("?").length > 1)
				{
					openWindows = uri[3].split("?");
				}
				redirectionUri = '';
				
				// open!
				openBookmarkedWindow();	
			}
		}		
		
		//--------- icons ---------------
		
		
		// saved icon-positions?`
		if(readCookie("vi-press-icons"))
		{ // saved icons positions
		
			var cookieValues = readCookie("vi-press-icons").split("#");			
			for(var i = 0; i < cookieValues.length; i++)
			{
				if(typeof cookieValues[i].split("?")[1] != "undefined")
				{
					$("a#"+cookieValues[i].split("?")[0]).css("left",cookieValues[i].split("?")[1].split(":")[0] + "px");
					$("a#"+cookieValues[i].split("?")[0]).css("top",cookieValues[i].split("?")[1].split(":")[1] + "px");
				}
			}
			
		}
		
		// make navigation open new windows (iteration!)
		$("a.icon").each(function(){
			var iconHref = this.href;
			var thisIcon = this;
			
			$("ul#prim-nav a").each(function(){
					if(iconHref == this.href)
					{
						
						// open new window
						$(this).click(function(){
							openIcon(thisIcon);
							return false;
						});
					}
			});
				
		});
		
		
		// save windows in cookie by leaving the page
		onbeforeunload = saveToCookie;
		
		// pos windows before each other
		/*$("div#presse-content-zone").ajaxSuccess(function(request, settings)
		{
			
			// first window (!)
			var windowPosX = $("div.window")[0].offsetLeft;
			var windowPosY = $("div.window")[0].offsetTop;
			
			$("div.window").each(function()
			{
				$(this).css("left",windowPosX);
				$(this).css("top",windowPosY);
				
				windowPosX += 40;
				windowPosY -= 40;
				
			});	
		});	
		*/
	}
	
}

// openes recursive each window after the other
function openBookmarkedWindow()
{
	if((openWindows.length-1) > openWindowsIndex)
	{// -1 -> last one is always empty
	
		// first of all, let's see if we can find the opener
		var openerFound = false;
		var opener;
		$("a").each(function(){
			
			var linkHrefStr = this.href + '';
			if(openWindows[openWindowsIndex].length > 0 && linkHrefStr.indexOf("/"+openWindows[openWindowsIndex]) != -1 )
			{ // found
				openerFound = true;
				opener = this;

			}		
		});
		
		// opener found --> animate opening
		if(openerFound)
		{
			if($(opener)[0].className == "icon")
			{	// if icon, then open	
				$(opener).addClass("icon_active");
			}
			// load divs per ajax
			loadWindow(opener, opener.href, true);
		}
		// not found --> just open
		else
		{
			loadWindow('', openWindows[openWindowsIndex],true);
		}
	
		// next round - new window
		openWindowsIndex++;
		
		// ready - now open redirection 
		if(((openWindows.length-1) == openWindowsIndex) && redirectionUri != '')
		{
			// reset
			openWindows = new Array();
			openWindowsIndex = 0;

			redirectionUri = redirectionUri.split("#");
			if(redirectionUri[3].split("?").length > 1)
			{
				openWindows = redirectionUri[3].split("?");
			}
			redirectionUri = '';
			
			// open!
			openBookmarkedWindow();	
			
		}

	
		// not found? next widow?
		$("div#presse-content-zone").ajaxError(function()
		{
			openBookmarkedWindow();
		});
	}


}

function openIcon(pIcon)
{
		
	// show open icon
	$(pIcon).addClass("icon_active");
	
	// load divs per ajax
	loadWindow(pIcon, pIcon.href);

}

function loadWindow(source, href, onLoad)
{
	
	// if not allready opened
	if(!openedWindows.contains(source.href + ""))
	{
		openedWindows.push(source.href+"");
		
		try
		{
			$.ajax({
					 url: href,
					success: function(html)
					{
						// "imagetoolbar" craches IE 6
						html = html.replace("imagetoolbar", "");
						
						// replace paths
						var path = /..\/..\/..\//g;
						html = html.replace(path, "", "g");
																
						var layerContent = $(html).children("div#windows").children("div.window");
										
						$("div#presse-content-zone").append(layerContent);
						
						// register windows
						$("div.window").each(function()
						{
							// new id
							if(!this.id)
							{		
								windowId++;
								this.id = windowId;
								
								//make invisible
								$(this).css("visibility","hidden");
								
																							
								// do i know the opener?
								if(source != "")
								{ // unknown
									// icon?
									if(source.id.indexOf("icon") != -1)
									{
										togethernessToIcon[windowId] = source;
										windowOpenedBy[this.id] = source;
									}	
									else
									{ // not an icon, search for window opened by
									
										windowOpenedBy[this.id] =$(source).parents(".window")[0];		
									}
																		
									var windowObject = desktop.registerWindow(windowId);
									
									
									// add close-event
									$(this).find("a.close_window")[0].href = "javascript:;"; // disable the anchor
									$(this).find("a.close_window").click(function(){
										animateClosing(this);
										return false; // dont follow the anchor
									});
								}
								else
								{
	
									$(this).css("visibility", "visible").hide().show().fadeIn(200,function(){
													$(this).show();
									});
																		
									desktop.registerWindow(windowId);
																		
									
									// add close-event
									$(this).find("a.close_window")[0].href = "javascript:;"; // disable the anchor
									// no parent - just hide!
									$(this).find("a.close_window").click(function(){
										$(this).parents(".window").fadeOut(400,function(){
											$(this).hide();
										});
										return false; // dont follow the anchor
									});
								}
								// cookie? ->position
								if(onLoad && typeof openWindowsPositions[href] != "undefined")
								{
									// do i have to position the window
									var windowPosition = openWindowsPositions[href].split(":");
									
									windowObject.setPositionX(windowPosition[0]+"px");
									windowObject.setPositionY(windowPosition[1]+"px");
									windowObject.setWidth(windowPosition[2]);
									windowObject.setHeight(windowPosition[3]);
									$(this).css("z-index",windowPosition[4]);
									
									// find biggest z-index and set active
									setBiggestZIndexActive();
								}
								
								//animate opening process
								animateOpening(source, this, onLoad);
								
							}
						});

						// replace the intern links
						replaceLinks();
								
						// if onload - load all windows
						if(onLoad)
						{
							openBookmarkedWindow();
						}
						
					}
				  });
			}
			catch(e){}	
			
		}

}


function setBiggestZIndexActive()
{
	
	var biggestZIndex = 0;
	var windowWithBiggestZIndexId = 0;
	$("div.window").each(function()
	{
		if(biggestZIndex < $(this).css("z-index"))
		{
			biggestZIndex = $(this).css("z-index");
			windowWithBiggestZIndexId = this.id;
		}		
	});
	// reset z-index
	desktop.setBiggestZIndex(biggestZIndex);	
	
	return windowWithBiggestZIndexId;
}

function replaceLinks()
{ // replaces all the intern window-content-links
	
	// open on click
	$("a.window_link").click(function(event)
	{	
		// load divs per ajax
		loadWindow(this, this.href);		
		return false; // dont follow the anchor
	});
	
	// ignore dblclick
	$("a.window_link").dblclick(function(event)
	{		
		return false; // dont follow the anchor
	});
	
	// event set --> remove class
	$("a.window_link").removeClass();
		
	// replace the print icon and make it visible
	$("div.extended-icon-print").show().find("img").click(function(e){
		printPage($(this).parents(".window").find(".content"));
		e.stopPropagation();	
	});
	
	// show close window in overview window
	$("a.close_uebersicht").show()
	
}

function insertHeadline()
{
	
	var mainWindowId = setBiggestZIndexActive();

	$("h2#sifr").html($("div#"+mainWindowId).find("div.title h2").html());
	$("div.sIFR-replaced").removeClass("sIFR-replaced").html($("h2#sifr"));
	replaceSifr();
	
}


function animateOpening(from, to, onLoad)
{
	
	//  making bookmarkable
	var uri = document.location + ''; //making a string
	var fileName = from.href + '';
	fileName = fileName.replace(baseUrl, "");
	if(uri.indexOf("#") != -1)
	{
		uri = uri.replace("%23","#"); // replacing encoding
		uri = uri.split("#");
		// not allready bookmarked !
		if(uri[2].indexOf(fileName) == -1 && fileName != "undefined")
		{			
			document.location = uri[0] + "##" + uri[2] + fileName + "?";
		}
	}
	else
	{
		document.location = uri + "##" + fileName + "?";
	}	
	
	// generate div width border
	if(!openingAnimationDivCreated)
	{
		$("div#presse-content-zone").append("<div id='openingAnimationDiv' style='position: absolute; border: 2px solid #c0c0c0'>&#160;</div>");
		openingAnimationDivCreated = true;
	}
	
	var fromWidth = $(from).width();
	var fromHeight = $(from).height();
	
	var fromLeft = emToPx($(from).css("left"));
	var fromTop = emToPx($(from).css("top"));
	
	if(from.id.indexOf("icon") != -1)
	{ // it's an icon animation!
		
		fromWidth -= 70;
		fromHeight -= 70;
		fromTop += 15;
		fromLeft += 30;
	}

	// saves the togetherness
	togetherness[to.id] = from;
	togethernessBasic[to.id] = from;

	if(isNaN(fromLeft) || fromLeft == 0)
	{ // not set per css --> calculate		
		var fromLeft = getAbsolutePosition(from).x;
		var fromTop = getAbsolutePosition(from).y;
	}
	
	$("#openingAnimationDiv").css({
					    top: fromTop,
					    left: fromLeft,
					    width: fromWidth,
					    height: fromHeight,
					    zIndex: $(to).css("z-index")
			      }).animate({
					    top: emToPx($(to).css("top")),
					    left: emToPx($(to).css("left")),						 
					    width: $(to).width(),
					    height: $(to).height()
	
			      },250,function(){
				      
					    $(this).hide(1,function(){
						    $(to).css("visibility", "visible").hide().show().fadeIn(400,function(){
							    $(this).show();

								// if not onload and dblclick --> move to foreground
								if(!onLoad)
								{
									desktop.setObjectActive(this.id);
								}
								
								//insert the new headline
								insertHeadline(this);
								// init form
								initForm();
						    });
					    });
														      
			      });
}

function animateClosing(closingId)
{
	var window = $(closingId).parents(".window");

	//  remove bookmark link
	var uri = document.location + '';//making a string
	var fileName = $(togethernessBasic[window[0].id])[0].href + '';
	fileName = fileName.replace(baseUrl, "")
	if(uri.indexOf("#") != -1)
	{

		uri = uri.replace(fileName+"?", "");
		document.location = uri;
	}
	
	var fromLeft = emToPx(window.css("left"));
	var fromTop = emToPx(window.css("top"));
	
	var to = togetherness[window[0].id];
	var toBasic = togethernessBasic[window[0].id];
	var toLeft = emToPx($(to).css("left"));
	var toTop = emToPx($(to).css("top"));
	
	if(isNaN(toLeft) || toLeft == 0)
	{ // not set per css --> calculate		
		var toLeft = getAbsolutePosition(to).x;
		var toTop = getAbsolutePosition(to).y;
	}
	
	// connect children to my parent
     connectToParent(window);
	
	
	// hide window
	desktop.startAction("closeWindow",window[0].id);
	
	var toWidth = $(to).width();
	var toHeight = $(to).height();	
	if(to.id.indexOf("icon") != -1)
	{ // it's an icon animation!
		
		toWidth -= 70;
		toHeight -= 70;
		toTop += 15;
		toLeft += 30;
	}

	if($(to).width() == 0 && $(to).height() == 0)
	{// window allready closes --> other animation

		// start animation
		$("#openingAnimationDiv").css({
						top: toTop,
						left: toLeft,
						width: window.width(),
						height: window.height(),
						zIndex: $(to).css("z-index")
				  }).show().animate({
						top: (fromTop + window.width()/2),
						left: (fromLeft + window.height() / 2),						 
						width: 0,
						height: 0

				  },250,function(){
							
						$(this).hide();			
						$(window).hide().remove();	
						
						// insert the headline of the last open window
						insertHeadline(window);	
				  });
	}
	else
	{ // close to parent

		// start animation
		$("#openingAnimationDiv").css({
						top: fromTop,
						left: fromLeft,
						width: window.width(),
						height: window.height(),
						zIndex: window.css("z-index")
				  }).show().animate({
						top: toTop,
						left: toLeft,						 
						width: toWidth,
						height: toHeight

				  },250,function(){
						
						// was it opened by an icon ?
						if(typeof togethernessToIcon[window[0].id] == 'object')
						{
							// close icon
							$(togethernessToIcon[window[0].id]).removeClass("icon_active");

							togethernessToIcon[window[0].id] = ''; // delet from array
						}
						
						$(this).hide();
						
						$(window).hide().remove();	
						
						// insert the headline of the last open window
						insertHeadline();
				  });
	}
	
	// set window as closed
	togetherness[window[0].id] = '';
	togethernessBasic[window[0].id] = '';
	windowOpenedBy[window[0].id] = '';
	openedWindows[openedWindows.indexOf(toBasic.href)] = '';
	
	
}

function initForm(window)
{

	$(window).find("form").submit(function()
	{
		// ajax
		var html = $.ajax({
			  type: this.method,
			  url: this.action,
			  data: $(window).find("form :input").serialize(),
			  async: false}).responseText;
			
		// "imagetoolbar" craches IE 6
		html = html.replace("imagetoolbar", "");
		
		// replace paths
		var path = /..\/..\/..\//g;
		html = html.replace(path, "", "g");
												
		var layerContent = $(html).children("div#windows").children("div.window");
		
		var windowId = $(this).parents("div.window")[0].id;

		$(this).parents("div.content").html($(html).children("div#windows").find("div.content").html());
		
		// init form
		initForm();
			
		return false;
	});
}

// prints only the content
function printPage(content)
{
	
	var title = content.find("h3").html();
	var content = content.html();
	
	var a = window. open('','','scrollbars=yes,menubar=no,statusbar=no,width=500,height=700');
	a.document.open("text/html");
	a.document.write('<html><head><title>'+title+'</title></head><body style="padding-left:20px;background-image:none;background-color:#FFFFFF;">');
	a.document.write(content);
	a.document.write('</body></html>');
	a.focus();
	a.print();
}


function connectToParent(window)
{
	// update the children
	for(i in windowOpenedBy)
	{
		if(windowOpenedBy[i] == window[0])
		{			
			togetherness[i] = togetherness[window[0].id];
			windowOpenedBy[i] = windowOpenedBy[window[0].id];
		} 
	}
	

	
	
}

function saveToCookie()
{
	
	/******* windows ************/
	// collect all open windows
	var windowsAndPositionsString = '';
	$("div.window").each(function(){
		
		var fileName  = togethernessBasic[this.id].href + '';
		fileName = fileName.replace(baseUrl, "");
		windowsAndPositionsString += fileName + "?" + getAbsolutePosition(this).x + ":" + getAbsolutePosition(this).y + ":" + $(this).width() + ":" + $(this).height() + ":" + $(this).css("z-index") + "#";
		
	});
	// cookie value: filename?x:y:width:heigh:z-index#
	createCookie("vi-press-windows",windowsAndPositionsString,cookieDays);
	

	/******* icons ************/
	// collect all icons
	var iconsPositionsString = '';
	$("a.icon").each(function(){
		

		iconsPositionsString += this.id + "?" + getAbsolutePosition(this).x + ":" + getAbsolutePosition(this).y + "#";
		
	});
	// cookie value: filename?x:y:width:heigh:z-index#
	createCookie("vi-press-icons",iconsPositionsString,cookieDays);
			
}





