var fde_array = new Array(),
    fde_array_r = new Array(),
    fde_array_r_2 = new Array(),
    fde_words = new Array(),
    fde_lowcased_words = new Array(),
    fde_words_to_request = new Array(),
    fde_getted_id_elements = new Array();
    fde_cached_words = new Array(),
    fde_tmp_1 = true, 
    fde_tmp_2 = true,
    fde_tmp_3 = true;

fde_array_r = [
/<script[^<>]*?>(.|\s)*?<\/script>/igm,// scripts
/<style[^<>]*?>(.|\s)*?<\/style>/igm,// styles
/<\!\-\-(.|\s)*?\-\->/igm,// html comments
/<[^<>]*?>/igm// other tags
];

fde_array_r_2 = [
new RegExp('\\[[^\\[\\]]*\\]', 'img'),//0 [...] codes
new RegExp('[\\\\`~<>,\./?|!@#$%^&*()_+=\\-\\[\\]\\{\\}:;\\\"\\\']+', 'igm'),//1 bad chars
new RegExp('\\s+', 'igm'),//2 spaces
new RegExp('^\\s*(.+)\\s*$', 'igm'),//3 trim
new RegExp('^\\s*(.+)\\s*$', 'igm'),//3 trim

new RegExp('  ', 'igm'),// to &nbsp;
new RegExp('\\n', 'igm'),// \n to <br>

new RegExp('\&', 'igm'),// &
new RegExp('\<', 'igm'),// <
new RegExp('\>', 'igm'), // >

new RegExp('\&amp;', 'igm'),// &amp;
new RegExp('\&lt;', 'igm'), // &lt;
new RegExp('\&gt;', 'igm'),// &gt;

new RegExp('[^а-яА-ЯйЙёЁa-zA-Z]+', 'igm'),// &gt;

new RegExp('\\[', 'igm'),// &gt;
new RegExp('\\]', 'igm'),// &gt;

'([^а-яА-ЯйЙёЁa-zA-Z]+)'// for ids
];    

fde_array = [
new Array(),// for scripts
new Array(),// for styles
new Array(),// for html comments
new Array(),// for other tags
new Array()// for ids

];

function fde_id(id)// FDE CACHING ID SYSTEM
{
    if(typeof(fde_getted_id_elements[id])=='undefined')
    {
        fde_getted_id_elements[id] = document.getElementById(id);
    }
    return fde_getted_id_elements[id];
}

function fde_source_change(s)// CHANGING SOURCES
{
    var i;
    for(i=1;i<=2;i++)
    {
        fde_id('fde_source_'+i).style.display=i==s?'':'none';
        fde_id('fde_b_'+i).disabled=i!=s?false:true;
    }
    
}
function fde_reset_entities()
{
    fde_getted_id_elements = new Array();
    fde_words = new Array();
    fde_lowcased_words = new Array();
    fde_words_to_request = new Array();
}
function fde_degenerate_synonyms()
{
    var i, n, c, matches, content, tmp, tmp_l, tmp_reg, id;
    content = fde_id('fde_source_1').value;// get text content
    // replacing all html tags to codes
    for(i in fde_array_r)
    {
        matches = content.match(fde_array_r[i]);
        c = 0;
        if(matches!=null)
        {
            for(n in matches)
            {
                tmp = '[__'+ Math.random()+ '_'+ c+ '_'+ i+ '__]';
                content = content.replace(matches[n], tmp);
                fde_array[i][tmp] = matches[n];
                c++;
            }
        }
    }
    // getting words
    tmp = content;
    tmp = tmp.replace(fde_array_r_2[0], ' ');
    //tmp = tmp.replace(fde_array_r_2[1], ' ');
    tmp = tmp.replace(fde_array_r_2[13], ' ');
    tmp = tmp.replace(fde_array_r_2[2], ' ');
    //tmp = tmp.replace(fde_array_r_2[3], '$1');
    //tmp = tmp.replace(fde_array_r_2[4], '$1');
    tmp = tmp.split(' ');
    c = 0;
    for(i in tmp)
    {
        if(tmp[i])
        {
            tmp_reg = new RegExp('(^|[`~\\>\\<,\\.\\?\\|\\!@#\\$%\\^&\\*\\(\\)_\\+\\=\\-\\]\\[\\{\\}\\:;\"\\s])'+tmp[i]+'($|[`~\\>\\<,\\.\\?\\|\\!@#\\$%\\^&\\*\\(\\)_\\+\\=\\-\\]\\[\\{\\}\\:;\"\\s])', 'm');
            while(content.match(tmp_reg)!=null)
            {
                id = 'fde_word_'+c;
                n = fde_words[id]['code'];
                content = content.replace(tmp_reg, '$1'+n+'$2');
                fde_array[4][n] = fde_words[id]['word'];
                c++;           
            }
         }        
    }
    // showing tags
    for(n in fde_array[4])
    {
        content = content.replace(new RegExp(fde_preg_quote(n), 'igm'), fde_array[4][n]);
    }
    for(i=3;i>=0;i--)
    {
        for(n in fde_array[i])
        {
            content = content.replace(new RegExp(fde_preg_quote(n), 'igm'), fde_array[i][n]);
        }
    }
    // updatind synonymizer box
    fde_id('fde_source_1').value = content;
}
function fde_generate_synonyms()
{    
    var i, n, c, matches, content, tmp, tmp_l, tmp_reg, id;
    fde_reset_entities();
    
    fde_id('fde_b_'+1).disabled=true;// disable "text" button        
    fde_id('fde_b_'+2).disabled=false;// activate "synonymizer" button
    content = fde_id('fde_source_1').value;// get text content
    // replacing all html tags to codes
    for(i in fde_array_r)
    {
        matches = content.match(fde_array_r[i]);
        c = 0;
        if(matches!=null)
        {
            for(n in matches)
            {
                tmp = '[__'+ Math.random()+ '_'+ c+ '_'+ i+ '__]';
                content = content.replace(matches[n], tmp);
                fde_array[i][tmp] = matches[n];
                c++;
            }
        }
    }
    // getting words
    tmp = content;
    tmp = tmp.replace(fde_array_r_2[0], ' ');
    //tmp = tmp.replace(fde_array_r_2[1], ' ');
    tmp = tmp.replace(fde_array_r_2[13], ' ');
    tmp = tmp.replace(fde_array_r_2[2], ' ');
    //tmp = tmp.replace(fde_array_r_2[3], '$1');
    //tmp = tmp.replace(fde_array_r_2[4], '$1');
    tmp = tmp.split(' ');
    c = 0;
    for(i in tmp)
    {
        if(tmp[i])
        {
            tmp_l = tmp[i].toLowerCase();
            if(typeof(fde_lowcased_words[tmp_l])=='undefined')
            {
                fde_lowcased_words[tmp_l] = new Array();
            }
            fde_words_to_request[tmp_l] = true;
            
            tmp_reg = new RegExp('(^|[`~\\>\\<,\\.\\?\\|\\!@#\\$%\\^&\\*\\(\\)_\\+\\=\\-\\]\\[\\{\\}\\:;\"\\s])'+tmp[i]+'($|[`~\\>\\<,\\.\\?\\|\\!@#\\$%\\^&\\*\\(\\)_\\+\\=\\-\\]\\[\\{\\}\\:;\"\\s])', 'm');
            while(content.match(tmp_reg)!=null)
            {
                n = '[__'+ Math.random()+ '_'+ c+ '_____]';
                id = 'fde_word_'+c;
                fde_words[id] = new Array();
                content = content.replace(tmp_reg, '$1'+n+'$2');
                
                fde_words[id]['word'] = tmp[i];
                fde_words[id]['code'] = n;
                fde_array[4][n] = "<span class='fde_word_class' id='"+id+"'>"+tmp[i]+"</span>";
                
                fde_lowcased_words[tmp_l][fde_lowcased_words[tmp_l].length] = id;
                c++;           
            }
         }        
    }
    
    content = content.replace(fde_array_r_2[5], ' &nbsp;');
    content = content.replace(fde_array_r_2[6], '<br />');
    // showing tags
    for(n in fde_array[4])
    {
        content = content.replace(new RegExp(fde_preg_quote(n), 'igm'), fde_array[4][n]);
    }
    for(i=3;i>=0;i--)
    {
        for(n in fde_array[i])
        {
            content = content.replace(new RegExp(fde_preg_quote(n), 'igm'), fde_quote_html(fde_array[i][n]));
        }
    }
    // updatind synonymizer box
    fde_id('fde_source_2').innerHTML = content;
    fde_id('fde_progress').style.display = '';
    //alert(content);
    fde_synonymize_process();
}
function fde_synonymize_process()
{
    var i, n, c, matches, content, tmp;
    for(i in fde_words_to_request)
    {
        if(fde_words_to_request[i]===true)
        {
            fde_words_to_request[i] = false;
            if(typeof(fde_cached_words[i])=='undefined')
            {
                FDMK(webroot+'test_ajax.php?word='+i+'&rnd='+Math.random(), 'GET', false);
                
            }
            else
            {
                fde_tmp_1 = i;
                fde_tmp_2 = fde_cached_words[i];
                fde_tmp_3 = window.setInterval('fde_update_status(fde_tmp_1,fde_tmp_2);', 100);
            }            
            break;
        }          
    }
}
function fde_update_word(id, link)
{
    if(typeof(fde_words[id])!='undefined')
    {
        fde_words[id]['word'] = link.value;
    }
}
function fde_update_status(word,words)
{
    var precent, select='', i, n, from, el, ell, a, normalized;
    if(typeof(fde_tmp_3)!='undefined')
    {
        clearInterval(window.fde_tmp_3);
    }
    fde_synonymize_process();
    word = word.toLowerCase();
    fde_cached_words[word] = words;//LOCAL CACHING SYSTEM
    if(typeof(fde_words_to_request[word])!='undefined')
    {
        fde_words_to_request[word] = 0;
    }
    if(word && words && typeof(fde_lowcased_words[word])!='undefined')
    {
        words  = words.split(',');
        for(n in fde_lowcased_words[word])
        {
            ell = fde_id('fde_source_2');
            el = ell.getElementsByTagName('SPAN');
            for(a in el)
            {
                if(typeof(el[a])!='undefined' && el[a].id==fde_lowcased_words[word][n])
                {
                    from = el[a].innerHTML;
                    if(from.substr(0,1)!='<')
                    {
                        normalized = fde_normalize_word(from, word);
	                    select = '<select onchange="fde_update_word(\''+el[a].id+'\', this);">';
	                    select+= "<option style='font-weight:bold!important;' value='"+normalized+"'>"+ normalized +"</otion>";
	                    for(i in words)
	                    {
	                        if(words[i])
	                        {
	                            normalized = fde_normalize_word(from, words[i]);
	                            select+= "<option value='"+normalized+"'>"+ normalized +"</otion>";
	                        }
	                    }
	                    select+= "</select>";
	                    el[a].innerHTML = select;
	                }
                }
            }
        }
    }
    precent = get_percent_process();
    fde_id('fde_progress').innerHTML = precent+'%';
    //if(precent==100)
    //{
    //    fde_id('fde_progress').innerHTML = '0%';
    //    fde_id('fde_progress').style.display = 'none';
    //}
}
function fde_reset_progress()
{
    fde_id('fde_progress').innerHTML = '0%';
    fde_id('fde_progress').style.display = 'none';
}
function fde_normalize_word(from, to)
{
	//alert(from);
	//alert(to);
	if(from.substr(0,1).toUpperCase()+from.substr(1)===from)
    {
        return to.substr(0,1).toUpperCase()+to.substr(1);
    }
    else if(from.toUpperCase()==from)
    {
        return to.toUpperCase();
    }
    else
    {
        return to.toLowerCase();
    }
}
function get_percent_process()
{
    var all=0, normal=0, precent=0;
    for(i in fde_words_to_request)
    {
        if(fde_words_to_request[i]===0)
        {
            normal++;
        }
        all++;          
    }
    percent = normal*100/all;
    percent = Math.round(percent);
    return percent;
}
function fde_quote_html(t)
{
    t = t.replace(fde_array_r_2[7], '&amp;');
    t = t.replace(fde_array_r_2[8], '&lt;');
    t = t.replace(fde_array_r_2[9], '&gt;');
    return t;
}
function fde_dequote_html(t)
{
    t = t.replace(fde_array_r_2[10], '>');
    t = t.replace(fde_array_r_2[11], '<');
    t = t.replace(fde_array_r_2[12], '&');
    return t; 
}
function fde_preg_quote(t)
{
    t = t.replace(fde_array_r_2[14], '\\[');
    t = t.replace(fde_array_r_2[15], '\\]');
    return t; 
}
// -----------------------------------------------------------------------------

var fdeax=new Array(), fi;
function FDMK(url,method,pars)
{
    var http_request=false,e,e2;
    if(window.XMLHttpRequest)
    {
        http_request = new XMLHttpRequest();
        if(http_request.overrideMimeType)
        {
            http_request.overrideMimeType('text/xml');
        }
    }
    else 
    if(window.ActiveXObject)
    { // IE
        try
        {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } 
        catch(e)
        {
            try
            {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } 
            catch(e2){}
        }
    }
    if(!http_request)
    {
        url=url.split('&ajax=true');
        if(url.length>=2)
            url=''+url[0]+url[1];
        url=url.split('?ajax=true');
        if(url.length>=2)
            url=''+url[0]+url[1];     
        location.href=url;
        return false;
    }
    http_request.onreadystatechange=function(){alertContents(http_request);};
    window.status='loading...';
    document.body.style.cursor="wait";
    if(method=='POST')
        http_request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    http_request.open(method,url,true);
    http_request.send(((pars)?pars:null));
}
function alertContents(http_request)
{
    var FDE_AJAX;
    switch(http_request.readyState)
    {    
        case 4:
        {
            window.status='loaded';
            document.body.style.cursor="auto";
            if(http_request.status==200)
            {
                FDE_AJAX=http_request.responseText.split("<FDE/>");
                if(FDE_AJAX.length>1)
                {
	                eval(FDE_AJAX[0]);               
	                for(fi=0;fi<fdeax.length;fi++)
	                {
	                    if(fdeax[fi]=='title')
	                        document.title=FDE_AJAX[fi+1];
	                    else
	                        fde_id(fdeax[fi]).innerHTML=FDE_AJAX[fi+1];                 
	                }
	            }//else{alert(FDE_AJAX[0]);} 
            }
            else
                alert('there are some problem with request');
        }
        break;
    }
}


