// Functions & classes for The Argonaut
// Author: Jason Robinson [jaywink@basshero.org] (unless otherwise noted)
// http://www.basshero.org

function clearComment(form) {
	var text = form.comment_text.value;
	if (text.substring(0,20) == c_comment_form_index) {
		text = '';
		document.getElementById('comment_text').value = text;
		document.getElementById('comment_text').style.color = 'black';
		submitButton.status = submitButton.status -1; // notify submitButton counter that text has been cleared
	}
	return false;
}

function share(app,link,text,source) {
	if (link.length + text.length > 139 && app == 'twitter') {
		if (link.length <= 140) {
			text = text.substring(0,139-link.length-4) + '... ';
		} else {
			// add mini url??
			text = link.substring(0,139);
		}
	} else {
		text = text + ' ' + link;
	}
	if (app == 'twitter') {
		text = text.replace(/ /g,'+').replace(/&/g,'%26');
		window.open('http://www.twitter.com/timeline/home?source='+encodeURIComponent(source)+'&status='+text,'sharer');
	} else if (app == 'facebook') {
		window.title=text;
		setMeta(text);
		window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(link),'sharer','toolbar=0,status=0,width=626,height=436');
	}
	return false;
}

function setMeta(desc) {
	var x=document.getElementsByTagName("meta");
	var i = 0;
	for (i=0;i<=x.length-1;i++) {
		if (x[i].name == 'description' || x[i].name == 'title') {
			document.getElementsByTagName("meta")[i].content = desc;
			//alert('description is '+x[i].content);
		}
	}
}

function parse_php (string) {
	// destroy a tab that mysteriously is added to the returned string
	string = string.replace(Chr(9),'');
	var record = new Array();
	record = string.split('&');
	var temp_array = new Array();
	var i = 0;
	var row = new Array();
	for (i=0;i<=record.length-1;i++) {
		row = record[i].split('=');
		temp_array[row[0]] = row[1];
	}
	return temp_array;
}

function write_to (div,string) {
	var div_content = document.getElementById(div).innerHTML;
	document.getElementById(div).innerHTML = div_content+string;
}

function getCentralPositionForBox (xLength,yLength) {
	userX = screen.availWidth;
	userY = screen.availHeight;
	x = Math.round((userX/2)-(xLength/2));
	y = Math.round((userY/2)-(yLength/2));
	var returnArray = new Array(x,y);
	return returnArray;
}

// thanks to www.hunlock.com
String.prototype.htmlEntities = function () {
   return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/=/g,'&#61;');
};
String.prototype.charConv = function () {
	return this.replace(/\$/g,'&#36;').replace(/\|/g,'&#124;').replace(/\?/g,'&#63;').replace(/\'/g,'&#39;')
}
String.prototype.charConvReverse = function () {
	return this.replace('&#36;','$').replace('&#124;','|').replace('&#63;','?').replace('&#39;',"'").replace('&#160;',' ');
}
String.prototype.lineBreaks = function () {
	return this.replace(/\n/g,'<br>');
}
String.prototype.whiteSpace = function () {
	return this.replace(/ /g,'&#160;');
}
String.prototype.backSlash = function () {
	return this.replace(/\\/g,'&#92;');
}
String.prototype.destroyTags = function () {
	return this.replace(/<[^<]+>/g,"").replace(/\[[^\[]+\]/g,"");
}
String.prototype.killHTML = function () {
	return this.replace('<','').replace('>','');
}
// thanks to http://www.developersnippets.com/2007/05/12/remove-special-characters-like-etc-from-a-string-using-javascript/
String.prototype.textAndNumbersOnly = function () {
	return this.replace(/[^a-zA-Z0-9- ]+/g,'');
}
function Chr(AsciiNum) {
	return String.fromCharCode(AsciiNum)
}

//  from www.tizag.com
function notEmpty(elem, helperMsg){
	if(elem.value.length == 0){
		alert(helperMsg);
		elem.focus();
		return false;
	}
	return true;
}

// isInteger, isEmpty, isDigit http://acmesoffware.com/acme/default.asp
function isInteger (s) {
  var i;
  if (isEmpty(s))
  if (isInteger.arguments.length == 1) return 0;
  else return (isInteger.arguments[1] == true);
  for (i = 0; i < s.length; i++) {
	 var c = s.charAt(i);
	 if (!isDigit(c)) return false;
  }
  return true;
}
function isEmpty(s) {
  return ((s == null) || (s.length == 0))
}
function isDigit (c) {
  return ((c >= "0") && (c <= "9"))
}

// anti-spam idea from http://gatekiller.co.uk/Post/JavaScript_Captcha  (c) Stephen Hill
var antiSpam = function() {
	var localCounter = 0;
	if (document.getElementById("antiSpam")) {
		var a = document.getElementById("antiSpam");
		var button = document.getElementById("comment_button");
		if (isNaN(a.value) == true) {
				a.value = 0;
		} else {
			a.value = parseInt(a.value) + 1;
			localCounter = a.value;
			// submit button is disabled by default. when countdown is finished, enable it
			if (a.value < c_forms_spam_wait) {
				button.value = c_forms_spam_wait - a.value;
			}
			if (a.value == c_forms_spam_wait) {
				submitButton.status = submitButton.status -1; // notify submitButton counter that spam counter has finished
				button.value = c_comments_write_form_submit;
			}
		}
	}
	var counter = setTimeout("antiSpam()", 1000);
	// cancel counting after 5x max time
	if (localCounter > c_forms_spam_wait*5) {
		clearTimeout(counter);
	}
}
antiSpam();

function submitButtonClass() {
	this.status = 2;
	this.count = function() {
		var counter = setTimeout("submitButton.count()",1000);
		if (this.status == 0) {
			clearTimeout(counter);
			var button = document.getElementById("comment_button");
			button.disabled = false;
		}
	}
}
var submitButton = new submitButtonClass();
submitButton.count();

function checkAntiSpam() {
	var status = false;
	var antispam = document.getElementById("antiSpam").value;
	//write_to('debug','antispam is '+antispam.toString());
	if (isInteger(antispam) == true)  {
		if (antispam >= c_forms_spam_wait) {
			status = true;
		} else {
			status = false;
		}
	} else {
		status = false;
	}
	return status;
}

function Ajaxx () {
	var v_httpObject = null;
	this.getHTTPObject = function () {
	   if (window.ActiveXObject) 
	       return new ActiveXObject("Microsoft.XMLHTTP");
	   else if (window.XMLHttpRequest) 
	       return new XMLHttpRequest();
	   else {
	      alert("Your browser does not support AJAX.");
	      return null;
	   }
	}
	this.send = function(url,params,return_obj) {
		this.v_httpObject = this.getHTTPObject();
		if (this.v_httpObject != null) {
			this.v_httpObject.open("POST",url,true);
			// Send the proper header information along with the request
			// thanks to http://www.openjs.com/articles/ajax_xmlhttp_using_post.php
			this.v_httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			this.v_httpObject.setRequestHeader("Content-length", params.length);
			this.v_httpObject.setRequestHeader("Connection", "close");
			this.v_httpObject.send(params); 
			this.v_httpObject.onreadystatechange = function () {
				if (server.v_httpObject.readyState == 4) {
					//alert('ye');
					response = server.v_httpObject.responseText;
					return_obj(response);
				}
			}
		}
	}
}

function Textinput () {
	this.text = '';
	this.author = '';
	this.author_website = '';
	//this.id = 0;
	this.tags = '';
	this.password = '';
	this.subject = '';
	this.item_id = '';
	
	this.clear = function() {
		this.text = '';
	}
	
	this.save_confirm = function(string) {
		record = parse_php(trim(string));
		if (record['rc'] == 0) {
			if (record['type'] == 'comment') {
				window.location.reload();
			} else if (record['type'] == 'item') {
				window.location = 'index.php';
			}
		} else {
			write_to('debug','<p>Failure :(</p>');
			write_to('debug','<p>'+string+'</p>');
		}
	}
	
	this.processFormData = function(form) {
		this.text = trim(form.comment_text.value);
		this.author = trim(form.comment_author.value);
		// take actions depending if item or comment
		if (form.comment_type.value == 'comment') {
			this.item_id = item_id;
			this.text = this.text.htmlEntities();
			this.author_website = trim(form.comment_website.value).htmlEntities().destroyTags();
			//this.item_id = '0';
		} else if (form.comment_type.value == 'item') {
			//this.id = 0;
			this.tags = trim(form.comment_tags.value);
			this.password = trim(form.comment_password.value);
			this.subject = trim(form.comment_subject.value);
			this.item_id = form.comment_id.value;
		}
		// do some character conversion
		this.text = this.text.lineBreaks().replace(/\'/g,'&#39;').backSlash();
		this.author = this.author.htmlEntities().replace(/\'/g,'&#39;').backSlash();
		this.tags = this.tags.replace(/\'/g,'&#39;').backSlash();
		this.subject = this.subject.destroyTags().replace(/\'/g,'&#39;').backSlash();
		this.password = hex_md5(this.password); // encrypt password
	}
	
	this.checkFormData = function(form) {
		var ok = true;
		// do some checking
		ok = notEmpty(form.comment_text,c_text_cannot_be_empty);
		if (ok == true) {
			// check captcha
			ok = checkAntiSpam();
		}
		if (form.comment_type.value == 'item') {
			if (ok == true) {
				ok = notEmpty(form.comment_author,c_author_cannot_be_empty);
			}
			if (ok == true) {
				ok = notEmpty(form.comment_password,c_password_cannot_be_empty);
			}
			if (ok == true) {
				ok = notEmpty(form.comment_subject,c_subject_cannot_be_empty);
			}
		}
		if (form.comment_type.value != 'item' && form.comment_type.value != 'comment') {
			alert('Stop spamming!');
			ok = false;
		}
		return ok;
	}
	
	this.save_comment = function(form) {
		var ok = this.checkFormData(form);
		this.processFormData(form);
		var params = encodeURI('type='+encodeURIComponent(form.comment_type.value)+'&author_website='+encodeURIComponent(this.author_website)+'&author='+encodeURIComponent(this.author)+'&text='+encodeURIComponent(this.text)+'&tags='+encodeURIComponent(this.tags)+'&password='+encodeURIComponent(this.password)+'&subject='+encodeURIComponent(this.subject)+'&item_id='+encodeURIComponent(this.item_id));
		if (ok == true) {
			server.send('save_comment.php',params,this.save_confirm);
		}
	}
	
	this.preview = function(form) {
		this.processFormData(form);
		var params = encodeURI('type='+encodeURIComponent(form.comment_type.value)+'&author_website='+encodeURIComponent(this.author_website)+'&author='+encodeURIComponent(this.author)+'&text='+encodeURIComponent(this.text)+'&tags='+encodeURIComponent(this.tags)+'&password='+encodeURIComponent(this.password)+'&subject='+encodeURIComponent(this.subject)+'&item_id='+encodeURIComponent(this.item_id));
		server.send('preview_post.php',params,this.popupResult);
	}
	
	this.popupResult = function(string) {
		OpenWindow=window.open("", "Preview", "height=700, width=820,scrollbars=yes,location=no,toolbar=no,menubar=no");
		OpenWindow.document.write("<HTML><head><TITLE></TITLE></head>")
		OpenWindow.document.write("<BODY>")
		OpenWindow.document.write(string);
		OpenWindow.document.write("</BODY>")
		OpenWindow.document.write("</HTML>")
		OpenWindow.document.close()
	}
	
	this.submitForm = function(form) {
		this.save_comment(form); 
	}
	
	this.deleteItem = function(item_id) {
		var params = encodeURI('item_id='+encodeURIComponent(item_id.toString()));
		server.send('news_delete_item.php',params,this.deleteVerify);
	}
	
	this.deleteVerify = function(string) {
		record = parse_php(string);
		if (record['rc'] == 0) {
			if (record['return_item'] != '0') {
				window.location = 'index.php?sivu=1#'+record['return_item'];
			} else {
				window.location = 'index.php';
			}
			window.location.reload();
		}
	}
}

function Contact() {
	this.subject = '';
	this.text = '';
	this.email = '';
	this.name = '';
	this.submitForm = function(form) {
		if (checkAntiSpam() == true) {
			this.subject = form.contact_subject.value;
			this.text = form.contact_text.value;
			this.email = form.contact_email.value;
			this.name = form.contact_name.value;
			this.text = this.text.killHTML().charConv();
			this.subject = this.subject.killHTML().charConv();
			this.name = this.name.killHTML().charConv();
			this.email = this.email.killHTML().charConv();
			this.text = this.text.htmlEntities();
			this.subject = this.subject.htmlEntities();
			this.name = this.name.htmlEntities();
			this.email = this.email.htmlEntities();
			if (this.text.length > 0 || this.subject.length > 0) {
				var params = encodeURI('type=contact_form&subject='+encodeURIComponent(this.subject)+'&text='+encodeURIComponent(this.text)+'&email='+encodeURIComponent(this.email)+'&name='+encodeURIComponent(this.name)+'&null=');
				server.send('send_mail.php',params,this.mailConfirm);
			} else {
				alert(c_text_or_subject_must_be_filled);
			}
		}
	}
	this.mailConfirm = function(string) {
		record = parse_php(string);
		if (record['rc'] == 0) {
			alert(record['result']);
			window.location.reload();
		} else {
			write_to('debug','<p>Failure :(</p>');
			write_to('debug','<p>'+string+'</p>');
		}
	}
}

function User() {
	this.login = '';
	this.password = '';
	this.submitForm = function(form) {
		var ok = true;
		this.login = form.user_login.value;
		this.password = form.user_password.value;
		ok = notEmpty(form.user_login,c_login_cannot_be_empty);
		ok = notEmpty(form.user_password,c_password_cannot_be_empty);
		if (ok==true) {
			this.login = this.login.charConv();
			this.login = this.login.htmlEntities();
			this.password = hex_md5(this.password);
			var params = encodeURI('login='+encodeURIComponent(this.login)+'&password='+encodeURIComponent(this.password)+'&null=');
			server.send('login_check.php',params,this.login_confirm)
		}
	} 
	this.login_confirm = function(string) {
		record = parse_php(string);
		if (record['rc'] == 0) {
			//write_to('debug','<p>Success!</p>');
			window.location = 'index.php';
		} else {
			write_to('debug','<p>Failure :(</p>');
			write_to('debug','<p>'+string+'</p>');
		}
	}
}

function PopOutBox() {
	this.x = document.getElementsByTagName("div")["panels"].offsetWidth;
	this.y = document.getElementsByTagName("div")["panels"].offsetHeight;
	this.create = function(width,height,div,content) {
		content = content.replace('&#34;','"');
		document.getElementById(div).style.visibility = 'visible';
		write_to(div,'<span class="'+div+'" style="position:absolute;height:'+height+'px;width:'+width+'px;top:'+Math.round(parseInt(this.y-height)/2).toString()+'px;left:'+Math.round(parseInt(this.x-width)/2).toString()+'px;">'+content+'</span>');
	}
	this.close = function(div) {
		document.getElementById(div).style.visibility = 'hidden';
	}
}

var server = new Ajaxx();
var comment = new Textinput();
var user = new User();
var contact = new Contact();
