$(document).ready(function() {
  initDayPickerButtons();
});

function initDayPickerButtons() {
  var now = new Date();
  var today = (now.getMonth()+1 + '/' + now.getDate() + '/' + now.getFullYear());  
  jQuery('ul.week-item').each(function () {
    var _holder = $(this);
    var _ajaxLinks = _holder.find('.day-picker-ajax-link');
    var _ajaxLinkIndex;
    
    // ajax content loaders
    _ajaxLinks.each(function (ind) {
      var _link = $(this);
      var _target;
      var _showtimesFor = $('#showtimes-for');
      
      if($(location).attr('href').indexOf('home.aspx') >= 0 || $(location).attr('pathname') == '/')
        _target = 'home-favorite-theatre-widget.aspx?showtime_date=' + _link.find('a').attr('showtime_date');
      else if($(location).attr('href').indexOf('movie-detail.aspx') >= 0) {
        if (_holder.parent().parent().attr('id') == 'div-get-tickets')
        {
          if (location.hash.length>0) 
            _target = 'MovieDetailGetTickets.aspx?node_id=' + getQuerystring('node_id') + '&showtime_date=' + (location.hash).substring(1) + '&search=' + getQuerystringFromAString('search',null,_link.find('a').attr('href'));                
          else if (location.href.indexOf('showtime_date')>-1)   
            _target = 'MovieDetailGetTickets.aspx?node_id=' + getQuerystring('node_id') + '&showtime_date=' + getQuerystring('showtime_date')+ '&search=' + getQuerystringFromAString('search',null,_link.find('a').attr('href'));                
          else
            _target = 'MovieDetailGetTickets.aspx' + _link.find('a').attr('href'); 
               
          _showtimesFor = $('#div-get-tickets #showtimes-for');
        }
        else
        {
          if (location.href.indexOf('showtime_date')==-1 && location.hash!='')   
            _target = 'MovieDetailFavorites.aspx?node_id=' + getQuerystring('node_id') + '&showtime_date=' + (location.hash).substring(1) + '&search=' + getQuerystringFromAString('search',null,_link.find('a').attr('href'));                
          else          
            _target = 'MovieDetailFavorites.aspx' + _link.find('a').attr('href');
          
          _showtimesFor  = $('#div-favorites #showtimes-for');
        }
      }
      else
      {
        if (location.href.indexOf('showtime_date')==-1 && location.hash!='') {  
          _target = 'theatre-showtimes.aspx?node_id=' + getQuerystring('node_id') + '&showtime_date=' + (location.hash).substring(1);
        } else {
          _target = 'theatre-showtimes.aspx' + _link.find('a').attr('href'); 
        }
      }

      if(ind == 0)
      {
        //this is where you look into _link.find('a').attr('href')
        //and find querystring of showtime_date, if it doesnt exists then use location.hash as the showtime_date        
        var _showtimeDate;
        if (location.hash.length>0) {
          _showtimeDate = (location.hash).substring(1);
        } else if (location.href.indexOf('showtime_date')==-1) {  
          _showtimeDate = today;
        } else {
         _showtimeDate = getQuerystring('showtime_date');
        }        
        
        if(_showtimeDate.length > 0 && isDate(_showtimeDate) != 'Invalid Date')
        {
          _showtimesFor.html(buildShowtimeDate(new Date(_showtimeDate).toLocaleDateString()));

          //Set correct day picker button to active
          _ajaxLinks.each(function (ind) {
            $(this).removeClass('active');
            
            if($(this).find('a').attr('showtime_date') == _showtimeDate)
            {
              $(this).addClass("active");
              return false;
            }
            
            if(ind == 7)
              $(this).addClass("active");
          });
          
        } else if ( $('#hshowtime_date').length > 0 && $('#hshowtime_date').val().length > 0) {
        
          //Set correct day picker button to active
          _ajaxLinks.each(function (ind) {
            $(this).removeClass('active');

            if( $(this).find('a').attr('showtime_date') == $('#hshowtime_date').val() )
            {
              $(this).addClass("active");
              return false;
            } else if(ind == 7) 
              $(this).addClass("active");

          });
          
          _showtimesFor.html(buildShowtimeDate(new Date($('#hshowtime_date').val()).toLocaleDateString()));  
  
        } else {
        _showtimesFor.html(buildShowtimeDate(_link.find('a').attr('id')));
        }
      }

      _link.click(function () {
        _ajaxLinks.each(function (ind) {
          $(this).removeClass('active');
        });
        
        $(this).addClass('active');
        
        if($(this).find('span').find('em').html() != 'MORE') { 
          
/*
          alert($('.clickhere').find('a').attr('href'));
          if ($('.clickhere').find('a').attr('href').indexOf('fandango.com/redirect.aspx')>0) {
            $('.clickhere').find('a').attr('href') + '&date=' + _showtimeDate; 
          }
*/          
          
         //redefine _target for movie detail only
          if($(location).attr('href').indexOf('movie-detail.aspx') >= 0) {
            if (_holder.parent().parent().attr('id') == 'div-get-tickets')
            {
              _target = 'MovieDetailGetTickets.aspx' + _link.find('a').attr('href'); 
              _showtimesFor = $('#div-get-tickets #showtimes-for');
            }
            else
            {
              _target = 'MovieDetailFavorites.aspx' + _link.find('a').attr('href');
              _showtimesFor  = $('#div-favorites #showtimes-for');
            }
          }            
          $.ajax({
              url: _target,
              success: function (msg) {
                var _divHolder;
                var _openers;
                
                if($(location).attr('href').indexOf('home.aspx') >= 0 || $(location).attr('pathname') == '/')
                  _divHolder = $('div.h');
                else if ($(location).attr('href').indexOf('movie-detail.aspx') >=0) {
                  if(_target.indexOf('GetTickets') >= 0)
                    _divHolder = $('#div-get-tickets-showtimes');
                  else
                    _divHolder = $('#div-favorites-showtimes');
                }
                else
                  _divHolder = $('div.showtime-results-holder');
                
                if($('#hidShowtimeDate').length > 0)

                  $('#hidShowtimeDate').val(_link.find('a').attr('showtime_date'));
                
                _showtimesFor.html(buildShowtimeDate(_link.find('a').attr('id')));
                
                location.hash = '#' + _link.find('a').attr('showtime_date');

                _divHolder.html(msg);
                _divHolder.show();
                
                _openers = jQuery('a.showtime-popup');
                initPopups(_openers);
              
              },
              error: function () {
                alert('AJAX Error!');
              }
          });
          return false;
        } //end if
      }); //end _link.click ?
      
      //begin test display showtimes using hash date   
      if(location.hash!='') {          
        $.ajax({
            url: _target,
            success: function (msg1) {
              var _divHolder;
              var _openers;
              
              if($(location).attr('href').indexOf('home.aspx') >= 0 || $(location).attr('pathname') == '/')
                _divHolder = $('div.h');
              else if ($(location).attr('href').indexOf('movie-detail.aspx') >=0) {
                if(_target.indexOf('GetTickets') >= 0)
                  _divHolder = $('#div-get-tickets-showtimes');
                else
                  _divHolder = $('#div-favorites-showtimes');
              }
              else
                _divHolder = $('div.showtime-results-holder');
              
              if($('#hidShowtimeDate').length > 0)
                $('#hidShowtimeDate').val(_link.find('a').attr('showtime_date'));
              
              //_showtimesFor.html(buildShowtimeDate(_link.find('a').attr('id')));
              _showtimesFor.html(buildShowtimeDate(new Date(_showtimeDate).toLocaleDateString()));
              
              _divHolder.html(msg1);
              _divHolder.show();
              
              _openers = jQuery('a.showtime-popup');
              initPopups(_openers);
            
            },
            error: function () {
              alert('AJAX Error!');
            }
          });
        return false;
      } 
      //end test      
    });
  });
}

function buildShowtimeDate(formattedShowtimeDate){
  if(formattedShowtimeDate != 'Invalid Date')
    return '<strong>Showtimes for:</strong>' + formattedShowtimeDate;
  else
    return formattedShowtimeDate;
}

function getQuerystring(key, default_)
{
  if (default_==null) default_="";
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  var qs = regex.exec(window.location.href);
  if(qs == null)
    return default_;
  else
    return qs[1];
}

function isDate(_date)
{
  var someDate = new Date(_date);
}

function getQuerystringFromAString(key, default_, _url_)
{
  if (default_==null) default_="";
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  var qs = regex.exec(_url_);
  if(qs == null)
    return default_;
  else
    return qs[1];
}
