/*
This sheet takes care of all the ajax stuff, we load it, then it uses ajax to keep all the pages going.
No page specific code on this page please.

*/

app_zone = 'main';

/** array - Possible pagenames for main section @constant */
var pagenames = ['welcome','topics','teacher','msgboard','student','admin' ];
/** array - List of page names in history */
var myhistory = new Array(); //list of page names



$(document).ready(main_top)
/** These functions are used in the main section of the site
    @constructor */
function main_top(){

    /** Requests user_stats, then calls {@link stats_dialog}  
           @name click_handlers#user_stats
           @event
        */
    $('#user_stats').livequery('click', function(event) {
        doajax('user_stats',{},function(){stats_dialog(data)}) 
    });

    /** Opens a dialog that shows all the user stats 
         @param {object} data Object with snames and stats
      */
    var stats_dialog = function(data){
        var dtext = $('<div title="User Stats">Below is the number of pages each of the groups has completed in each section<br/><br/></div>');
        var tab = MakeTable(data.snames,data.stats);
        tab.appendTo(dtext);
        dtext.dialog({
            height: 600,width:500,modal: true,overlay: {backgroundColor: '#000',opacity: 0.5},
            buttons: {
                'Cool': function() {$(this).dialog('destroy').remove();}       
            },
            close:function(){$(this).dialog('destroy').remove()}
        });          
    }
    
    /** Loads the html for a page, then calls {@link getscript} 
         @param {string} pname Name of the page to open
      */
    getpage = function(pname){
        if (pagehtml[pname]){
            $('#fromajax').html(pagehtml[pname])
            getscript(pname);
        }
        else{
    		$('#fromajax').load('/rpc',{action:'getpage_main',data:$.toJSON({'pname':pname})},function(responseText, textStatus, XMLHttpRequest){
                if(textStatus!='success'){confirm('Could not load the page you tried '+pname)}
                else{
                    getscript(pname);
                    pagehtml[pname] = $('#fromajax').html();
                }
            });
        }
        myhistory.push(pname);
        pagename = pname;
	}; 
    
    /** Loads scripts and styles for a certain page by looking at elements on the page  
         @param {string} pname Name of the page to load elements for
      */
    var getscript = function(pname){
        var scripts = $('#pageinfo').attr('pscript');
        var styles = $('#pageinfo').attr('pssheet');
       
        if (currentstyle != styles){
            $('#pagestyle').attr('href',"/css/mainpages/"+styles+".css?version=1");
            currentstyle = styles;
        }
        if (scripts != currentscript){
            clearscripts();
            for(var i = 0; i < scripts.split(',').length; i++){
                $.ajax({
                   type: "GET",
                   url: "js/mainpages/"+scripts.split(',')[i]+".js",
                   dataType: "script"
                 });
             }
             currentscript = scripts;
        }  
    }


    
    /** Takes people to any page in the main section
           @name click_handlers#gotopg
           @event
        */
    $('[id^=gotopg]').livequery('click', function(event) {
        var pname = $(this).attr('pname');
        getpage(pname);
    });
    

     /** Opens a new window with a "printed page" must have a 'page' attribute that is the name of the page
           @name click_handlers#printpage
           @event
        */ 
    $('#printpage').livequery('click', function(event) {
        var name = $(this).attr('page');
    window.open('printedpages/'+name+'.html','Print_Me','width=400,height=200,toolbar=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes, resizable=yes')
    // window.open('printedpages/recycle18.html','PrintMe','width=400,height=200,toolbar=yes, location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes, resizable=yes')
    });
    
 
//BUTTON
    $(".button").livequery(function(){  
        $(this).addClass('buttonnothov');
        $(this).hover(function(){
             //happens on entry
                $(this).removeClass('buttonnothov');
    			$(this).addClass('buttonhov');
                
            }, function() {
                $(this).removeClass('buttonhov');
                $(this).addClass('buttonnothov');  
            });
    });
        
     /** Go to the previous page
           @name click_handlers#aback
           @event
        */ 
    $('#aback').click(function(){ 
        myhistory.pop(); 
        var prev = myhistory.pop();
        if (prev!=pagename){
            getpage(prev);
            myhistory.pop();
        }
	});
    
    /** Shows all the page info in a dialog, including pagename,currentscript,name,teacher,usrtype
           @name click_handlers#ainfo
           @event
        */ 
    $('#ainfo').click(function(){ 
        var dtext = $('<div title="Page Information"></div>'); 
        dtext.html('pname:&nbsp;'+pagename+'<br/>'+'currentscript:&nbsp;'+currentscript+'<br/>'+'name:&nbsp;'+name+'<br/>'+'teacher:&nbsp;'+teacher+'<br/>'+'usrtype:&nbsp;'+usrtype+'<br/>');
        dtext.dialog();
	});

    
    /** erases all cookies, goes to the welcome page
           @name click_handlers#logoff
           @event
        */
    $('#logoff').click(function(){ 
        eraseCookie('name');
        eraseCookie('usrtype');
        eraseCookie('teacher');
        getpage('welcome');
	});
    
    /** Goes to the teacher page if not already there, and if the current user is a teacher
           @name click_handlers#teachpage
           @event
        */
    $('#teachpage').click(function(){ 
        if(pagename!='teacher' && usrtype=='teacher'){getpage('teacher');}
	});
 
    /** Goes to the main parent page by changing the window location 
           @name click_handlers#parentpage
           @event
        */
    $('#parentpage').click(function(){ 
        window.location="/topics?topic=parent&num=5";
	});
    
         
   
//CLICKABLES   
	$('.sdiv').hide();
	$('[id^=cdiv]').livequery('click', function(event) {
		   $('.sdiv').hide(); 
		   $('#sdiv'+$(this).attr('id').slice(4,6)).show(); 
		   clickaction(parseInt($(this).attr('id').slice(4,6)),10)
	});	


   
   $(".teachertable").livequery(function(){
        $(this).tablesorter({
                                sortList:[[0,0],[2,1]], 
                                widgets: ['zebra']
                                });	
   })   
   
//Code ran when page is opened

    //COOKIES
    //confirm('after cookies')
    name = readCookie('name');
    usrtype = readCookie('usrtype');
    teacher =  readCookie('teacher');
    
    //ADD USER DIALOG
    prepare_usr_dlg('main');
    
    firstpname = $('#fpagename').html();
    if (!firstpname){
        firstpname = 'welcome';
        $('#header').hide();
    }
    getpage(firstpname);

};


