//Iñtërnâtiônàlizætiøn
var xmlFileName = 'menu.xml';
var contentPath = 'content/';
var site = 'http://www.guu-gua.dk/';

google.load('search', '1', {language : 'da', style : google.loader.themes.GREENSKY});

$(document).ready(function() {
	var pageID = getPageID();

	if(pageID == 'sitemap')
	{
		//we found the keyword sitemap - load it
		ParseXml(contentPath+xmlFileName, loadSiteMap, parseFailed);			
		
		//set onclick event on site logo
		$('#topmenulogo').click(function(){
			window.location.replace(site);
		});
	}
	else if(pageID < 0) //google crawler
	{
		//we found a page id - but since google cant crawl ajax we let php take care of it
	}
	else //if(pageID > 0 || pageID == 0)
	{
		//build normal page
		ParseXml(contentPath+xmlFileName, loadMenu, parseFailed);			

		//set onclick event on site logo
		$('#topmenulogo').click(function(){
			setDefaultPage();
		});
	}

	//add facebook icon
	$('#leftmenubottom').html("<a href='http://www.facebook.com/group.php?gid=16324254948' target='_blank'><img src='facebook.png' border='0' /></a><br /><iframe src='http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.guu-gua.dk&amp;layout=button_count&amp;show_faces=true&amp;width=142&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:142px; height:21px' allowTransparency='true'></iframe>")
	
	//animate facebook icon - reset animation to startout point and start it (again)
	$('#leftmenubottom').animate({left: '-=142'}, 0, function(){
		$('#leftmenubottom').animate({left: '+=142'}, 5000);
	});		

	//animate the hover info
	$('#topmenulogo').hover(
	  function () {
		$(this).css('cursor', 'pointer');
		$(this).html("<div class='popup'>Logoet er tegnet af illustratoren Nille Strønæs, tegnestuen Tusindfryd</div>");
	  }, 
	  function () {
		$(this).css('cursor', 'auto');
		$(this).html("");
	  }
	);

	//animate the info popup
	$('#topmenupopup').html("<div class='popup2'>Tryk på logoet for at komme tilbage til forsiden</div>")
	$('#topmenupopup div').hide().delay(1000).fadeIn(2500).delay(5000).fadeOut(2500);
});

function ParseXml(filename, successFunc, errorFunc){
	$.ajax({
		type: "GET",
		url: filename,
		cache: true,
		ifModified: true,
		contentType: "text/xml; charset=utf-8",
		dataType: "xml",
		success: successFunc,
		error: errorFunc
	});
}

function ParseHtml(filename, successFunc, errorFunc){
	$.ajax({
		type: "GET",
		url: filename,
		cache: false,
		ifModified: true,
		contentType: "text/html; charset=utf-8",
		dataType: "html",
		success: successFunc,
		error: errorFunc
	});
}

function parseFailed(request, description, innerError)
{
	$('#content').html('<div class="error">Error: Failed to parse xml.<br>Description: ' + description + '<br>Inner error: ' + innerError.message + '</div>');
}

function getLink(menuItem, isSiteMap){
	//get title if it is defined
	var menuTitle = menuItem.attr('title');
	if(menuTitle === undefined)	menuTitle = '';
	
	//get id if it is defined
	var menuId = menuItem.attr('id');
	if(menuId === undefined) menuId = '';

	//return the a tag
	if(isSiteMap === true){
		return $('<a href="?'+menuId+'" id="'+menuId+'" title="'+menuTitle+'">'+menuTitle+'</a>');
	}else{
		return $('<a href="#!'+menuId+'" id="'+menuId+'" title="'+menuTitle+'">'+menuTitle+'</a>');	
	}
}

function getPageID()
{
	var idString = '';
	var isGoogleSearch = false;
	
	//check if the id is in url after '?' or '?_escaped_fragment_'
	var searchs = window.location.search.split('?');
	if(searchs.length > 1)
	{
		var googleSearchs = window.location.search.split('?_escaped_fragment_');
		if(googleSearchs.length > 1)
		{
			isGoogleSearch = true;
			idString = googleSearchs[1];
		}
		else
		{
			idString = searchs[1];
			//we found something, but its in the search - so set url to have the same value in #
			window.location.replace(site+'#!'+idString);
		}
	}

	//check if the id is in url after '#' or '#!'
	var hashs = window.location.hash.split('#');
	if(hashs.length > 1)
	{
		var googleHashs = window.location.hash.split('#!');
		if(googleHashs.length > 1)
		{
			idString = googleHashs[1];
		}
		else
		{
			idString = hashs[1];
		}
	}

	//send pageID back, if idString contains a string
	var pageID = parseInt(idString);
	if(pageID !== undefined && !isNaN(pageID))
	{
		if(isGoogleSearch){
			//send negative number to shold its google bot search through the site
			return -pageID;
		}else{
			return pageID;
		}
	}
	
	//if it is a keyword send that back
	if(idString == 'sitemap')
	{
		return idString;
	}

	return 0;
}

function setDefaultPage(){
	var topMenuElements = $('#topmenu ul li a[id]');
	if(topMenuElements.length > 0){
		//fake that its a first time load situation
		window.location.hash = '!'+topMenuElements.first().attr('id');
		topMenuElements.first().click();
	}else{
		$('#content').html('<div class="error">Could not find any pages to show</div>');
	}
}

//call to build the top menu. Builds topmenu and triggers buildMenu()
function loadMenu(xml)
{
	var hasBeenClicked = false;

	//startup an unordered list to contain the topMenuItems
	var topmenu = $('<ul></ul>')
	
	//run through the topmenu elements in the xml file
	$(xml).find('topmenu topmenuitem').each(function(){
		var xmlChildren = $(this).children('sidemenu').children('sidemenuitem');

		//build top menu item
		var topMenuItem = $('<li></li>');
		if($(this).attr('title') === undefined) topMenuItem.css('display', 'none');
		var topMenuId = $(this).attr('id');
		
		//build link
		var link = getLink($(this));
		link.click(function(){
			$('#leftmenu').slideUp('fast', function(){
				if(getPageID() == 0)
				{
					//set the topMenuItems id as pageID, if we are in a first time load situation
					window.location.hash = '!'+topMenuId;
				}
				
				//build side menu, and load content if its empty
				$('#leftmenu').html(buildMenu(xmlChildren));
				
				//set chosen top menu item as "selected" (and all others as unselected)
				$('#topmenu ul li a').removeAttr('class');
				link.attr('class', 'selected');
				
				//show new side menu
				$('#leftmenu').slideDown('fast');
			});
		});	
		
		//check if one of the children has the pageID
		var linkElements = $(this).find('[id][id="'+getPageID()+'"]');
		if(!hasBeenClicked && linkElements.length > 0){
			//if one of the children has the pageID, then load that sidemenu
			hasBeenClicked = true;
			link.click();
		}
		
		//add link and top menu item to top menu
		topMenuItem.html(link)
		topMenuItem.appendTo(topmenu);
	});

	$('#topmenu').html(topmenu);
	
	if(!hasBeenClicked){
		setDefaultPage();
	}
}

//recursive call to build the side menu. Builds sidemenues and triggers loadPage()
function buildMenu(sideMenuItems){
	//set ul tag around the list of li tags
	var sideMenu;
	var hasBeenClicked = false;

	if(sideMenuItems.length > 0){
		//startup an unordered list to contain the sideMenuItems
		sideMenu = $('<ul></ul>');
		
		//add each for the menu items to the 'sideMenu'
		sideMenuItems.each(function(){
			var sideMenuItem = $('<li></li>');
			
			//add child nodes (we have to do this before adding link, and then prepend link. Otherwise the link will be in the bottom or we will override the link)
			sideMenuItem.html(buildMenu($(this).children('submenu').children('submenuitem')));
			
			//add a menu item that is a link
			if($(this).attr('title') === undefined) sideMenuItem.css('display', 'none');
			var link = getLink($(this)); 

			//add click event to the link
			var sideMenuFilename = $(this).attr('filename');
			var sideMenuId = $(this).attr('id');
			link.click(function(){
				//only load if the page is not allready loaded
				if($(this).attr('class') == ''){
					if(sideMenuFilename !== undefined){
						//load html file into content
						$('#content').fadeOut('fast', function(){
							ParseHtml(contentPath+sideMenuFilename, loadPage, parseFailed);
							//set chosen side menu item as "selected" (and all others as unselected)
							$('#leftmenu ul li a').removeAttr('class');
							link.attr('class', 'selected');
							//we are finished loading - lets show everything to the user
							$('#content').fadeIn('fast', function(){
								//update url to fit the page
								window.location.hash = '!'+sideMenuId;
							});
						});
					}
				}
				//Since the link is collapsible, we should toggle all submenuitems. 
				//However the A tag is sibling to these submenuitems, so we use this way to find them
				$(this).siblings().slideToggle();
			});
			
			sideMenuItem.prepend(link);
			
			
			//check if one of the children has the pageID
			var linkElements = $(this).find('[id][id="'+getPageID()+'"]');
			if(linkElements.length > 0){
				//if one of the children has the pageID, we want to show it. Otherwise default is hidden.
				//However the A tag is not child but a sibling to these submenuitems, so we use this way to find them
				link.siblings().show();
			}else{
				link.siblings().hide();
			}
			
			//check if this has the pageID
			if(sideMenuId == getPageID()){
				//if this has the pageID, click the link
				hasBeenClicked = true;
				link.click();
			}

			//add the collected nodes to the parent node (sideMenu)
			sideMenuItem.appendTo(sideMenu);
		});
	}else{
		sideMenu = $('');
	}
	
	return sideMenu;
}

//add content to page
function loadPage(html){
	//fill content
	$('#content').html(html);
	
	//we have to check both http://www.site.extension and http://site.extension
	var siteWithOutWWW = site.replace('www.', '');

	//IE: if the img url is not full path (aka its relative), add contentPath in front of it
	$('#content img[src][src^="'+site+'"]').not('[src^="'+site+contentPath+'"]').each(function(){
		$(this).attr('src', $(this).attr('src').replace(site, site+contentPath));
	});	
	//IE: if the img url is not full path (aka its relative), add contentPath in front of it
	$('#content img[src][src^="'+siteWithOutWWW+'"]').not('[src^="'+siteWithOutWWW+contentPath+'"]').each(function(){
		$(this).attr('src', $(this).attr('src').replace(siteWithOutWWW, siteWithOutWWW+contentPath));
	});
	//Firefox: if the img url is not full path (aka its relative), add contentPath in front of it
	$('#content img[src]:not([src^="http"])').each(function(){
		$(this).attr('src', site+contentPath+$(this).attr('src'));
	});

	//IE: if the hyper ref is not full path (aka its relative), add contentPath in front of it
	$('#content a[href][href^="'+site+'"]').not('[href^="'+site+contentPath+'"]').each(function(){
		if($(this).attr('href').substring(site.length, site.length+1) != "#"){
			$(this).attr('href', $(this).attr('href').replace(site, site+contentPath));
		}
	});
	//IE: if the hyper ref is not full path (aka its relative), add contentPath in front of it
	$('#content a[href][href^="'+siteWithOutWWW+'"]').not('[href^="'+siteWithOutWWW+contentPath+'"]').each(function(){
		if($(this).attr('href').substring(siteWithOutWWW.length, siteWithOutWWW.length+1) != "#"){
			$(this).attr('href', $(this).attr('href').replace(siteWithOutWWW, siteWithOutWWW+contentPath));
		}
	});
	//Firefox: if the hyper ref is not full path (aka its relative), add contentPath in front of it
	$('#content a[href]:not([href^="http"])').each(function(){
		if($(this).attr('href').substring(0,1) != "#"){
			$(this).attr('href', site+contentPath+$(this).attr('href'));
		}
	});
}

//build site map
function loadSiteMap(xml)
{
	$('#leftmenu').html('<ul><li><a href="?">Tilbage til forsiden</a></li><li><a href="?sitemap" class="selected">Sitemap og søgning</a></li></ul>');
	
	//build the site map
	var siteMapContainer = $('<div></div>');
	siteMapContainer.css('margin', '10px');
	buildSiteMap($(xml).find('topmenu topmenuitem')).appendTo(siteMapContainer);

	//build the search bar
	var searchContainer = $('<div>Loading...</div>');
	searchContainer.css('width', '100%');
	searchContainer.attr('id', 'cse');
	
	//build a table add sitemap and search to them. We use table since the width i variable
	var table = $('<table><tr></tr></table>');
	table.css('width', '100%');

	var siteMapCell = $('<td></td>')
	siteMapContainer.appendTo(siteMapCell);
	siteMapCell.appendTo(table);
	
	var searchCell = $('<td></td>')
	searchContainer.appendTo(searchCell);
	searchCell.appendTo(table);
	
	//add table as content
	$('#content').html(table);

	startupGoogleSearch();
}

//recursive function to build the sitemap
function buildSiteMap(xml){
	var siteMap = $('<ul></ul>')
	if(xml.length > 0) 
	{
		$(xml).each(function(){
			var subSiteMap = $('<li></li>');
			if($(this).attr('filename') === undefined){
				var title = $(this).attr('title')
				if(title === undefined){
					subSiteMap.html('<a href="?"><img border=0 src="favicon.ico" /></a>');
				}else if(title.length == 0){
					subSiteMap = $('<span></span>');
				}else{
					subSiteMap.html(title);
				}
			}else{
				subSiteMap.html(getLink($(this), true));
			}
			subSiteMap.append(buildSiteMap($(this).children('sidemenu').children('sidemenuitem')));
			subSiteMap.append(buildSiteMap($(this).children('submenu').children('submenuitem')));
			subSiteMap.appendTo(siteMap);
		});
	}else{
		siteMap = $('');
	}
	return siteMap;
}

function startupGoogleSearch(){
	google.setOnLoadCallback(function() {
		var customSearchControl = new google.search.CustomSearchControl('011780285506715163930:4q3ckj0yuko');
		customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
		customSearchControl.draw('cse');
	}, true);
}
