var lastSlogNum = 20;
var lastNewSlogNum = 0;
var newSlogClassName = '';

var lReturnFunction = '';
var isL = false;
var currentSubmitForm = null;
var sendSlogForm = null;
var sendSlogSubmitValue = '';

/* var defaultKeyword = '';
var searchActionLanguage = '';
var searchActionTab = '';
var slogUrl = ''; */	// External variables

var searchActionInWeb = false;
var tabSuggest = 0;
var suggestOn = 1;

function submitSearch(sender)
{
	var form = sender;
	var searchValue = form.q.value;
	searchValue = searchValue.replace("#", "'23");
	form.action = 'http://' + document.location.host + '/' + searchActionLanguage;

	if ((form.saWeb && searchActionInWeb) || (searchActionTab == 'web'))
	{
		if (searchValue != defaultKeyword) form.action += slogUrl + encodeURI(searchValue);
	}
	else
	{
		if (searchValue != defaultKeyword || searchActionTab != 'slogs') form.action += searchActionTab + '/';
		if (searchValue != defaultKeyword) form.action += slogUrl + encodeURI(searchValue);
	}
	return true;
}
function showL(returnFunction)
{
	lReturnFunction = returnFunction;
	var lDiv = document.getElementById('lDiv');
	var overlay = document.getElementById('overlay');

	overlay.style.visibility = "visible";
	removeClassName(lDiv, 'hide');

	return false;
}
function register()
{
	removeClassName(document.getElementById('registerDiv'), 'hide');
}
function doL()
{
	// ***** Missed login logic
	addClassName(document.getElementById('lDiv'), 'hide');
	document.getElementById('overlay').style.visibility = "hidden";
	lReturnFunction();
}
function cancelL()
{
	lReturnFunction = '';

	addClassName(document.getElementById('lDiv'), 'hide');
	document.getElementById('overlay').style.visibility = "hidden";
}
subscribe = function subscribe()
{
	if (!isL) return showL(subscribe);
}
reply = function reply()
{
	if (!isL) return showL(reply);
}
submitComment = function submitComment(sender)
{
	var commentBox = document.getElementById('commentBox');
	if (commentBox.className.indexOf('hide') > -1)
	{
		removeClassName(commentBox, 'hide');
		return false;
	}
	currentSubmitForm = sender;
	var commentText = sender.commentText.value;
	var errorTextEl = document.getElementById('errorCommentText');

	var cont = true;
	if (!commentText || commentText.length < 5)
	{
		removeClassName(errorTextEl, 'hide');
		cont = false;
	}
	else addClassName(errorTextEl, 'hide');

	if (sender.commentName)
	{
		var commentName = sender.commentName.value;
		var commentEmail = sender.commentEmail.value;
		var errorNoNameEl = document.getElementById('errorCommentNoName');
		var errorNoEmailEl = document.getElementById('errorCommentNoEmail');
		var errorNoValidEmailEl = document.getElementById('errorCommentNoValidEmail');

/*
		if (commentEmail.length > 0 && commentEmail != commentDefaultEmail){
			if (!checkEmail(commentEmail)) {
				removeClassName(errorNoValidEmailEl, 'hide');
				addClassName(errorNoEmailEl, 'hide');
				cont = false;
			} else {
				addClassName(errorNoValidEmailEl, 'hide');
			}
		} else {
			addClassName(errorNoValidEmailEl, 'hide');
		}
*/

		if ((commentEmail == commentDefaultEmail)||(!validateEmail(commentEmail))){
				sender.commentEmail.value='';
		}
        
		if (commentName == commentDefaultName || !commentName)
		{
			removeClassName(errorNoNameEl, 'hide');
			cont = false;
		}
		else addClassName(errorNoNameEl, 'hide');
	}

	if (!cont) return false;

	http_request = false;
	if (window.XMLHttpRequest)
	{ // Mozilla, Safari,...
	   http_request = new XMLHttpRequest();
	   if (http_request.overrideMimeType) {
	   	// set type accordingly to anticipated content type
	      //http_request.overrideMimeType('text/xml');
	      http_request.overrideMimeType('text/html');
	   }
	} else if (window.ActiveXObject) { // IE
	   try {
	      http_request = new ActiveXObject("Msxml2.XMLHTTP");
	   } catch (e) {
	      try {
	         http_request = new ActiveXObject("Microsoft.XMLHTTP");
	      } catch (e) {}
	   }
	}
	if (!http_request)
	{
	   // should post without ajax
	   alert('Cannot create XMLHTTP instance');
	   return false;
	}

	sender.Buscar.value = document.getElementById('waitMessage').innerHTML;
	sender.Buscar.disabled = true;
	var url = sender.action;
	parameters = getFormElements(sender);
	http_request.onreadystatechange = postResponse;
	http_request.open('POST', url, true);
	http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http_request.setRequestHeader("Content-length", parameters.length);
	http_request.setRequestHeader("Connection", "close");
	http_request.send(parameters);
	sender.commentText.value = '';

	return false;
}

submitClip = function submitClip(origin, clip)
{
document.getElementById('light').style.display='block';
document.getElementById('fade').style.display='block';

if (origin==1){
    var clipPreview = document.getElementById('clipPreview');
    clipPreview.innerHTML = '';
    var a = document.createElement('div');
    clipPreview.appendChild(a);
    a.innerHTML = clip;
}

window.scroll(0,0);

return false;
}

submitReply = function submitReply(reply_comment_id)
{

document.getElementById('lightreply').style.display='block';
document.getElementById('fade').style.display='block';

document.getElementById('reply_comment_id').value = reply_comment_id;

window.scroll(0,0);

return false;
}

saveClip = function saveClip(origin)
{    

  if (origin==2) clip_reply = "Clip";else clip_reply="Reply";
  if (origin==4) reply_comment_id = document.getElementById('reply_comment_id').value;else reply_comment_id = 0;

	var commentClip = document.getElementById('comment' + clip_reply).value;

	if (commentClip == commentDefaultClip) commentClip='';

	if (origin == 2){
        var clipPreview = document.getElementById('clipPreview').innerHTML;
        clipPreview = clipPreview.replace(/&/g, '%26');
        if (commentClip == ''){
                commentText = clipPreview;
        }else{
            commentText = commentClip + '<br /><br />' + clipPreview;
        }
  }else{ //origin = 4
        var commentDisplayName = document.getElementById('comment_display_name_' + reply_comment_id).innerHTML;
        var commentTextOriginal = commentClip;
        commentText = '<font style="font-size: 9px; color: #808080;">Re: ' + commentDisplayName + '.</font> <br>' + commentClip;
  }
 
  var commentName = document.getElementById('commentName' + clip_reply).value;
	var commentEmail = document.getElementById('commentEmail' + clip_reply).value;

	if ((commentEmail == commentDefaultEmail)||(!validateEmail(commentEmail))){
			commentEmail='';
	}

	var errorNoNameElClip = document.getElementById('errorCommentNoName' + clip_reply);
	var errorNoEmailElClip = document.getElementById('errorCommentNoEmail' + clip_reply);
	var errorNoValidEmailElClip = document.getElementById('errorCommentNoValidEmail' + clip_reply);
	if (origin == 4) var errorTextElClip = document.getElementById('errorCommentText' + clip_reply);
	var cont = true;

	if (commentName == commentDefaultName || !commentName)
	{
		removeClassName(errorNoNameElClip, 'hide');
		cont = false;
	}
	else addClassName(errorNoNameElClip, 'hide');

	if (origin == 4){
        if (!commentTextOriginal || commentTextOriginal.length < 5)
        {
            removeClassName(errorTextElClip, 'hide');
            cont = false;
        }
        else addClassName(errorTextElClip, 'hide');
  
  }
	if (!cont) return false;

	http_request = false;
	if (window.XMLHttpRequest)
	{ // Mozilla, Safari,...
	   http_request = new XMLHttpRequest();
	   if (http_request.overrideMimeType) {
	   	// set type accordingly to anticipated content type
	      //http_request.overrideMimeType('text/xml');
	      http_request.overrideMimeType('text/html');
	   }
	} else if (window.ActiveXObject) { // IE
	   try {
	      http_request = new ActiveXObject("Msxml2.XMLHTTP");
	   } catch (e) {
	      try {
	         http_request = new ActiveXObject("Microsoft.XMLHTTP");
	      } catch (e) {}
	   }
	}
	if (!http_request)
	{
	   // should post without ajax
	   alert('Cannot create XMLHTTP instance');
	   return false;
	}

	parameters = 'commentText=' + commentText + '&commentText2=&commentName=' + commentName + '&commentEmail=' + commentEmail + '&key_id=' + key_id + '&q=' + q + '&clip=1&origin=' + origin + '&reply_comment_id=' + reply_comment_id;
	http_request.onreadystatechange = postResponse;
	http_request.open('POST', postUrl, true);
	http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http_request.setRequestHeader("Content-length", parameters.length);
	http_request.setRequestHeader("Connection", "close");
	http_request.send(parameters);

	document.getElementById('light').style.display='none';
	document.getElementById('lightreply').style.display='none';
	document.getElementById('fade').style.display='none';
	return false;
}


function postResponse()
{
	if (http_request.readyState == 4) {
		if (http_request.status == 200)
		{
			if ((navigator.appName == "Microsoft Internet Explorer")
					&& (http_request.responseText.indexOf('<object') != -1))
			{
				document.location = document.location;
			}
			var sender = currentSubmitForm;
			result = http_request.responseText;
			var resEl = document.getElementById('newSlog');
			var com = document.getElementById('newSlogComment');
			com.innerHTML = http_request.responseText;
            var you = document.getElementById('you');
            you.innerHTML = document.getElementById('commentName').value;
			//pageTracker._trackEvent('Slog', 'Post');

			var newEl = resEl.cloneNode(true);
			newEl.id += ++lastNewSlogNum;
			newEl.lastChild.lastChild.firstChild.firstChild.lastChild.id = '';
			if (!newSlogClassName) newSlogClassName = (hasClassName(newEl, 'odd') ? 'odd' : 'even');
			else newSlogClassName = (newSlogClassName == 'odd' ? 'even' : 'odd');
			addClassName(newEl, newSlogClassName);
			removeClassName(newEl, newSlogClassName == 'odd' ? 'even' : 'odd');
			newEl = resEl.parentNode.insertBefore(newEl, resEl.nextSibling);
			removeClassName(newEl, 'hide');
			// Hide the oldest slogs
			var oldSlogNum = lastSlogNum - lastNewSlogNum;
			var el = document.getElementById((oldSlogNum > 0 ? 'slog' + oldSlogNum : 'newSlog' + (-(oldSlogNum - 1))));
			if (el) addClassName(el, 'hide');

			var noslog = document.getElementById('noslog');
			if (noslog) addClassName(noslog, 'hide');

			if (sender && sender.commentEmail)
			{
				//var commentUI = document.getElementById('commentUI')
				//addClassName(commentUI, 'hide');
/*
				addClassName(sender.commentEmail, 'hide');
				addClassName(sender.commentName, 'hide');
				var emailhid = document.getElementById('emailhid')
				addClassName(emailhid, 'hide');
*/
			}
			if (sender)
			{
				sender.Buscar.value = document.getElementById('postMessage').innerHTML;
				sender.Buscar.disabled = false;
			}
	   } else {
	      alert('There was a problem with the request.');
	   }
	}
}
function getFormElements(f)
{
	var retVal = '';
	for (var n = 0; n < f.elements.length; n++)
	{
		element = f.elements[n];
		switch (element.type)
		{
			case 'text':
			case 'textarea':
			case 'submit':
			case 'hidden':
				retVal += element.name + "=" + escape(encodeURI(element.value)) + "&";
			break;
		}
	}
	return retVal;
}



function hasClassName(element, className)
{
	var elementClassName = element.className;
	return (elementClassName.length > 0 && (elementClassName == className || new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName)));
}

function addClassName(element, className)
{
	if (!hasClassName(element, className)) element.className += (element.className ? ' ' : '') + className;
	return element;
}

function removeClassName(element, className)
{
	var reg = new RegExp("(^|\\s+)" + className + "(\\s+|$)", "g");
	element.className = element.className.replace(reg, ' ');
	return element;
}

function toggleClassName(element, className)
{
	return hasClassName(element, className) ? removeClassName(element, className) : addClassName(element, className);
}

function showReply(coommentId, commentDiv)
{
	var newReplyDiv = document.getElementById('newReply');

	removeClassName(newReplyDiv, 'hide');
	return false;
}
function submitReply(sender)
{
	return false;
}
function notMe()
{
  var d = new Date();
  document.cookie = "user='';path=/;expires=" + d.toGMTString() + ";";
  window.location.reload();
}


function suggest(text,lang,key){
	if ((key!=13)&&(suggestOn==1)){
		tabSuggest = 0;
		http_request = false;
		if (window.XMLHttpRequest)
		{ // Mozilla, Safari,...
		   http_request = new XMLHttpRequest();
		   if (http_request.overrideMimeType) {
		   	// set type accordingly to anticipated content type
		      //http_request.overrideMimeType('text/xml');
		      http_request.overrideMimeType('text/html');
		   }
		} else if (window.ActiveXObject) { // IE
		   try {
		      http_request = new ActiveXObject("Msxml2.XMLHTTP");
		   } catch (e) {
		      try {
		         http_request = new ActiveXObject("Microsoft.XMLHTTP");
		      } catch (e) {}
		   }
		}
		if (!http_request)
		{
		   // should post without ajax
		   alert('Cannot create XMLHTTP instance');
		   return false;
		}

		var url = suggestUrl + "?text=" + text + '&lang=' + lang;
	  http_request.onreadystatechange = suggestResponse;
		http_request.open('GET', url, true);
		http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		http_request.setRequestHeader("Content-length",0);
		http_request.setRequestHeader("Connection", "close");
		http_request.send(null); //null agregado por bug httpd, si esta desabilitado firebug no anda! (sin null)
	}
	return false;
}
function suggestResponse()
{
	if (http_request.readyState == 4) {
		if (http_request.status == 200)
		{
			if ((navigator.appName == "Microsoft Internet Explorer")
					&& (http_request.responseText.indexOf('<object') != -1))
			{
				document.location = document.location;
			}
			result = http_request.responseText;
			var suggestDiv = document.getElementById('suggestDiv');
      suggestDiv.innerHTML = result;
	   } else {
	      //alert('There was a problem with the request.');
	   }
	}
}

function tabSuggestions(key){
	if (key==40){
		suggestOn = 0;
		var suggestItem = document.getElementById('suggest_'+(tabSuggest+1));
		if (suggestItem != null){
			var suggestItemPrev = document.getElementById('suggest_'+(tabSuggest));
			if (suggestItemPrev != null) suggestItemPrev.style.backgroundColor = '';
			tabSuggest = tabSuggest + 1;
			var inputText = document.getElementById('q');
			inputText.value = suggestItem.innerHTML;
			suggestItem.style.backgroundColor = '#E1E1E1';
		}
		else return false;
	}
	if (key==38){
		suggestOn = 0;
		var suggestItemPrev = document.getElementById('suggest_'+(tabSuggest));
		if (suggestItemPrev != null) suggestItemPrev.style.backgroundColor = '';
		tabSuggest = tabSuggest - 1;
		var inputText = document.getElementById('q');
		if (tabSuggest<=0){
			inputText.value = '';
			tabSuggest = 0;
			suggestOn = 1;
			return false
		}else{
			var suggestItem = document.getElementById('suggest_'+tabSuggest);
			inputText.value = suggestItem.innerHTML;
			suggestItem.style.backgroundColor = '#E1E1E1';
		}
	}
}
function showCommentBox(){
	var commentBox = document.getElementById('commentBox');
	if (commentBox.className.indexOf('hide') > -1)
	{
		removeClassName(commentBox, 'hide');
	}
  var commenttext= document.getElementById('commentText')
	document.location.href='#top';
	//commenttext.focus();
  var agregarcomentario= document.getElementById('agregarcomentario')
	addClassName(agregarcomentario, 'hide');
  //var agregarcomentario2= document.getElementById('agregarcomentario2')
	//addClassName(agregarcomentario2, 'hide');
}

function showDialog(dialogId)
{
	var overlayDiv = document.getElementById('overlay');
	var dialogDiv = document.getElementById(dialogId);
	if (overlayDiv.style.visibility == "visible")
	{
		var dialogsDiv = document.getElementById('dialogs');
		dialogsDiv.appendChild(dialogDiv);
		overlayDiv.style.visibility = "hidden";
		addClassName(dialogDiv, "hide");
	}
	else
	{
		overlayDiv.appendChild(dialogDiv);
		overlayDiv.style.visibility = "visible";
		removeClassName(dialogDiv, "hide");
	}
}
function spam(sender, keywordId)
{
	var dialog = document.getElementById('spamDialog');
	dialog.style.top = (sender.offsetTop - 10) +  'px';
	dialog.style.left = (sender.offsetLeft - 10) + 'px';
	removeClassName(dialog, 'hide');

	http_request = false;
	if (window.XMLHttpRequest)
	{
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) http_request.overrideMimeType('text/html');
	} else if (window.ActiveXObject) {
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
					http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	if (!http_request)
	{
		// should post without ajax
		alert('Cannot create XMLHTTP instance');
		return false;
	}


	var url = 'http://' + window.location.hostname + '/spam.php?key_id=' + keywordId;
	http_request.onreadystatechange = function () {};
	http_request.open('GET', url, true);
/*	http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http_request.setRequestHeader("Content-length", parameters.length);
	http_request.setRequestHeader("Connection", "close");
	http_request.send(parameters);
	sender.commentText.value = '';*/
	http_request.send('');
	setTimeout(spamResponse, 2000);
}
function spamResponse()
{
	var dialog = document.getElementById('spamDialog');
	addClassName(dialog, 'hide');
}
function spamComment(sender, commentId)
{
	var dialog = document.getElementById('spamDialog');
	dialog.style.top = (sender.offsetTop + 200) + 'px';
	dialog.style.left = (sender.offsetLeft) + 'px';
	removeClassName(dialog, 'hide');
	http_request = false;
	if (window.XMLHttpRequest)
	{
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) http_request.overrideMimeType('text/html');
	} else if (window.ActiveXObject) {
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
					http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	if (!http_request)
	{
		// should post without ajax
		alert('Cannot create XMLHTTP instance');
		return false;
	}


	var url = 'http://' + window.location.hostname + '/spamcomment.php?comment_id=' + commentId;
	http_request.onreadystatechange = function () {};
	http_request.open('GET', url, true);
/*	http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http_request.setRequestHeader("Content-length", parameters.length);
	http_request.setRequestHeader("Connection", "close");
	http_request.send(parameters);
	sender.commentText.value = '';*/
	http_request.send('');
	setTimeout(spamResponse, 2000);
}

function navigateR(url)
{
    var nlink = document.createElement ("a");
    if (typeof(nlink.click) == 'undefined') //FF
        location.href = url;
    else
    { //IE
        nlink.href = url;
        document.body.appendChild(nlink);
        nlink.click();
    }
}





function semanticRefine(keyid)
{
	if (!keyid) return false;

	http_request = false;
	if (window.XMLHttpRequest)
	{ // Mozilla, Safari,...
	   http_request = new XMLHttpRequest();
	   if (http_request.overrideMimeType) {
	   	// set type accordingly to anticipated content type
	      //http_request.overrideMimeType('text/xml');
	      http_request.overrideMimeType('text/html');
	   }
	} else if (window.ActiveXObject) { // IE
	   try {
	      http_request = new ActiveXObject("Msxml2.XMLHTTP");
	   } catch (e) {
	      try {
	         http_request = new ActiveXObject("Microsoft.XMLHTTP");
	      } catch (e) {}
	   }
	}
	if (!http_request)
	{
	   // should post without ajax
	   alert('Cannot create XMLHTTP instance');
	   return false;
	}

	var url = 'http://' + window.location.hostname + '/slogtagger.php?keyid=' + keyid;
	http_request.onreadystatechange = semanticRefineResponse;
	http_request.open('POST', url, true);
/*
	http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http_request.setRequestHeader("Content-length", parameters.length);
	http_request.setRequestHeader("Connection", "close");
	http_request.send(parameters);
*/
	http_request.send('');
	return false;
}


function semanticRefineResponse()
{
	if (http_request.readyState == 4) {
		if (http_request.status == 200)
		{
			if ((navigator.appName == "Microsoft Internet Explorer")
					&& (http_request.responseText.indexOf('<object') != -1))
			{
				document.location = document.location;
			}

			result = http_request.responseText;
			var semanticdiv = document.getElementById('semanticrefine');
			if (result){
				semanticdiv.innerHTML = result;
			}else{
				semanticdiv.innerHTML = 'no match found';
			}

	   } else {
	      alert('There was a problem with the request.');
	   }
	}
}

function semanticRefineRemove()
{
	alert('remove');
}

function setUserName(name)
{
  document.getElementById('commentName').value = name;
  document.getElementById('commentNameClip').value = name;
  document.getElementById('commentNameReply').value = name;
  return false;
}

function setUserEmail(email)
{
  document.getElementById('commentEmail').value = email;
  document.getElementById('commentEmailClip').value = email;
  document.getElementById('commentEmailReply').value = email;
  document.getElementById('mySlogsEmail').value = email;   
  return false;
}

function validateEmail(email)
{
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	return filter.test(email);
}
