$(function () {
	$('.enable-javascript').show();

    $("input#Date, input#InactiveDate, input#InvoiceDate").datepicker({ maxDate: '+0d' });

    $("input#CityName").autocomplete({
        source: "/City/Autocomplete",
        minLength: 2
    });
    
    $("input#EmployeeName, input#Assigned, input#UserFullName, input#UserName").autocomplete({
        source: "/User/Autocomplete",
        minLength: 2
    });

    $("input#ServiceCenterName").autocomplete({
    	source: "/VehicleService/ServiceCenterNameAutocomplete",
    	minLength: 2
    });
    
    $("form select#Year").change(function () {
    	var year = $(this).val();
	    var months = availableLogYearMonths[year];
	    var options = '<option>Select Month</option>';
	    if (months != undefined) {
		    for (var i = 0; i < months.length; i++) {
			    options += '<option>' + months[i] + '</option>';
		    }
	    }
	    $("form select#Month").html(options);
    });
    
    $("input#ModelYear,input#Price,input#VehicleId,input#EndOdometer,input#GasPurchased").numeric();
    
    $(".report-miles").append('&nbsp;<span class="muted"><i class="fa fa-caret-down"></i></span>').each(function () {
        var content = $(this).next('.report-calculation');
        $(this).qtip({
            content: content,
            hide: {
                fixed: true,
                delay: 1000
            },
            style: {
                width: 520,
                classes: "qtip-light"
            },
            position: {
                my: "top right",
                at: "bottom left"
            },
        });
    });

    // add popup for span titles
    $('span[title]').append('&nbsp;<span class="muted"><i class="fa fa-caret-down"></i></span>').qtip({
        content: {
            text: false // Use each elements title attribute
        },
        style: { classes: "qtip-light" } // Give it some style
    });

	$(".miles-unknown").addClass('label label-warning').append('&nbsp;<span class="muted"><i class="fa fa-caret-down"></i></span>')
        .each(function () {
            $(this).qtip({
                content: "No previous log for this vehicle",
                style: {
                    classes: "qtip-red"
                }
            });
        });
});

// add recent logs to a div if it exists
$(function () {
	var $recentLogs = $("#RecentLogs");
	if ($recentLogs.length > 0) {
		$.ajax({
			url: "/CreateLog/RecentLogs",
			success: function (data) {
				$recentLogs.append(data);
			}
		});
	}
});

/**
Ability to run the defered promises in sequence
*/
(function ($) {
	"use strict";
	var copy = function (a) {
		return Array.prototype.slice.call(a);
	};

	/**
        Handle a sequence of methods, stopping on failure by default
        @param Array<Function> chain    List of methods to execute.  Non-deferred return values will be treated as successful deferreds.
        @param Boolean  continueOnFailure   Continue executing even if one of the returned deferreds fails.
        @returns Deferred
     */
	$.sequence = function (chain, continueOnFailure) {
		var handleStep, handleResult,
            steps = copy(chain),
            def = new $.Deferred(),
            defs = [],
            results = [];
		handleStep = function () {
			if (!steps.length) {
				def.resolveWith(defs, [results]);
				return;
			}
			var step = steps.shift(),
                result = step; // used to be step();, but we're already dealing with promises
			handleResult(
                $.when(result).always(function () {
                	defs.push(this);
                }).done(function () {
                	results.push({ resolved: copy(arguments) });
                }).fail(function () {
                	results.push({ rejected: copy(arguments) });
                })
            );
		};
		handleResult = continueOnFailure ?
                function (result) {
                	result.always(function () {
                		handleStep();
                	});
                } :
                function (result) {
                	result.done(handleStep)
                        .fail(function () {
                        	def.rejectWith(defs, [results]);
                        });
                };
		handleStep();
		return def.promise();
	};
}(this.jQuery));

var matchCountFunc = function() {
	var $link = $(this);
	var url = $link.attr("matchcount");
	$link.append(' <span class="badge"><i class="fa fa-spinner fa-spin"></i></span>');
	return $.ajax({
		url: url,
		success: function (matchcount) {
			$('span', $link).remove();
			if (matchcount > 0) {
				$link.append(" <span class='badge badge-info'>" + matchcount + "</span>");
			} else {
				$link.append(" <span class='badge'>0</span>");
			}
			$link
				.append(' <sup><i class="fa fa-clone"></i></sup>');
		}
	});
};

// add get match count for all the current items
$(function () {
	var $requests = $("a[matchcount]").map(matchCountFunc);
	$.sequence($requests);
});

$(function() {
    // move checkbox elements into their labels
    $('label[for]').each(function() {
        var $label = $(this);
        var $for = $label.attr('for');
        if ($for.length > 0) {
            var $input = $('input#' + $for + ',input[name="' + $for + '"]');
            if ($input.filter(':checkbox').length > 0) {
                $input.prependTo($label);
                $label.addClass('checkbox');
            }
        }
    });
});

// Add active class to nav
$(function() {
	var idNavActiveRegex = {
        'log-nav': /\/log/i,
        'vehicle-nav': /\/vehicle|\/servicereminder|\/fuellog/i,
        'user-nav': /\/user/i,
		'config-nav': /\/City|\/Purpose/i,
		'account-nav': /\/Account/i
    };
	var set = false;
    $.each(idNavActiveRegex, function (id, regex) {
        if (regex.test(document.URL)) {
        	$("#" + id).addClass('active');
	        set = true;
        }
    });
    if (!set) {
    	$("#" + 'create-nav').addClass('active');
    }
});

function addButtonIcons () {
	var textToIcon = {
		'Enter Log': 'plus',
		'Edit': 'edit',
		'Filter': 'filter',
		'Details': 'info-circle',
		'Delete': 'trash',
		'Add': 'plus',
		'Export': 'download',
		'Import': 'upload',
		'Driver Mileage': 'user',
		'Vehicle Mileage': 'car',
		'Show Active': 'check-circle',
		'Show Inactive': 'ban',
		'Set Inactive' : 'ban',
		'Reactivate': 'check-circle',
		'Config': 'cog',
		'Cities': 'map',
		'Purposes': 'arrow-right',
		'Vehicle Service': 'wrench',
		'Vehicle': 'car',
		'Cost': 'money',
		'Reminder': 'clock-o',
		'Fuel Logs': 'tachometer',
		'Users': 'users',
		'Logs': 'road'
	};
	$.each(textToIcon, function(text, icon) {
		$("a:contains('" + text + "'):not(:has(i:first-child))")
            .prepend('<i class="fa fa-'+ icon +'"></i> ');
	});

	$(".navbar-inverse a[title='Manage']:not(:has(i))")
        .prepend('<i class="icon-user icon-white" /> ');
}


function addTargetBlankIcon() {
	$("a[target='_blank']:not(:has(i:last-child))")
        .append(' <sup><i class="fa fa-clone"></i></sup>');
}

$(function () {
	addButtonIcons();
	addTargetBlankIcon();
});

// Convert MVC3 WebGrid paging to Bootstrap
$(function() {
    var $paging = $('table.table tfoot tr td');

    var $currentPage =
        $paging.contents()
            .filter(function () { return this.nodeType == 3 && this.length != 1; });
    var $otherPages = $('a', $paging);

    if ($paging.length == 1 && $otherPages.length > 0) {
        $currentPage.wrap('<li class="active"><a href="#">');
        $otherPages.wrap('<li>');
        $('li', $paging).wrapAll('<div class="pagination"><ul>');
    }
});

// auto complete email address based on username
$(function () {
    $('.create-user input#FullName').keyup(function () {
        var fullName = $(this).val();
        var names = fullName.split(' '); ///[a-z().]+(\s+[a-z().]+)+/i.test(fullName)
        if (names.length > 1) {
            var username = names[0][0] + names[names.length - 1];
            username = username.toLowerCase();
            $('.create-user input#Username').val(username);
            $('.create-user input#Email').val(username + "@ethra.org");
        }
    });
    
    $('.create-user input#Username').keyup(function () {
        $('.create-user input#Email').val($(this).val() + "@ethra.org");
    });
});

$(function() {
    // add qtip
    $("a.qtip-modal").each(function () { bindQtipModal($(this)); });
    
    function bindQtipModal(element) {

        element.click(function() { return false; });

        element.append('&nbsp;<span class="muted"><i class="fa fa-caret-down"></i></span>');

        element.qtip({
            content: {
                ajax: {
                    url: element.attr('href')
                },
                text: "<p class=\"loading\">...</p>"
            },
            hide: {
                fixed: true,
                delay: 500
            },
            style: {
                classes: 'qtip-light qtip-shadow',
                width: 300
            },
            position: {
                viewport: $(window)
            }
        });
    }
	
    $('.qtip-show-next-div').each(function () {
    	$(this).qtip({
    		content: {
    			text: $(this).next('div')
    		},
    		hide: {
    			fixed: true,
    			delay: 500
    		},
    		style: {
    			classes: 'qtip-light qtip-shadow qtip-override',
    			width: false
    		},
    		position: {
    			my: 'top left',  // Position my top left...
    			at: 'bottom left', // at the bottom right of...
    		}
    	});
    });
});

/*
 * Form Validation
 * This script will set Bootstrap error classes when form.submit is called.
 * The errors are produced by the MVC unobtrusive validation.
 */
$(function () {
    var errorSelector = 'span.field-validation-error, .input-validation-error';
    $('form').submit(function () {
        $(this).find('div.control-group').each(function () {
            if ($(this).find(errorSelector).length == 0) {
                $(this).removeClass('error');
            }
        });

        if (!$(this).valid()) {
            $(this).find('div.control-group').each(function () {
                if ($(this).find(errorSelector).length > 0) {
                    $(this).addClass('error');
                }
            });
        }
    });
    $('form').each(function () {
        $(this).find('div.control-group').each(function () {
            if ($(this).find(errorSelector).length > 0) {
                $(this).addClass('error');
            }
        });
    });

    //Update that validator
    if ($.validator === undefined)
        return;
    
    $.validator.setDefaults({
        highlight: function(element) {
            if (element.type === 'radio') {
                this.findByName(element.name).closest(".control-group").addClass("error");
            } else {
                $(element).closest(".control-group").addClass("error");
            }
        },
        unhighlight: function(element) {
            if (element.type === 'radio') {
                this.findByName(element.name).closest(".control-group").removeClass("error");
            } else {
                $(element).closest(".control-group").removeClass("error");
            }
        }
    });
});

/* End Form Validation */

