// @codekit-prepend "gui.js"

(function($) {

MaterioFlag = function(){
  var _isLoadingList = false ;

  /**
  * init()
  */
  function init(){
    //trace('MaterioFlag :: init MaterioFlag');

    buildBlocks();

    $(document)
      .bind('flagGlobalAfterLinkUpdate', onFlaging)
      .bind('resultscompleted resultschanged', onResultsUpdated)
      .bind('init-scroller-pager', onInitScrollerPager)
      .bind('load-scroller-pager', onLoadScrollerPager)
      .bind('view-mode-changed', onViewModeChanged)
      .bind('history-state-change', onHistoryStateChange);

    ajaxifyLinks();

    // trigger updated event for direct html loading
    if(isList()){
      setTimeout(function(){
        triggerContentChanged();
      }, 10);
    }
  };

  function onFlaging(event){
    //trace('MaterioFlag :: onFlaging', event);
    refreshBlocks();
  };

  function onResultsUpdated(event){
    //trace('MaterioFlag :: onResultsUpdated', event);
    ajaxifyLinks(event.container);
  };

  function buildBlocks(activename){
    //trace('MaterioFlag :: buildBlocks', activename);

    if($('#block-materio-flag-materio-flag-mybookmarks').length){
      var type = 'bookmarks';
      var block = '#block-materio-flag-materio-flag-mybookmarks';
    }else if($('#block-materio-flag-materio-flag-mylists').length){
      var type = 'lists';
      var block = '#block-materio-flag-materio-flag-mylists';
    }

    if(type == 'lists'){

      // nav block
      $('a.open-list:not(.ajax-processed)', '#block-materio-flag-materio-flag-mylists-nav').each(function(index){
        $this = $(this)
          .bind('click', onClickOpenLink)
          .addClass('ajax-processed');

        var name = $this.attr('class').match(/flag_lists_[^_]+_[0-9]+/);
        // trace('MaterioFlag :: name', name);
        $('<span class="preview"><i class="icon-eye-open"></i></span>').attr('name', name).insertAfter($this).bind('click', onClickShowPreview);
      });
        
      // preview block
      $('section.flag-list:not(.ajax-processed)', '#block-materio-flag-materio-flag-mylists').each(function(index){
        var name = $(this).attr('class').match(/flag_lists_[^_]+_[0-9]+/);
        $('<i class="icon-remove"></i>').appendTo($('h2.listname', this)).attr('name', name).bind('click', onClickClosePreview);

        $('a.open-list',  this).bind('click', onClickOpenLink);
      
      }).addClass('ajax-processed');

      // trigger refresh block event for enabling lazyload images
      setTimeout(function(){
        $.event.trigger({
          type : 'my'+type+'-block-builded',
          block : block,
          name : name
        });  
      },10);
      
    }

    

    // trace('MaterioFlag :: activename', activename);
    if(activename == undefined)
      activename = readCookie('materiomyflaglistsopened');

    // trace('MaterioFlag :: activename', activename);
    if(activename)
      showPreview(activename);

    
  };

  function refreshBlocks(name){
    //trace('MaterioFlag :: refreshBlocks | name', name);
    if($('#block-materio-flag-materio-flag-mybookmarks').length){
      var type = 'bookmarks';
    }else if($('#block-materio-flag-materio-flag-mylists').length){
      var type = 'lists';
    }
    
    if(type != undefined){
      var id = '#block-materio-flag-materio-flag-my'+type;
      var url = Drupal.settings.basePath+Drupal.settings.pathPrefix+'materioflag/refresh/block/'+type;
      $.getJSON(url, function(json){
        //trace('MaterioFlag :: block refreshed '+type, json);
        
        $(id).replaceWith(json.block);
        $('#block-materio-flag-materio-flag-mylists-nav').replaceWith(json.block_nav);
        
        buildBlocks(name);        

        $.event.trigger({
          type : 'my'+type+'-block-updated',
          listname : name
        });
      });
    }

    ajaxifyLinks();
  };

  function ajaxifyLinks(container){
    //trace('MaterioFlag :: ajaxifyLinks', container);

    container = ((container != null) ? container : 'body');
 
    // trace('MaterioFlag :: typeof Drupal.flagLink', typeof Drupal.flagLink);
    if (typeof Drupal.flagLink != 'undefined')
      Drupal.flagLink(container);

    $('a.flag-lists-create:not(.ajax-processed)', container)
      .bind('click', onClickCreatLink)
      .addClass('ajax-processed');

    $('a.edit-list:not(.ajax-processed)', container)
      .bind('click', onCLickEditList)
      .addClass('ajax-processed');
  };

  /**
  * show hide preview
  */
  function onClickShowPreview(event){
    //trace('MaterioFlag :: onClickShowPreview', event);
    showPreview($(this).attr('name'));
  };

  function showPreview(name){
    //trace('MaterioFlag :: showPreview', name);
    $('section.'+name, '#block-materio-flag-materio-flag-mylists').addClass('active')
      .siblings('section').removeClass('active');

    createCookie('materiomyflaglistsopened', name, 1);

    $.event.trigger('init-layout');
  };

  function onClickClosePreview(event){
    //trace('MaterioFlag :: onClickClosePreview', event);
    eraseCookie('materiomyflaglistsopened');
    $(this).parents('section.flag-list').removeClass('active');

    $.event.trigger('init-layout');
  };

  /**
  * onClickOpenLink
  */
  function onClickOpenLink(event){
    event.preventDefault();
    var $link = $(event.currentTarget);
    var fid = $link.attr('href').match(/lists\/([0-9]+)$/);
    // trace('MaterioFlag :: type', type);
    loadList(fid[1]);
    return false;
  };

  function loadList(fid){
    var url = Drupal.settings.basePath+Drupal.settings.pathPrefix+'materioflag/ajax/list/'+fid;
    
    $.event.trigger('loading-content');

    $.getJSON(url, {'current_path':document.location.href},function(json){
      //trace('MaterioFlag :: json', json);
      if(json.redirect){
        window.location = json.redirect;
      }else{
        changeContent(json);
      }
    });
  };

  function changeContent(json){
    if(json.return){

      $('.inner-content','#content').html(json.return);
      
      $.event.trigger('loaded-content');
      
      // no need of ajaxifylinks because it's triggered with resultschanged
      // ajaxifyLinks('#content');

      var path = Drupal.settings.basePath + Drupal.settings.pathPrefix + json.path;
      
      $.event.trigger({
        type : 'new-history-page',
        path : path,
        title : json.title,
        content : json.return
      });

      // TODO:  change language links for folders  
      // for (language in Drupal.settings.materio_search_api_ajax.languages) {
      //   var l = Drupal.settings.materio_search_api_ajax.languages[language];
      //   $('#block-locale-language li.'+language+' a').attr('href', Drupal.settings.basePath + l.prefix+'/' + json.search_path + '/' + json.keys)        
      // };

      triggerContentChanged();

    }else{
      //trace('MaterioFlag :: no results');
    }
  };

  function triggerContentChanged(){
    $.event.trigger({
      type: 'resultschanged',
      container : '#content .flaglist-items'
    });
  };

  /**
  * onClickCreatLink(event)
  */
  function onClickCreatLink(event){
    event.preventDefault();
    var $link = $(event.currentTarget);
    var type = $link.attr('href').match(/[^\/]*$/);
    // trace('MaterioFlag :: type', type);
    var url = Drupal.settings.basePath+Drupal.settings.pathPrefix+'materioflag/createlist/form/'+type[0];

    $.getJSON(url, function(json){
      //trace('MaterioFlag :: creat list : json', json);
      showCreateListForm(json, $link);
    });
    return false;
  };

  function showCreateListForm(json, $link){
    
    // google analytics
    $.event.trigger({
      type:"record-stat",
      categorie:"flagLists",
      action: 'show create form'
    });

    var $modal = $('<div id="modal" class="modal"/>').appendTo('body');
    $modal
      .css({
        position:'absolute',
        top:'40%', left:'50%',
        marginLeft:'-150px', width:'300px',
        zIndex:"99999"
      })
      .append(json.return)
      .find('input[type="submit"]', '#materio-flag-create-list-form').bind('click', function(event) {
        event.preventDefault();
        switch($(this).attr('name')){
          case 'cancel':
            //trace('MaterioFlag :: cancel',event);
            $(this).parents('#modal').remove();
            
            // google analytics
            $.event.trigger({
              type:"record-stat",
              categorie:"flagLists",
              action: 'cancel create form'
            });

            break;
          case 'create':
            //trace('MaterioFlag :: create',event);
            var title = $(this).parents('form').find('input[name*="flag-lists-name"]').val();
            var type = $(this).parents('form').find('input[name*="type"]').val();

            // google analytics
            $.event.trigger({
              type : "record-stat",
              categorie : "flagLists",
              action : "submit create form",
              label : 'title : '+title
            });

            createList($modal, type, title, $link);
            break;
        }
        
        return false;
      })
      .parents('form').find('input[type="text"]').focus();
      // TODO:  esc keypressed close the form  
  };

  function createList($modal, type, title, $link){
    var url = Drupal.settings.basePath+Drupal.settings.pathPrefix+'flag-lists/add/'+type+'/js';
    $.getJSON(url, {name:title}, function(data) {
      if (data.error) {
        //trace(data.error);
      }
      else {
        // select.append('<option value="'+data.flag.fid+'">'+data.flag.title+'</option>');
        // $('input.name', $(this)).val('');
        // dialog.dialog('close');
        //trace('MaterioFlag :: created list : data', data);

        flagEntityWithList(data.flag.name, $link.attr('nid'), $link.attr('token'));
        $modal.remove();
      }
    });
  };
  
  function flagEntityWithList(name, nid, token){
    // var ret;
    // Send POST request
    $.ajax({
      type: 'POST',
      url: Drupal.settings.basePath+Drupal.settings.pathPrefix+'flag-lists/flag/'+name+'/'+nid,
      data: { js: true, token: token },
      dataType: 'json',
      success: function (data2) {
        //trace('MaterioFlag :: node taged with newly created list : data2', data2)
        if (data2.status) {
          
          // google analytics
           $.event.trigger({
              type : "record-stat",
              categorie : 'FlagLists',
              action : 'node flaged',
              label : 'nid : '+nid+' | flag : '+name
            });

          refreshBlocks(name);
          refreshNodeLinks();
        }else {
          // Failure.
          alert(data2.errorMessage);
        }
      },
      error: function (xmlhttp) {
        alert('An HTTP error '+ xmlhttp.status +' occurred.\n'+ element.href);
      }
    });
  };

  function refreshNodeLinks(){
    
    var nids = new Array();
    $('.flag-lists-entity-links').parents('.node').each(function(index) {
      nids.push($(this).attr('class').match(/node-([0-9]+)/)[1]);
    });
    // trace('MaterioFlag :: nids', nids);
    
    var url = Drupal.settings.basePath+Drupal.settings.pathPrefix+'materioflag/nodelinks';
    $.getJSON(url, {nids:nids.join(";")}, function(data) {
      // trace('MaterioFlag :: data', data);
      for(nid in data.links){
        // trace('MaterioFlag :: nid', nid);
        // trace('MaterioFlag :: data.links[nid]', data.links[nid]);
        $('.node-'+nid+' .flag-lists-entity-links').replaceWith(data.links[nid]);

        // trace('MaterioFlag :: typeof Drupal.flagLink', typeof Drupal.flagLink);
        // if (typeof Drupal.flagLink != 'undefined')
        //   Drupal.flagLink($('.node-'+nid+' .flag-lists-entity-links'));  

        ajaxifyLinks('.node-'+nid+' .flag-lists-entity-links');

      }
    });
    
    $.event.trigger({
      type : 'materioflag-nodelinks-updated',
      nids : nids
    });
  };

  /**
  * onCLickEditList(event)
  */
  function onCLickEditList(event){
    // TODO:  empécher le double formulaire  
    event.preventDefault();
    var $link = $(event.currentTarget);
    var lid = $link.attr('href').match(/[^\/]*$/);
    var type = 'materiau'; // this is cheap
    
    var url = Drupal.settings.basePath+Drupal.settings.pathPrefix+'materioflag/editlistform/'+type+'/'+lid[0];

    $.getJSON(url, function(json){
      //trace('MaterioFlag :: editlist : json', json);
      showEditListForm(json, $link);
    });
    return false;
  };

  function showEditListForm(json, $link){
    
    // google analytics
    $.event.trigger({
      type:"record-stat",
      categorie:"flagLists",
      action: 'show edit form'
    });

    var $modal = $('<div id="modal" class="modal"/>').appendTo('body');
    $modal
      .css({
        position:'absolute',
        top:'40%', left:'50%',
        marginLeft:'-150px', width:'300px',
        zIndex:"99999"
      })
      .append(json.return)
      .find('input[type="submit"]', '#materio-flag-edit-list-form').bind('click', function(event) {
        event.preventDefault();

        var $form = $(this).parents('form');
        var title = $form.find('input[name*="flag-lists-title"]').val();
        var fid = $form.find('input[name*="fid"]').val();
        var name = $form.find('input[name*="name"]').val();

        switch($(this).attr('name')){
          case 'cancel':
            //trace('MaterioFlag :: cancel',event);
            $(this).parents('#modal').remove();
            
            // google analytics
            var action = 'cancel edit form';            

            break;
          case 'save':
            //trace('MaterioFlag :: create',event);
            
            // google analytics
            var action = "submit edit form";

            editList($modal, fid, name, title);
            break;
          case 'delete':
            //trace('MaterioFlag :: delete',event);

            if(confirm('Do you realy want to delete the folder '+title+'?')){
              var action = "submit delete form";
              deleteList($modal, fid);  
            }else{
              var action = "cancel delete form";
            }
            
            break;
        }
        
        // google analytics
        $.event.trigger({
          type:"record-stat",
          categorie:"flagLists",
          action: action
        });

        return false;
      })
      .parents('form').find('input[type="text"]').focus();
      // TODO:  esc keypressed close the form  
  };

  function editList($modal, fid, name, title){
    var url = Drupal.settings.basePath+Drupal.settings.pathPrefix+'materioflag/editlist/'+fid+'/'+name+'/'+title;
    $.getJSON(url, function(data) {
      if (data.error) {
        // trace(data.error);
        if(data.message)
          alert(data.message);
      }
      else {
        //trace('MaterioFlag :: saved list : data', data);
        
        $.event.trigger({
          type : 'list-edited',
          name : data.listname,
          title : data.title,
        });

        refreshBlocks();
        refreshNodeLinks();

        $modal.remove();
      }
    });
  };

  function deleteList($modal, fid){
    // prompt('are you sure ?');
    var url = Drupal.settings.basePath+Drupal.settings.pathPrefix+'materioflag/deletelist/'+fid;
    $.getJSON(url, function(data) {
      if (data.error) {
        // trace(data.error);
        if(data.message)
          alert(data.message);
      }
      else {
        //trace('MaterioFlag :: deleted list : data', data);

        refreshBlocks();
        refreshNodeLinks();
        // TODO:  if the deleted list was the current displayed list ??
        $modal.remove();
      }
    });
  }

  /**
  *
  */
  function onInitScrollerPager(event){
    // trace('MaterioFlag :: MaterioFlag :: onInitScrollerPager');
    if (isList()){
      // trace('MaterioFlag :: event.pager', event);
      event.pager.hide();
    }
  };

  function onLoadScrollerPager(event){
    if (isList())
      loadNextListPage(event.href);
  };

  function loadNextListPage(href){
    // trace('MaterioFlag :: loadNextListPage', href);
    if(!_isLoadingList){
      var fid = href.match(/lists\/([^\/|\?]+)/);
      var page = href.match(/\?page=([0-9]+)/);
      var url = Drupal.settings.basePath+Drupal.settings.pathPrefix+'materioflag/ajax/list/'+fid[1]+'/'+page[1];
      // trace('MaterioFlag :: url', url);
      loadNextPage(url, $('.materio-flags-list', '#content'), '.flaglist-items');
    }
  };

  function loadNextPage(url, $container, target){
    //trace('MaterioFlag :: loadNextPage');
    _isLoadingList = true;
    $container.addClass('loading');
    $.getJSON(url, function(json){
      //trace('json', json);
      _isLoadingList = false;
      $container.removeClass('loading');
      addNextpage(json, target);
    });
  };

  function addNextpage(json, container_class){
    var $newcontent = $(json.return),
        $newitems = $(container_class, $newcontent).children('article').addClass('just-added'),
        $newpager = $('ul.pager', $newcontent);
    
    $(container_class, '#content').append($newitems);
    $('ul.pager', '#content').replaceWith($newpager.hide());


    // TODO: animation, this should be on theme side
    $(container_class, '#content').children('.just-added').each(function(i){
      // $(this).delay(5000*i).removeClass('just-added');
      var $this = $(this);
      setTimeout(function(){
        $this.removeClass('just-added');
      }, 150*i);
    });

    $.event.trigger({
      type : 'resultscompleted',
      container : $(container_class, '#content')
    });
  };

  function onViewModeChanged(event){
    if (isList())
      loadList(getFid());
  };

  /**
  * history
  */
  function onHistoryStateChange(event){
    if(isList())
      triggerContentChanged();
  };

  /**
  * Helpers
  */

  function getFid(){
    return $('.materio-flags-list', '#content').attr('fid');;
  };

  function isList(){
    return $('.materio-flags-list', '#content').length;
  };


  /** 
  * cookies 
  */
  function createCookie(name,value,days) {
    if (days) {
      var date = new Date();
      date.setTime(date.getTime()+(days*24*60*60*1000));
      var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
  }

  function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
      var c = ca[i];
      while (c.charAt(0)==' ') c = c.substring(1,c.length);
      if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
  }

  function eraseCookie(name) {
    createCookie(name,"",-1);
  }


  init();


};

var materioflag = new MaterioFlag();
  
})(jQuery);