// Bnet Common JS for Forums / Comments
$(document).ready(function(){
	if (typeof console == "undefined") {
	// override firebug errors TODO Remove console calls
		var console = { log: function() {} };
	}
});

var Cms = {

	// The RTE editor instance
	Editor: null,

	ajaxErrorInit:function(target){
		if($('#ajax_error').length == 0) $('body').append($('<div id="ajax_error"></div>'))
		$('#ajax_error').ajaxError(function(event, request, settings) {
				//console.log(request)
				$('#ajax_error').html(Msg.cms.requestError+'<br/>' + ('<b>'+request.status+'</b>: '+settings.url)||'')
				Overlay.open('#ajax_error')

				//$(this).text('Error requesting ' + settings.url + ' ' + request.statusText);
			});
	},
	anchorTo:function(target){
		var targetOffset = $("#"+target).offset().top;
		$('html,body').animate({scrollTop: targetOffset}, "fast");
	},
	ignore:function(userId,remove){
		$('#thread .character-options').hide();
		var ignoreList = Cookie.read('bnetUserIgnore')
		ignoreList = (ignoreList != null)?decodeURIComponent(ignoreList).split(','):[];
		//console.log(userId.toString() + " " + ignoreList )
		var arrayLoc = $.inArray(userId.toString(),ignoreList)
		var actionTaken = false
		if(remove) {
			if(arrayLoc > -1) {
								ignoreList.splice(arrayLoc,1)
								Cookie.create('bnetUserIgnore',encodeURIComponent(ignoreList.join(',')),{path:Core.baseUrl, expires: 8760});
								//alert("Removed User from Ignore List");
								actionTaken = true;
			}
			else {	Overlay.open(Msg.cms.ignoreNot);
				 }
		}
		else{
			if (arrayLoc < 0){
					ignoreList.push(userId);
					if(ignoreList.length > 100) ignoreList.shift()
					Cookie.create('bnetUserIgnore',encodeURIComponent(ignoreList.join(',')),{path:Core.baseUrl, expires: 8760});
					//alert('User Ignored')
					actionTaken = true;
			}
			else Overlay.open(Msg.cms.ignoreAlready)
		}
		if(actionTaken) window.location.reload(); // location.href = location.href
	},
	Station: {
		_WOFFSET : 921,
		init: function(){
			$('input.filter').bind('keyup',Cms.Station.forumFilter)
		},

		forumFilter: function(e){
			var pool = $(this).parents('.child-forums').children('.forums-list');

			if(e.keyCode == 27)
				$(this).val('');

			var filterVal = $(this).val();

			pool.children().each(function(){
				var matchText = $.trim($(this).text().toLowerCase())
				console.log(matchText)
				var filterMatch = matchText.indexOf(filterVal) > -1
				$(this)[(filterMatch)?"removeClass":"addClass"]('filtered');
			})

			Cms.Station.countHidden($(this).parents('.child-forums'));

		},

		toggleFilter: function(target,showAll){

			var pool = $(target).parents('.child-forums').children('.forums-list');

			$(target).addClass('selected').siblings().removeClass('selected')

			if(showAll){
				pool.children('.pre-filtered').removeClass('pre-filtered')
				Cms.Station.countHidden($(target).parents('.child-forums'))
			}
			else
				pool.children(':not([alt=flagged])').addClass('pre-filtered')

		},

		clearFilter: function(target){

			var parentRoot = $(target).parents('.child-forums')

			var allButton = parentRoot.find('.filter-options a:last')

			if(allButton.length > 0)
				allButton.click();
			else
				Cms.Station.toggleFilter(target,true)

			parentRoot.find('input.filter').val('').trigger('keyup')

		},

		countHidden: function(target){

			var filtered = target.find('.forum-link:hidden')

			if(filtered.length > 1)
				target.find('.hidden-count').show().children('.hidden-value').text(filtered.length)
			else
				target.find('.hidden-count').hide();
		},


		btLiteScroll: function(dir) { //Blizz-Tracker Lite Header Animation

			if (typeof locX == 'undefined') {
				origX = locX = parseFloat($('#bt-holder').css('left').replace('px', ''));
			}

			var maxLeft = ($('#bt-holder > div').length/3) * this._WOFFSET - origX;
			$('#bt-holder').css('width', maxLeft + origX);
			var targX = locX + this._WOFFSET * dir;

			if (targX <= origX && targX > -maxLeft) {
				locX = targX;
				//console.log(this._WOFFSET +"//"+ maxLeft +"//"+ locX )
				$('#bt-holder').stop().animate({'left':locX});
				$('#station-view .bt-left')[targX == origX ? "fadeOut" : "fadeIn"]();
				$('#station-view .bt-right')[targX <= this._WOFFSET - maxLeft ? "fadeOut" : "fadeIn"]();
			}
		},
		parentToggle: function(targ, ev) {
			var forumParentToggle = Cookie.read('forumParentToggle')
			forumParentToggle = (forumParentToggle != null)?decodeURIComponent(forumParentToggle).split(','):[];
			var arrayLoc = $.inArray(targ.toString(),forumParentToggle)
			if(arrayLoc > -1) forumParentToggle.splice(arrayLoc,1)
			else forumParentToggle.push(targ.toString())
			Cookie.create('forumParentToggle',encodeURIComponent(forumParentToggle.join(',')),{path:Core.baseUrl+"/forum/", expires: 8760});
			$('#child' + targ).slideToggle();
			$(ev).toggleClass('collapsed').blur();
		}
	},
	Topic: {
		toggleCharacter:function(toggle,ref){
			$.get(Core.baseUrl+"/../preference/character?display="+toggle,
				   function(){
					  	//$.get(Core.baseUrl+"/../nop?reload");
						$('.character-options .gameCharHide')[(toggle)?"show":"hide"]();
						$('.character-options .gameCharShow')[(toggle)?"hide":"show"]();
						$('.userCharacter')[(toggle)?"fadeIn":"fadeOut"]("fast");
						$('.character-options').hide();
				 	});
		},
		postValidate:function(target){
			var err = 0,
				errString = [],
				editorMax = $('#editorMax').attr('rel'),
				subject = $('#subject'),
				editor = $('#post-edit .post-editor'),
				value = BML.textarea.val();

			$('#post-errors').html("");

			if (subject.length > 0 && subject.val().trim() == '') {
				err++;
				errString.push(Msg.cms.validationError);
				subject.css('border', '1px solid red');
			} else {
				subject.css('border', 'none');
			}

			if (value.replace(/<[^>+]>/g,'').trim() == '') {
				err++;

				if (errString[0] != Msg.cms.validationError)
					errString.push(Msg.cms.validationError);

				editor.css('border', '1px solid red');
			} else {
				editor.css('border', 'none');
			}

			if (value.length > editorMax) {
				err++;
				errString.push(Msg.cms.characterExceed.replace('XXXXXX', editorMax));
				editor.css('border', '1px solid red');
			}

			if (err > 0) {
				var ul = $('<ul/>').appendTo('#post-errors');

				for (var i = 0; i < errString.length; ++i) {
					$('<li/>').html(errString[i]).appendTo(ul);
				}
				
				return false;
			} else {
				return true;
			}
		},
		vote: function (postId, voteType, val, type) {
			var postURI = Core.baseUrl + ((type == 'comments') ?  "/discussion/comment" : "/forum/topic/post")
					+ '/' + postId + '/' + voteType;
			$('#thread .rate-action').hide();
			$.ajax({ 	type : 'POST',
				   		url : postURI,
					 	data : { voteValue: val, xstoken:xsToken },
						success: function(e) {
							//console.log(e);
							var rateDir = (e.vote > 0)?"up":"down"
							$("#k-" + postId).addClass('voted')
							$("#k-" + postId + ' .rate-btn').parent().removeClass('selected')
							$("#k-" + postId + ' .rate' + rateDir).parent().addClass('selected');
						},
						error: function(request,status,error) {
							//console.log(request);
							Overlay.open(request.statusText);
						}
				   });
		},
		report: function(postId,accountName,target) {
			$('#thread .rate-action').hide();
			$('#thread .reporting').removeClass('reporting'); // Remove class if report exists
			$('#'+target).addClass('reporting');

			$('#report-table').show(); //Reset post format
			$('#report-success').hide();
			$('#report-detail').val('');

			$('#report-post').insertAfter($('#'+target))
				.show();
			$('#report-postID').html(postId);
			$('#report-poster').html(accountName);
		},
		reportSubmit: function(type){
			var postId = $('#report-postID').html(),
				postURI = Core.baseUrl + ((type == 'comments') ?  "/discussion/comment" : "/forum/topic/post")
					+ '/' + postId + '/report',
				reason = $.trim($('#report-detail').val());

			if(reason == '' || reason.length > 256){
				if(reason == '')
					Overlay.open(Msg.cms.validationError)
				if(reason.length > 256)
					Overlay.open(Msg.cms.characterExceed.replace('XXXXXX',256))
				$('#report-detail').addClass('response-error')
				return
			}
			$('#report-detail').removeClass('error')

			$.ajax( { 	type: 		'POST',
				   		url:		postURI,
						data:		{	type:	$('#report-reason').val(),
										reason:	reason,
										xstoken:xsToken
									},
						success:	function(e){
										//console.log(e);
										$('.reporting').removeClass('reporting');
										$('#report-table').hide();
										$('#report-success').show();
									},
						error: function(e){
									//console.log(e);
							 	}
				   });
		},
		reportCancel: function() {
			$('.reporting').removeClass('reporting');
			$('#report-post').hide();
		},
		countDownInit:function() {
			Cms.cdTimeout = setInterval ("Cms.Topic.countDownUpdate()",1000)
			$("#submitBtn").hide();
		},
		countDownUpdate:function(){
			targ = $('#postTimeCountdown')
			var remains = Number(targ.html())
			if(--remains <= 0) {
				clearInterval(Cms.cdTimeout)
				$("#submitBtn").show();
				$("#postCountdown").hide();
			}
			else targ.html(remains)
		},
		voteSticky:function(firstPostId){

			$.ajax( { 	type: 		'POST',
				   		url:		Core.baseUrl + "/forum/topic/post/" + firstPostId + "/report",
						data:		{	type:	'STICKY_REQUEST',
										reason:	' ',
										xstoken:xsToken
									},
						success:	function(e){
										//console.log(e);
										$('.sticky-request').hide();
										Overlay.open(Msg.cms.stickyRequested)
									}
				   });

		},
		topicInit: function(topicId) {
			$('.rate-btn-holder').bind('mouseleave', function() {
					$(this).children('.rate-action').hide();
				})
			$('.user-name').bind('mouseleave', function() {
					//$(this).children('.character-options').hide();
				})

			Cms.ajaxErrorInit();
			Cms.Topic.readThread(topicId);
			if($.trim($('#post-errors > div').html())!= ''){
				$('#post-errors').hide();
				Overlay.open('#post-errors')

			}
		},
		topicInitIe: function(){
			$('#thread .post').bind('mouseenter',function(){ $(this).addClass('iehover'); })
							  .bind('mouseleave',function(){ $(this).removeClass('iehover'); });
		},
		previewToggle: function(target, type) {
			target = $(target);
			target
				.addClass('selected')
				.siblings('.selected').removeClass('selected');

			var preview = $('#post-preview');
			var edit = $('#post-edit');

			if (type == 'preview') {
				var postTitle = '';

				if ($('#subject').length > 0)
					postTitle = '<h3>'+ $('#subject').val().replace(/&/g,'&amp;') +'</h3>';

				edit.hide();
				preview.show().html(postTitle + BML.toHtml());
			} else {
				preview.hide();
				edit.show();
			}
		},

		cachedQuotes: {},

		quote: function(target, userName, post_id, page){
			if (Cms.Topic.cachedQuotes[post_id]) {
				var data = Cms.Topic.cachedQuotes[post_id];

				BML.quote(data.detail, data.name, post_id, page);
				return;
			}

			$.ajax({
				dataType: 'json',
				type: 'GET',
				url: Core.baseUrl +'/forum/topic/post/'+ post_id +'/frag',
				success: function(data) {
					Cms.Topic.cachedQuotes[post_id] = data;
					BML.quote(data.detail, data.name, post_id, page);
				}
			})
		},

		pollRefresh: function(bool, data) {
			if (bool) {
				$("#poll-container .result-container .result").each(function() {
						var targw = $(this).width();
						$(this).width(0).animate({width:targw}, "slow");
					});
			} else {
				var targr = $('#poll-container .result-container .result');
				var totalOpt = targr.length;
				var totalVotes = 0;
				for (x in data) {
					totalVotes += data[x];
				}
				// targr.each(function(){
				//     var targw = $(this).width();
				//     $(this).animate({width:targw}, "slow");
				// } )
			}
		},
		pollToggle: function(anch, target, pollId) {
			if ($(anch).hasClass('selected') && target == 'vote') {
				// Vote
				Cms.Topic.pollVote(pollId);
			};

			$('#poll-container .' + target).show()
					.siblings('div').hide();

			if (!$(anch).hasClass('selected') && target == 'results') {
				// Animate Results
				Cms.Topic.pollRefresh(true);
			}

			$(anch).addClass('selected').siblings().removeClass('selected');
		},
		pollVote: function(pollId) {
			var voteValue = [];
			$("#poll-container input:checked").each(function() {
				voteValue.push($(this).val());
			});
			if(voteValue.length == 0) { return; }
			$.post( Core.baseUrl + "/forum/topic/poll/" + pollId + "/vote?selection=" + voteValue.join('&selection=')+"&xstoken="+xsToken,
					function(data) {
						//console.log(data);
						window.location.reload();
					   	/*$('#poll-container .v-btn').addClass('voted');
						$('#poll-container .r-btn').click();
						Cms.Topic.pollRefresh(false, data);
						*/
					}
				); //End Post
		},
		readThread:function(id){
			var threadRead = Cookie.read('visitedThread')
			threadRead = (threadRead != null)?decodeURIComponent(threadRead).split(','):[];

			var d = new Date;
			d = d.getTime()

			var mod = false
			for(x in threadRead)
			{ 	threadRead[x] = threadRead[x].split('//');
				if(threadRead[x][0] == id) { threadRead[x][1] = d; mod = true; }
			}

			if(!mod) threadRead.push([id,d])
			for(x in threadRead) { threadRead[x] = threadRead[x].join('//'); }

			if(threadRead.length > 100) threadRead.shift()
			Cookie.create('visitedThread',encodeURIComponent(threadRead.join(',')),{path:Core.baseUrl+'/forum', expires: 8760});
		}
	},
	Forum: {
		threadListInit:function(){
			$('.post-title a').bind('click', function(){ $(this).parent().parent().addClass('read'); })
		},
		setView:function(type,target){
			Cookie.create('forumView', type, {path:"/", expires: 8760} );

			$(target).addClass('active')
				.siblings()
				.removeClass('active');

			$('#posts').attr('class',type)

			$('#posts').html($('#posts').html()) // force IE 6/7 redraw.

		},
		initContextQuotes: function(thread_id, page) {
			$(document).click(function() {
				var selection;
				if (window.getSelection)
					selection = window.getSelection().toString();
				else
					selection = document.selection.createRange().text;

				if (selection == "")
					$('.quote-button').remove();
			});

			$('#thread .post-detail').mouseup(function(e) {
				var selection;
				if (window.getSelection)
					selection = window.getSelection().toString();
				else
					selection = document.selection.createRange().text;

				// Remove old buttons
				$('.quote-button').remove();

				// Create button and position
				if (selection != "") {
					var node = $(this);
					var post = node.parents('.post');
					var author = $.trim(post.find('.char-name-code').html());
					var id = post.attr('id').replace('post-', "");

					$('<button type="button"/>')
						.html('<span><span>'+ Msg.bml.quote +'</span></span>')
						.addClass('ui-button button2 quote-button')
						.appendTo('body')
						.click(function() {
							BML.quote(selection, author, id, page);
							$(this).remove();
							window.location = '#new-post';
						})
						.css({
							top: e.pageY,
							left: e.pageX,
							position: 'absolute'
						});
				}
			});
		}
	},
	Comments: {
		replyTo: function(target, parent, author) {
			//Cms.anchorTo(target);
			var cId = target,
				target = $("#c-" + target),
				cfr = $('#comment-form-reply'),
				cmtTextarea = $('#comment-ta-reply');

			if (cfr.prev().attr("id") != target.attr("id")) {
				var commentText = "@" + author + ": ";

				cfr.slideUp(50, function() {
					cmtTextarea.val(commentText).focus();
					$(this).insertAfter(target).slideDown(50);
				});

			}
			else
				cfr.slideToggle(50);

			$('#replyTo').val(parent);
		},
		validateComment:function(target){
			var ta = $(target).find("textarea")
			if(ta.val().trim() == ''){
				ta.css('borderColor',"red");
				Overlay.open(Msg.cms.validationError);
				return false;
			}
			else return true;
		},
		commentInit: function() {
			$('.rate-btn-holder').bind('mouseleave', function() {
					$(this).children('.rate-action').hide();
				})
			$('.auto-expand').each(function(){
									 var taRef = $('<div class="ta-sizeRef"></div>')
									 						.attr('class',$(this).attr('class'))
															.html($(this).val().replace(/\n/g,'<br/>').replace(/\s{2}/g,' &#160;'))
															.width(($(this).width())*0.98)
															.insertAfter($(this))
									$(this).bind('keyup',function(){
															taRef.html($(this).val().replace(/\n/g,'<br/>').replace(/\s{2}/g,' &#160;'));
															$(this).height(taRef.height())
														})
											.bind('focus',function(){$(taRef).width(($(this).width())*0.98)})
											.height(taRef.height())
									})
		},
		commentInitIe: function() {
			$('#page-comments .comment').bind('mouseenter',function(){ $(this).addClass('iehover'); })
										.bind('mouseleave',function(){ $(this).removeClass('iehover'); });
		}
	},
	Blog: {
		getRelated: function(kw, excludeId) {
			$.get(Core.baseUrl + '/sidebar/articles.frag?k=' + kw + '&exclude=' + excludeId,
					function(data){
						$('#sidebar-related').show();
						var dataContent = (typeof data == 'string')?data:data.documentElement.innerHTML
						$('#related-news').html(dataContent);
					}
				 );
		}
	}
}
