//DISABLE GLOBAL CACHING
$.ajaxSetup({cache:false});

//GLOBAL VARIABLES
var menuDimension = new Array();
    menuDimension['width'] = 735;
    menuDimension['height']= 129;
var subMenuEntryHeight = 15;
var menuArrowWidth = 10;
var menuArrowHeight = 13;
var menuFontSize = 12;
var rightBoarder = 10;

//redirect to corresponding ajax item after language switch. 
//Array, where the order, specifies the click sequence.
var redirectOptions = new Array();
//update the link befor sending it as POST
function getRedirectionOptions(link){
	((redirectOptions.length == 0)?link+='':link +='?');
	for (var x=0; x < redirectOptions.length; x++){
		link += 'citem'+ x + '=' +redirectOptions[x] + ((x<redirectOptions.length-1)?'&':'');
	}
	return link;
}

//useed to get options and simulate clicks respectively
$(document).ready(function(){
	var options = getUrlVars()  //getQueryParams(document.location.search);
	setTimeout( function(){
		for (op in options){	
			//alert(options[op]); //elementName = ;
			if ( op.indexOf("citem") != -1){ 
				($( ( ('#'+options[op]).replace('.','\\.') )   ).parent().parent().attr('id') == 'submenuitems')?($('#submenu').slideDown('slow')):"";
				$( ( ('#'+options[op]).replace('.','\\.') )   ).click();
				$( ( ('#'+options[op]).replace('.','\\.') )   ).attr('class','active')  ; //.toggleClass('active') <-- not working in IE...
			}
		}
	}, 100);
});

// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
    var vars = {};
    var hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars[hash[0]] = hash[1];
    }

    return vars;
}


//menu content. If new elements have to be added to the page do it here, the rest will be generated automaically 
//menuItems[i] --> [[MainTitleGerman, MainTitleGermanLink] , [MainTitleEnglish, MainTitleEnlgishLink]]
var menuItems = 
[
	[ 
		[["START","/index.html"],["START","/english/index.html"]] 
	],
	[
		[["Vision", "/inst_vision.html"],["Vision","/english/inst_vision.html"]],
		[["Team","/inst_team.html"],["Team","/english/inst_team.html"]],
		[["&Uuml;ber uns","/inst_about.html"],["About us","/english/inst_about.html"]],
		[["Beirat","/inst_beirat.html"],["<nobr>Advisory Board</nobr>","/english/inst_beirat.html"]],
		[["Bildergalerie","/inst_bildergalerie.html"],["Gallery","/english/inst_bildergalerie.html"]],
		[["Presse","/inst_presse.html"],["Press","/english/inst_presse.html"]],
		[["Qualit&auml;t","/inst_quality.html"],["Quality","/english/inst_quality.html"]],
		[["INSTITUT", "/inst_vision.html"],["INSTITUTE", "/english/inst_vision.html"]]
	],
	[
		[["<nobr>MBA &quot;European Management&quot;</nobr>","/prog_mba_em.html"],["<nobr>MBA &quot;European Management&quot;</nobr>","/english/prog_mba_em.html"]],
		//[["<nobr>MBA (ab Oktober 2010!)</nobr>","/prog_mba_de.html"],["<nobr>MBA (German Language)</nobr>","/prog_mba_de.html"]],		
		[["<nobr>Open Enrollment</nobr>","/prog_mba_oe.html"],["<nobr>Open Enrollment</nobr>","/english/prog_mba_oe.html"]],
		//[["<nobr>Stipendien</nobr>","/prog_scholarship.html"],["<nobr>Scholarships</nobr>","/english/prog_scholarship.html"]],
		[["Statistik","/prog_statistic.html"],["Statistic","/english/prog_statistic.html"]],
		[["Service","/prog_services.html"],["Service","/prog_services.html"]],
		[["Download","/inst_info.html"],["Download","/english/inst_info.html"]],
		[["PROGRAMME","/prog_mba_em.html"],["PROGRAMMES","/english/prog_mba_em.html"]]
	],
	[
		[["<nobr>Professoren der UdS</nobr>","/lehr_stammprof.html"],["<nobr>Professors of the UdS</nobr>","/english/lehr_stammprof.html"]],
		[["Gastprofessoren","/lehr_gastprof.html"],["Visiting&nbsp;Professors","/english/lehr_gastprof.html"]],
		[["Publikationen","/lehr_veroff.html"],["Publications","/english/lehr_veroff.html"]],
//		[["Forschung","/lehr_forschung.html"],["Research","/english/lehr_forschung.html"]],
		[["Testimonials","/lehr_testimonial.html"],["Testimonials","/english/lehr_testimonial.html"]],
		[["PROFESSOREN","/lehr_stammprof.html"],["FACULTY","/english/lehr_stammprof.html"]]
	],
	[
		[["Stud.IP","http://app.mba-europe.de/studip"],["Stud.IP","http://app.mba-europe.de/studip"]],
		[["Webmail","http://134.96.74.34/webmail/src/login.php"],["Webmail","http://134.96.74.34/webmail/src/login.php"]],
		[["RSS News","/stud_termine.html"],["RSS News","/english/stud_termine.html"]],
		[["Job Portal","/stud_jobportal.html"],["Job Portal","/english/stud_jobportal.html"]],
		[["Events","/stud_events.html"],["Events","/english/stud_events.html"]],
		[["Alumni","/stud_alumni.html"],["Alumni","/english/stud_alumni.html"]],
		[["Testimonials","/stud_testimonial.html"],["Testimonials","/english/stud_testimonial.html"]],
		[["STUDENTEN","/stud_termine.html"],["STUDENTS","/english/stud_termine.html"]]
	],
	[
		[["Unternehmen","/networks_company.html"],["Companies","/english/networks_company.html"]],
		[["Alumni","/networks_alumni.html"],["Alumni","/english/networks_alumni.html"]],
		[["Hochschulen","/networks_partners.html"],["Universities","/english/networks_partners.html"]],
		[["NETZWERKE","/networks_company.html"],["NETWORKS","/english/networks_company.html"]]
	],
	[
		[["Kontakt","/service_kontakt.html"],["Contact","/english/service_kontakt.html"]],
		[["Unternehmen","/service_unternehmen.html"],["Companies","/english/service_unternehmen.html"]],
		[["<nobr>Einrichtungen</nobr>","/service_centrals.html"],["<nobr>Service Centrals</nobr>","/english/service_centrals.html"]],
		[["Anfahrt","/service_anfahrt.html"],["Location&nbsp;Map","/english/service_anfahrt.html"]],
		//[["Links","/service_links.html"],["Links","/english/service_links.html"]],
		[["FAQ","/service_faq.html"],["FAQ","/english/service_faq.html"]],
		[["SERVICE","/service_kontakt.html"],["SERVICE","/english/service_kontakt.html"]]
	]
];




//hack for compatibility purposes, node subnode and path are determined automatically in this implementation
function mainMenuEn(node, subnode, path)
{
	mainMenu("en");
}

function mainMenuDe(node, subnode, path)
{
	mainMenu("de");
}

//Determine the width (in pixels) of a menu entry to distribute the Menunames equidistantly
function getTextWidth(item){
	if (document.getElementById("ruler") == null){
		document.write('<span id="ruler" style="visibility:hidden; position:absolute;"> </span>');
	}
	var spanObject = document.getElementById("ruler");
	spanObject.innerHTML = item;
	return spanObject.offsetWidth;
}


//use JQuery to take care of the fadein and fadeout properties of the menu
//store a timeout value in the parent of the menu and submenu column that is resetted if the mouse 
//hovers over one of the divs.
$(document).ready(function(){
	$("*[id^='mname_'],*[id^='items_']").each(function(){
		$(this).mouseenter(function(){
				clearTimeout($(this).parent().data('timeoutId'));
				var element = this;
				$(element).parent().parent().parent().children().find("*[id^='arrows_']").fadeIn(0, function(){$(element).parent().parent().parent().children().find("*[id^='arrows_']")[0].style.visibility='visible';});
				$(element).parent().find("*[id^='items_']").fadeIn(0, function(){$(element).parent().children()[0].style.visibility='visible';});			   
			}).mouseleave(function(){
				var element = this;
			   var timeoutId = setTimeout(function(){ 
					$(element).parent().parent().parent().children().find("*[id^='arrows_']").fadeOut("fast", function(){$(element).parent().parent().parent().children().find("*[id^='arrows_']")[0].style.visibility='hidden';});
					$(element).parent().find("*[id^='items_']").fadeOut("fast", function(){$(element).parent().children()[0].style.visibility='hidden';});
					} 			   	
			   	, 150 );
			   $(this).parent().data('timeoutId', timeoutId); //set the timeoutId, allowing us to clear this trigger if the mouse comes back over
			});	
	});
});


//fade in the active menu
$(document).ready(function(){
	setTimeout(function(){
		$("*[id^='items_']").each(function(){
			$(this).find("a[href]").each(function(){
				//alert($(this).css('color'));
				if ($(this).css('color') == "#d12c15" || $(this).css('color') == "rgb(209, 44, 21)"){
					//alert("done");
					var element = this;
					$(element).parent().parent().parent().parent().parent().children().find("*[id^='arrows_']").fadeIn(0, function(){$(element).parent().parent().parent().parent().parent().children().find("*[id^='arrows_']")[0].style.visibility='visible'; });	
					$(element).parent().parent().parent().find("*[id^='items_']").fadeIn(0, function(){$(element).parent().parent().parent().children()[0].style.visibility='visible';});	
				}		
			});
		});
	}, 0 );
});



//generates the div for the country flags in the upper right corner
function setLanguages(language){
	var germanFlagFile = "/Bilder/german.png";
	var englishFlagFile = "/Bilder/english.png";
	var activeFlagColor = "gray";
	
	//generate link for redirection to english or german version respectivly
	var link = document.location.pathname;
	if (language=="de") link = "/english"+link;
	//else we have to remove the "english" phrase from the link
	else link = link.split("/english")[1];

	var redirectCode = ' onClick="window.location=getRedirectionOptions(\'' +link + '\')" ';

	//alert(document.location.pathname);

	var langdiv = '<div id="languages" style="position:absolute; right:10px; top:5px; background-color:yellow; width:48px; height:16px; z-index:5;">';
	langdiv += '<div id="german" '+ ((language=="en")?redirectCode:" ") +'style="background-color:'+ ((language=="de")?activeFlagColor:"white") +'; height:16px; width:24px; float:left; background-image:url(' + germanFlagFile +'); background-repeat:no-repeat; background-position:center; cursor:pointer;"> </div>';
	langdiv += '<div id="english" '+ ((language=="de")?redirectCode:" ") +' style="background-color:'+ ((language=="en")?activeFlagColor:"white") +'; height:16px; width:24px; float:right; background-image:url(' + englishFlagFile +'); background-repeat:no-repeat; background-position:center; cursor:pointer;"> </div>';
	langdiv += '</div>';
	return langdiv;
}

//generates the div for a specific column
function generateSubMenu(language, column, spacer){
	//Determine current active item
	var active = document.location.pathname;
	//alert(active);
	//alert(menuItems[column][0][((language=='de')?0:1)][1]);
	//determine width of each column
	width = getTextWidth(menuItems[column][menuItems[column].length-1][((language=='de')?0:1)][0])+10;
	//determine the maximal size of all menu items to define the width of items_*column* for correct jquery fadeout animation in STUPID IE!
	itemsWidth = 0;	
	for (var x=0; x<menuItems[column].length; x++){
		if (getTextWidth(menuItems[column][x][((language=='de')?0:1)][0])+10 > itemsWidth){
			itemsWidth = getTextWidth(menuItems[column][x][((language=='de')?0:1)][0])+10;
		}
	}

	
	var subMenu = ""
	//add spacer befor each column	
	if (column != 0){
		subMenu += '<div id="spacer" style="width:'+spacer+'px; float:left;"> &nbsp;</div>';
	}
	//generate the div around each column
	subMenu += '<div id="menuitem'+column+'" style="width:'+ width +'px; postition:relative; float:left; height:'+ menuDimension['height'] +'px; background-color:white;">';
	//generate div for the arrows	
		subMenu += '<div id="arrow_'+column+'" style="position:relative; float:left; width:'+menuArrowWidth+'px; height:'+menuDimension['height']+'px;">';
			subMenu += '<div id="arrows_'+column+'" style="position:absolute; bottom:4px; width:'+menuArrowWidth+'px; visibility:hidden;">';
					//generate a new div for each submenu entry
					if (menuItems[column].length > 1){
						for(var i=0; i<menuItems[column].length+1; i++){
							if (i==0) subMenu += '<div style="width:'+(menuArrowWidth)+'px; height:'+menuArrowHeight+'px; background-image:url(/Bilder/arrow_top.png); background-repeat:no-repeat" background-position:center;></div>'; 				
							else if (i==menuItems[column].length-1) subMenu += '<div style="width:'+(menuArrowWidth)+'px; height:'+menuArrowHeight+'px; background-image:url(/Bilder/arrow_spacer.png); background-repeat:no-repeat" background-position:center;></div>';		
							else if (i==menuItems[column].length) subMenu += '<div style="width:'+(menuArrowWidth)+'px; height:'+menuArrowHeight+'px; background-image:url(/Bilder/arrow_bottom.png); background-repeat:no-repeat" background-position:center;></div>';
							else subMenu += '<div style="width:'+(menuArrowWidth)+'px; height:'+menuArrowHeight+'px; background-image:url(/Bilder/arrow_middle.png); background-repeat:no-repeat" background-position:center;></div>';
						}
					}		
			subMenu += '</div>';
		subMenu += '</div>';
	//generate wrapper for columns
		subMenu += '<div id="wrapper_'+ column +'" style="float:right; position:relative; height:'+menuDimension['height']+'px; width:'+(width-menuArrowWidth)+'px;">';
			subMenu += '<div id="column_'+ column +'" style="position:absolute; bottom:4px; width:'+(width-menuArrowWidth)+'px;">';
				//generate the submenu div. this will be hidden if no moverover event is present
				subMenu += '<div id="items_'+ column +'"  style="position:relative; width:'+ itemsWidth +'px; visibility:hidden; background-color:white;">';
				//generate a new div for each submenu entry
				for(var i=0; i<menuItems[column].length-1; i++){
					subMenu += '<div id="'+menuItems[column][i][((language=='de')?0:1)][0]+'" class="fsubmenu" style="width:'+(width-menuArrowWidth)+'px; height:'+menuArrowHeight+'px; line-height:'+menuArrowHeight+'px;">'
					subMenu += '<a '+((menuItems[column][i][((language=='de')?0:1)][1]==active)?'style="color:#d12c15;"':' ')+' href="'+menuItems[column][i][((language=='de')?0:1)][1]+'" '+ ((menuItems[column][i][((language=='de')?0:1)][1].substring(0,7)=="http://")?' target="blank" ':' ') +' >' + menuItems[column][i][((language=='de')?0:1)][0]+ '</a>';
					subMenu += '</div>';
				}
				//generate space between MENUNAME and SUBMENU
				subMenu += '<div id="spacer" style="height:10px;"> </div>';
	
				subMenu += '</div>';
				//generate the MenuNAMES
				subMenu += '<div id="mname_'+ column +'" class="fmenu"  style="width:'+ (width-menuArrowWidth) +'px; position:relative;">';
					subMenu += '<a ';
						//in case one of the subentries is the active page, make the name in red
						for(var i=0; i<menuItems[column].length-1; i++){
							if (menuItems[column][i][((language=='de')?0:1)][1]==active){
								subMenu += ' style="color:#d12c15;" ';
							}
						}	
					subMenu += ' href="'+menuItems[column][menuItems[column].length-1][((language=='de')?0:1)][1]+'">' + menuItems[column][menuItems[column].length-1][((language=='de')?0:1)][0] +'</a>';				
				subMenu += '</div>'
			subMenu += '</div>';			
		subMenu += '</div>';
	subMenu += '</div>';
	
	return subMenu;
}

function generateMenu(language){
	//compute array of spacers such that the menuentries are equidistantly distributed
	//first determine the lenght, the menu would occupy if no spacers are present
	var lengthAllEntries = 0;
	for (var j=0; j<menuItems.length; j++){
		//for the last menu entry we have to go through all subentries to get the width since these could be longer than the menu name itself
		if (j==menuItems.length-1){
			var max = 0;
			for (var x=0; x<menuItems[j].length; x++){
				if (getTextWidth(menuItems[j][x][((language=='de')?0:1)][0])+10 > max){
					max = getTextWidth(menuItems[j][x][((language=='de')?0:1)][0])+10;
				}
			}
			lengthAllEntries += max;
		}
		else{
			lengthAllEntries += getTextWidth(menuItems[j][menuItems[j].length-1][((language=='de')?0:1)][0])+10;
		}
	}
	var spacer = (menuDimension['width']-lengthAllEntries-rightBoarder) / (menuItems.length-1);
		
	var entries = "";
	//get menu dimensions and number of columns to distribute these equidistantly 
	columnSize = menuDimension['width'] / menuItems.length;
	//iterate through entries and generate columns
	for (var i=0; i<menuItems.length; i++){
		entries += generateSubMenu(language, i, spacer);
	}
	
	return entries;
}

//generatate menu
function mainMenu(language)
{
	var menu = "";
	//language flags
	menu += setLanguages(language);	
	
	//logo
	menu += '<div id="logo" style="float:left; height:129px; width:225px; background-color:white; background-image:url(/Bilder/logo_mba_school.gif); background-repeat:no-repeat; background-position:left;"></div>';
	
	//menu itself
	menu += '<div id="menu" style="float:left; height:' +menuDimension['height']+ 'px; width:' +menuDimension['width']+ 'px; background-color:white;">'; 
	menu += generateMenu(language);
	menu += '</div>';	
	//end main menu
	
	//black bar
	menu += '<div id="rightbar" style="float:left; height:129px; width:5px;"> <div id="bar" style="margin-top:5px; width:5px; height:10px; background-color:#cccccc; background-image:url(/Bilder/shaddow_right_top.png);"></div>  <div id="bar" style="width:5px; height:115px; background-color:#cccccc; background-image:url(/Bilder/shaddow_right.png);"></div> </div>';	
	
	
	document.write(menu);
}

//add the qc-edit class to all editable tags
function makeEditable(){
	$('#koerper').find('p, span, div').each(function(){
		$(this).addClass('qc-edit');
	});

}

