var PICHEAD_STATUS_STOP = 0;
var PICHEAD_STATUS_PLAY = 1;
var PICHEAD_STATUS_PAUSE = 2;

var ENTRY_OPTIONS_DEFAULT_OPACITY = '0.2';
var ENTRY_OPTIONS_HIGHLIT_OPACITY = '1';
var ENTRY_OPTIONS_FADE_DURATION = 100;

var PICHEAD_START_INTERVAL = '10s';
var PICHEAD_START_DURATION = 1700;
var PICHEAD_SWITCH_INTERVAL = '17s';
var PICHEAD_SWITCH_DURATION = 3700;

var PICHEAD_CONTROLS_DEFAULT_OPACITY = '0.1';
var PICHEAD_CONTROLS_HIGHLIT_OPACITY = '0.7';
var PICHEAD_CONTROLS_FADE_DURATION = 300;

var PICHEAD_COOKIE_DAYS = 365;
var PICHEAD_COOKIE_PATH = '/';

var PICHEAD_PATH = '/images/pichead/';
var IMAGES_PATH = '/images/';

var initialPicheadIndex = 1;
var maxHeaderIndex = 5;
var currentIndex = initialPicheadIndex;

var picheadStatus = PICHEAD_STATUS_PLAY;

var playerButton;
var picheadWrapper;
var picheadCurrent;
var picheadNext;
var picheadInfo;

var picheadItem;

var led;

var emailRe = '/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i';

Led = function(id) {
  this.element = $('#' + id);
};

Led.prototype.on = function() {
  var el = this.element;
  el.stop(true, true);
  el.fadeTo(200, 1);
};

Led.prototype.off = function() {
  var el = this.element;
  el.stop(true, true);
  el.addClass('done');
  el.fadeTo(2000, 0, function() {
    el.removeClass('done');
  });
};

$(document).ready(function() {

  led = new Led('led');
  led.on();

  picheadItem = new Object();
  picheadItem.id = 1;
  picheadItem.info = '';
  picheadItem.file = '';
  picheadItem.resume = 0;

  picheadWrapper = $('#pichead_wrapper');
  picheadCurrent = $('#pichead_current');
  picheadNext = $('#pichead_next');
  picheadInfo = $('#pichead_info_text');

  //PICHEAD_COOKIE_OPTIONS = new Object();
  //PICHEAD_COOKIE_OPTIONS.expires = PICHEAD_COOKIE_DAYS;
  //PICHEAD_COOKIE_OPTIONS.path = PICHEAD_COOKIE_PATH;

  // initially, hide all the entries' options

  $('div.entry_tools').animate({
    opacity: ENTRY_OPTIONS_DEFAULT_OPACITY
  }, 1);

  initializeEntryOptionsDisplay();

  if (maxHeaderIndex < 1) {
    return;
  }

  var savedStatus = parseInt($.cookie('pichead_status'));

  //alert($.cookie('pichead_status'));

  if (savedStatus == PICHEAD_STATUS_STOP ||
      savedStatus == PICHEAD_STATUS_PLAY) {
    picheadStatus = savedStatus;
  } else if (savedStatus == PICHEAD_STATUS_PAUSE) {
    // get the image id
    picheadStatus = savedStatus;
    var savedPicheadId = $.cookie('pichead_id');
    if (savedPicheadId) {
      picheadItem.resume = parseInt(savedPicheadId);
    }
  }

  initializePicheadControls();
  initializePichead();

  initializeTagsToggleButton();

  led.off();
});


/**
 * Adds listeners to each "div.entry_container" which displays and hides
 * entry options when mouse enters and leaves entry block.
 */
var initializeEntryOptionsDisplay = function() {

  $('div.entry_container').bind('mouseenter',function(){
    $('div.entry_tools:first', this).animate({
      opacity: ENTRY_OPTIONS_HIGHLIT_OPACITY
    }, 300);
  }).bind('mouseleave',function(){
    $('div.entry_tools:first', this).animate({
      opacity: ENTRY_OPTIONS_DEFAULT_OPACITY
    }, ENTRY_OPTIONS_FADE_DURATION);
  });

};


/**
 *
 *
 */
var initializePichead = function() {

  picheadWrapper.animate({opacity: '0'}, 1, '', function() {});

  var interval = picheadStatus == PICHEAD_STATUS_STOP ? 1 : PICHEAD_START_INTERVAL;
  //nextPicheadItem();
  $(document).oneTime(interval, launchPichead);
};

/**
 * Replaces the original logo and puts first image in pichead;
 * If pichead is stopped, nothing else happens;
 * If pichead is paused, the image user paused on will fade once it's loaded;
 * If pichead is being played, the pichead switch routine will also be fired off;
 */
var launchPichead = function() {

  var img = new Image();
  led.on();
  $.ajax({
    type: 'POST',
    url: '/pichead/next',
    data: 'id=' + picheadItem.id + '&resume=' + picheadItem.resume,
    success: function(msg) {
      led.off();
      var pars = msg.split('|');
      picheadItem.id = pars[2];
      picheadItem.info = pars[1];
      picheadItem.filename = pars[0];

      $(img).load(function() {

        $.cookie('pichead_id', picheadItem.id, {expires:PICHEAD_COOKIE_DAYS, path: PICHEAD_COOKIE_PATH});
        picheadInfo.html(picheadItem.info);
        picheadCurrent.append(this);

        if (picheadStatus == PICHEAD_STATUS_PLAY) {
          picheadWrapper.css('display', 'block');
          picheadWrapper.animate({
            opacity: '1'
          }, PICHEAD_START_DURATION, '', initializePicheadSwitch);
        } else if (picheadStatus == PICHEAD_STATUS_PAUSE) {
          picheadWrapper.css('display', 'block');
          picheadWrapper.animate({
              opacity: '1'
            }, PICHEAD_START_DURATION);
        }

      }).error(function() {
        led.off();
      }).attr('src', PICHEAD_PATH + 'pichead_' + picheadItem.filename + '.jpg')
          .error(function(){/*alert('damin');*/});
    },
    error: function(request, error) {
      led.off();
    }
  });
};

var initializePicheadSwitch = function() {
  picheadWrapper.everyTime(
      PICHEAD_SWITCH_INTERVAL,
      'picheadSwitchTimer',
      picheadSwitch);
};

/**
 *
 */
var picheadSwitch = function() {

  var img = new Image();
  led.on();
  $.ajax({
    type: 'POST',
    url: '/pichead/next',
    data: 'id=' + picheadItem.id,
    success: function(msg) {
      var pars = msg.split('|');
      picheadItem.id = pars[2];
      picheadItem.info = pars[1];
      picheadItem.filename = pars[0];

      $(img).load(function () {
        led.off();
        $.cookie('pichead_id', picheadItem.id, {expires:PICHEAD_COOKIE_DAYS, path: PICHEAD_COOKIE_PATH});
        picheadInfo.html(picheadItem.info);

        $(this).animate({opacity: '0'}, 1, '', function() { // this prevents flicker
          picheadNext.append(this);
          $('#pichead_logo').css('opacity', '1'); // this fixes ie7 seethru issue
          $(this).animate({ opacity: '1' }, PICHEAD_SWITCH_DURATION, '', function() {
            //$('img:first', picheadCurrent).replaceWith(this); // won't work in opra
            picheadCurrent.empty();
            picheadCurrent.append($(this).clone());
            picheadNext.empty();
          });
        });
      }).error(function () {
          led.off();
      }).attr('src', PICHEAD_PATH + 'pichead_' + picheadItem.filename + '.jpg');

    },
    error: function(request, error) {
      led.off();
    }
  });
};

/**
 *
 */
var initializePicheadControls = function() {
  var controls = $('#pichead_controls');
  controls.animate({ opacity: PICHEAD_CONTROLS_DEFAULT_OPACITY}, 1);

  picheadWrapper.bind('mouseenter', function() {
    controls.animate({ opacity: PICHEAD_CONTROLS_HIGHLIT_OPACITY},
        PICHEAD_CONTROLS_FADE_DURATION);
  });

  picheadWrapper.bind('mouseleave', function() {
    controls.animate({ opacity: PICHEAD_CONTROLS_DEFAULT_OPACITY},
        PICHEAD_CONTROLS_FADE_DURATION);
  });

  initializePlayButton();
  initializeStopButton();
  initializePlayFromStopButton();
  initializeInfoButton();
};

var initializePlayButton = function() {
  var play = $('#pichead_play');
  play.bind('click', togglePicheadSwitchin);
  if (picheadStatus == PICHEAD_STATUS_PAUSE) {
    play.attr('src', IMAGES_PATH + 'button_play.png');
  }
};

var togglePicheadSwitchin = function() {
  var playButton = $('#pichead_play');
  if (picheadStatus == PICHEAD_STATUS_PLAY) { // pause
    picheadWrapper.stopTime('picheadSwitchTimer');
    picheadStatus = PICHEAD_STATUS_PAUSE;
    $.cookie('pichead_status', PICHEAD_STATUS_PAUSE, {expires:PICHEAD_COOKIE_DAYS, path: PICHEAD_COOKIE_PATH});
    playButton.attr('src', IMAGES_PATH + 'button_play.png');

  } else { // PICHEAD_STATUS_(STOP||PAUSE) // start
    $.cookie('pichead_status', PICHEAD_STATUS_PLAY, {expires:PICHEAD_COOKIE_DAYS, path: PICHEAD_COOKIE_PATH});
    initializePicheadSwitch();
    playButton.attr('src', IMAGES_PATH + 'button_pause.png');
    picheadStatus = PICHEAD_STATUS_PLAY;
  }
};

var initializeStopButton = function() {
  $('#pichead_stop').bind('click', function() {
    picheadWrapper.stopTime('picheadSwitchTimer');
    picheadStatus = PICHEAD_STATUS_STOP;
    $.cookie('pichead_status', PICHEAD_STATUS_STOP, {expires:PICHEAD_COOKIE_DAYS, path: PICHEAD_COOKIE_PATH});
    picheadWrapper.animate({ opacity: '0'}, PICHEAD_START_DURATION, '',
        function() {
          picheadWrapper.css('display', 'none');
          initializePlayFromStopButton();
        }
    );
  });
};

var initializeInfoButton = function() {
  var picheadInfoCont = $('#pichead_info_cont');
  picheadInfoCont.animate({ opacity: '0' }, 1);
  picheadInfoCont.css('display', 'block');
  $('#pichead_info').bind('mouseover', function() {
    picheadInfoCont.animate({ opacity: '1' }, PICHEAD_CONTROLS_FADE_DURATION);
  });
  $('#pichead_info').bind('mouseout', function() {
    picheadInfoCont.animate({ opacity: '0' }, PICHEAD_CONTROLS_FADE_DURATION);
  });
};

var showPlayFromStopButton = function() {
};

var initializePlayFromStopButton = function() {
  var playFromStopButton = $('#pichead_play_fromstop');
  playFromStopButton.animate({ opacity: '0'}, 1, function() {
    playFromStopButton.css('display', 'block');
  });
  
  if (picheadStatus == PICHEAD_STATUS_STOP) {
    $('#header').bind('mouseenter', function() {
      playFromStopButton.animate({ opacity: PICHEAD_CONTROLS_HIGHLIT_OPACITY },
          PICHEAD_CONTROLS_FADE_DURATION);
    }).bind('mouseleave', function() {
      playFromStopButton.animate({ opacity: '0' }, PICHEAD_CONTROLS_FADE_DURATION);
    });
    playFromStopButton.one('click', function() {
      picheadStatus = PICHEAD_STATUS_PLAY;
      $.cookie('pichead_status', PICHEAD_STATUS_PLAY, {expires:PICHEAD_COOKIE_DAYS, path: PICHEAD_COOKIE_PATH});
      picheadWrapper.animate({ opacity: '0' }, 1);
      picheadWrapper.css('display', 'block');
      $('#pichead_play').attr('src', IMAGES_PATH + 'button_pause.png');
      playFromStopButton.animate({ opacity: '0' }, PICHEAD_CONTROLS_FADE_DURATION, '',
          function() { playFromStopButton.css('display', 'none'); });
      picheadWrapper.animate({ opacity: '1' }, PICHEAD_START_DURATION, '',
          function() {
            initializePicheadSwitch();
          });


    });
  }
};

var initializeTagsToggleButton = function() {
  $('#tags_toggle_btn').click(function() {
    var tagsCont = $('#tags_container_wrapper');
    if (tagsCont.text().length == 0) {
      led.on();
      $.ajax({
        type: 'get',
        url: '/tag/list',
        success: function(msg) {
          led.off();
          tagsCont.html(msg);
          tagsCont.toggle('normal');
          return false;
        }
      });
    } else {
      tagsCont.toggle('normal');
    }

    return false;
  });
};