var QuickReply = {
	
	request: Core.request(),
	
	init: function() {
		var submitButton = document.getElementById("submitQuickReply");
		if(submitButton) {
			Core.addEventListener(submitButton, 'click', QuickReply.sendReply);
		}
	},
	
	refreshRequestObject: function() {
		QuickReply.request = Core.request();
	},
	
	sendReply: function(e) {
		QuickReply.refreshRequestObject();
		
		var textarea = document.getElementById("messageQuickReply");
		var msg = textarea.value;
		
		if(msg.length <= 3) {
			alert("Your message has to be more than three characters long.");
			Core.preventDefault(e);
			return false;
		}
		
		Core.preventDefault(e);
		
		var threadIdHolder = document.getElementById("threadid");
		var threadid = threadIdHolder.value;
				
		var req = QuickReply.request;
		
		req.open("POST", Penelope_Config.website_url + "/ajax/user/quick-reply/", true);
		req.onreadystatechange = QuickReply.displayPost;
		req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		req.send("threadid="+ escape(threadid) +"&message=" + encodeURIComponent(msg));
		
		
		textarea.disabled = true;
		this.value = 'Posting...'
		this.disabled = true;
		
		return false;
		
	},
	
	displayPost: function() {
		var req = QuickReply.request;
		if(req.readyState == 4 && req.status == 200) {
			var reply = req.responseText;

			document.getElementById("messageQuickReply").disabled = false;
			var submit = document.getElementById("submitQuickReply");
			submit.disabled = false;
			submit.value = "Quick Reply";
			
			if("OK" != Core.trim(reply)) {
				alert(reply);
			}
			else {
				document.getElementById("messageQuickReply").value = "";
				PostReloader.refresh();
			}
			
		}
	}
	
}


var PostReloader = {
	
	request: null,
	callback: null,
	
	refresh: function(callback) {
		PostReloader.callback = callback;
		PostReloader.request = Core.request();
		
		var threadIdHolder = document.getElementById("threadid");
		var threadid = threadIdHolder.value;
		
		var pageNumHolder = document.getElementById("page_number");
		var page = pageNumHolder.firstChild.nodeValue;
		
		var req = PostReloader.request;
		
		req.open("GET", Penelope_Config.website_url + "/ajax/thread/reload-posts?threadid=" + threadid + "&page=" + page, true);
		req.onreadystatechange = PostReloader.loadPosts;
		req.send(null);
	},
	
	loadPosts: function() {
		var req = PostReloader.request;
		
		if(req.readyState == 4 && req.status == 200) {
		
			var data = req.responseXML;
			
			var pageHolder = data.getElementsByTagName("page_number")[0];
			var newpage = pageHolder.firstChild.nodeValue;
			
			pageHolder = document.getElementById("page_number");
			var oldpage = pageHolder.firstChild.nodeValue;
			
			if(newpage != oldpage) {
				var current = window.location;
				var newurl = "test";
				var expression = /\/page\/.+/
				if(expression.test(current)) {
					current = String(current);
					newurl = current.replace(expression, "");
					
				}
				else {
					newurl = current;
				}
				newurl = String(newurl);
				newurl = newurl.replace(/\/$/, "");
				newurl = newurl + "/page/" + newpage;
				window.location = newurl;
			}
			
			var postsContainer = document.getElementById("postsContainer");
			while(postsContainer.childNodes.length > 0) {
				postsContainer.removeChild(postsContainer.firstChild);
			}
			
			var posts = data.getElementsByTagName("post");
			for(var i = 0; i < posts.length; i++)
			{
				var id = posts[i].getElementsByTagName("id")[0].firstChild.nodeValue;
				var html = posts[i].getElementsByTagName("code")[0].firstChild.nodeValue;
				
				postsContainer.innerHTML += html;
			}
			
			SpoilerBBCode.init();
		}
	}
}

Core.start(QuickReply);


var Attachments = {

	thumbSize: 50,

	init: function() {
	
		var images = Core.getElementsByClass('attachmentImage');
		for(var i = 0; i < images.length; i++) {
			/*
			var img = images[i];
			//Core.addEventListener(img, 'mouseover', Attachments.onImage);
			Core.addEventListener(img, 'mousemove', Attachments.adjustSize);
			Core.addEventListener(img, 'mouseout', Attachments.shrinkImage);
			
			var parent = img.parentNode.parentNode;
			img._actualWidth = Core.getElementsByClass('actualWidth', parent)[0].firstChild.nodeValue;
			img._actualHeight = Core.getElementsByClass('actualHeight', parent)[0].firstChild.nodeValue;
			
			var newSizes = Attachments.resize(img._actualWidth, img._actualHeight, Attachments.thumbSize, Attachments.thumbSize);
			img._thumbWidth = newSizes.width;
			img._thumbHeight = newSizes.height;
			img.width = newSizes.width;
			img.height = newSizes.height;*/
		}
	
	},
	
	shrinkImage: function(event) {
		var dimensions = Attachments.resize(this._actualWidth, this._actualHeight, Attachments.thumbSize, Attachments.thumbSize);
		this.width = dimensions.width;
		this.height = dimensions.height;
		setStyleByClass('div', 'attachmentImageHolder', 'height', Attachments.thumbSize + 'px');
		setStyleByClass('div', 'attachments', 'marginBottom',  '50px');
	},
	
	adjustSize: function(event) {
		if(event.offsetX) {
            var x = event.offsetX;
            var y = event.offsetY;
        } else {
            var x = event.layerX;
            var y = event.layerY;
        }
        
        var halfway = Core.round(this.width/2, 0);
        /*var diff = halfway - x;
        diff = Math.abs(diff);
        
        
        var halfwayPct = (100-(diff/halfway))/100;*/
        
        if(x <= halfway) {
        	var diff = x;
        } else if(x == halfway) {
        	var diff = this._actualWidth - Attachments.thumbSize;
        } else {
        	var diff = this.width - x;
        }
        
        var newSize = Attachments.thumbSize + diff;
        newSize = Math.round(newSize);
    
        var newDimensions = Attachments.resize(this._actualWidth, this._actualHeight, newSize, newSize);
        
        setStyleByClass('div', 'attachmentImageHolder', 'height', newDimensions['height']+10 + 'px');
        setStyleByClass('div', 'attachments', 'marginBottom', 50-(newDimensions['height']-50) + 'px');
        
    	this.width = newDimensions['width'];
    	this.height = newDimensions['height'];
        
	},
	
	resize: function(width, height, maxwidth, maxheight) {
		if(width > maxwidth || height > maxheight) {

			var widthRatio = maxwidth/width;
			var heightRatio = maxheight/height;
		
			if(widthRatio < heightRatio) {
				var new_width = width*widthRatio;
				var new_height = height*widthRatio;
			}
			else if(heightRatio < widthRatio) {
				var new_height = height*heightRatio;
				var new_width = width*heightRatio;
			}
			else {
				var new_width = width*widthRatio;
				var new_height = height*heightRatio;
			}
		}
		else {
			var new_width = width;
			var new_height = height;
		}
				
		new_width = Core.round(new_width, 2);
		new_height = Core.round(new_height, 2);
		
		var returnVar = [];
		returnVar.width = new_width;
		returnVar.height = new_height;
		
		return returnVar;
	}

}

Core.start(Attachments);

var Ratings = {

	req: null,
	postid: null,

	init: function() {
	
		var approvalButtons = Core.getElementsByClass("approvePostButton");
		
		for(var i = 0; i < approvalButtons.length; i++)
		{
		
			if(Core.hasClass(approvalButtons[i], 'clickedApprove')) {
				approvalButtons[i]._approve = true;
			}
			
			approvalButtons[i]._disapprove = false;
		
			Core.addEventListener(approvalButtons[i], 'mouseover', Ratings.showGreenButton);
			
			Core.addEventListener(approvalButtons[i], 'mouseout', Ratings.revertButton);
			
			Core.addEventListener(approvalButtons[i], 'click', Ratings.positiveRating);
		
		}
		
		var disapprovalButtons = Core.getElementsByClass("disapprovePostButton");
		
		for(var i = 0; i < disapprovalButtons.length; i++)
		{
		
			if(Core.hasClass(disapprovalButtons[i], 'clickedDisapprove')) {
				disapprovalButtons[i]._disapprove = true;
			}
			disapprovalButtons[i]._approve = false;
		
			Core.addEventListener(disapprovalButtons[i], 'mouseover', Ratings.showRedButton);
			
			Core.addEventListener(disapprovalButtons[i], 'mouseout', Ratings.revertButton);
			
			Core.addEventListener(disapprovalButtons[i], 'click', Ratings.negativeRating);
		
		}
	
	
	},
	
	getPostId: function(buttonPressed) {
	
		var parent = buttonPressed.parentNode;
		
		var els = Core.getElementsByClass("postid", parent);
		
		var postidElement = els[0];
		
		var postid = postidElement.firstChild.nodeValue;
		
		return postid;
	
	},
	
	resetButtons: function(target) {
	
		var parent = target.parentNode;
		
		var els = Core.getElementsByClass("clickedApprove", parent);
		for(var i = 0; i < els.length; i++) {
			Core.removeClass(els[i], 'clickedApprove');
			els[i]._approve = false;
		}
		
		var els = Core.getElementsByClass("clickedDisapprove", parent);
		for(var i = 0; i < els.length; i++) {
			Core.removeClass(els[i], 'clickedDisapprove');
			els[i]._disapprove = false;
		}
	
	},
	
	positiveRating: function(e) {
	
		Ratings.rate(e, true);
	
	},
	
	negativeRating: function(e) {
	
		Ratings.rate(e, false);
	
	},
	
	rate: function(e, pos) {
	
		var target = Core.getEventTarget(e);
		
		var postid = Ratings.getPostId( target );
		Ratings.postid = postid;
		
		Ratings.resetButtons(target);
		
		if(pos) {
			var positive = 'true';
			target._approve = true;
		} else {
			var positive = 'false';
			target._disapprove = true;
		}
		
		var req = Core.request();
		
		req.open("GET", Penelope_Config.website_url + "/ajax/rate-post/?postid=" + postid + "&positive=" + positive, true);
		req.onreadystatechange = Ratings.updateTotal;
		req.send(null);
	
		Ratings.req = req;
	
	},
	
	updateTotal: function() {
	
		var req = Ratings.req;
		
		if(req.readyState == 4 && req.status == 200) {
		
			var response = req.responseText;
			
			var el = document.getElementById("postRating_" + Ratings.postid);
			
			if(response != 0) {
				var nextEl = document.createElement("span");
				
				if(response > 0) {
					Core.addClass(nextEl, 'positiveRating');
					var textNode = document.createTextNode( "+" + response );
				} else {
					var textNode = document.createTextNode( response );
					Core.addClass(nextEl, 'negativeRating');
				}
				
				
				nextEl.appendChild( textNode );
			} else {
			
				var nextEl = document.createTextNode( response );
				
			}
			
			while(el.childNodes.length > 0) {
				el.removeChild(el.firstChild);
			}
			
			el.appendChild(nextEl);
			
		
		}
		
	
	},
	
	revertButton: function(e) {
	
		Core.removeClass(this, 'clickedApprove');
		Core.removeClass(this, 'clickedDisapprove');
		
		if(this._approve) {
			Core.addClass(this, 'clickedApprove');
		}
		if(this._disapprove) {
			Core.addClass(this, 'clickedDisapprove');
		}
		
	},
	
	showGreenButton: function(e) {
	
		Core.removeClass(this, 'clickedDisapprove');
		Core.addClass(this, 'clickedApprove');
	
	},
	
	showRedButton: function(e) {
		
		Core.removeClass(this, 'clickedApprove');
		Core.addClass(this, 'clickedDisapprove');
	
	}
	
	
}

Core.start(Ratings);