/*
 *  script containing all the panel related function
 *  Depends on jquery.
 *
 *  @author Elie Andraos <elie.andraos@letscod.com>
 */


 /*
  * a prototype function to center horizontally a dom element (toolbar panel basically)
  * relatively to the window
  */
  $.fn.setPanelMargins = function()
  {
    var elemWidth = $(this).width();   // dom element width
    var winWidth  = $(window).width(); // window width

    if(winWidth <= elemWidth)
      return;

    var left = winWidth  - elemWidth;
    left = Math.floor((left/2));

    $(this).css({'left': left+"px"});
  }


 /*
  * checks if the element is still being dragged inside the panel
  */
  function draggingInPanel(event)
  {
    var valid_x, valid_y;

    // window height, toolbar height
    var win_height     = $(window).height();
    var toolbar_height = $("div#fusion-toolbar-container").height();
    var panel_height   = $("div#toolbar-panel").height();

    var diff_Y =  win_height - (toolbar_height + event.clientY);

    if(diff_Y <= panel_height)
      valid_y = true;
    else
      valid_y = false;


    var wind_width    = $(window).width();
    var panel_width   = $("div#toolbar-panel").width();
    //because the panel is centered and relatively to the window size
    //we need to calculate the margin
    var margin   =  Math.ceil(((wind_width - panel_width) / 2 ));

    if( (event.clientX < margin) || (event.clientX > (panel_width + margin)) )
       valid_x = false;
    else
       valid_x = true;


    if(valid_x && valid_y)
       return true;
    else
       return false;
  }

  /*
   * loads the panel
   */
  function loadPanel(panelId)
  {
     if( !isPanelClosed() && ( getOpenedPanelReferer() == panelId ) )
     {
       //the panel is opened and the user clicked on the same toolbar icon
       closePanel();
       return;
     }

     var panel = $("div#fusion-toolbar #"+panelId);
     //debug(panel);
     $("div#panel-body").empty();
     $(panel).clone(true).removeClass("hidden").appendTo($("div#panel-body"));

    $("div#toolbar-panel").slideUp().show('fast', function () {
      //callback function after the panel shows to add custom events (draggable, dblclick, carousel ...)
      addPanelBehaviors();
    });

  }

  /*
   * Close the panel if opened
   */
  function closePanel()
  {
    if(isPanelClosed())
      return;

    $("div#toolbar-panel").slideDown().hide('fast');
  }

  /*
   *  function that checks if the toolbar panel is closed
   */
  function isPanelClosed()
  {
    if($("div#toolbar-panel").css("display") == "none")
      return true;
    else
      return false;
  }

  /*
   * returns which widget is loaded in the panel
   */
  function getOpenedPanelReferer()
  {
    if(isPanelClosed())
      return null;

    return $("div#panel-body").children(":first").attr("id");
  }

  /*
   * adds the draggable behaviors to the widgets inside the panel
   * bind the double click even to edit or add a widget
   * init a carousel for the widgets
   *
   */
  function addPanelBehaviors()
  {
     $("div#panel-body").find('.sff-widget').each(function() {

       $(this).dblclick(function(){
         // open widget edit form in modal
         $().modalLoadUrl($(this).fusionWidgetEditUrl());
       });

       // add draggable behavior
       $(this).draggable({
         helper: 'clone',
         revert: 'invalid',
         refreshPositions: true,
         appendTo: '#sff-widget-draggable',
         start: function(event, ui) {
           // on drag show the recycle (on the left)
           $("#fusion-toolbox-trash").show();
         },
         drag: function(event, ui)
         {
           // if the grabbale element is not inside the panel,
           // and the panel is not closed => close the panel
           if(!draggingInPanel(event) && !isPanelClosed())
             $("div#toolbar-panel").hide();
         },
         stop: function(event, ui)
         {
           $('#fusion-toolbox-trash').hide();
         }
       });
     })

     //init the recent widgets carousel items inside the panel
     var list = $('div#panel-body').find('ul.panel-used-widgets');
     if(list.length)
     {
       $(list).jcarousel( {scroll : 5} );
     }
  }


  /*
   *  updates the panel content live after the user performs custom widget actions
   * (add/edit or delete)
   *
   */
  function updatePanelContent(ajax_url)
  {
      // if the panel is closed, do nothing
      if(isPanelClosed())
        return false;

      var model_container_id  = $("div#panel-body").children(":nth-child(1)").attr('id');
      var prefix_id = "widget-";
      var suffix_id = "-panel";
      var count = (model_container_id.length - (prefix_id.length + suffix_id.length));
      current_model = model_container_id.substr(prefix_id.length, count);

      ajax_url = ajax_url.replace('__model__', current_model);

      $.get(ajax_url + '?' + $().timestamp(), function(data) {
        // update the div after the <li> in the carousel toolbar which contains the panel info,
        // in case the user opened it again
        $("ul.toolbar-carousel").find("#"+ model_container_id).find("div.recent-widgets").html(data);
        // update the recent widgets opened in the panel live
        if(!isPanelClosed())
        {
          $("div#panel-body").find("#"+ model_container_id).find("div.recent-widgets").html(data);
        }
        // add the draggable, dblclick and carousel behavior
        addPanelBehaviors();
        return true;
      });

      return false;
  }
