$(document).ready(function() {

    /**
     * Cookie to store user's selected currency. Default: 'EUR'.
     */
    if (!$.cookie('currency')) {
        $.cookie('currency', 'EUR', {path: '/'});
    } else {
        $('select#your-currency').val($.cookie('currency'));
    }

    /**
     * Cookie to store user's selected your-country.
     */
    if (!$.cookie('yourcountry')) {
        $.cookie('yourcountry', 'default', {path: '/'});
    } else {
        $('select#your-country').val($.cookie('yourcountry'));
    }

    /**
     * Cookie to store user's selected your-country for the calling rates table.
     */
    if (!$.cookie('yourcountry_t')) {
        $.cookie('yourcountry_t', 'default', {path: '/'});
    } else {
        $('select#your-country').val($.cookie('yourcountry_t'));
    }
    /**
     * Cookie to store user's selected your-country.
     */
    if (!$.cookie('destinationcountry')) {
        $.cookie('destinationcountry', 'default', {path: '/'});
    } else {
        $('select#destination-country').val($.cookie('destinationcountry'));
    }

    /**
     * Rates ticker. Found at bottom of most pages.
     */
    /* Replace sample-rates list with animated info. bar. */
    $('#rates-ticker').each(function() {

        var title = $(this).find('dt.title').text();

        var rates = $(this).find('dd ul li').map(function() {
            var rate = new Object();
            rate.country = $(this).find('dl dt').html();
            rate.cost = $(this).find('dl dd').text();
            return rate;
        });

        var rates_length = rates.length;
        var i = 0; // Index for rates.

        var sample_rates_bar = '<div id="rates-ticker">'
            + '<h2><a href="/pc/rates">' + title + '</a></h2>'
            + '<span class="separator">|</span>'
            + '<ul><li class="rate"><span class="rate"><span class="inner">' + rates[i].country + ' - '
            + '<span class="rate-value">' + rates[i].cost + '</span></span></span></li></ul>'
            + '<div id="ticker-nav">'
            + '<a id="ticker-next" class="previous" title="Previous" href="#">Previous</a>'
            + '<a id="ticker-prev" class="next" title="Next" href="#">Next</a>'
            + '</div>'
            + '</div>';

        $(this).replaceWith(sample_rates_bar);

        $('#rates-ticker').each(function() {
            var previous = $(this).find('a.previous');
            var next = $(this).find('a.next');
            var rate = $(this).find('li.rate span.rate span.inner');

            var fader = function() {
                i++;
                i = i % rates_length;

                var rate_info = rates[i].country + ' - '
                    + '<span class="rate-value">' + rates[i].cost + '</span>'

                rate.fadeOut(1000, function() {
                    rate.html(rate_info); // Replace text with next rate.
                }).fadeIn(1000);
            }

            /* Replace the rate at set interval. */
            var interval = setInterval(fader, 5000);

            /* Replace rate on click previous. */
            previous.click(function() {
                i--;
                if (i < 0) i += rates_length;
                i = i % rates_length;

                var rate_txt = rates[i].country + ' - '
                + '<strong><span class="rate-value">' + rates[i].cost + '</span></strong>'

                rate.html(rate_txt); // Replace text with previous rate.
                clearInterval(interval);
                interval = setInterval(fader, 5000);
                return false;
            });

            /* Replace rate on click next. */
            next.click(function() {
                i++;
                i = i % rates_length;

                var rate_txt =  rates[i].country + ' - '
                + '<strong><span class="rate-value">' + rates[i].cost + '</span></strong>'

                rate.html(rate_txt); // Replace text with next rate.
                clearInterval(interval);
                interval = setInterval(fader, 5000);
                return false;
            });

        });
    });

    /**
     * Rates widget (found on rates page).
     */
    var update_rates = function() {

        your_country = $('#your-country option:selected').text();
        your_country_t = $('#your-country option:selected').val();
        destination_country = $('#destination-country option:selected').text()
        currency_symbol = $('#your-currency option:selected').val()

        $.cookie('currency', currency_symbol, {path: '/'});
        $.cookie('yourcountry', your_country, {path: '/'});
        $.cookie('yourcountry_t', your_country_t, {path: '/'});
        $.cookie('destinationcountry', destination_country, {path: '/'});

        if ($('#your-country').attr("selectedIndex") > 0 && $('#destination-country').attr("selectedIndex") > 0) {
            /* AJAX get returning rate data. Callback manipulates DOM */
            $.getJSON('/pc/rates/data?your_country=' + your_country +
                '&destination_country=' + destination_country +
                '&currency_symbol=' + currency_symbol, function(data){
                $('#rates').css('visibility', 'visible');
                $('#rate-instructions').hide();
                $('#rates').each(function() {
                    $(this).find('h2 span.your-country-name').text(data['your_country_name'] + ' ');
                    $(this).find('h2 span.destination-country-name').text(data['destination_country_name']);
                    $('table').each(function() {
                        $(this).find('td.landline-landline strong').text(data['landline_landline']);
                        $(this).find('td.landline-mobile strong').text(data['landline_mobile']);
                        $(this).find('td.mobile-landline strong').text(data['mobile_landline']);
                        $(this).find('td.mobile-mobile strong').text(data['mobile_mobile']);

                        $(this).find('td span.currency_code').text(currency_symbol);

                        if(data['text_text'] != '') {
                            $('#text-rate').show();
                            $('#text-rate-instructions').hide();
                            $(this).find('td.text-text strong').text(data['text_text']);
                        }
                        else {
                            $('#text-rate').hide();
                            $('#text-rate-instructions').show();
                        }
                    });
                });
            });
        }
    }

    /* Call/text rate component */
    $('#countries.widget').each(function() {

        /* Your country select event handling. */
        $('#your-country').change(update_rates);

        /* Destination country select event handling. */
        $('#destination-country').change(update_rates);

        /* Destination country select event handling. */
        $('#your-currency').change(update_rates);

        update_rates();
    });

    /**
     * Rates call table (found on 'Calling rates table' page).
     */
    var update_rates_call_table = function(your_country, your_currency) {

        var tbody = $('table#rates-call tbody');

        /* Replace the <tbody> nodes with a 'loading' message first. */
        tbody.html('<tr class="loading"><td colspan="5"><strong>Loading...</strong></td></tr>');

        /* AJAX get returning rates data. Callback updates data in the call rates table. */
        $.getJSON('/pc/rates/calltable/data?your_country=' + your_country + '&your_currency=' + your_currency, function(data){

            tbody.each(function() {

                var rows = ''; // This will store the table rows.

                for (var i in data) {
                    var rates_dict = data[i]

                    /* We use this for loop to get the country name (a key at the dict. root) */
                    for (var country in rates_dict); // rates_dict only has 1 attribute at root.
                    if (i % 2) { cls = "odd" } else { cls = "even" }
                    var row = '<tr class="'+cls+'">'
                        + '<td>' + country + '</td>'
                        + '<td>' + rates_dict[country]['landline_landline'] + '</td>'
                        + '<td>' + rates_dict[country]['landline_mobile'] + '</td>'
                        + '<td>' + rates_dict[country]['mobile_landline'] + '</td>'
                        + '<td>' + rates_dict[country]['mobile_mobile'] + '</td>'
                        + '</tr>';

                    rows += row;
                }

                $('span.currency_code').text(your_currency);

                tbody.html(rows); // Replace the 'loading' message here.

            });
        });
    }

    /* Change table data according to selected 'your-country' and 'your-currency' values */
    $('form#rate-changer-calltable').each(function() {
        var your_country = $.cookie('yourcountry_t'); // Default your-country. This gets changed by the SELECT#your-country event handler.
        var your_currency = $.cookie('currency'); // Default currency. This gets changed by the SELECT#your-currency event handler.

        /* Your country select event handling. */
        $('#your-country').change(function() {
            your_country = $(this).attr('value');
            $.cookie('yourcountry_t', your_country, {path: '/'});
            update_rates_call_table(your_country, your_currency);
        });

        /* Your currency select event handling. */
        $('#your-currency').change(function() {
            your_currency = $(this).attr('value');
            $.cookie('currency', your_currency, {path: '/'});
            if (your_country != 'default')
                update_rates_call_table(your_country, your_currency);
        });

        /**
         * At some point this should be refactored so we're not depending on the
         * default option text to see if the user has selected a valid country.
         */
        if ($.cookie('yourcountry_t') != '- Select country -' && $.cookie('currency')) {
            update_rates_call_table($.cookie('yourcountry_t'), $.cookie('currency'));
        }

    });

    /**
     * Rates currency handling for sms rates table.
     */
    var update_rates_sms_table = function(your_currency, callback) {

        var tbody = $('table#rates-sms tbody');

        /* Replace the <tbody> nodes with a 'loading' message first. */
        tbody.html('<tr class="loading"><td colspan="5"><strong>Loading...</strong></td></tr>');

        /* AJAX get returning rates data. Callback updates data in the call rates table. */
        $.getJSON('/pc/rates/smstable/data?your_currency=' + your_currency, function(data){

            var rows = ''; // This will store the table rows.

            for (var i in data) {
                var country_name = data[i]['country_name'];
                var value__min = data[i]['value__min'];
                if (i % 2) { cls = "odd" } else { cls = "even" }
                var row = '<tr class="'+cls+'">'
                    + '<td>' + country_name + '</td>'
                    + '<td>' + value__min + '</td>'
                    + '</tr>';

                rows += row;
            }

            tbody.html(rows); // Replace the 'loading' message here.

            $('span.currency_code').text(your_currency);

            if(callback) {
                callback();
            }
        });
    }

    var update_rates_sms_alternate_table = function(your_currency, callback) {

        var tbody = $('table#rates-sms-alternate tbody');

        /* Replace the <tbody> nodes with a 'loading' message first. */
        tbody.html('<tr class="loading"><td colspan="5"><strong>Loading...</strong></td></tr>');

        /* AJAX get returning rates data. Callback updates data in the call rates table. */
        $.getJSON('/pc/rates/smstable/alternate?your_currency=' + your_currency, function(data){

            var rows = ''; // This will store the table rows.

            for (var i in data) {
                var country_name = data[i]['country_name'];
                var network = data[i]['network'];
                var value = data[i]['value'];
                if (i % 2) { cls = "odd" } else { cls = "even" }
                var row = '<tr class="'+cls+'">'
                    + '<td>' + country_name + '</td>'
                    + '<td>' + network + '</td>'
                    + '<td>' + value + '</td>'
                    + '</tr>';

                rows += row;
            }

            tbody.html(rows); // Replace the 'loading' message here.

            $('span.currency_code').text(your_currency);

            if(callback) {
                callback();
            }
        });
    }

    $('form#rate-currencies-smstable').each(function() {
        var your_currency = $.cookie('currency');

        // The callback that calls the callback that executes the function to link to the anchor (if there is one)
        initial_callback = function() {
            update_rates_sms_alternate_table(your_currency, function() {
                if(jQuery.url.attr('anchor')) {
                    document.location.href = '#' + jQuery.url.attr('anchor');
                }
            });
        }

        update_rates_sms_table(your_currency, initial_callback); // Updates the sms rates tabe through DOM manipulation.

        /* Your country select event handling. */
        $('#your-currency').change(function() {
            var your_currency = $(this).attr('value');
            $.cookie('currency', your_currency, {path: '/'});
            update_rates_sms_table(your_currency); // Updates the sms rates tabe through DOM manipulation.
            update_rates_sms_alternate_table(your_currency); // UPdates the alternate SMS table
        });
    });

    /**
     * Make TDs in #nav act like A elements. Takes the href the A it contains.
     */
    $('table#nav td').not(".first").each(function() {
        $(this).click(function() {
            window.location = $(this).find('a').attr('href');
        });
    })

    /**
     * Toggle the visibility of #language-menu.
     */
    $('#select-language').toggle(
        function() {
            $(this).attr({'class':'open'});
            $('#language-menu').css({'visibility':'visible'});
        },
        function() {
            $(this).attr({'class':'closed'});
            $('#language-menu').css({'visibility':'hidden'});
        }
    );

    /**
     * Hide the #language-menu when <body> receives click event.
     */
    $('body').click(function() {
        /* We call the click event on #select-language to keep its toggle state. */
        if ($('#language-menu').css('visibility') == 'visible')
            $('#select-language').trigger('click');
    });

    /**
     * We don't let the click event propogate to <body> from #language-menu.
     * This prevents menu being closed when clicked.
     */
    $('#language-menu').click(function(e) {
        e.stopPropagation();
    });

    /**
     * Call change language method on item click.
     * TODO: This is to be refactored by A.S.
     */
    $('#language-menu ul').each(function() {

        var url = '/i18n/setlang/';
        if ($(this).hasClass('authenticated')) {
            url = '/pc/settings/language/';
        }
        var form_markup = '<form method="post"></form>';
        $(this).wrapInner(form_markup);
        var form = $(this).find('form');
        form.attr('action', url);
        form.append('<input id="languageInput" type="hidden" name="language"></input>');
        if ($(this).hasClass('authenticated')) {
            form.append('<input type="hidden" name="next" value="' + document.location.href +'"></input>');
            form.append('<input type="hidden" name="' + SESSION_COOKIE_NAME + '" value="' + SESSION_KEY +'"></input>');
        }
        var input = form.find('input#languageInput');
        $(this).find('li a').each(function() {
            $(this).click(function() {
                var value = $(this).attr('id');
                input.attr('value', value);
                form.submit();
                return false;
            });
        });
    });

    $(".howitworks #video").click(function() {
        $(this).find("a").each(function() {
            $(this).click(function(){ return false; });
        })

        window.open($(this).find("a").attr("href"));
    });
});

