/**
 * @version $Id$
 */
Mp3Player2 = function(config){
  // configurable {
  this.play_list = [];
  this.play_list_id = '1';
  this.player_id = '';
  this.selector = '';
  this.volume = 30;
  this.auto_resume = true;
  this.active = true;
  this.show_prestart_message = true;
  this.prestart_message_show_time = 10000;
  // }
  
  $.extend(this, config);
  
  this.item_id = '';
  this.saved_position = 0;
  this.play_state = true;
  this.forced_pause = false;
  this.is_resumed = false;
  this.is_init = false;
  this.message_shown = false;
  this.message_selector = null;
  this.prestart_message_timer = null;
  
  if(this.show_prestart_message)
    this.showPrestartMessageIf();
}

Mp3Player2.prototype = {
  _unactive: function() {
    this.play_state = this.active = false;
  },
  
  play: function(by_state) {
    if(by_state && !this.play_state)
      return;

    //this._commandToPlayer('method:setPosition', this.saved_position);
    if(this.isPlaying != 'true')
      this._commandToPlayer('method:play', '');
    this._commandToPlayer('enabled', 'true');
    this.getEl().addClass('play').removeClass('pause');
    this.play_state = true;
    this.forced_pause = false;
  },
  
  pause: function(force) {
    this._commandToPlayer('method:pause', '');
    this.isPlaying = 'false';
    this.getEl().addClass('pause').removeClass('play');
    if(force === true)
      this.forced_pause = true;
    else
      this.play_state = false;
  },
  
  next: function() {
    var num = this.findItem(this.item_id);
    
    if(num !== false) {
      
      if(num < this.play_list.length - 1)
        num ++;
      else
        num = this.findFirstItem();
        
    } else {
      
      num = this.findFirstItem();
      if(num === false)
        return false;
        
    }
    
    this.applyItemByNum(num);
      
    return true;
  },
  
  prev: function() {
    var num = this.findItem(this.item_id);
    
    if(num !== false) {
      
      if(num > 0)
        num --;
      else 
        num = this.findLastItem();
        
    } else {
      
      num = this.findLastItem();
      if(num === false)
        return false;
        
    }
    
    this.applyItemByNum(num);
      
    return true;
  },
  
  resume: function() {
    this.auto_resume = true;
    if(this.is_resumed || !this.is_init)
      return;
      
    this.is_resumed = true;
    
    if(!this.item_id)
      this.saved_position = 0;
    
    var num = this.item_id ? this.findItem(this.item_id) : this.findFirstItem();
    if(num === false) {
      num = this.findFirstItem();
      this.saved_position = 0;
    }
      
    if(num === false)
      return false;
      
    this.applyItemByNum(num, this.saved_position);

    return true; 
  },
  
  applyItemByNum: function(num, position) {
    var item = this.play_list[num];
    this.item_id = item.id;
    this.saved_position = position;
    this._commandToPlayer('method:setUrl', item.path);
    
    if(this.play_state && !this.forced_pause) {
      this.pause();
      this.play();
    }
  },
  
  findItem: function(id) {
    for(var i = 0, l = this.play_list.length; i < l; i ++) {
      if(this.play_list[i].id == id)
        return i;
    }
    
    return false;
  },
  
  findFirstItem: function() {
    return this.play_list.length ? 0 : false;
  },
  
  findLastItem: function() {
    return this.play_list.length ? this.play_list.length - 1 : false;
  },
  
  getPlayer: function() {
    return document.getElementById(this.player_id);
  },
  
  _initEvents: function() {
    this.getPlayButton().click(this.onPlay.createDelegate(this));
    this.getPauseButton().click(this.onPause.createDelegate(this));
    this.getPlayPauseButton().click(this.onPlayPause.createDelegate(this));
    this.getNextButton().click(this.onNext.createDelegate(this));
    this.getPrevButton().click(this.onPrev.createDelegate(this));
    $(window).unload(this.onUnload.createDelegate(this));
  },
  
  loadState: function() {
    var play_state = getCookie(this._getPlayerVarName('state'));
    this.play_state =  this.active && (!play_state || play_state == '1');
    
    /*var position = getCookie(this._getVarName('position'));
    if(position)
      position = parseInt(position);
    this.saved_position = position ? position : 0;*/
    
    var item_id = getCookie(this._getVarName('item'));
    this.item_id = item_id ? item_id : '';
  },
  
  saveState: function() {
    setCookie(this._getPlayerVarName('state'), this.play_state ? 1 : 0, 635, '/');
    //setCookie(this._getVarName('position'), this.saved_position, 0, '/');
    setCookie(this._getVarName('item'), this.item_id, 635, '/');
  },
  
  showPrestartMessage: function() {
    this.message_shown = true;
    $(document).ready((function() {
      this.message_selector = $('<div class="player_message">Сайт имеет музыкальное сопровождение.<br/><a href="#" class="off_link">Нажмите здесь, чтобы отключить</a></div>')
       .appendTo('body').getIdSelector();
       
      this.getOffLink().click(this.onUnactive.createDelegate(this));
      this.prestart_message_timer = setTimeout(this.onPrestartMessageTimeout.createDelegate(this), this.prestart_message_show_time);
    }).createDelegate(this));
  },
  
  showPrestartMessageIf: function() {
    var message_shown = getCookie(this._getPlayerVarName('message'));

    if(!message_shown || message_shown != '1') {
      this.showPrestartMessage();
      setCookie(this._getPlayerVarName('message'), '1', 0, '/');
    }
  },
  
  hideMessage: function() {
    this.getMessageEl().remove();
    this.message_shown = false;
  },
  
  getOffLink: function() {
    return $('.off_link', this.getMessageEl());
  },
  
  getMessageEl: function() {
    return $(this.message_selector);
  },
  
  _getVarName: function(name) {
    return 'player_' + this.player_id + '_' + this.play_list_id + '_' + name;
  },
  
  _getPlayerVarName: function(name) {
    return 'player_' + this.player_id + '_' + name;
  },
  
  getNextButton: function() {
    return $('.next', this.getEl());
  },
  
  getPrevButton: function() {
    return $('.prev', this.getEl());
  },
  
  getPlayButton: function() {
    return $('.play', this.getEl());
  },
  
  getPauseButton: function() {
    return $('.pause', this.getEl());
  },
  
  getPlayPauseButton: function() {
    return $('.play-pause', this.getEl());
  },
  
  getEl: function() {
    return $(this.selector);
  },

  _commandToPlayer: function(command, param) {
    if(this.is_init && this.getPlayer()) 
      this.getPlayer().SetVariable(command, param);
  },
  
  onPlayPause: function() {
    if(this.isPlaying == 'true')
      this.pause();
    else
      this.play();
  },
  
  onPlay: function() {
    this.play();
  },
  
  onPause: function() {
    this.pause();
  },
  
  onPrev: function() {
    this.prev();
  },
  
  onNext: function() {
    this.next();
  },
  
  onUpdate: function() {
    //document.title = this.isPlaying == 'true' ? 'playing' + this.position : 'not playing';
    if(this.forced_pause)
      return;
    
    if(this.isPlaying != 'false')
      this.saved_position = this.position;
      
    if(this.isPlaying == 'false' && this.play_state) {
      this.next();
    }
  },
  
  onInit: function() {
    this._initEvents();

    this.loadState();

    this.is_init = true;

    this._commandToPlayer('method:setVolume', this.volume);

    if(this.auto_resume && !this.message_shown)
      this.resume();
  },
  
  onUnactive: function() {
    this.hideMessage();
    
    this._unactive();
    clearTimeout(this.prestart_message_timer);
    
    if(this.auto_resume && this.is_init)
      this.resume();
  },
  
  onPrestartMessageTimeout: function() {
    this.hideMessage();
    
    if(this.auto_resume && this.is_init)
      this.resume();
  },
  
  onUnload: function() {
    this.saveState();
    this._commandToPlayer('enabled', 'false');
    this._commandToPlayer('method:stop', '');
  }
  
}
