$(document).ready(function() {	
	var slug = "leave_calendar";
        
    // $('#loading-icon').ajaxStart(function() { $(this).show() });
    // $('#loading-icon').ajaxComplete(function() { $(this).hide() });
    
	//Show more events
	$(document).on('click', '.more_events', function() {
		var day 	= $(this).attr('id');
        $('.events_container').fadeOut(300);
		$('#dayof_' + day).fadeToggle(300);
	});
	
	//Hide more events on click
	$(document).on('click', '.close_events', function() {
		$('.events_container').fadeOut(300);
	});
	
	//Hide more events on esc
	$(document).keyup(function(e) {
		if (e.keyCode == 27) { $('.events_container').fadeOut(300); }
	});
    
    // hide more events on click elsewhere
    $(document).click(function(event) {
        if(!$(event.target).is('.more_events'))
            $('.events_container').fadeOut(300);
    });
    
	$(document).on('click', '.events_container', function(event) {
        event.stopPropagation();
    });

    $('.timepicker').timepicker(
    {
        ampm: true,
    	hourMin: 6,
    	hourMax: 19,
        stepMinute: 15
    });
    
    $('#event').bind('keyup keypress change', function()
    {   
        $('#leave_type').val('');
        $('#employee_id').val('');
    });
    $('#employee_id').change(function()
    {   
        $('#event').val('');
    });
    $('#leave_type').change(function()
    {   
        $('#event').val('');
    });
    
    
    $('#all_day').click(function()
    {
        if($(this).attr('checked'))
        {
            $('#start_time').val('Start');
            $('#end_time').val('End');
        }
    });
    
    $('#start_time').change(function()
    {
        if($(this).val() != 'Start') $('#all_day').removeAttr('checked');
    });
    
    $('#end_time').change(function()
    {
        if($(this).val() != 'End') $('#all_day').removeAttr('checked');
    });
    
    $('#blackout').change(function()
    {
        if($(this).attr('checked'))
        {
            $('.blackout_hide').hide();
        }
        else
        {
            $('.blackout_hide').show();
        }
    });
    
    $('#leave-calendar-form').submit(function(event)
    {
        event.preventDefault();
        
        var form_data = $(this).serializeArray();
        
        var error = '';
        if(!$('#blackout').attr('checked'))
        {
            for (var i=0; i < form_data.length; i++) 
            {
                var item = form_data[i];

                var has_error = false;
                if(item.value == '' && item.name != 'id' && (item.name != 'employee_id' && item.name != 'event'))
                {
                    if(item.name == 'leave_type' && $('#event').val() != '') continue;
                    error += '&bull; Please provide a value for the ' + titlecase(item.name.replace(/_/g, ' ')) + ' field.<br />';            
                }
                else if((item.name == 'start_time' && item.value == 'Start') || (item.name == 'end_time' && item.value == 'End'))
                {
                    has_error = false;
                
                    var all_day = $('#all_day').attr('checked');
                
                    if(!all_day) 
                    {
                        error += '&bull; Please provide a value for the ' + titlecase(item.name.replace(/_/g, ' ')) + ' field (or choose "All Day").<br />';                
                    }
                }
            };
            
            if($('#event').val() == '' && $('#employee_id').val() == '')
            {
                error += '&bull; Please choose an employee or provide an event name (but not both).<br />';                
            }
            
            if($('#event').val() != '' && $('#employee_id').val() != '')
            {
                error += '&bull; Please choose an employee <strong><em>or</em></strong> provide an event name (<strong>but not both</strong>).<br />';                
            }
            
            var start_date = new Date($('#leave_date').val());
            var end_date = new Date($('#leave_date_end').val());
            
            if(start_date > end_date)
            {
                error += '&bull; The end date cannot come before the start date!<br />';
            }
                        
            // check if that's a blackout day!
            var check_date = $('input[name="leave_date"]').val().replace(/\//g, '');
            if($('#' + check_date).hasClass('blackout_day'))
            {
                error += '&bull; You cannot add any leave time to a blackout day!<br />';
            }
        }
        else
        {
            if($('input[name="leave_date"]').val() == '')
            {
                error += '&bull; Please provide a date to un/blackout a date.<br />';                
            }
            
            var check_date = $('input[name="leave_date"]').val().replace(/\//g, '');
            if($('#' + check_date + ' strong').length > 0)
            {
                error += '&bull; You can\'t blackout a date with leave already added. Please change the leave time before adding the blackout date.<br />';
            }
        }
                        
        if(error != '')
        {
            $('.specific_errors').html(error);

			$("#leave-calendar-error").dialog(
			{
				modal: true,
				buttons: 
				{
					Ok: function() 
					{
						$(this).dialog("close");
					}
				},
                width: 600
            });
			return;            
        }
        
        if(!$('#blackout').attr('checked'))
        {
            $.ajax({
                url: '/index.php?action=' + slug + '_submit_leave_time',
                type: 'POST',
                data: form_data,
                success: function(response)
                {
                    if(response == 'success')
                    {
                        refresh_calendar();
                        clear_form();
                    }
                }
            });
        }
        else
        {
            $.ajax({
                url: '/index.php?action=' + slug + '_submit_blackout',
                type: 'POST',
                data: { blackout_date: $('input[name="leave_date"]').val() },
                success: function(response)
                {
                    if(response == 'success')
                    {
                        refresh_calendar();
                        clear_form();
                    }
                }
            });
        }
    });
    
	$(document).on('click', '.edit_event', function(event)
    {
        event.preventDefault();
        
        if($('#blackout').attr('checked'))
        {
            $('.specific_errors').html('&bull; Please uncheck "Add/Remove Blackout Dates" before attempting to edit an entry.');

			$("#leave-calendar-error").dialog(
			{
				modal: true,
				buttons: 
				{
					Ok: function() 
					{
						$(this).dialog("close");
					}
				},
                width: 600
            });
			return;            
        }
        
        $('.edit_message').show();
        $('.not_edit_message').hide();
        
        var id = $(this).attr('href').replace('#', '');
        
        $('.delete_entry').attr('id', 'id_' + id);
        
        $.ajax({
            url: '/index.php?action=' + slug + '_ajax_fetch_event',
            data: {id: id},
            type: 'POST',
            dataType: 'json',
            success: function(response)
            {
                $('#all_day').removeAttr('checked');
                $.each(response, function(name, value)
                {
                    if((name == 'start_time' ||  name == 'end_time') && value == 'all_day')
                    {
                        $('#all_day').attr('checked', 'checked');
                        $('[name="' + name + '"]').val(titlecase(name.replace('_time', '')));
                        return true; // $.each equivalent of continue
                    }
                    
                    $('[name="' + name + '"]').val(value);
                });
            }
        });
    });
    
	$(document).on('click', '.delete_entry', function(event)
    {
        event.preventDefault();
        
        var id = $(this).attr('id').replace('id_', '');
        
        $.ajax({
            url: '/index.php?action=' + slug + '_delete_entry',
            type: 'POST',
            data: {id: id},
            success: function(response)
            {
                if(response == 'success')
                {
                    refresh_calendar();
                    clear_form();
                }
            }
        });
    
    });
    
    $('a[href="#reset-form"]').click(function(event)
    {
        event.preventDefault();
        clear_form();
    });
});

function refresh_calendar()
{
    $('#loading-icon').show();
    $('#calendar-refresh').load(window.location.pathname + ' #calendar-refresh', function() { $('#loading-icon').hide(); });
}

function clear_form()
{
    $('.edit_message').hide();
    $('.not_edit_message').show();
    $('#leave-calendar-form input, #leave-calendar-form select').each(function()
    {
        if($(this).attr('name') == 'all_day') $(this).removeAttr('checked');
        else if($(this).attr('name') == 'start_time' || $(this).attr('name') == 'end_time') $(this).val(titlecase($(this).attr('name').replace('_time', '')));
        else $(this).val('');
    });
}

/*
 * Convert HTML elements titlecase with jQuery 
 * (jQuery plugin version of http://individed.com/code/to-title-case/js/to-title-case.js)
 */
jQuery.fn.titlecase = function() {
    return this.each(function() {
        var newText = jQuery(this).text().replace(/([\w&`'‘’"“.@:\/\{\(\[<>_]+-? *)/g,
        function(match, p1, index, title) {
            if (index > 0 && title.charAt(index - 2) !== ":" && match.search(/^(a(nd?|s|t)?|b(ut|y)|en|for|i[fn]|o[fnr]|t(he|o)|vs?\.?|via)[ \-]/i) > -1) return match.toLowerCase();
            if (title.substring(index - 1, index + 1).search(/['"_{(\[]/) > -1) return match.charAt(0) + match.charAt(1).toUpperCase() + match.substr(2);
            if (match.substr(1).search(/[A-Z]+|&|[\w]+[._][\w]+/) > -1 || title.substring(index - 1, index + 1).search(/[\])}]/) > -1) return match;
            return match.charAt(0).toUpperCase() + match.substr(1);
        });
        jQuery(this).text(newText)
    });
};

function titlecase(text)
{
    var newText = text.replace(/([\w&`'‘’"“.@:\/\{\(\[<>_]+-? *)/g,
    function(match, p1, index, title) {
        if (index > 0 && title.charAt(index - 2) !== ":" && match.search(/^(a(nd?|s|t)?|b(ut|y)|en|for|i[fn]|o[fnr]|t(he|o)|vs?\.?|via)[ \-]/i) > -1) return match.toLowerCase();
        if (title.substring(index - 1, index + 1).search(/['"_{(\[]/) > -1) return match.charAt(0) + match.charAt(1).toUpperCase() + match.substr(2);
        if (match.substr(1).search(/[A-Z]+|&|[\w]+[._][\w]+/) > -1 || title.substring(index - 1, index + 1).search(/[\])}]/) > -1) return match;
        return match.charAt(0).toUpperCase() + match.substr(1);
    });
    
    return newText;
}
