/* Author: 
  Jan-Erik Strøm
*/

var Uploader = function() {
  this.success = 0;
  this.failed = 0;
  this.skipped = 0;
  this.completed = 0;
  this.total = 0;
};

Uploader.prototype.setup = function(options) {
  var that = this;

  $(options.el).uploadify({
    'multi': true,
    'uploader': options.uploader,
    'auto': true,
    'expressInstall': options.expressInstall,
    'script': options.script,
    'fileDataName': 'file',
    'fileExt': '*.txt',
    'fileDesc': 'Deluxe Ski Jump Stats File(s) (*.txt)',
    'removeCompleted': false,

    'onSelectOnce': function (event, data) {
      that.total = data.fileCount;
      $('#status').removeClass('quiet');
      $('#status').addClass('loud');
      $('.uploadifyQueue').show();
    },

    'onAllComplete': function(event, data) {
      $('#status').removeClass('loud');
      $('#status').addClass('quiet');
      $('#clear').show();
      that.total = 0;
      that.completed = 0;
      that.success = 0;
      that.failed = 0;
      that.skipped = 0;
    },

    'onComplete': function (event, ID, fileObj, response, data) {
      var queueItem = $(options.el + ID);
      queueItem.html(fileObj.name + '<br /><strong>' + response + '</strong>');

      queueItem.removeClass('uploadifyQueueItem');
      queueItem.removeClass('completed');

      that.completed = that.completed + 1;
      if (response.indexOf('Success') != -1) {
        queueItem.addClass('success');
        that.success = that.success + 1;
      } else if (response.indexOf('already') != -1) {
        queueItem.addClass('info');
        that.skipped = that.skipped + 1;
      } else {
        queueItem.addClass('error');
        that.failed = that.failed + 1;
      }

      $('#status').html('Completed: ' + that.completed + 
                        '/' + that.total + 
                        ' (' + that.success + 
                        ' success, ' + that.failed + 
                        ' failed, ' + that.skipped + 
                        ' skipped)');
    }
  });

  $('#clear').click(function () {
    $('.completed').remove();
    $('#status').html("");
    $('#clear').hide();
    $('.uploadifyQueue').hide();
  });
};

function showTooltip(x, y, contents) {
  $('<div id="tooltip">' + contents + '</div>').css( {
    position: 'absolute',
    display: 'block',
    top: y - 20,
    left: x + 5,
    border: '2px solid #FFBBBB',
    padding: '2px',
    'background-color': '#fee',
    opacity: 1
  }).appendTo("body");
}

function setupFormGraph(options) {
 $.plot($(options.el), options.data, {
    xaxis: { 
      mode: "time",
      timeformat: "%b %y"            
    },

    yaxis: {
      min: 1,
      max: Math.max(100, options.maxRank)
    },

    points: {
      show: true,
      fill: true,
      radius: 5         
    },

    lines: {
      show: true            
    },

    grid: {
      hoverable: true,
      clickable: true
    }                  
  });

  var previousPoint = null;
  $(options.el).bind("plothover", function (event, pos, item) {        
    if (item) {
      if (previousPoint != item.datapoint) {
        previousPoint = item.datapoint;

        $("#tooltip").remove();

        var x = new Date();
        x.setTime(item.datapoint[0]);

        var y = item.datapoint[1];

        showTooltip(item.pageX, item.pageY,
                    x.toUTCString() + "<br />Rank: " + y);
      }
    }
    else {
      $("#tooltip").remove();
      previousPoint = null;            
    }
  });
}

(function($) {
  
  $.fn.jumpertip = function(options) {
    var settings = $.extend({
        content: '',
        isOpen: false
    }, options||{});

    var self = this;

    self.click(function() {
      if (!settings.isOpen) {

        settings.isOpen = true;

        var tinytip$ = $('<div />')
          .addClass('jumpertip')
          .css({ 
            'position': 'absolute',
            'z-index': 9999
          })
          .html('<img src="' + settings.loadingImage + '" alt="loading" />')
          .appendTo(self.parent())          
        
        tinytip$.load(settings.content, function() {          
          $('img.close', tinytip$).click(function() {
              remove();
          })

          tinytip$
            .draggable({ handle: '.jumpertip-header' })
            .resizable();            
        })
      } else {
        remove();
      }
    });

    function remove() {
      self.siblings('div.jumpertip').remove();
      settings.isOpen = false;
    }
  };

})(jQuery);
