/**
 * All JS relating to the front page page should go into this file.
 */

var auto_creator = null,
    errorbox = null,
    map = null,
    map_animator = null,
    freetest_dialog = null;

$(document).ready(function() {
    // Setup map.
    map = new LI.Map('map', {
        'init': function() {
            map_animator.start();
        },
        'center_lat': 20.0
    });
    map_animator = new LI.MapAnimator(map, {});

    // Setup free test auto creator.
    auto_creator = new LI.TestAutoCreator(CSRF_TOKEN, {
            error: function(msg) {
                freetest_dialog.dialog.qtip('api').hide();
                $('#autogen-status').hide();
                $('#freetest-url').removeAttr('disabled');
                $('#freetest-run-test-button').show();
                if (msg) {
                    $('#freetest-url').errortip({ 
                        content: msg,
                        position: {
                            my: 'top center',
                            at: 'bottom center',
                            adjust: {
                                y: -10
                            }
                        },
                        hide: {
                            event: 'unfocus',
                            delay: 100,
                            effect: function(offset) {
                                $(this).fadeOut();
                            }
                        }
                    });
                }
            },
            only_create_user_scenario: true,
            success: function(name, user_scenario_id) {

                $.getJSON('/test/user-scenario/start-freetest/'
                        + user_scenario_id + '/?url='
                        + encodeURIComponent($('#freetest-url').val()),
                        function(data) {
                            if (data.result == 'ok' && data.id)
                            {
                                window.location = '/test/view/' + data.id; 
                            }
                            else if (data.result == 'error')
                            {
                                freetest_dialog.dialog.qtip('api').hide();
                                $('#freetest-url').errortip({ 
                                    content: data.message,
                                    position: {
                                        my: 'top center',
                                        at: 'bottom center',
                                        adjust: {
                                            y: -10
                                        }
                                    },
                                    hide: {
                                        event: 'unfocus',
                                        delay: 100,
                                        effect: function(offset) {
                                            $(this).fadeOut();
                                        }
                                    }
                                });  
                            }

                            $('#autogen-status').hide();
                            $('#freetest-url').removeAttr('disabled');
                            $('#freetest-run-test-button').show();
                        }
                );
            }
        });

    // Setup errorbox.
    errorbox = new LI.ErrorBox('errorbox');

    // Setup event handlers.
    $('#freetest-run-test-button').click(function() {
        freetest_dialog = new LI.Dialogs.FreetestDialog(
              '<br />Note that free tests are published on our web page for all to see.<br />'
            + '<a href="/account/register/">Register a free account</a> to make test results private.'
            + '<div class="hidden" id="pick-a-freetest-holder"><span class="pick-a-freetest-header">There are many tests running right now, but you can still queue your test. Estimated queue time is currently <span id="queue-wait-time">0</span> minute(s). If you want instant action, you might want to look at a currently running test instead:</span></div>',
        { 
            title: 'Start a free load test',
            callback: function(confirmed) {
            }
        }); 

        return false;
    }).tooltip('index_freetest_run_test');
    $('#freetest-url').keyup(function(e) {
        if (13 == e.which) {
            $('#freetest-run-test-button').trigger('click');
            e.preventDefault();
            $('#freetest-url').blur();
        }
    }).tooltip('index_freetest_url');

    // Check for query param url, used to support old queuetest.php
    if (location.search != '')
    {
        var res = null;
        if ((res = location.search.match(new RegExp("^\\\?url=(.*?)$"))) != null)
        {
            $('input[name="freetest-url"]').val(res[1]);
            $('#freetest-run-test-button').click();
        }
    }

    // Fetch some fun stats.
    $.getJSON('/statistics/frontpage/', function(data) {
        var tests = '';
        if (data)
        {
            $.each(data.current_running_locations, function(key, test) {
                var host = test.url.split(/\/+/g)[1];
                if (test.id == undefined)
                {
                    test.id = Math.random(new Date().getTime());
                }

                map.add_marker('test_' + test.id, test.latitude, test.longitude, {
                    'image': '/static/images/target.png',
                    'click': function (e) {
                        var host = test.url.split(/\/+/g)[1];
                        window.location = '/load-test/' + host + '-' + test.public_id;
                    },
                    'tooltip': host
                });

                $.each(test.loadzones, function(k, lz) {
                    if (map.get_marker_from_name(lz.identifier) == undefined)
                    {
                        map.add_marker(lz.identifier, lz.latitude, lz.longitude, { 'tooltip': lz.title });
                    }
                    map_animator.add_line_between_markers('line_' + lz.identifier + '_test_' + test.id,
                                                            lz.identifier, 'test_' + test.id, {});
                });
            });
        }
    });

    $('#watch-live-btn').click(function(e) {
        $.getJSON('/test/list-freetests/', function(data) {
            if (data[0] != undefined && data[0].url && data[0].public_id)
            {
                if (data[0].status != 2)
                {
                    // hmmm, not running
                }
                var host = data[0].url.split(/\/+/g)[1];
                window.location = '/load-test/' + host + '-' + data[0].public_id;
            }
        });
        $(e.target).hide();
        $(e.target).next().show();
        return false;
    });

    $('.screenshot_holder .screenshot').click(function(e) {
        var youtube = '<iframe id="youtube-vid" width="502" height="370" src="'
            + 'http://www.youtube.com/embed/CkGuBONAXLE?rel=0&amp;hd=1&amp;autoplay=1&amp;autohide=1&amp;modestbranding=1'
            + '" frameborder="0" allowfullscreen></iframe>';
        $(e.target).parent().css('background', 'none');
        $(e.target).replaceWith(youtube);
        $('#youtube-vid').css('margin-bottom', '10px');
    });

    // Lazy load the Google Maps API.
    var s = document.createElement("script");
    s.type = "text/javascript";
    s.src  = "http://maps.google.com/maps/api/js?v=3&libraries=geometry&sensor=false&callback=map.init";
    $("head").append(s);

});

