var utils = {
    size: function(o){
        var size = 0, key;
        for (key in o) {
            if (o.hasOwnProperty(key)) size++;
        }
        return size;
    }
}
var features = {
    vars:{
        list:{
            basic:{
                digit_dialing:{
                    title: '7, 10, and 11 Digit Dialing',
                    short_desc: 'All dialing methods are handled and fully functional, with each and every account.',
                    long_desc: ''
                },
                caller_id:{
                    title: 'Caller ID w/ Name',
                    short_desc: 'All accounts include fully functional Caller ID with both name and number.',
                    long_desc: 'All accounts include fully functional Caller ID with both name and number.'
                },
                call_waiting:{
                    title: 'Call Waiting w/ ID',
                    short_desc: 'View the full Caller ID (name and number) of any incoming calls, even when you are already on the line.',
                    long_desc: ''
                },
                three_way:{
                    title: 'Three Way Calling',
                    short_desc: 'While connected with another party, simply flash over on your phone device and dial out. Flash back, and all three parties will be joined on one line.',
                    long_desc: ''
                },
                call_forwarding:{
                    title: 'Call Forwarding',
                    short_desc: 'At the click of a button, instantly forward all calls to an alternative phone number of your choosing. Additionally, you may forward calls based on a custom pre-defined criteria (Custom Inbound Call Routing).',
                    long_desc: ''
                },
                call_blocking:{
                    title: 'Call Blocking',
                    short_desc: 'Block calls based upon your own unique criteria, all from the comfort of your web based vPanel account. Add specific numbers to block, or create your own custom rules (such as blocking entire area codes, or allowing only a \'whitelist\' of contacts to be able to reach you).',
                    long_desc: ''
                },
                dnd:{
                    title: 'Do Not Distribute',
                    short_desc: 'Not in the mood for conversation? Turn \'DND\' on, and all calls will be forwarded to voicemail or a busy tone.',
                    long_desc: ''
                },
                sixety_seven:{
                    title: '*67 Outbound Caller ID Blocking',
                    short_desc: 'Don\'t wish to disclose your information on a particular call? Not a problem. Simply dialing *67 before calling automatically blocks your outgoing Caller ID.',
                    long_desc: ''
                },
                sixety_nine:{
                    title: '*69 Call Return',
                    short_desc: 'Swiftly call back the last person who called your VOIPo number by dialing *69.',
                    long_desc: ''
                }
            },
            convenience:{
                transfer_number:{
                    title: 'Transfer In Your Current Number',
                    short_desc: 'We\'ve made the number transfer (porting) process as easy as possible. Simply fax or email in a one page authorization form, and we\'ll take care of the rest! Check the status of your transfer online, or call in and speak directly with a friendly VOIPo porting specialist.',
                    long_desc: ''
                },
                area_code:{
                    title: 'Choose Your Own Area Code',
                    short_desc: 'With Voice-Over-IP technology, no longer is your number bound to a geographical location. Choose a number from over 7,000 locations and areas across the country!',
                    long_desc: ''
                },
                keep_number:{
                    title: 'Keep Your Number If You Move',
                    short_desc: 'Moving soon? With VOIPo, you can keep your number regardless of location.',
                    long_desc: ''
                },
                tech_support:{
                    title: 'California-Based Tech Support',
                    short_desc: 'We\'re located in Southern California. Deal with knowledgeable support agents and friendly californians that can actually solve your problems and help you.',
                    long_desc: ''
                },
                portable:{
                    title: 'Portable VoIP Device',
                    short_desc: 'We ship you a VOIP device, free of charge. Plug it in at home, or take it with your on the road. The choice is yours!',
                    long_desc: ''
                },
                softphone:{
                    title: 'Softphone Access',
                    short_desc: 'VOIPo allows all users the option of utilizing software based phones.',
                    long_desc: ''
                },
                emergency:{
                    title: 'e911 Service',
                    short_desc: 'All accounts come with 911 service enabled. Quickly update the address a 911 operator would receive within the simplicity of your vPanel account.',
                    long_desc: ''
                },
                seven_eleven:{
                    title: '711 Service',
                    short_desc: '711 Telecommunications Relay Service (deaf and blind relay).',
                    long_desc: ''
                },
                four_eleven:{
                    title: '411 Directory Assistance',
                    short_desc: '411 "Information" (Directory Assistance) available to all users.',
                    long_desc: ''
                }
            },
            advanced:{
                custom_caller_id:{
                    title: 'Custom Incoming Caller ID',
                    short_desc: 'Your dynamic list of vPanel contacts can override the default network Caller ID with the description of your choosing! This is particularly useful for receiving calls from a cell phone or other source that does not send a traditional Caller ID details.',
                    long_desc: ''
                },
                contacts_list:{
                    title: 'Contacts List',
                    short_desc: 'Add and manage an unlimited amount of contact names from within vPanel. Additionally, you can create customized contact groups like family, work, and friend (or enemies!). Our Contacts System is fully integrated with other vPanel features including \'Customer Caller ID,\' and \'Call Routing\'.',
                    long_desc: ''
                },
                call_logs:{
                    title: 'Online Call Logs',
                    short_desc: 'Each and every call made from your account on the VOIPo network is logged and displayed online for your convenience and security.',
                    long_desc: ''
                },
                speed_dial:{
                    title: 'Unlimited Speed Dial',
                    short_desc: 'Create as many speed dial codes as you can remember! With a few clicks, you can seamlessly and easily add/modify speed dial functionality for specific numbers and contacts.',
                    long_desc: ''
                },
                voicemail:{
                    title: 'Advanced Voicemail',
                    short_desc: 'Voicemail for the modern, technological world. With VOIPo Advanced Voicemail, in addition to the ability to check your messages over the phone -- notifications can be delivered directly to your email (message included). Need more accessibility? We thought so too, and incorporated short and sweet US SMS (text) based notifications as well.',
                    long_desc: ''
                },
                online_voicemail:{
                    title: 'View Voicemails Online',
                    short_desc: 'Jump on the web and listen to your new and saved voicemail messages, all from the simplicity of your vPanel account.',
                    long_desc: ''
                },
                emailed_voicemail:{
                    title: 'Voicemails E-Mailed',
                    short_desc: 'Simply specify an email address, and we\'ll automatically send a notification when someone has left a voicemail. In addition, choose to attach the actual voicemail (.wav file) to the email itself!',
                    long_desc: ''
                },
                sms_voicemail:{
                    title: 'Voicemail SMS Notifications',
                    short_desc: 'We have introduced SMS (text) notifications as an additional method for voicemail alerts. Receive a short, concise \'text\' with just the essentials: Caller ID, Number, Date/Time, and message length. The textual notification is short enough to fit into a single \'text with all major US carriers.',
                    long_desc: ''
                },
                distinctive_ringtones:{
                    title: 'Distinctive Ringtones',
                    short_desc: 'Know who is calling you before you ever check the phone! Assign different ringtones to incoming users, for immediate identification.',
                    long_desc: ''
                },
                virtual_numbers:{
                    title: 'Virtual Numbers',
                    short_desc: 'Added through your vPanel account, Virtual Numbers are unique, different phone numbers that ring through to the same line as your primary VOIPo number (incoming only).',
                    long_desc: ''
                },
                voicemail_boxes:{
                    title: 'Virtual Number Voicemail Boxes',
                    short_desc: 'Enable unique voicemail mailboxes at your disposal for each individual Virtual Number assigned to the account.',
                    long_desc: ''
                },
                failover:{
                    title: 'Network Failover Forwarding',
                    short_desc: 'Power or ISP outage? With Failover Forwarding, simply specify an alterative contact number and our system will automatically forward calls there when you\'re not connected to our network.',
                    long_desc: ''
                },
                inbound_call_routing:{
                    title: 'Custom Inbound Call Routing',
                    short_desc: 'Route incoming calls with your own custom rule sets and predefined criteria.',
                    long_desc: ''
                },
                outbound_call_routing:{
                    title: 'Custom Outbound Call Routing',
                    short_desc: 'Route outgoing calls with your own custom rule sets and predefined criteria.',
                    long_desc: ''
                },
                inbound_sip_address:{
                    title: 'Inbound SIP Address Routing',
                    short_desc: 'Need an inbound SIP address? All accounts have one by default.',
                    long_desc: ''
                },
                outbound_sip_address:{
                    title: 'Outbound SIP Address Routing',
                    short_desc: 'Route outgoing calls via SIP address with ease!',
                    long_desc: ''
                },
                simul_ring:{
                    title: 'Simultaneous Ring',
                    short_desc: 'Setup an additional external number (cell, work, etc) that will ring simultaneously with your VOIPo line.',
                    long_desc: ''
                },
                sms_control:{
                    title: 'Control Features by SMS',
                    short_desc: 'You asked, and we delivered. Send simple, secure \'texts\' to us via cell phone and automatically configure your VOIPo account on the fly!',
                    long_desc: ''
                }
            },
            cloud_uses:{
                forward_to_num:{
                    title: 'Forward to any Us/Can Number',
                    short_desc: 'Forward your number to any US or Canadian number such as a cell phone.',
                    long_desc: ''
                },
                forward_to_sip:{
                    title: 'Forward to a SIP Address',
                    short_desc: 'Forward your number to a SIP address such as user@voipwelcome.com.',
                    long_desc: ''
                },
                register_to_sip:{
                    title: 'Register to a SIP Account',
                    short_desc: 'Setup a SIP account to register your IP Phone or ATA to so that you can receive calls directly.',
                    long_desc: ''
                },
                receive_fax:{
                    title: 'Use to Receive Faxes',
                    short_desc: 'Set your phone number up to function as a fax number and you\'ll be able to receive faxes on it.  When a fax comes in, it\'ll be e-mailed to you as a PDF file.',
                    long_desc: ''
                }
            }, 
            cloud_features:{
                call_logs:{
                    title: 'Online Call Logs',
                    short_desc: 'Each and every received with your account on the VOIPo network is logged and displayed online for your convenience and security.',
                    long_desc: ''
                },
                control_panel:{
                    title: 'Online Control Panel',
                    short_desc: 'Manage your account and updating your number routing instantly in our online control panel.',
                    long_desc: ''
                },
                voicemail_boxes:{
                    title: 'Voicemail Boxes',
                    short_desc: 'Setup and manage voicemail boxes for each number.',
                    long_desc: ''
                },
                transfer_in_numbers:{
                    title: 'Transfer In Numbers',
                    short_desc: 'Already have a number you\'d like to use with VOIPo?  Transfer it to VOIPo.',
                    long_desc: ''
                },
                caller_id:{
                    title: 'Caller ID',
                    short_desc: 'All incoming calls contain Caller ID so you know who is calling.',
                    long_desc: ''
                },
                online_faxes:{
                    title: 'Send Faxes Online',
                    short_desc: 'Send faxes right from your online control panel by simply uploading a document and entering the destination number.',
                    long_desc: ''
                },
                routing:{
                    title: 'Instantly Change Routing',
                    short_desc: 'From your online control panel, you can update the destination routing for your numbers instantly.',
                    long_desc: ''
                },
                sip_address:{
                    title: 'Free Inbound SIP Address',
                    short_desc: 'In addition to being able to be called from the regular phone network, all numbers on the VOIPo network can also be called by a SIP address.  SIP Address Format: 10DigitNumber@in01.voipwelcome.com',
                    long_desc: ''
                }
            }       
        }
    },
    init: function(){
        features.build_lists();
        features.bind();
        $('.featuredetailsholder .arrow').css('top', function(){
            return ($('.featuredetailsholder:first').outerHeight() - $(this).outerHeight()) / 2;
        });
    },
    build_lists: function(){
        features.display_list(features.vars.list.basic, 'basic');
        features.display_list(features.vars.list.convenience, 'convenience');
        features.display_list(features.vars.list.advanced, 'advanced');
        features.display_list(features.vars.list.cloud_features, 'cloud_features');
        features.display_list(features.vars.list.cloud_uses, 'cloud_uses');
        features.tinge();
    },
    display_list: function(list, type){
        var html = '';
        var html2 = '';
        var count = 0;
        $.each(list, function(k,v){
            count++;
            if((type == 'advanced') && count > utils.size(list) / 2){
                html2 += '<li><span key="'+k+'" category="'+type+'" tinge="'+this.short_desc+'">'+this.title+'</span></li>';
            }
            else{
                html += '<li><span key="'+k+'" category="'+type+'" tinge="'+this.short_desc+'">'+this.title+'</span></li>';
            }
        });
        if(type == 'advanced'){
            $('#advanced1').html(html);
            $('#advanced2').html(html2);
        }
        else{
            $('#'+type).html(html);
        }
    },
    show_details: function(key, cat){
        var details = features.vars.list[cat][key];
        $('.featuredetailsholder h2').html(details.title);
        $('.featuredetailscontent').html(details.short_desc);
        $('.featuredetailsholder .arrow').css('top', function(){
            return ($('.featuredetailsholder:first').outerHeight() - $(this).outerHeight()) / 2;
        });
    },
    tinge: function(){
        $('#features .features li span').tinge({pointer: 'lm', pointer_color: '#1E5985', hide_delay: 0, margin: 5});   
    },
    bind: function(){
        $('.secondary_nav a').click(function(){
            var t = $(this);
            $('.secondary_nav a.on').removeClass('on');
            t.addClass('on');
            $('.bigfeatures').hide();
            if(t.hasClass('voip_features')){
                $('#voip_features').show();    
            }
            else{
                $('#cloud_feats').show();    
            }
            return false;
        });
        var scroll_feature = function(){
            var pad = 349;
            var distance = $(window).scrollTop();
            var f = $('.featuredetails');
            if(distance > pad){
                var diff = distance - pad;
                var matchheight = $('#features_left').outerHeight() - 35;
                var total = diff + f.outerHeight();
                if(total >= matchheight){
                    f.animate({top: matchheight - f.outerHeight()}, 100);
                }
                else{
                    f.animate({top: diff}, 100);
                }
            }
            else{
                f.animate({top: 0}, 100);
            }  
        };
        $('#features .features li span').click(function(){
            var t = $(this);
            $('li.on').removeClass('on');
            t.parent('li').addClass('on');
            features.show_details(t.attr('key'), t.attr('category'));
            scroll_feature();
        });
        $(window).scroll(function(){
            scroll_feature();
        });
    }
};

var rates = {
    cache_all: null,
    loader: null,
    current_call: null,
    showing_all: false,
    typing: null,
    init: function(){
        rates.bind();
        rates.show_all();
        //$('.rates_table').tablesorter({debug: false, widgets: ['zebra'], sortList: [[0,0]]});
    },
    show_all: function(){
        if(rates.showing_all == false){
            rates.showing_all = true;
            if(rates.cache_all || false){
                rates.iterate_all(rates.cache_all);
            }
            else{
                rates.check_call();
                rates.current_call = $.getJSON("http://secure.voipo.com/rates.php?request=getRates&callback=?", function(r){
                    rates.current_call = null;
                    rates.cache_all = r;
                    rates.iterate_all(rates.cache_all); 
                    rates.loader = $('.rates_table tbody').html(); 
                });
            }
        }
    },
    iterate_all: function(r){
        var html = '';
        if(r || false){
            $.each(r, function(){
                var pe = 'No';
                if(parseInt(this.packageEligible) == 1){
                    pe = 'Yes';
                }
                html += '<tr><td>'+this.title+'</td><td>'+this.digits+'</td><td>'+this.rate.substr(0,4)+'</td><td>'+pe+'</td></tr>';
            });
        }
        else{
            html += '<td colspan="10">Sorry, no rates are available at this time.</td>';
        }
        $('.rates_table tbody').html(html);
        $('.rates_table').trigger("update");
    },
    country: function(country){ 
        rates.check_call();
        rates.current_call = $.getJSON("http://secure.voipo.com/rates.php?request=getTitleRates&callback=?&title="+country, function(r){
            rates.current_call = null;
            rates.showing_all = false;
            rates.iterate_all(r);
        });
    },
    phone_number_rate: function(phone){
        rates.check_call();
        rates.current_call = $.getJSON("http://secure.voipo.com/rates.php?request=getPhoneNumberRate&callback=?&phoneNumber="+phone, function(r){
            rates.current_call = null;
            rates.showing_all = false;
            rates.iterate_all(r);
        });
    },
    prefix: function(prefix){
        rates.check_call();
        rates.current_call = $.getJSON("http://secure.voipo.com/rates.php?request=getPrefixRates&callback=?&prefix="+prefix, function(r){
            rates.current_call = null;
            rates.showing_all = false;
            rates.iterate_all(r);
        });
    },
    check_call: function(){
        if(rates.current_call || false){
            rates.current_call.abort();
            rates.current_call = null;
        }
    },
    bind: function(){
        $('#country').bind('keyup', function(){
            clearTimeout(rates.typing);
            $('.rates_table tbody').html(rates.loader); 
            var t = $(this);
            var country = t.val();
            if(country.length >= 1){
                rates.typing = setTimeout(function(){return function(){rates.country(country);}}(), 250);
            }
            else if(country.length <= 0){
                rates.show_all();
            }
        });
        $('#phone_number').bind('keyup', function(){
            clearTimeout(rates.typing);
            $('.rates_table tbody').html(rates.loader); 
            var t = $(this);
            var phone = t.val();
            var numberCheck = /^[0-9]+/;
            if(numberCheck.test(phone) && phone.length > 5){
                rates.typing = setTimeout(function(){return function(){rates.phone_number_rate(phone);}}(), 250);  
            }
            else if(phone.length <= 0){
                rates.show_all();
            }
        });
        $('#prefix').bind('keyup', function(){
            clearTimeout(rates.typing);
            $('.rates_table tbody').html(rates.loader); 
            var t = $(this);
            var prefix = t.val();
            if(prefix.length >= 1){
                rates.typing = setTimeout(function(){return function(){rates.prefix(prefix);}}(), 250);
            }
            else if(prefix.length <= 0){
                rates.show_all();
            }
        });
    }
};
    
$(document).ready(function(){
    if($('#features').length > 0){
        features.init();  
    }
    else if($('#rates').length > 0){
        rates.init();
    }
    else if($('#page2').length > 0 || $('#page3').length > 0){
        $('select').change(function(){
            var t = $(this);
            t.parents('ul').find('.paper span').html(t.val());
        });
        $('select').change();
    }
});

