var nextCal;
var prevCal;

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

function calendarClicks() {
    if(jQuery("#range-calendar").length == 0) return false;

    jQuery("#calendar-multi-days a").click(function() {
        var click = gup( 'c' );
        var href = jQuery(this).attr("href");
        if(click != '1') {
            var lastDay = jQuery("#range-calendar select[name$='lastDay']").val();
            var lastMonth = jQuery("#range-calendar select[name$='lastMonth']").val();
            href = href + "&lastDay=" + lastDay + "&lastMonth=" + lastMonth + "&c=1";
            window.location.href = href;
        } else {
            var firstDay = jQuery("#range-calendar select[name$='firstDay']").val();
            var firstMonth = jQuery("#range-calendar select[name$='firstMonth']").val();
            href = href.replace("firstDay", "lastDay");
            href = href + "&firstDay=" + firstDay + "&firstMonth=" + firstMonth;

            window.location.href = href;
        }
        return false;
    });
    return true;
}

function preloadCal() {
    var nextCalUrl = jQuery('#calendar-next').attr('href');
    if(typeof nextCalUrl != 'undefined') {
        nextCalUrl = nextCalUrl.substring(nextCalUrl.indexOf('?'),nextCalUrl.length);
        jQuery.get("calendar.html" + nextCalUrl, function( data ) {
            nextCal = data;
        });
        jQuery('#calendar-next').click(function() {
            jQuery('#calendar').html(nextCal);
            preloadCal();
            calendarClicks();
            return false;
        });
    }

    var prevCalUrl = jQuery('#calendar-prev').attr('href');
    if(typeof prevCalUrl != 'undefined') {
        prevCalUrl = prevCalUrl.substring(prevCalUrl.indexOf('?'),prevCalUrl.length);
        jQuery.get("calendar.html" + prevCalUrl, function( data ) {
            prevCal = data;
        });
        jQuery('#calendar-prev').click(function() {
            jQuery('#calendar').html(prevCal);
            preloadCal();
            calendarClicks();
            return false;
        });
    }


}

jQuery(document).ready(function() {
    jQuery('#search-calendar select').change(function() {
        jQuery('#search-calendar').submit();
    });
    jQuery('#search-calendar #filter-reset').click(function () {
        jQuery('#search-calendar select').find('option:first').attr('selected', 'selected').parent('select');
        jQuery('#search-calendar').submit();
    });

    preloadCal();
    calendarClicks();
    
});
