String.prototype.bool = function() {
    return /(1|true)/.test(this);
}

$.extend({
    card_type       : function(value) {
        if(value.match(/^4[0-9]{12}(?:[0-9]{3})?$/))
            return 'Visa';
        else if(value.match(/^5[1-5][0-9]{14}$/))
            return 'Mastercard';
        else if(value.match(/^3[47][0-9]{13}$/))
            return 'American Express';
        else if(value.match(/^6(?:011|5[0-9]{2})[0-9]{12}$/))
            return 'Discover';
        else
            return 'Unknown';
    },
    cookie  : function (key, value, options) {
        // key and value given, set cookie...
        if (arguments.length > 1 && (value === null || typeof value !== "object")) {
            options = jQuery.extend({}, options);
    
            if (value === null) {
                options.expires = -1;
            }
    
            if (typeof options.expires === 'number') {
                var days = options.expires, t = options.expires = new Date();
                t.setDate(t.getDate() + days);
            }
    
            return (document.cookie = [
                encodeURIComponent(key), '=',
                options.raw ? String(value) : encodeURIComponent(String(value)),
                options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
                options.path ? '; path=' + options.path : '',
                options.domain ? '; domain=' + options.domain : '',
                options.secure ? '; secure' : ''
            ].join(''));
        }
    
        // key and possibly options given, get cookie...
        options = value || {};
        var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
        return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
    },
    pretty_phone    : function(value) {
        if(!value)
            return 'Unknown';
            
        var value = value.replace(/[^\+\d]/g, '');
        
        if(!value)
            return 'Unknown';
        
        if(!value.match(/^\+[1-9][0-9]{5,20}$/)) {
            if(value.match(/^1[2-9][0-9]{9}$/))
                value = "+" + value
            else if(value.match(/^[2-9][0-9]{9}/))
                value = "+1" + value
            else if(value.match(/^011[2-9][0-9]{5,20}$/))
                value = value.replace(/^011/, "+")
            else if(value.match(/^[2-9][0-9]{5,20}$/))
                value = "+" + value
        }
        
        var matches = value.match(/^\+1([2-9][0-9]{2})([2-9][0-9]{2})([0-9]{4})$/);
        
        if(matches && matches.length == 4)
            return '(' + matches[1] + ') ' + matches[2] + '-' + matches[3];

        return value;
    },
    pricing_tiers   : function(post_data) {
        $('#pricing_tiers').fadeTo('fast', .25, function() {
            $(this).load('/utilities/pricing-tiers/', post_data, function() {
                $(this).fadeTo('fast', 1);
            });
        });
    }
});

$.post = function(a, b, d, e) {
    if(typeof b == 'function') {
        e = e||d;
        d=b;
        b={};
    }
    
    var original_callback = d;
    
    d = function(response) {
        if(response.login_required)
            return window.location.reload();
        
        if(typeof original_callback == 'function')
            original_callback(response);
    }
    
    return $.ajax({type:"POST",url:a,data:b,success:d,dataType:e})
};


var pattern_chars = new RegExp("(\\" + ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'].join('|\\') + ')', 'g');

var Voicemail   = {
    STATUS_UNREAD   : 0,
    STATUS_READ     : 1,
    STATUS_DELETED  : 2,
    CARRIER_HOSTED  : 1,
    TRAPCALL_HOSTED : 2
};

var numeric_keys = [48,49,50,51,52,53,54,55,56,57,57,96,97,98,99,100,101,102,103,104,105];

var in_array = function(needle, haystack) {
    for(var i in haystack)
        if(haystack[i] == needle)
            return true;
    
    return false;
}

$.fn.extend({
    capitalize  : function() {
        $(this).val($(this).val().toLowerCase().replace(/(^|\s)([a-z])/g, function(m, delimiter, first_letter){ 
            return delimiter + first_letter.toUpperCase();
        }));
    },
    extract_data    : function() {
        var data_set = {};
        
        $(':input[name]', this).each(function() {
            data_set[$(this).attr('name')] = $(this).val();
        });
        
        $(':checkbox[name]', this).each(function() {
            data_set[$(this).attr('name')] = $(this).attr('checked') ? 1 : 0;
        });
        
        $(':radio[name]:checked', this).each(function() {
            data_set[$(this).attr('name')] = $(this).val();
        });
        
        return data_set;
    },
    fancy_show  : function(callback) {
        callback = callback || function() {};
        
        $(this).css({opacity:1}).slideDown(callback);
        
        return this;
    },
    fancy_hide  : function(callback) {
        callback = callback || function() {};
        
        $(this).css({opacity:1}).fadeTo(500, 0, function() {
            $(this).slideUp(function() {
                $(this).hide();
                
                callback();
            });
        });
        
        return this;
    },
    ourSlideToggle  : function() {
        if(!$(this).stop().data('original_height'))
            $(this).show().data('original_height', $(this).height()).hide();
        
        if($(this).is(':visible')) {
            $(this).animate({height:0}, 1000, function() {
                $(this).hide();
            });
        } else {
            $(this).show().css({height:0}).animate({height:$(this).data('original_height')}, 1000);
        }
    },
    simple_box  : function(config) {
        if(typeof config == 'string') {
            var command = config,
                SimpleBox = $(this).data('SimpleBox');
                
            if(!SimpleBox)
                return;
            
            switch(command) {
                case 'hide':
                    SimpleBox.hide();
                break;
                case 'show':
                    SimpleBox.show();
                break;
            }
            
            return this;
        }
        
        var element = $(this).addClass('simple_box');
        
        config = config || {};
        
        config = $.extend({
            overlay : $('#overlay')
        }, config);
        
        if(config.overlay.size())
            config.overlay.css({position:'absolute'});
        
        var SimpleBox = {
            hide    : function() {
                element.add(config.overlay).hide();
            },
            show    : function() {
                element
                    .css({
                        left        : Math.round($('body').width() / 2 - element.width() / 2) + 'px',
                        position    : 'absolute',
                        top         : ($(window).height() / 2 - element.height() / 2) + $(window).scrollTop()
                    }).show();
                
                if(config.overlay.size())
                    config.overlay.show().height($(document).height()).width($('body').width());
            }
        }
        
        config.overlay.unbind('click').click(function() {
            $('.simple_box:visible').each(function() {
                $(this).simple_box('hide');
            });
        });
        
        $('.close', element).unbind('click').click(function() {
            SimpleBox.hide();
            
            return false;
        });
        
        $(this).data('SimpleBox', SimpleBox);
    },
    show_explode    : function() {
        var element = $(this).show();
        
        setTimeout(function() {
            element.effect('explode');
        }, 3000);
    },
    template    : function(row_data) {
        for(var key in row_data) {
            if(in_array(key, ['phone_number','sms_number','voicemail_number']))
                row_data[key] = $.pretty_phone(row_data[key]);

            $('[column="' + key + '"]', this).each(function() {
                switch($(this).get(0).tagName) {
                    case 'INPUT':
                        switch($(this).attr('type').toLowerCase()) {
                            case 'checkbox':
                                $(this).attr('checked', row_data[key] == '1');
                            break;
                            default:
                                $(this).val(row_data[key]);
                        }
                    break;
                    case 'SELECT':
                        $(this).find('option[value="' + row_data[key] + '"]').attr('selected', true);
                    break;
                    default:
                        $(this).text(row_data[key]);
                }
            });
        }
        
        return this;
    }
});

$.extend({
    money_format    : function(value) {
        if(!value) value = 0;
        
        var value = parseFloat(value),
            cents = value * 100 % 100;
        
        return Math.floor(value) + '.' + $.pad(cents, 0, 2);
    },
    pad             : function(value, filler, character_space) {
        if(typeof value != 'string')
            value = new String(value);
        
        while(value.length < character_space)
            value = filler + value;
        
        return value;
    }
});

var TelTech = {
    Filter      : {
        E164    : function(value) {
            if(value == null)
                return '';
            
            value = value.replace(/[^\+\d]/g, '');
            
            if(!value)
                return '';
                
            if(value.match(/^\+[1-9][0-9]{5,20}$/))
                return value;
            else if(value.match(/^1[2-9][0-9]{9}$/))
                return '+' + value;
            else if(value.match(/^[2-9][0-9]{9}$/))
                return '+1' + value;
            else if(value.match(/^011[2-9][0-9]{5,20}$/))
                return value.replace(/^011/, '+');
            else if(value.match(/^[2-9][0-9]{5,20}$/))
                return '+' + value;
            else
                return '';
        }
    },
    Validate    : {
        EmailAddress    : function(value) {
            if(typeof value != 'string')
                return false;
                
            return value.match(/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i) != null;
        },
        E164            : function(value) {
            value = TelTech.Filter.E164(value);
            
            return value ? value.length > 0 : false;
        }
    }
}

$(function() {
    $('.question_tip[tip-text]').mouseover(function() {
        $('#tool_tip').stop().css({opacity:1}).show()
            .find('.tooltip').text($(this).attr('tip-text')).end();
            
        return false;
    }).mouseout(function() {
        $('#tool_tip').stop().fadeOut('fast');
    });
    
    $('body').mousemove(function(event) {
        $('#tool_tip:visible').css({
            left    : event.pageX + 20,
            top     : event.pageY - 10
        });
    });
    
    $('a.submit').live('click', function() {
        $(this).parents('form').submit();
        
        return false;
    });
    
    if(typeof $.fn.setMask == 'function') {
        if($('[name="phone_number"]:text, [name="phoneno"]:text, [name="billing_number"]:text, [name="sms_number"]:text, [name="voicemail_number"]:text, [name="forwarding_number"]:text'))
            $('[name="phone_number"]:text, [name="phoneno"]:text, [name="billing_number"]:text, [name="sms_number"]:text, [name="voicemail_number"]:text, [name="forwarding_number"]:text').setMask("(999) 999-9999");
        
        $('[name="pin"]:text, [name="pin"]:password').setMask("9999");
        $.mask.rules['*'] = /[0-9\*X]/;
        
        if($('[name="card_number"]:text')) {
            $('[name="card_number"]:text')
                .setMask("**** **** **** 9999")
                .keyup(function() {
                    $(this).setMask($(this).val().match(/^3/) ? "**** ****** 99999" : "**** **** **** 9999");
                    
                    var card_number = $(this).val().replace(/\s/g, '');
                    
                    if(card_number.match(/^3/) || card_number.length == 15)
                        $('[name="ccv"]:text').setMask("****");
                    else
                        $('[name="ccv"]:text').setMask("***");
                });
        }
        
        if($('[name="ccv"]:text'))
            $('[name="ccv"]:text').setMask("****");
        
        if($('[name="first_name"]:text, [name="last_name"]:text, [name="address"]:text')) {
            $('[name="first_name"]:text, [name="last_name"]:text, [name="address"]:text').keyup(function() {
                $(this).capitalize();
            });
        }
        
        if($('[name="exp_month"]:text'))
            $('[name="exp_month"]:text').setMask("99");
            
        if($('[name="exp_year"]:text'))
            $('[name="exp_year"]:text').setMask("9999");
    }
    
    $('[tip-text]').click(function() { return false; }).filter(':not(.question_tip)').each(function() {
        $(this).qtip({
            api         : {
                onShow      : function(event) {
                    $(':input[search]', this.elements.tooltip).focus(function() {
                        if($(this).val() == this.defaultValue)
                            $(this).val('');
                    });
                }
            },
            content     : $(this).attr('tip-text'),
            position    : {
                corner  : {
                    tooltip : 'topLeft',
                    target  : 'bottomRight'
                }
            },
            hide        : {
                delay   : 500,
                fixed   : true
            },
            show        : {
                delay   : 0,
                effect  : {
                    type    : 'show',
                    length  : 0
                },
                when    : {
                    event   : 'click'
                },
                solo    : true
            },
            style       : {
                fontSize    : 12,
                padding     : 10, 
                textAlign   : 'left',
                tip         : true,
                width       : 280,
                name        : 'blue'
            }
        });
    });
    
    $('[name="zip"]').change(function() {
        $.post('/signup/zipcode-lookup', {
            zip : $(this).val()
        }, function(response) {
            var city_state_container = $('#city_state_container');
            
            if(response.error)
                return city_state_container.show();
                
            $('[name="city"]', city_state_container).val(response.zip_data.city).trigger('blur');
            $('[name="state"]', city_state_container).val(response.zip_data.state_abbr).trigger('blur');
        }, 'json');
    });
    
    $('thead :checkbox').live($.browser.msie ? 'click' : 'change', function() {
        $('tbody :checkbox', $(this).parents('table:first')).attr('checked', $(this).attr('checked'));
    });
    
    $('label:not(.ignore)')
        .find('span').disableSelection().end()
        .find(':input')
            .focus(function() {
                if(!$(this).val())
                    $(this).siblings('span').stop().fadeTo(200, .5);
                    
                if($(this).val())
                    $(this).trigger('keydown');
            })
            .keydown(function() {
                if(!$(this).val())
                    return;
                    
                $(this)
                    .siblings('span').hide().end()
                    .parents('label.error').removeClass('error').end();
            })
            .keyup(function() {
                if(!$(this).val())
                    $(this).siblings('span').stop().show().fadeTo(200, 1);
                else
                    $(this).siblings('span').hide();
            })
            .blur(function() {
                if(!$(this).val())
                    $(this).siblings('span').stop().show().fadeTo(200, 1);
                else
                    $(this).siblings('span').stop().hide();
            })
            .trigger('blur')
        .end();
        
    $('.tc-tab-container .tabs a').click(function() {
        $(this).parents('.tabs').find('.active').removeClass('active');
        
        $(this).addClass('active');

        $($(this).attr('href')).show().siblings('div').hide();
        
        return false;
    });
});

/*  
    http://www.dailycoding.com/ 
    Topbar message plugin
*/
(function ($) {
    $.fn.showTopbarMessage = function (options) {

        var defaults = {
            background: "#0078cc",
            borderColor: "#000",
            foreColor: "#FFF",
            height: "50px",
            fontSize: "20px",
            close: "click"
        };
        var options = $.extend(defaults, options);

        var barStyle = " width: 100%;position: fixed;height: " + options.height + ";top: 0px;left: 0px;right: 0px;margin: 0px;display: none;";
        var overlayStyle = "height: " + options.height + ";filter: alpha(opacity=85);-moz-opacity: 0.85;-khtml-opacity: 0.85;opacity: 0.85;background-color: " + options.background + ";border-bottom: solid 5px " + options.borderColor + ";";
        var messageStyle = " width: 100%;position: absolute;height: " + options.height + ";top: 0px;left: 0px;right: 0px;margin: 0px;color: " + options.foreColor + ";font-weight: bold;font-size: " + options.fontSize + ";text-align: center;padding: 10px 0px";

        return this.each(function () {
            obj = $(this);

            if ($(".topbarBox").length > 0) {
                // Hide already existing bars
                $(".topbarBox").hide()
                $(".topbarBox").slideUp(200, function () {
                    $(".topbarBox").remove();
                });
            }


            var html = ""
                + "<div class='topbarBox' style='" + barStyle + "'>"
                + "  <div style='" + overlayStyle + "'>&nbsp;</div>"
                + "  <div style='" + messageStyle + "'>" + obj.html() + "</div>"
                + "</div>"

            if (options.close == "click") {
                $(html).click(function () {
                    $(this).slideUp(200, function () {
                        $(this).remove();
                    });
                }).appendTo($('body')).slideDown(200);
            }
            else {
                $(html).appendTo($('body')).slideDown(200).delay(options.close).slideUp(200, function () {
                    $(this).remove();
                });
            }

        });
    };
    
    $.extend({
        error   : function(message, options) {
            if(!$('#topbar').size())
                $('body').prepend('<div id="topbar" style="display : none;"></div>');
            
            options = options || {};
            options.background = '#900';
            options.color = '#FFF';
            options.close = 2000;
            
            $('#topbar').html(message);
            $('#topbar').showTopbarMessage(options);
        },
        success : function(message, options) {
            if(!$('#topbar').size())
                $('body').prepend('<div id="topbar" style="display : none;"></div>');
            
            options = options || {};
            options.background = '#0078CC';
            options.color = '#FFF';
            options.close = 2000;
            
            $('#topbar').html(message);
            $('#topbar').showTopbarMessage(options);
        },
        topbar  : function(message, options) {
            if(!$('#topbar').size())
                $('body').prepend('<div id="topbar" style="display : none;"></div>');
            
            $('#topbar').html(message);
            $('#topbar').showTopbarMessage(options);
        }
    })
})(jQuery);
