var CharLimiter = {
  init: function(limit, textarea, label, button){
    this.limit = limit;
    this.textarea = $(textarea);
    this.label = $(label);
    this.button = $(button);
    
    $(textarea).bind('keyup', this, this.updated);

    if(this.textarea.attr('value') === undefined) return;    
    
    this.checkLimit(this.textarea.attr('value').length);
  },
  
  updated: function(event){
    event.data.checkLimit($(this).attr('value').length)
  },
  
  checkLimit: function(charCount){
    if(charCount > this.limit)
      this.deactivated();
    else
      this.active();
      
    this.updateCharsLeft();
  },
  
  deactivated: function(){
    var value = this.textarea.attr('value');
    
    this.button.attr('disabled', 'disabled');
    this.button.addClass('disabled');
    this.label.parent().css({color: '#f00'});
    if($('#send .warning').length < 1)
      $('#send').prepend('<div class="warning"><p id="too-long">Ditt meddelande är för långt. Max antal tecken är 80.</p></div>');
    else if($('#send #too-long').length < 1)
      $('#send .warning').append('<p id="too-long">Ditt meddelande är för långt. Max antal tecken är 80.</p>');
  },
  
  active: function(){
    this.label.parent().css({color: ''});
    this.button.attr('disabled', '');
    this.button.removeClass('disabled');
    if($('#too-long').length > 0){
      $('#too-long').remove();
      if($('#send .warning').text().length < 1)
        $('#send .warning').remove();
    }
  },
  
  updateCharsLeft: function(){
    var chars = this.textarea.attr('value').length;
    var left = this.limit - chars;
    this.label.html(left);
  }
};

var MoodSlider = {
    moods: ['karleksfull', 'glad', 'neutral', 'arg'],
    init: function(handle){
        if($('#message-mood').size() < 1) return;
        $('#message-mood').hide();
        $(handle).slider({
            animate: true,
            value: 0,
            min: 0,
            max: 3,
            step: 1,
            change: function(event, ui){
                var moods = MoodSlider.moods;
                $('#message-mood option').attr('selected', '');
                $('#message-mood option[value~=' + moods[ui.value] + ']').attr('selected', 'selected');
            }
        })
        .slider('value', jQuery.inArray($('#message-mood option[selected~=selected]').attr('value'), this.moods));
    }
}


var FriendAdder = {
  friends: 1,
  removeButtonDisplayed: false,
  
  init: function(selector, target, limit){
    this.target = $(target);
    this.limit = limit;
    $(selector).bind('click', this, this.click);
    $('#remove-friend').live("click", function(event){
      event.preventDefault();
      FriendAdder.remove();
    })
  },
  
  click: function(event){
    event.preventDefault();
    if(!event.data.tooManyFriends())
      event.data.add()
    else
      event.data.disable()
  },
  
  add: function(){
    this.friends++;
    var markup = "<div class='friend'><label for='friend-name-" + this.friends + "'>Namn:</label> <input type='text' id='friend-name-" + this.friends + "' name='till[namn][]' /><br /><label for='friend-email-" + this.friends + "'>Epost:</label> <input type='text' id='friend-email-" + this.friends + "' name='till[email][]' /></div>";
    this.target.append(markup);
    
    if(this.friends > 1 && !this.removeButtonDisplayed)
      this.addRemoveButton();
  },
  
  remove: function(){
    if(this.friends < 2) return;
    
    this.friends--;
    if(this.friends < 2) this.removeRemoveButton();
    
    $('#friends .friend:last').remove();
    
    
  },
  
  addRemoveButton: function(){
    this.removeButtonDisplayed = true;
    var markup = '<a href="#" id="remove-friend">- <span>Ta bort en vän</span></a>';
    $('#control-friends-btns').prepend(markup);
  },
  
  removeRemoveButton: function(){
    this.removeButtonDisplayed = false;
    $('#remove-friend').remove();
  },
  
  disable: function(){
    //console.log("disabled");
  },
  
  tooManyFriends: function(){
    return this.friends > this.limit;
  }
};


var DivUpdater = {
  init: function(src, dst){
    this.src = $(src);
    this.dst = $(dst);
    
    this.src.bind('keyup', this, this.updated);
    this.setText(this.src.attr('value'));
  },
  
  updated: function(event){
    event.data.setText($(this).attr('value'));
  },
  
  setText: function(text){
    this.dst.html(text);
  }
};


var FormShower = {
  
  init: function(id, url, prefix){
    this.el = $(id);
    this.url = prefix + url;
    this.prefix = prefix
    
    this.el.click(function(event){
      event.preventDefault();
      
      if($.browser.msie && $.browser.version < 9){ alert(window.location.protocol + "//" + window.location.host + prefix); window.location = window.location.protocol + "//" + window.location.host + prefix; }
      else $.get(FormShower.url, FormShower.loaded);
    })
    
    this.el.hide()
  },
  
  loaded: function(response){
    $('#slide').append(response);
    
    CharLimiter.init(80, '#friends-form textarea', '#chars-left', '#submit');
    FriendAdder.init('#add-friend', '#friends', 5);
    DivUpdater.init('#friends-form textarea', '#message');
    MoodSlider.init('#mood-slider');
    
    $('#show').animate({marginTop: -580}, 300);
  },
  
  execute: function(url){
    if($.browser.msie && $.browser.version < 9){ window.location = window.location.protocol + "//" + window.location.host +  FormShower.prefix; }
    else { $.get(FormShower.url, FormShower.loaded); }
  }
  
};




var Relation = {
  init: function(){
    CharLimiter.init(80, '#friends-form textarea', '#chars-left', '#submit');
    FriendAdder.init('#add-friend', '#friends', 5);
    DivUpdater.init('#friends-form textarea', '#message');
    MoodSlider.init('#mood-slider');
    FormShower.init('#send-message', '/meddelanden/form', '/index.php');
  }
};




$(document).ready(Relation.init);
