var _events = new Array();
var _delta_days = 0;
var _d_query = '';
var _day_limit = 7;
var _filter_id = -1;
var _block_cal_requests = false;
var _events_displayed = 0;

window.onload = function() {

  $(function() {
    $(".email-dialog").dialog({
      autoOpen: false,
      bgiframe: true,
      modal: true,
      position: top,
      width: 366,
      height: 310,
      closeOnEscape: true
    });
  });

  $("#calendar_box").datepicker(
    {
      //gotoCurrent: true,
      onSelect: function(d, c) { dateSelect(d) }
    }
  );

  // get a date from date_calendar cookie, if not found ... use today
  cookie_date = $.cookie('nhm_calendar_date');
  if (cookie_date) {
    $.cookie('nhm_calendar_date', null);
    getEvents(cookie_date);
  }
  else {
    getEvents('today');
  }
}

function dateSelect(d) {

  $("#calendar_box").datepicker('disable');
  
  ds = d.split('/');
  d = ds[2] + '-' + ds[0] + '-' + ds [1];

  _d_query = ds[2] + '-' + ds[0];
	    
  if (_events[_d_query]) {
    //$("#event_template").empty();
    showDayEvents(d);
  }
  else {
    getEvents(d);
  }
  
}

function showDayEvents(d) {

  if (!_block_cal_requests) {

    _block_cal_requests = true;
    
	  showTab('day');
	  $(".an-event").removeClass().hide();
	
	  if (d == '') {
	    cal_date = $("#calendar_box").datepicker('getDate');
	    this_day = $.datepicker.formatDate('yy-mm-dd', cal_date);
	  }
	  else {
	    this_day = d;
	  }
	
	  d2 = $.datepicker.parseDate('yy-mm-dd', this_day);
	  d3 = $.datepicker.formatDate('MM d, yy', d2);
	  $(".text-date-day").html(d3);
	
	  today = getToday();
	  text_today = 'Today';
	  if (today != this_day) text_today = $.datepicker.formatDate('M d', d2);
	  $(".day_tab").find('a').html(text_today);
	
	  $("#calendar_box").datepicker('setDate' , d2);
	 	      
	  events_shown = 0;
	
	  for (i in _events[_d_query]) {
	   
	    e = _events[_d_query][i];
	    if (e["edate"] == this_day) {
	        	
        if (e["title"] == 'MUSEUM CLOSED') { showClosure('', e["description"]); }            
            
	      var show_me = filterMe(e["types"]);
	      if (!show_me) continue;
	
	      events_shown++;
	
	      this_class = "event-" + i;
	      $("#event_template").clone(true).addClass(this_class + " an-event").appendTo("#events").attr('id', this_class);
	
	      var etitle = e["title"];
	      if (e["elink"]) {
	        etitle = e["elink"] + e["title"] + '</a>';
	      }
	
	      $("." + this_class + " div a").attr('id', _d_query + '_' + i);
	
	      $("." + this_class + " .etitle").find("b").prepend(etitle);
	      $("." + this_class + " .idescription").prepend(e["description"]);
	      icons = e["types"];
	      for (t in icons) {
	        $("." + this_class + " .eicons").prepend(getEventTypeIcon(icons[t]) + '&nbsp;');
	      }
	      if (e["reservation"]) {
	        $("." + this_class + " .ereservation").show();
	      }
	
	      if (e["fee"]) {
	        $("." + this_class + " .etitle").append("&nbsp;&nbsp;<img src=\"/site/sites/all/themes/zen_nhm_theme/images/buy_events_icon_small.gif\" title=\"" + e['fee_label'] + "\" alt=\"" + e['fee_label'] + "\">");
	      }
	      if (e["fee_label"]) {
	        $("." + this_class + " .efee").show().append(e['fee_label'] + '.');
	        if (e["fee_description"]) {
	          $("." + this_class + " .efee").append('<br/>' + e['fee_description']);
	        }
	      }
	
	      if (e["location"]) {
	        $("." + this_class + " .elocation").append(e["location"]);
	        $("." + this_class + " .elocation").show();
	      }
	      if (e["start"]) {
	        if (e["end"]) {
	          $("." + this_class + " .etime").append(hm(e["start"]) + ' to ' + hm(e["end"]));
	        }
	        else {
	          $("." + this_class + " .etime").append(hm(e["start"]));
	        }
	
	        $("." + this_class + " .etime").show();
	      }
	      $("." + this_class).slideDown("normal",function(){
	         _events_displayed++;
	         if (_events_displayed == events_shown) {
  	         _events_displayed = 0;
  	         _block_cal_requests = false;   
            $("#calendar_box").datepicker('enable');      
	         }
        });
	      
	    }
	  }
	  if (events_shown == 0) {
      showError();
      _events_displayed = 0;
      _block_cal_requests = false; 	    
      $("#calendar_box").datepicker('enable');      	    
	  }
	
	} // end block cal req
	
}

function showWeekEvents(d, container) {
  $("." + container + " .week_events").html('');

  events_shown = 0;
  for (eidx in _events[_d_query]) {
    if (events_shown < _day_limit) {
      e = _events[_d_query][eidx];

      // don't show daily events in the week or month view
      skip_me = false;
      for (t in e["types"]) if (e["types"][t] == 0) skip_me = true;
      if (skip_me) continue;

      var show_me = filterMe(e["types"]);
      if (!show_me) continue;

      if (e["edate"] == d) {
        if (e["title"] == 'MUSEUM CLOSED') {
          events_shown++;
          $("." + container + " .week_events").append('<div class="week_event"><a name="#" onclick="showDayEvents(\'' + d + '\')">' + e["title"] + '</a></div>');
          $("." + container + " .week_events").append('<div class="week_event"><a name="#" onclick="showDayEvents(\'' + d + '\')">More info &gt;</a></div>');
          return events_shown;             
        } else {
          events_shown++;
          $("." + container + " .week_events").append('<div class="week_event"><a name="#" onclick="showDayEvents(\'' + d + '\')">' + e["title"] + '</a></div>');
        }
      } 
    }
  }
  if (events_shown > 0) {
    $("." + container + " .week_events").append('<div class="week_event"><a name="#" onclick="showDayEvents(\'' + d + '\')">More info &gt;</a></div>');
  }
  return events_shown;
}


function getEvents(d) {
  if (d == 'today') d = getToday();

  d2 = $.datepicker.parseDate('yy-mm-dd', d);
  $("#calendar_box").datepicker('setDate' , d2);

  d_query = $.datepicker.formatDate('yy-mm', d2);
  _d_query = d_query;
  
  if (_events[_d_query]) {
  }
  else {
    $(".working").fadeIn();
    _events[_d_query] = Array();
    $.ajax({
      type: "GET",
      url: "/site/calendar/get_day/" + d_query,
      dataType: "json",
      success: function(data) {
        $(".working").fadeOut('normal', function () { procEvents(data) } );
      },
      error: function(data) {
        $(".working").fadeOut('normal', function () { showError(); } );
      }
    });	
  }
}

function procEvents(data) {
  nidx = 0;
  
  // TEMP FIX
  temp_date = _d_query.split('-');
  if (temp_date[1].length == 1) {
    _d_query = temp_date[0] + '-01';
  }
  
  //alert(typeof _events[_d_query]);
  // FF & IE show object with pageload
  // FF shows object from mincal call.  *** IE shows undefined in call from FP ***

  if (typeof(_events[_d_query]) == "undefined") {
    _events[_d_query] = Array();    
	}					 
  
  $.each(data.items,
    function(i, item) {
      nid = item.nid;
      d1 = item.node_data_field_calendar_date3_field_calendar_date3;
      d2 = d1.split(' ');
      edate = d2[0];
      eidx = getEventIdx(nid, edate);

      if (eidx < 0) {
        _events[_d_query][nidx] = Array();
        _events[_d_query][nidx]["nid"] = nid;
        _events[_d_query][nidx]["title"] = item.node_data_field_event_description_field_event_name;
        _events[_d_query][nidx]["description"] = item.node_data_field_event_description_field_event_description;
        if (item.node_data_field_event_type_field_event_type) {
          _events[_d_query][nidx]["types"] = Array();
          _events[_d_query][nidx]["types"][item.node_data_field_event_type_delta] = item.node_data_field_event_type_field_event_type;
        }

        _events[_d_query][nidx]["edate"] = edate;

        link_nid = item.node_data_field_event_description_field_event_internal_link_nid;
        if (link_nid > 0) {
          _events[_d_query][nidx]["elink"] = "<a href=\"/site/node/" + link_nid + "\">";
        }

        if (item.node_data_field_event_description_field_event_location != "") {
          _events[_d_query][nidx]["location"] = getLocation(item.node_data_field_event_description_field_event_location);
        }

        _events[_d_query][nidx]["reservation"] = false;
        if (item.node_data_field_event_description_field_event_reservation == "0") {
          _events[_d_query][nidx]["reservation"] = true;
        }

        _events[_d_query][nidx]["fee_description"] = '';
        _events[_d_query][nidx]["fee_label"] = '';
        _events[_d_query][nidx]["fee"] = false;
        if (item.node_data_field_event_description_field_event_fee == "1") {
          _events[_d_query][nidx]["fee_label"] = 'Free with paid Museum admission';
        }
        if (item.node_data_field_event_description_field_event_fee == "2") {
          _events[_d_query][nidx]["fee"] = true;
          _events[_d_query][nidx]["fee_label"] = 'This event has an additional fee';
          _events[_d_query][nidx]["fee_description"] = item.node_data_field_event_description_field_event_fee_description;
        }

        _events[_d_query][nidx]["start"] = item.node_data_field_event_description_field_start_time;
        _events[_d_query][nidx]["end"] = item.node_data_field_event_description_field_end_time;

        nidx = nidx + 1;

      }
      else {
        _events[_d_query][eidx]["types"][item.node_data_field_event_type_delta] = item.node_data_field_event_type_field_event_type;
      }
    }
  );
  
  showDayEvents('');
  
}

function getEventIdx(nid, edate) {
  for (i in _events[_d_query]) {
    e = _events[_d_query][i];
    if (e["nid"] == nid && e["edate"] == edate) {
      return i;
    }
  }
  return -1;
}

function filterMe(types) {
  var show_me = true; // only if there's a filter defined, we should set this to false
  if (_filter_id >= 0) {
    show_me = false;
    for (x in types) {
      if (types[x] == _filter_id) {
        show_me = true;
      }
    }
  }
  return show_me;
}

function filterBy(i) {
  $(".working").hide(); // just in case
  _filter_id = i;
  if (i >= 0) {
    var img = getEventTypeIcon(i);
    var name = getEventTypeName(i);
    $(".filtering").html(img + '&nbsp;&nbsp;&nbsp;Showing only events of type ' + name + '.  <a href="#" onclick="filterBy(-1)">Show all >></a>');
    $(".filtering").slideDown();
  }
  else {
    $(".filtering").slideUp();
  }
  showDayEvents('');
}

function getEventTypeName(x) {
  e_name = Array();
  e_name[0]  = "Daily Event";
  e_name[1]  = "Lecture";
  e_name[2]  = "Child Event";
  e_name[3]  = "Adults";
  e_name[4]  = "Fellows Events";
  e_name[5]  = "Field Trips";
  e_name[6]  = "Museum Tours";
  e_name[7]  = "Member Only Events";
  e_name[8]  = "For Families";
  e_name[9]  = "Dinosaurs";
  e_name[10] = "Insects";
  return e_name[x];
}

function getEventTypeIcon(x) {
  e_icon = Array();
  e_icon[0]  = "/site/sites/all/themes/zen_nhm_theme/images/daily_events_icon_small.gif";
  e_icon[1]  = "/site/sites/all/themes/zen_nhm_theme/images/lectures_events_icon_small.gif";
  e_icon[2]  = "/site/sites/all/themes/zen_nhm_theme/images/children_events_icon_small.gif";
  e_icon[3]  = "/site/sites/all/themes/zen_nhm_theme/images/adults_events_icon_small.gif";
  e_icon[4]  = "/site/sites/all/themes/zen_nhm_theme/images/fellows_events_icon_small.gif";
  e_icon[5]  = "/site/sites/all/themes/zen_nhm_theme/images/field_events_icon_small.gif";
  e_icon[6]  = "/site/sites/all/themes/zen_nhm_theme/images/museum_events_icon_small.gif";
  e_icon[7]  = "/site/sites/all/themes/zen_nhm_theme/images/member_events_icon_small.gif";
  e_icon[8]  = "/site/sites/all/themes/zen_nhm_theme/images/families_events_icon_small.gif";
  e_icon[9]  = "/site/sites/all/themes/zen_nhm_theme/images/dinosaurs_events_icon_small.gif";
  e_icon[10] = "/site/sites/all/themes/zen_nhm_theme/images/insects_events_icon_small.gif";
  return "<img src=\"" + e_icon[x] + "\" alt=\"" + getEventTypeName(x) + "\" title=\"" + getEventTypeName(x) + "\" >";
}

function getToday() {
  var d = new Date();
  return $.datepicker.formatDate('yy-mm-dd', d);
}

function hm(d) {
  if (d) {
    d1 = d.split(' ');
    d = d1[1];
    d1 = d.split(':');
    s = ':';
    am = 'am';
    h = d1[0];
    m = d1[1];
    if (h >= 12) {
    	h = h - 12;
    	am = 'pm';
    	if (h == 0) {
    	  h = 12;
    	}
    }
    d = h + s + m + am;
    return d;
  }
  else {
    return '';
  }
}

function getLocation(l) {
  e_loc = Array();

  e_loc[1]  = "Level 1";
  e_loc[2]  = "Level 2";
  e_loc[3]  = "Level G";
  e_loc[4]  = "Grand Foyer";
  e_loc[5]  = "Dueling Dinosaurs";
  e_loc[6]  = "Exposition Entrance";
  e_loc[7]  = "Main Entrance";
  e_loc[8]  = "Jean Delacour Auditorium";
  e_loc[9]  = "Discovery Center";
  e_loc[10] = "North American Mammal Hall, Level 1";
  e_loc[11] = "African Mammal Hall, Level 1";
  e_loc[12] = "North American Mammal Hall, Level 2";
  e_loc[13] = "Offsite";
  e_loc[14] = "South Lawn";
  e_loc[15] = "Throughout Museum";

  return e_loc[l];
}

function showError() {
  showTab('error');
}

function showClosure(closedHeader, closedMsg) {
  $("#closure_message").html('<span class="text-date-day">' + closedMsg + '</span>');
  showTab('closure');
}

function showTab(t) {
  $(".view").hide();
  $("." + t + "_view").show();

  if (t != 'error') {
    $(".tab").removeClass("bl_select");
    $("." + t + "_tab").addClass("bl_select");
  }

  if (t == 'week') {
    weekLoad();
  }
  if (t == 'month') {
    monthLoad();
  }
}

function monthLoad() {
  
  $(".week").hide();
  $(".week").find('h3').html('&nbsp;');
  $(".week .week_events").html('&nbsp;');

  d = $("#calendar_box").datepicker('getDate');
  d.setDate(1);
  day = d.getDay();
  
  month_name = $.datepicker.formatDate('MM yy', d);
  $(".text-date-week").html(month_name);
  this_month = $.datepicker.formatDate('m', d);
  shown_events_month = 0;
  
  for (i = 0; i < day + 32; i++) {
    same_month = $.datepicker.formatDate('m', d);
    if (this_month == same_month) {  
      if (i >= day) {
        $(".week-" + i).find('h3').html($.datepicker.formatDate('d', d));
        shown_events_day = showWeekEvents($.datepicker.formatDate('yy-mm-dd', d), "week-" + i); 
        shown_events_month = shown_events_month + shown_events_day;
        // Daylight savings time
        if ($.datepicker.formatDate('mm-dd', d) == '11-01') {
          d.setTime(d.getTime() + 90000000); 
        } else {
          d.setTime(d.getTime() + 86400000); 
        }
      }
      $(".week-" + i).slideDown();
    }
  }
  if (shown_events_month == 0) {
    showError();
  }

}

function weekLoad() {

  $(".week").hide();
  $(".week").find('h3').html('&nbsp;');
  $(".week .week_events").html('&nbsp;');

  d = $("#calendar_box").datepicker('getDate');
  day = d.getDay();

  month_name = $.datepicker.formatDate('MM yy', d);
  $(".text-date-week").html(month_name);

  d.setTime(d.getTime() - ((day + 1) * 86400000));

  shown_events_week = 0;
  for (i = 0; i < 7; i++) {
    d.setTime(d.getTime() + 86400000);
    $(".week-" + i).find('h3').html($.datepicker.formatDate('M d', d));
    shown_events_day = showWeekEvents($.datepicker.formatDate('yy-mm-dd', d), "week-" + i);
    shown_events_week = shown_events_week + shown_events_day;
    $(".week-" + i).slideDown();
  }
  if (shown_events_week == 0) {
    showError();
  }
}

function sendEmailForm(e) {
  $(".sending-email").hide();
  $(".dialog-error").hide();
  $(".dialog-error-name").hide();
  $(".dialog-error-from").hide();
  $(".dialog-error-to").hide();
  $(".dialog-paragraph").show();

  var key = e.id;
  var key_parts = key.split('_');
  e = _events[key_parts[0]][key_parts[1]];
  if (e) {
    //$(".email-etitle").html("Will email the event named <b>" + e['title'] + "</b>");
    $('.email-dialog').dialog('option', 'buttons', { "Send Email": function() { sendEmail(e) } });
    $('.email-dialog').dialog('open');
  }
}

var _sending_email = false;
function sendEmail(e) {

  $(".dialog-error").hide();
  $(".dialog-error-name").hide();
  $(".dialog-error-from").hide();
  $(".dialog-error-to").hide();
  
  var email_name = $("#email-name").val();
  var email_from = $("#email-from").val();
  var email_to = $("#email-to").val();
  var email_message = $("#optional_message").val();
  
  if (email_name == '') {
    $(".dialog-error-name").slideDown('');
    return;
  }
  
  if (!isEmail(email_from)) {
    $(".dialog-error-from").slideDown('');
    return;
  }

  if (!isEmail(email_to)) {
    $(".dialog-error-to").slideDown('');
    return;
  }

  if (_sending_email) {
    return;
  }
  _sending_email = true;

  $(".dialog-paragraph").hide();
  $(".sending-email").show();

  var d = $.datepicker.parseDate('yy-mm-dd', e["edate"]);
  var nice_d = $.datepicker.formatDate('MM d, yy', d);

  var data = {
    nid: e["nid"],
    date: e["edate"],
    nice_date: nice_d,
    ename: email_name,
    from: email_from,
    to: email_to,
    emessage: email_message
  };
  
  var post_data = 'data=' + $.toJSON(data);
  $.post(
    "/site/email-friend-post",
    post_data,
    function (data) {
      _sending_email = false;
      if (data[0]) {
        $('.email-dialog').dialog('close');
      }
      else {
        $('.email-dialog').dialog('close');
      }
    },
    "json");
}

function isEmail(v) {
  var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
  if (filter.test(v)) {
    return true;
  }
  else {
    return false;
  }
}
