var API_DOMAIN = 'http://visit-fortwilliam.co.uk';

var API_CONTROLS = API_DOMAIN + '/API_events/API_events_controls.php?jsoncallback=?';
var API_RESULTS  = API_DOMAIN + '/API_events/API_events_results.php?jsoncallback=?';

if (typeof(lcms_api.client_id) == "undefined" || lcms_api.client_id == '' || lcms_api.client_id == undefined || lcms_api.client_id == null) {
    document.write('This script is not properly installed. Cannot continue without a CLIENT_ID.');
} else {
    document.write('<div id="eventsWrapper"></div>');
}

if (typeof(lcms_api.data_scope) == "undefined") {
    lcms_api.data_scope = 'client';
}

$(document).ready(function() {
    
    // If events div is present then load them up
    if ($("#eventsWrapper").length > 0) {
    
        $.getJSON(API_CONTROLS, {}, function(data){
            $("#eventsWrapper").html(data.html);
            Events_searchHandler();
        });
    }
        
});


function Events_searchHandler() {
    $("#doSearch").click(function() {
        $(this).blur();
        Events_DoSearch('months');
    });
    
    $("#doFutureSearch").click(function() {
        $(this).blur();
        Events_DoSearch('future');
    });
    
    Events_DoSearch('future');
}

function Events_eventHandler() {
    $(".showDetail").click(function() {
        var eventItem = $(this).closest(".event_item");
        eventItem.find(".previewContent").hide('medium', function(){
            eventItem.find(".detailedContent").show('medium');
        });
        return false;
    });

}

function Events_DoSearch(searchType) {
    $("#searchResults").fadeOut('fast');
    
    var goBtnLabel = $(".searchButton").attr('value');
    $(".searchButton").attr('disabled', 'disabled');
    $(".searchButton").attr('value', 'Searching Events...');
    
    var data = new Object();
    data.providerId = lcms_api.client_id;
    data.dataScope = lcms_api.data_scope;
    
    if (searchType == 'months') {
        data.month = $("#monthCombo").val();
        data.year = $("#yearCombo").val();
        
    } else if (searchType == 'future') {
        data.futureMonths = $("#futureMonthsCombo").val();
    }
    
    $.getJSON(API_RESULTS, data, function(data) {
        $(".searchButton").removeAttr('disabled');
        $(".searchButton").attr('value', goBtnLabel);
        $("#searchResults").html(data.html);
        $("#searchResults").fadeIn('normal');
        Events_eventHandler();
    });
    return false;
}