var ie6 = (typeof document.addEventListener != 'function');
var re_whiteHead = new RegExp("^\\s+");
var re_whiteTail = new RegExp("\\s+$");
var re_isMD5 = new RegExp("^[0-9a-fA-F]{32}$");
var windowBlurred = false;
var blurredNewComments = 0;

function md5data(textarea) {
	var s = textarea.value.replace(re_whiteHead,"").replace(re_whiteTail, "");
	if (s.match(re_isMD5)) {
		var sh = s.toLowerCase();
		document.getElementById("GoToSubmit").value = "Go";
		document.getElementById("GoToTextArea").style.backgroundColor = "#dfd";
	} else {
		var sh = hex_md5(s).toLowerCase();
		document.getElementById("GoToSubmit").value = "Hash and Go";
		document.getElementById("GoToTextArea").style.backgroundColor = "#fff";
	}
	document.getElementById("DirectGoToLink").innerHTML = 
		'&nbsp;<a href="hash/'+sh+'" title="Direct hash link not containing hashed text.">'+sh+'</a>';
}

var comment_highlighted = null;

function highlightSelectedComment() {
	var comment_ref = location.href.split(/#/);
	var comment_hl = "";
	if (comment_ref[1]) {
		if (comment_ref[1].match(/c([0-9]+)/)) {
			comment_hl = comment_ref[1];
		}
	}
	if (comment_hl != "") {
		var c = document.getElementsByName(comment_hl);
		if (c.length > 0) {
			c = c[0].parentNode.parentNode;
			c.className = "CommentHL";
			comment_highlighted = c;
		}
	}
}

function injectUrlTools(ref) {
	var refs = ref.split("?");
	refs = refs[0];
	var m;
	if (refs.match(/(\.jpg|\.jpeg|\.gif|\.png)$/i)) {
		document.write('&nbsp;[<a href="#" onclick="injectImage(this, \'ImagePreview0\', \''+ref+'\'); return false;">show image</a>]<div id="ImagePreview0"></div>');
	} else if (m = ref.match(/youtube.com\/watch\?v=([a-zA-Z0-9_\-]{11})/)) {
		document.write('&nbsp;[<a href="#" onclick="injectYoutube(this, \'YoutubePreview0\', \''+m[1]+'\'); return false;">show video</a>]<div id="YoutubePreview0"></div>');
	}
}

function injectImage(showhide, id, ref) {
	var el = document.getElementById(id);
	if (!el) {
		return;
	}
	if (el.innerHTML != '') {
		showhide.innerHTML = 'show image';
		el.innerHTML = '';
	} else {
		showhide.innerHTML = 'hide image';
		el.innerHTML='<img src="'+ref+'"/>';
	}
}

function injectYoutube(showhide, id, youtubeid) {
	var el = document.getElementById(id);
	if (!el) {
		return;
	}
	if (el.innerHTML != '') {
		showhide.innerHTML = 'show video';
		el.innerHTML = '';
	} else {
		showhide.innerHTML = 'hide video';
		el.innerHTML='<object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/'+youtubeid+'&hl=pl_PL&fs=1&"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/'+youtubeid+'&hl=pl_PL&fs=1&" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object>';
	}
}

function rehighlightComment(permalink) {
	if (comment_highlighted != null) {
		comment_highlighted.className = "";
	}
	var c = permalink.parentNode.parentNode;
	c.className = "CommentHL";
	comment_highlighted = c;
}

function xhrCreate() {
  var xhr = null;
  if (window.XMLHttpRequest) { 
    xhr = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
  }
  return xhr;
}

function xhrRequest(mode, msg, xhr, url, onSent, onRecv, onRecvError, xhrArg) {
  xhr.onreadystatechange = function()
  {
    if (xhr.readyState == 2) {
      if (onSent != null)
        onSent(xhr, xhrArg);
    } else if (xhr.readyState == 4) {
      if (xhr.status == 200) {
        if (onRecv != null)
          onRecv(xhr.responseText, xhrArg);
      } else {
        if (onRecvError != null)
          onRecvError(xhr.status, xhrArg);
      }   
    }   
  }
  xhr.open(mode, hashbashBase+url, true);
	if (mode == "POST") {
		xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xhr.setRequestHeader("Content-length", msg.length);
		xhr.setRequestHeader("Connection", "close");
	}
  xhr.send(msg);
}

function xhrSend(xhr, url, onSent, onRecv, onRecvError, xhrArg) {
	xhrRequest("GET", null, xhr, url, onSent, onRecv, onRecvError, xhrArg);
}

function injectNewComments(comments) {
	if (comments.length <= 0) {
		return;
	}
	//comments = comments.reverse();
	var comls = document.getElementById("CommentsList");
	for (var ci in comments) {
		var c = comments[ci];
		var comel = document.createElement("li");
		comel.innerHTML = c.html;
		comel.className = "CommentNew";
		comls.insertBefore(comel, comls.firstChild);
	}
	hashbashNewestCid = comments[comments.length - 1].id;
	if (windowBlurred) {
		blurredNewComments += comments.length;
		document.title = "(" + blurredNewComments + ") " + hashbashTitle + " - HashBash";
	}
}

function setupUpdate() {
	if (windowBlurred) {
		setTimeout("queryUpdate()", hashbashUpdateIntervalBlur);
	} else {
		setTimeout("queryUpdate()", hashbashUpdateIntervalFocus);
	}
}

function showInlineElement(elementId, show) {
	var el = document.getElementById(elementId);
	if (el) {
		if (show) {
			el.style.display = "inline";
		} else {
			el.style.display = "none";
		}
	}
}

function queryUpdate() {
	var xhr = xhrCreate();
	xhrSend(
		xhr, 
		"hash/"+hashbashHash+".json?sincecid="+hashbashNewestCid,
		null, 
		function(s, xhrArg) {
			var r = eval('(' + s + ')');
			if (r.error) {
				return;
			}
			injectNewComments(r.comments);
			setupUpdate();
		},
		function(err, xhrArg) {
			setupUpdate();
		}, 
		null
	);
}

function commentDelete(commentId) {
	if (confirm("Delete comment (#"+commentId+")?") != true) {
		return;
	}
	var xhr = xhrCreate();
	xhrRequest("POST", "_method=delete",
		xhr, 
		"comment/"+commentId+".json",
		null,
		function(s, xhrArg) {
			var r = eval('(' + s + ')');
			if (r.error_message) {
				alert("Delete error: "+r.error_message);
				return;
			}
			var c = document.getElementById("c"+commentId);
			if (c) {
				c.style.display = "none";
			}
		},
		function(s, xhrArg) {
			alert("Delete error: connection problem, try again.");
		},
		null
	);
}
