/* USER VARIABLES */

// Number of events to display per page (int)
var numEvents = 20;
// Whether to display empty filter items (true/false)
var showEmptyFilters = true;
// Base URL for BrassRing (string)
//var brassringURL = "http://stagingjobs.brassring.com/1033/ASP/TG/cim_home.asp?partnerid=25008&siteid=5101&gqid=673&codes=";
var brassringURL = "http://jobs.brassring.com/1033/ASP/TG/cim_home.asp?partnerid=25008&siteid=5100&gqid=564&codes=";
// Location of the XML file (string)
//var xmlFileLocation = "events.xml.php";
var xmlFileLocation = "http://www.ubs.com/2/e/medlib/group/graduates/eventcal/xml/events.xml";

/* END OF USER VARIABLES, DO NOT EDIT BELOW THIS LINE */

// Current page
var pageNum = 0;
// Count of active events
var totalNumEvents = 0;
// Today's date
var today = new Date();
// Filter vars
var fltCountry;
var fltGroup;
var fltSchool;
// Array of filterList objects
var arrFilterList = []; 
// Array of calendar item objects
var arrEventItems = []; 
// Count of events for the current view
var numInstanceEvents = 0;
// Temporary array
var tmpArray = [];

// Event Calendar object
var eventItem = function()
{
  this.get_html = function()
  { 
    var txt = '<tr class="eventHead" alt="row_' + this.id + '">\n' +
              '<td class="first">' + this.ec_event_strdate + '</td>' +
              '<td>' + this.ec_country + '</td>' +
              '<td>' + this.ec_event_loc + '</td>' +
              '<td>' + this.ec_event_name + '</td>' +
              '</tr>\n' +
              '<tr class="eventBody" alt="row_' + this.id + '">\n' +
              '<td colspan="4"><div class="left">' +
              '<big><b>' + this.ec_event_name + '</b></big><br/><br/>' + 
              '<b>Division</b>: ' + this.ec_level_group + '<br/>' + this.ec_description + '<br/>' +
              this.ec_reg + '<br/></br>' +
              '</div>' +
              '<div class="right">' +
              '<img dat="row_' + this.id + '" class="closeBtn" src="http://www.ubs.com/2/e/medlib/group/graduates/eventcal/images/btn_x_orange.gif" alt="Close Detail" title="" border="0" />' +
              '<b>Date:</b> ' + this.ec_event_strdate + '<br/><br/>' +
              '<b>Time:</b> ' + this.ec_event_time + '<br/><br/>' +
              '<b>City:</b> ' + this.ec_city + '<br/><br/>' +
              '<b>Country:</b> ' + this.ec_country + '<br/><br/>' +
              '<b>School Level:</b> ' + this.ec_school + '<br/><br/>' +
              '<b>Location:</b> ' + this.ec_event_loc + '<br/><br/>' +
              '</div></td>' +
              '</tr>\n';
      return txt;
    } 
}

// Filter Group object
var filterGroup = function()
{
    this.name = '';   // name of filter; string
    this.items = '';  // list of filterItems; array

    this.debug = function()
    {
        var txt = this.name + '\n';
        for(var i=0; i<this.items.length; i++) {
          txt+= ' ' + this.items[i].name + ' : ' + this.items[i].count + '\n';
        }
        alert(txt);
    }
}

// Filter Item object
var filterItem = function(name, count)
{
    this.name = name;   // name of filter item; string
    this.count = count; // number of events which contain this item; int
}


$(document).ready(function() { 
  // Remove event trapping
  window.onresize = null;
  document.onmousemove = '';

  // Get filter vars
  fltCountry = ($.jget['country']) ? decodeURIComponent($.jget['country'])  : '';
  fltGroup = ($.jget['group']) ? decodeURIComponent($.jget['group']) : '';
  fltSchool = ($.jget['school']) ? decodeURIComponent($.jget['school']) : '';
  // Get page number
  pageNum = ($.jget['pg']) ? $.jget['pg'] : 0;

  // Load table
  $.ajax({
    type: "GET",
    url: xmlFileLocation,
    dataType: "xml",
    success: function(xml) {
      // Populate events
      $(xml).find('event').each(function(i) {
        arrEventItems.length = i;
        arrEventItems[i] = new eventItem(); 
        arrEventItems[i].id = i;
        arrEventItems[i].ec_event_num = $(this).find('event_num').text();
        arrEventItems[i].ec_event_time = $(this).find('event_time').text();
        arrEventItems[i].ec_event_strdate = $(this).find('event_strdate').text();
        arrEventItems[i].ec_event_end_pcdate = $(this).find('event_end_pcdate').text();
        arrEventItems[i].ec_event_name = $(this).find('event_name').text();
        arrEventItems[i].ec_description = $(this).find('description').text();
        arrEventItems[i].ec_city = $(this).find('city').text();
        arrEventItems[i].ec_country = $(this).find('country').text();
        arrEventItems[i].ec_school = $(this).find('school').text();
        arrEventItems[i].ec_event_loc = $(this).find('event_loc').text();
        arrEventItems[i].ec_level_group = $(this).find('level_group').text();
        var ec_reg_link = ( $(this).find('ats_link').text() ) ? 
            brassringURL +
            //$(this).find('vendor_code').text() + ',' +
            $(this).find('ats_link').text() :
            '';
        arrEventItems[i].ec_reg = ( ec_reg_link ) ? '<a target="_blank" href="' + ec_reg_link + '"><img src="http://www.ubs.com/2/e/medlib/group/graduates/eventcal/images/btn_register_off.gif" alt="Register" title="" border="0" /></a>' : '';

      }); // close each

      // Populate filters
      $(xml).find('filter').each(function(i) {
        tmpArray = [];
        arrFilterList.length = i;
        arrFilterList[i] = new filterGroup();
        arrFilterList[i].name = $(this).attr("name");
        $(this).find('item').each(function(j) {
           tmpArray.length = j;
           tmpArray[j] = new filterItem( $(this).attr("name"), $(this).attr("count") );
        });
        arrFilterList[i].items = tmpArray; 
        //arrFilterList[i].debug();
      }); // close each

    },
    error: function(obj, str, exc){
      alert("Error: " + str);
    },
    complete: function(obj, str){
      // Populate the calendar
      populateCalendar();

      // Invoke tablesorter
      addTableWidget();
      $("#event_cal").tablesorter( {sortList:[[0,0]], widgets:['zebra','eventTable'], headers:{0:{sorter:'eventdate'}} });

      // Populate the filters
      populateFilters();

      // Populate the pagination
      populatePagination();

      // Attach click behaviors
      bindBehaviors(); 
    }
  }); //close $.ajax

});


// Populate the calendar
function populateCalendar()
{
    for(var i=0; i<arrEventItems.length; i++)
    { 
        var proceed = 1;
        var eTxt = "";
        // Check date for validity
        var validDate = today.compare(arrEventItems[i].ec_event_end_pcdate);
        // Pagination variables
        var pageTop = numEvents * pageNum;
        var pageBot = pageTop + numEvents + 1;

        if(validDate == 1)
        {
            // Count number of active events
            totalNumEvents++;

            // Check filters
            if(fltCountry && fltCountry != arrEventItems[i].ec_country) { proceed = -1; }
            if(fltGroup && fltGroup != arrEventItems[i].ec_level_group) { proceed = -1; }
            if(fltSchool && fltSchool != arrEventItems[i].ec_school) { proceed = -1; } 

            if(proceed == 1)
            {
                // Number of events for this view
                numInstanceEvents++;

                if (numInstanceEvents>pageTop && numInstanceEvents<pageBot)
                {
                    // Add the event to the page
                    eTxt = arrEventItems[i].get_html();
                    $( eTxt ).appendTo('#event_cal tbody'); 
                }  // end page check 
            } // end filter check
        }  // end date check
    }

    // Message for no results
    var rowCount = $('#event_cal tbody').children().length;
    if( rowCount == 0 ) {
        $( '<tr class="eventHead">\n' +
           '<td class="first" colspan="4">There are no events scheduled which meet that criteria.</td>' +
           '</tr>\n'
        ).appendTo('#event_cal tbody'); 
    } 
      
    // Hide the loading graphic
    $("#loadIcon").hide(); 
}


// Add pagination links
function populatePagination()
{
    // Calculate number of pages
    var numOfPages = Math.ceil(numInstanceEvents / numEvents);
    // Create the menu
    if(numOfPages > 0) 
    {
        var txt = "Page: ";
        for(var i=0; i<numOfPages; i++) {
            if(i == pageNum)
                txt+= '&nbsp;[' + (i+1) + ']&nbsp;';
            else
                txt+= '&nbsp;<a href="?pg=' + i + '&amp;country=' + encodeURIComponent(fltCountry) + '&amp;group=' + encodeURIComponent(fltGroup) + '&amp;school=' + encodeURIComponent(fltSchool) + '">' + (i+1) + '</a>&nbsp;';
        }
        // Replace the loading graphic with the paginator
        $("#loadIcon").html(txt).show();
    }
}


// Populate and activate the event filters
var populateFilters = function() 
{ 
  // Add 'reset all' if any filters are present
  if(fltCountry || fltGroup || fltSchool) {
    $('<a href="?country=&amp;group=&amp;school=">[reset all]</a>').appendTo('#filterBy');
  }

  // Add content to 'country' category and bind toggle events
  if(!fltCountry) {
    tmpArray = arrFilterList[0].items;
    for(var i=0; i<tmpArray.length; i++) 
    {
      if(tmpArray[i].count > 0) {
        $('\n<div class="item"><a href="?country=' + encodeURIComponent(tmpArray[i].name) + '&amp;group=' + encodeURIComponent(fltGroup) +
          '&amp;school=' + encodeURIComponent(fltSchool) + '">' + tmpArray[i].name + '&nbsp;(' + tmpArray[i].count + ')</a></div>').appendTo('div.country.content');
      } else if(showEmptyFilters == true) {
        $('\n<div class="item"><span>' + tmpArray[i].name + '&nbsp;(' + tmpArray[i].count + ')</span></div>').appendTo('div.country.content');
      }
    }
    bindFilterOpen( $("div.country.header"), $('div.country.content') );
  } else {
    $('\n<div class="active">' + fltCountry  + 
      ' <a href="?country=&amp;group=' + encodeURIComponent(fltGroup) + '&amp;school=' + encodeURIComponent(fltSchool) +
      '">[reset]</a></div>').appendTo('div.country.content'); 
    bindFilterClose( $("div.country.header"), $('div.country.content') );
  }

  // Add content to 'group' category and bind toggle events 
  if(!fltGroup) {
    tmpArray = arrFilterList[1].items;
    for(var i=0; i<tmpArray.length; i++) 
    {
      if(tmpArray[i].count > 0) {
        $('\n<div class="item"><a href="?country=' + encodeURIComponent(fltCountry) + '&amp;group=' + encodeURIComponent(tmpArray[i].name) +
          '&amp;school=' + encodeURIComponent(fltSchool) + '">' + tmpArray[i].name + '&nbsp;(' + tmpArray[i].count + ')</a></div>').appendTo('div.group.content');
      } else if(showEmptyFilters == true) {
        $('\n<div class="item"><span>' + tmpArray[i].name + '&nbsp;(' + tmpArray[i].count + ')</span></div>').appendTo('div.group.content');
      }
    }
    bindFilterOpen( $("div.group.header"), $('div.group.content') );
  } else {
    $('\n<div class="active">' + fltGroup + 
      ' <a href="?country=' + encodeURIComponent(fltCountry) + '&amp;group=&amp;school=' + encodeURIComponent(fltSchool) +
      '">[reset]</a></div>').appendTo('div.group.content'); 
    bindFilterClose( $("div.group.header"), $('div.group.content') );
  }

  // Add content to 'school' category and bind toggle events 
  if(!fltSchool) {
    tmpArray = arrFilterList[2].items;
    for(var i=0; i<tmpArray.length; i++) 
    {
      if(tmpArray[i].count > 0) {
        $('\n<div class="item"><a href="?country=' + encodeURIComponent(fltCountry) + '&amp;group=' + encodeURIComponent(fltGroup) +
          '&amp;school=' + encodeURIComponent(tmpArray[i].name) + '">' + tmpArray[i].name + '&nbsp;(' + tmpArray[i].count + ')</a></div>').appendTo('div.school.content'); 
      } else if(showEmptyFilters == true) {
        $('\n<div class="item"><span>' + tmpArray[i].name + '&nbsp;(' + tmpArray[i].count + ')</span></div>').appendTo('div.school.content');
      }
    }
    bindFilterOpen( $("div.school.header"), $('div.school.content') );
  } else {
    $('\n<div class="active">' + fltSchool + 
      ' <a href="?country=' + encodeURIComponent(fltCountry) + '&amp;group=' + encodeURIComponent(fltGroup) +
      '&amp;school=">[reset]</a></div>').appendTo('div.school.content'); 
    bindFilterClose( $("div.school.header"), $('div.school.content') );
  }
  
}


// TableSorter Widget to keeps data rows attached to header rows
var dr_htm = [];
var dr_num = [];
var addTableWidget = function() {
  $.tablesorter.addWidget({ 
    // Give the widget a id 
    id: "eventTable", 
    // Format is called on init and when a sorting has finished 
    format: function(table) { 
      // Collect all eventBody rows (only once)
      if(dr_htm.length == 0) {
        $("tr.eventBody").each(function() { 
          dr_num.push( $(this).attr('alt') );
          dr_htm.push( $(this).clone() ); 
        }); 
      };
      
      // Remove eventBody rows
      $("tr.eventBody").remove(); 

      // Replace eventBody rows in the proper place
      for(var i=0; i<dr_num.length; i++) {
        var rowId = dr_num[i];
        $('tr.eventHead[alt='+rowId+']').after(dr_htm[i]);
      }

      // Close button
      $('tr.eventBody img[alt=Close Detail]').click(function() {
        var rowId = $(this).attr('dat');
        $('tr.eventBody[alt='+rowId+']').css('display','none'); 
        $('tr.eventHead[alt='+rowId+']').removeClass('eventActive'); 
        // Reset the header click  function to 'open'
        $('tr.eventHead[alt='+rowId+']').unbind('click');
        bindOpen( $('tr.eventHead[alt='+rowId+']') );
      }); 

    }
  });
}


// Add tablesorter parser for our date format
$.tablesorter.addParser({ 
  // set a unique id 
  id: 'eventdate', 
  is: function(s) { 
    // return false so this parser is not auto detected 
    return false; 
  }, 
  format: function(s) { 
    // Disregard 'ending date', then use "usLongDate" processing
    if(s.indexOf(' - ') != -1) {
      // Fixes most multi-day events
      s = s.replace(/ - .+,/,','); 
      // Special case for year-spanning events
      if(s.lastIndexOf(',') > 6) {
        s = s.substr(0, s.lastIndexOf(',') );
      }
    }
    return $.tablesorter.formatFloat(new Date(s).getTime());
  }, 
  // set type, either numeric or text 
  type: 'numeric' 
});


// Add event handlers after ajax load
var bindBehaviors = function() {
  // Header row initial state
  $('tr.eventHead').click(function() {
    $(this).addClass('eventActive'); 
    var rowId = $(this).attr('alt');
    if($.browser.msie) {
      $('tr.eventBody[alt='+rowId+']').css('display','block');
    } else {
      $('tr.eventBody[alt='+rowId+']').css('display','table-row');
    };

    $(this).unbind('click');
    bindClose( $(this) );
  });

  // Hover on table row
  $('tr.eventHead').hover(function() {
    var rowId = $(this).attr('alt');
    $('tr.eventHead[alt='+rowId+']').addClass('eventOver');
  }, function() {
    var rowId = $(this).attr('alt');
    $('tr.eventHead[alt='+rowId+']').removeClass('eventOver');
  });
           
} 

// Reset the table header click function to 'close'
var bindClose = function(obj) {
    obj.click(function() {
      var rowId = $(this).attr('alt');
      $('tr.eventBody[alt='+rowId+']').css('display','none'); 
      $('tr.eventHead[alt='+rowId+']').removeClass('eventActive'); 

      obj.unbind('click');
      bindOpen( obj );
    }); 
};

// Reset the table header click function to 'open'
var bindOpen = function(obj) {
  obj.click(function() {
    obj.addClass('eventActive'); 
    var rowId = obj.attr('alt');
    if($.browser.msie) {
      $('tr.eventBody[alt='+rowId+']').css('display','block');
    } else {
      $('tr.eventBody[alt='+rowId+']').css('display','table-row');
    };

    obj.unbind('click');
    bindClose( obj );
  }); 
}


// Set the filter click function to 'close'
var bindFilterClose = function(oHead, oBody) {
  oHead.removeClass('closed');
  oHead.addClass('open');
  oBody.show();
  // Rebind for open
  oHead.click(function() {
    oHead.unbind('click');
    bindFilterOpen( oHead, oBody );
  }); 
};

// Set the filter click function to 'open'
var bindFilterOpen = function(oHead, oBody) {
  oHead.removeClass('open');
  oHead.addClass('closed');
  oBody.hide();
  // Rebind for close
  oHead.click(function() {
    oHead.unbind('click');
    bindFilterClose( oHead, oBody );
  }); 
}


// Display a string or simple array in an alert box
function dump_var( v ) {
  if(typeof v === 'string') {
    alert(v);
  } else {
    var txt='';
    for( var i in v ) {
      txt += '[' + i + '] = [' + v[i] + ']\n';
    }
    alert(txt);
  } 
} 

// Eliminate duplicate and blank entries from arrays, results alpha sorted
Array.prototype.unique = function()
{ 
  var mark = [];

  for(var i in this)
  { 
    // var indx = this[i]; --> if type does not matter 

    // create a unique index if type does matter
    var indx = this[i] + "_" + typeof(this[i]);
    
    // Eliminate duplicates or blanks
    if(mark[indx] || this[i] == "")
      delete this[i];
    else {
      mark[indx] = this[i]; 
    }
  }

  this.sort();

  // empty indexed entries are at the end of the array
  // shorten it [delete does not reduce array] 
  while(!this[this.length-1]) this.length--; 
}

// Count duplicate entries in array, return associative array
Array.prototype.duplicates = function()
{
  var arrResults = [];

  for(var i in this)
  {
    if( this[i] && (typeof(this[i]) != 'function') )
    {
      arrResults.length++;
      if(arrResults[this[i]]) {
        arrResults[this[i]]++;
      } else {
        arrResults[this[i]] = 1;
      }
    }
  } 
  return arrResults;
}

// Check a date to see if it's in the past. Returns 1 for valid date, -1 for past date
Date.prototype.compare = function(eDate)
{
  // Date format: 2008-06-20
  var yr = eDate.substr(0,4);
  var mo = eDate.substr(5,2);
  var da = eDate.substr(8,2);

  // Make sure we have all components
  if(!yr || !mo || !da)
      return -1;

  // Compare dates
  if(yr < this.getFullYear() || (yr == this.getFullYear() && mo < this.getMonth()+1) ||
    (yr == this.getFullYear() && mo == this.getMonth()+1 && da < this.getDate()))
    return -1;
  else
    return 1;
}

