﻿;
var errorReporter = (function(){

    function getSelectionEx(o){
        var d = window.document
        var extn = 60
        var maxtxtlen = 100
        try{
	        var txt=null;
	        var sel=null;
	        if(window.getSelection){ // Not IE
		        sel=window.getSelection();
	        }else{ // IE
		        if(d.getSelection){
			        sel=d.getSelection();
		        }else{
			        sel=d.selection;
		        }
	        }
	        if(sel!=null){
		        var pre="",txt=null,suf="";
		        if(sel.getRangeAt){
			        var r=sel.getRangeAt(0);
			        txt=r.toString();
			        var r2=d.createRange();
			        r2.setStartBefore(r.startContainer.ownerDocument.body);
			        r2.setEnd(r.startContainer,r.startOffset);
			        pre=r2.toString();
			        var r3=r.cloneRange();
			        r3.setStart(r.endContainer,r.endOffset);
			        r3.setEndAfter(r.endContainer.ownerDocument.body);
			        suf=r3.toString();
		        }else{
			        if(sel.createRange){
				        var r=sel.createRange();
				        txt=r.text;
				        var r2=sel.createRange();
				        r2.moveStart("character",-extn);
				        r2.moveEnd("character",-txt.length);
				        pre=r2.text;
				        var r3=sel.createRange();
				        r3.moveEnd("character",extn);
				        r3.moveStart("character",txt.length);
				        suf=r3.text;
			        }else{
				        txt=""+sel;
			        }
		        }
		        var p;
		        var s=(p=txt.match(/^(\s*)/))&&p[0].length; // пробелы в начале - их в префикс
		        var e=(p=txt.match(/(\s*)$/))&&p[0].length; // пробелы в конце - их в суффикс
		        pre=pre+txt.substring(0,s);
		        suf=txt.substring(txt.length-e,txt.length)+suf;
		        txt=txt.substring(s,txt.length-e);
    		    
		        pre = pre.replace(/[\r\n]+/g," ").replace(/^\s+/g,"").replace(/\s{2,}/g,' ');   // удаляем переносы строк, и длинные последовательности пробелов
		        suf = suf.replace(/[\r\n]+/g," ").replace(/\s+$/g,"").replace(/\s{2,}/g,' ');
		        txt = txt.replace(/[\r\n]+/g," ").replace(/\s{2,}/g,' ');
    		    
		        pre=pre.substring(pre.length-extn,pre.length).replace(/^\S{1,10}\s+/,"");   // обрезаем до нужной длины и удаляем первое слово (оно может быть обрезано)
		        suf=suf.substring(0,extn).replace(/\s+\S{1,10}$/,""); // обрезаем до нужной длины и удаляем последнее слово (оно может быть обрезано)
		        if(txt==""){
			        return null;
		        }
		        if(o && typeof(o.checkTextLength)==='function') {
		            if(!o.checkTextLength(txt)) {
		                if(o && typeof(o.onTextTooBig)==='function') o.onTextTooBig()
    		            throw "Selected text is too big."
    		        }
		        } else if(txt.length > maxtxtlen) {
                    if(o && typeof(o.onTextTooBig)==='function') o.onTextTooBig()
		            throw "Selected text is too big."
		        }
		        return {
			        pre:pre,
			        text:txt,
			        suf:suf
		        };
	        }else{
		        throw "Not supported by browser."
		        return;
	        }
        }catch(e){
	        return null;
        }
    };
    
    var wnd
    var form
    
    function init(o) {
        wnd = $(o.wnd || '#errorReporterWnd')
        form = wnd.find('form:first')
        if(wnd.length !=1 || form.length != 1)
            return
        
        form.submit(function(e){
            e.preventDefault()
        })
        wnd.find('.errorReporter-btn-cancel').click(function(){
            wnd.hide()
        })
        wnd.find('.errorReporter-btn-ok').click(function(e){
            e.preventDefault()
            wnd.hide()
            $.ajax({
                url: form.attr('action'),
                type: 'POST',
                data: form.serialize()
            })
            return false
        })
        $(document).keydown(function(e){
            if(e.ctrlKey && e.keyCode == 13)  // Ctrl-Enter
            {
                e.preventDefault()
                
                if(!wnd.is(':visible')) {
                    var sel = getSelectionEx({checkTextLength: o&&o.checkTextLength, onTextTooBig: o&&o.onTextTooBig})
                    if(sel != null) {
                        form[0].reset()
                        var sp1 = $('<span/>').text(sel.pre)
                        var sp2 = $('<strong/>').text(sel.text).css({color:'red'})
                        var sp3 = $('<span/>').text(sel.suf)
                        wnd.find('.ortho-error-preview').empty().append(sp1).append(sp2).append(sp3)
                        wnd.find('.error-reporting-status').text('')
                        wnd.find('.ortho-error-pre').val(sel.pre)
                        wnd.find('.ortho-error-text').val(sel.text)
                        wnd.find('.ortho-error-suf').val(sel.suf)
                        wnd.find('.ortho-error-url').val(document.location.href)
                        wnd.find('.ortho-error-previewtxt').val(wnd.find('.ortho-error-preview').html())
                        wnd.show()
                    }
                }
                
            } else if (e.keyCode == 27) { // Esc
                wnd.hide()
            }
        })
    }
    /*
    $(function(){
        init()
    })
    //*/
    return {
        init: init
    }
}());

