var SIZE_OF_SUBSTRING = 300;


$(function () {

    var copy_btn = $("#trans_paste");
    if( window.clipboardData && clipboardData.setData )
    {
	clipboardData.setData("Text", copy_btn.val());
	copy_btn.show();
    }
});

function joinTwoArrays(arr1, arr2){
    var newArray = new Array(arr1.length + arr2.length);
    var j = 0;
    for (var i = 0; i < newArray.length; i++) {
	if (i < arr1.length) newArray[i] = arr1[i];
	else { 
	    newArray[i] = arr2[j];
	    j++;
	}
    }
    return newArray;
}

//	doing splitting of the text. gets strings by pattern, which passed as parameter
//	@param text - text to split
//	@param patternRepresentation - pattern
//	@param recursLevel - define level of splitting. 0 - splitting by dots, 1 - splitting by commas, 2 - splitting by spaces
//	@return - list of split strings
function getSplittedText(text, patternRepresentation, recursLevel){
    var pattern = new RegExp(patternRepresentation, 'gim');
    var resList = new Array(0);
    var end = 0;
    var currRes;
    
    if (text.length < SIZE_OF_SUBSTRING) {
	resList = joinTwoArrays(resList, new Array(text));
	return resList;
    }
    
    while (currRes = pattern.exec(text)) {
	// get captured string
	var group = currRes[0];
	// if start of the match doesn't equal to the end of the previous match - we have a missed text
	if (currRes.index != end) {
	    var start = end;
    	var head = text.substring(end - 1, currRes.index + group.length);
    	if (recursLevel == 0)
    	    resList = joinTwoArrays(resList, getSplittedText(head, ".{1," + SIZE_OF_SUBSTRING + "}[,]", 1));
    	else resList = joinTwoArrays(resList, getSplittedText(head, ".{1," + SIZE_OF_SUBSTRING + "}[\\s]", 2));
        } else
    	resList = joinTwoArrays(resList, new Array(group));
	end = currRes.index + group.length + 1;
    }
	
    // append tail after last match
    var tail = text.substring(end, text.length);
    if (tail.length > SIZE_OF_SUBSTRING){
	// split string by spaces with length equals to SIZE_OF_SUBSTRING
	if (recursLevel == 0)
	    resList = joinTwoArrays(resList, getSplittedText(tail, ".{1," + SIZE_OF_SUBSTRING + "}[,]", 1));
	    else resList = joinTwoArrays(resList, getSplittedText(tail, ".{1," + SIZE_OF_SUBSTRING + "}[\\s]", 2));
    } else if (tail.length > 0)
	resList = joinTwoArrays(resList, new Array(tail));

    return resList;
}



function joinTranslateBlock(text, lang, from) {
    text = text.replace(/\r|\n|\r\n/g,"<br/>");

    google.language.translate(text, from, lang, function(result) {
	if (!result.error) {
	    var res = result.translation;
	    res = res.replace(/\&\#39;/g,"\'");
	    res = res.replace(/\&quot;/g,"\"");					
	    res = res.replace(/<br\/>/g,"\r\n");

	    $("#dstText").val($("#dstText").val() + res);
	    current++;
	    if(current < (source.length))
		joinTranslateBlock(source[current], lang, from);

	} else {
	    if(result.error.code == 400) 
		$("#dstText").val("Невозможно автоматически определить язык исходного текста\nПожалуйста, укажите его вручную");
	    else
		$("#dstText").val("Ошибка "+result.error.code+" - "+result.error.message);
	}
    });
}

function translit(s)
{
    var t="аaбbвvгgдdеeёjoжzhзzиiйjjкkлlмmнnоoпpрrсsтtуuфfхkhцcчchшshщshhъ''ыyь'эehюjuяjaАAБBВVГGДDЕEЁJoЖZhЗZИIЙJjКKЛLМMНNОOПPРRСSТTУUФFХKhЦCЧChШShЩShhЪ''ЫYЬ'ЭEhЮJuЯJa";
    t=t.replace(/([а-яёЁ])([a-z']+)/gi,'.replace(/$1/g,"$2")');
    return eval("s"+t);
}

function joinTranslate() {
    var patternRepresentation = "(.|[\\r\\n]){1," + SIZE_OF_SUBSTRING + "}[\\r\\n.\\?!;]";
    var text = $("#srcText").val();
    var lang = $("#transTo").val();
    var from = $("#transFrom").val();
    
//    $("#google_experiment").html("<iframe src='http://translate.join.ua/ok/?rnd="+Math.random()+"' border=0 style='border:none;width:1px;height:1px'></iframe>");

    if(lang == '') return false;

    if(lang == 'translit') {
	$("#dstText").val(translit( text));
	return false;
    }


    current = 0;	
    source = getSplittedText(text, patternRepresentation, 0);
    $("#dstText").val('');
    joinTranslateBlock(source[current], lang, from);
    $("#translation_window").show("slow");
    return false;
}

function joinTranslateClear() {
    $("#dstText").val('');
    $("#srcText").val('');
    return false;
}
// Printing contents of text area
function printTextArea(textAreaId) {
	var elementRef = document.getElementById(textAreaId);
	var windowUrl = 'about:blank';
	var uniqueName = new Date();
	var windowName = 'Print' + uniqueName.getTime();
	var printWindow = window.open(windowUrl, windowName, 'left=50000,top=50000,width=0,height=0');
	
	printWindow.document.write(elementRef.value);
	printWindow.document.close();
	printWindow.focus();
	printWindow.print();
	printWindow.close();
	
	return false;
}


function setDirection(from, to) {
    $("#transTo").val(to);
    $("#transFrom").val(from);
}


function translateWord() {
    $.getJSON("http://translate.join.ua/dict/?callback=?", {word: $("#word").val(), dictionary:$("#dictionary").val()}, function(data) {
	$("#wordTranslation").html(data+"<br/>");
    });
    return false;
}