var thispage;
var status = 0;

var loadstatus = 1;

function stab(id){
if($(id)){
	if(status!=id){
		$(id).blindDown({ duration: 0.2 });
	if(status!=0){
		$(status).blindUp({ duration: 0.2 });
	
	}
		status=id;
	}
}
	
}

document.observe("dom:loaded", function() {
	$('searchresults').hide();
	$('topnav').update(topnavhtml);
	$('snav').update(snavhtml);
	$('sidebar').hide();
	hideDropDown();
	hideSideElements();

});


function hideSidebar(){
	$('sidebar').hide();
	$('content').setStyle({width:'950px'});
}


function showSidebar(){
	$('sidebar').show();
	$('content').setStyle({width:'715px'});
}

window.onload = function(){
        /*
        A function that toggles the visibility of nested ul’s
        */
        // For every li
        $$("#topnav li").each(function(node){
                // if there’s a ul
                var ul = $A(node.getElementsByTagName("ul")).first();
                if(ul != null){
                        // toggle it’s visibility on these events
                        node.onmouseover = function(){
                                Element.show(ul);
                        }
                        node.onmouseout = function(){
                                Element.hide(ul);
                        }
                }
        });

       /*
        A function that makes the sidenav work
        */


        $$(".snavt").each(function(node){
                var child = $('s'+node.identify());
                if(child != null){
                        // toggle it’s visibility on these events
                        node.onclick = function(){
                                stab('s'+node.identify());
                        }
                }
        });


}


function hideDropDown(){

	/* Hide sub unordered lists */

	$$("#topnav ul li ul").each(function(node){
	        Element.hide(node);
	});

}

function hideSideElements(){

	$$('.sslinks').each(function(node){
	        Element.hide(node);
	});

}






/* ajax functions */

var home = 'home';


function loadAjax(page){
var url = 'content/' + page + '.html';

new Ajax.Request(url, {
  method: 'get',
  onSuccess: function(transport) {
    var content = $('content');
      response = transport.responseText;
      if(username!=null){
	response = response.gsub('{username}', username);
      }
      else{
	response = response.gsub('{username}', 'guest');
      }
	if(page!=home){
      pagefooter = '<a href="javascript:void(0)" onclick="window.scrollTo(0,0); return false" class="top"></a>';

	}
	else{
      pagefooter = '';
	}

      content.update(response+pagefooter);
      if(($('ptitle') != undefined)){
      doctitle = $('ptitle').innerHTML;
      document.title = 'LEAD Portal - ' + $('ptitle').innerHTML;
      $('ptitle').remove();
      }
      else{
      doctitle = 'LEAD Portal';
      document.title = 'LEAD Portal';
      }
      $('title').innerHTML = doctitle;
      thispage = page;
      attachLinks();
      updateHighlight();
      if(thispage==home){
	hideSidebar();
      }
      else{
	showSidebar();
      }
      new Effect.BlindDown('content',{afterFinish: function() {loadstatus=1; }});
  },
  onFailure: function() {
    var content = $('content');
      $('title').innerHTML = 'Unable to load page';
      document.title = 'LEAD Portal';
      content.update('<p>The page you requested could not be loaded.<br />Check that you are properly connected to the internet.</p>');
      thispage = 'e404';
      attachLinks();
      new Effect.BlindDown('content',{afterFinish: function() {loadstatus=1; }});
  }
});
}

function go(page){
scroll(0,0);
if(loadstatus==1){
if(thispage==null){loadAjax(page);loadstatus=0;}
else if(page!=thispage){
loadstatus=0;
$('title').innerHTML = 'Loading...';
new Effect.BlindUp('content', {  duration: 0.5, afterFinish: function() {loadAjax(page) } } );
}
}
}


function attachLinks(){
  $$("a").each(function(links){
  links.observe('click', activateLink)
  });
}

function activateLink(event) {
  var element = event.element();
  if(element.href){
  querystr = element.href.split("#");
  if(!Object.isUndefined(querystr[1])){
    query = querystr[1].toQueryParams();
    if(!Object.isUndefined(query.page)){
	if(!Object.isUndefined(query.section)){
		stab('s'+query.section);
	}
      go(query.page);
    }
  }
}
}

function getDirectLoadPage(){
  load = home;
  querystr = location.href.split("#");
  if(!Object.isUndefined(querystr[1])){
    query = querystr[1].toQueryParams();
    if(!Object.isUndefined(query.page)){
	if(!Object.isUndefined(query.section)){
		stab('s'+query.section);
	}
      load = query.page;
    }
  }
  return load;
}

Event.observe(window, 'load', function() {
  load = getDirectLoadPage();
  go(load);

  attachLinks();

});




// structure manipulation

function pURL(name){
   name = name.gsub(' ','-').toLowerCase();
   return name;
}

var topnavhtml = '<ul>';



pages.each(function(s) {


	if(s.link!= null){
		var newlink = s.link;
	}
	else{
		var newlink = pURL(s.name);
	}

	topnavhtml = topnavhtml + '<li><a href="#?page=' + newlink + '&section=' + newlink + '"  id="'+pURL(s.name)+'">' + s.name + '</a>';
	if(s.submenu.size()>0){
	topnavhtml = topnavhtml + '<ul>';
	s.submenu.each(function(t){

	if(t.link!= null){
		var newlink1 = t.link;
	}
	else{
		var newlink1 = pURL(t.name);
	}

		topnavhtml = topnavhtml + '<li><a href="#?page=' + newlink1 + '&section=' + newlink + '">' + t.name + '</a></li>';
	});
	topnavhtml = topnavhtml + '</ul>';
	}
	topnavhtml = topnavhtml + '</li>';

});

topnavhtml = topnavhtml + '</ul>';


var snavhtml = '';

pages.each(function(s) {
//move the next line below one more line to make submenuless entries appear
if(s.submenu.size()>0){


	if(s.link!= null){
		var newlink = s.link;
	}
	else{
		var newlink = pURL(s.name);
	}

	snavhtml = snavhtml + '<a href="javascript:void(0)" class="snavt" id="'+newlink+'">' + s.name + '</a>';
	
	snavhtml = snavhtml + '<div id="s'+pURL(s.name)+'" class="sslinks">';
	s.submenu.each(function(t){
	if(t.link!= null){
		var newlink1 = t.link;
	}
	else{
		var newlink1 = pURL(t.name);
	}
		snavhtml = snavhtml + '<a href="#?page=' + newlink1 + '&section=' + newlink + '" class="snavs">' + t.name + '</a>';
	});
	snavhtml = snavhtml + '</div>';

	}

});




//sitemap

function makeSiteMap(){
	$('sitemap').update(topnavhtml);
	attachLinks();
}


// history
/*
new PeriodicalExecuter(checkChange, 0.5);

function checkChange(){
	if(getDirectLoadPage()!=thispage){
		go(getDirectLoadPage());
	}
}
*/


/* userinfo */




function createUser(){

document.observe('lightview:loaded', function() {
  Lightview.show({
    href: 'assets/createuser.html',
    rel: 'ajax',
  
    options: {
      autosize: true,
      closeButton: false,
      overlayClose: false,
      menubar: false,
      keyboard: false,
      
      ajax: {
        method: 'get',
        evalScripts: true,
        onComplete: function(){ }
      }
    }
  });
});

}
function browserWarning(){

document.observe('lightview:loaded', function() {
  Lightview.show({
    href: 'assets/browser.html',
    rel: 'ajax',
  
    options: {
      autosize: true,
      closeButton: true,
      overlayClose: false,
      menubar: false,
      keyboard: false,
      
      ajax: {
        method: 'get',
        evalScripts: true,
        onComplete: function(){ }
      }
    }
  });
});

}




function notepad(){


  Lightview.show({
    href: 'assets/notepad.html',
    rel: 'ajax',
  
    options: {
      autosize: true,
      closeButton: false,
      overlayClose: false,
      menubar: false,
      keyboard: false,

      
      ajax: {
        method: 'get',
        evalScripts: true,
        onComplete: function(){ }
      }
    }
  });


}


function settings(){


  Lightview.show({
    href: 'assets/settings.html',
    rel: 'ajax',
  
    options: {
      autosize: true,
      menubar: false,

      
      ajax: {
        method: 'get',
        evalScripts: true,
        onComplete: function(){ }
      }
    }
  });


}

function updateHighlight(){
	highlight = jar.get('highlight');
	if(highlight=='on'){
		$$('.hl').each(function(e){e.setStyle({
		  backgroundColor: '#F3F7B0'
		});});
	}
	else{
		$$('.hl').each(function(e){e.setStyle({
		  backgroundColor: ''
		});});
	}
}

function saveHighlight(onoffswitch){
	jar.put('highlight',onoffswitch);
	updateHighlight();
	Lightview.hide();
}


document.observe('lightview:opened', function(event) {


if($('cnname')){
  $('cnname').focus();
$('lv_overlay').observe('click', function(){$('cnname').focus();});
}

if($('npdata')){
contents = jar.get('notepad');
if(contents!=null){
$('npdata').value=contents;
}
else{
$('npdata').value='Welcome to your notepad.\nYou may jot down anything here as you browse through the site!';
}
}

});

function cnvalidate(cnform){
if(cnform.cnname.value.stripTags()==''){return false;}else{ jar.put('username', cnform.cnname.value.stripTags()); Lightview.hide();$('intro').sendEvent('PLAY', 'true');var username = jar.get('username'); newAttachUsername(username); return false;  }return false;
}

function newAttachUsername(username){

		$('uname').update(username);
		$('name').show();

}

jar = new CookieJar({
expires:31536000,   // seconds
path: '/'
});

var username = jar.get('username');
if(username == null){

	document.observe("dom:loaded", function() {
		$('name').hide();
	});

if (getBrowser()) { browserWarning()}
	// create new user
	createUser();
	
}

else{
	document.observe("dom:loaded", function() {
		$('uname').update(username);
	});
}

function displayUser(){
if(username!=null){$$('.username').each(function(u){u.update(username)});}
}

function getBrowser(){
if (
    (navigator.userAgent.indexOf("MSIE 6") > -1) ||
	(navigator.userAgent.indexOf("MSIE 8") > -1)
) {
	return true;
	
}
}







document.observe("dom:loaded", function() {

new Tip('tbprint', "This site is printer-friendly. Only the page contents of this site will be printed.", {
				title: 'Print',
				style: 'protogrey',
				radius: 4,
				border: 4,
				target: $('tbprint'),
				stem: 'bottomRight',
				hook: { target: 'topLeft', tip: 'bottomRight' },
				width: 180
			});


new Tip('tbsetting', "Configure the way the site works.", {
				title: 'Settings',
				style: 'protogrey',
				radius: 4,
				border: 4,
				target: $('tbsetting'),
				stem: 'bottomRight',
				hook: { target: 'topLeft', tip: 'bottomRight' },
				width: 180
			});


new Tip('tbfav', "Add page to favourites so you can return to it later.", {
				title: 'Bookmark',
				style: 'protogrey',
				radius: 4,
				border: 4,
				target: $('tbfav'),
				stem: 'bottomRight',
				hook: { target: 'topLeft', tip: 'bottomRight' },
				width: 180
			});


new Tip('tbnotepad', "Use this notepad to jot down notes as you browse through the website.", {
				title: 'Notepad',
				style: 'protogrey',
				radius: 4,
				border: 4,
				target: $('tbnotepad'),
				stem: 'bottomRight',
				hook: { target: 'topLeft', tip: 'bottomRight' },
				width: 180
			});

new Tip('name', "<div id='nameh'><a href='#page=profile' onclick=\"go('profile')\">My Profile</a><a href='javascript:void(0);' onclick='Tips.hideAll();settings();'>Site Settings</a></div>", {
				radius: 4,
				style: 'protogrey',
				border: 4,
				target: $('name'),
				stem: 'topMiddle',
				hook: { target: 'bottomMiddle', tip: 'topMiddle' },
				width: 150,
				showOn: 'click',
				hideOn: 'click',
				hideAfter: 2
			});




});


function bookmarksite(title, url){
if (document.all)
window.external.AddFavorite(url, title);
else if (window.sidebar)
window.sidebar.addPanel(title, url, "")
}


/* sls */

function validate(){
 
i=1;
while(i<=40){
if(i<10){
zerotrail = '0';
}
else {zerotrail='';}
if(document.getElementById('f'+zerotrail+i).value==''){
alert('You have to complete every question before you can continue...');
return false;
}
i++;
}
return true;
}

function updateSelection(qnobj,colour){
 
//window.scrollBy(0,53); 
 
qnid = qnobj.id;
qn = qnid.substr(1,2)
choice = qnid.substr(4,4)

document.getElementById('f'+qn).value = choice
i=1;
while(i<=6){
document.getElementById('q'+qn+'-'+i).style.background = colour;
document.getElementById('q'+qn+'-'+i).style.fontWeight = 'normal';
i++;
}
 
document.getElementById('q'+qn+'-'+choice).style.background = '#FDDBFF';
document.getElementById('q'+qn+'-'+choice).style.fontWeight = 'bold';
}

function saveSLS(){

slsdata = [];
slsdata.push(0);
i=0;
while(i<40){
i++;
fid = 'f'+i.toPaddedString(2);

s = $F(fid);
if(s=="1"){s=1}
if(s=="2"){s=2}
if(s=="3"){s=3}
if(s=="4"){s=4}
if(s=="5"){s=5}
if(s=="6"){s=6}
slsdata.push(s);
}

	jar.put('slsdata',slsdata);
	jar.put('slsdate',genDate());
	location.href="#?page=student-leadership-scale-results&section=activities";
	go('student-leadership-scale-results');

}


function genDate(){
var currentTime = new Date()
var nmonth = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
month = new Array();
month[1]="January"; month[2]="February"; month[3]="March"; month[4]="April"; month[5]="May"; month[6]="June"; month[7]="July"; month[8]="August"; month[9]="September"; month[10]="October"; month[11]="November"; month[12]="December";
gendate = (day + ' ' + month[nmonth] + " " + year);
return gendate;
}


/* LMA */




		var lmacurrqn;
		var lmacurrqnp;
		var lmascore;

function nextqn(init){

	if(init){
		lmacurrqn = -1;
		lmacurrqnp = 0;
		lmascore = 0;
	}

	if(lmacurrqnp==0&&!init){
		alert('Please select an option...');
	}
	else{
		lmacurrqn++;
		lmascore = lmascore + lmacurrqnp;
		if(lmaquestion[lmacurrqn]!=null){
			$('o1').setStyle({background:''});
			$('o2').setStyle({background:''});
			$('o3').setStyle({background:''});
			$('o4').setStyle({background:''});
			$('o5').setStyle({background:''});
			lmacurrqnp=0;
			$('qnholder').update(lmaquestion[lmacurrqn]);
		}
		else{
			// ended
			//save score
			jar.put('lmascore', lmascore);

			//redirect
			location.href="#?page=motivation-assessment-results&section=activities"
			go('motivation-assessment-results');
		}
	}
}

function updateS(item){
	$('o1').setStyle({background:''});
	$('o2').setStyle({background:''});
	$('o3').setStyle({background:''});
	$('o4').setStyle({background:''});
	$('o5').setStyle({background:''});
	$('o'+item).setStyle({background:'#E4F8DB'});
	lmacurrqnp = item;
}



/* game1 */


		function g1_process() {
			var flashInfo = $('lightviewContent').g1_getData();

			gamedata = { rep: flashInfo[0], timebonus: flashInfo[1], cashbonus: flashInfo[2], score: flashInfo[3] };
			jar.put('g1',gamedata);
			location.href="#page=game-1-results&section=activities";
			go('game-1-results');
			Lightview.hide();
		}

		function g1_done(){
			g1_process();
		}


/* game2 */


		function g2_process() {
			var flashInfo = $('lightviewContent').g2_getData();
			jar.put('g2',flashInfo);
			location.href="#page=game-2-results&section=activities";
			go('game-2-results');
			Lightview.hide();
		}

		function g2_done(){
			g2_process();
		}


/* tbboxes */

function openup(num){

$('showonce').hide();
 
i=1
while($("a"+i)){
$("a"+i).hide();
i++;
}
 
$("a"+num).show();
}

/*fergie*/

function fhideAll(){
$('lee').hide();
$('ryan').hide();
$('eric').hide();
$('roy').hide();
$('dwight').hide();
}

function fShow(something){
fhideAll();
$(something).show();
}



/* report */

function myReportUpdate(){

// game1

g1scores = jar.get('g1');

if(g1scores==null){
	var rp_g1='<table width="100%"><tr><td><font size="4">Game 1 - Rule your Country</font></td><td rowspan="2" width="52"><img src="img/failed.gif"></td></tr><tr><td>You have not attempted / completed this game.  <div style="margin-top:4px;"><a href="#?page=game-1&section=activities" onclick="go(\'game-1\')" class="link">Play this game</a></div></td></tr></table>';
}
else{
	var rp_g1='<table width="100%"><tr><td><font size="4">Game 1 - Rule your Country</font></td><td rowspan="2" width="52"><img src="img/passed.gif"></td></tr><tr><td>You have completed this game with a total score of <i>'+g1scores.score+'</i> ! <div style="margin-top:4px;"><a href="#?page=game-1&section=activities" onclick="go(\'game-1\')" class="link">Play this game</a> <a href="#?page=game-1-results&section=activities" onclick="go(\'game-1-results\')" class="link">View detailed scores</a></div></td></tr></table>'
}
$('rp_g1').update(rp_g1);


// game2

g2scores = jar.get('g2');

if(g2scores==null){
	var rp_g2='<table width="100%"><tr><td><font size="4">Game 2 - Ship Commander</font></td><td rowspan="2" width="52"><img src="img/failed.gif"></td></tr><tr><td>You have not attempted / completed this game.  <div style="margin-top:4px;"><a href="#?page=game-2&section=activities" onclick="go(\'game-2\')" class="link">Play this game</a></div></td></tr></table>'
}
else{
	var rp_g2='<table width="100%"><tr><td><font size="4">Game 2 - Ship Commander</font></td><td rowspan="2" width="52"><img src="img/passed.gif"></td></tr><tr><td>You have completed this game with a total score of <i>'+g2scores+'</i> ! <div style="margin-top:4px;"><a href="#?page=game-2&section=activities" onclick="go(\'game-2\')" class="link">Play this game</a> <a href="#?page=game-2-results&section=activities" onclick="go(\'game-2-results\')" class="link">View detailed scores</a></div></td></tr></table>'
}
$('rp_g2').update(rp_g2);



//lma

lmascore = jar.get('lmascore');

if(lmascore==null){
	var motivationscore_res = 'You have not attempted the leadership motivation assessment.';
	var motivationscore_pic= '<img src="img/failed.gif">';
}
else if(lmascore<56){
	var motivationscore_res = 'Your score of '+lmascore + ' is too low.';
	var motivationscore_pic= '<img src="img/failed.gif">';
}
else{
	var motivationscore_res = 'You have completed the Leadership Motivation Assessment with a score of <i>'+lmascore + ' / 70</i> !';
	var motivationscore_pic= '<img src="img/passed.gif">';
}
var rp_lma='<table width="100%"><tr><td><font size="4">Leadership Motivation Assessment</font></td><td rowspan="2" width="52">'+motivationscore_pic+'</td></tr><tr><td>'+motivationscore_res+'<div style="margin-top:4px;"><a href="#?page=motivation-assessment&section=activities" onclick="go(\'motivation-assessment\')" class="link">Take the Motivation Assessment</a></div></td></tr></table>'

$('rp_lma').update(rp_lma);


//sls

slsdata = jar.get('slsdata');
if(slsdata==null){
	var rp_sls='<table width="100%"><tr><td><font size="4">Student Leadership Scale</font></td><td rowspan="2" width="52"><img src="img/failed.gif"></td></tr><tr><td>You have not completed the Student Ledaership Scale.  <div style="margin-top:4px;"><a href="#?page=student-leadership-scale&section=activities" onclick="go(\'student-leadership-scale\')" class="link">Take the Student Leadership Assessment</a></div></td></tr></table>'
}
else{
	var rp_sls='<table width="100%"><tr><td><font size="4">Student Leadership Scale</font></td><td rowspan="2" width="52"><img src="img/passed.gif"></td></tr><tr><td>You have completed the Student Leadership Scale. <div style="margin-top:4px;"><a href="#?page=student-leadership-scale&section=activities" onclick="go(\'student-leadership-scale\')" class="link">Take the Student Leadership Assessment</a> <a href="#?page=student-leadership-scale-results&section=activities" onclick="go(\'student-leadership-scale-results\')" class="link">View detailed report</a></div></td></tr></table>'
}
$('rp_sls').update(rp_sls);
}