/**
 * Hack to make a generic multi state checkbox from the one made for the RMUI.
 * @todo: make the MSCheckbox generic and adapt a new one for RMUI for specific needs.
 */
if (typeof MSCheckbox != "undefined") {
   MultiStateCheckbox = Class.create(MSCheckbox, {
   // overload the click listener to skip all specific checks done when changing rights in the RMUI.
     createClickHandler: function(self) {
       return function(){
         // always return next state.
         self.next();
       }
     } 
  });
}

PageCreator = Class.create({
   initialize: function(element, baseURL) {
      this.form = $(element);
      this.baseURL = baseURL;
      this.input = this.form.down(".title");
      this.url = this.form.down(".url");
      this.clean = this.form.down(".clean");
      this.submit = this.form.down("input[type='button']") || this.form.down("button");
      if(typeof this.submit.disable == "function"){ 
        this.submit.disable();
      }
      Event.observe(this.input, "keyup", this.updateURL.bind(this));
   },
   updateURL:function(){
      updateName(this.input, this.clean);
      this.url.innerHTML = (this.baseURL + "<strong>" + $F(this.clean) + "</strong>");
      if (this.clean != "" && typeof this.submit.enable == "function") {
         this.submit.enable();
      }
   }
});
(function(){

if (typeof XWiki == "undefined") {
   XWiki = {};
}

if (typeof XWiki.MeetingManager == "undefined") {
   XWiki.MeetingManager = {};
}

var emailDialogBoxURL = "/xwiki/bin/view/MMCode/MeetingEmails";
var serviceURL = "/xwiki/bin/view/MMCode/MeetingManagerService?xpage=plain";
var addParticipantServiceURL = "/xwiki/bin/view/MMCode/MeetingAddParticipantService?xpage=plain&outputSyntax=plain";
var participantsServiceURL = "/xwiki/bin/view/MMCode/MeetingParticipantsService?xpage=plain";

document.observe("dom:loaded", function() {

  XWiki.currentDocument = $$("meta[name='page']")[0].content;
  XWiki.currentSpace = $$("meta[name='space']")[0].content;
  
  if ($('participant-suggest')) {
     Event.observe($('participant-suggest'), "focus", function(ev) {
        if (!$('participant-suggest').suggest) {
         var suggestURL = "/xwiki/bin/view/MMCode/MeetingParticipantSuggest?xpage=plain&meeting=" + XWiki.currentSpace + "." + XWiki.currentDocument + "&";
         $('participant-suggest').suggest = new ajaxSuggest(ev.element(), {
          script: suggestURL,
          varname:'input',
          seps: ',',
          callback: function(arg) {
            addPage(arg.info, arg.value);
            $('participantadd').disabled = false;
          }
         });
        }
     });
  }

  if($('addnewoption')) {
     Event.observe($('addnewoption'), "click", function(){
        $('newoption').toggleClassName("hidden");
     });
     if(typeof window.location.hash === "string" && window.location.hash == "#vote") {
        $('newoption').removeClassName("hidden")
     }
  }

  if ($('addparticipant')) {
     Event.observe($('addparticipant'), "click", function(){
        $('addparticipantinner').toggleClassName("hidden");
     });
     if(typeof window.location.hash === "string" && window.location.hash == "#participants") {
        $('addparticipantinner').removeClassName("hidden");
     }
  }

  if ($('participantadd')) {
     Event.observe($('participantadd'), "click", onAddParticipant);
  }

  if($('myparticipation') && $('savemyparticipation')) {
     Event.observe($('savemyparticipation'), "click", saveMyParticipation);
  }

  if($('modifymyparticipation')) {
     Event.observe($('modifymyparticipation'), "click", function(){
        $('myparticipation').removeClassName("hidden");
        $('myparticipation').up("li").addClassName("my");
     });
  }

  if($('mydisponibilities')) {
     makeMyDisponibilitiesEditable();
     Event.observe($('savemydisponibilities'), "click", updateMyDisponibilities);
  }

  if($('meetingdatetype')) {
     Event.observe($('meetingdatetypefixed'), "click", function() {
         $('meetingdatetype').addClassName("hidden");
         $('meetingdatefixed').removeClassName("hidden");
     });
     Event.observe($('meetingdatetypevote'), "click", function() {
         $('meetingdatetype').addClassName("hidden");
         $('meetingdatevote2').removeClassName("hidden");
     });
  }

  // forcing the date display to french
  // if you want english display you have to change it here
  // and change it also in MMCode.MeetingClass
  if($('MMCode.MeetingClass_0_date')) {
     new DatePicker({
       relative:'MMCode.MeetingClass_0_date',
       language:"en",
       dateFormat: [ ["dd", "mm", "yyyy"], "/" ]
     });
  }

  if ($('editmeetingdate')) {
     Event.observe($('editmeetingdate'), "click", function() {
        $('dateselection').toggleClassName("hidden");
     });
  }

  if($('startmeeting')) {
     Event.observe($('startmeeting'), "click", function(){
         Modalbox.show(serviceURL + "&service=startmeeting&meeting=" + XWiki.currentSpace + "." + XWiki.currentDocument, {
            title: "meetings.meeting.startmeeting"
         });
     });
  }

  if($('endmeeting')) {
     Event.observe($('endmeeting'), "click", function(){
         Modalbox.show(serviceURL + "&service=endmeeting&meeting=" + XWiki.currentSpace + "." + XWiki.currentDocument, {
            title: "meetings.meeting.endmeeting"
         });
     });
  }

  if($('makecycle')) {
     Event.observe($('makecycle'), "click", function(){
         Modalbox.show(serviceURL + "&service=makecycle&meeting=" + XWiki.currentSpace + "." + XWiki.currentDocument, {
            title: "meetings.meeting.makecycle"
         });
     });
  }

if($('endmeetingbottom')) {
     Event.observe($('endmeetingbottom'), "click", function(){
         Modalbox.show(serviceURL + "&service=endmeeting&meeting=" + XWiki.currentSpace + "." + XWiki.currentDocument, {
            title: "meetings.meeting.endmeeting"
         });
     });
  }

  if($('finishvote')) {
      Event.observe($('finishvote'), "click", function(evt) {
          Modalbox.show($('finishvoteinfo').down("div"), {"title": "meetings.meeting.vote.finish"});
      });
  }

  if($('validatedate')) {
     Event.observe($('validatedate'), "click", function(evt) {
        if(typeof XWiki.MeetingManager.map != "undefined")
        {
           XWiki.MeetingManager.map.unload();
        }
        var url = XWiki.getActionURL(XWiki.currentSpace, XWiki.currentDocument, "save", 0);
        var args = Form.serialize($('dateselection').down('form'), true);
        $('meetingdatedisplay').addClassName("loading");
        var ajx = new Ajax.Request(url, {
            method: "post",
            parameters: args,
            onComplete: function(transport) {
               var ajx2 = new Ajax.Request("/xwiki/bin/view/MMCode/MeetingDateSelection?xpage=plain" + "&meeting=" + XWiki.currentSpace + "." + XWiki.currentDocument, {
                  onSuccess: function(transport) {
                     $('meetingdatedisplay').removeClassName("loading");
                     $('dateselection').addClassName("hidden");
                     $('meetingdatedisplay').innerHTML = transport.responseText;
                     if($('dateselection').select("input[type='checkbox']")[0].value == "1") {
                         XWiki.MeetingManager.map = XMap($('map_canvas'), $('MMCode.MeetingClass_0_location').value, {
                              message: $('MMCode.MeetingClass_0_location').value,
                              zoom: 16
                         });
                     }

                  }
               });
            }
        });
        evt.stop(); // prevent form submit
     });
  }
});


function makeMyDisponibilitiesEditable() {
   var touchedAlready = 0;
   var options = $('mydisponibilities').select("div.my");
   for (var i=0;i<options.length;i++) {
      if (!options[i].up("td").hasClassName("unknown")) {
         touchedAlready = 1;
      }
    }
    displayMyDisponibilitiesOptionsForm();
    if (touchedAlready == 1)
{
        $('savemydisponibilities').innerHTML = "meetings.meeting.vote.update";
    }
} 

function displayMyDisponibilitiesOptionsForm() {
   var table = XWiki.MeetingManager.myDispos = new Array();
   $('mydisponibilities').select("div.my").each(function(elem) {
      var state = 0;
      if (elem.up("td").hasClassName("unavailable")) {
        state = 2;
      }
      else if (elem.up("td").hasClassName("available")) {
        state = 1;
      }                 
      table.push({
         element: elem,
         attemptId: elem.getAttribute("rel"),
         checkbox: new MultiStateCheckbox(elem, 0, "", state)
      });
   });
}

/**
 * Refactor this ugly code.
 */
function updateMyDisponibilities() {
   var md = XWiki.MeetingManager.myDispos;
   var available = "";
   var unavailable = "";
   var availableElements = [];
   var unavailableElements = [];
   var unknownElements = [];
   for (var i=0;i<md.length;i++) {
      if (md[i].checkbox.state == 1) {
        available += (md[i].attemptId + ",");
        availableElements.push(md[i].element.up("td"));
      }
      else if(md[i].checkbox.state == 2) {
        unavailable += (md[i].attemptId + ",");
        unavailableElements.push(md[i].element.up("td"));
      }
      else {
        unknownElements.push(md[i].element.up("td"));
      }
   }
   var queryString = "&MMCode.MeetingParticipantClass_" + $('myid').value + "_available=" + available;
   queryString += "&MMCode.MeetingParticipantClass_" + $('myid').value + "_unavailable=" + unavailable;
   var url = XWiki.getSaveURL() + queryString;
   var ajx = new Ajax.Request(url, {
      onComplete: function(transport){
         availableElements.each(function(el){
            el.removeClassName("unavailable"); 
            el.removeClassName("unknown");
            el.addClassName("available");
         });
         unavailableElements.each(function(el){
            el.removeClassName("available"); 
            el.removeClassName("unknown");
            el.addClassName("unavailable");
         });
         unknownElements.each(function(el){
            el.removeClassName("unavailable"); 
            el.removeClassName("available");
            el.addClassName("unknown");
         });
         $('savemydisponibilities').innerHTML = "meetings.meeting.vote.update";
      }
   });
   
}

function saveMyParticipation() {
   var qs = "";
   $('myparticipation').select("select","textarea").each(function(elem) {
       qs += ("&" + elem.id + "=" + elem.value);
   });
   var url = XWiki.getSaveURL() + qs;
   var presence = $('myparticipation').select("select")[0].value;
   var message = $('myparticipation').select("textarea")[0].value;
   var ajx = new Ajax.Request(url, {
      onSuccess: function(transport) {
         $('myparticipation').addClassName("hidden");
         $('myparticipation').up("li").removeClassName("my");
         $('myparticipation').up("li").removeClassName("undecided");
         $('myparticipation').up("li").removeClassName("confirmed");
         $('myparticipation').up("li").removeClassName("declined");
         $('myparticipation').up("li").addClassName(presence);
         $('myparticipation').up("li").down("span.participationmessage").innerHTML = "&quot;" + message + "&quot;";
         $('myparticipationmessage').innerHTML = message;
      }
   });
}

function onAddParticipant(event) {
   var participants = $('participant-input').value;
   if ($('participantaddnotif').checked) {
      displayEmailNotificationDialog(participants);
   }
   else {
      XWiki.MeetingManager.addParticipantToMeeting("");
   }
}

XWiki.MeetingManager.addParticipantToMeeting = function(withEmailParams) {
   // We only add the participants without sending emails
   var participants = $('participant-input').value;
   var url = addParticipantServiceURL + "&meeting=" + XWiki.currentSpace + "." + XWiki.currentDocument 
              + "&participants=" + participants + "&" + withEmailParams;
   var ajx = new Ajax.Request(url, {
      onComplete: function(transport) {         
         if (transport.responseText.startsWith("SUCCESS")) {
           // reset the users        
           $('participant-items').innerHTML = "";
           $('participant-input').value = "";
           // We can update the page
           var vurl = participantsServiceURL + "&meeting=" + XWiki.currentSpace + "." + XWiki.currentDocument;
           var ajx = new Ajax.Request(vurl, {
             onComplete: function(transport) {         
               $('participantscontent').innerHTML = transport.responseText;
             }
           });
         } else {
           alert("meetings.meeting.addparticipantserror");
         }
      }
   });
}

XWiki.MeetingManager.removeParticipant = function(nb) {
   var removeURL = XWiki.getActionURL(XWiki.currentSpace, XWiki.currentDocument, "objectremove") + "?classname=MMCode.MeetingParticipantClass&classid=" + nb;
   var ajx = new Ajax.Request(removeURL, {
      onComplete: function(transport) {         
       // We can update the page
       var vurl = participantsServiceURL + "&meeting=" + XWiki.currentSpace + "." + XWiki.currentDocument;
       var ajx2 = new Ajax.Request(vurl, {
          onComplete: function(transport) {         
             $('participantscontent').innerHTML = transport.responseText;
          }
       });
     }
   });
}

function escapeForXML(origtext) {
   return origtext.replace(/\&/g,'&'+'amp;').replace(/</g,'&'+'lt;').replace(/>/g,'&'+'gt;').replace(/\'/g,'&'+'apos;').replace(/\"/g,'&'+'quot;');
}
  
function removePage(tag, page, pageTitle) {
   tag.parentNode.parentNode.removeChild(tag.parentNode);
   updatePageList();
}
  
function addPage(obj) {
    var page = obj.info;
    var pageTitle = obj.value;
    addPage(page, pageTitle);
  }

function addPage(page, pageTitle) {
   var el = $("participant-items");
   var spage = escapeForXML(page);
   var spageTitle = escapeForXML(pageTitle);
   var li = document.createElement("li");
   var span = document.createElement("span");
   span.innerHTML = spageTitle;   
   span.className = "participant-item";
   span.value = page;
   var img = document.createElement("img");
   img.src = "/xwiki/bin/download/MMCode/MeetingManager/cross.gif?rev=1.3";
   img.onclick = function() { removePage(this, spage, spageTitle); };
   li.appendChild(span);
   li.appendChild(img);
   el.appendChild(li);
   updatePageList();
  }

// retrieves the current list of pages
function updatePageList() {
 var fld = $("participant-input");
 fld.value = getPageList();
 var suggestfld = $("participant-suggest");
 suggestfld.value = "";
}

// retrieves the current list of pages
function getPageList() {
  var docs = document.getElementsByClassName("participant-item");
  var i;
  var pages = "";
  for (i = 0; i < docs.length; i++)
  {
   var doc = docs[i];
   if (pages!="")
    pages += ",";
   pages += doc.value;
  }
  return pages;
 }

function displayEmailNotificationDialog(participants) {
   var url = emailDialogBoxURL + "?xpage=plain&participants=" + participants + "&meeting=" + XWiki.currentSpace + "." + XWiki.currentDocument + "&mail=MMCode.MeetingAddParticipantEmail";
   Modalbox.show(url, {title:"eMail de Notification", width:800});
}


XWiki.getActionURL = function(space, name, action, ajax) {
  if (XWiki.constants) {  
     return "" + XWiki.contextPath + "/" + XWiki.servletpath + action + "/" + space + "/" + name + (ajax ? "?ajax=1" : "");
  }
  else {
     return "/xwiki/bin/"+ action +"/" + space + "/" + name + (ajax ? "?ajax=1" : "");
  }
}

XWiki.getSaveURL = function(space, name) {
   if (!space && !name) {
      var space = XWiki.currentSpace;
      var name = XWiki.currentDocument;
   }
   return XWiki.getActionURL(space, name, "save", 1);
}

XWiki.MeetingManager.sendMails = function() {
    var options = {
       sendmail: "1",
       participants: $('participants').value,
       emails: $('recipient').value,
       template: $('template').value,
       meeting: $('meeting').value,
       mailnote: $('mailnote').value
    };
    var qs = "";
    for(o in options) {
      qs += ("&" + o + "=" + options[o]);
    }
   XWiki.MeetingManager.addParticipantToMeeting(qs);
}

// email notification dialog box
window.NotificationMailBox = Class.create(Lightbox, {
  /**
   * Override initialize method
   */ 
  initialize: function($super, url, nextOpCallback) {
    $super(url)
    this.nextOpCallback = nextOpCallback;
  },

  /**
   * Skip the redirect on close = cancel
   */
  lbClose: function($super) {
    this.lbHide();
  }
 });

document.observe("dom:loaded", function() {
    // Remove shortcuts
    for (shortc in window.shortcut.all_shortcuts) {
        window.shortcut.remove(shortc);
    }

    Event.observe($('createnewmeeting'), "click", function(){
      Modalbox.show($('newmeetingform').down('form'), {
        title: this.title,
        overlayClose: false,
        width:800,
        afterLoad: function() {
          var url = location.protocol + "//" + location.hostname + XWiki.getActionURL(XWiki.currentSpace, "", "view", 0);
          var p = new PageCreator($('MB_content').down("form"), url);
        }
      });
    });

});
})();

