if (typeof console == "undefined") {
     window.console = {
        log: function () {}
    };
}

// calendar popup almost

$(function(){   
    // Datepicker calendar
    if($('.datepicker').length){
        $( ".datepicker" ).datepicker();
    }
});

$(function(){   
    // tabs
    if($('#fabtab1').length){
        $( "#fabtab1" ).tabs();
    }
});


var ActivityTimer = {
/*	ok this her function tracks time on task
 * 	if we keep sending call to updated the time, the session never ends
 * 	so we can send the page to logout if the timer hits two hours */

	initialize: function(){
        var dateobj = new Date();
		var timer=setInterval("ActivityTimer.markTime()",30000);
		this.timeon = 30;
		this.dateobj = dateobj;

        ($("#ti_aid")  != undefined ) ? this.aid  = $('#ti_aid').val()  : this.aid=0;
		($("#ti_asid") != undefined ) ? this.asid = $('#ti_asid').val() : this.asid=0;
		($("#ti_cuid") != undefined ) ? this.cuid = $('#ti_cuid').val() : this.cuid=0;
		($("#ti_prid") != undefined ) ? this.prid = $('#ti_prid').val() : this.prid=0;
		this.markTime();
	},
	markTime: function(){
        var timestamp = this.dateobj.getTime();
		this.timeon = this.timeon + 30;
		var pars = {'event':'markTime', 'aid':this.aid, 'asid':this.asid, 'cuid':this.cuid, 'prid':this.prid, 'timeon':this.timeon, 'now':timestamp };
		$.post("index.cfm", pars);
		if (this.timeon == 3600){ //if the page has been sitting for 1 hour, log out the user 
            document.location.href='index.cfm?event=logout';
		}
	}
}



$(function(){

	//finad all tool tips on page and automagically makes them
	$('[id^=trigger_]').switooltip();
	//new calpicker();

    if ($('#username')) {
        $('#username').focus();
    }
    if ($('#mobileNum')) {
        inputChecker.initialize();
    }
    if ( window.location.href.search(/showSummaryEssayGrade/i) > -1) {
        $('#feedback').show();
    }
	if ( window.location.href.search(/showSummary/i) > -1) {
		ActivityTimer = new ActivityTimer();
	}
	if ( window.location.href.search(/showEssay/i) > -1) {
		ActivityTimer = new ActivityTimer();
	}
	if ( window.location.href.search(/showQuiz/i) > -1) {
		ActivityTimer = new ActivityTimer();
	}
	if ( window.location.href.search(/showPeerReview/i) > -1) {
		ActivityTimer = new ActivityTimer();
	}
	if ( window.location.href.search(/pgjump/i) > -1) {
		ActivityTimer = new ActivityTimer();
	}
	if (document.getElementById('ti_asid')) {
		ActivityTimer.initialize();
	}
	if ( window.location.href.search(/showActivity/i) > -1) {
		ActivityTimer = new ActivityTimer();
	}


});

var calpicker =  {
	curCalTarget : 0,
	mycal : $('#mycal'),
	initialize: function(){
	},
	showcal : function(calID){
		calpicker.curCalTarget = $('#'+calID);
		$('#mycal').data("calID",calID);
		calCoords = calpicker.curCalTarget.offset();
		var ycal = (calCoords.top + 25)+"px";
		var xcal = (calCoords.left - 45)+"px";
		$('#mycal').css({'top' : ycal, 'left' : xcal, 'position':'absolute'});
		$('#mycal').toggle();
	},
	updatecal: function(newdate){
		$('#mycal').load('index.cfm?event=calChooserjq&date='+newdate);
	},
	choosedate: function(datechoosen){
		$('#' + $('#mycal').data("calID")).val(datechoosen);
		calpicker.closecal();
	},
	closecal:function(){
		$('#mycal').toggle();
	}
}

var subwindow;

function popupwin(aDocument)
{
	if (!subwindow || subwindow.closed)
	{ 
		subwindow = window.open(aDocument,"subwindow","width=660,height=635,resizable,scrollbars=yes");
	} else {
		subwindow.document.location.href = aDocument;
		subwindow.focus();
	}
}



$(function(){
	var txts = $('textarea');

	for(var i = 0, l = txts.length; i < l; i++) {
		if(/^[0-9]+$/.test(txts[i].getAttribute("maxlength"))) {
			txts[i].onkeyup = function() {
				var len = parseInt(this.getAttribute("maxlength"), 10);
				if(this.value.length > len) {
					alert('Maximum length exceeded: ' + len);
					this.value = this.value.substr(0, len);
					return false;
				}
			}
		}
	}
  
	//if ( window.location.href.search(/Assignments/i) > -1) {

        //Searcher.initialize();
		//ts.initialize();
    //}

	if ( $('#SearchString')) {
    	Searcher.initialize();
		//console.log('search');
    }

	if ($('swisortable')) {
		ts.initialize();
		//console.log('table');
    }

	
});


var Searcher = {
	initialize : function(){
		this.searchbox = $('#SearchString');
		this.searchbox.keyup(function() {
			Searcher.autocomplete();
		});
		this.searchbox.blur(function() {
			Searcher.hide();
		});
	},
	autocomplete: function(term){
		var	loading = false;
		//var sstrinput = $('#SearchString');
		var sstr = this.searchbox.val();
		var divtarget = $("#Search_Suggestions");
		var minchars = 1;
		if(sstr.length > minchars && loading != true) {
			loading = true;
			$.get("index.cfm",
				{ event:"searchResultsAjax", 'SearchString':sstr },
				function(data) { divtarget.html(data); loading = false;});
			divtarget.show();
			Coords = this.searchbox.offset();
			var ycal = (Coords.top + 25)+"px";
			var xcal = (Coords.left - 1)+"px";
			divtarget.css({'top' : ycal, 'left' : xcal, 'position':'absolute'});
		}
	},
	hide: function(term){
		$("#Search_Suggestions").delay(800).fadeOut(200);
	}
}




var inputChecker = {

	initialize: function(){

	},
	//add to numeric only form fields onkeypress="return inputChecker.requireNum(event);"
	requireNum: function(e){
		var unicode=e.charCode? e.charCode : e.keyCode;
		if (unicode!=8 && unicode!=9 && unicode!=37 && unicode!=39){ //if the key isn't the backspace key (which we should allow) 
			if (unicode < 48 || unicode > 57){ //if not a number
				return false; //disable key press 
			} else {
				return true; //disable key press 
			}
		}
	}
}



//tablesorter
var ts = {
	sortMethod : Array.sort,
	currentTable : false,
	currentTableBody : false,
	initialize : function(){
		ts.currentTable = $('.swisortable');
		ts.currentTableBody = ts.currentTable.find('tbody');
		//console.log($('.swisortable'));
		//console.log(ts.currentTable.find('thead>tr>th'));

		ts.currentTable.find('thead>tr>th').not('.ignore')
						.bind('click', function(event) {
							ts.sort(this);
						});
		ts.sort($('#sortDate'));
	},
	sort: function(thx) {
		ts.currentTable.find('thead>tr>th').removeClass('TbleSrt-down');
		ts.currentTable.find('thead>tr>th').removeClass('TbleSrt-up');
		th = $(thx);
		var thIndex = th.index() + 1;
		if(th.attr('sort') == 'sortDate'){
			ts.sortMethod = ts.sortDate;
		}else{
			ts.sortMethod = ts.sortCaseInsensitive;
		}
		//Get all the rows of employee grid
		var rows = this.currentTable.find('tbody>tr>td:nth-child(' + thIndex + ')');
		if (this.lastThIndex != thIndex){
			rows.sort(this.sortMethod).each(function() {
				trRow = $(this).parent();
				ts.currentTableBody.append(trRow);
			});
			th.addClass('TbleSrt-down');
			this.lastThDesc = 1;
		} else {
			//reversal -  no sort needed
			rows.each(function() {
				trRow = $(this).parent();
				ts.currentTableBody.prepend(trRow);
			});
			if (this.lastThDesc){
				th.addClass('TbleSrt-up');
				this.lastThDesc = 0;
			}else{
				th.addClass('TbleSrt-down');
				this.lastThDesc = 1;
			}
		}
		this.lastThIndex = thIndex;
	},
	sortDate : function(a,b) {
		var aa = $(a).html();
		var bb = $(b).html();
		var aasort = $(a).attr('sort');
		var bbsort = $(b).attr('sort');
		aa = $.trim(aa);
		bb = $.trim(bb);

		if (aa == '') {
			aa = '01/01/90';
		}
		if (bb == '') {
			bb = '01/01/90';
		}
		var dt1, dt2, yr = -1;
		
		if (aa.length == 10) {
			dt1 = aa.substr(6,4)+aa.substr(3,2)+aa.substr(0,2);
		} else {
			yr = '20'+aa.substr(6,2);
			dt1 = yr+aa.substr(0,2)+aa.substr(3,2);
		}
		
		if (bb.length == 10) {
			dt2 = bb.substr(6,4)+bb.substr(3,2)+bb.substr(0,2);
		} else {
			yr = '20' + bb.substr(6,2);
			dt2 = yr+bb.substr(0,2)+bb.substr(3,2);
		}

		if (dt1==dt2) {
			if (aasort==bbsort){
				return 0;
			} else if (aasort<bbsort){
				return -1;
			}
		} else if (dt1<dt2) {
			return -1;
		}
		return 1;
	},
	sortCaseInsensitive : function(a,b) {
		var aa = $(a).text().toLowerCase();
		var bb = $(b).text().toLowerCase();
		aa = $.trim(aa);
		bb = $.trim(bb);
		//console.log(aa + "<>" + bb);
		if (aa==bb) {
			return 0;
		} else if (aa == ' '){
			return -1;
		} else if (aa == ''){
			return -1;
		} else if (aa<bb) {
			return -1;
		} else {
			return 1;
		}
	}
}



////// Required for FCK editor and form serialize function/////
function fckUpdateClass()
{
  this.UpdateEditorFormValue = function()
  {
    for ( i = 0; i < parent.frames.length; ++i )
    if ( parent.frames[i].FCK )
    parent.frames[i].FCK.UpdateLinkedField();
  }
}
// instantiate the class
var FckUpdateObject = new fckUpdateClass();


$(function(){   
	if ($('#Rubric')) {
		LoStudentAssignment.initialize();

		if ($('#left-blog')) {
			LoStudentAssignment.leftdiv = "left-blog";
		}
	}
});

var LoStudentAssignment = {
/* 
 * this will take the rubric div and cover the left2 column.
 */
	yPos : 0,
	xPos : 0,

	initialize: function(){
		this.content = $('#Rubric');
		this.leftdiv = $('#left2');
        this.c = $('#left2').clone().empty();
	},
	rubric: function(){
        this.c = $('#left2').clone().empty();

		//this.content.absolutize(); 
		//this.content.clonePosition($(this.leftdiv)); 
        //console.log($('#left2').offset());
        c_pos = $('#left2').offset();
        //$('#Rubric').offset( {"left": c_pos.left, 'top':c_pos.top }); 
		//$('#left2').toggle();
        //$('#Rubric').show();
        // .outerWidth() takes into account border and padding.
        var c_width = $('#left2').width();
        var c_height = $('#left2').height();

        $('#Rubric').width(c_width);
        $('#Rubric').height(c_height);
        $('#Rubric').css({
            position: "absolute",
            'background-color': "#fff",
            'padding-left': "10px",
            'padding-right': "10px",
            top: c_pos.top + "px",
            left: c_pos.left + "px"
        }).show();
        //this.c.html($('#Rubric').html());
		//this.content.style.display = 'block';
		this.content.attr('background','#fff' );
		if($('#player')) {
			$('#player').toggle();
		}
	},
	assignment: function(){
        $('#Rubric').toggle();
		if($('#player')) {
			$('#player').toggle();
		}
	}
}


function newNoteBookFck() {
	var newFckNote = new FCKeditor("newNotefckEditor");
	//newFckNote.toolbarSet = "MGHajax" ;
	newFckNote.BasePath = "views/fckeditor/"
	newFckNote.CustomConfigurationsPath = "../mghConfig.js" ;
	$('#NewNote').show(); 
    newFckNote.ReplaceTextarea() ;
	//newFckNote.value=''; 
}

function notebookdelete(nid) {
    if (confirm('Are you sure you want to Delete this Note?')) {
        $.get('index.cfm?event=notebookDelete', {'notebookID':nid }, function(data) { $('#NoteBook_'+nid ).remove(); });
    }
}



