(function(){
	document.write('<script type="text/javascript" src="/lib/global/scripts/pt-add-ons/prototip.js"></script>');
	document.write('<script type="text/javascript" src="/lib/global/scripts/rating/rating.js"></script>');
	document.write('<script type="text/javascript" src="/lib/global/scripts/pt-add-ons/starbox.js"></script>');
	document.write('<script type="text/javascript" src="/lib/global/scripts/text-edit/text-edit.js"></script>');
})();

var user_review =  {
	init: function() {
		user_review.setShowButtons();
		user_review.setCreateForm();
		user_review.setVoteTip();
		user_review.setESRBToolTip();
		user_review.checkForNewData();
		user_review.setProdFinder();
	},
	
	// creation app
	setShowButtons: function() {
		if ($$('.single-review')[0]) { return; }
		$A($('content').select('.review-body')).each(function(boxAt) {
			if (boxAt.scrollHeight > 100) {
				var pTag = new Element ('p', {className: 'show'});
				var newButton = new Element('a', {
					href: '#',
					className: 'show'
				});
				newButton.update('show full review');
				newButton.onclick = function() {
					user_review.showBody(this, boxAt);
					return false;
				}
				pTag.appendChild(newButton);
				boxAt.parentNode.appendChild(pTag);
			}
		});
	},
	showBody: function(trigger, target) {
		switch(trigger.hasClassName('show')) {
			case true:
				trigger.removeClassName('show');
				trigger.addClassName('hide');
				trigger.update('hide review');
				this.newHeight = target.scrollHeight + 'px';
			break;
			case false:
				trigger.removeClassName('hide');
				trigger.addClassName('show');
				trigger.update('show full review');
				this.newHeight = 100 + 'px';
			break;
		}
		target.morph('height:' + this.newHeight);
	},
	setCreateForm: function() {
		if (!$('userReviewForm')) { return; }
		new Ajax.Request('/user-reviews/ajax/check_ur_rating/', {
			parameters: {
				globalID: window.location.href.split('/')[5]
			},
			onSuccess: function(t) {
				var h = $H(t.responseText.evalJSON()).toObject();
				switch(h.dupe) {
					case false:
						user_review.setStarLegend();
						new Starbox('review_score', 0, {
							overlay: 'big.png',
							ratedClass: 'rated',
							rerate: true,
							buttons: 5,
							indicator: 'Rate this game!',
							onRate: catchWriteUserReviewRate
						});
					break;
					case true:
						new Starbox('review_score', h.score, {
							overlay: 'big.png',
							ratedClass: 'rated',
							rated: true,
							rerate: true,
							buttons: 5,
							rerate: true,
							indicator: 'You have already scored on this product, but can change your score.',
							onRate: catchWriteUserReviewRate
						});
						new Starbox('star_target', h.score, {
							locked: true,
							buttons: 5
						});
						$('score').value = h.score;
						if (!$('pro_con_container').visible()) {
							new Effect.Appear('pro_con_container');
							user_review.setEditModeProCon();
						}
						if ($('text_body').visible() && $('body').innerHTML.length != 0) {
							user_review.updateProCon();
							preview.previewTimer();
						}
					break;
				}
			},
			onFailure: function(t){
				_tools.ajaxBug(t);
			}
		});
		if ($('title')) {
			Event.observe($('title'), 'keypress', user_review.charCounter);
			Event.observe($('title'), 'keypress', user_review.titlePreviewTimer);
		}
		if ($('body')) {
			Event.observe($('body'), 'keypress', user_review.charCounter);
		}
		if ($('pros_select')) {
			Event.observe($('pros_select'), 'change', user_review.setProsCons);
		}
		if ($('cons_select')) {
			Event.observe($('cons_select'), 'change', user_review.setProsCons);
		}
	},
	setProsCons: function(e) {
		var pcTarget = Event.element(e);
		pcValue = pcTarget.options[pcTarget.selectedIndex].value;
		pcText = pcTarget.options[pcTarget.selectedIndex].text;
		if (!pcValue) {return;}
		var table = $('pros_cons').select('tbody')[0];
		var pcType = pcTarget.id.split('_')[0];
		var cellContent = new Element('span');
		cellContent.appendChild(document.createTextNode(pcText));
		cellContent.appendChild(new Element('input',{
			type: 'hidden',
			name: pcType,
			value: pcValue
		}));
		var closeLink = new Element('a',{
			href: '#',
			title: pcText,
			rel: pcValue + '|' + pcTarget.id
		});
		closeLink.onclick = function() {
			user_review.removeProCon(this); return false;
		}
		closeLink.update('x');
		cellContent.appendChild(closeLink);
		var prosCells = [];
		var consCells= [];
		$A(table.select('td')).each(function(cellAt,index) {
			if (index % 2 == 0) {
				prosCells.push(cellAt)
			} else if (index % 2 == 1) {
				consCells.push(cellAt);
			}
		});
		var loopTarget = pcType + 'Cells';
		var emptyCells = [];
		$A(eval(loopTarget)).each(function(cellAt) {
			if (cellAt.select('select').length == 0 && cellAt.select('a').length == 0) {
				emptyCells.push(cellAt);
			}
		});
		if (emptyCells.length != 0) {
			emptyCells[0].update(cellContent);
		} else {
			var newRow = new Element('tr');
			var dummyCell = new Element('td');
			var targetCell = new Element('td');
			dummyCell.update('&nbsp;');
			targetCell.appendChild(cellContent);
			switch(pcType) {
				case "pros":
					newRow.appendChild(targetCell);
					newRow.appendChild(dummyCell);
				break;
				case "cons":
					newRow.appendChild(dummyCell);
					newRow.appendChild(targetCell);
				break;
			}
			table.appendChild(newRow);
		}
		$(pcTarget.options[pcTarget.selectedIndex]).remove();
		user_review.updateProCon();
	},
	removeProCon: function(trigger) {
		var optValue = trigger.rel.split('|')[0];
		var targetValue = trigger.rel.split('|')[1];
		var newOpt = new Element('option',{
			value: optValue
		});
		newOpt.update(trigger.title);
		$(targetValue).select('optgroup')[0].appendChild(newOpt);
		//var targetCell = trigger.parentNode.parentNode;
		//var targetRow = trigger.parentNode.parentNode.parentNode;
		trigger.parentNode.parentNode.update('');
		/*
		//check current empty rows
		var emptyCells = [];
		$A(targetRow.select('td')).each(function(cellAt) {
			if (cellAt.childNodes.length == 0) {
				emptyCells.push(cellAt);
			}
		});
		if (emptyCells.length == 2) {
			targetRow.remove();
		}
		*/
		//check for empty cells in column
		var proCells = [];
		var conCells = [];
		$A($('pros_cons').select('td')).each(function(cellAt,index) {
			if (index % 2 == 0) {
				proCells.push(cellAt);
			} else {
				conCells.push(cellAt);
			}
		});
		conCells.each(function(cellAt,index) {
			if (cellAt.childNodes.length == 0 && conCells[index+1] && conCells[index+1].childNodes.length != 0) {
				cellAt.update(conCells[index+1].innerHTML);
				conCells[index+1].update('');
			}
		});
		proCells.each(function(cellAt,index) {
			if (cellAt.childNodes.length == 0 && proCells[index+1] &&proCells[index+1].childNodes.length != 0) {
				cellAt.update(proCells[index+1].innerHTML);
				proCells[index+1].update('');
			}
		});
		var rowCleanerTimer = window.setTimeout(function(){
			$A($('pros_cons').select('tr')).each(function(rowAt) {
				var emptyCells = [];
				$A(rowAt.select('td')).each(function(cellAt) {
					if (cellAt.childNodes.length == 0) { emptyCells.push(cellAt) }
				});
				if (emptyCells.length == 2) {rowAt.remove()};
				user_review.updateProCon();
			});			
		},100);
	},
	updateProCon: function() {
		var baseTable = $('pros_cons').cloneNode(true);
		baseTable.select('.control-row')[0].remove();
		baseTable.removeAttribute('id');
		baseTable.addClassName('pros-cons');
		$A(baseTable.select('a')).each(function(linkAt) {
			linkAt.remove();
		});
		$A(baseTable.select('input')).each(function(inputAt) {
			inputAt.remove();
		});
		if (preview.previewArea.select('table').length != 0) {
			preview.previewArea.select('table')[0].remove();			
		}
		preview.previewArea.insert({top:baseTable});
		user_review.checkTextInputArea();
		user_review.changeSteps(2);
	},
	setEditModeProCon: function() {
		var proList = [];
		var conList = [];
		$('pros_cons').select('a').each(function(linkAt){
			if (linkAt.rel.indexOf('pros') != -1) {
				proList.push(linkAt.rel.split("|")[0])
			} else {
				conList.push(linkAt.rel.split("|")[0])
			}
		});
		$('pros_select').select('option').each(function(optionAt){
			if (proList.indexOf(optionAt.value) != -1) {
				optionAt.remove();
			}
		});
		$('cons_select').select('option').each(function(optionAt){
			if (conList.indexOf(optionAt.value) != -1) {
				optionAt.remove();
			}
		});
	},
	checkTextInputArea: function() {
		if (!$('text_body').visible()) {
			new Effect.Appear('text_body');
			$('pc_submit').addClassName('hide');
			$('final_submit').removeClassName('hide');
		} else {
			if (!$F('title') && !$F('body')) {
				new Effect.Fade(preview.previewParent);
			}
		}
	},
	charCounter: function(e) {
		var target = Event.element(e);
		$(target.id + '_count').update($F(target).length + " characters.");
		if ($F(target).length >= eval("user_review." + target.id + "Max")) {
			$(target.id + '_count').addClassName('error');
			$(target.id + '_count').update($(target.id + '_count').innerHTML + " Too many characters for this field.");
		} else {
			$(target.id + '_count').removeClassName('error');
		}
		
	},
	titlePreviewTimer: function() {
		var previewTimer = window.setTimeout(function(){
			user_review.titlePreview();
		},500);
	},
	titlePreview: function() {
		user_review.checkPreview();
		user_review.checkTextInputArea();
		$('title_target').update($('title').value);
	},
	checkPreview: function() {
		if(!$('text_body').visible()) {
			new Effect.Appear('text_body');
		}
		if(!$(preview.previewParent).visible()) {
			new Effect.Appear(preview.previewParent);
		}
	},
	bodyUpdater: function() {
		$('bodyText').value = document.getElementsByClassName('text-preview')[0].innerHTML;
	},
	userReviewRate: function(el,info) {
		user_review.changeSteps(1);
		$('star_legend').hide();
		if ($('step_1_guide')) {
			$('step_1_guide').hide();			
		}
		new Effect.Appear('pro_con_container');
		$('score').value = info.rated;
		//user_review.checkPreview();
		$('score_target').update(info.rated);
		new Starbox('star_target', info.rated, {
			locked: true,
			buttons: 5
		});
	},
	setVoteTip: function() {
		if (!document.getElementsByClassName('average-score')[0]) { return;}
		var tipTimer = window.setTimeout(function() {
			if (document.getElementsByClassName('average-score')[0].getElementsByClassName('rated')[0]) {
				var tipMessage = "You have already voted on this product";
			} else {
				var tipMessage = "Click stars to rate this product";
			}
			var tipTarget = document.getElementsByClassName('average-score')[0].getElementsByClassName('stars')[0];
			new Tip(tipTarget, tipMessage ,{
				style: 'gpblue',
				stem: 'topLeft',
				width: 'auto'
			});
		}, 3500);
	},
	setESRBToolTip: function() {
		if (!$('esrb_button')) {return;}
		new Tip('esrb_button', $('esrb_content'),{
			style: 'gpblue',
			title: 'ESRB Information',
			hideOn: { element: 'closeButton', event: 'click' },
			hideAfter: 1,
			stem: 'leftMiddle',
		 	hook: { target: 'rightMiddle',tip: 'leftMiddle', mouse: false },
			width: 400
		});
	},
	changeSteps: function(step) {
		var stepValue = step -1;
		var stepItems = $$('ul.steps')[0].select('li');
		var stopMe = false;
		stepItems.each(function(stepAt,index) {
			if (stepAt.className.indexOf('on') != -1 && index == 2) {
				stopMe = true;
			}
		});
		if (stopMe) {return};
		stepItems.each(function(stepAt) {
			stepAt.removeClassName('on');
		});
		if (stepItems[step]) {
			stepItems[step].addClassName('on');
		}
	},
	setStarLegend: function() {
		if (!$('star_legend')) {return};
		var legendText = [];
		legendText[0] = 'An absolute insult to humanity. Kill it with fire and holy water.';
		legendText[1] = 'Should come with a sticker: “Warning, contains poisonous amounts of suckage.” Remember Backyard Wrestling?';
		legendText[2] = 'Approach with caution – try before you buy. Enter the Matrix and Dynasty Warriors games fall frequently in this category.';
		legendText[3] = 'Highly enjoyable, but falls short of true greatness. The Fight Nights and Tony Hawks of the world.';
		legendText[4] = 'The best of the best. If you don’t own this game, you should. Think, Halo, Zelda, Resident Evil, and Metal Gear Solid.';
		var itemCount = 4;
		$('star_legend').select('li').each(function(itemAt) {
			new Starbox(itemAt, itemCount+1, {
				overlay: 'default.png',
				buttons: 5,
				locked: true,
				indicator: legendText[itemCount]
			});
			itemCount--;
		});
		new Effect.Appear('star_legend');
	},
	showAllProsCons: function(trigger,mode) {
		switch(mode) {
			case "show":
				$('main_pros_cons').select('tr.hide').each(function(rowAt){
				    rowAt.removeClassName('hide');
					rowAt.addClassName('showz');
				});
				trigger.update('hide pros/cons');
				trigger.removeAttribute('onclick');
				trigger.onclick = function() {
					return user_review.showAllProsCons(this,'hide');
				}
			break;
			case "hide":
				$('main_pros_cons').select('tr.showz').each(function(rowAt){
				    rowAt.removeClassName('showz');
					rowAt.addClassName('hide');
				});
				trigger.update('show pros/cons');
				trigger.removeAttribute('onclick');
				trigger.onclick = function() {
					return user_review.showAllProsCons(this,'show');
				}
			break;
		}
		return false;
	},
	checkForNewData: function() {
		if (window.location.href.indexOf("/new/") == -1) { return; }
		if (window.location.href.indexOf("article") != -1) {
			this.globalID = $$('span.global-id')[0].id;
			this.bodyContent = "<p>You posted your review of [--replace_name--]</p>";
			this.bodyContent += '<p><a href="/user-reviews/user/"' + util.userName() + '"/>See all of your reviews</p>';
		} else if (window.location.href.indexOf("list") != -1) {
			this.globalID = window.location.href.split("/")[5];
			this.bodyContent = "<p>You added your input into the mix for [--replace_name--]</p>";
		} else {
			return;
		}
		var mssg =  {
			"header": "Congratulations, " + util.userName() + "!",
			"bodyContent": this.bodyContent
		}
		new Ajax.Request('/user-reviews/ajax/prod_data/', {
			method: 'post',
			parameters: {
				globalID: this.globalID
			},
			onSuccess: function(t) {
				this.titlePlat = $H(t.responseText.evalJSON()).toObject();
				this.displayTitle = this.titlePlat.title + " for the " + this.titlePlat.platform;
				mssg.bodyContent = mssg.bodyContent.replace('[--replace_name--]', this.displayTitle);
				util.talkbox($H(mssg).toJSON());
			},
			onFailure: function(t){
				_tools.ajaxBug(t);
			}
		});
	},
	
	// pro-con email app
	sendProsCons: function() {
		new Ajax.Request('/user-reviews/ajax/email_pros_cons/', {
			onSuccess: function(t) {
				util.talkbox(t.responseText);
			},
			onFailure: function(t){
				_tools.ajaxBug(t);
			}
		});
		return false;
	},
	sendProConEmail: function() {
		switch($F('email_body').length != 0) {
			case false:
				$('pc_email_error').show();
			break;
			
			default:
				new Ajax.Request('/user-reviews/ajax/send_pc_email/', {
					method: 'post',
					parameters: $('emailProConForm').serialize(true),
					onSuccess: function(t) {
						util.talkbox(t.responseText);
					},
					onFailure: function(t){
						_tools.ajaxBug(t);
					}
				});				
			break;
		}
		return false;
	},
	
	// user review finder app
	focusFinderApp: function(field) {
		if (sniff.isIE) {//resets the z index so elements within will be over existing OVER them
			$('gamefinder').style.zIndex = 2;
		}
		$('keywords_lbl').hide();
		field.removeAttribute('onlick');
		field.onfocus = function() {
			$('keywords_lbl').hide();
		}
		field.onblur = function() {
			if (!$F('keywordsbox')) {
				$('keywords_lbl').show();
			}
		}
	},
	sendFinder: function() {
		var newURL = '/user-reviews/sort/' + $F('sortType') + '/' + $F('platform') + '/';
		window.location.href = newURL;
	},
	setProdFinder: function() {
		if (!$('urFinderForm')){ return false; }
		if (sniff.isIE) { 
			$('completer').style.position = "relative";
			$('completer').style.top = "54px";
			$('completer').style.left = "12px";
			$('completer').style.width = "514px";

		}
		new Ajax.Autocompleter("keywordsbox", "completer", "/user-reviews/ajax/prod_completer/", {
			minChars: 3,
			paramName: 'productTitle',
			afterUpdateElement: function(text,li) {
				$('pathToTake').value = li.id;
				
			}
		});
		if ($('keywordsbox') && $F('keywordsbox')) {
			user_review.focusFinderApp();
			$('keywords_lbl').hide();
		}
		if ($('pathToTake') && $F('pathToTake')) {
			$('pathToTake').value = '';
		}
	},
	prodFinder: function() {
		if (!$('pathToTake') || !$F('pathToTake')) { 
			var mssg = {
				"header": "There is an error",
				"bodyContent": "<p>Please select a product from the auto-suggested list. If the product you are searching for is not in that list, we have no information on that product.</p>"
			}
			util.talkbox($H(mssg).toJSON());
			return;
		}
		window.location.href = $F('pathToTake');
	},
	
	// validation logic
	failPoint: 0,
	errorMssg: null,
	errorFields: [],
	titleMax: 200,
	bodyMax: 4000,
	validate: function() {
		user_review.failPoint = 0;
		user_review.errorFields = [];
		user_review.errorMssg = '';
		if (!$F('score')) {
			user_review.failPoint++;
			user_review.errorMssg += '<li>Please select a score for the product you are reviewing.</li>';
		}
		switch($('text_body').visible()) {
			case true:
				if ($F('title') && !(/^[A-Z0-9a-z\s\'\"\.\,\?\!\&\-]+$/).test($F('title'))) {
					user_review.failPoint++;
					user_review.addErrorField($('title'));
					user_review.errorMssg += '<li>You have used a non-allowed character in your title.</li>';
				}
				if (($F('title') && $F('title').replace(/\s/gi,'').length == 0) && ($F('body') && $F('body').replace(/\s/gi,'').length)) {
					user_review.failPoint ++;
					user_review.errorMssg += '<li>If you wish to write a full review, please use characters other than just spaces in your title and body fields.</li>';
				}
				if ($F('title').length >= user_review.titleMax) {
					user_review.failPoint ++;
					user_review.addErrorField($('title'));
					user_review.errorMssg += '<li>You have exceeded the character limit for the title.</li>';
				}
				if ($F('body') && $F('body').length < 100) {
					user_review.failPoint++;
					user_review.addErrorField($('body'));
					user_review.errorMssg += '<li>100 character minimum is required for user reviews.</li>';
				}
				if ($F('body').length >= user_review.bodyMax) {
					user_review.failPoint++;
					user_review.addErrorField($('body'));
					user_review.errorMssg += '<li>You have exceeded the character limit for the body.</li>';
				}
				// check for both title and body
				if ((!$F('title') && $F('body')) || ($F('title') && !$F('body'))) {
					user_review.failPoint++;
					if (!$F('title')) {
						user_review.addErrorField($('title'));
					} else if (!$F('body')) {
						user_review.addErrorField($('body'));
					}
					user_review.errorMssg += '<li>If you choose to write a full user review, both title and body are required.</li>';
				}
				// new pro-con checking
				if ($F('title') && $F('body')) {
					var userForm = $('userReviewForm').serialize(true);
					if (!userForm.pros && !userForm.cons) {
						user_review.failPoint++;
						user_review.errorMssg += '<li>Please enter at least one pro or one con for the product you are reviewing.</li>';
					}
				}
			break;
		}
		user_review.submitCheck();
	},
	addErrorField: function(el) {
		if (user_review.errorFields.indexOf(el) == -1) {
			user_review.errorFields.push(el);
		}
	},
	submitCheck: function() {
		if (user_review.failPoint != 0) {
			var message = {
				"header": "There is an Error",
				"bodyContent": "<ol>" + user_review.errorMssg + "</ol>"
			}
			user_review.errorFields.each(function(fieldAt) {
				fieldAt.addClassName('error');
			});
			util.talkbox($H(message).toJSON());
		} else {
			if ($F('title') && $F('body')) {
				if (goog) { goog.postUserReview(); }
			}
			$('userReviewForm').submit();
		}
	}
}

function catchWriteUserReviewRate(el,info) {
	user_review.userReviewRate(el,info);
}

document.observe("dom:loaded", user_review.init);