/**
 * TOC:
 * - Komodo user message jQuery plugin
 * - Komodo sharing presentation dialog box
 * - Komodo watch tracking jQuery plugin
 * - Komodo user note form jQuery plugin
 * - Komodo playlist item creation dialog JQuery plugin
 */

/**
 * Komodo user message jQuery plugin
 * 
 * Initialize to the div that should be the dialog box
 * The dialog box should contain a form to submit with a relevant action attribut.
 * 
 * @param:  Object with the following required properties:
 *          - presentationId: the current presentation Id
 *          The following parameters are optional:
 *          - debugMode: Debug message should appear in the console
 *          - params: Some additional parameters to send
 ****************************************/
(function($){
  $.fn.extend({ 
    komodoUserMessage: function(params) {
      var defaults = {
        params:'&'
      };
      var options =  $.extend(defaults, params);
      var $this = $(this);
      var form = $this.find('form');
      var textarea = form.find('textarea');
      
      var init = function() {
        debug('Start komodoUserMessage');
        if(options.presentationId == null) debug('presentationId missing');
        
        form.find('button').button({icons: {primary:'ui-icon-mail-closed'} });
        form.submit(function(e){
          e.preventDefault();
          //no content... no message
          if(textarea.val()=='') return false;
          //current chapter related message
          if($('input[name=isReferingToChapter]').is(':checked')) options.params += '&timecode=' + Math.round(timecode);
          //send the message
          $.ajax({
            url: form.attr('action'), 
            data: form.serialize() + '&presentationId=' + options.presentationId + options.params,
            type: 'POST',
            success: function(data, status){
              textarea.removeClass('ui-autocomplete-loading');
              $this.find('.message').fadeIn('slow',function(){
                $(this).delay(3000).
                fadeOut('slow',function(){textarea.val('');});
              })
            },
            ajaxSend: function(){textarea.addClass('ui-autocomplete-loading');}
          });
        });
        //dialog box appear
        $this.dialog({resizable: false, width:330, height:225});
      };
      var debug = function(message) {
        if(options.debugMode && window.console) { 
          console.log(message);
        };
      };
      init();
    }
  });
})(jQuery);

/**
 * ZeroClipboard librarie
 * @see: http://code.google.com/p/zeroclipboard
 */
var ZeroClipboard={version:"1.0.7",clients:{},moviePath:"../ZeroClipboard.swf",nextId:1,$:function(a){if(typeof(a)=="string"){a=document.getElementById(a)}if(!a.addClass){a.hide=function(){this.style.display="none"};a.show=function(){this.style.display=""};a.addClass=function(b){this.removeClass(b);this.className+=" "+b};a.removeClass=function(d){var e=this.className.split(/\s+/);var b=-1;for(var c=0;c<e.length;c++){if(e[c]==d){b=c;c=e.length}}if(b>-1){e.splice(b,1);this.className=e.join(" ")}return this};a.hasClass=function(b){return !!this.className.match(new RegExp("\\s*"+b+"\\s*"))}}return a},setMoviePath:function(a){this.moviePath=a},dispatch:function(d,b,c){var a=this.clients[d];if(a){a.receiveEvent(b,c)}},register:function(b,a){this.clients[b]=a},getDOMObjectPosition:function(c,a){var b={left:0,top:0,width:c.width?c.width:c.offsetWidth,height:c.height?c.height:c.offsetHeight};while(c&&(c!=a)){b.left+=c.offsetLeft;b.top+=c.offsetTop;c=c.offsetParent}return b},Client:function(a){this.handlers={};this.id=ZeroClipboard.nextId++;this.movieId="ZeroClipboardMovie_"+this.id;ZeroClipboard.register(this.id,this);if(a){this.glue(a)}}};ZeroClipboard.Client.prototype={id:0,ready:false,movie:null,clipText:"",handCursorEnabled:true,cssEffects:true,handlers:null,glue:function(d,b,e){this.domElement=ZeroClipboard.$(d);var f=99;if(this.domElement.style.zIndex){f=parseInt(this.domElement.style.zIndex,10)+1}if(typeof(b)=="string"){b=ZeroClipboard.$(b)}else{if(typeof(b)=="undefined"){b=document.getElementsByTagName("body")[0]}}var c=ZeroClipboard.getDOMObjectPosition(this.domElement,b);this.div=document.createElement("div");var a=this.div.style;a.position="absolute";a.left=""+c.left+"px";a.top=""+c.top+"px";a.width=""+c.width+"px";a.height=""+c.height+"px";a.zIndex=f;if(typeof(e)=="object"){for(addedStyle in e){a[addedStyle]=e[addedStyle]}}b.appendChild(this.div);this.div.innerHTML=this.getHTML(c.width,c.height)},getHTML:function(d,a){var c="";var b="id="+this.id+"&width="+d+"&height="+a;if(navigator.userAgent.match(/MSIE/)){var e=location.href.match(/^https/i)?"https://":"http://";c+='<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="'+e+'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="'+d+'" height="'+a+'" id="'+this.movieId+'" align="middle"><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="false" /><param name="movie" value="'+ZeroClipboard.moviePath+'" /><param name="loop" value="false" /><param name="menu" value="false" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><param name="flashvars" value="'+b+'"/><param name="wmode" value="transparent"/></object>'}else{c+='<embed id="'+this.movieId+'" src="'+ZeroClipboard.moviePath+'" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="'+d+'" height="'+a+'" name="'+this.movieId+'" align="middle" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="'+b+'" wmode="transparent" />'}return c},hide:function(){if(this.div){this.div.style.left="-2000px"}},show:function(){this.reposition()},destroy:function(){if(this.domElement&&this.div){this.hide();this.div.innerHTML="";var a=document.getElementsByTagName("body")[0];try{a.removeChild(this.div)}catch(b){}this.domElement=null;this.div=null}},reposition:function(c){if(c){this.domElement=ZeroClipboard.$(c);if(!this.domElement){this.hide()}}if(this.domElement&&this.div){var b=ZeroClipboard.getDOMObjectPosition(this.domElement);var a=this.div.style;a.left=""+b.left+"px";a.top=""+b.top+"px"}},setText:function(a){this.clipText=a;if(this.ready){this.movie.setText(a)}},addEventListener:function(a,b){a=a.toString().toLowerCase().replace(/^on/,"");if(!this.handlers[a]){this.handlers[a]=[]}this.handlers[a].push(b)},setHandCursor:function(a){this.handCursorEnabled=a;if(this.ready){this.movie.setHandCursor(a)}},setCSSEffects:function(a){this.cssEffects=!!a},receiveEvent:function(d,e){d=d.toString().toLowerCase().replace(/^on/,"");switch(d){case"load":this.movie=document.getElementById(this.movieId);if(!this.movie){var c=this;setTimeout(function(){c.receiveEvent("load",null)},1);return}if(!this.ready&&navigator.userAgent.match(/Firefox/)&&navigator.userAgent.match(/Windows/)){var c=this;setTimeout(function(){c.receiveEvent("load",null)},100);this.ready=true;return}this.ready=true;this.movie.setText(this.clipText);this.movie.setHandCursor(this.handCursorEnabled);break;case"mouseover":if(this.domElement&&this.cssEffects){this.domElement.addClass("hover");if(this.recoverActive){this.domElement.addClass("active")}}break;case"mouseout":if(this.domElement&&this.cssEffects){this.recoverActive=false;if(this.domElement.hasClass("active")){this.domElement.removeClass("active");this.recoverActive=true}this.domElement.removeClass("hover")}break;case"mousedown":if(this.domElement&&this.cssEffects){this.domElement.addClass("active")}break;case"mouseup":if(this.domElement&&this.cssEffects){this.domElement.removeClass("active");this.recoverActive=false}break}if(this.handlers[d]){for(var b=0,a=this.handlers[d].length;b<a;b++){var f=this.handlers[d][b];if(typeof(f)=="function"){f(this,e)}else{if((typeof(f)=="object")&&(f.length==2)){f[0][f[1]](this,e)}else{if(typeof(f)=="string"){window[f](this,e)}}}}}}};


/**
 * Komodo sharing presentation dialog box
 * 
 * Initialize to the div that should be the dialog box
 * Copy/paste functionality is provided by the ZeroClipboard library
 * ZeroClipboard.swf is required and should be located on the relevant folder.
 * 
 * @param:  Object with the following required properties:
 *          - relativeUrlRoot: the relative URL root
 *          The following parameters are optional:
 *          - debugMode: Debug message should appear in the console
 ****************************************/
(function($){
  $.fn.extend({ 
    komodoSharingPresentation: function(params) {
      var defaults = {};
      var options =  $.extend(defaults, params);
      var $this = $(this);
      
      var init = function() {
        debug('Start komodoSharingPresentation');
       $('body').bind('tick', sync);
        $this.dialog({resizable: false});
        $this.find('button').button();
        ZeroClipboard.setMoviePath(options.relativeUrlRoot+"/js/ZeroClipboard.swf");
        var clipTimecode = new ZeroClipboard.Client();
        clipTimecode.glue("sharingInstantButtonTimecode", "sharingInstantDialog");
        clipTimecode.addEventListener('mouseDown', function(client) {
          href = document.location.href.split('#')[0].split('?')[0];
          clipTimecode.setText(href+'#'+Math.round(timecode));
          $this.find('.message').fadeIn('slow',function(){
            $(this).delay(3000).fadeOut('slow',function(){});
          })
        });
        var clipPres = new ZeroClipboard.Client();
        clipPres.glue("sharingInstantButtonPres", "sharingInstantDialog");
        clipPres.addEventListener( 'mouseDown', function(client) {
          href = document.location.href.split('#')[0].split('?')[0];
          clipPres.setText(href);
          $this.find('.message').fadeIn('slow',function(){
            $(this).delay(3000).fadeOut('slow',function(){});
          })
        });
      };
      var sync = function(e, timecode){
        console.log(timecode);
        $this.find('.sharingInstantTimecode').html(formatTime(window.timecode/1000));
      }
      var debug = function(message) {
        if(options.debugMode && window.console) { 
          console.log(message);
        };
      };
      var formatTime = function(_time) {
        var mins     = parseInt(_time/60,10);
        var secs     = parseInt(_time%60,10);
        var hs       = parseInt(mins/60,10);
        var mins     = parseInt(mins%60,10);
        if((hs==0)&&(mins==0)) {_time = "00:"+secs.toString();}
        else if(hs==0) {_time = (mins<10?"0"+mins.toString():mins.toString())+":"+(secs<10?"0"+secs.toString():secs.toString());}
        else {_time = hs.toString()+":"+(mins<10?"0"+mins.toString():mins.toString())+":"+(secs<10?"0"+secs.toString():secs.toString());}
        return _time;
      }
      init();
    }
  });
})(jQuery);

/**
 * Komodo watch tracking jQuery plugin
 * 
 * Periodically send information to the server
 * 
 * @param:  Object with the following required properties:
 *          - url: the script url to send to the data
 *          The following parameters are optional:
 *          - interval: The interval of time between two requests, default: 30s
 *          - debugMode: Debug message should appear in the console
 *          - params: Some optional parameters to add to the request
 ****************************************/
(function($){
  $.fn.extend({ 
    komodoWatchTracking: function(params) {
      var defaults = {
        interval:30,
        params:'&'
      };
      var options =  $.extend(defaults, params);
      var $this= $(this);
      var notes='';noteCount=0;
      var isNoteActivated=false;
      
      var init = function() {
        debug('Start komodoWatchTracking');
        setTimeout(function(){send()},options.interval*1000);
        $('body').bind('note-activate', noteActivate);
        $('body').bind('note-deactivate', noteDeactivate);
      };
      var send = function() {
        if(isNoteActivated) {
          notes='';noteCount=0;
          $.each($('.cli-note-form-user'), function(){
            isModified = $(this).find('input[name=isModified]');
            if(isModified.is(':checked')) {
              notes+='&timecodes['+noteCount+']='+$(this).find('input[name=timecode]').val();
              notes+='&notes['+noteCount+']=' + $(this).find('textarea').val();
              notes+='&mediaIds['+noteCount+']=' + $(this).find('input[name=mediaId]').val();
              isModified.attr('checked', false);
              noteCount++;
            }
          });
        }
        //preserve options.params untouched for the next loops
        var paramsToSend = notes + options.params
        $.ajax({
          url: options.url, 
          data:'timecode=' + timecode + '&interval=' + options.interval + paramsToSend, 
          success: function(data, status){
            // If at least one note was modified
            if(noteCount>0) {
              $('body').triggerHandler('message',[presentation.i18n[jQuery.fn.colibri.language].noteSaved]);
            }
          },
          type:'POST'
        });
        setTimeout(function(){send()},options.interval*1000)
      }
      var debug = function(message) {
        if(options.debugMode && window.console) { 
          console.log(message);
        };
      };
      var noteActivate = function() {isNoteActivated=true;}
      var noteDeactivate = function() {isNoteActivated=false;}
      init();
    }
  });
})(jQuery);

/**
 * Komodo user note form jQuery plugin
 * 
 * Set up a user note form
 ****************************************/
(function($){
  $.fn.extend({ 
    komodoUsernoteForm: function(params) {
      var defaults = {params:'&'};
      var options =  $.extend(defaults, params);
      
      var init = function() {
        debug('Start komodoUsernoteForm');
        window.onbeforeunload = checkSaving;
        $('.cli-note-form').each(function(){
          var form = $(this);
          form.mouseover(function(e){e.stopPropagation();});
          form.hover(showControls, hideControls);
          var menuButton = form.find('.cli-note-menu-button');
          menuButton.click(function(){
            window.onbeforeunload = null;
            showMenu(this, form);$(this).blur();
          }).mouseout(function(e){e.stopPropagation();})
        })
      };
      var checkSaving = function(){
        var savingRequired = false;
        $('.cli-note-form').each(function(){
          isModified = $(this).find('input[name=isModified]');
          if(isModified.is(':checked')) {savingRequired = true;}
        });
        if(savingRequired == true) {return options.savingMessage;}
      }
      var showControls = function(){
        $(this).find('.cli-note-menu-button').effect('slide', {direction:'up', mode:'show'}, 'fast').mouseover(function(e){e.stopPropagation();});
      };
      var hideControls = function(){
        $(this).find('.cli-note-menu-button').effect('slide', {direction:'down', mode:'hide'}, 'fast').mouseover(function(e){e.stopPropagation();});
      };
      var showMenu = function(menuButton, form){
        //current user note form
        if(form.hasClass('cli-note-form-user')){
          $('#noteSave').click(function(){saveNote(form)});
          $('#noteDelete').click(function(){deleteNote(form)});
          $('.cli-note-menu-user').css('display','block').position({
            of:menuButton,
            my:'right top',
            at:'right bottom',
            offset:'0 -2'
          }).mouseover(function(e){e.stopPropagation();}).mousemove(function(e){e.stopPropagation();});
        }
        //shared note form
        else if(form.hasClass('cli-note-form-shared')){
          $('#noteDelete').click(function(){deleteNote(form)});
          $('.cli-note-menu-shared').css('display','block').position({
            of:menuButton,
            my:'right top',
            at:'right bottom',
            offset:'0 -2'
          }).mouseover(function(e){e.stopPropagation();}).mousemove(function(e){e.stopPropagation();});
        }
        $('body').bind('mousemove.note',function(e){
          hideMenu(e);
          window.onbeforeunload = checkSaving;
        })
        //$('body').mousemove(function(e){hideMenu(e);});
      };
      var hideMenu = function(e){
        if( !$(e.target).hasClass('cli-note-menu') && 
            !$(e.target).hasClass('cli-note-menu-button') &&
            !$(e.target).hasClass('cli-note-menu-button-span')) {
          $('.cli-note-menu').css('display','none');
          $('.cli-note-menu a').unbind('mousemove.note');
          $('#noteSave').unbind();$('#noteDelete').unbind();
        }
      };
      /**
       * delete a user note
       * 
       * @param form, the DOM element
       */
      var deleteNote = function(form){
          $.ajax({
            url: options.url+'?operation=delete', 
            data: form.serialize() + options.params,
            type: 'POST',
            success: function(data, status){
              form.find('textarea').val('');
              form.find('textarea').css('height',14);
              form.find('input[name=isModified]').attr('checked',false);
              form.find('input[name=usernoteId]').val('');
              form.closest('div.cli-note-container-user').removeClass('cli-note-container-user-bg');
              if(form.hasClass('cli-note-form-shared')) form.effect('fold',500);
              $('body').triggerHandler('message',[presentation.i18n[jQuery.fn.colibri.language].noteDeleted]);
            }
          });
      };
      /**
       * save a user note
       * 
       * @param form, the DOM element
       */
      var saveNote = function(form){
          dataToSend = {
            'operation':'save'
          }
          notes='';noteCount=0;
          $.each($('.cli-note-form-user'), function(){
            isModified = $(this).find('input[name=isModified]');
            if(isModified.is(':checked')) {
              notes+='&timecodes['+noteCount+']='+$(this).find('input[name=timecode]').val();
              notes+='&notes['+noteCount+']=' + $(this).find('textarea').val();
              notes+='&mediaIds['+noteCount+']=' + $(this).find('input[name=mediaId]').val();
              isModified.attr('checked', false);
              noteCount++;
            }
          });
          $.ajax({
            url: options.url, 
            data: $.param(dataToSend) + notes + options.params,
            type: 'POST',
            success: function(data, status){
              form.find('input[name=usernoteId]').val(data.usernoteId);
              $('body').triggerHandler('message',[presentation.i18n[jQuery.fn.colibri.language].noteSaved]);
            },
            ajaxSend: function(){}
          })
      };
      var debug = function(message) {
        if(options.debugMode && window.console) { 
          console.log(message);
        };
      };
      init();
    }
  });
})(jQuery);

/**
 * Komodo playlist item creation dialog JQuery plugin
 * 
 * Initialize to the div that should be the dialog box
 * 
 * @param:  The following parameters are optional:
 *          - debugMode: Debug message should appear in the console
 ****************************************/
(function($){
  $.fn.extend({ 
    komodoPlaylistItemCreation: function(params) {
      var defaults = {};
      var options =  $.extend(defaults, params);
      var $this = $(this);
      var form = $this.find('form');
      var context = {} //an array of object {title:'',level:'',timecodeIn:'',timecodeOut:''}
      
      var init = function() {
        debug('Start komodoPlaylistItemCreation');
        $('body').bind('chapterChange', chapterChange);
        $this.dialog({autoOpen: false, resizable: false});
        $('.playlist-item-context').corner('3px');
        $this.find('button').button().click(function(e){
          e.preventDefault();
          $.ajax({
            url: form.attr('action'),
            data: form.serialize(),
            type: 'POST',
            success: function(data, status){
              $this.find('.message').fadeIn('slow',function(){
                $(this).delay(3000).fadeOut('slow',function(){});
              })
            }
          });
        });
      };
      /**
       * When the current chapter is set, the context should be written in the related div
       * and form inputs should be fulfilled
       */
      var chapterChange = function(e, timecode, _context){
        context = _context;
        var contextString = '<ul>';
        for(i=0;i<context.length;i++) {
          contextString += '<li class="level'+context[i].level+'"><a href="javascript:;">'+context[i].title+'</a></li>';
        }
        $('.playlist-item-context').html(contextString + '</ul>');
        form.find('input[name=mediaId]').val(context[context.length-1].mediaId);
        form.find('input[name=timecodeIn]').val(context[context.length-1].timecodeIn);
        form.find('input[name=timecodeOut]').val(context[context.length-1].timecodeOut)
      };
      var debug = function(message) {
        if(options.debugMode && window.console) { 
          console.log(message);
        };
      };
      init();
    }
  });
})(jQuery);

