var toSize=function (x) {
    if(x<1000) return x+'b'; 
    if(x<1000000) return Math.floor(x/1000)+'kb'; 
    var mb=Math.floor(x/1000)/1000;
    if (mb%1>0) mb=mb.toFixed(2); 
    return mb+'mb';
};
var tabs_cur;
var tabs_idx;
var tabs_cache;

$(function() {
        var tabs;
        var formcheck;
        var file;
        $.tablesorter.addParser(
            {
                id: 'position',
                is: function(s) {return s;},
                format: function(s) {
                        return parseInt(s.split(" ")[0]);
                }, 
                type: 'numeric'
            })
        var display_shot = function(site,shot) {
                var html = "<ul class='resultlist'>"
                var is_200 = false;
                var h,w;
                for (var key in shot) {
                    if (shot[key].resolution[0] == 200 || shot[key].resolution[1] == 200) is_200 = true;
                    if (!is_200 && shot[key].type == 'normal') {
                        if(shot[key].resolution[1] > shot[key].resolution[0]) {
                            h=Math.ceil(shot[key].resolution[0]/shot[key].resolution[1]*200);
                            w=200;
                        } else {
                            w=Math.ceil(shot[key].resolution[1]/shot[key].resolution[0]*200);
                            h=200;
                        }
                    }
                    html+='<li name="'+shot[key].link+'"> '+shot[key].type+' - '+shot[key].resolution[0]+'x'+shot[key].resolution[1]+', size — '+toSize(shot[key].size);
                }
                if (!is_200) {
                    html+='<li name="/browsershot/size/200/'+site+'"> resize - '+h+'x'+w+', size — ???';
                }
                html+="</ul>"

                $("#shot #result #list").html(html);
                $("#shot #result #link").html("http://"+window.location.host+"/browsershot.html#"+site);
                $("#shot #result img").attr('src',"/browsershot/size/200/"+site);
                $("#shot #result #img_link").html("http://"+document.location.host+"/browsershot/size/200/"+site);
                $("#shot #result >> ul > li").css("cursor","pointer").click(function() {
                        $("#shot #result img").attr("src",$(this).attr("name"));
                        $("#shot #result #img_link").html("http://"+document.location.host+$(this).attr("name"));
                });
                $("#shot #result").show('slow');

        }

        //вывод результата работы мистема
        var display_mystem = function(cur,to) {
            tabs_cache={}
            tabs_idx=0;
            tabs_cur=cur;
            $("#table").empty();
            var res = cur["result"];
            var hash = cur["hash"];
            var html = "";
            $("#mystem #result #link").html("http://"+document.location.host+document.location.pathname+document.location.search+"#"+hash);
            document.location.hash=hash;
            $("#mystem textarea").val(cur["org"]);
            var html = "<table><thead>";
            html += "<tr><th rowspan=2>#</th><th rowspan=2>сайты</th><th colspan=2>размер текста</th><th colspan=2>всего вхождений</th><th colspan=2>точных вхождений</th><th colspan=2>словоформ</th><th rowspan=2>zipf</th></tr>";
            html += "<tr><th>слов</th><th>знаков</th><th>кол-во</th><th>плотность</th><th>кол-во</th><th>плотность</th><th>кол-во</th><th>плотность</th></tr>";
            html +="</thead><tbody>";
            var idx=1;
            
            for (var key in res) {
                var stat = res[key].stat;
                var fetched=false;
                
                html+='<tr>';
                try {
                    var pos=0;
                    if(cur["task"]["yandex"]) {
                        pos = cur["task"]["yandex"].indexOf(cur['text2url']['yandex'][key])+1;

                    }
                    html+='<td>'+(pos?pos:'')+'</td>';

                    if(!pos) fetched=true;
                } catch(err) {
                    fetched=true;
                    html+='<td></td>';
                }
                html+='<td class='+(fetched?"list_fetched":"list_se")+' style="'+(res[key]["error"]?";color:red":"")+'"><a group="tab" href="#mtab'+idx+'">'+key+'</a></td>';
                for (var i in stat) {
                    if(i%2 && i>2 && stat[i].length > 1) {
                        stat[i]=stat[i].map(function(x) {return x.toFixed(2)+'%'})
                    }
                    html+='<td>'+stat[i].join("-")+'</td>';
                }
                html+='</tr>';
                idx++;
            }
            html += '</tbody>';
            if(idx > 2) {
                html +='<tfoot>';
                html += '<tr><td colspan=11>&nbsp;</td></tr><tr><td></td><th>МАКСИМУМ:</th>';
                for (var i in cur.stat.max) {
                    if(i%2 && i>2 && cur.stat.max[i].length > 1) cur.stat.max[i]=cur.stat.max[i].map(function(x) {return x.toFixed(2)+'%'});
                    html+='<td>'+cur.stat.max[i].join("-")+'</td>';
                }
                html += '</tr>';
                html += '<tr><td></td><th>В СРЕДНЕМ:</th>';
                for (var i in cur.stat.avg) {
                    if(i%2 && i>2 && cur.stat.avg[i].length > 1) cur.stat.avg[i]=cur.stat.avg[i].map(function(x) {return x.toFixed(2)+'%'});
                    html +='<td>'+cur.stat.avg[i].join("-")+'</td>';
                }
                html += '</tr><tr><td></td><th>МИНИМУМ:</th>';
                for (var i in cur.stat.min) {
                    if(i%2 && i>2 && cur.stat.min[i].length > 1) cur.stat.min[i]=cur.stat.min[i].map(function(x) {return x.toFixed(2)+'%'});
                    html+='<td>'+cur.stat.min[i].join("-")+'</td>';
                }
                html += '</tr>';
                html += '</tfoot>'
            }
            html += '</table>';
            $("#mystem #result #tabs").html(html);
            var draw = function(key) {
                var html="";
                if(!tabs_cache[key]) {
                    tabs_idx++;
                    tabs_cache[key]=tabs_idx;
                    idx=tabs_idx;
                    var cur = tabs_cur;
                    var res=cur["result"][key];
                    if (res["error"]) {
                        html += "<div style='display:none' class='tab' id='mtab"+idx+"'>При загрузки произошла ошибка — <span style='color:red'>"+res["error"]+"</span></div>";
                    } else {
                        html += "<div style='display:none' class='tab' id='mtab"+idx+"'>";
                        html += "<table class='words_result'><thead><tr><th>#</th><th>Слово</th><th class=\"{sorter:'position'}\">Всего</th>";
                        var tags=["plain"];
                        var words={};
                        for(var tag in res) {
                            if(tag != "stat" && tag != "plain") {
                                html += "<th class=\"{sorter:'position'}\">"+tag+"</th>";
                                tags.push(tag);

                            }
                            var tmp = res[tag]["words"];
                            for(var word in tmp) {
                                if(!words[word]) words[word]={};
                                words[word][tag]='<span class="table_count">'+tmp[word].count+'</span><span class="table_procent"><sup style="color:green">'+tmp[word].procent+'%</sup></span>';
                                if(tag == "plain") {
                                    words[word]["range"]='<span class="table_range">'+tmp[word].pos+'</span>';
                                    words[word]["zipf"]='<span class="table_zipf">'+tmp[word].zipf+'</span>';
                                }
                            }
                        }
                        html += '<th>zipf</th></tr></thead><tbody>';
                        for(var word in words) {
                            html += '<tr>';
                            html += '<td>'+words[word].range+'</td>';
                            html += '<td>'+word+'</td>';
                            for(var tag in tags) {
                                tag=tags[tag];
                                html += '<td>'+(words[word][tag]?words[word][tag]:0)+'</td>';
                            }
                            html += '<td>'+words[word].zipf+'</td>';
                            html += '</tr>';
                        }
                        html += '</tbody><thead><tr class="itogo"><th></th><th>Итого</th>';
                        for(var tag in tags) {
                            tag=tags[tag];
                            html += '<th>'+res[tag].count[0]+'</th>';
                        }
                        html += '<th>'+res.stat[8]+'</th>';
                        html += "</tr></thead>";
                        html += "</table></div>";
                    }
                    $("#mystem #result #table").append(html);
                    $("#mystem #result #table > div[id=mtab"+idx+"] > table > thead > tr > th").css("cursor","pointer");
                    $("#mystem #result #table > div[id=mtab"+idx+"] > table").tablesorter({ sortList:[[0,0]] });
                    
                }
                return tabs_cache[key];
                
            }


            if(cur["task"]["query_org"]) {
                $("#mystem #result #req").html(cur["task"]["query_org"]);
                $("#mystem #result #se").show();
            } else {
                $("#mystem #result #se").hide();
            }
            
            $("#mystem #result #tabs > table > tbody > tr > td > a").click( function() {
                    var id = draw($(this).text());
                    var group = $(this).attr( "group" );
                    $("."+group).hide(); 
                    $('#mtab'+id).show();
                    $("#mystem #result #tabs > table > tbody > tr > td > a").attr("class","tab-hide");
                    $(this).attr("class","tab-show");
                    return false;
            } );
            $("#mystem #result #tabs  table").tablesorter({ sortList:[[0,0]] });
            $("#mystem #result #tabs > table > tbody > tr > td > a:eq(0)").click();
            $("#mystem #result").show('slow');

        }




        var success_mystem = function(cur) {
            $("#mystem #error").hide();
            $("#mystem #notice").hide();
            $("#mystem #startup").hide();
            $("#mystem #result").hide();
            var count = 0;
            for (var key in cur ) { count+=1; }
            if(cur["try"]) {
                $("#mystem #notice > span").html("Ваш запрос поставлен в очередь");
                $("#mystem #notice").show();
                setTimeout(function() {
                        $("#mystem #notice > span").html("проверка готовности");
                        $("#mystem #notice").show();
                        $.ajax(
                            {
                                type: "GET",
                                url:"/mystem/"+cur["try"]+".js?" + (Math.random()*10000000000000000),
                                dataType: 'json',
                                async:true,
                                success:success_mystem
                            }
                        );
                },1000);
            } else if (cur["error"] && count == 1)  {
                $("#mystem #error > span").html(cur["error"]);
                $("#mystem #error").show();
            } else {
                display_mystem(cur);
            }
        }

        $('#mystem').submit(function() {
                $(this).find("#error,#notice,#startup,#result").hide();
                $(this).find("#notice > span").html("отправка запроса");
                $(this).find("#notice").show();
                $.ajax({type: "POST",url:"/mystem/",dataType: 'json',data: $(this).serializeArray(),async:true,success:success_mystem});
                return false;
        });



        $('#shot').submit(function() {
                
                var site = $(this).find("input").val().replace("http://","");
                document.location.hash=site;
                var url = "/browsershot/json/"+site;
                var tryLoad = 0;
                var success = function(cur) {
                    tryLoad+=1;
                    if(tryLoad == 10) {
                        cur.error="ошибка загрузки. превышено время ожидания.";
                    }
                    $("#shot > div > div").hide()
                    if(cur.length>0) {
                        display_shot(site,cur);
                    } else if (cur["error"])  {
                        $("#shot #error > span").html(cur["error"]);
                        $("#shot #error").show();
                    } else {
                        $("#shot #notice > span").html("Ваш запрос поставлен в очередь.");
                        $("#shot #notice").show();
                        setTimeout(function() {
                            $("#shot #notice > span").html("отправка запроса");
                            $("#shot #notice").show();
                            $.ajax({type: "GET",url:url,dataType: 'json',async:true,success:success});
                        },1000);
                    }
                }
                success([]);
            return false;
        });


        if(window.displaySite) {
            $('#shot').find("input[@type='text']").val(window.displaySite);
            $('#shot').submit();
        }

        if(window.displayMystem) {
            success_mystem({"try":window.displayMystem});
        }


        if(window.displayTOP10) {
            success_top10({"try":window.displayTOP10});
        }


});



