function calc_statistic()
{
	var alltext = document.getElementById('textarea_id').value;

	//Remove all symbols \r
	while (alltext != alltext.replace("\r\n", "\n")) alltext = alltext.replace("\r\n", "\n");
	
	//Number of lines
	lines = alltext.split("\n");
	document.getElementById('txtLines').value = lines.length;
	
	//Number of characters
	document.getElementById('txtChars').value = alltext.length;
	
	//Number of words
	words = alltext.split(/[\s.,\W]+/);
	document.getElementById('txtWords').value = words.length;
	
	//Longest line length
	max_line_length = 0;
	for (var i=0; i<lines.length; i++)
	{
		line_length = lines[i].length
		if (line_length > max_line_length) max_line_length = line_length
	}
	document.getElementById('txtLongest').value = max_line_length;
	
}

function format_one_pass(text, user_max_line_length)
{
	var newtext = ""
	var part_of_line = ""
	var number_lines
	
	var temp_symbol
	
	lines = text.split("\n")
	number_lines = lines.length
	
	//Cycle for each line
	for (var i=0; i<number_lines; i++)
	{
		if (lines[i].length > user_max_line_length)
		{
			//Get piece of line from 0 to user_max_line_length+1
			//We need to operate with following situation: when space symbol has position
			//user_max_line_length+1, so we don't need so add /n immediately after position user_max_line_length,
			//because fist symbol in next line will be a space
			part_of_line = lines[i].substr(0, user_max_line_length)
			
			//Anylaze this part of line
			if (part_of_line.indexOf(" ") == -1)
			{
				//If this line has no space symbols - so add hard \n 
				//We need to check that symbol after \n will not be an space
				temp_symbol = lines[i].charAt(user_max_line_length)
				if (temp_symbol == " ") lines[i] = lines[i].substring(0,user_max_line_length) + "\n" + lines[i].substring(user_max_line_length+1)
				else lines[i] = lines[i].substring(0,user_max_line_length) + "\n" + lines[i].substring(user_max_line_length)
			}
			else
			{
				//This part of line has space symbol	
				//Search last space symbol
				last_space_position = part_of_line.lastIndexOf(" ")
				lines[i] = lines[i].substring(0,last_space_position) + "\n" + lines[i].substring(last_space_position+1)
			}
		}
	
		//Do not add new line symbol to last line
		if (i != number_lines-1) newtext = newtext + lines[i] + "\n"
		else newtext = newtext + lines[i]
	}

	return newtext
}

function format()
{
	var alltext = document.getElementById('textarea_id').value
	var user_max_line_length = document.getElementById('user_max_line_length').value
	var formated_text
	
	var previous_symbol
	
	//Remove all symbols \r
	while (alltext != alltext.replace("\r\n", "\n")) alltext = alltext.replace("\r\n", "\n");
	
	//We need to remove all \n symbols, but remain groups of \n
	var last_new_line = alltext.lastIndexOf("\n")
	var current_new_line = alltext.indexOf("\n")

	while (current_new_line < last_new_line)
	{
		current_new_line = alltext.indexOf("\n")
		previous_symbol = alltext.charAt(current_new_line-1)
		next_symbol = alltext.charAt(current_new_line+1)
		
		if ((next_symbol != "\n") && (previous_symbol != "\r")) alltext = alltext.substring(0, current_new_line) + " " +  alltext.substring(current_new_line+1)
		else alltext = alltext.substring(0, current_new_line) + "\r" +  alltext.substring(current_new_line+1)
	}
	
	//Replace all \r for \n
	while (alltext != alltext.replace("\r", "\n")) alltext = alltext.replace("\r", "\n");
	
	//For this moment we can have situation, where string "\n " was transformed to "  " (2 spaces)
	//so replace "  " for " " 
	while (alltext != alltext.replace("  ", " ")) alltext = alltext.replace("  ", " ");
	
	formated_text = alltext
	while (formated_text != format_one_pass(formated_text, user_max_line_length)) formated_text = format_one_pass(formated_text, user_max_line_length);
	
	document.getElementById('textarea_id').value = formated_text

	//Recalc statistic
	calc_statistic();
}

function getFile(fileName){
    oxmlhttp = null;
    try{
        oxmlhttp = new XMLHttpRequest();
        oxmlhttp.overrideMimeType("text/xml");
    }
    catch(e){
        try{
            oxmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch(e){
            return null;
        }
    }
    if(!oxmlhttp) return null;
    try{
       oxmlhttp.open("GET",fileName,false);
       oxmlhttp.send(null);
    }
    catch(e){
       return null;
    }
    return oxmlhttp.responseText;
}


function show_editor()
{
	//fileurl   =  pow_server.GET['http://marketingconexito.com/formateadordeemails/banner.txt'];
	 
	// these lines clear up the urlencoded variables that were returned  
	 
	//fileurl =  unescape(fileurl.replace(/\+/g," ")); 
	
	// load the content or the file or url into "contents"
	
	//var contents = pow_file(fileurl);
	//doccument.write(contents);
	var banner= "banner.txt";
	var text = getFile(banner);
	//document.write(text);
	var aleat = Math.floor(4*Math.random()) + 1;
	var fileLines = new Array();
	fileLines = text.split("http://");
	var gF = fileLines[aleat];;
	var index = aleat;
	var bannerurl = "http://" + gF;
	var output = "";
	var yourserver = 'http://marketingconexito.com/formateadordeemails/';
	output = "<div align=\"center\">"
	output = output + "<a href=\"" + yourserver + "logo.php?index="+index+" \" target=\"_blank\">"
	output = output + "<!--LOGO_URL--><img border=\"0\" src=\""+bannerurl+"\" width=\"468\" height=\"60\"></a><!--END_LOGO_URL-->"
	output = output + "</div><br>"
	
	output = output + "<table align=\"center\" border=\"0\"> <tr><td bgcolor=\"#CCCCCC\" align=\"center\"> <font color=\"#FFFFFF\" face=\"Verdana, Arial, Helvetica, sans-serif\">	<textarea id=\"textarea_id\" cols=\"55\" rows=\"15\" onkeyup=\"calc_statistic()\"></textarea><br><br> Por favor escriba o pegue el Email a ser formateado<br><br> <a href=\"javascript:SelectAll()\">Seleccionar Todo</a> &nbsp;&nbsp;&nbsp; <a href=\"javascript:CopyAll()\">Copiar al portapapeles</a> &nbsp;&nbsp;&nbsp; <a href=\"javascript:ClearAll()\">Borrar</a> <br><br> Tama&ntilde;o maximo de la Linea: <input type=\"text\" id=\"user_max_line_length\" size=\"3\" value=\"50\">	<input type=\"submit\" id=\"format\" value=\"Formatear\" onclick=\"format()\"><br><br><TABLE id=\"statistic_table\" cellSpacing=\"1\" cellPadding=\"1\" align=\"center\" border=\"0\"><TR>	<TD align=\"center\"><STRONG>Estadisticas</STRONG></TD>	<TD align=\"center\" colSpan=\"2\">&nbsp;</TD></TR><TR>	<TD align=\"center\">Conteo de Caracteres (Incluye Espacios):</TD>	<TD align=\"center\"><INPUT id=\"txtChars\" style=\"WIDTH: 53px; HEIGHT: 22px; BACKGROUND-COLOR: transparent; TEXT-ALIGN: center\" type=\"text\" size=\"3\" name=\"txtChars\"></TD></TR><TR>	<TD align=\"center\">Conteo de Lineas (Lienas en blanco cuentan):</TD>	<TD align=\"center\"><INPUT id=\"txtLines\" style=\"WIDTH: 53px; HEIGHT: 22px; BACKGROUND-COLOR: transparent; TEXT-ALIGN: center\" type=\"text\" size=\"3\" name=\"txtLines\"></TD></TR><TR>	<TD align=\"center\">Numero de palabras:</TD>	<TD align=\"center\"><INPUT id=\"txtWords\" style=\"WIDTH: 53px; HEIGHT: 22px; BACKGROUND-COLOR: transparent; TEXT-ALIGN: center\" type=\"text\" size=\"3\" name=\"txtWords\"></TD></TR><TR>	<TD align=\"center\">Linea mas larga:</TD>	<TD align=\"center\"><INPUT id=\"txtLongest\" style=\"WIDTH: 53px; HEIGHT: 22px; BACKGROUND-COLOR: transparent; TEXT-ALIGN: center\" type=\"text\" size=\"3\" name=\"txtLongest\"></TD></TR></TABLE> <br></font></td></tr></table>"  
	
	//output = output + "<br><div align=\"center\">"
	//output = output + "<a href=\"" + yourserver + "text.php\" target=\"_blank\">"
	//output = output + "<!--BOTTOM_TEXT-->Copiar Codigo del Formateador Generador Aqui</a><!--END_BOTTOM_TEXT-->"
	//output = output + "</div></br>"
	document.write(output)
}

function SelectAll()
{
	//Select all text in the textarea
	var alltext = document.getElementById('textarea_id')
	alltext.focus()
	alltext.select()
}

function CopyAll()
{
	var alltext = document.getElementById('textarea_id')
	therange = alltext.createTextRange()
	therange.execCommand("Copy")
	window.status="Text copied to clipboard"
	setTimeout("window.status=''",2400);
}

function ClearAll()
{
	var alltext = document.getElementById('textarea_id')
	alltext.value = ""
	calc_statistic()
}