// google.load("language", "1");

function init(){
    var src = document.getElementById("src");
    var dst = document.getElementById("dst");
    var i = 0;
    for (l in google.language.Languages) {
        var lng = l.toLowerCase();
        var lngCode = google.language.Languages[l];
        if (google.language.isTranslatable(lngCode)) {
            src.options.add(new Option(lng, lngCode));
            dst.options.add(new Option(lng, lngCode));
        }
    }
}

// JavaScript Document
jQuery(document).ready(function(){

	jQuery("input[name='language']").each(function() {
		if ($(this).attr('userlanguage') == $(this).val()) {
		  $(this).attr("checked", true);
		}
  	});

    jQuery("span[id='keyword']").click(function(){
        jQuery("input[name='keyword']").val($(this).html());
        jQuery("form[name='keyword_form']").submit();
    });
    
    jQuery("span[id='search_reference']").click(function(){
        jQuery("input[name='searchword']").val($(this).html());
        jQuery("form[name='reference_form']").submit();
    });
    
    jQuery("span[id='search_background']").click(function(){
        jQuery("input[name='background']").val($(this).html());
        jQuery("form[name='background_form']").submit();
    });
    
    jQuery("span[id='Testjudge']").click(function(){
        $dialog = $("#Testjudge_dialog").dialog({
            disabled: true,
            autoOpen: false,
            width: '80%',
            title: '請貼上您要測試的程式碼以及測試資料',
            close: function(event, ui){
                $(this).dialog("destroy");
            },
            buttons: {
                "結束": function(){
                    $(this).dialog("close");
                },
                "測試執行": function(){
                    //$(this).dialog("close");
                    // IndataDialog();
                    doTestjudge();
                }
            }
        });
        $dialog.dialog('open');
        return true;
    });
    
    jQuery("span[id='background']").click(function(){
        var index = jQuery("span[id='background']").index(this);
        var background = jQuery("span[id='background']:eq(" + index + ")").text();
        var backgrounds = jQuery("input[name='background']").val();
        if (backgrounds == '') {
            backgrounds += background;
            //            jQuery("input[name='background']").val(background);
        }
        else {
            backgrounds += "," + background;
        }
        jQuery("input[name='background']").val(backgrounds);
    });
    jQuery("span[id='clean_background']").click(function(){
        jQuery("input[name='background']").val("");
    });
    
    jQuery("span[id='img_ProblemSettings']").click(function(){
        var problemid = $(this).attr("problemid");
        var title = $(this).attr("title");
        jQuery.ajax({
            type: "GET",
            url: "Problem.ajax",
            data: "action=getProblemSettings&problemid=" + problemid,
            async: false,
            timeout: 5000,
            success: function(result){
                var json_ProblemSettings = JSON.parse(result);
                jQuery("input[name='tabid']").each(function(){
                    if (json_ProblemSettings.tabid == $(this).val()) {
                        $(this).attr("checked", true);
                    }
                });
                jQuery("input[name='difficulty']").each(function(){
                    if (json_ProblemSettings.difficulty == $(this).val()) {
                        $(this).attr("checked", true);
                    }
                });
                jQuery("input[name='background']").val(json_ProblemSettings.background);
                jQuery("input[name='keywords']").val(json_ProblemSettings.keywords);
                jQuery("input[name='sortable']").val(json_ProblemSettings.sortable);
            }
        }); // jQuery ajax
        var $dialog = $("#ProblemSettings_dialog").dialog({
            autoOpen: false,
            width: '60%',
            title: problemid + ': ' + title,
            close: function(){
                $(this).dialog("destroy");
            },
            buttons: {
                "取消": function(){
                    $(this).dialog("destroy");
                },
                "設定": function(){
                    jQuery.ajax({
                        type: "POST",
                        url: "Problem.ajax",
                        data: "action=setProblemSettings&problemid=" + problemid + "&" + $("form[name='ProblemSettings_form']").serialize(),
                        async: false,
                        timeout: 5000,
                        success: function(result){
                        }
                    }); // jQuery ajax
                    //location.replace(location.href);
                    //history.go(-1);
                    $(this).dialog("destroy");
                    location.reload();
                }
            }
        });
        
        $dialog.dialog('open');
        return false;
    });
    
    
    jQuery("a[id='translate']").bind('click', function(){
        var from = jQuery("a[id='translate'] span").attr('id');
        var to = jQuery("a[id='translate'] span").attr('name');
        from = from.replace("_", "-");
        to = to.replace("_", "-");
        google.setOnLoadCallback(init);
        jQuery("#problem_title").html(translate(from, to, jQuery("#problem_title")));
        jQuery("#problem_content").html(translate(from, to, jQuery("#problem_content")));
        jQuery("#problem_theinput").html(translate(from, to, jQuery("#problem_theinput")));
        jQuery("#problem_theoutput").html(translate(from, to, jQuery("#problem_theoutput")));
        jQuery("#problem_hint").html(translate(from, to, jQuery("#problem_hint")));
        
        //jQuery("#problem_title").html(translate(from, to, jQuery("#problem_title").text()));
        //jQuery("#problem_content").html(translate(from, to, jQuery("#problem_content").html()));
        //jQuery("#problem_theinput").html(translate(from, to, jQuery("#problem_theinput").text()));
        //jQuery("#problem_theoutput").html(translate(from, to, jQuery("#problem_theoutput").text()));
        //jQuery("#problem_hint").html(translate(from, to, jQuery("#problem_hint").text()));
    });
    
});

function translate(from, to, jQueryObject){
    var returndata;
    google.language.translate(jQueryObject.html(), from, to, function(result){
        if (result.translation) {
            returndata = result.translation;
            jQueryObject.html(result.translation);
        }
        else {
            returndata = "ERROR translation from" + from + " to " + to;
            jQueryObject.html("ERROR translation from" + from + " to " + to);
        }
    });
    return returndata;
}

function doTestjudge(){

    $dialog3 = $("#showdetail_dialog").dialog({
        autoOpen: false,
        width: '60%',
        title: '測試執行結果',
        close: function(event, ui){
            //$(this).dialog("destroy");
            //location.reload();
        },
        buttons: {
            "返回": function(){
                $(this).dialog("close");
            }
        }
    });
    
    jQuery.ajax({
        type: "POST",
        url: "./Testjudge",
        data: $('#form_Testjudge').serialize(),
        async: true,
        timeout: 5000,
        beforeSend: function(){
            jQuery("#showdetail_dialog #spinner").show();
            jQuery("div[id=jsondetail]").hide();
            $dialog3.dialog("open");
        },
        success: function(result){
            var outputs = JSON.parse(result);
            if (outputs[0].solutionid != 0) {
                getStatusinfo(outputs[0].solutionid);
            }
            else {
                jQuery("#showdetail_dialog #spinner").hide();
                var jsondetail = jQuery("div[id='jsondetail']");
                jsondetail.show();
                jsondetail.children("#judgement").removeClass("acstyle").html(outputs[0].judgement);
                //jsondetail.children("#judgement").html(outputs[0].judgement);
                jsondetail.children("#info").html(outputs[0].info);
                jsondetail.children("#reason").html(outputs[0].reason);
                jsondetail.children("#hint").html(outputs[0].hint);
            }
        }
    });
    return false;
}

var jsondetails_string;

function getStatusinfo(solutionid){
    var it;
    it = jQuery.interval(function(){
        jQuery.ajax({
            type: "POST",
            url: "./Solution.ajax",
            data: "action=getStatusinfo&solutionid=" + solutionid,
            async: false,
            //cache: false,
            timeout: 5000,
            success: function(result){
                var statusinfo = JSON.parse(result);
                if (statusinfo.verdict == "Waiting...") {
                }
                else {
                    jQuery.clear(it);
                    jQuery("#showdetail_dialog #spinner").hide();
                    getJsondetails(solutionid);
                    //alert(jsondetails_string);
                    while (jQuery("div[id=jsondetail]").length > 1) {
                        jQuery("div[id=jsondetail]:last").remove();
                    }
                    //alert(result);
                    var jsondetails = JSON.parse(jsondetails_string);
                    if (jsondetails.length == 1) {
                        jQuery("div[id=jsondetail]:last span[id=line1]").hide();
                    }
                    else {
                        jQuery("div[id=jsondetail]:last span[id=line1]").show();
                    }
                    
                    for (var i = 0; i < jsondetails.length && jsondetails[i] != null; i++) {
                        if (jQuery("div[id=jsondetail]").length < i + 1) {
                            jQuery("div[id=jsondetail]:last").clone(true).insertAfter(jQuery("div[id=jsondetail]:last"));
                        }
                        jQuery("div[id=jsondetail]:last").show();
                        jQuery("div[id=jsondetail]:last span[id=testlength]").text(i + 1);
                        jQuery("div[id=jsondetail]:last span[id=score]").text(jsondetails[i].score + "%");
                        
                        if (jsondetails[i].judgement == "AC") {
                            jQuery("div[id=jsondetail]:last span[id=judgement]").addClass("acstyle").text(jsondetails[i].judgement);
                        }
                        else {
                            jQuery("div[id=jsondetail]:last span[id=judgement]").removeClass("acstyle").text(jsondetails[i].judgement);
                        }
                        jQuery("div[id=jsondetail]:last span[id=info]").text("(" + jsondetails[i].info + ")");
                        jQuery("div[id=jsondetail]:last span[id=reason]").text(jsondetails[i].reason);
                        jQuery("div[id=jsondetail]:last pre[id=hint]").text(jsondetails[i].hint);
                        jQuery("div[id=jsondetail]").show();
                    }
                    return;
                }
            }
        }); // jQuery ajax
    }, 1000);
}

function getJsondetails(solutionid){
    jQuery.ajax({
        type: "POST",
        url: "./Solution.ajax",
        data: "action=getJsondetails&solutionid=" + solutionid,
        async: false,
        //cache: false,
        timeout: 5000,
        success: function(result){
            //			alert(result);
            jsondetails_string = result;
            return;
        }
    });
    
}

