/* Copyright 2008 Park Assist -- All rights reserved. */

/* konsole is a safe wrapper for the Firebug console. */
var konsole = {
  log: function(args){},
  dir: function(args){}
};

if (typeof window.console != 'undefined' && typeof window.console.log == 'function') {
  konsole = window.console;
}

// rails auth token enabled in jquery
jQuery(document).ajaxSend(function(event, request, settings) {
  if (typeof(AUTH_TOKEN) == "undefined") return;
  if (settings.type == 'GET') return; // Don't add anything to a GET request lest IE turn it into a POST.
  settings.data = settings.data || "";
  settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(AUTH_TOKEN);
});

// add javascript request type
jQuery.ajaxSetup({ 'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")} });

$(document).ready(function(){

  // block all AJAX requests by default
  // FIXME: we probably dont want/need this but its here for testing for now
  // $().ajaxStart($.blockUI).ajaxStop($.unblockUI);

  //TODO: Move this into an admin only application.js
  // assumes only one refreshable on the page
  $('select.refresh-sites').change(function(){
    var client = $('option:selected', $(this)).attr('c_slug');
    var sel = $('select.refreshable').empty();
    
    if (client === '') { return; }
    
    jQuery.getJSON("/sites.json", {client_id: client}, function(json, tStatus){

        konsole.log("fetching sites for new client: ", client);
        sel.append($("<option>select a Site</option>"));
      
      $.each(json, function(){
        var site = this.site;
        sel.append( $("<option value='" + site.id + "'>" + site.name + "</option>"));
      });
    });
  });
  
  $('#flash .flash-close-button').live('click', function(){$('#flash').slideUp(500);});

  $('#fullscreen').click(function() { $('body').toggleClass('fullscreen') });

  // check metric options field for proper hash format
  $('#metric-edit-form').submit(function() {
    var valid = false;
    var text = $('#metric-edit-form #metric_options').val();
    var pattern = /(\w+):\s*(.+)/g;
    var result;

    // now parse the key:value pairs
    while ((result = pattern.exec(text)) != null) {
      var hidden_field = $("<input type='hidden' />").attr('name', "metric[options]["+result[1]+"]").val(result[2].replace(/[\"\']/g, ''));
      konsole.log("new field: ", hidden_field);
      $('#metric-edit-form').append(hidden_field);
      valid = true;
    }

    // Note: must return true for form to still submit
    if ( valid ) {
      $('#metric-edit-form #metric_options').remove();
      return true;
    } else {
      // TODO: make a better UI notification than using a javascript alert box
      alert('Please check for the format of the Options field.\n\nYou must specify query_id at a minimum.\n');
      return false;
    }
  });

  //
  // ** Client#show actions 
  //
  //
  $("#client-actions-close").click(function() { 
    $("#client-actions-body").empty();
    $("#client-actions").hide(); 
  });

  //    1. add user
  //
  $("a#client-add-user").click(function() {
      var ajax_err = false;

      // clear out actions section
      $("#client-actions-body").empty();
      $("#client-actions-title").empty();

      // send GET request
      $.ajax({
        type: "GET",
        dataType: "script",
        url: $(this).attr("href"),
        beforeSend: function() { $.blockUI(); },
        complete: function() { $.unblockUI(); },
        error: function(request, textStatus, err) {
          konsole.log("Error creating new client via AJAX", err);
          ajax_err = true;
        }
      });

      // update actions section
      $("#client-actions-title").html("Add a new user");
      $("#client-actions").show();
      return ajax_err;
  });
  //
  //    2. edit client profile
  //
  $("a#client-edit-profile").click(function() {
      var ajax_err = false;
      
      // clear out actions section
      $("#client-actions-body").empty();
      $("#client-actions-title").empty();

      // send GET request
      $.ajax({
        type: "GET",
        dataType: "script",
        url: $(this).attr("href"),
        beforeSend: function() { $.blockUI(); },
        complete: function() { $.unblockUI(); },
        error: function(request, textStatus, err) {
          konsole.log("Error updating client profile via AJAX", err);
          ajax_err = true;
        }
      });

      // update actions section
      $("#client-actions-title").html("Edit client profile");
      $("#client-actions").show();
      return ajax_err;
  });

  //
  //    3. edit client user
  //
  $("#client-edit-users a").live("click", function() {
      var ajax_err = false;
      
      // clear out actions section
      $("#client-actions-body").empty();
      $("#client-actions-title").empty();

      // send GET request
      $.ajax({
        type: "GET",
        dataType: "script",
        url: $(this).attr("href"),
        beforeSend: function() { $.blockUI(); },
        complete: function() { $.unblockUI(); },
        error: function(request, textStatus, err) {
          konsole.log("Error updating user profile via AJAX", err);
          ajax_err = true;
        }
      });

      // update actions section
      $("#client-actions-title").html("Edit user profile");
      $("#client-actions").show();
      return ajax_err;
  });
});

$.paseweb = $.paseweb || {};  /* create the paseweb namespace */

// dynamically add a rails Flash-style message
// we're expecting a span element here (may be text or jQ object)
$.extend($.paseweb, {
  set_flash: function(span, _type){
    var type = _type || 'notice';
    var div = $("<div class='flash " + type + " ui-corner-all' id='flash'> </div>");
    var close = $("<div class='flash-close-button ui-state-default ui-corner-all'><span class='ui-icon ui-icon-closethick'>Close</span></div>");
    div.append(close);
    div.append($(span));
    
    $('#flash').remove();
    $('#navigation').after(div);
  },

  noReportData: function(dom_id) {
    var output_msg = "<p class='no-report-data-msg'>There is no data for this timeframe to report.</p>";
    $(dom_id).replaceWith(output_msg);
  }

});

// These functions perform arithmetic on a set of objects
$.fn.extend({
  sum: function(member){
    var total = 0;
    this.each(function(i){
      total += this[member];
    });
    return total;
  }
});

// Image pre-loader
// -- arr is the array of images to preload
$.preloadImages = function(arr) {
  $.each(arr, function(i) {
    $("<img>").attr("src", this); 
  }); 
};

/* This will convert a string in the format 'yyyyMMdd' into a JavaScript Date object */
function js_date(date_string) {
  var ds = date_string.toString();
  return new Date(Date.UTC(ds.slice(0,4), ds.slice(4,6)-1, ds.slice(6)));
}

/* This will convert a string in the format 'yyyyMMdd' into the number of milliseconds since the epoch 1/1/1970 00:00:00 +00:00 (UTC) */
function yyyyMMddToUnixtime(dateString) {
  var ds = dateString.toString();
  return Date.UTC(ds.slice(0,4), ds.slice(4,6)-1, ds.slice(6));
}

/* Calculate the number of days elapsed between 2 JavaScript Date objects */
function days_between(date1, date2) {
  var ONE_DAY = 86400000;//1000 * 60 * 60 * 24
  var date1_ms = date1.getTime();
  var date2_ms = date2.getTime();
  var difference_ms = Math.abs(date1_ms - date2_ms);
  return Math.round(difference_ms/ONE_DAY);
}
