var base_url = 'http://www.rctc.edu/dashboard/';

navigation.instance = null;
navigation.perspective = null;
navigation.view = null;  // 1 summary, 2 expanded, 3 details
navigation.direction = null;
navigation.goal = null;
navigation.coremeasure = null;
navigation.display = null;  //1 chart, 2 process, 3 files, 4 info
navigation.year = null;
navigation.level = null;
navigation.visible = null;

function gup(name)
{
  var n = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+n+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function check_hash(hash)
{
  var valid=/(^\d+\.\d+\.\d+\.\d+\.\d+\.\d+\.\d+\.\d+$)/
  
  if (valid.test(hash))
	return true;

  return false;
}

function guh()
{
  var ar = (window.location.href).split("#");
 
  if(ar[1])
  {
    hash = ar[1];
    
    if(!check_hash(hash))
    {
      alert("The entered URL is an invalid dashboard location, redirecting to the dashboard start page") 
      window.location.href = base_url;     
    }
  }
  else
    hash = null;  

  return hash;
}

function create_hash()
{
  var hash = ("#"+navigation.instance);
  hash += ("."+navigation.perspective);
  hash += ("."+navigation.view);
  hash += ("."+navigation.direction);
  hash += ("."+navigation.goal);
  hash += ("."+navigation.coremeasure);
  hash += ("."+navigation.display);
  // hash += ("."+navigation.year);
  //hash += ("."+navigation.level);
  hash += ("."+navigation.visible);
 
  return hash;
}

function initiate_navigation()
{
  navigation.instance = 7;
  navigation.perspective = 1;
  navigation.view = 1;  // 1 summary, 2 expanded, 3 details
  navigation.direction = 0;
  navigation.goal = 0;
  navigation.coremeasure = 0;
  navigation.display = 1;  //1 chart, 2 process, 3 files, 4 info
  navigation.year = navigation.instance + 10;
  navigation.level = 0;
  navigation.visible = 1;

  if(gup("instance_id")) 
    navigation.instance = gup("instance_id");
  
  session.instance_id = navigation.instance;
  
  //this is a param coming from IPP
  if(gup("orgunit_id"))
	    navigation.perspective = gup("orgunit_id");
  
  if(gup("perspective_id"))
    navigation.perspective = gup("perspective_id");
  
  if(gup("direction"))
    navigation.direction = gup("direction");
      
  if(gup("goal"))
    navigation.goal = gup("goal");  
  
  //this is a param coming from IPP
  if(gup("coremeasure_id"))
    navigation.coremeasure = gup("coremeasure_id");  
  
  if(gup("cm_id"))
	navigation.coremeasure = gup("cm_id");

  if(gup("view") == 4)
  {
    base_url = 'https://www.rctc.edu/dashboard/';	
	
    var u = location.href;

    $(".monitor").hide(); 
    
    if(window.location.protocol != "https:")
    {
      location.href = base_url+'#'+navigation.instance+'.'+navigation.perspective+'.0.0.0.0.0.4';	
    }
  }
  else
  {	  
    if(gup("view"))
      navigation.view = gup("view");
    else
    {
      if(gup("direction") || gup("cm_id") || gup("coremeasure_id"))
	    navigation.view = 2;
    
      if(navigation.perspective > 1)
      {
    	if(navigation.perspective != 7)
    	  navigation.view = 2;
    	 
      }
    }

    if((navigation.perspective == 1 || navigation.perspective == 7) && (navigation.direction == 0 || navigation.goal == 0))
    {	
	  navigation.direction = 1;
	  navigation.goal = 1;	 	
    }
    
  }
 
 // if(navigation.coremeasure > 0)
//	  navigation.visible = 1; 
  
  var u = base_url+create_hash();
  
 // alert(navigation.coremeasure + " " + navigation.perspective)
  
  var h = guh();
  
  if(!h)
    location.href = u;
  else
  {
	//need instance id at least to set correct instance or global data
	var ar = hash.split(".");
	navigation.instance = parseInt(ar[0].replace("#",""),10); 
	navigation.perspective = parseInt(ar[1],10); 
	navigation.view = parseInt(ar[2],10);
	navigation.direction = parseInt(ar[3],10);
	navigation.goal = parseInt(ar[4],10);
	navigation.coremeasure = parseInt(ar[5],10);
	navigation.display = parseInt(ar[6],10);  //1 chart, 2 process, 3 files, 4 info
	navigation.visible = parseInt(ar[7],10);
  }
}

function set_history_events()
{
  $("a[rel='history']").unbind("click");
  
  $("a[rel='history']").click(function(){ 
   	var hash = this.href;
   	hash = hash.replace(/^.*#/, '');
   	$.historyLoad(hash);
   	return false;
  });	
}

function change_view(hash)
{
	
	
  $("#monitor").hide(); 
  $("#overview").hide();
  
  var ar = hash.split(".");
  navigation.instance = parseInt(ar[0].replace("#",""),10); 
  navigation.perspective = parseInt(ar[1],10); 
  navigation.view = parseInt(ar[2],10);
  navigation.direction = parseInt(ar[3],10);
  navigation.goal = parseInt(ar[4],10);
  navigation.coremeasure = parseInt(ar[5],10);
  navigation.display = parseInt(ar[6],10);  //1 chart, 2 process, 3 files, 4 info
  navigation.visible = parseInt(ar[7],10);  
  
  document.title = "BSC Application";
  
  var tmp = 1;
  	
  if(session.perspective_id != navigation.perspective)
  {	  
	$("#direction_list").hide();
	$("#details").hide();
	$("#perspective_summary").hide();
	$("#admin_area").hide();  
	$("#wait").show();
	
	if(global)
	  $("#dashboard_name").html(global.orgunit_list[navigation.perspective].orgunit_name);  
	   
	session.perspective_id = navigation.perspective; 

	$("#direction_list").html("");	
	$("#summary_link").attr("href","#"+navigation.instance+"."+navigation.perspective+".1.0.0.0.0.1");
	
    var url = "json_bsc_all.php?perspective_id="+navigation.perspective+"&instance_id="+navigation.instance;
    
    $.ajax({
      url: url,
      method: 'GET',
      dataType: 'json',
      beforeSend: function(req) {
        req.setRequestHeader('Accept-Encoding', 'gzip, deflate');
      },
      success: function(json) {
    	 
        perspective = json;
    	
        var d = -1;
    	var g = -1;
    		
    	$.each(perspective.DIRECTION, function(_d, dir) {
    	  if(d < 0 && perspective.DIRECTION[_d].GOAL)
    	  {
    	    d = _d;     	    
    	  }
    	});
    	
    	$.each(perspective.DIRECTION[d].GOAL, function(_g, goal) {
    	  if(g < 0)
    		g = _g; 
    	});
    	//console.log(d+" " +g)   	
 
    	
    	$("#expanded_link").attr("href","#"+navigation.instance+"."+navigation.perspective+".2."+d+"."+g+".0.0.1");
    	$("#orgunit_link").attr("href","#"+navigation.instance+"."+navigation.perspective+".3.0.0.0.0.1");
    	$("#admin_link").attr("href","#"+navigation.instance+"."+navigation.perspective+".4.0.0.0.0.1");
       
        navigation.direction = 999;
        navigation.goal = 999;       
  			
        if(perspective.DIRECTION)
        {
          $.each(perspective.DIRECTION, function (d, dir) {
        	  
            if(d < navigation.direction)
        	  navigation.direction = d;
          });
            
          var d = navigation.direction;

          if(perspective.DIRECTION[d].GOAL)
          {
            $.each(perspective.DIRECTION[d].GOAL, function (g, goal) {
          	  if(g < navigation.goal)
          		navigation.goal = g;
            });
          }
        }

        if(navigation.direction == 999)
          navigation.direction = 0;
        
        if(navigation.goal == 999)
            navigation.goal = 0;
           
       
  			
        if(authorized_orgunits && authorized_orgunits[session.perspective_id])        	                      
          session.manager = 1;
        else
          session.manager = 0;
  
        
  			
        document.title = "RCTC Dashboards - " + perspective.DETAILS.TITLE;
  
        
        
  			
        if(navigation.coremeasure > 0)
        {
        	 
        	
        	
          if(perspective.COREMEASURE[navigation.coremeasure])
          {
            navigation.direction = parseInt(perspective.COREMEASURE[navigation.coremeasure].DIRECTION_NUM,10);
            navigation.goal = parseInt(perspective.COREMEASURE[navigation.coremeasure].GOAL_NUM,10);
          }
          else
          {
        	alert("The entered URL is an invalid dashboard location, redirecting to the "+perspective.DETAILS.TITLE+" start page") 
        	navigation.coremeasure = 0;
        	location.href = base_url+create_hash();
          }
        }
        
       
  			
        $('.fy_title').html("FY "+(session.y1+5));  
        $('#wait').hide();
    
        //chart
        for(i=session.y1;i<=session.y2;i++)
        {
          $('.y'+i).show();
        }

        //files 
        $('.cmfy'+session.y2).show(); 
        $('.cmpy'+session.y2).show();
        
        if(perspective.DIRECTION)
        {  
          display_intro();           
          build_perspective();          
          set_history_events();
        }
        //alert("N"+navigation.view)
        change_view2(navigation.view);
   
        if(session.admin_js == 1)
        {	
          if(session.admin == 1)
          {
        	set_context_menus();
          }
          else
            disable_context_menus();  
        }
        
        return false;
      }, 
      error: function (xhr, desc, exceptionobj) {      
        alert("initialization error");      
      }
    });
  }
  else
  {
	change_view2(navigation.view);
  }
}

function change_view2(view)
{   
	//alert(99)
	$(".monitor").hide(); 
	$("#overview").hide();
	
	get_admin();
    get_details(); 
    
	navigation.view = view;

    if(navigation.view == 4)
    {
      var u = location.href;

      if(window.location.protocol != "https:")	  
      {
    	$("#direction_list").hide();
      	$("#details").hide();
      	$("#perspective_summary").hide();
      	$("#wait").hide();
        $("#admin_area").hide();
          
    	base_url = 'https://www.rctc.edu/dashboard/';
          
    	var str = "Do wish to be redirected to a secure administrative location?<br><br><table cellpadding=8><tr>";
    	str += '<td><button onclick="location.href=\''+base_url+'#'+navigation.instance+'.'+navigation.perspective+'.4.0.0.0.0.1\';">Yes</button></td>';
    	str += '<td><button onclick="location.href=\''+base_url+'\';">No</button></td>';
    	str += '</tr></table>';
    	
    	$("#monitor").html(str);
    	$(".monitor").show();
    	
        return false;
      }
      else
      {        
    	$("#direction_list").hide();
    	$("#details").hide();
    	$("#perspective_summary").hide();
    	$("#wait").hide();
        $("#admin_area").show();
        
        if(session.admin == 1)
        {
          $(".admin_functions").show();  
          $("#login_button").html("Log Out"); 
        }
      }
    }  
    else
    {
      $("#admin_area").hide();  
	  $("#wait").show();	    
	  
      if(navigation.view == 1)
      {        
    	$("#direction_list").hide();
    	$("#details").hide();
    	$("#admin_area").hide();  
    	  
    	if((navigation.perspective == 1 || navigation.perspective == 7 || navigation.perspective == 6 || navigation.perspective == 5 || navigation.perspective == 91 || navigation.perspective == 3 || navigation.perspective == 2) && navigation.direction == 0)
    	  navigation.direction = 1;
    	  
    	if(perspective && perspective.DIRECTION && perspective.DIRECTION[navigation.direction])
    	  $("#perspective_summary").show();
        else
        {
          $(".monitor").show();  
        }
          
        $("#wait").hide();        
      }

      if(navigation.view == 2)
      {     	 
    	 // alert(2)
    	$("#details").hide();
    	$("#perspective_summary").hide();
    	$("#admin_area").hide();         
    	 
        $(".monitor").hide();            
        
        if(perspective && perspective.DIRECTION && perspective.DIRECTION[navigation.direction])
        {        	
          if(perspective.DIRECTION[navigation.direction].GOAL[navigation.goal].built == 0)   
          {
            show_measure(navigation.perspective, navigation.direction, navigation.goal);         
          }
        	 
          if(navigation.coremeasure > 0)
          {          
        	perspective.COREMEASURE[navigation.coremeasure].GRAPH_LEVEL = 1;
            perspective.COREMEASURE[navigation.coremeasure].CHART_TYPE1 = perspective.COREMEASURE[navigation.coremeasure].INITIAL_CHART_TYPE;
        		
        	var items = 0;    
        	
            if(navigation.display == 1)
            { 	        	  
        	  if(perspective.CORE_MEASURE_INVENTORY_ITEM[navigation.coremeasure])
        	  {
        	    $.each(perspective.CORE_MEASURE_INVENTORY_ITEM[navigation.coremeasure], function(i, item) {
        	      if(item)
        		    items++;
        	    });
        	  }
        	
        	  var pops = 0;
      	  
        	  if(perspective.CORE_MEASURE_POPULATION[navigation.coremeasure])
        	  {
        	    $.each(perspective.CORE_MEASURE_POPULATION[navigation.coremeasure], function(p, pop) {
        	      if(pop)
        		    pops++;
        	    });        	  
        	  }
        	
        	  if(pops == 0 || items == 0)
        	  {
        	    if(session.admin == 1)
        		  load_chart(navigation.coremeasure, navigation.visible); 
        	    else
        	    {        	
        		  $(".monitor").show(); 
        	    }
        		  
        	  }
              else
                load_chart(navigation.coremeasure, navigation.visible);     
            }
           
            if(navigation.display == 2)
            {              
        	  get_process(navigation.coremeasure, navigation.visible); 
            }
          
            if(navigation.display == 3)
          	  get_files(navigation.coremeasure, navigation.visible); 

            if(navigation.display == 4)
        	  get_description(navigation.coremeasure, navigation.visible);     
         
          }
          else
          {        	  
        	 // alert(1)
            if(perspective.DIRECTION[navigation.direction] && perspective.DIRECTION[navigation.direction].GOAL[navigation.goal])
            {	
              if(perspective.DIRECTION[navigation.direction].GOAL[navigation.goal].COREMEASURE)
              {
                 $.each(perspective.DIRECTION[navigation.direction].GOAL[navigation.goal].COREMEASURE, function (c, cm) {
          
        	       get_chart(c,0);  
                });
              }
            }
          
        	//console.log(navigation.visible)
        	
            if(navigation.visible == 1)
            {
              $('#coremeasure_list_'+navigation.direction+'_'+navigation.goal).show();
              $('#goal_id_'+navigation.direction+'_'+navigation.goal).find('#goal_link').attr('href','#'+navigation.instance+'.'+perspective.PERSPECTIVE_ID+'.2.'+navigation.direction+'.'+navigation.goal+'.0.1.0');           
            
            }
            else
            {
              $('#coremeasure_list_'+navigation.direction+'_'+navigation.goal).hide(); 
              $('#goal_id_'+navigation.direction+'_'+navigation.goal).find('#goal_link').attr('href','#'+navigation.instance+'.'+perspective.PERSPECTIVE_ID+'.2.'+navigation.direction+'.'+navigation.goal+'.0.1.1');
            }
          }   
          
          $(".monitor").hide();    
          $("#direction_list").show(); 
        }
        else
        {        	
          if(navigation.perspective != 1 || navigation.perspective != 7)
          {
            $(".monitor").show();             
          }
        }
        
        $("#wait").hide();
        
        if(navigation.coremeasure > 0)
          $('html,body').animate({scrollTop:$("#id_"+navigation.coremeasure).offset().top},'fast','linear');
        else
          $('html,body').animate({scrollTop:$("#goal_id_"+navigation.direction+"_"+navigation.goal).offset().top},'fast','linear');
      }
      
      if(navigation.view == 3)
      {          	
    	$("#perspective_summary").hide();
    	$("#admin_area").hide();  
    	$("#direction_list").hide();
        $("#wait").hide();
        $("#details").show();
      } 
    }    
    //$('.coremeasure_list div').tsort({attr:'title'})
}