$(document).ready(function() {
	$.ajaxSetup({cache: false});
	$('#login_form').submit(function() {
		if ($('#username_in').val().length > 0 && $('#password_in').val().length > 0) {
			$('#login_button').attr("disabled", "true");
			$('#login_button').val("Loging in...");
			
			var varUsername = $("#username_in").val();
			var varPassword = hex_md5($("#password_in").val());
			
			$.get("/login/lvu.php", { method: 'in', un: varUsername, pw: varPassword, rem: 1 }, function(data) {
				if (data == 1) {
					window.location = $('#ref_in').val();
				} else {
					$('#login_button').removeAttr("disabled");
					$('#login_button').val("Login")
					$('#password_in').val("")
					$('#test_div').html('<p><b>'+data+'</b></p>');
				}
			});
			
		} else {
			$('#password_in').value = ""
			$('#test_div').html('<p><b>Please enter both a username and password.</b></p>');
		}
		return false;
	});
	
	$('#logout_button').click(function(e) {
		e.preventDefault();
		$('#logout_button').attr("disabled", "true");
		$.get("/login/lvu.php", { method: 'out' }, function(data) {
			if (data == 1) {
				window.location = "/admin/";
			} else {
				$('#logout_button').removeAttr("disabled");
				alert('<p><b>Logout failed</b></p>');
			}
		});
	});
	
	/*
	 *	Blog posting/commenting code
	 */
	
	$("#post_blog").click(function() {
		if ($('#blog_subject').val().length > 0 && $('#blog_text').val().length > 0) {
			$('#post_blog').attr("disabled", true);
			$('#post_blog').val("Posting Entry...");
			
			var vblog_subject= $('#blog_subject').val();
			var vblog_date = $('#blog_year').val() + '-' + $('#blog_month').val() + '-' + $('#blog_day').val() + ' ' + $('#blog_hour').val() + ':' + $('#blog_minute').val() + ':00';
			var vblog_text = $('#blog_text').val();
			vblog_text = vblog_text.replace(/\n/g, "<br />");
			
			$.post("/blog_files/blog_new_entry.php", { blog_subject: vblog_subject, 
					blog_date: vblog_date, blog_text: vblog_text }, function(data) {
				if (data == -1) {
					$("#post_blog").removeAttr("disabled");
					$('#post_blog').val("Post Blog");
					$('#alert_div').html('<p><b>Please select another subject</b></p>');
				} else {
					window.location = data;
				}
			});
		} else {
			$('#alert_div').html('<p><b>Make sure you have a valid subject and blog body.</b></p>');
		}
	});
});

function createAjaxObj(){
	var httprequest=false
	if (window.XMLHttpRequest){ // if Mozilla, Safari etc
		httprequest=new XMLHttpRequest()
		if (httprequest.overrideMimeType)
			httprequest.overrideMimeType('text/xml')
		}
	else if (window.ActiveXObject){ // if IE
		try {
			httprequest=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e){
			try{
				httprequest=new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e){}
		}
	}
	return httprequest
}

function checkemail(email){
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
	
	if (filter.test(email)) {
		return true;
	}else {
		return false;
	}
}

function post_comment() {
	sendobj=createAjaxObj()
		
	if (document.getElementById('name_comment').value.length > 0 && checkemail(document.getElementById('email_comment').value)) {
		
		document.getElementById('add_comment').disabled = true
		document.getElementById('add_comment').value = "Posting Comment..."
	
		if (sendobj){
			var rand_no = Math.random();
			rand_no = rand_no * 10000000;
			rand_no = Math.ceil(rand_no);
			var name = document.getElementById('name_comment').value;
			var email = document.getElementById('email_comment').value;
			var website = document.getElementById('website_comment').value;
			var comment = document.getElementById('text_comment').value;
			comment = comment.replace(/\n/g, "<br />");
			var parameters="rand="+rand_no+"&name="+name+"&email="+email+"&website="+website+"&comment="+comment
			sendobj.open('GET', "/blog_files/blog_comment.php?"+parameters, true)
			sendobj.onreadystatechange=doComment
			sendobj.send(null)
		}
		
	} else {
		document.getElementById('alert_div').innerHTML = '<p><b>Please make sure you have entered a name and a valid email.</b></p>'
	}
}

function doComment() {
	
	if (sendobj.readyState == 4){ //if request of file completed
		var commentResult = sendobj.responseText
		if (commentResult != 0 && commentResult != -1) {
			var strNameLink = ""
			if (document.getElementById('website_comment').value.length > 0) {
				strNameLink = "<a href=\"http://"+document.getElementById('website_comment').value.replace("http://","")+"\">"+document.getElementById('name_comment').value+"</a> replies:<br />"
			} else {
				strNameLink = document.getElementById('name_comment').value+" replies:<br />"
			}
			
			var comment = document.getElementById('text_comment').value;
			comment = comment.replace(/\n/g, "<br />");
			document.getElementById('blog_comment_block').innerHTML = document.getElementById('blog_comment_block').innerHTML + "<div class=\"blog_entry_comment\"> \
			" + strNameLink + " \
			<small><i>"+commentResult+" EST</i></small> \
			<p>"+comment+"</p> \
			</div>"
			
			document.getElementById('add_comment').disabled = false
			document.getElementById('add_comment').value = "Add Comment"
			document.getElementById('name_comment').value = ""
			document.getElementById('email_comment').value = ""
			document.getElementById('website_comment').value = ""
			document.getElementById('text_comment').value = ""
			document.getElementById('alert_div').innerHTML = ""
		} else {
			document.getElementById('add_comment').disabled = false
			document.getElementById('add_comment').value = "Add Comment"
			if (commentResult == -1) {
				document.getElementById('alert_div').innerHTML = '<p><b>You didn\'t add a comment!</b></p>'
			} else {
				document.getElementById('alert_div').innerHTML = '<p><b>Comment failed to post</b></p>'
			}
		}
	}
	
}

function updateInfo() {
	postobj=createAjaxObj()
	
	document.getElementById('update_about_button').disabled = true
	document.getElementById('update_about_button').value = "Updating Information..."

	if (postobj){
		var rand_no = Math.random();
		rand_no = rand_no * 10000000;
		rand_no = Math.ceil(rand_no);
		var about_text= document.getElementById('about_text').value;
		about_text = about_text.replace(/\n/g, "<br />");
		var parameters="rand="+rand_no+"&about_text="+about_text;
		postobj.open('GET', "/admin/update_about.php?"+parameters, true)
		postobj.onreadystatechange=newRedirect
		postobj.send(null)
	}
}

function formSubmit(event) {

	if (window.XMLHttpRequest){ // if Mozilla, Safari etc
		if (event && event.which == 13)
			post_comment();
	} else if (window.ActiveXObject) { // if IE
		if (window.event && window.event.keyCode == 13)
			post_comment();
	}

}

/* Check for new comments periodically */

// -------------------------------------------------------------------
// Main Comment Checking Routine
// -------------------------------------------------------------------

function commentChecker(threadID, curComments, delay){
	this.threadID=threadID // Current thread ID
	this.curComments=curComments // Current number of comments
	this.delay=delay //Delay between msg change, in miliseconds.
	this.commentCode = document.getElementById('blog_comment_block').innerHTML;
	this.ajaxobj=createAjaxObj()
	this.getCommentCount()
}

// -------------------------------------------------------------------
// getCommentCount()- Makes asynchronous GET request to "blog_check_comments.php" with the supplied parameters
// -------------------------------------------------------------------

commentChecker.prototype.getCommentCount=function(){
	this.ajaxobj = null;
	this.ajaxobj=createAjaxObj()
	if (this.ajaxobj){
		var instanceOfTicker=this
		var rand_no = Math.random();
		rand_no = rand_no * 10000;
		rand_no = Math.ceil(rand_no);
		var parameters="rand="+rand_no+"&number="+this.threadID+"&comments="+this.curComments
		this.ajaxobj.onreadystatechange=function(){instanceOfTicker.initialize()}
		this.ajaxobj.open('GET', "/blog_files/blog_check_comments.php?"+parameters, true)
		this.ajaxobj.send(null)
	}
}

// -------------------------------------------------------------------
// initialize()- Initialize ticker method.
// -Gets contents of RSS content and parse it using JavaScript DOM methods
// -------------------------------------------------------------------

commentChecker.prototype.initialize=function(){
	if (this.ajaxobj.readyState == 4){ //if request of file completed
		if (this.ajaxobj.status==200){ //if request was successful
			var instanceOfTicker=this
			this.upateComments()
		}
	}
}

// -------------------------------------------------------------------
// rotatemsg()- Rotate through RSS messages and displays them
// -------------------------------------------------------------------

commentChecker.prototype.upateComments=function(){
	var instanceOfTicker=this
	var returnText = this.ajaxobj.responseText;
	
	if (returnText != this.curComments) {
		this.curComments++;
		this.commentCode = returnText;
		var commentDiv=document.getElementById('blog_comment_block');
		commentDiv.innerHTML = this.commentCode;

	}
	
	setTimeout(function(){instanceOfTicker.getCommentCount()}, this.delay) //update container every delay (in ms)
}
