//global variables to indicate what panes are visible
var currentOn=0;
var instOn=0;
var tab="discipline";
var lastID=0;

$().ready(function(){
	//round corners
	$('#cp_content').corner("round 14px cc:#FCF3CC");
	$('.sector_head').corner("top 14px");
	$('.sector').corner("bottom 14px").parent().css('padding', '2px').corner("bottom 14px");
	
	//attached click events
	$('#imageWrapper').find("div").bind("click",function(){
		showDiv($(this).attr('id').substring(2));
		}); 
	//instructions dialog
	$('a[rel*=facebox]').live('click', function(){
	//	facebox("FOO");
	jQuery.facebox({ ajax: this.href });
	return false;
	
	//$('#facebox .content').html('<div class="loading"><img src="'+$.facebox.settings.loadingImage+'"/></div>');
      //$.get(this.href, null, function(data) { $.facebox.reveal(data); });
	});
});

//activates a clicked tab and inserts the contents of an html file
function switchTab(whichTab){

	if($('#'+whichTab).parents().is('#filter'))
		showHideClass("showAll");
	else if($('#'+whichTab).parents().is('#highlight'))
		highlight("showAll");
	
	$.ajax({
	  url: "http://www.aps.anl.gov/Beamlines/Sectors_Map/cp_"+whichTab+"s.html",
	  cache: false,
	  success: function(html){
	    $('#'+whichTab).parents('.tabset').find('.nav').html(html);
	  }
	});
	//deactivate all menu items, then activate the selected item
	$('#'+whichTab).parents('.tabs').find('.active').removeClass('active');
	$('#'+whichTab).addClass('active');
	
	//hide the techniques pane
	if($('#'+whichTab).parents().is('#filter')){
		tab=whichTab;
		$('#techniques_wrapper').slideUp("normal");
		loadXML(lastID);
	}
}

//loads content into the techniques detail pane
function showTechniques(whichCategory,categoryShortName,whatToDo){
	toggleVis('#'+categoryShortName,categoryShortName,whatToDo);
	
	$.ajax({
	  url: "http://www.aps.anl.gov/Beamlines/Sectors_Map/proxy_technique.php",
	  cache: false,
	  datatype: 'xml',
	  data: "subcategory="+whichCategory, 
	  success: function(xml){
		$(xml).find('subcategory').each(function(){
			$('#sc_name').html("<a href=\"javascript:toggleVis(\'#sc_name"+"\',\'"+categoryShortName+"\',\'stayOn\');\">"+$(this).attr('name')+"</a>");	
			$('#sc_name').addClass('on');
			$('#t_names').empty();
			$('#t_names').append('<ul>');
			$(this).find('technique').each(function(i,technique){
				var id = $(technique).attr('id');		
				$('#t_names ul').append("<li id=\"tl"+id+"\"><a href=\"javascript:toggleVis('#tl"+id+"','t"+id+"','vis');\">"+$(technique).text()+"</a></li>");
			});
			$('#t_names').append('</ul>');
		});
	  }
	});
	toggleTechniques();
}
//toggles visibility of the techniques panel
function toggleTechniques(){
	$('#techniques_wrapper').slideToggle("normal");
	return false;
}

//showDiv loads data into the currently hidden div (onclick) and shows it
function showDiv(id){
	if(currentOn != 1){
		currentOn=1;
		lastID=id;
		loadXML(id);
		toggleDivs("#sector1","#sector2");
	}
	else if(currentOn == 1){
		currentOn=2;
		lastID=id;
		loadXML(id);
		toggleDivs("#sector2","#sector1");
	}
	return false;
}
//toggleDivs performs the animation
function toggleDivs(id_on, id_off){
	$(id_on).css("zIndex","1");
	$(id_on).animate({left: 425}, 500);
	$(id_off).css("zIndex","0");
	$(id_off).animate({left: 50}, 500);
}

function highlight(className){
	$('#imageWrapper').find("div").removeClass('sector_on');
	if(className != 'showAll')
		$('#imageWrapper').find("div."+className).addClass('sector_on');
}

function showHideClass(className){
	if(className=='showAll')
		$('#imageWrapper').find("div").show();
	else{
		$('#imageWrapper').find("div").hide();
		$('#imageWrapper').find("div."+className).show();
	}
}

function toggleVis(theItem,className,whatToDo){
	//this item was already selected, so turn it off and show all sectors.
	if(whatToDo == "stayOn"){
		showHideClass(className);
		clearNav('#techniques');
		$(theItem).addClass('on');
	}
	else{
		if($(theItem).is('.on')){
			$(theItem).removeClass('on');
			(whatToDo=='vis') ? showHideClass('showAll') : highlight('showAll');
		}
		else{
			//turn off all the menu items
			if(whatToDo=='vis'){
				clearNav('#filter');
				clearNav('#techniques');
				showHideClass(className);
			}
			else{
				clearNav('#highlight');
				highlight(className);
			}
		$(theItem).addClass('on');
		}
	}
}

function loadXML(url_id) 
//initiates the Ajax request and calls the necessary methods
{
	$.ajax({
  	url: "http://www.aps.anl.gov/Beamlines/Sectors_Map/proxy_sector.php",
  	cache: false,
	datatype: 'xml',
	data: "sector_id="+url_id+"&detail="+tab+"s", 
	success: function(xml){
		clearDivs();
		$(xml).find('sector').each(function(){
			$("#s"+currentOn+"_number").html($(this).attr('id'));
			$("#s"+currentOn+"_displaying").html('&raquo; '+tab.toUpperCase()+"S");
			$(this).find('beamline').each(function(i,beamline){
				
				if(i<3)
					$("#s"+currentOn+"_"+i).addClass("beamline");
												   
				var id = $(beamline).attr('id');
				var name = $(beamline).attr('name');
				var operator = $(beamline).attr('operator');
				var status = $(beamline).find('status').text();
				var url = $(beamline).find('beamlineURL').text();
				var color;
				switch(status){
					case null: color="red"; break;
					case "Operational/Accepting General Users": color="green"; break;
					case "Operational": color="orange"; break;
					default: color="red"; break;
				}

				$("#s"+currentOn+"_name"+i).html("<img src=\"http://www.aps.anl.gov/Beamlines/Sectors_Map/img/status_"+color+".gif\" alt=\""+status+"\" />");
				$("#s"+currentOn+"_name"+i).append("&nbsp; <a href=\"http://www.aps.anl.gov/Beamlines/Directory/showbeamline.php?beamline_id="+id+"\" rel=\"facebox\">Beamline "+name+"</a>");
				$("#s"+currentOn+"_name"+i).append("&nbsp; <span class=\"caption\">"+"<a href=\""+url+"\">"+operator+"</a></span>");
			
					var tmp=[];
					$(beamline).find(tab).each(function(){
						tmp.push($(this).text());																					
					});
					tmp = tmp.sort();
					for(j=0;j<tmp.length;j++){
						$("#s"+currentOn+"_disciplines"+i).append(tmp[j]);
						if(j<tmp.length-1)
							$("#s"+currentOn+"_disciplines"+i).append(",&nbsp;");
					}
					var energy=[];
					$(beamline).find('energy').each(function(){
						energy.push($(this).text());																					
					});
					if(energy.length>0){
						$("#s"+currentOn+"_energy"+i).append("Energy Range: ");
						energy = energy.sort();
						for(j=0;j<energy.length;j++){
							$("#s"+currentOn+"_energy"+i).append(energy[j]);
							if(j<energy.length-1)
								$("#s"+currentOn+"_energy"+i).append(",&nbsp;");
						}
					}
			});
		});
	},
	error: showError
	});
}

function showLoading(){
	clearDivs();
	$("#s"+currentOn+"_name0").html("Data Loading...");
}

function showError(){
	clearDivs();
	$("#s"+currentOn+"_name0").html("Data unavailable.<br />Please try again later.");
}

function clearDivs(){
		for(t=0;t<4;t++){
		$("#s"+currentOn+"_name"+t).html("");
		$("#s"+currentOn+"_energy"+t).html("");
		$("#s"+currentOn+"_disciplines"+t).html("");
	}
	$("#s"+currentOn+"_number").html(" <img src=\"/Beamlines/Sectors_Map/img/ajax-loader.gif\" />");	
}

function clearNav(divID){
	$(divID).find('li').removeClass('on');
	$(divID).find('span').removeClass('on');

	if(divID=='#techniques')
		$('#sc_name').removeClass('on');
}
function hidePanel(){
	$('#sector'+currentOn).animate({left: 50}, 500);
}

function resetMap(){
	$('#sector'+currentOn).css("zIndex","0");
	hidePanel();
	showHideClass('showAll');
	highlight('showAll');
	clearNav('#filter');
	clearNav('#techniques');
	clearNav('#highlight');
	switchTab('discipline')
}