Date.prototype.customFormat=function(formatString){ 
   var YYYY,YY,MMMM,MMM,MM,M,DDDD,DDD,DD,D,hhh,hh,h,mm,m,ss,s,ampm,dMod,th;
   YY = ((YYYY=this.getFullYear())+"").substr(2,2);
   MM = (M=this.getMonth()+1)<10?('0'+M):M;
   MMM = (MMMM=["January","February","March","April","May","June","July","August","September","October","November","December"][M-1]).substr(0,3);
   DD = (D=this.getDate())<10?('0'+D):D;
   DDD = (DDDD=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][this.getDay()]).substr(0,3);
   th=(D>=10&&D<=20)?'th':((dMod=D%10)==1)?'st':(dMod==2)?'nd':(dMod==3)?'rd':'th';
   formatString = formatString.replace("#YYYY#",YYYY).replace("#YY#",YY).replace("#MMMM#",MMMM).replace("#MMM#",MMM).replace("#MM#",MM).replace("#M#",M).replace("#DDDD#",DDDD).replace("#DDD#",DDD).replace("#DD#",DD).replace("#D#",D).replace("#th#",th);

   h=(hhh=this.getHours());
   if (h==0) h=24;
   if (h>12) h-=12;
   hh = h<10?('0'+h):h;
   ampm=hhh<12?'am':'pm';
   mm=(m=this.getMinutes())<10?('0'+m):m;
   ss=(s=this.getSeconds())<10?('0'+s):s;
   return formatString.replace("#hhh#",hhh).replace("#hh#",hh).replace("#h#",h).replace("#mm#",mm).replace("#m#",m).replace("#ss#",ss).replace("#s#",s).replace("#ampm#",ampm);
}
/** 
* Toggle next siblings visiblity and change links text to
*/
var showText = '[N&auml;yt&auml; ilmot]';
var hideText = '[Piilota ilmot]';

function toggleView(toggleLink) {
    var viewArea = toggleLink.nextSibling.nextSibling;
    if(toggleLink.innerHTML == showText) {
        viewArea.style.display = 'block';
        toggleLink.innerHTML = hideText;
    }
    else {
        viewArea.style.display = 'none';
        toggleLink.innerHTML = showText;        
    }
}


function initListeners() {
    dojo.event.connect(
        document.getElementById('openEntryProgramBtn'), 
        "onclick", 
        "initEntryAjaxAppJson");
    dojo.event.connect(
        document.getElementById('openEntryListBtn'), 
        "onclick", 
        "showSignedUsers");
    
}


/**
* Entry applications initializion  using json
*/
function initEntryAjaxAppJson() {
    document.getElementById('openEntryProgramBtn').disabled = true;
    startAjaxRequest();    
    var requestUri = SGL_JS_WEBROOT +"/index.php/entrycal/entrycalajax/action/get_users_json/entrycal_item_id/" + ENTRYCAL_ITEM_ID + "/";
    dojo.io.bind({
        url: requestUri,
        handle: function(type, data, evt){
            if(type == "load"){
                // do something with the data object
                eval('var users =' + data + ';');
                var userlist = document.getElementById('userlist');
                // empty table if coming from an other mode
                while(userlist.rows.length > 0) {userlist.deleteRow(0);}
                for(var i = 0 ; i < users.length ; i++) {
                    var row = document.createElement('tr');
                    var usr_id = users[i].usr_id;
                    row.id = 'usr' + usr_id;
                    row.appendChild(cCell(users[i].first_name));
                    row.appendChild(cCell(users[i].last_name));
                    row.appendChild(cCell(users[i].clubname));
                    row.appendChild(cCell('')); var time = users[i].time;
                    row.appendChild(cCell('')); var note = users[i].note;
                    row.appendChild(cCell('')); var entry = users[i].entry;
                    userlist.appendChild(row);
                    if (entry > 0) {
                        setEntrycalRemoveAction(usr_id, time, note);
                    } else {
                        setEntrycalAddAction(usr_id);
                    }
                }
                
                var usertable =  document.getElementById('usertable');
                usertable.style.display = 'block';
                document.getElementById('openEntryProgramBtn').style.display = 'none';
                // redisplay  entry list button if (possibly) closed
                document.getElementById('openEntryListBtn').style.display = 'block';
                document.getElementById('openEntryListBtn').disabled = false;
                finishAjaxRequest();
                
            }else if(type == "error"){
                // here, "data" is our error object
                // respond to the error here
                alert("Ajax engine init failed!");
            }else{
                // other types of events might get passed, handle them here
                alert("Ajax engine init failed!");
            }
        },
        mimetype: "text/plain"
    });
}

/**
* Get signed users to table
*/
function showSignedUsers() {
    document.getElementById('openEntryListBtn').disabled = true;
    startAjaxRequest();
    dojo.io.bind({
        url: SGL_JS_WEBROOT +"/index.php/entrycal/entrycalajax/action/get_signed_users_json/entrycal_item_id/" + ENTRYCAL_ITEM_ID + "/",
        handle: function(type, data, evt){
            if(type == "load"){
                // do something with the data object
                eval('var users =' + data + ';');
                var userlist = document.getElementById('userlist');
                while(userlist.rows.length > 0) {userlist.deleteRow(0);}
                var usertable =  document.getElementById('usertable');
                for(var i = 0 ; i < users.length ; i++) {
                    var row = document.createElement('tr');
                    var usr_id = users[i].usr_id;
                    row.id = 'usr' + usr_id;
                    row.appendChild(cCell(users[i].first_name));
                    row.appendChild(cCell(users[i].last_name));
                    row.appendChild(cCell(users[i].clubname));
                    row.appendChild(cCell(users[i].time));
                    row.appendChild(cCell(users[i].note));
                    row.appendChild(cCell(''));
                    userlist.appendChild(row);
                }
                usertable.style.display = 'block';
                // enable going to editing entry list
                document.getElementById('openEntryProgramBtn').style.display = 'block';
                document.getElementById('openEntryProgramBtn').disabled = false;
                // disable button to enter this mode
                document.getElementById('openEntryListBtn').style.display = 'none';
                finishAjaxRequest();
            }else if(type == "error"){
                // here, "data" is our error object
                // respond to the error here
                alert("Ajax engine init failed!");
            }else{
                // other types of events might get passed, handle them here
                alert("Ajax engine init failed!");
            }
        },
        mimetype: "text/plain"
    });
    // also create summary
    startAjaxRequest();
    dojo.io.bind({
        url: SGL_JS_WEBROOT +"/index.php/entrycal/entrycalajax/action/get_report_json/entrycal_item_id/" + ENTRYCAL_ITEM_ID + "/",
        handle: function(type, data, evt){
            if(type == "load"){
                // do something with the data object
                eval('var clubs =' + data + ';');
                var clublist = document.getElementById('clublist');
                while(clublist.rows.length > 0) {clublist.deleteRow(0);}
                var summary =  document.getElementById('summary');
                var total = 0;
                for(var i = 0 ; i < clubs.length ; i++) {
                    var row = document.createElement('tr');
                    row.appendChild(cCell(clubs[i].clubname));
                    row.appendChild(cCell(clubs[i].count));
                    total += parseInt(clubs[i].count);
                    clublist.appendChild(row);
                }
                var row = document.createElement('tr');
                row.appendChild(cCell("Total"));
                row.appendChild(cCell(total));
                clublist.appendChild(row);
                summary.style.display = 'block';
                finishAjaxRequest();
            }else if(type == "error"){
                // here, "data" is our error object
                // respond to the error here
                alert("Ajax engine init failed!");
            }else{
                // other types of events might get passed, handle them here
                alert("Ajax engine init failed!");
            }
        },
        mimetype: "text/plain"
    });
}


function cCell(text) {
    var cell = document.createElement('td');
    cell.appendChild(document.createTextNode(text));
    return cell;   
}
function getNodeValue(obj,tag)
{
    if (obj.getElementsByTagName(tag)[0] && obj.getElementsByTagName(tag)[0].firstChild) {
    	return obj.getElementsByTagName(tag)[0].firstChild.nodeValue;        
    } else {return '';}
}

/**
* Set remove button and action for it as well as metadata
*/
function setEntrycalRemoveAction(usr_id, time, note) {
    var userrow = document.getElementById('usr' + usr_id);
    // set time
    userrow.childNodes[3].innerHTML = time;
    // set note
    userrow.childNodes[4].innerHTML = note;
    // set action
    userrow.childNodes[5].innerHTML = '';
    var delButton = document.createElement('input');
    delButton.type = 'button';
    delButton.value = 'Poista ilmo';
    userrow.childNodes[5].appendChild(delButton);
    dojo.event.connect(
        delButton, 
        "onclick", 
        function(evt){
            delButton.disabled = true;
            removeEntry(usr_id);}
        );
    
}
/**
* Set add entry button and action for it as well as metadata
*/
function setEntrycalAddAction(usr_id) {
    var userrow = document.getElementById('usr' + usr_id);
    // reset time
    userrow.childNodes[3].innerHTML = '';
    // reset note
    userrow.childNodes[4].innerHTML = '';
    // set action
    var addButton = document.createElement('input');
    addButton.type = 'button';
    addButton.value = 'Ilmoita';
    var addWithNoteButton = document.createElement('input');
    addWithNoteButton.type = 'button';
    addWithNoteButton.value = 'Ilmoita...';
    userrow.childNodes[5].innerHTML = '';
    userrow.childNodes[5].appendChild(addButton);
    dojo.event.connect(
        addButton, 
        "onclick", 
        function(evt){
            addButton.disabled = true;
            addWithNoteButton.disabled = true;
            addEntry(usr_id, false);
        }
        );
    userrow.childNodes[5].appendChild(addWithNoteButton);
    dojo.event.connect(
        addWithNoteButton, 
        "onclick", 
        function(evt){
            addButton.disabled = true;
            addWithNoteButton.disabled = true;
            addEntry(usr_id, true);
        }
        );
    
}

function removeEntry(usr_id) {
    startAjaxRequest();
    var requestUri = SGL_JS_WEBROOT + "/index.php/entrycal/entrycalajax/action/"+ ENTRYCAL_REMOVE_CMD +"/usr_id/"+ usr_id +"/item_id/" + ENTRYCAL_ITEM_ID + "/";
    dojo.io.bind({
        url: requestUri,
        handle: function(type, data, evt){
            if(type == "load"){
                if(data == 'queryok') {
                    setEntrycalAddAction(usr_id);
                    finishAjaxRequest();
                } else {
                    alert('Error with asynchronous request. Someone else may have been editing user at same time or DB error occured. Try refreshing the page.');
                    finishAjaxRequest();
                }
            }else if(type == "error"){
                // here, "data" is our error object
                // respond to the error here
                alert("Ajax request failed!");
                finishAjaxRequest();
            }else{
                // other types of events might get passed, handle them here
            }
        },
        mimetype: "text/plain"
    });
}

function addEntry(usr_id, note) {
    var notetext = '-';
    if(note) {
        notetext = prompt("Kirjoita lisätieto ilmoittautumisen yhteyteen");
    }
    
    startAjaxRequest();
    var requestUri = SGL_JS_WEBROOT + "/index.php/entrycal/entrycalajax/action/"+ ENTRYCAL_ADD_CMD +"/usr_id/"+ usr_id +"/item_id/" + ENTRYCAL_ITEM_ID + "/note/" + unescape(notetext) +"/";
    dojo.io.bind({
        url: requestUri,
        handle: function(type, data, evt){
            if(type == "load"){
                if(data == 'queryok') {
                    var date = new Date()
                    setEntrycalRemoveAction(usr_id,date.customFormat('#MMMM# #D#, #YYYY#  #h#:#mm#'), notetext);
                    finishAjaxRequest();
                } else {
                    alert('Error with asynchronous request. Someone else may have been editing user at same time or DB error occured. Try refreshing the page.');
                    finishAjaxRequest();
                }
            }else if(type == "error"){
                // here, "data" is our error object
                // respond to the error here
                alert("Ajax request failed!");
                finishAjaxRequest();
            }else{
                // other types of events might get passed, handle them here
            }
        },
        mimetype: "text/plain"
    });
}

var requestsInQue = 0;

function startAjaxRequest() {
    requestsInQue++;
    var text;
    if (requestsInQue > 1) {
        text = '(' + requestsInQue +') Communicating with server...';
    } else {text = 'Communicating with server...';}
    ajaxStatus('on', text);
}
function finishAjaxRequest() {
    requestsInQue--;
    var text;
    if(requestsInQue > 0) {
        if(requestsInQue > 1) {
            text = '(' + requestsInQue +') Communicating with server...';
        } else {text = 'Communicating with server...';}
        ajaxStatus('on', text);
    } else {
        ajaxStatus('delayoff', 'Request completed', 2000);
    }
}

var ajaxStatusTimer;

function ajaxStatus(state, text, timeout) {
    switch(state) {
        case 'off':
            document.getElementById('ajaxInfo').style.display = 'none';
            break;
        case 'on':
            if (ajaxStatusTimer) {clearTimeout(ajaxStatusTimer);}
            document.getElementById('ajaxTxt').innerHTML = text;
            document.getElementById('ajaxImg').src =
                SGL_JS_WEBROOT + '/images/mozilla_giallo.gif';
            document.getElementById('ajaxInfo').style.display = 'block';
            break;
        case 'delayoff':
            document.getElementById('ajaxTxt').innerHTML = text;
            document.getElementById('ajaxImg').src =
            SGL_JS_WEBROOT + '/images/mozilla_giallo_halted.gif';
            document.getElementById('ajaxInfo').style.display = 'block';
            ajaxStatusTimer = setTimeout("ajaxStatus('off');",timeout);
            break;            
    }
}

