//======================================================================
// DLMF Common Javascript
//======================================================================

//----------------------------------------------------------------------
// Basic Cookie support.

// A date in the past, for expiring cookies
var EXPIRE_NOW = new Date();
var EXPIRE_NEVER = new Date();
EXPIRE_NOW.setTime(EXPIRE_NOW.getTime() - 1000);
EXPIRE_NEVER.setFullYear(EXPIRE_NEVER.getFullYear() +1);

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
	var c = ca[i];
	while (c.charAt(0)==' ') c = c.substring(1,c.length);
	if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null; }

function setCookie(name,value){
    if(value != null){
	document.cookie = name+"="+value+";path=/;expires="+EXPIRE_NEVER; }
    else {
	document.cookie = name+"=false;path=/;expires="+EXPIRE_NOW; }}

//======================================================================
// If there's a form and query data in the URL, prefill the form.
//======================================================================

function prefillForms(){
    if(document.forms != null){
	var pairs = window.document.location.search.substring(1).split("&");
	for(var i = 0; i < pairs.length; i++){
	    var pos = pairs[i].indexOf('=');
	    if(pos == -1) continue;
	    //var key = unescape(pairs[i].substring(0,pos));
	    var key = pairs[i].substring(0,pos);
	    // Note: values can be escaped two different ways.
	    //var val = unescape(pairs[i].substring(pos+1).replace(/\+/g,' '));
	    var val = decodeURIComponent(pairs[i].substring(pos+1).replace(/\+/g,' '));
	    $("input[name='"+key+"'][type='radio'][value='"+val+"']").attr('checked',true);
	    $("input[name='"+key+"'][type='text']").attr('value',val);
	    $("select[name='"+key+"'] option[value='"+val+"']").attr('selected',true);
	}}}

//======================================================================
// Stylesheet selection.
//======================================================================
// Adapted From http://www.alistapart.com/stories/alternate/  by Paul Snowden
// Saves a persistent cookie!.

var BODY = null;
var REQ_Style = readCookie("Style");
var DEF_Style = null;

// This contrivance attempts to find the body & set style BEFORE onload!
// to avoid visible switch of styles.
// But note: it's not guaranteed to happen before onload!!!
if(REQ_Style != null){
    var init_step=0;
    var timer = window.setInterval(function(){
	init_step++;
	if((typeof document.getElementsByTagName != 'undefined')
	   && (((BODY=document.getElementsByTagName('body')[0]) != null)
	       || (BODY=document.body) != null)){
	    if(DEF_Style == null) 
		DEF_Style = BODY.className.replace(/ /g,'#');
	    BODY.className = REQ_Style.replace(/#/g,' ');
	    window.clearInterval(timer); }
	if(init_step > 100){
	    window.clearInterval(timer); }},
	50); }

function updateCSSStyle() {
    if(BODY == null){
	BODY = document.getElementsByTagName('body')[0];
	if(DEF_Style == null)
	    DEF_Style = BODY.className.replace(/ /g,'#'); 
    }
    REQ_Style = readCookie("Style");
    BODY.className = (REQ_Style == null ? DEF_Style : REQ_Style).replace(/#/g,' ');
    // If a customize form is present, set fields
    $("#customize\\.form").each(function(){
	    var classes = $('body').attr('class').split(' ');
	    for(i=0; i < classes.length; i++){
		$("#choose_"+classes[i]).attr('checked',true); }
	    var format = readCookie("Format");
	    if(format == null){ format = 'auto'; }
	    $("#choose_format_"+format).attr('checked',true);
	    format = readCookie("VizFormat");
	    if(format != null){
		$("#choose_vizformat_"+format).attr('checked',true); }
	});
    return true; }

// Used by Customization forms (if any).
function set_style(group,value){
    var classes = $('body').attr('class').split(' ');
    var newstyle = "";
    var nondefault = false;
    for(i=0; i < classes.length; i++){
	var pair = classes[i].split('_');
	if(pair[0] == group){
	    pair[1] = value; }
	nondefault = nondefault || (pair[1] != 'default');
	newstyle += (newstyle == "" ? "" : "#");
	newstyle += pair[0]+'_'+pair[1]; }
    $('body').attr('class',newstyle.replace(/#/g,' '));
    setCookie("Style",(nondefault ? newstyle : null)); 
    return false; }

function set_format(value){
    setCookie("Format", ((value != null) && (value != "auto") ? value : null));
    return false; }

//======================================================================
// Support for getting/selecting Visualization formats (VRML, X3D,...)
//======================================================================

function set_vizformat(value){
    if(value == "auto"){ value = null; }
    setCookie("VizFormat",value);
    return false; }

function set_thisvizformat(value){
    if(value == "auto"){ value = null; }
    setCookie("ThisVizFormat",value);
    if(value != null){
	$("#vizpop_submit").removeAttr('disabled'); }
    return false; }

function set_vizfeatures(value){
    if(value == "auto"){ value = null; }
    setCookie("VizFeatures",value);    
    return false; }

var pending_viz_url;
function CheckViz(url){
    if(readCookie("VizFormat") == null){
	$('#vizpop form').each(function(){ this.reset(); });
	$("#vizpop_submit").attr('disabled',true);
	//$("#choose_vizformat_remember").attr('disabled',true);
	pending_viz_url = url;
	var fmt = readCookie("ThisVizFormat");
	if(fmt != null){
	    $("#choose_thisvizformat_"+fmt).attr('checked',true);
	    $("#vizpop_submit").removeAttr('disabled');
	    //$("#choose_vizformat_remember").removeAttr('disabled'); 
	}
	/*
	features = readCookie("VizFeatures");
	if(features != null){
	    radio = document.getElementById("choose_vizfeatures_"+features);
	    if(radio != null){
		radio.checked = true; }}
	*/
	$("#mask").height( $(document).height())
	    .fadeIn('slow');
	//.css('display',"block");
	$("#vizpop").css("left",($(window).scrollLeft()+$(window).width()/2-150)+"px")
	    .css("top",($(window).scrollTop()+$(window).height()/2-150)+"px")
	    //.show('slow');
	    .fadeIn('slow');
	//.css('display',"block");
	// Take down the pop up if they've navigated around ?? Is a minute enough?
	window.setTimeout("CheckVizCancel()",60000);
	return false; }
    else {
	return true; }}

function CheckVizDone(){
    if($("#choose_vizformat_remember:checked").val() != undefined){
	// [NOTE that you do NOT test for attr("checked")... which is screwy...
	// If we should remember the choice, copy the temporary choice to permanent.
	setCookie("VizFormat",readCookie("ThisVizFormat"));
	setCookie("ThisVizFormat",null);  }
    $("#mask").css('display','none');
    $("#vizpop").css('display','none');
    // Now move on to the approriate graphic (dispatcher will use format choice)
    window.location = pending_viz_url; 
    return false; }

function CheckVizCancel(){
    $("#mask").css('display','none');
    $("#vizpop").css('display','none');
    return false; }

//======================================================================
// Highlighting the document portion identified by the document fragment.
//======================================================================
var SELECTED_ID='';

function hiliteFrag(){
    var id = window.document.location.hash.substr(1).replace(/\./,'\\.');
    if(id != SELECTED_ID){
	if(SELECTED_ID != ''){
	    $('#'+SELECTED_ID).removeClass('selected'); }
	SELECTED_ID = id;
	if(id == ''){}
	else if(id.search(/\.info$/) >0){
	    //$('#'+id).addClass('selected'); 
	    //$('#'+id+" .infocontent").addClass('shown'); 
	    $('#'+id+" .infocontent").addClass('selected'); 
	//$('#'+id).addClass('selected').find('.infocontent').addClass('shown'); 
}
	else {
	    $('#'+id).addClass('selected'); }
    }}

//======================================================================
// Exposing the Info/metadata
//======================================================================
// Info boxes are visible by:
//  *  PopUp on mouseover of the Info icon
//     Uses info:hover in CSS
// They are "displayed" (in the document flow) by:
//  * toggling Show/Hide annotations 
//    which affects ALL infoboxes by adding class='shown'
//    sets sidewide cookie
//  * clicking an Info icon
//    which toggles that Info box by adding class='shown' 
//    adds/removes that id from page cookie.
//  * If frag ID (in url) is to an Info box.

// NOTE: IE doesn't seem to allow storing cookies PER PAGE (ie w/ path=page)
// rather it wants the whole directory. Thus ID's get prefixed w/ the page.

var SHOWN_INFO = '';
var infoOpened = new Object();
var THISPAGE = window.document.location.pathname.replace(/^.*\//,'');
function updateInfo(){
    var showall = readCookie("ShowInfoAll") == 'true';
    var showids = readCookie("ShowInfo_"+THISPAGE);
    var trigger = (showall ? "all" : ((showids == null) || (showids == "") ? "none" : showids));
    if(trigger != SHOWN_INFO){	// If displayed state is diff. from request in cookies
	SHOWN_INFO = trigger;
	if(showall){
	    $('#showinfo').css('display','none');
	    $('#hideinfo').css('display','list-item');
	    $(".infocontent").addClass('shown').show('slow'); }
	else {
	    $('#showinfo').css('display','list-item');
	    $('#hideinfo').css('display','none');
	    infoOpened = new Object();
	    if(showids != null){
		var ids = showids.split('#');
		for(i=0; i < ids.length; i++){  
		    infoOpened[ids[i]]=ids[i]; }}
	    $('.infocontent').each(function(){ 
		    var id = $(this).parent().attr('id');
		    if(infoOpened[id]){
			$(this).addClass('shown').slideDown("slow"); }
		    else {
			$(this).removeClass('shown').hide(); }});
	}}}

// Show (all) Annotations button clicked
function showInfo(){
    setCookie("ShowInfoAll",true);
    $('#showinfo').css('display','none');
    $('#hideinfo').css('display','list-item');
    $(".infocontent").addClass('shown')
	//.css({position:'relative', display:'none',float:'right'})
	.slideDown('slow'); }

// Hide (all) Annotations button clicked
function hideInfo(){
    setCookie("ShowInfoAll",null);
    $('#showinfo').css('display','list-item');
    $('#hideinfo').css('display','none');
    $(".infocontent").removeClass('shown').slideUp('slow'); }

function updateInfoCookie (){
    var shown_info='';
    var page = window.document.location.pathname.replace(/^.*\//,'');
    for(var anid in infoOpened){
	shown_info += (shown_info=='' ? '' : '#') + anid; }
    if(shown_info == ""){
	shown_info=null;
	document.cookie = "ShowInfo_"+page+"=;expires="+EXPIRE_NOW; }
    else {
	document.cookie = "ShowInfo_"+page+"="+shown_info; }
}

//======================================================================
// Orchestrate the whole mess.
//======================================================================

// Note: onLoad doesn't (necessarily) get invoked via <back> or <forward>,
// or following a link within the same document.
// Since we're trying to track changes to cookies, stylesheets, #frag (!)
// we need to occasionally peek at the state & possibly refresh.
// So, we set a timer to check the document's URL every second and update if needed.

var PREV_COOKIE = "";
function do_refresh(){
    if(document.cookie != PREV_COOKIE){
	updateCSSStyle(); 
	PREV_COOKIE = document.cookie; }
    updateInfo();
    hiliteFrag(); 
}

var beenhere=false;
$(document).ready(function(){
	/*
	$(window).bind('pageshow',function(){
		if(beenhere){
		    window.alert("Hey! we've been here before!"); }
		else {
		    window.alert("Hey! First time here!"); 
		    beenhere=true; }});
	*/
	// Set up sticky info boxes on clicks
	$(".infoicon").toggle(
			  function(event){
			      var box = $(this).parent().find('.infocontent');
			      if(!box.hasClass('shown')){
				  box.removeClass('hover').addClass('shown')
				      .animate({height:"show"},200,'linear',
					       function(){
						   var id = box.parent().attr('id');
						   if(id != null){ 
						       infoOpened[id]=id; 
						       updateInfoCookie(); }  
					       }); }
			      return false; },
			  function(event){
			      var box = $(this).parent().find(".infocontent");
			      if(box.hasClass('shown')){
				  box.slideUp('slow',function(){ 
					  box.removeClass('shown').removeClass('hover');
					  var id = box.parent().attr('id');
					  if(id != null){
					      delete infoOpened[id];
					      updateInfoCookie(); }
				      }); }
			      return false; });
	// Set up popup info boxes on hover.
	// Popup on entering the icon
	$(".infoicon").hover(
			 function(event){
			     var box = $(this).parent().find(".infocontent");
			     if(! box.hasClass('shown') && ! box.hasClass('hover')){
				 box//.addClass('hover')
				     .animate({opacity:"show", height:"show"},200); }
			     //return false; 
},
			 null);
	// but don't popdown until we leave the info box as a whole
	$(".info").hover(null,
			 function(event){
			     var box = $(this).find(".infocontent");
			     //			     if(box.hasClass('hover')){
			     if(!box.hasClass('shown')){
				 box.animate({opacity:"hide", height:"hide"},200, 'linear',
					      function(){ box.removeClass('hover'); });
				 			     }
			     //return false;
 });

    /* script footnotes too, so they work in IE */
	$(".footnote").hover(
			 function(event){
			     var box = $(this).find(".note_content");
			     box.animate({opacity:"show", height:"show"},200); },
			 function(event){
			     var box = $(this).find(".note_content");
			     box.animate({opacity:"hide", height:"hide"},200, 'linear',
					 function(){ box.removeClass('hover'); }); });

	$(".vizimg a:has(.graphics)").click(function(event){
		return CheckViz($(this).attr('href'));
	    });

	$("body.navbar_popup .navbar").hover(
           function(){ $(this).animate({width:100},200); },
           function(){ $(this).animate({width:20},200); });

	//do_refresh();
	updateCSSStyle(); 
	//hiliteFrag(); 
	prefillForms();
	window.setInterval("do_refresh()",500); // Set timer to recover, if needed.
});


