//Calendar/Dates controls setup



function setAllDayEvent(){

    if ($('alldayevent').checked) {
        $('endDateDate').value = $('startDateDate').value;
        $('startDateTime').selectedIndex = 0;
        $('endDateTime').selectedIndex = $('endDateTime').options.length - 1;
    }
	
}

//Ensures the allday event check is handled correctly when the date is changed
function startDateChanged(){
    if ($('alldayevent').checked) {
        $('alldayevent').checked = false;
    }
    var startDateD = Date.parseDate($('startDateDate').value + ' ' + $('startDateTime').value, 'm/d/Y H:i');
    var endDateD = Date.parseDate($('endDateDate').value + ' ' + $('endDateTime').value, 'm/d/Y H:i');
    if (startDateD > endDateD) {
        $('endDateDate').value = $('startDateDate').value;
        $('endDateTime').selectedIndex = $('startDateTime').selectedIndex;
    }
    var recurrenceEndsD = Date.parseDate($('recurrenceEnds').value + ' 23:59', 'm/d/Y H:i');
    if (endDateD > recurrenceEndsD) {
        $('recurrenceEnds').value = $('endDateDate').value;
    }
}

function endDateChanged(){
    if ($('alldayevent').checked) {
        $('alldayevent').checked = false;
    }
    var startDateD = Date.parseDate($('startDateDate').value + ' ' + $('startDateTime').value, 'm/d/Y H:i');
    var endDateD = Date.parseDate($('endDateDate').value + ' ' + $('endDateTime').value, 'm/d/Y H:i');
    if (startDateD > endDateD) {
        $('startDateDate').value = $('endDateDate').value;
        $('startDateTime').selectedIndex = $('endDateTime').selectedIndex;
    }
    var recurrenceEndsD = Date.parseDate($('recurrenceEnds').value + ' 23:59', 'm/d/Y H:i');
    if (endDateD > recurrenceEndsD) {
        $('recurrenceEnds').value = $('endDateDate').value;
    }
}

Ext.get('startDateDate').on('change', startDateChanged);
Ext.get('startDateTime').on('change', startDateChanged);
Ext.get('endDateDate').on('change', endDateChanged);
Ext.get('endDateTime').on('change', endDateChanged);
Ext.get('alldayevent').on('change', setAllDayEvent);

//Recurrence controls
function recurrenceHasChanged(){
    $('dailyRecurrence').hide();
    $('weeklyRecurrence').hide();
    $('monthlyRecurrence').hide();
    $('recurrenceEnds').hide();
    if ($('recursNever').checked) {
        $('recurrence').hide();
    }
    else 
        if ($('recursDaily').checked) {
            $('dailyRecurrence').show();
            $('recurrence').show();
            $('recurrenceEnds').show();
        }
        else 
            if ($('recursWeekly').checked) {
                $('weeklyRecurrence').show();
                $('recurrence').show();
                $('recurrenceEnds').show();
            }
            else 
                if ($('recursMonthly').checked) {
                    $('monthlyRecurrence').show();
                    $('recurrence').show();
                    $('recurrenceEnds').show();
                }
    
}

recurrenceHasChanged();

Calendar.setup({
    electric : false,
    inputField: "startDateDate", // ID of the input field
    ifFormat: "%m/%d/%Y", // the date format
    button: "startDateCal", // ID of the button
    onUpdate: startDateChanged
});

Calendar.setup({
    electric : false,
    inputField: "endDateDate", // ID of the input field
    ifFormat: "%m/%d/%Y", // the date format
    button: "endDateCal", // ID of the button
    onUpdate: endDateChanged
});

Calendar.setup({
    electric : false,
    inputField: "recurrenceEnds", // ID of the input field
    ifFormat: "%m/%d/%Y", // the date format
    button: "recurrenceEndsCal" // ID of the button
});

//Categories controls

var showAllCategories;

function showCategoriesBox(){

    var keyword = $('keywordBox').value;
    
    //Cleaning all the old categories before repulling them
    $('categoriesBox').update('<h3>Calendars: (All)</h3><br/>Loading...');
    showAllCategories = true;
    StructureAjax.getCategoriesTree('Event', "(?i).*" + keyword + ".*", loadCategoriesCallback);
    
    $('categoriesBox').show({
        duration: .4
    });
}

function hideCategoriesBox(){
    var categoriesBox = $('categoriesBox');
    categoriesBox.hide({
        duration: .4
    });
}

function loadAllCategories(){
    var keyword = $('keywordBox').value;
    
    //Cleaning all the old categories before repulling them
    $('categoriesBox').update('Loading...');
    showAllCategories = true;
    StructureAjax.getCategoriesTree('Event', "(?i).*" + keyword + ".*", loadCategoriesCallback);
    
}



function loadCategoriesCallback(data){

    var keyword = $('keywordBox').value;
    
    var lastLevel = 0;
    var currentLevel = 0;
    var secondLevelCount = 0;
    var showAllShowed = false;
    var strHTML = '<a href="javascript: hideCategoriesBox();" style="float:right; text-decoration:none;">' + 
                  '<img src="/calendar/images/btn_close.gif" alt="Close"/>' +
		'</a>';

    for (var i = 0; i < data.length; i++) {
        var cat = data[i];
        currentLevel = cat.categoryLevel;
        if (lastLevel > currentLevel) 
            strHTML += '</ul>';
        if (currentLevel > lastLevel) {
            strHTML += '<ul>';
        }
        if (currentLevel == 0) {
            secondLevelCount = 0;
            showAllShowed = false;
            strHTML += '<h3>' + cat.categoryOrigName + ':'
            if (countLevelCategories(data, i + 1, 1) > 10 && !showAllCategories) 
                strHTML += ' (<a href="javascript: loadAllCategories(' + cat.inode + ')">all</a>)' +
                '</h3>';
            else 
                strHTML += '</h3>';
            
            if (countLevelCategories(data, i + 1, 1) == 0) 
                strHTML += '<ul><li>No Match Found</li></ul>';
            
        }
        else 
            if (currentLevel > 0) {
                secondLevelCount++;
                if (showAllCategories || secondLevelCount <= 10) {
                
                    var catClass = "";
                    if (keyword != "" && cat.categoryOrigName.toLowerCase().indexOf(keyword.toLowerCase()) > -1) 
                        catClass = "category_higlighted";
                    
                    strHTML += '<li>' +
                    '	<a href="javascript: addCategory(' +
                    cat.inode +
                    ', \'' +
                    cat.categoryOrigName +
                    '\')">' +
                    cat.categoryOrigName +
                    '</a>' +
                    '</li>';
                }
                else 
                    if (!showAllCategories && secondLevelCount > 10 && !showAllShowed) {
                        strHTML += '<li>...</li>';
                        showAllShowed = true;
                    }
            }
        lastLevel = currentLevel;
    }
    strHTML += '</ul>';
    $('categoriesBox').update(strHTML);
}

function countLevelCategories(data, startIndex, level){
    var count = 0;
    for (var i = startIndex; i < data.length; i++) {
        var cat = data[i];
        if (cat.categoryLevel != level) 
            break;
        count++;
    }
    return count;
}

function addCategory(catInode, catLabel){
    var catsBox = $('selectedCategoriesBox');
    var strHTML = '<div id="category' + catInode + 'Box">' +
    	'<a href="javascript: removeCategory(\'' + catInode + '\');" id="removeCat' + catInode + '">' +
    	'	<img src="/calendar/images/btn_close.gif" alt="close" class="close" style="float:right;">' +
    	'</a>' +
    	'<label for="cat' +	catInode + '">' + catLabel.truncate(40) + '</label>' +
    	'<input type="hidden" name="categories" id="cat' + catInode + '" value="' + catInode + '"/>' +
    	'<input type="hidden" name="categoryNames" id="catLabel' + catInode + '" value="' + catLabel + '"/>' +
    	'<br/></div>';
    catsBox.update(catsBox.innerHTML + strHTML);
    hideCategoriesBox();
    $('keywordBox').value = '';
}

function removeCategory(catInode){
    $('category' + catInode + 'Box').remove();
}

function initializeCategories(){

    var keywordBox = $("keywordBox");
    keywordBox.observe("keyup", keywordsCheckKeys);
    
    var showCategoriesButton = $("showCategoriesButton");
    showCategoriesButton.observe("click", showCategoriesBox);
    
    
}

function keywordsCheckKeys(event){
    if ($('keywordBox').value.length == 0) {
        hideCategoriesBox();
    }
    else 
        if ($('keywordBox').value.length >= 3 || event.keyCode == 8) {
            showCategoriesBox();
        }
}

initializeCategories();

//Locations and maps management

function suggestLocations(){
    var currentValue = $F('location');
    if (currentValue.length > 1) {
        CalendarAjax.findLocations(currentValue, suggestLocationsCallback);
    }
    else 
        if (currentValue.length == 0) {
            Ext.get('locationSuggestions').hide({
                duration: .4
            });
        }
    showMapLink();
}

function showAllLocations(){
    CalendarAjax.findLocations('', suggestLocationsCallback);
}

var buildingsCache = new Array();
var facilitiesCache = new Array();

function suggestLocationsCallback(buildings){
    if (buildings.length > 0) {
        $('locationSuggestions').update('');
        var htmlBuffer = "<a href='javascript: hideLocationSuggestions();' style='float:right; text-decoration:none;'/><img src='/calendar/images/btn_close.gif' alt='Close'/></a>";
        for (var i = 0; i < buildings.length; i++) {
            var building = buildings[i];
            buildingsCache[building.identifier] = building;
            htmlBuffer += '<a href=\"javascript: setBuilding(' + building.identifier + ');\">' + building.title + '</a><br/>';
            var facilities = building.facilities;
            for (var j = 0; j < facilities.length; j++) {
                var facility = facilities[j];
                facilitiesCache[facility.identifier] = facility;
                htmlBuffer += '&nbsp;&nbsp;&nbsp;- <a href=\"javascript: setFacility(' + building.identifier + ', ' + facility.identifier + ');\">' + facility.title + '</a><br/>';
            }           
        }

        htmlBuffer += "<br/>";

        $('locationSuggestions').update(htmlBuffer);
        Ext.get('locationSuggestions').show({
            duration: .4
        });
    }
    else {
        Ext.get('locationSuggestions').hide({
            duration: .4
        });
    }
}

Ext.get('location').on('keyup', suggestLocations);

function setBuilding(id){
    var building = buildingsCache[id];
    $('location').value = building.title + " @ " + building.address;
    Ext.get('locationSuggestions').hide({
        duration: .4
    });
    showMapLink();
}

function setFacility(buildingId, facilityId){
    var building = buildingsCache[buildingId];
    var facility = facilitiesCache[facilityId];
    var fieldValue = building.title + ", " + facility.title;
    if (facility.roomId != null) 
        fieldValue += ", Room " + facility.roomId;
    fieldValue += " @ " + building.address;
    $('location').value = fieldValue;
    Ext.get('locationSuggestions').hide({
        duration: .4
    });
    showMapLink();
}

function hideLocationSuggestions(){
    Ext.get('locationSuggestions').hide({
        duration: .4
    });
}


var mapAddress = "";
function showMapLink(){
    var currentValue = $F('location');
    var address = '';
    if (currentValue.indexOf("@") > -1) {
        var arr = currentValue.split("@");
        if (arr.length == 2) {
            address = arr[1];
            currentFullLocation = arr[0] + "<br/>" + arr[1];
        }
    }
    else 
        if (currentValue.length > 0) {
            address = currentValue;
            currentFullLocation = currentValue;
        }
    if (address != '') {
        $('locationMapLink').show({
            duration: .4
        });
    }
    else {
        $('locationMapLink').hide();
    }
    mapAddress = address;
}

function showMap(){
    var url = 'http://maps.google.com/maps?f=q&hl=en&geocode=&sll=37.0625,-95.677068&sspn=50.244827,82.265625&ie=UTF8&z=17&iwloc=addr&om=0&q=' + mapAddress;
    window.open(url);
}

//Global functions
function checkEscapeKey(jsevent){
    if (jsevent.keyCode == 27) {
        hideCategoriesBox();
		hideLocationSuggestions();
		$('suggestedTagsDiv').hide();
    }
}

Ext.get(document).on("keyup", checkEscapeKey);

function submitEvent () {
	$('addCalendarEvent').submit();
}

function cancelSubmit () {
	if(confirm("Are you sure?"))
		window.location = '/calendar';
}


