/*
 * dashboard widget
 *
 * Copyright (c) 2008, Park Assist -- All Rights Reserved
 *
 * dependencies: jquery-ui/ui.core.js, jquery.timers.js, jquery-ui/effects.highlight.js, jquery.timeago.js
 */
 
(function($) {

  $.paseweb = $.paseweb || {};  /* create the paseweb namespace */
    
  $.widget("paseweb.widget", {
    _init: function() {
      this.wi_id = $(this.element).attr('id');
      /* group all widgets using the same interval on one timer */
      this.label = "paseweb.dashboard." + this.options.refreshSeconds;

      this.start();
    },
    
    start: function() {
      if (this.options.refreshSeconds > 0) {
        
        if (this.options.query_id) {
          this.options.url = "/sites/" + $.paseweb.dashboard.site_id + "/queries/" + this.options.query_id + ".json";
        }
        else if (this.options.endpoint) {
          this.options.url = "/sites/" + $.paseweb.dashboard.site_id + "/status/" + this.options.endpoint + ".json";
        }
        
        $(this).everyTime(1000 * this.options.refreshSeconds, this.label, function(){
          this.poll();
        });
        // kick off a poll now
        this.poll();
      }
    },
    
    stop: function(){
      if (this.options.refreshSeconds > 0) {
        konsole.log("widget ", this.wi_id, " stop / ", this.label);
        $(this).stopTime(this.label);
      }
    },
    
    /* send the AJAX request to fetch values for this widget */
    poll: function() {
      $.ajax({
        type: "GET", dataType: "json", url: this.options.url, 
        widget: this, // stash a reference to the widget object, for callbacks
        success: this.jsonSuccess, 
        error: this.jsonError,
        global:false
      });
      
      return this;
    },
    
    jsonSuccess: function(json, tStatus) {
      // konsole.log("jsonSuccess", tStatus, json);
      if (tStatus != 'success') {
        konsole.log("jsonSuccess failed:", tStatus);
        return;
      }
      if (!json){
        konsole.log("jsonSuccess empty body");
        return;
      }
      
      var widg = this.widget;
      if (json.revision && (json.revision != $.paseweb.revision)) {
        konsole.log("version mismatch detected", $.paseweb.revision, json.revision);
        widg.reloadRequired();
      } else if (json && json.error) {
        if (json.error == 'RETRY') {
          konsole.log("got RETRY on", widg.wi_id);
          // retry in five seconds
          $(widg).oneTime(5000, function(){
            widg.poll();
          });
        } else {
          konsole.log("got ERROR on", widg.wi_id);
          widg.clear_loading();
          widg.flash({color: '#E67D7D'});
        }
      } else {
        widg.refresh(json);

        $('.tooltip', widg.element).tooltip(); // apply behavior
        
        widg.clear_loading();
        widg.flash();
      }
    },
    
    reloadRequired: function(){
      // I'm only telling you once.
      if (typeof $.paseweb.dashboard.reload_required != 'undefined') { return; }
      
      $.paseweb.dashboard.reload_required = true;
      $('.widget-container').widget("stop");
      
      var msg = $("<span>Notice: server version updated. <a href='#'>click here to reload.</a></span>");
      $('a', msg).click(function(){
        window.location.reload();
      });
      $.paseweb.set_flash(msg, 'error');
    },
    
    jsonError: function(request, tStatus, error){
      // konsole.log("ajax Error caught: ", request, tStatus, this);
      konsole.log("got error on", this.widget.wi_id);
      this.widget.flash({color: '#E67D7D'});
    },
    
    refresh: function(json) {
      this.options.js_callback.call(this,json);
      
      this.updated(json["timestamp"]);
      return this;
    },
    
    updated: function(updatedAtTimestamp) {
            
      // If we dont have an updated_at_timestamp, just use the current time
      updatedAtTimestamp = updatedAtTimestamp || new Date().toISOString().replace(/\"/g,'');
      // We also strip out the milliseconds component so that the string can be correctly parsed as a date
      updatedAtTimestamp = updatedAtTimestamp.replace(/\.\d*/,'')
      
      $(".updated", this.element)
        .empty()
        .hide()
        .append($('<abbr class="timeago" title="'+ updatedAtTimestamp +'">at ' + $.timeago.parse(updatedAtTimestamp).toString('h:MM tt') + '</abbr>').timeago())
        .fadeIn();
    },
    

    
    /* visually update the widget on refresh */
    flash: function(options) {
      el = $('.head', this.element);
      if ($.isFunction(el.effect)) {
        el.effect("highlight", options || {}, 2000);
      }
      return this;
    },
    
    clear_loading: function() {
      $('.loading',this.element).removeClass('loading');
    }

  });
  
  /* override these default options when calling the widget() function:
   * $('div').widget({refreshSeconds: 1200})
   */
  $.paseweb.widget.defaults = {
    
    chart: null,
    refreshSeconds: 120,
    js_callback: null,
    url: null,
    endpoint: null
  };
    
})(jQuery);
