// the width of a day in list (amount to move by)
var day_width = 27;

var day_pos_min = 0;

// the width of a month (amount to move by)
var month_width = 44;
var month_pos_min = 0;

$(document).ready(function(){
  // set the number of months
  month_pos_min = ($('#monthList').children().size() - 12) * -month_width;
  
  // change city dialog
  $('#citySelectPop').dialog({
    autoOpen: false,
    title: "Select a New City",
    resizable: true,
    width: 475,
    height: 200,
    modal: true,
    buttons: {
      Cancel: function(){
        $(this).dialog('close');
      },
      OK: function(){
        
        // console.log('>>' + $('#newCity_select option:selected').text() + ', ' + $('#newRegion_select option:selected').text() + ', ' + $('#newCountry option:selected').text());
        
        if($('#newCountry_city_id').val() != '')
        {
          var calendar_city_text = $('#newCountry_city_id option:selected').text() + ', ' + $('#newCountry_region_id option:selected').text() + ', ' + $('#newCountry option:selected').text();
          var calendar_city_id = $('#newCountry_city_id').val();
          // set the text and the cookie
          $('#city').html(calendar_city_text);
          $.cookie('calendar_city_display',calendar_city_text);
          
          // set hidden values
          $('#city_id').val(calendar_city_id);
          $.cookie('calendar_city',calendar_city_id);
          
          // clear lat / lng vals
          $('#city_lat').val('');
          $('#city_lng').val('');
          
          // run search
          getEvents();
        }
        
        // close dialog
        $(this).dialog('close');
      }
    }
  });
  
  // loading dialog
  $('#loadingPop').dialog({
    autoOpen: false,
    title: 'Loading...',
    width: 200,
    height: 0,
    modal: true,
    resizable: false
  });
  
  // change category
  $('#event_parent_type_id').change(getEvents);
  
  // change page size
  $('#page_size').change(getEvents);
  
  // change city butt
  $('#changeCityButt').click(function(){
    
    $('#citySelectPop').dialog('open');
    
  });
  
  // clear search button
  $('#resetButt').click(clearSearch);
  
  // day panel controllers
  $('#dayControlLeft').click(dayListUp);
  $('#dayControlRight').click(dayListDown);
  
  // month panel controllers
  $('#monthControlLeft').click(monthListUp);
  $('#monthControlRight').click(monthListDown);
  
  // add month click listener
  $('#monthList li').click(monthClick);
  
  // fire getEvent on range change
  $('select.rangeSelect').change(getEvents);
  
  // add search button listener
  $('#searchButt').click(getEvents);
  
  // add search field listener
  $("#searchInput").keydown(function(e){
    if (e.keyCode == 13) { // ENTER key clicked?
      getEvents();
    }
  });

  
  // check if we have a calendar city set
  if($.cookie('calendar_city') == null)
  {
    /**
     * get location of user
     */
    $.getScript('http://j.maxmind.com/app/geoip.js',function(){
    
      // console.log(geoip_city());
      
       // function geoip_country_code() { return 'CA'; }
       // function geoip_country_name() { return 'Canada'; }
       // function geoip_city()         { return 'Vancouver'; }
       // function geoip_region()       { return 'BC'; }
       // function geoip_region_name()  { return 'British Columbia'; }
       // function geoip_latitude()     { return '49.2500'; }
       // function geoip_longitude()    { return '-123.1333'; }
       // function geoip_postal_code()  { return ''; }
      
      $('#city').html(geoip_city() + ', ' + geoip_region() + ', ' + geoip_country_name());
      
      var geo_lat = geoip_latitude();
      var geo_lng = geoip_longitude();
      
      // set hidden lat and lng vals, clear db location refs
      $('#city_lat').val(geo_lat);
      $('#city_lng').val(geo_lng);
      $('#city_id').val('');
      
      // attempt to get the closest city from the geocoded location
      $.getJSON(
        'calendar/getClosestCity',
        {
          'city_lat' : geo_lat,
          'city_lng' : geo_lng
        },
        // set the city data if successful
        function(city_data) {
          //console.log(city_data[0].lat + ' ' + city_data[0].lng + ' ' + city_data[0].id);
          
          // unset the lat and lng
          $('#city_lat').val('');
          $('#city_lng').val('');
          
          // set the city id
          $('#city_id').val(city_data[0].id);
        }
      );
      
      getMonth('','');
    
    });
  }
  else
  {
    $('#city').html($.cookie('calendar_city_display'));
    
    // set hidden values
    $('#city_id').val($.cookie('calendar_city'));
    
    // clear lat / lng vals
    $('#city_lat').val('');
    $('#city_lng').val('');
    
    getMonth('','');
  }
});

/**
 * json request to get current month and number of days
 */
function getMonth(month_num, year_num)
{
  // console.log('requested month number: ' + month_num);
  
  // get days in month
  $.getJSON(
    '/calendar/getMonth',
    {
      'month': month_num,
      'year': year_num,
      'city_id': $('#city_id').val(),
      'city_lat': $('#city_lat').val(),
      'city_lng': $('#city_lng').val()
    },
    function(month_data){
      
      // highlight month
      $('#monthList li').removeClass('active');
      $('#monthList li.' + month_data.year + '_' + month_data.month).addClass('active');
      
      // set position min for day slider
      day_pos_min = (month_data.num_days - 19) * -day_width;
      
      // clear day list and range selectors
      $('#dayList').empty();
      $('#start_day').html();
      $('#end_day').html();
      
      // get array of days containing events
      var event_days = month_data.event_days;
      
      // add new days
      for(var i = 1; i <= month_data.num_days; i++)
      {
        $('#dayList').append('<li>'+i+'</li>');
        
        // add full class if day contains events
        if(event_days[i])
        {
          $('#dayList li:last').addClass('full');
        }
        
        $('#start_day').append('<option value="'+i+'">'+i+'</option>');
        
        $('#end_day').append('<option value="'+i+'">'+i+'</option>');
      }
      
      // select last day in range selector if no month set (page first load)
      if(month_num == '')
      {
        $('#end_day option:last').attr('selected', true)
      }
      
      // add onlick functionality to days
      $('#dayList li').bind('click', dayClick);
      
      // set width of list
      $('#dayList').css('width', month_data.num_days * 27);
      
      getEvents();
    }
  );
}

/**
 * handle month click 
 */
function monthClick(e)
{
  // reset range filters
  //resetRange();
  
  // get month
  getMonth($(this).children('.month_num').html(), $(this).children('.year').html());
}

/**
 * handle day click event
 */
function dayClick(e)
{
  // console.log($(this).html());
  
  // set day in range drop down
  $('#start_day').val($(this).html());
  $('#end_day').val($(this).html());
  
  // get events
  getEvents();
}

/**
 * move day list up
 */
function dayListUp()
{
  // get position
  var pos = $('#dayList').position();
  
  // check can move
  if(pos.left < 0)
  {
    $('#dayList').css({
      left: function(index, value){
        return (pos.left + day_width) + 'px';
      }
    });
  }
}

/**
 * move day list down
 */
function dayListDown()
{
  // get position
  var pos = $('#dayList').position();
  
  // check can move
  if(pos.left > day_pos_min)
  {
    $('#dayList').css({
      left: function(index, value){
        return (pos.left - day_width) + 'px';
      }
    });
  }
}


/**
 * move month list down
 */
function monthListDown()
{
  // get position
  var pos = $('#monthList').position();
  
  // check can move
  if(pos.left > month_pos_min)
  {
    $('#monthList').css({
      left: function(index, value){
        return (pos.left - month_width) + 'px';
      }
    });
  }
}

/**
 * move month list up
 */
function monthListUp()
{
  // get position
  var pos = $('#monthList').position();
  
  // check can move
  if(pos.left < 0)
  {
    $('#monthList').css({
      left: function(index, value){
        return (pos.left + month_width) + 'px';
      }
    });
  }
}

/**
 * change the page
 */
function changePage(page)
{
  $('#page').val(page);
  
  getEvents();
}

/**
 * clear the search:
 * - reset page_size to 5
 * - show all categories
 * - set range to entire current month
 */
function clearSearch()
{
  $('#event_parent_type_id').val(0);
  $('#page_size').val(5);
  resetRange();
  
  getEvents();
}

/**
 * reset range to whole month
 */
function resetRange()
{
  $('#start_day').val(1);
  
  $('#end_day').val($('#dayList li').length);
}

/**
 * make events call
 */
function getEvents()
{
  // show loading notify
  $('#loadingPop').dialog('open');
  
  // get events in month
  var range = new Object();

  // set month var
  range.month = $('#monthList li.active .month_num').html();
  range.year  = $('#monthList li.active .year').html();
  
  // console.log('events range month: ' + range.month);
  
  range.start_day = $('#start_day').val();
  range.end_day = $('#end_day').val();
  
  // retrieve the name to search for
  var search_name =  $('#searchInput').val() == 'type here to search by name' ?  '' : $('#searchInput').val(); 
  
  // call
  $.get(
    '/calendar/getEvents',
    {
      'range': range,
      'page_size': $('#page_size').val(),
      'event_parent_type_id': $('#event_parent_type_id').val(),
      'page': $('#page').val(),
      'city_id': $('#city_id').val(),
      'city_lat': $('#city_lat').val(),
      'city_lng': $('#city_lng').val(),
      'name': search_name
    },
    function(data){

      $('#resultsWrap').html(data);
      
      // hide loading notify
      $('#loadingPop').dialog('close');

    },
    'html'
  );
  
  // highlight range
  $('#dayList li').removeClass('selected');
  
  for(var i = range.start_day; i <= range.end_day; i++)
  {
    $('#dayList li:eq('+(i - 1)+')').addClass('selected');
  };
}


