/**
 * deals with formatting a value based on a type
 * 
 * type = number, dollar, url, phone
 * usage: $.formatter('2000000', 'number');
 */
(function($){
    $.formatter = function(value, type)
    {
        return $.formatter.format[type].call(this, value);
    };
    
    $.formatter.format = {
        
        /**
         * adds commas to a string, and removes non-numeric characters like $ signs
         */
        number: function(value)
        {
            value += ''; // make sure it's a string
            x = value.split('.');
            x1 = x[0].replace(/\D/g, ''); // get rid of non-digits
            x2 = (x.length > 1) ? '.' + x[1] : '';
            while (/(\d+)(\d{3})/.test(x1)) {
                x1 = x1.replace(/(\d+)(\d{3})/, '$1' + ',' + '$2');
            }
            return x1 + x2;
        },
            
        /**
         * formats a dollar value using the number format, but makes sure the dollar sign is added back on
         */
        dollar: function(value)
        {
            return "$" + $.formatter.format.number(value);
        },
        
        /**
         * Produces a standard phone number string in the format (555) 555-5555 ext. 555
         * If the format is not recognized, the number is left alone.
         */
        phone: function(value)
        {
            if (value == "") return value;
            var orig_value = value;

            // get rid of all spaces and non word or number characters
            value = value.replace(/(\W|_)/g, "");
            /(?:\d+)(\D+)(?:\d+)/.test(value);
            value = $.trim(value.replace(RegExp.$1, " "));

            var parts = value.split(" ");

            // remove the number one if it is the first character of the first array elem
            var ret = parts[0].replace(/\b1?/, "");

            if (ret.length == 7) {
                /(\b\d{3}?)/.test(ret);
                ret = ret.replace(RegExp.$1, RegExp.$1 + "-");

            } else if (ret.length == 10) {
                // make it like so: (925) 9446585
                /(\b\d{3}?)/.test(ret);
                ret = ret.replace(RegExp.$1, "(" + RegExp.$1 + ") ");

                /(\s\b\d{3}?)/.test(ret);
                ret = ret.replace(RegExp.$1, RegExp.$1 + "-");

            } else {
                return orig_value;
            }

            if (parts.length > 1) {
                ret += " ext. " + parts[1];
            }

            return ret;
        },
            
        /**
         * formats a url, making sure the http:// is added to the beginning
         */
        url: function(value)
        {
            // var rUrl = /^(http|https)/;
            value = $.trim(value);
            return (/^(http|https)/.test(value)) ? value : "http://" + value;
        }
        
    }
})(jQuery);

/**
 * deals with formatting input fields on blur
 * 
 * type = number, dollar, url, phone
 * usage: $('.my_number_elments').formatFields('number');
 */
(function($){
    $.fn.formatFields = function(type){
        return this.each(function(){
            // make sure the field is formatted when the page loads
            var formatted_val = $.formatter($(this).val(), type);
            $(this).val(formatted_val);
            // make sure the field is formatted when it is unfocused
            $(this).blur(function(){
                var formatted_val = $.formatter($(this).val(), type);
                $(this).val(formatted_val);
            })
        });
    }
})(jQuery);

/**
 * Adds a standard set of form indicator behavior to a form page.  When the
 * user clicks the submit button, the appropriate controls hide and the 
 * form indicator appears, then the form is submitted.
 */
$(function(){
    $(".form_indicator_section .action_btn").click(function(){
        $(".action_btn").hide();
        $(".cancel_link").hide();
        $(".form_indicator").show();
        setTimeout(function(){
            $(".action_btn").parents("form").get(0).submit();
        }, 200);
    })
})

/**
 * This is similar to the form indicator behavior set above, but it deals with
 * submit buttons and indicators that are inline.
 */
$(function(){
    $("#action_btn_inline_block").click(function(){
        $("#action_btn_inline_block").hide();
        $("#form_ind").css({'display':'inline-block'});
        setTimeout(function(){
            $("#action_btn_inline_block").parents("form").get(0).submit();
        }, 200);
    })
})

/**
 * All messages in the system have an "okay" link at the bottom.  This adds
 * the action, which causes the message to slide up when clicked.
 */
$(function(){
    $("a.okay_link").click(function(event){
        $(event.target).parent().parent().parent().slideUp("fast");
    })
})

/**
 * Finds all of the checkgroup select all links and applies an event handler to them 
 * that will select all of the checkboxes in the parent group when clicked.
 */
$(function(){
    $("a.select_all_link").click(function(){
        var checkboxes = $(this).parents('div.check_group:first').children('label').children('input');
        
        // if all of the checkboxes are checked, we'll reverse the behavior and uncheck all boxes
        var checked_count = 0;
        checkboxes.each(function(){
            if (this.checked) checked_count++;
        })
        var all_checked = (checked_count == checkboxes.length);
        
        checkboxes.each(function(){
            this.checked = (all_checked) ? false : true;
        })
    })
})

/**
 * formatter fields
 */
$(function(){
    $("#link_store_url").formatFields("url");
    $("#settings_client_url").formatFields("url");
})
