/*

AJAX driven menus framework
copyright 2009 Pat Edison

*/

	var current_menu_ref = null;
	var main_menu = [];
	var newhash = null; // special hash used to fetch pages via AJAX
	var current_url = null;
	var loadedobjects = "";
	var returnees_page = -1; // keeps track of pages displayed on 'Returnees' page
	var currentStoryKey = 1; // default array key for Current Story Box this could be randomly generated
	var currentStoryBox = null; // keeps track of which multipanel is open
	var currentStory = ""; // id name of currentStoryBox div
	var changeWindowSizeErrorOccured = false;
	var multibarDiv = null; // container for multibars.swf
	var multibarsLoaded = false;


	
	
	

	window.onresize = changeWindowSizeTimer;
	
	
	function setupAJAX() {
	if (window.XMLHttpRequest) {
	  // If IE7/8, Mozilla, Safari, etc: Uses native XMLHttpRequest
	var ajaxRequest = new XMLHttpRequest();
	return ajaxRequest;
	} else {
	if (window.ActiveXObject) {
	  // ...otherwise, use the ActiveX control for IE5.x and IE6
	 var ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
	 return ajaxRequest;
	  } else {
	alert("Sorry, this page won't work with this browser!\nYou need to upgrade to a recent version of\nFirefox, Safari, Opera or Internet Explorer.");
	
	  }
	 }
	}
	
	window.onload = function(){
	make_main_menu();
	make_sub_menu();
	make_non_men_items();
	boot_EPG();
	preloadImages();
	pollHash();
	profiles.load();
	fill_ads_array();// bring in available side ads 
	swfobject.embedSWF("swf/ACET&ACSP_RadioCaroline_teg.swf", "AC_ad", "160", "200", "9.0.0"); // stick in AC Lighting ad
	$("#listen_click_div").bind("click", function() {
	$("#mediaplayer_slideDiv").slideToggle(400);
	});
	$("#directly_help_button").bind("click", function() {
	$("#donations_div").slideToggle(400);
	return false;
	});
	
	//listen_click_div.onclick = function(){toggleBasicSlide('wots_playing');window.frames["epg"].getWotsPlaying()};
	//placeEasterRCSGpanel(); // remove after Easter!
	document.onmousemove = follow; // function for popping up messages in profiles.js
	if(navigator.userAgent.indexOf("Opera")!=-1){load_css("opera");};
		

	}
	
	
	/*MAKE MAIN MENU
	  Use main_menu_items array is in menu_config.js
	  to create menu objects
	*/
	function make_main_menu() {
	var cssStyleNormal = "background-image: url(images/corners/menu.gif);";
	var cssStyleOver = "background-image: url(images/corners/menu_over.gif);";
	var main_menuDiv = document.getElementById('main_menuDiv');
	var ul = document.createElement("ul");
	ul.id="menu";
	for (var i=0; i<main_menu_items.length; i++){
	if (main_menu_items[i].url.indexOf("html")!=-1 ){
	var key = main_menu_items[i].url.split(".html")[0]; // use main part of url as key
	}
	main_menu[key] = new construct_menu_item(main_menu_items[i],cssStyleNormal, cssStyleOver);// pass through to constructor
	ul.appendChild(main_menu[key].li);// append li of latest item in main_menu array to ul
	}
	main_menuDiv.appendChild(ul);// append menu to div
	for (var j=2; j<5; j++){
	if (main_menu_items[j].url.indexOf("html")!=-1 ){
	var key = main_menu_items[j].url.split(".html")[0]; // use main part of url as key
	main_menu[key].anchor.id = "indent";// would prefer to use 'class' but it causes an error
	}
	}
	if(!window.location.hash) parse_menu_item("home.html"); // display Home Page content
	}
	
	
	//MAKE SUB MENU
	function make_sub_menu(){
	var cssStyleNormal = "background-color: #f5f5f5";
	var cssStyleOver = "background-color: #d3d3d3";
	var sub_menuDiv = document.getElementById('sub_menuDiv');
	var ul = document.createElement("ul");
	ul.id="submenu";
	for (var i=0; i<sub_menu_items.length; i++){
	if (sub_menu_items[i].url.indexOf("html")!=-1 ){
	var key = sub_menu_items[i].url.split(".html")[0]; // use main part of url as key
	}
	main_menu[key] = new construct_menu_item(sub_menu_items[i],cssStyleNormal, cssStyleOver);// pass through to constructor
	ul.appendChild(main_menu[key].li);// append li of latest item in main_menu array to ul
	}
	sub_menuDiv.appendChild(ul);// append menu to div
	}
	
	// MAKE NON MENU ITEMS (so we can fire JS after a non menu page has loaded)
	function make_non_men_items(){
	for (var i=0; i<non_menu_items.length; i++){
	if (non_menu_items[i].url.indexOf("html")!=-1 ){
	var key = non_menu_items[i].url.split(".html")[0]; // use main part of url as key
	}
	main_menu[key] = new Object();
	main_menu[key].jsfunc2 = non_menu_items[i].jsfunc2; // add jsfunc2 property so we can use it later
	main_menu[key].menuname = non_menu_items[i].menuname; // need this to make browser page title
	main_menu[key].latch = function(){}; // need this to prevent error in get_content() but it does nothing
	main_menu[key].delatch = function(){}; // ditto
	
	}
	}
	
	
	// menu item obj constructor
	function construct_menu_item(items, cssStyleNormal, cssStyleOver){
	this.url = items.url;
	this.menuname = items.menuname;
	this.externalURL = items.externalURL; // external url
	this.secondItemURL = items.secondItemURL; // url of additional content
	this.secondItemDiv = items.secondItemDiv; // the div to load any additional content
	this.css = items.css; // when set to true triggers the loading of a style sheet
	this.js = items.js; // when set to true triggers the loading of an javascript into the head of the page
	this.jsfunc1 = items.jsfunc1; // javascript function to run instead of loading html
	this.jsfunc2 = items.jsfunc2; // javascript function to run after loading html
	this.anchor = document.createElement("a");// create anchor for menu
	var mytextnode = document.createTextNode(items.menuname);
	this.li = document.createElement("li"); // list item tag
	this.anchor.onclick = function(){parse_menu_item(items.url, items.externalURL);return false;};// on menu click send anchor obj and all its properties to parser
	this.anchor.href="#";
	this.anchor.appendChild(mytextnode);
	this.li.appendChild(this.anchor);
	// menu highlights
	this.anchor.onmouseover = function() {this.style.cssText = cssStyleOver; if(current_menu_ref) kill_menu_highlight();};// change current menu item to 'normal' state
	this.anchor.onmouseout = function() {this.style.cssText = cssStyleNormal; menu_highlight()};
	this.latch = function(){
	this.anchor.style.cssText = cssStyleOver;
	}
	this.delatch = function(){
	this.anchor.style.cssText = cssStyleNormal;
	}
	
	}
	
	// change highlight of current menu item on mouseout
	function menu_highlight(){
	if(current_menu_ref) current_menu_ref.latch();
	}
	
	// change highlight of current menu item on mouseover
	function kill_menu_highlight(){
	if(current_menu_ref) current_menu_ref.delatch();
	}
	
	function parse_menu_item(url, externalURL){
	if(externalURL){
	window.open(externalURL); // open url in external window only
	return; // no need to proceed
	}
	window.location.hash = url; // apply hash to address bar
	//delete_ads(); // get rid of any ads that may be placed down sides
	//get_side_ads();
	}
	
	function pollHash(){
    window.setInterval("URL_listener()", 100);
    }
    
	function URL_listener(){
    if (window.location.hash != current_url){
    current_url = window.location.hash;
	multibarsLoaded = false;
    get_content();
    }
	}
	
	function parse_history_pages(url){
	window.location.hash = url;
	}
	
	function get_content(){
	if ((current_url == "") || (current_url == undefined)) return; // block blanks
	returnees_page = -1; // in case we have just come from 'Returnees' page and are going back to it. Resets to first page
	qcq_page = -1; // ditto
	var second_url = 0;
	var second_div_id = 0;
	var jumpIsPresent = false;
	var url = current_url.substr(1);// get rid of hash symbol at front
	// deal with special code for blogs page
	if( url.indexOf('blogs.html')!=-1 ){
		if( url.indexOf("=")!=-1 ){
		var p = url.split("=");	
		open_blogs_page(decodeURIComponent(p[1]));
		}else{
		open_blogs_page(null);	
		}
	return;
	}
	// extract main part of url which is used as key for main_menu faux associative array
	if (url.indexOf("html")!=-1 ) {
	var key = url.split(".html")[0];
	// test for legal key and latch menu if true
		if(main_menu[key] != undefined) {
		if(current_menu_ref) current_menu_ref.delatch();// kill this to allow CSS style to resume
		main_menu[key].latch(); // latch this menu's colour to grey
		current_menu_ref = main_menu[key]; // pass ref
		}else{
		if(current_menu_ref) current_menu_ref.delatch(); // kill any previous menu highlight or it will be left on
		get_other_content(url,"content_wrapper"); // load content actioned by non-menu item
		return;
		}
	}

	try {
	// alert(key)
	if (main_menu[key].jsfunc1){
	eval(main_menu[key].jsfunc1);// execute the js function instead of loading directly via AJAX
	document.title = "Radio Caroline - " + main_menu[key].menuname;
	return; // as we have no further business here
	}
	}catch(e){
	// if an error occurs valuating or executing special js function then bailout to Home Page
	alert("Sorry, an error occured: "+e);
	window.location.hash = "home.html"; // reload Home Page (if error doesn't kill us)
	return;
    }
				   
	if(main_menu[key].css) load_css(main_menu[key].menuname);// load css into doc head
	if(main_menu[key].js) load_js(main_menu[key].menuname);// load js into doc head
	if(main_menu[key].secondItemURL) second_url = main_menu[key].secondItemURL;// pick up any extra content URL
    if(main_menu[key].secondItemDiv) second_div_id = main_menu[key].secondItemDiv;// pick up id of Div to put it in
	var newURL = key+".html"; // reconstruct url to get rid of anything on the end from an old style url
	
	
	var timeout = setTimeout(loading,200);
	delete_ads(); // get rid of any ads that may be placed down sides
	var ajaxRequest = setupAJAX();
  	var bustcacheparameter=(newURL.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime();
	ajaxRequest.open("GET",newURL+bustcacheparameter, true);
	//read returned data from server and place it in div
	ajaxRequest.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
			if (ajaxRequest.status == 200){
			var returned_data = ajaxRequest.responseText;
			window.scrollTo(0,0);// scroll to top of page
			clearTimeout(timeout);// stop 'loading' animation as content is about to be loaded
			document.getElementById('content_wrapper').innerHTML = returned_data;
			document.title = "Radio Caroline - " + main_menu[key].menuname;
			if ((second_url) && (second_url != "0")) get_other_content(second_url, second_div_id);// second request for additional content
			// deal with any extra js code that needs executing
			if (main_menu[key].jsfunc2){
				try{
				var jsName = main_menu[key].jsfunc2;
				setTimeout(function(){ executeJS(jsName) } ,300); // delay to allow DOM to load
				}catch(e){
				//alert("Sorry, an error while loading extra content\n"+e);
				}
				}
				get_side_ads();
				garbageMan();
				}else{
				// first check if failing to find page is caused by a named anchor tag being on the existing page
				clearTimeout(timeout);
				var content = document.getElementById('content_wrapper');
				var atags = content.getElementsByTagName("a");
				for (var i=0; i<atags.length; i++) {
					try {
					if(atags[i].hasAttribute("name")) jumpIsPresent = true;
					}catch(e){
				               alert("Sorry, an error occured while loading extra content\n"+e);
					}
			if (jumpIsPresent) return; // named anchor tag found
			}
					
					content_missing_message("content_wrapper", ajaxRequest.status, true); // no anchor tag so display error message
			}
	      }	
	}
	   ajaxRequest.send(null); 
	}
	
	// clean up anything we need to after page loads
	function garbageMan(){
	delete(blogObjs);
	delete(multibarDiv);
	}
	
	 // display 'loading' animation 
    function loading(){
    var content_wrapper = document.getElementById('content_wrapper');
    content_wrapper.innerHTML = "<br /><br /><div align='center'><img src='images/ajax-loader.gif' />"  
    }
	
	function executeJS(js){
	eval(js);// execute any special JS code after page loads	
	}
	
	// dynamically load css
	function load_css(txt){
	var css = "css/"+txt.toLowerCase()+".css";
	css = css.replace(/ /g, '_');// replace spaces with underscores
	if(loadedobjects.indexOf(css)!=-1) return;// stylesheet has already been loaded
	var fileref=document.createElement("link");
	fileref.setAttribute("media", "all");
	fileref.setAttribute("type", "text/css");
	fileref.setAttribute("rel", "stylesheet");
	fileref.setAttribute("href", css);
	if (fileref!=""){
	document.getElementsByTagName("head").item(0).appendChild(fileref)
	loadedobjects+=css+" " //add to checking array
	}
	}
	
	function reload_css(cssName){
	var head = document.getElementsByTagName("head").item(0);
	var headlinks = head.getElementsByTagName("link");
	//for (var i=0; i<headlinks.length; i++) {
		//if(headlinks[i].href.indexOf(cssName)!=-1 )  {
		var fileref=document.createElement("link");
		fileref.setAttribute("media", "all");
		fileref.setAttribute("type", "text/css");
		fileref.setAttribute("rel", "stylesheet");
		fileref.setAttribute("href", "css/"+cssName);
		document.getElementsByTagName("head").item(0).appendChild(fileref)
		//head.replaceChild(fileref, headlinks[i]);
		//}
	//}
	}
	
	// dynamically load js
	function load_js(txt){
	var js = "js/"+txt.toLowerCase()+".js";
	js = js.replace(/ /g, '_');// replace spaces with underscores
	if(loadedobjects.indexOf(js)!=-1) return;// stylesheet has already been loaded
	var fileref=document.createElement("script");
	fileref.setAttribute("type", "text/javascript");
	fileref.setAttribute("src", js);
	if (fileref!=""){
	document.getElementsByTagName("head").item(0).appendChild(fileref)
	loadedobjects+=js+" " //add to checking array
	}
	}
	
	function parse_page_title(str){
	var legend = str.replace(/_/g, " "); // remove underscores
	legend = legend.slice(0,(legend.length-5)); // knock off .html
    return legend.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}); // convert to title case
    }
	
	function content_missing_message(div,err, buttons){
	document.getElementById(div).innerHTML= "<br /><br /><div id='try_againDIV' align='center'><p style='color: #99ccff; font-size: 16px;'>Sorry &#150; this content appears to be missing or there was a problem with your Internet connection</p><br />Error "+err+"</div>";
			if(buttons){
			var try_again = document.createElement("input");
			try_again.setAttribute("type","button");
			try_again.setAttribute("value","Try again");
			try_again.style.cssText = "cursor: pointer;";
			try_again.onclick=function(){get_content();};
			var try_againDIV = document.getElementById('try_againDIV')
			try_againDIV.appendChild(try_again);
			// make reload Home button
			var reloadHome = document.createElement("input");
			reloadHome.setAttribute("type","button");
			reloadHome.setAttribute("value","or reload Home Page");
			reloadHome.style.cssText = "cursor: pointer;";
			reloadHome.onclick=function(){window.location.hash = "home.html";};
			var try_againDIV = document.getElementById('try_againDIV')
			try_againDIV.appendChild(reloadHome);	
			}
	}
	  

	
	function get_other_content(url,div_id, callback){
	if(div_id === null) return; // safety net
	var ajaxRequest = setupAJAX();
  	var bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime();
	ajaxRequest.open("GET",url+bustcacheparameter, true);
	//read returned data from server and place it in div
	ajaxRequest.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
		if (ajaxRequest.status == 200) {
			var returned_data = ajaxRequest.responseText;
			try{
			document.getElementById(div_id).innerHTML = returned_data;
			if(callback) setTimeout(function(){ executeJS(callback) },300); // delay to allow DOM to load
			}catch(e){
			content_missing_message(div_id, ajaxRequest.status, false);
			}
			}else{
			content_missing_message(div_id, ajaxRequest.status, false);
			}
	      }
	    }
	   ajaxRequest.send(null); 
	  }
	  
	
	  
	function load_home_page_extras(){
	var flashvars = {};
	var params = {wmode: "transparent", AllowScriptAccess: "sameDomain"};
	var attributes = {};
	swfobject.embedSWF("swf/multibars.swf", "multibarDiv", "100%", "22", "9.0.0", false, flashvars, params, attributes, setupMultibars);
	get_other_content("php/get_blog_teasers.php","blogs_teaser");
	//swfobject.embedSWF("swf/easter_prizes_animation.swf", "prizes_swf", "1000", "107", "9.0.0", false, flashvars, params, attributes);
	//var timenow = new Date();
	//var theMinutes = timenow.getMinutes();
	//if (theMinutes % 2 == 0){
	//get_other_content("mini_innovations/mini_innovations.html","mini_shop"); // load on even minutes
	//}else{
	get_other_content("mini_webshop/webshop_window.html","mini_shop"); // load on odd minutes
	//}
	// for auction... remove when it's over
	//CD_Init(); // start countdown timer
	//setTimeout(function(){ document.getElementById("countdownDivHomePage").style.display = "block"; },1000); // delay to allow timer to start
	}
	
	
	
	function setupMultibars(e){
	if (e.success){
	multibarDiv = e.ref;
	multibarsLoaded = true;
	changeWindowSizeTimer();
	}else{
	alt_multibars(); // build basic but usable textual menu
	}
	var slide = new slideObj;
	if(currentStoryBox == null){
	currentStoryBox = document.getElementById(multibar_items[currentStoryKey].slideDiv); // get DOM obj for current story-box
	// Slide currentStoryBox at setup
	slide.slidedown(currentStoryBox.id, false); // slide it down
	}else{
	// slidedown current box - allows user to leave Home page and return to the same story
	slide.slidedown(currentStoryBox.id, true); // slide it down	
	}

	}
	
	function changeWindowSizeTimer(){
	if(window.location.hash.indexOf("home.html") == -1) return; // only relevent to Multibars on Home Page

	setTimeout(changeWindowSize,300);	
	}
	
	function changeWindowSize(){
	if(!multibarsLoaded) return;
	var areaWidth = document.getElementById('content_wrapper').offsetWidth;
	//alert("From changeWindowSize")
		try{
			write_log("Attempting to trigger multibars to "+areaWidth+" wide");
		multibarDiv.trigger(areaWidth, multibar_items);
		multibarDiv.defaultTriangle(currentStoryKey);

		
		}catch(e){
			write_log("Failed to trigger multibars - trying again");
			if(changeWindowSizeErrorOccured == false) setTimeout(changeWindowSize,2000); // wait 3 secs and then try one more time...
				changeWindowSizeErrorOccured = true; // prevent recursion	
		}
		
		
	}
	
	
	// sent back from multibars.swf
	function changePanel(nextDivName){
	currentStoryBox.style.zIndex = 0; // move current div to bottom layer
	var div = document.getElementById(nextDivName);
	div.style.zIndex = "4"; // move triggered div top layer
	var slide = new slideObj;
	slide.slidedown(nextDivName, true); // slide it down
	// set currentStoryKey
	for (var i=0; i<multibar_items.length; i++) {
			if(nextDivName == multibar_items[i].slideDiv) currentStoryKey = i;	
			}

	}
	
	function alt_multibars(){
	// build alternate HTML menu
	multibarDiv = document.getElementById("multibarDiv");
	deleteprior(multibarDiv); // get rid of what's already there
	var ul = document.createElement("ul");
	for (var i=0; i<multibar_items.length; i++) {
	var slideDivName = multibar_items[i].slideDiv;
	var displayText = multibar_items[i].displayText;
	var col = multibar_items[i].colour;
	var this_li = new alt_multibars_contructor(slideDivName, displayText, col);
	ul.appendChild(this_li);	
	}
	multibarDiv.id = "altMultiBarMenu";
	multibarDiv.appendChild(ul);	
	}
	
	// if swf blows out for any reason we make our own menu
	function alt_multibars_contructor(slideDivName, displayText, col){
	this.li = document.createElement("li");
	this.a = document.createElement('a');
	this.href = document.createAttribute('href');
	this.a.setAttribute("href","#");
	this.a.onclick = function(){changePanel(slideDivName);return false;};
	this.a.href="#";
	var textbox = document.createTextNode(displayText);
	var font = document.createElement("font");
	font.style.color = "#"+col.substring(2);
	font.appendChild(textbox);
	this.a.appendChild(font)
	this.li.appendChild(this.a);	
	return this.li;
	}