﻿(function($) {
    $(function() {
        $('.datepicker').datepicker({ dateFormat: 'm/d/yy' });
        if ($('.daterangepicker').length > 0) {
            $('.daterangepicker').daterangepicker({ dateFormat: 'm/d/yy' });
        }
        StripeList();

        // Hover for buttons.
        // http://www.filamentgroup.com/lab/styling_buttons_and_toolbars_with_the_jquery_ui_css_framework/
        $('.fg-button').hover(
	        function() { $(this).addClass('ui-state-hover'); },
	        function() { $(this).removeClass('ui-state-hover'); }
        )

        $('.eq-height').equalHeights();

        $('.buttonset').buttonset();
    });
})(jQuery);

function StripeList() {
    $('table.list tbody tr:visible:even').removeClass('listaltrow');
    $('table.list tbody tr:visible:odd').addClass('listaltrow');
}

function initLoadDelete(deleteUrl) {
    if ($('#dialogdeleteconfirm').length == 0 && $('.list a.delete').length > 0) {
        $('table.list').after('<div id="dialogdeleteconfirm" title="Confirm" style="display: none;"><p id="dialogconfig-message">Are you sure you want to delete this load?</p></div>');
    }
    
    // Delete links.
    $('.list a.delete').live('click', function(event) {
        var row = $(event.target).closest('tr');
        var data = { Id: row.attr('id') };
        var confirm = $('#dialogdeleteconfirm');
        confirm.data('callback', function() {
            $.ajax({
                url: deleteUrl,
                data: data,
                type: 'POST',
                success: function(result) {
                    row.fadeOut('normal', StripeList);
                }
            });
        });
        confirm.dialog('open');

        return false;
    });

    // Confirm dialog.
    $('#dialogdeleteconfirm').dialog({
        autoOpen: false,
        width: 375,
        buttons: {
            'Ok': function() {
                var dialog = $(this);
                if (dialog.data('callback')) {
                    dialog.data('callback')();
                    dialog.removeData('callback');
                }
                dialog.dialog('close');
            },
            'Cancel': function() {
                $(this).dialog('close');
            }
        }
    });
}


function initCustomerActions(activateUrl, inactivateUrl) {
    if ($('#dialogactivateconfirm').length == 0) {
        $('table.list').after('<div id="dialogactivateconfirm" title="Confirm" style="display: none;"><p id="dialogconfig-message">Are you sure you want to activate this customer?</p></div>');
    }

    if ($('#dialoginactivateconfirm').length == 0) {
        $('table.list').after('<div id="dialoginactivateconfirm" title="Confirm" style="display: none;"><p id="dialogconfig-message">Are you sure you want to inactivate this customer?</p></div>');
    }

    // Activate links.
    $('.list a.activate').live('click', function(event) {
        var row = $(event.target).closest('tr');
        var data = { Id: row.attr('id') };
        var confirm = $('#dialogactivateconfirm');
        confirm.data('callback', function() {
            $.ajax({
                url: activateUrl,
                data: data,
                type: 'POST',
                success: function(result) {
                    row.fadeOut('normal', StripeList);
                }
            });
        });
        confirm.dialog('open');

        return false;
    });

    // Inactivate links.
    $('.list a.inactivate').live('click', function(event) {
        var row = $(event.target).closest('tr');
        var data = { Id: row.attr('id') };
        var confirm = $('#dialoginactivateconfirm');
        confirm.data('callback', function() {
            $.ajax({
                url: inactivateUrl,
                data: data,
                type: 'POST',
                success: function(result) {
                    row.fadeOut('normal', StripeList);
                }
            });
        });
        confirm.dialog('open');

        return false;
    });

    // Confirm dialogs.
    $('#dialogactivateconfirm').dialog({
        autoOpen: false,
        width: 375,
        buttons: {
            'Ok': function() {
                var dialog = $(this);
                if (dialog.data('callback')) {
                    dialog.data('callback')();
                    dialog.removeData('callback');
                }
                dialog.dialog('close');
            },
            'Cancel': function() {
                $(this).dialog('close');
            }
        }
    });

    // Confirm dialogs.
    $('#dialoginactivateconfirm').dialog({
        autoOpen: false,
        width: 375,
        buttons: {
            'Ok': function() {
                var dialog = $(this);
                if (dialog.data('callback')) {
                    dialog.data('callback')();
                    dialog.removeData('callback');
                }
                dialog.dialog('close');
            },
            'Cancel': function() {
                $(this).dialog('close');
            }
        }
    });
}

function initAwardBid(awardBidUrl) {
    $('a.award-bid').live('click', function(event) {
        var parentContainer = $(event.target).closest('div.parent-bid');
        var data = { Id: parentContainer.attr('id') };
        $.ajax({
            url: awardBidUrl,
            data: data,
            type: 'POST',
            success: function(result) {
                $('div.parent-bid').filter(function() { return $(this).attr('id') != parentContainer.attr('id'); }).fadeOut('slow', function() { $(this).after('<p class="tip">Declined</p>') });
                parentContainer.fadeOut('slow', function() { parentContainer.after('<h2>Awarded</h2>') });

                $("#dialog-awarded").dialog({
                    modal: true,
                    buttons: {
                        Ok: function() {
                            $(this).dialog('close');
                        }
                    }
                });
            }
        });

        return false;
    });
}

function initDeclineBid(declineBidUrl) {
    $('a.decline-bid').live('click', function(event) {
        var parentContainer = $(event.target).closest('div.parent-bid');
        var data = { Id: parentContainer.attr('id') };
        $.ajax({
            url: declineBidUrl,
            data: data,
            type: 'POST',
            success: function(result) {
                parentContainer.fadeOut('slow', function() { $(this).after('<p class="tip">Declined</p>') });
            }
        });

        return false;
    });
}

function initLoadFacet(options) {
    var settings = {
        CommodityType: '',
        EquipmentSize: '',
        EquipmentType: '',
        GrossWeight: ''
    };
    if (options) {
        $.extend(settings, options);
    }

    $('a.loadfacet').click(function() {
        var link = $(this);
        var value = link.attr('rel');

        if (link.hasClass("CommodityType")) {
            $('#' + settings.CommodityType).val(value);
        }

        if (link.hasClass("CommodityTypeRemove")) {
            $('#' + settings.CommodityType).val('');
        }
        
        if (link.hasClass("EquipmentSize")) {
            $('#' + settings.EquipmentSize).val(value);
        }

        if (link.hasClass("EquipmentSizeRemove")) {
            $('#' + settings.EquipmentSize).val(value);
        }

        if (link.hasClass("EquipmentType")) {
            $('#' + settings.EquipmentType).val(value);
        }

        if (link.hasClass("EquipmentTypeRemove")) {
            $('#' + settings.EquipmentType).val(value);
        }
        
        if (link.hasClass("GrossWeight")) {
            $('#' + settings.GrossWeight).val(value);
        }

        if (link.hasClass("GrossWeightRemove")) {
            $('#' + settings.GrossWeight).val(value);
        }
        
        $('#loadFacetForm').submit();
        
        return false;
    });
}

(function($) {
    $.fn.simpleselect = function(options) {
        var settings = {
            select: function() { }
        };
        if (options) {
            $.extend(settings, options);
        }

        this.children().each(function() {
            $(this).addClass('ui-state-default');
        }).hover(function() {
            $(this).addClass('ui-state-hover');
        }, function() {
            $(this).removeClass('ui-state-hover');
        }).click(function() {
            $(this).toggleClass('ui-state-active').siblings().removeClass('ui-state-active');

            settings.select($(this));
        });

        return this;
    }
})(jQuery);

/*
*
* Copyright (c) 2006/2007 Sam Collett (http://www.texotela.co.uk)
* Licensed under the MIT License:
* http://www.opensource.org/licenses/mit-license.php
* 
* Version 1.0
* Demo: http://www.texotela.co.uk/code/jquery/numeric/
*
* $LastChangedDate: 2007-05-29 11:31:36 +0100 (Tue, 29 May 2007) $
* $Rev: 2005 $
*/

/*
* Allows only valid characters to be entered into input boxes.
* Note: does not validate that the final text is a valid number
* (that could be done by another script, or server-side)
*
* @name     numeric
* @param    validCallback       A function that runs if the number is valid (fires onblur)
* @param    invalidCallback     A function that runs if the number is not valid (fires onblur)
* @author   Sam Collett (http://www.texotela.co.uk)
* @example  $(".numeric").numeric(validCallback, invalidCallback);
*
*/
(function($) {
    $.fn.numeric = function(validCallback, invalidCallback) {
        allowNegative = false;
        decimal = ".";
        validCallback = typeof validCallback == "function" ? validCallback : function() { };
        invalidCallback = typeof invalidCallback == "function" ? invalidCallback : function() { };
        this.keypress(
		    function(e) {
		        var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
		        // allow enter/return key (only when in an input box)
		        if (key == 13 && this.nodeName.toLowerCase() == "input") {
		            return true;
		        } else if (key == 13) {
		            return false;
		        }
		        var allow = false;
		        // allow Ctrl+A
		        if ((e.ctrlKey && key == 97 /* firefox */) || (e.ctrlKey && key == 65) /* opera */) return true;
		        // allow Ctrl+X (cut)
		        if ((e.ctrlKey && key == 120 /* firefox */) || (e.ctrlKey && key == 88) /* opera */) return true;
		        // allow Ctrl+C (copy)
		        if ((e.ctrlKey && key == 99 /* firefox */) || (e.ctrlKey && key == 67) /* opera */) return true;
		        // allow Ctrl+Z (undo)
		        if ((e.ctrlKey && key == 122 /* firefox */) || (e.ctrlKey && key == 90) /* opera */) return true;
		        // allow or deny Ctrl+V (paste), Shift+Ins
		        if ((e.ctrlKey && key == 118 /* firefox */) || (e.ctrlKey && key == 86) /* opera */
			    || (e.shiftKey && key == 45)) return true;
		        // if a number was not pressed
		        if (key < 48 || key > 57) {
		            /* '-' only allowed at start */
		            if (allowNegative && key == 45 && this.value.length == 0) return true;
		            /* only one decimal separator allowed */
		            if (key == decimal.charCodeAt(0) && this.value.indexOf(decimal) != -1) {
		                allow = false;
		            }
		            // check for other keys that have special purposes
		            if (
					    key != 8 /* backspace */ &&
					    key != 9 /* tab */ &&
					    key != 13 /* enter */ &&
					    key != 35 /* end */ &&
					    key != 36 /* home */ &&
					    key != 37 /* left */ &&
					    key != 39 /* right */ &&
					    key != 46 /* del */
				    ) {
		                allow = false;
		            }
		            else {
		                // for detecting special keys (listed above)
		                // IE does not support 'charCode' and ignores them in keypress anyway
		                if (typeof e.charCode != "undefined") {
		                    // special keys have 'keyCode' and 'which' the same (e.g. backspace)
		                    if (e.keyCode == e.which && e.which != 0) {
		                        allow = true;
		                    }
		                    // or keyCode != 0 and 'charCode'/'which' = 0
		                    else if (e.keyCode != 0 && e.charCode == 0 && e.which == 0) {
		                        allow = true;
		                    }
		                }
		            }
		            // if key pressed is the decimal and it is not already in the field
		            if (key == decimal.charCodeAt(0) && this.value.indexOf(decimal) == -1) {
		                allow = true;
		            }
		        }
		        else {
		            allow = true;
		        }
		        return allow;
		    }
	    )
	    .blur(
		    function() {
		        var val = $(this).val();
		        if (val != "") {
		            var re = new RegExp("^\\d+$|\\d*" + decimal + "\\d+");
		            if (!re.exec(val)) {
		                invalidCallback.apply(this);
		            } else {
		                validCallback.apply(this);
    		        }
		        }
		    }
	    );
        return this;
    }
})(jQuery);


/*-------------------------------------------------------------------- 
* javascript method: "pxToEm"
* by:
Scott Jehl (scott@filamentgroup.com) 
Maggie Wachs (maggie@filamentgroup.com)
http://www.filamentgroup.com
*
* Copyright (c) 2008 Filament Group
* Dual licensed under the MIT (filamentgroup.com/examples/mit-license.txt) and GPL (filamentgroup.com/examples/gpl-license.txt) licenses.
*
* Description: Extends the native Number and String objects with pxToEm method. pxToEm converts a pixel value to ems depending on inherited font size.  
* Article: http://www.filamentgroup.com/lab/retaining_scalable_interfaces_with_pixel_to_em_conversion/
* Demo: http://www.filamentgroup.com/examples/pxToEm/	 	
*							
* Options:  	 								
scope: string or jQuery selector for font-size scoping
reverse: Boolean, true reverses the conversion to em-px
* Dependencies: jQuery library						  
* Usage Example: myPixelValue.pxToEm(); or myPixelValue.pxToEm({'scope':'#navigation', reverse: true});
*
* Version: 2.0, 08.01.2008 
* Changelog:
*		08.02.2007 initial Version 1.0
*		08.01.2008 - fixed font-size calculation for IE
--------------------------------------------------------------------*/

Number.prototype.pxToEm = String.prototype.pxToEm = function(settings) {
    //set defaults
    settings = jQuery.extend({
        scope: 'body',
        reverse: false
    }, settings);

    var pxVal = (this == '') ? 0 : parseFloat(this);
    var scopeVal;
    var getWindowWidth = function() {
        var de = document.documentElement;
        return self.innerWidth || (de && de.clientWidth) || document.body.clientWidth;
    };

    /* When a percentage-based font-size is set on the body, IE returns that percent of the window width as the font-size. 
    For example, if the body font-size is 62.5% and the window width is 1000px, IE will return 625px as the font-size. 	
    When this happens, we calculate the correct body font-size (%) and multiply it by 16 (the standard browser font size) 
    to get an accurate em value. */

    if (settings.scope == 'body' && $.browser.msie && (parseFloat($('body').css('font-size')) / getWindowWidth()).toFixed(1) > 0.0) {
        var calcFontSize = function() {
            return (parseFloat($('body').css('font-size')) / getWindowWidth()).toFixed(3) * 16;
        };
        scopeVal = calcFontSize();
    }
    else { scopeVal = parseFloat(jQuery(settings.scope).css("font-size")); };

    var result = (settings.reverse == true) ? (pxVal * scopeVal).toFixed(2) + 'px' : (pxVal / scopeVal).toFixed(2) + 'em';
    return result;
};


/*-------------------------------------------------------------------- 
* JQuery Plugin: "EqualHeights"
* by:	Scott Jehl, Todd Parker, Maggie Costello Wachs (http://www.filamentgroup.com)
*
* Copyright (c) 2008 Filament Group
* Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
*
* Description: Compares the heights or widths of the top-level children of a provided element 
and sets their min-height to the tallest height (or width to widest width). Sets in em units 
by default if pxToEm() method is available.
* Dependencies: jQuery library, pxToEm method	(article: 
http://www.filamentgroup.com/lab/retaining_scalable_interfaces_with_pixel_to_em_conversion/)							  
* Usage Example: $(element).equalHeights();
Optional: to set min-height in px, pass a true argument: $(element).equalHeights(true);
* Version: 2.0, 08.01.2008
--------------------------------------------------------------------*/

$.fn.equalHeights = function(px) {
    $(this).each(function() {
        var currentTallest = 0;
        $(this).children().each(function(i) {
            if ($(this).height() > currentTallest) { currentTallest = $(this).height(); }
        });
        if (!px || !Number.prototype.pxToEm) currentTallest = currentTallest.pxToEm(); //use ems unless px is specified
        // for ie6, set height since min-height isn't supported
        if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({ 'height': currentTallest }); }
        $(this).children().css({ 'min-height': currentTallest });
    });
    return this;
};
