/**
 * Homescreen indicator widget
 */
jQuery.fn.configureHomescreen = function(s) {
  var settings = jQuery.extend({
    'add_tab_url' : null, 
    'reorder_tabs_url' : null, 
    'tabs' : null
  }, s);
  
  return this.each(function() {
    var wrapper = $(this).addClass('configure_homescreen');
    
    var tabs_wrapper = $('<div class="homescreen_tabs"><ul></ul></div>').appendTo(wrapper);
    var tabs_list = tabs_wrapper.find('ul');
    var tab_settings_wrapper = $('<div class="homescreen_tab_settings"></div>').appendTo(wrapper);
    
    /**
     * Add tab to the list
     * 
     * @param Object tab
     * @param Boolean select
     */
    var add_tab = function(tab, select) {
      var list_item = $('<li class="homescreen_tab real_homescreen_tab" homescreen_tab_id="' + tab['id'] + '">' + 
        '<img src="' + App.Wireframe.Utils.imageUrl('widgets-drag-handle.png', 'homescreens') + '" class="reoder_homescreen_tabs"> ' + 
        '<a href="#" class="select_tab">' + tab['name'].clean() + '</a>' + 
      '</li>');
      
      if(tabs_list.find('li.real_homescreen_tab').length > 0) {
        tabs_list.find('li.real_homescreen_tab:last').after(list_item);
      } else {
        tabs_list.prepend(list_item);
      } // if
      
      list_item.find('a.select_tab').click(function() {
        select_tab($(this).parent().attr('homescreen_tab_id'));
        return false;
      });
      
      list_item.append('<span class="homescreen_tab_options">' +
          '<a href="' + tab['urls']['edit'] + '" class="rename_homescreen_tab" title="' + App.lang('Rename') + '"><img src="' + App.Wireframe.Utils.imageUrl('/icons/12x12/edit-tab.png', 'homescreens') + '"></a>' + 
          '<a href="' + tab['urls']['delete'] + '" class="delete_homescreen_tab" title="' + App.lang('Remove') + '"><img src="' + App.Wireframe.Utils.imageUrl('/icons/12x12/delete-tab.png', 'homescreens') + '"></a>' + 
        '</span>'
      );
      
      var settings_wrapper = $('<div class="homescreen_tab" homescreen_tab_id="' + tab['id'] + '"></div>').appendTo(tab_settings_wrapper);
      
      settings_wrapper.append('<div class="homescreen_tab_header">' + 
        '<span class="homescreen_tab_description">' + App.lang('Tab Info') + ': ' + (typeof(tab['description']) == 'string' ? tab['description'].clean() : App.lang('No description provided')) + '</span>' + 
      '</div>' + tab['manager']);
      
      // Rename home screen tab
      list_item.find('a.rename_homescreen_tab').click(function() {
        var link = $(this);        
        var tab_name_wrapper = link.parents('li.homescreen_tab:first');
        var tab_name = tab_name_wrapper.find('a.select_tab');
        var homescreen_tab_id = tab_name_wrapper.attr('homescreen_tab_id');
        
        if(homescreen_tab_id) {
          var new_homescreen_tab_name = jQuery.trim(prompt(App.lang('Please insert new tab name'), tab_name.text()));
          
          if(new_homescreen_tab_name && new_homescreen_tab_name != tab_name.text()) {
            var old_homescreen_tab_name = tab_name.text();
            
            tab_name.text(new_homescreen_tab_name);
            
            $.ajax({
              'url' : App.extendUrl(link.attr('href'), { 'async' : 1 }), 
              'type' : 'post', 
              'data' : {
                'homescreen_tab[name]' : new_homescreen_tab_name,
                'submitted' : 'submitted'
              }, 
              'error' : function() {
                tab_name.text(old_homescreen_tab_name);
                App.Wireframe.Flash.error('Failed to rename tab from ":old_name" to ":new_name". Please try again later', {
                  'old_name' : old_homescreen_tab_name, 
                  'new_name' : new_homescreen_tab_name
                });
              }
            });
          } // if
        } // if
        
        return false;
      });
      
      // Remove home screen tab
      list_item.find('a.delete_homescreen_tab').asyncLink({
        'confirmation' : App.lang('Are you sure that you want to remove selected home screen tab?'), 
        'before' : function() {
          if(tabs_wrapper.find('li.homescreen_tab.real_homescreen_tab').length <= 1) {
            App.Wireframe.Flash.error('Last home screen tab can not be deleted');
            return false;
          } // if
        }, 
        'success' : function() {
          var link = $(this);        
          var tab_name_wrapper = link.parents('li.homescreen_tab:first');
          var homescreen_tab_id = tab_name_wrapper.attr('homescreen_tab_id');
          
          
          if(homescreen_tab_id) {
            tab_name_wrapper.remove();
            tab_settings_wrapper.find('div.homescreen_tab[homescreen_tab_id=' + homescreen_tab_id + ']').remove();            
            select_first_tab();
          } // if
          
          App.Wireframe.Flash.success('Home screen tab has been removed');
        }
      });
      
      if(select === true) {
        select_tab(tab['id']);
      } // if
    }; // add_tab
    
    /**
     * Select given tab
     * 
     * @param Integer homescreen_tab_id
     */
    var select_tab = function(homescreen_tab_id) {
      var tab = tabs_wrapper.find('li.homescreen_tab[homescreen_tab_id=' + homescreen_tab_id + ']');
      
      if(!tab.is('.selected')) {
        tabs_wrapper.find('li.homescreen_tab.selected').removeClass('selected');
        tab_settings_wrapper.find('div.homescreen_tab.selected').removeClass('selected');
        
        tab.addClass('selected');
        tab_settings_wrapper.find('div.homescreen_tab[homescreen_tab_id=' + homescreen_tab_id + ']').addClass('selected');
      } // if
    }; // select_tab
    
    /**
     * Select first tab
     */
    var select_first_tab = function() {
      if(tabs_wrapper.find('li.real_homescreen_tab:first').length > 0) {
        select_tab(tabs_wrapper.find('li.real_homescreen_tab:first').attr('homescreen_tab_id'));
      } // if
    }; // select_first_tab
    
    if(jQuery.isArray(settings['tabs'])) {
      $.each(settings['tabs'], function (i, tab) {
        add_tab(tab);
      });

      select_first_tab();
    } // if
    
    // Add New Tab Button
    var list_item = $('<li class="homescreen_tab add_homescreen_tab">' + 
      '<a href="' + settings['add_tab_url'] + '" title="' + App.lang('Add New Tab') + '" class="select_tab"><img class="add_homescreen_tab" src="' + App.Wireframe.Utils.imageUrl('/icons/12x12/add-tab.png', 'homescreens') + '"></a>' + 
    '</li>').appendTo(tabs_list);
    
    list_item.find('a').flyoutForm({
      'success' : function(tab) {
        add_tab(tab, true);
        
        App.Wireframe.Flash.success('Tab ":name" has been successfully added', {
          'name' : tab['name']
        });
      }, 
      'error': function() {
        App.Wireframe.Flash.error('Failed to add new home screen tab. Please try again later');
      }
    });
    
    // Tab reordering
    var save_timeout;
    
    tabs_list.sortable({
      'axis' : 'x', 
      'handle' : 'img.reoder_homescreen_tabs', 
      'items' : 'li.real_homescreen_tab', 
      'forcePlaceholderSize' : true,
      'update' : function (event, ui) {
        if (save_timeout) {
          clearTimeout(save_timeout);
        } // if
        
        save_timeout = setTimeout(function () {
          var data = {
            'submitted' : 'submitted'
          };
          
          var counter = 1;
          
          wrapper.find('li.homescreen_tab.real_homescreen_tab').each(function() {
            data['homescreen_tabs[' + $(this).attr('homescreen_tab_id') + ']'] = counter++;
          });
          
          $.ajax({
            'url' : App.extendUrl(settings['reorder_tabs_url'], { 'async' : 1 }), 
            'type' : 'post', 
            'data' : data, 
            'success' : function() {
              if(save_timeout) {
                clearTimeout(save_timeout);
              } // if
            }, 'error' : function() {
              if(save_timeout) {
                clearTimeout(save_timeout);
              } // if
              
              App.Wireframe.Flash.error('Failed to reorder tabs. Please try again later');
            }
          });
        }, 1000);
      }
    });
  });
  
};