var returnUrl; // URL to return to after logging in.
var lastSelected;
var lastSelectedUnit;
var lastSelectedUnitPrint;
var lastSelectedTopic;
var lastSelectedfreeGame;
var languageCardURL;
var shouldReloadAfterLogin;
var unitNext=0;
var unitPrev=0;
var unitId = 0;

var xunitNext = 0;
var xunitPrev = 0;
var xunitId = 0;
var xLastUnit = 0;

var oldXref=0;
$(document).ready(function initLinks() {
	
	//Turn off the buttons until there is a selected worksheet.
	turnOffWorksheetButtons();	

	//only run this code if we have a unit list
	if (unitList) {
		
		// check if the scroller exist - scroller gets created if there is more than 8 unitlist
		if(unitList.length > 8){
			var isScroll  = true;
		}
	
		$("#prevButton").click(function() {
			eval($("#unitLink-"+unitPrev).click());
		
			if(isScroll){
				var element = $("#unitLink-"+unitNext);
				var topPos = document.getElementById('unitLink-'+(element[0]['id'].replace('unitLink-','')-1)).offsetTop;
				var verticalOffset = topPos-75;
				if (verticalOffset<0) verticalOffset=0;
				$('#browserScroller')[0].scrollTo(verticalOffset);
			}
		
			return;
		});
	    $("#nextButton").click(function() {
			eval($("#unitLink-"+unitNext).click());
			
			if(isScroll){
				var element = $("#unitLink-"+unitNext);
				var topPos = document.getElementById('unitLink-'+(element[0]['id'].replace('unitLink-','')-1)).offsetTop;
				var verticalOffset = topPos-75;
				if (verticalOffset<0) verticalOffset=0;
				$('#browserScroller')[0].scrollTo(verticalOffset);
			}
		
			return;
		});
		
		//line that causes whole numbers to drop down
		//eval($("#unitLink-"+unitNext).click());
		//eval(ftr+";");

		$("#unit-"+unitNext+",#title-"+unitNext).css("font-weight","bold");
		if ($("#unitLink-"+unitNext).attr('firstLoad')!=undefined) {
	    	var imageLoader = new rwtsLoadImage($("#worksheetImage"), '/resources/interactives/thumbnails/'+$("#unitLink-"+unitNext).attr('firstLoad'), false);
	    	imageLoader.load();
		}
	    lastSelectedUnit = $("#unitLink-"+unitNext).attr('firstLoad');
	    lastSelectedKind = $("#unitLink-"+unitNext).attr('firstKind');
	    lastSelected = unitNext;

		$("#prevButton").css("display","none");
  	        $("#nextButton").css("display","none");

		if (unitList.length > 1) {
			for (i=0;i<(unitList.length);i++)
		    {
				
		        if (i == unitId)
		        {
		          	unitNext = i+1;
					unitPrev = i-1;
					
		        	switch(i)
			        {   
			            case 0: //first item
			                $("#prevButton").css("display","none");
			                $("#nextButton").css("display","inline");
			                break;
			            case unitList.length-1: //last item
			                $("#nextButton").css("display","none");
			                $("#prevButton").css("display","inline");
			                break;
			            default:
			                $("#prevButton").css("display","inline");
			                $("#nextButton").css("display","inline");
			                break;
			        }
		        }
		    }
		}
		if(typeof anonymous == 'function') {
			anonymous();
		}
	}
});

function locateSelectedUnitByURL() {
	var myFile = document.location.toString();
	if (myFile.match('#')) { // the URL contains an anchor
	  // click the navigation item corresponding to the anchor
	  var myAnchor = myFile.split('#')[1];
	  //var myChapter = myAnchor.split('-')[0];
	  //var myUnit = myAnchor.split('-')[1];
	  var id=$('a[href="#'+myAnchor+'"]').attr('id');
	  var topPos = document.getElementById(id).offsetTop;
	  var verticalOffset = topPos-75;
	  if (verticalOffset<0) verticalOffset=0;
	  $('#browserScroller')[0].scrollTo(verticalOffset);
	  eval($('a[href="#'+myAnchor+'"]').click());
	} else {
		eval($("#unitLink-0").click());
	}
}


function turnOffWorksheetButtons(){
	$('#printWorksheet').css("display","none");
    $('#viewWhiteboard, #viewWhiteboardFlash').css("display","none");
	$('#crossReferenceWorksheet').css("display","none");
	$('#goToWorksheet').css("display","none");
}


function showWorksheetbuttons(){
    $('#printWorksheet').css("display","inline");
    $('#viewWhiteboard, #viewWhiteboardFlash').css("display","block");
    $('#crossReferenceWorksheet').css("display","inline");
	$('#goToWorksheet').css("display","inline");
}

function activateXref() {
	$('#crossReferenceBox').fadeIn('slow');
	$('#crossReferenceBox').load(lastSelectedUnit+'/crossref');
}

function showInteractive(topic, disableChampion) {
	if (topic == undefined) return;
	if (disableChampion == true) topic += "?nc=1";
	if (lastSelectedKind == 'questionmatch') {
        window.open('/resources/interactives/interactivewindow/'+topic,'','status=0,toolbar=0,location=0,menubar=0,resizable=0,scrollbars=0,width=876,height=660');
	} else {
		window.open('/resources/dragdrop/dragdropwindow/'+topic,'','status=0,toolbar=0,location=0,menubar=0,resizable=0,scrollbars=0,width=876,height=660');
	}
}

function showInteractivePreview(topic, login) {
        if (topic == undefined) return;
	if (lastSelectedTopic == 'Whole-Numbers' || lastSelectedTopic == 'Addition-and-Subtraction' || lastSelectedfreeGame == '1'){
		if (lastSelectedKind == 'questionmatch') {
        		window.open('/resources/interactives/interactivewindow/'+topic,'','status=0,toolbar=0,location=0,menubar=0,resizable=0,scrollbars=0,width=876,height=660');
        	} else {
                	window.open('/resources/dragdrop/dragdropwindow/'+topic,'','status=0,toolbar=0,location=0,menubar=0,resizable=0,scrollbars=0,width=876,height=660');
        	}
	}else{
		if(login == 'login'){
			shouldReloadAfterLogin = "true";
			showTb('/worksheets/login',false,550,300);
		}else{
			shouldReloadAfterLogin = "true";
			showTb('/worksheets/login/doupgrade',false,771,488);
		}
	}
}

function showlanguageCard() {//opens the language card in a new window. Only temperary until oym upgrade the language cards to Action Script 3 then we will load them in the whiteboard viewer
	//alert(lastSelectedUnit+"/languagecard");
	window.open(lastSelectedUnit+"/languagecard",'','status=0,toolbar=0,location=0,menubar=0,resizable=0,scrollbars=1,width=750,height=600');
}

function oldshowInteractive(topic) {
	$('#interactivecontent').html(AC_FL_RunContent(
    'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0',
    'width', '960',
    'height', '720',
    'src', '/load/interactives/question-match-template',
    'quality', 'high',
    'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
    'play', 'true',
    'loop', 'true',
    'scale', 'showall',
    'wmode', 'transparent',
    'devicefont', 'false',
    'id', 'question-match-template',
    'bgcolor', '#000000',
    'name', 'question-match-template',
    'menu', 'true',
    'allowFullScreen', 'false',
    'allowScriptAccess','always',
    'movie', '/load/interactives/question-match-template',
    'salign', '',
    'flashvars', 'configFile=/resources/interactives/'+topic
    ));
	$('#interactive').fadeIn();
}

function showXRef(linkId, year, topic, unitLabel, chapter) {
	var numLinkId = parseInt(linkId.replace("xref",""));
	xunitNext = numLinkId + 1;
	xunitPrev = numLinkId - 1;
	
	var imageLoader = new rwtsLoadImage($("#xrefBlock"), '/worksheets/'+topic+'/'+year+'/'+unitLabel+'/smthumb.jpg', false);
	imageLoader.load();
	if (oldXref) $('#'+oldXref).css('font-weight','');
	$('#'+linkId).css('font-weight','bold');
	oldXref=linkId;
	lastSelectedXrefUnit = '/worksheets/'+topic+'/'+year+'/'+unitLabel;
	lastSelectedXrefUnitPrint = '/worksheets/'+topic+'/'+year+'/'+unitLabel+'/'+chapter+'/print'; 
	
	
	$('#xRefWhiteboardButton').html(AC_FL_RunContent(
    'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0',
    'width', '116',
    'height', '38',
    'src', '/load/fsimage',
    'quality', 'high',
    'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
    'play', 'true',
    'loop', 'true',
    'scale', 'none',
    'wmode', 'transparent',
    'devicefont', 'false',
    'id', 'embed',
    'bgcolor', '#000000',
    'name', 'fsimage',
    'menu', 'true',
    'allowFullScreen', 'true',
    'allowScriptAccess','sameDomain',
    'movie', '/load/fsimage',
    'salign', '',
    'flashvars', 'image=/worksheets/'+topic+'/'+year+'/'+unitLabel+"/"+chapter+"/"
    )); //end AC code

	switch(numLinkId)
        {   
            case 0: //first item
                $("#xprevButton").css("display","none");
                $("#xnextButton").css("display","inline");
                break;
            case xLastUnit-1: //last item
                $("#xnextButton").css("display","none");
                $("#xprevButton").css("display","inline");
                break;
            default:
                $("#xprevButton").css("display","inline");
                $("#xnextButton").css("display","inline");
                break;
        }	
}

function showInteractiveThumb(unitId, name, kind, unit, freegame) {
	//4_Mult_Div_2-01
	//if (unitLabel == undefined) {
    // unitId = '0';
    // unitLabel = 'test';
    // chapter = '2';
    //}

	$(".unitCode,.unitTitle").css("font-weight","");
    $("#"+unit).css("display","block");
    $('#arrow_'+unit).attr("src", "/arrow1.png");
	$("#unit-"+unitId+",#title-"+unitId).css("font-weight","bold");

	$('#browserScroller').css({'height':'auto'});

	var $pane = $('#browserScroller');
	var $container = $pane.parent();
	var dragH = Math.max(Math.min((400 / $pane.innerHeight() * 366), 99999), 1);
	var $drag = jQuery('>.jScrollPaneTrack .jScrollPaneDrag', $container);
	$drag.css({'height':dragH+'px'});
	var $drag = jQuery('>.jScrollPaneTrack .jScrollPaneDrag', $container);
	if (($pane.innerHeight() / 400) < .99) {
		$drag.css({'display':'none'});
	} else {
		$drag.css({'display':'block'});
	}

    var imageLoader = new rwtsLoadImage($("#worksheetImage"), '/resources/interactives/thumbnails/'+name.replace('(','').replace(')',''), false);
    //var imageLoader = new rwtsLoadImage($("#worksheetImage"), '/var/www/OYM/public/fpdf/test_bg.jpg', false);
    imageLoader.load();
    lastSelectedUnit = name;
    lastSelectedKind = kind;
    lastSelected = unitId;
    lastSelectedTopic = unit;
    lastSelectedfreeGame = freegame;
    //$('#worksheetOptions').get(0).style.display = 'block';
	//if ($('#crossReferenceBox').css('display')!='none') {
	//	activateXref();
	//}
	
	//prev/next buttons
	if (unitList) {
		for (i=0;i<(unitList.length);i++)
	    {
			
	        if (i == unitId)
	        {
	          	unitNext = i+1;
				unitPrev = i-1;
				
	        	switch(i)
		        {   
		            case 0: //first item
		                $("#prevButton").css("display","none");
		                $("#nextButton").css("display","inline");
		                break;
		            case unitList.length-1: //last item
		                $("#nextButton").css("display","none");
		                $("#prevButton").css("display","inline");
		                break;
		            default:
		                $("#prevButton").css("display","inline");
		                $("#nextButton").css("display","inline");
		                break;
		        }
	        }
	    }
	}

    showWorksheetbuttons();
}

function showUnit(unitId, unitLabel, chapter, unit) {
	lastSelectedKind = 'questionmatch';
	window.unit=unitLabel;

	//bold selected unit
/*    if (unitLabel == undefined) {
     unitId = '0';
     unitLabel = 'test';
     chapter = '2';
    }*/
	if (unitLabel==undefined) {
		return true;
	}
	

        if($("#unit-"+unitId).length == 0 && $("#unitLink-"+unitId).length == 0 ){
		unitLabel = '';
		$("#worksheetImage").attr("src","/load/blank.gif");
                return;
        }

    
    if (jQuery('#mycarousel').length>0) {
	    //related resources carousel
		if (undefined!==window.myCarousel) {
		    var escUnitLabel = escape(unitLabel);
		    $.getJSON(escUnitLabel+"/"+chapter+"/related.json",
		    	function(json)
		    	{
    				myCarouselData = new Array();
					myCarousel.reset();
		    		for (i=0;i<json.length;i++)
		    		{	
						var linkUrl = '/worksheets/'+year+'/'+json[i]['image']+'/resource';
						if (linkUrl.search('interactiveresource') != -1) {
							var linkUrl = json[i]['image'].replace(/:/g,'_').replace('/interactiveresource','');
							myCarouselData[i] = "<div class='carouselItem' onclick='showInteractive(\""+linkUrl+"\")'><img src='/worksheets/"+topic+"/"+year+"/"+json[i]['image']+"/related-thumb.jpg' height='160' /><br />"+json[i]['title']+"</div>";
		    			} else {
		    				myCarouselData[i] = "<div class='carouselItem' onclick='showTb(\""+linkUrl+"\",false,800,520)'><img src='/worksheets/"+topic+"/"+year+"/"+json[i]['image']+"/related-thumb.jpg' height='160' /><br />"+json[i]['title']+"</div>";
		    			}
						
		    		}
		    		myCarousel.reset();
		       	}
			);
		} else {
			jQuery('#mycarousel').attr('unitId', unitId);
			jQuery('#mycarousel').attr('unitLabel', unitLabel);
			jQuery('#mycarousel').attr('chapter', chapter);
		}
	}
    
	
	$(".unitCode,.unitTitle,.unitRow").css("font-weight","");
    $("#unitLink-"+unitId).css("font-weight","bold");
    $("#unit-"+unitId+",#title-"+unitId).css("font-weight","bold");
    
    //$("#"+unit).css("display","block");
    //$("#browserScroller").scrollTo( "#unit-"+unitId, 1000, {offset: {top:75, left:0} });
    
    lastSelected = unitId;
	lastSelectedUnit = '/worksheets/'+topic+'/'+year+'/'+unitLabel;

	lastSelectedUnitPrint = '/worksheets/'+topic+'/'+year+'/'+unitLabel+'/'+chapter+'/print'; 
    switch (unitLabel) {
        case "test":
            var imageLoader = new rwtsLoadImage($('#worksheetImage'), '/worksheets/'+topic+'/'+year+'/test.jpg', '/theme/images/takeTheTest.png');
            break;
        case "test:Answers":
            var imageLoader = new rwtsLoadImage($('#worksheetImage'), '/worksheets/'+topic+'/'+year+'/testAnswers.jpg', false);
            break;
        case "test:Records":
            var imageLoader = new rwtsLoadImage($('#worksheetImage'), '/worksheets/'+topic+'/'+year+'/testRecords.jpg', false);
            break;
        default:
            var imageLoader = new rwtsLoadImage($("#worksheetImage"), '/worksheets/'+topic+'/'+year+'/'+unitLabel+'/thumb.jpg', false);
            break;
    }
	imageLoader.load();
	//unitId = unitId.replace('%','\\%');
	$("#worksheetDescription").html("<h3>"+$("#unit-"+unitId).html()+" - "+$("#title-"+unitId).html()+"</h3>"+$("#desc-"+unitId).html());
    
    $('#worksheetOptions').get(0).style.display = 'block';
    $('#whiteboardButton').html(AC_FL_RunContent(
    'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0',
    'width', '116',
    'height', '38',
    'src', '/load/fsimage',
    'quality', 'high',
    'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
    'play', 'true',
    'loop', 'true',
    'scale', 'none',
    'wmode', 'transparent',
    'devicefont', 'false',
    'id', 'embed',
    'bgcolor', '#000000',
    'name', 'fsimage',
    'menu', 'true',
    'allowFullScreen', 'true',
    'allowScriptAccess','sameDomain',
    'movie', '/load/fsimage',
    'salign', '',
    'flashvars', 'image=/worksheets/'+topic+'/'+year+'/'+unitLabel+"/"+chapter+"/"
    )); //end AC code

	//prev/next buttons
	if (unitList) {
		for (i=0;i<(unitList.length);i++)
	    {
	        if (i == unitId)
	        {

	            unitNext = i+1;
				unitPrev = i-1;
	        	switch(i)
		        {   
		            case 0: //first item
		                $("#prevButton").css("display","none");
		                $("#nextButton").css("display","inline");
		                break;
		            case unitList.length-1: //last item
		                $("#nextButton").css("display","none");
		                $("#prevButton").css("display","inline");
		                break;
		            default:
		                $("#prevButton").css("display","inline");
		                $("#nextButton").css("display","inline");
		                break;
		        }
	        }
	    }
	}
	showWorksheetbuttons();
	if ($('#crossReferenceBox').css('display')!='none') {
		activateXref();
	}
}
var ajaxTime = 30000;
var ajaxTimer;
var showingTb = false;

function statusCheck()
{
    $.getJSON("/worksheets/status",function(data)
    {
        switch(data.loginStatus)
        {
            case 'guest':
            case 'nosub':
                ajaxTime = 60000;
                break;
            case 'passexpired':
                showTb('/worksheets/login/expired',true,300,130);
                stopCheckingStatus(); // don't run anymore - user is stuck here until refresh or location change
                break;
            case 'sessionquota':
            /*    if(data.shouldNag && !showingTb)
                {
                    showTb('/worksheets/login/quota',true);
                }*/
                ajaxTime = 30000;
                break;
            case 'valid':
                ajaxTime = 30000;
        }
    });
    
    if(ajaxTime != 0)
    {
        clearTimeout(ajaxTimer);
        ajaxTimer = setTimeout(statusCheck,ajaxTime);
    }
}

function stopCheckingStatus()
{
    clearTimeout(ajaxTimer);
    ajaxTime = 0;
}

function startCheckingStatus()
{
    clearTimeout(ajaxTimer);
   /* statusCheck();Disabled as per alans request on the 26/02/10*/
}

// 300x140
function showTb(url,modal,width,height)
{
	if (url=='undefined/print') {
		return;
	}
	// a better test to make sure that the TB_window exists, rather than relying on flags
    if($("#TB_window")[0]!=undefined)
    {
        closeTb();
        setTimeout("_showTb('"+url+"',"+modal+","+width+","+height+")",1000);
 	    return;
	}
    else
    {
        //_showTb(url,modal,width,height);
		setTimeout("_showTb('"+url+"',"+modal+","+width+","+height+")",500);
    }
}

function showWhiteboard(url) {
  window.open(url, 'wb', 'top=0,left=0,width=' + window.screen.availWidth + ',height=' + window.screen.availHeight);
  return;
}

// --- don't call these directly - use the functions above ---
function _showTb(url,modal,width,height)
{
    tb_show('',url+'?TB_iframe=true&width='+width+'&height='+height+'&modal='+modal);
    showingTb = true;
	
	return;
}

function closeTb()
{
    tb_remove();
    showingTb = false;
}
function closeTB_reload()
{
	tb_remove();
    	showingTb = false;
	window.location.reload( true ); 
}
function flashChecker(){
	var requiredMajorVersion = 10;
	// Minor version of Flash required
	var requiredMinorVersion = 0;
	// Minor version of Flash required
	var requiredRevision = 0;
	
	//alert('flash Checker'+ typeof(DetectFlashVer) + requiredMajorVersion + requiredMinorVersion + requiredRevision);
	var hasReqestedVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);
	//alert('flash Checker'+ hasReqestedVersion);
	if(!hasReqestedVersion){
		//var pass = self.parent.sysCheck();
		//self.parent.showTb('/syscheck.html',true,800,600);
		var url = "http://www.adobe.com/go/getflash/";
		showTb(url,false,800,520);
		
	}
	return true;
}




