// TODO: toolbar als login
/* ClassRoom */
function ClassRoom(mainCrDivStr)
{
//vars
this.mainCrDivStr = mainCrDivStr;
this.people = new Array();

//methods
this.addPerson = addPerson;
this.updateDiv = updateDiv;


}

var rol;
var randnr = Math.random();
//setTimeout('document.write', 1000, '<script src=\"/ajax/get_messages/'+randnr+'\"></script>');
// TODO: http://brainerror.net/scripts/javascript/blendtrans/

function addPerson(anId,aName,aRole,aGender)
{
  if(!aGender) aGender = 'm';
  p = new Person(anId,aName,aRole,aGender);
  this.people[this.people.length] = p;
//   alert("Hi, I'm part of the "+this.people.length+" people here.");
  this.updateDiv();
  return p;
}

function updateDiv ()
{
if(!document.getElementById('classRoom1')) return false;

crDiv = document.getElementById('classRoom1');
crDiv.innerHTML = '';
for(var n=0;n<this.people.length;n++)
{
//   alert(this.people[n].getHtml());
  crDiv.innerHTML += this.people[n].getHtml();
//    $('#person'+n).click(function(e){
      //document.getElementById('person'+n).showBalloon(n);
//      $('#sayBalloon'+n).css('visibility','visible');
//      $('#sayBalloon'+n).fadeIn();
//alert('clicked '+n);
//  });////$('#sayBalloon1').css('visibility: visible');
  document.getElementById('container'+n).style.left = (128*n)+'px';
//  $('#container'+n).css('left: '+(128*n)+'px');
//   document.getElementById('container'+n).style.position = 'fixed';
//   document.getElementById('person'+n).style.left = (128*n)+'px';
//   document.getElementById('sayBalloon'+n).style.left = (128*n)+'px';
//   document.getElementById('thinkBalloon'+n).style.left = (128*n)+'px';
}
}

/* PERSON */

function Person(anId,aName,aRole,aGender)
{
//vars
  this.id = anId;
  this.myName = aName;
  this.myRole = aRole;
  this.myGender = aGender;
//   this.sayBalloon = new Object;
//   this.thinkBalloon = new Object;

//methods
  this.setName = setName;
  this.getHtml = getHtml;
  this.say = say;
  this.think = think;
  this.showBalloon = showBalloon;

//   alert("Hi, I'm new here. My name is "+this.myName);
}

function getHtml()
{
  var out = '';
//  var ev='onclick="$(\'#sayBalloon'+this.id+'\').css(\'visibility\',\'\');"$(\'#sayBalloon'+this.id+'\').fadeIn();"';
  var ev='onmouseover="ev(\'person'+this.id+'\',\'person\',\'mouseover\')" onmouseout="ev(\'person'+this.id+'\',\'person\',\'mouseout\')" onclick="ev(\'person'+this.id+'\',\'person\',\'click\')"';
// var ev='onmouseover="ev(';+this.id+','onmouseover')"';

  out += '<img id="person'+this.id+'" '+ev+' src="'+roleToImg(this.myRole,'64',this.myGender,true)+'">';
//  if(this.myRole=='leerling')
//
//  if(this.myRole=='leerkracht') out += '<img id="person'+this.id+'" '+ev+' src="'+GUI_URL+'/res/pic/ico/rollen/rol-leerkracht-'+this.myGender+'-sh64.png">';
//  if(this.myRole=='beheerder') out += '<img id="person'+this.id+'" '+ev+' src="'+GUI_URL+'/res/pic/ico/rollen/rol-beheerder-sh64.png">';
//  if(this.myRole=='supervisor') out += '<img id="person'+this.id+'" '+ev+' src="'+GUI_URL+'/res/pic/ico/rollen/rol-webmaster-sh64.png">';
//  if(this.myRole=='webmaster') out += '<img id="person'+this.id+'" '+ev+' src="'+GUI_URL+'/res/pic/ico/rollen/rol-webmaster-sh64.png">';
  // /res/pic/ico/rollen/groep-sh.png
  var evSay=ev.replace(/\'person/g,'\'sayBalloon',true);
  var evThink=ev.replace(/\'person/g,'\'thinkBalloon',true);
  out += '<div class="balloon" id="sayBalloon'+this.id+'" '+evSay+'>Ik heb niets te zeggen...</div>';
  out += '<div class="balloonThought" id="thinkBalloon'+this.id+'" '+evThink+'>Zzzz....</div>';

  out = '<div class="pcontainer" id="container'+this.id+'">'+out+'</div>';
  return out;
}

function setName(aName)
{
  this.myName = aName;
}
function say(aStr,balloonType)
{
  if(!balloonType) balloonType = 'say';
  balloon = document.getElementById(balloonType+'Balloon'+this.id);
  balloon.innerHTML = aStr;
  balloon.style.fontWeight = "normal";
  this.showBalloon(this.id,balloonType);
}

function showBalloon(balloonId,balloonType)
{
  if(!balloonType) balloonType = 'say';
//  $('#'+balloonType+'Balloon'+this.id).fadeIn();
  balloon = document.getElementById(balloonType+'Balloon'+balloonId);
//  $(balloon).fadeIn('slow');
  balloon.style.visibility='visible';
//  $(balloon).fadeIn('slow');
//  $('#'+objId).parent().find('div.balloon').css('visibility','visible');
}

function think(aStr)
{
  this.say(aStr,'think');
}




//
function ev(objId,objClass,myEventType)
{
  id=parseInt(objId.replace(/[a-z]+/i,''));
  if(((objClass=='sayBalloon') || (objClass=='thinkBalloon')) && (myEventType=='click'))
//    document.getElementById(objId).style.visibility = 'hidden';
    {
//        $(objId).fadeOut();
        $('#'+objId).parent().find('div.balloon').css('visibility','hidden');
        $('#'+objId).parent().find('div.balloonThought').css('visibility','hidden');

    }
  if((objClass=='person') && (myEventType=='click'))
  {
    $('#'+objId).parent().find('div.balloon').css('visibility','visible');
//    $('#'+objId).parent().find('div.balloon').fadeIn();
//    alert('clicked'+objId.id);
  }
//    document.getElementById('sayBalloon'+id).style.visibility='visible';

//   else alert(myEventType+' '+document.getElementById(objId).id);
}
function roleToImg(roleName,size,gender,justImgUrl)
{
    if(!gender) gender = 'm';//N.B. m = meisje voor leerling!
    if(!size) size = '64';
    if(roleName=='supervisor') roleName = 'webmaster';
    imgUrl = GUI_URL+'/res/pic/ico/rollen/rol-'+roleName+'-'+(gender=='m'?'m':'v')+'-sh'+size+'.png';
    if(roleName=='leerling')
        imgUrl = GUI_URL+'/res/pic/ico/rollen/rol-'+roleName+'-'+(gender=='m'?'j':'m')+'-sh'+size+'.png';
    if(roleName=='webmaster')
        imgUrl = GUI_URL+'/res/pic/ico/rollen/rol-'+roleName+'-sh'+size+'.png';
    if(roleName=='groep')
        imgUrl = GUI_URL+'/res/pic/ico/rollen/groep-sh.png';
    if(justImgUrl)
        return imgUrl;
    return '<img src="'+imgUrl+'">';
}

function initKlas()
{
    $('body').append('<div id="classRoom1" class="poppetjes"></div>');
    var pnr=0;
    myClassRoom = new ClassRoom();
    wm = myClassRoom.addPerson( (pnr++),'Erik','webmaster','m' );

    if(rol=='leerling')
    {
        if(geslacht=='m')
            llm = myClassRoom.addPerson( (pnr++),'leerling','leerling','m' );
        if(geslacht=='v')
            llm = myClassRoom.addPerson( (pnr++),'leerling','leerling','v' );
    }
    if(rol=='leerkracht')
    {
        llm = myClassRoom.addPerson( (pnr++),'leerling','leerling','m' );
    }
    lk = myClassRoom.addPerson( (pnr++),'leerkracht','leerkracht','m' );
    //wm.say('Je bent niet ingelogd.');


}

function initDigicom()
{
    //if(rol)  && rol=='leerling') var leerling_id=userid;
    
    makePopup('comVlak',{highLight:false, closeButton: false}).removeClass('vlak').addClass('comVlak').addClass('vlak').removeClass('myPopup');
    $('#comVlak .content').append('<div id="digicom"></div>');

    t='<b>Stuur bericht</b>';
    t+='<div id="sendToLeerling"><img src="'+GUI_URL+'/res/pic/ico/rollen/rol-leerling-j-sh64.png"/><br><b>aan leerling</b></div><br>';
    if(rol=='leerling')
        t+='<div id="sendToLeerkracht"><img src="'+GUI_URL+'/res/pic/ico/rollen/rol-leerkracht-m-sh64.png"/><br><b>aan leerkracht</b></div><br>';
    if(rol=='leerkracht')
    {
        t+='<div id="sendToGroep"><img src="'+GUI_URL+'/res/pic/ico/rollen/groep-sh.png"/><br><b>aan groep</b></div><br>';
        t+='<div id="sendToWebmaster"><img src="'+GUI_URL+'/res/pic/ico/rollen/rol-webmaster-sh64.png"/><br><b>aan webmaster</b></div><br>';
    }
    $('#digicom').hide().css('text-align','center');
    $('#digicom').html(t);
    $('#digicom > div').click(function(){composeMsg(this);});
    $('#digicom > div').hover(
        function(){$(this).css({background:'#ccccff', cursor: 'pointer'}).css('-moz-border-radius','10px')},
        function(){$(this).css('background','')}
    );


    r=$(document).width() - 55;

    //$('#comVlak').css('right', ''+toString(window.innerWidth - 55) );
    $('#comVlak').css('right', r.toString()+'px' );
    
    $('#digicom').show();
/*
if(interFaceLoaded==false)
    {
        $.ajax({
           type: "GET",
           url: GUI_URL+"/res/ui.core.js",
           success: function(){
                $.ajax({
                   type: "GET",
                   url: GUI_URL+"/res/ui.core.js",
                   success: function(){
                        $('#comVlak').draggable();
                        interFaceJsLoaded = true;
                   }
               },
               dataType: "script",
               cache: true

            });
           },
           dataType: "script",
           cache: true

        });
    }
*/
        $('#comVlak').hover(
            function(){digiComMouseState = 'over'; digiComVisible(true);},
            function(){digiComMouseState = 'out'; setTimeout('digiComVisible(false)',1000);}
        );

    makePopup('msgPopup',{highLight:false, closeButton: true});
    //$('#msgPopup').draggable();

    checkMsg();

}

var digiComMouseState;
//var adjust1 = 15;
//var is_chrome = /chrome/.test( navigator.userAgent.toLowerCase() );
//if($.browser.safari) adjust1 = 15; // g chrome
//var interFaceLoaded = false;

function digiComVisible(makeVisible)
{
    if(makeVisible)
    {
        if(isOpera) $('#comVlak').animate({ left: -28 });
        else
        $('#comVlak').animate({ right: $(document).width() - $('#comVlak').width() + 18 });
    } else
    {
        if(digiComMouseState == 'out')
            {
                if(isOpera) $('#comVlak').animate({left: -138 },'slow');
                else
                $('#comVlak').animate({right: $(document).width() - 55 },'slow');
                
            }
    }

}

function makePopup(popupId,settings)
{//,highLight,closeButton
//    if($('#'+popupId).fadeIn('fast')) return false;// if it already exists, just show it.
    vlak_html_tmp = vlak_html.replace('nieuwVlak',popupId);
    $('body').append(vlak_html_tmp);
    //$('#nieuwVlak').attr('id',popupId);
    // nvlak = document.getElementById('nieuwVlak');
    // mvlak.id = popupId;

    //alert($('#nieuwVlak').html());
    $('#'+popupId).addClass('myPopup');
    if(settings['closeButton'])
        $('#'+popupId+' .tr1 .tdc').append('<a class="close" href="#close" accesskey="x" title="Venster sluiten..." onclick="closePopup(\'#'+popupId+'\');">&nbsp;X&nbsp;</a>');
    return $('#'+popupId);
}

function closePopup(popup,speed)
{
    if(!speed) speed = 'normal';
    $('#backgroundPopup').css({visibility:'hidden'});
    $('#msgPopup .close').css({color:'white',background:'red'});
    $(popup).fadeOut(speed, function(){
        $('#msgPopup .close').css({color:'',background:''});
    });
}
function centerPopup(popupId)
{
//request data for centering
var windowWidth = document.documentElement.clientWidth;
var windowHeight = document.documentElement.clientHeight;
var popupHeight = $("#"+popupId).height();
var popupWidth = $("#"+popupId).width();
//centering
$("#"+popupId).css({
"position": "absolute",
"top": windowHeight/2-popupHeight/2,
"left": windowWidth/2-popupWidth/2
});
//only need force for IE6

//$("#"+popupId).css({
//"height": windowHeight
//});
}

var toRole = '';
function composeMsg(recipientDiv)
{
//    alert(recipientDiv.id);
    if(recipientDiv.id=='sendToLeerling') toRole='leerling';
    if(recipientDiv.id=='sendToLeerkracht') toRole='leerkracht';
    if(recipientDiv.id=='sendToGroep') toRole='groep';
    if(recipientDiv.id=='sendToWebmaster') toRole='webmaster';

    content =  'Bericht aan <b>'+toRole+'</b><br><br><div style="width:208px;text-align:center;">'+roleToImg(toRole,'64','m',false)+'</div><br>\n';
    $content = $('#msgPopup .content');
    $content.html(content+'<select id="recipientSelector" style="width:208px;"></select><br><br>');
    $.post('/ajax/getEventXML', {toRole:toRole}, function(xmlRet)
    {
//        alert(xmlRet);
        $('eventDoc',xmlRet).find('groepen').find('groep').each(function()
        {
            if(toRole=='leerling')
            {
                $('#recipientSelector').append('  <optgroup label="Groep '+this.getAttribute('code')+'">');
                  $(this).find('leerling').each(function(){
                      $('#recipientSelector').append('  <option value="'+this.getAttribute('id')+'">'+this.getAttribute('naam')+'</option>');

                });
                $('#recipientSelector').append('  </optgroup>');
            }
            if(toRole=='leerkracht')
            {
                $('#recipientSelector').append('  <optgroup label="Groep '+this.getAttribute('code')+'">');
                  $(this).find('leerkracht').each(function(){
                      $('#recipientSelector').append('  <option value="'+this.getAttribute('id')+'">'+this.getAttribute('naam')+'</option>');

                });
                $('#recipientSelector').append('  </optgroup>');
            }
            if(toRole=='webmaster')
            {
                $(this).find('webmaster').each(function(){
                      $('#recipientSelector').append('  <option value="'+this.getAttribute('id')+'">'+this.getAttribute('naam')+'</option>');

                });
            }
            if(toRole=='groep'){
                $('#recipientSelector').append('  <option value="'+this.getAttribute('id')+'">'+this.getAttribute('code')+'</option>');
            }
        });
    });
        
//        if(resTxt = $(xmlRet).find('failure').text())
//        $('#msgPopup .responseText').html('<span style="color:red;"><b>'+resTxt+'</b></span>');


    content = '<textarea id="msgContent" rows="5" style="width:205px;" onkeyup="if(this.value.length>90){this.value=this.value.substr(0,90);}"></textarea><br><br>';
    content += '<input type="submit" onclick="sendMsg();" accesskey="s" value="Stuur bericht..." /><br><br>';
    content += '<div class="responseText"></div>';
    $content.append(content);

    $msg=$('#msgPopup').css({top:50,left: 300,width:400}).fadeIn('fast');
    $('#msgContent').focus();
}

function sendMsg()
{
    if($('#msgContent').val().length==0) {
        $('#msgContent').focus();
        $('#msgPopup .responseText').html('Typ eerst een bericht.');
        return false;
    }
    $('#msgPopup .responseText').html('<img src="'+GUI_URL+'/res/pic/ajax-loader.gif"> Bezig met verzenden...');
    
    $.post('/ajax/send_msg', {contents:$('#msgContent').val(),toRole:toRole,toId:$('#recipientSelector option:selected').val()}, function(xmlRet){

//    	alert(xmlRet);
    	
        if(resTxt = $(xmlRet).find('success').text())
        {
            $('#msgPopup .responseText').html('<span style="color:green;"><b>Bericht aan \''+toRole+'\' is succesvol verzonden.</b></span>');
            $('#msgPopup .close').css({color:'white',background:'red'});
            setTimeout('closePopup("#msgPopup","slow")',1000);
        }
        if(resTxt = $(xmlRet).find('failure').text())
		{
	        $('#msgPopup .responseText').html('<span style="color:red;"><b>'+resTxt+'</b></span>');
		}
    });

}

var msg_items = [];
var msg_delay = 1000;

var wm;
var lk;
var llm;

function checkMsg()
{
    $.post('/ajax/getMsgXML', {foo:'bar'}, function(xmlRet)
    {
//		alert(xmlRet);
		
		msg_items = [];
		
        $('eventDoc',xmlRet).find('messages').find('message').each(function()
        {
            //msg['from_id'] = this.getAttribute('from_id');
            //msg['from_role'] = this.getAttribute('from_role');
            //msg['timestamp'] = this.getAttribute('timestamp');
            msg_items[msg_items.length] = this.getAttribute('timestamp');
            aPerson = wm;
            if(this.getAttribute('from_role')=='leerkracht') aPerson = lk;
            //if(this.getAttribute('from_role')=='beheerder') aPerson = new Person();
            if(this.getAttribute('from_role')=='leerling') aPerson = llm;
            if (aPerson) aPerson.say('<b>' + this.getAttribute('from_name') + '</b>:<br/>'+this.getAttribute('text'),'say');
            //console.log(aPerson.id);
            if (aPerson)
	            $('#container'+aPerson.id+' .balloon').bind('click',
                {
                    fromRole: this.getAttribute('from_role'),
                    fromId:this.getAttribute('from_id'),
                    timestamp:this.getAttribute('timestamp')
                },markAsRead);
            return false; //break
        });
        
//		alert(msg_items.length);
    
	    if (msg_items.length > 0 && !windowfocus)
	    {
	    	for (m = 0; m < msg_items.length; m++)
	    	{
	    		if (msg_items[m] > lastmsg)
	    		{
	    			lastmsg = msg_items[m];
			    	alert("Je hebt een bericht ontvangen!");
			    	windowfocus = true;
			    	break;
	    		}
	    	}
	    }
    });

    if (msg_items.length == 0) msg_delay += 500;
    if (msg_delay > 5000) msg_delay = 5000;

    setTimeout('checkMsg();', msg_delay);
}

var windowfocus = true;
window.onfocus = function(){windowfocus = true;};
window.onblur = function(){windowfocus = false;};
var lastmsg = "0000-00-00 00:00:00";

function markAsRead(event)
{
    $.post('/ajax/markAsRead', event.data);
}
//
//setTimeout("$('table.comVlak').mouseout(function(){$('#digicom').fadeOut();});",1000)
//


