// JavaScript Document

var mainContentTxtApplyObj;
function mainContentTxtApply() {
	mainContentTxtApplyObj = getAjaxObj();
	var mod = 'read';
	var fle = mainContentTxtFile + userLang;

	/*obj.open("POST", "validarMail.php", true);
	obj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	obj.onreadystatechange = callback; //callback es una función definida x el programador
	obj.send("m="+mail);*/

	mainContentTxtApplyObj.open('GET', writerURL + "?site=" + site + "&mod=" + mod + "&fle=" + fle, true);
	mainContentTxtApplyObj.onreadystatechange = mainContentTxtApplyCallback; //callback es una función definida x el programador
	mainContentTxtApplyObj.send(null);
}

function mainContentTxtApplyCallback() {
var obj = mainContentTxtApplyObj;
	if(obj.readyState == 4) {
		if(obj.status == 200) {
			if(obj.responseText) {
				var x = document.getElementById('mainContent');
				x.innerHTML = obj.responseText;
			}
		}
	}
}

var format4Php = {
	encode : function(s) {
		var str = s;
		str = str.replace(/(\r\n|\n|\r)/g, '<br />');
		return str;
	},
	decode : function(s) {
		//have to check os.. damn
	}
}

var mainContentTxtEditObj;
function mainContentTxtEdit( toolkit ) {
	var pre = ( toolkit == 'pre' ) ? true : false;
	var toolkit;
	//alert("ALERT DEBUG -> Estas aca?")
	try
	{
		if( !pre )
		{
			//alert("ALERT DEBUG -> Entra por no Pre");
			if( site == 'mr' )
			{
				var roger = w.confirm('\
Reemplazar el texto actual de ' + mainContentTxtFile + '?\
				');
			}
			if( site == 'sp' )
			{
				var note = false;
				var img = false;
				var vid = false;
				var missingData = false;
				var intro = d.getElementById('editNoteIntro');
				intro = ( intro ) ? intro.value : true;
				var title = d.getElementById('editNoteTitle').value;
				var desc = d.getElementById('editNoteDesc').value;
				
				if( !intro || !title || !desc )
				{
					w.alert('\
Los campos de "Datos" contienen la información que identifica al artículo en la página.\n\n\
Deben estar completos para salvar la actualización.\
					');
					var x = document.getElementById('txtEditSavedMsg');
					x.innerHTML = '\
Su edici&oacute;n no ha sido salvada.\
					';
					return false;
				}
				switch( toolkit )
				{
					case 'note':
						note = true;
						var roger = w.confirm('\
Si salva "' + title + '" como una nueva nota :\n\n\t\
- Será añadida al historial de notas.\n\t\
- Las imágenes y videos marcados serán añadidos a las galerías correspondientes.\n\n\
Desea continuar?\
						');
						break;
					case 'img':
						img = true;
						var roger = w.confirm('\
Si salva "' + title + '" como una nueva nota :\n\n\t\
- Será añadida al historial de notas.\n\t\
- Las imágenes y videos marcados serán añadidos a las galerías correspondientes.\n\n\
Desea continuar?\
						');
						break;
					case 'vid':
						//alert("ALERT DEBUG -> Entra por VID");
						vid = true;
						var roger = w.confirm('\
Si salva "' + title + '" como una nueva nota :\n\n\t\
- Será añadida al historial de notas.\n\t\
- Las imágenes y videos marcados serán añadidos a las galerías correspondientes.\n\n\
Desea continuar?\
						');
						break;
					default:
						alert( 'First argument ("toolkit") must be present.' );
						return false;
						break; // just in case.
				}
			}
			if( !roger )
			{
				return false;
			}
		}
	}
	catch( e )
	{
		alert( 'Ha ocurrido un error : \n\t- "' + e.description + '".\nZona de confirmación.' );	
	}
	try
	{
		var mod = 'write';
		var fle = mainContentTxtFile + userLang;
		
		var aujourdHui = new Date();
		var jour = aujourdHui.getDate();
		var mois = aujourdHui.getMonth() + 1;
		var annee = aujourdHui.getFullYear();
		var j = annee + addZero(mois) + addZero(jour);
	
		var patt = /.(\d{1,5})/;
		var rand = Math.random().toString().match(patt); // gets a random number with 3 digits
		var n = rand[rand.length - 1];
	
		var id = j + site.toUpperCase() + n; // master unique id
	
		var x;
		var z;
		var l; //hyperlink from user input, img and line
		var lnk; //actual hyperlink after adding or not 'http://'
		var findProt = new Array('ftp://', 'http://', 'https://');
		var replaceProt = new Array('ffttpp://', 'hhttttpp://', 'hhttttppss://');
		var lst = 0; //bool, if within a list
		var formatListType = '';
	
		var txt = '<p class="para">';
		var xml = '<note>\n';
			
		var f = d.getElementById('formDiv');
		var list = d.getElementsByName('jacqueline');
		var listLength = list.length;
		var db = new Array();
	}
	catch( e )
	{
		alert( 'Ha ocurrido un error : \n\t- "' + e.description + '".\nZona de variables.' );	
	}
	var i = 0;
	while(i < listLength) {
		var n = list[i];
		if(n.id) {
			var t = n.id.match(/\d+/);
			editTools[t][checkToolOrder] = i;
			orderTools[i] = editTools[t];
		}
		++i;
	}

	for(x in orderTools) {
		var tool = orderTools[x];
		//alert(tool);
		var y = tool[checkToolDel];
		if(y) {
			try {
				var e = tool[editToolType];
				var tempTxt;
				var tempXml = '\t<tool type="' + e + '">\n';
				
				//this makes no sense.. the class has to be oriented towards the tag name....
				var toolsLineClass = 'toolsBr';
				var toolsParaClass = 'toolsBr';
				var toolsBrClass = 'toolsBr';
				var toolsListClass = 'toolsBr';
				var toolsImgClass = 'toolsBr';
				var toolsVidClass = 'toolsBr';
				
				var formatBlankSpace = ' ';	//tiene un espacio en blanco por contenido
				var formatLineBr = '';
				var formatParaBr = '';
	
				var formatDivAlign = '';
				var formatDivFloat = '';
				var formatTextAlign = '';
	
				var formatLinkOpen = '';
				var formatLinkAttrs = 'target="_blank" class="toolFormatLink"';
				var formatColor = '';
				var formatFont = '';
				var formatSize = '';
				var formatBold = '';
				var formatItalic = '';
				var formatUnderline = '';
				var formatLinkClose = '';
	
				var listItemOpen = '';
				var listItemClose = '';
	
				var listItemOpen = '';
				var listItemClose = '';
	
				//var maxWidth = 644; // took out 30px for the overflow scroll
				var maxWidth = 624; // so that it fits on the webpage. REVIEW once background is changed to flat color.
				var formatDivWidth = '';
				var formatOpac = ''; // opacity with new css3 semi-standards. =P
				var formatImgWidth = '';
				var formatImgMargin = 'margin:10px;';
				var formatVidWidth = '';
				var formatVidHeight = '';
				
				var imgOrigWidth = '';
				var vidOrigWidth = '';
				var vidOrigHeight = '';
				var imgCaption = '';
				var imgCaptionWidth = '';
				var imgCaptionCode = '';
				var vidEmbedCode = '';
			}
			catch(e) {
				var msg = 'Ha ocurrido un error : "' + e.description + '". Zona de asignación de variables.';
				alert(msg);
			}
			
			try {
				if(tool[editToolId])
					z = d.getElementById(tool[editToolId]);
				if(tool[toolImgData])
					imgOrigWidth = tool[toolImgData][2];
				if(tool[toolVidData])
					vidEmbedCode = Url.decode(tool[toolVidData][1]);
				if(lst != 0) {
					formatLineBr = '';
					listItemOpen = '<li>';
					listItemClose = '</li>';
				}
				if(tool[editToolForm]) {
					var frm = d.getElementsByName(tool[editToolForm]);
					for(i=0; i<frm.length; i++) {
						switch (frm[i].className) {
							case 'formatLineBr':
								if(frm[i].checked)
									formatLineBr = ' <br /> ';
								break;
							case 'formatParaBr':
								if(frm[i].checked)
									formatParaBr = ' </p><p class="para">';
								break;
							case 'formatListType':
								if(frm[i].checked)
									formatListType = frm[i].value;
								break;
							case 'formatDivWidth':
								var tempWidth;
								if(frm[i].value) {
									tempWidth = frm[i].value;
									if(tempWidth > maxWidth)
										tempWidth = maxWidth;
								}
								else
									tempWidth = maxWidth;
								formatDivWidth = 'width:' + tempWidth + 'px;';
								break;
							case 'formatOpac':
								if(frm[i].value)
									formatOpac = 'opacity:' + frm[i].value + ';filter:alpha(opacity=' + frm[i].value*100 + ');';
								break;
							case 'formatTextAlign':
								if(frm[i].value)
									formatTextAlign = 'text-align:' + frm[i].value + ';';
								break;
							case 'formatDivAlign':
								if(frm[i].checked)
									formatDivFloat = 'text-align:' + frm[i].value + ';';
								break;
							case 'formatDivFloat':
								if(frm[i].checked)
									formatDivFloat = 'float:' + frm[i].value + ';';
								break;
							case 'formatImgWidth':
								var tempWidth = frm[i].value;
								if(!tempWidth)
									tempWidth = imgOrigWidth;
								if(tempWidth > maxWidth)
									tempWidth = maxWidth;
								formatImgWidth = 'width:' + tempWidth + 'px;';
								break;
							case 'formatImgMargin':
								if(frm[i].value)
									formatImgMargin = 'margin:' + frm[i].value + 'px;';
								break;
							case 'formatVidWidth':
								var formatVidWidth = frm[i].value;
								if(!formatVidWidth)
									formatVidWidth = (vidEmbedCode)? vidEmbedCode.match(/width="(\d*)"/)[1] : ''; // video sin aplicar
								if(formatVidWidth > maxWidth)
									formatVidWidth = maxWidth;
								break;
							case 'imgCaption':
								if(frm[i].value) {
									imgCaption = frm[i].value;
								}
								break;
							case 'imgCaptionWidth':
								var tempImgWidth = frm[i].value;
								if(!tempImgWidth)
									tempImgWidth = (formatImgWidth)? formatImgWidth : formatVidWidth;
								else if(tempImgWidth > maxWidth)
									tempImgWidth = maxWidth;
								imgCaptionWidth = 'width:' + tempImgWidth + 'px;';
								break;
							case 'formatColor':
								if(frm[i].value)
									formatColor = 'color:' + frm[i].value + ';';
								break;
							case 'formatFont':
								if(frm[i].value)
									formatFont = 'font-family:' + frm[i].value + ';';
								break;
							case 'formatSize':
								if(frm[i].value)
									formatSize = 'font-size:' + frm[i].value + ';';
								break;
							case 'formatBold':
								if(frm[i].checked)
									formatBold = 'font-weight:' + frm[i].value + ';';
								break;
							case 'formatItalic':
								if(frm[i].checked)
									formatItalic = 'font-style:' + frm[i].value + ';';
								break;
							case 'formatUnderline':
								if(frm[i].checked)
									formatUnderline = 'text-decoration:' + frm[i].value + ';';
								break;
						}
					}
				}
				if(tool[editToolLink]) {
					l = d.getElementById(tool[editToolLink]);
					if(l.value) {
						l = d.getElementById(tool[editToolLink]);
						lnk = (l.value.match(/(ftp|http|https)/))? l.value : 'http://' + l.value;
						lnk = lnk.replace('ftp://', 'ffttpp://'); //code to prevent wfile.php to replace the url incorrectly
						lnk = lnk.replace('http://', 'hhttttpp://'); //code to prevent wfile.php to replace the url incorrectly
						lnk = lnk.replace('https://', 'hhttttppss://'); //code to prevent wfile.php to replace the url incorrectly
						formatLinkOpen = '<a href="' + lnk + '" ' + formatLinkAttrs + '>'
						formatLinkClose = '</a>';
					}
				}
				if(tool[toolImgData] && tool[editToolLink] && !l.value) { //l was assigned necessarily on the previous if.
					var img = tool[toolImgData][0];
					formatLinkOpen = '<a href="_upload/' + img + '" ' + formatLinkAttrs + '>'
					formatLinkClose = '</a>';
				}
				if(imgCaption)
					imgCaptionCode = '\
	<div class="imgToolCaptionDiv" style="' + imgCaptionWidth + '">\
		' + formatLinkOpen + '\
			<span class="imgToolCaptionSpan" style="' + formatColor + formatFont + formatSize + formatBold + formatItalic + formatUnderline + '">\
				' + imgCaption + '\
			</span>\
		' + formatLinkClose + '\
	</div>\
	';
			}
			catch(e) {
				var msg = 'Ha ocurrido un error : "' + e.description + '". Zona de asignación de atributos.';
				alert(msg);
			}
			
			try {			
				if(e == 'br_') {
					tempTxt = '</p><p class="para">';
				}
				if(e == 'list_') {
					if(z.value == 'begin') {
						tempTxt = '<' + formatListType + '>';
						++lst;
					}
					if(z.value == 'end') {
						tempTxt = '</' + formatListType + '>';
						--lst;
					}
				}
				if(e == 'line_') {
					tempTxt = listItemOpen + formatLinkOpen + '<span style="' + formatColor + formatFont + formatSize + formatBold + formatItalic + formatUnderline + '">' + z.value + '</span>' + formatLinkClose + listItemClose + formatBlankSpace;
				}
				if(e == 'para_') {
					tempTxt = '<span style="' + formatColor + formatFont + formatSize + formatBold + formatItalic + formatUnderline + '">' + listItemOpen + z.value + listItemClose + formatBlankSpace + '</span>';
					if(lst != 0)
						tempTxt = tempTxt.replace(/\r\n|\n|\r/g, ' </li><li> ');
					else
						tempTxt = tempTxt.replace(/\r\n|\n|\r/g, ' <br /> ');
				}
				if(e == 'img_') {
					if(tool[toolImgData]) {
						var img = tool[toolImgData][0];
						var iWidth = parseInt( formatImgWidth.match( /\d{1,3}/ )[ 0 ] );
						var iMargin = parseInt( formatImgMargin.match( /\d{1,3}/ )[ 0 ] );
						iWidth -= ( 2 * iMargin );
						formatImgWidth = formatImgWidth.replace( /\d{1,3}/, iWidth );
						tempTxt = formatLinkOpen + '<img class="imgToolImgImg" border="0" src="_upload/' + img + '" style="' + formatImgWidth + formatImgMargin + formatOpac + '" />' + formatLinkClose;
						if( parseInt( tool[ toolImgData ][ 4 ] ) && !pre ) {
							//alert(parseInt(tool[toolImgData][4]));
							db[tool] = new AjaxDb();
							db[tool].id = id;
							db[tool].insert(tool, tool[editToolId]);
						}
					}
					else
						tempTxt = '\
<div style="text-align:left;">\
	<p class="sys">Faltó aplicar la imagen.</p>\
</div>\
'; //alineado left o center?
				}
				//alert("ALERT DEBUG -> e == vid_ ?");
				if(e == 'vid_') {
					if(tool[toolVidData]) {
						var vid = tool[toolVidData][0];
						vidOrigWidth = vidEmbedCode.match(/width="(\d*)"/)[1];
						vidOrigHeight = vidEmbedCode.match(/height="(\d*)"/)[1];
						formatVidHeight = (vidOrigHeight*formatVidWidth)/vidOrigWidth;
						formatVidHeight = parseInt(formatVidHeight);
						var vidSize = 'width="' + formatVidWidth + '" height="' + formatVidHeight + '"';
						tempTxt = '\
<object ' + vidSize + '><param name="movie" value="http://www.youtube.com/' + vid + '&rel=1&color1=0xe1600f&color2=0xfebd01&border=0"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/' + vid + '&rel=1&color1=0xe1600f&color2=0xfebd01&border=0" type="application/x-shockwave-flash" wmode="transparent" ' + vidSize + '></embed></object>\
';
						//alert("ALERT DEBUG -> por grabar");
						if(tool[toolVidData][2] && !pre) {
							//alert(tool[toolVidData][2]);
							//alert("ALERT DEBUG -> Por Grabar adentro del IF");
							db[tool] = new AjaxDb();
							db[tool].id = id;
							//alert("ALERT DEBUG -> Por Llamar al Insert");
							db[tool].insert(tool, tool[editToolId]);
							//alert("ALERT DEBUG -> Volvio del Insert");
						}
					}
					else {
						tempTxt = '\
<div style="text-align:left;">\
	<p class="sys">Faltó aplicar el video o el c&oacute;digo ingresado era incorrecto.</p>\
</div>\
'; //alineado left o center?
					}
				}
				if(e == 'group_') {
					if(z.value == 'begin') {
						tempTxt = '\
<div class="imgToolContainerDiv" style="' + formatDivAlign + formatDivFloat + '">\
	<div class="imgToolImgDiv" style="' + formatDivWidth + formatOpac + formatTextAlign + '">\
';
					}
					if(z.value == 'end') {
						tempTxt = '\
		<div class="clearfloat"></div>\
	</div>\
	' + imgCaptionCode + '\
</div>\
';
					}
				}
				if( formatParaBr )
				{
					tempTxt += formatParaBr;
				}
				else if( formatLineBr )
				{
					tempTxt += formatLineBr;
				}
				//alert( tempTxt );
				txt += tempTxt;
				tempXml += '\t</tool>\n'
				xml += tempXml;
			}
			catch(e) {
				var msg = 'Ha ocurrido un error : "' + e.description + '". Zona de evaluación de herramientas.';
				//alert(msg);
			}
		}
	}
	while(lst > 0) {
		txt += '</' + formatListType + '>' //change it so that it can be ordered list as well
		--lst;
	}
	txt += '</p><div class="clearfloat"></div>';
	txt += '</note>\n';
	//alert(txt);
	txt = txt.replace(/</g, '[[');
	txt = txt.replace(/>/g, ']]');
	//alert(txt);
	intro = ( intro && note ) ? Url.encode( intro ) : '';
	title = ( title ) ? Url.encode( title ) : '';
	desc = ( desc ) ? Url.encode( desc ) : '';
	txt = ( txt ) ? Url.encode( txt ) : '';
	try
	{
		var uri;
		if( pre )
		{
			uri = previewerURL;
		}
		else if ( note )
		{
			uri = writerURL;
		}
		else
		{
			uri = galleryURL;
		}
		mainContentTxtEditObj = getAjaxObj();
		mainContentTxtEditObj.open('POST', uri, true);
		mainContentTxtEditObj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		//mainContentTxtEditObj.overrideMimeType('text/xml'); // VERY useful for passing a text response as xml
		mainContentTxtEditObj.onreadystatechange = ( pre ) ? mainContentTxtPreviewCallback : mainContentTxtEditCallback;
		var str = "site=" + site + "&id=" + id + "&mod=" + mod + "&fle=" + fle + "&toolkit=" + toolkit + "&intro=" + intro + "&title=" + title + "&desc=" + desc + "&txt=" + txt;
		//alert(str);
		mainContentTxtEditObj.send(str);
	}
	catch( e )
	{
		alert(e.description + ' Zona de envío XMLHttpRequest.');
	}
}

function mainContentTxtPreviewCallback() {
	var obj = mainContentTxtEditObj;
	if(obj.readyState == 4) {
		if(obj.status == 200) {
			if(obj.responseText) {
				var x = d.getElementById('previewBox');
				x.innerHTML = obj.responseText;
			}
		}
	}
}

function mainContentTxtEditCallback() {
	var obj = mainContentTxtEditObj;
	if(obj.readyState == 4) {
		if(obj.status == 200) {
			if(obj.responseText) {
				var x = d.getElementById('txtEditSavedMsg');
				x.innerHTML = obj.responseText;
				mainCont( 0 );
			}
		}
	}
}