$(document).ready(function(){
    
    // Focus fields with validation errors
    $('div.fieldWithErrors :input').focus();

    // Expanding shortened strings in test log (very long parameters or return values)
    $('div.contained-lines').each( function () {
        var toggle = document.createElement("div");
        $(toggle).append("More...")
        $(toggle).addClass("toggle-contained")

        if (toggle.nextSibling)
            this.parentNode.insertBefore(toggle, this.nextSibling)
        else
            this.parentNode.appendChild(toggle)

        $(toggle).bind("click", {div: this}, function (event) {
            if ($(event.data.div).hasClass("shown")) {
                $(event.data.div).removeClass("shown")
                this.innerHTML = "More..."
            } else {
                $(event.data.div).addClass("shown")
                this.innerHTML = "Less..."
            }
        });
    });

    // Show and hide stdout from test run
    $('ul.recent-runs li').click(function(event) {
        $(this).children('.output').slideToggle(200);
    });
    $('ul.recent-runs a').click(function(event) {
        event.stopPropagation();
    });

    // Sidebar file browser: fill elements clickable
    $('ul.file-status li').click(function(event) {
        window.location.href = $(this).children('a').attr('href');
        return false;
    });

    $('ul.file-status li .status a').click(function(event) {
        event.stopPropagation();
    });

    $('a.feedback').click(function(event) {
        var container = $(this).siblings("div")[0];
        $(container).toggle('normal').find("p:first").html("We'd like to hear about any issues you encounter while using Go Test It.").removeClass("error");
      
        $(this).siblings("div").find("form").submit(function () {
            $.ajax({
                type: 'POST',
                dataType: 'json',
                url: this.action,
                data: "contents=" + encodeURIComponent($('textarea', this).val()) + 
                      "&authenticity_token=" + encodeURIComponent($('input', this).val()) +
                      "&format=json",
                success: function (res) { 
                    if (res.status == "OK")
                    {
                        $(container).siblings('a').html("Thank you for your comments")
                        $(container).hide('normal')
                    } else {
                        $("p:first", container).html(res.message).addClass("error")
                    }
                },
                error: function (res) { $("p:first", container).html(res.statusText).addClass("error");}
            });
            event.preventDefault();
            return false;
        }).find("button[name=cancel]").click(function (event) {
            $(container).hide('normal');
            event.preventDefault();
            event.stopPropagation();
            return false;
        });
        event.preventDefault();
    });


    var dismissable = !document.getElementById('reopen-script-recorder-button');
    // on a customer site, when not using firefox, show a dismissable warning
    if (window.page_info && window.page_info.customer_subdomain) {
      if ( (!$.browser.mozilla) && ((!dismissable) || (getCookie('firefox_banner') != 'hide') || 
             ($('#flashNotice, #flashError, #recorder-not-installed').length > 0)
         )  ) {
        $('div.container').prepend(
            '<div id="flashNotice" class="error">We recommend you use ' +
            '<a href="http://www.mozilla.com/">Firefox</a>' +
            ' with the <a href="/recorder">Go-Test Recorder</a> installed to edit test scripts.' + 
            (dismissable ? '&nbsp; <span class="dismiss">(<a href="#">dismiss</a>)</span></div>' : '')
        );
        $('#flashNotice .dismiss a').click(function (event) {
            $('#flashNotice').hide();
            setCookie('firefox_banner', 'hide');
            event.stopPropagation();
            event.preventDefault();
        });
      }
    }

    // Front page of marketing site: clickable boxes
    $('#recorderBox, #browserBox, #hostedBox, #scriptingBox').click(function(event) {
        window.location.href = $(this).children('h3').children('a').attr('href');
        return false;
    });

    // Front page of marketing site: overlay screencast
    $("#screencastTrigger a[rel]").overlay({expose: '#000', effect: 'apple'});
});


function setCookie(cookieName, cookieValue) {
    var today = new Date();
    var expire = new Date();
    expire.setTime( today.getTime() + (1000 * 60 * 60 * 24 * 365) );
    document.cookie = cookieName + "=" + escape(cookieValue)
                    + ";path=/" + ";expires="+expire.toGMTString();
}
function getCookie(cookieName) {
     var start = document.cookie.indexOf( cookieName + "=" );
     if ( start == -1 ) return "";
     var len = start + cookieName.length + 1;
     if ( ( !start ) &&
       ( cookieName != document.cookie.substring( 0, cookieName.length ) ) )
         {
           return "";
         }
     var end = document.cookie.indexOf( ";", len );
     if ( end == -1 ) end = document.cookie.length;
     return unescape( document.cookie.substring( len, end ) );
}
// TODO: Only looking at the begining of the string fails for gotest and selenese

function detect_format(text) {
  
    text = text.replace(/^[\s\r\n]*/,"");

    if (!text)
        return null;

    // Only "{" is correct, but the others might be mistakes
    if ("{[\"'".indexOf(text.charAt(0)) > -1)
        return "gti";

    // Onle "<" is correct, but maybe they missed it out
    if (text.charAt(0) == "<" || {html:1,head:1,link:1,title:1,body:1,table:1,tr:1,th:1,td:1,thead:1,tbody:1}[text.match(/^[a-z]*/i)[0].toLowerCase()])
        return "html";

    if (text.match(/^#![a-z\/]+python/i) || 
        text.match(/^ *from +[a-z0-9\._]+ +import +/im) || 
        text.match(/^ *import +[a-z0-9\._]+/im) ||
        text.match(/^ *\b(class|def|if|elif|try|except|finally|while|for)\b[^:\n\?]+:$/im))
        return "py";

    if (text.match(/^#![a-z\/]+ruby/i) ||
        text.match(/^ *require *['"]/im) ||
        text.match(/(\{ *\||\bdo *\|)/) ||
        text.match(/^ *end *$/) )
        return "rb";

    return null;
}


$(function guessEditPageFilename() {


    if ($('#test_script_name').length == 0)
        return;

    var test_script_name = $('#test_script_name')[0];
    var previous_ending = test_script_name.value.indexOf(".") > 0 ? test_script_name.value.substr(test_script_name.value.lastIndexOf(".") + 1) : null;
    var chosen_ending;
    var guessed_ending;

    function set_guess () {
      if(test_script_name.value)
          test_script_name.value = test_script_name.value.replace(/(\.(js|html|gti|rb|py|.{2,4}))?$/, (previous_ending ? ("." + previous_ending) : ""));
      $('ul.note li.selected').removeClass('selected');
      if (previous_ending)
          $('ul.note li.' + previous_ending).addClass('selected');
    }
    function update_guess () {

        if (chosen_ending) {
            if (guessed_ending == chosen_ending) {
                chosen_ending = null;
            } else if (previous_ending == chosen_ending) {
                return;
            } else {
                previous_ending = chosen_ending;
                return set_guess();
            }
        }

        if (guessed_ending) {
            
          if (previous_ending != guessed_ending) {
              previous_ending = guessed_ending;
              return set_guess(); 
          }

        }

    }
    set_guess();

    $(test_script_name).change(function () {

        chosen_ending = previous_ending = null;
        this.value.replace(/\.(js|gti|html|py|rb|.{2,4})$/, function(m, ending) {
            chosen_ending = ending;
        });

        update_guess();

    });

    var guessInterval = setInterval(function () {

        guessed_ending = detect_format($('#test_script_contents').val());

        update_guess();

    }, 1000);

});
