/**
 * Слайдер
 */

var funs = [];

var currentFunid = -1;

var maxLength = 250;

function doKeyPress(event) {
	var textArea = $(event.target);
	var charCode = event.charCode;
	if ((charCode == 32) || (charCode == 13) || (charCode > 47)) { 
		if (maxLength && (textArea.val().length > maxLength - 1)) {
			 	event.preventDefault();
				return false;
		}
	}
}

function doKeyUp(event) {
	var textArea = $(event.target);
	var limitOne = textArea.parent().children(".limitOne").children();
	if (maxLength && textArea.val().length > maxLength) {
		textArea.val(textArea.val().substr(0, maxLength));
	}
	str = textArea.val();
	limitOne.text(maxLength - str.length);
}

function authorLinkMouseOver(obj, event) {

	position = $(event.target).offset();
	pleft = position.left - 80 + 'px';
	ptop = position.top - 10 + 'px';

	$("#authorWindow").css({
		'top' : ptop,
		'left' : pleft
	});

	$("#authorPic").attr(
			'src',
			'resources/images/userpics/id' + $(obj).data('authorid')
					+ '_64.png');

	$("#authorWindow").show();
	$('#authorActionProfile').attr('href',
			'/profile?id=' + $(obj).data('authorid'));
	
	$('#authorActionStories').attr('href',
			'/stories?person=' + $(obj).data('authorid'));

	if ($(obj).data('authorid') != $("#authorActionRateUp").data('authorid')) {
		$("#authorActionSend").click(function() {
			position = $("#authorWindow").offset();
			pleft = position.left - 10 + 'px';
			ptop = position.top - 50 + 'px';

			$("#writeOneMessageWindow").css({
				'top' : ptop,
				'left' : pleft
			});

			$('#writeOneMessageWindow').show();
			message = true;

			$('#oneMessageAnswerText').val('');
			$('#oneMessageAnswerText').focus();
		});

		$("#writeOneMessageWindowSend").data('authorid',
				$(obj).data('authorid'));
		$('#writeOneMessageWindowSend').unbind('click');
		$('#writeOneMessageWindowSend').button().click(
				function() {
					msg = $('#oneMessageAnswerText').val();
					tsTimeStamp= new Date().getTime();
					$.ajax({
						type : 'POST',
						data : {data : tsTimeStamp},
						url : 'ajax?message=' + escape(encodeURIComponent(msg))
								+ '&id=0' + '&to=' + $(obj).data('authorid'),
						success : function(response) {
							$("#writeOneMessageWindow").hide();
							sliderFuns.resumeTimer();
						},
						error : function(ex) {
							dialog.messageBox('Error!  Status = ' + ex.status);
						}
					});
				});

		$('#writeOneMessageWindowClose').click(function(event) {
			$('#writeOneMessageWindow').hide();
			message = false;
			sliderFuns.resumeTimer();
		});

	}

	$("#writeOneMessageWindow").hide();
};

function sendMessageTo(personid, event){

	position = $(event.target).offset();
	pleft = position.left - 50 + 'px';
	ptop = position.top - 60 + 'px';
	$("#writeOneMessageWindow").css({
		'top' : ptop,
		'left' : pleft
	});
	$('#writeOneMessageWindow').show();
	message = true;
	$('#oneMessageAnswerText').val('');
	$('#oneMessageAnswerText').focus();


	if (personid != $("#writeOneMessageWindowSend").data('authorid')) {		
		$("#writeOneMessageWindowSend").data('authorid',
				personid);
		$('#writeOneMessageWindowSend').unbind('click');
		$('#writeOneMessageWindowSend').button().click(
				function() {
					msg = $('#oneMessageAnswerText').val();
					tsTimeStamp= new Date().getTime();
					$.ajax({
						type : 'POST',
						data : {data : tsTimeStamp},
						url : 'ajax?message=' + escape(encodeURIComponent(msg))
								+ '&id=0' + '&to=' + $(this).data('authorid'),
						success : function(response) {
							$("#writeOneMessageWindow").hide();
						},
						error : function(ex) {
							dialog.messageBox('Error!  Status = ' + ex.status);
						}
					});
				});

		$('#writeOneMessageWindowClose').click(function(event) {
			$('#writeOneMessageWindow').hide();
			message = false;
		});

	}

}

var sliderFuns = (function() {

	var slider, wrapper, arrowLeft, arrowRight, slides, timer, stopped = false, message = false,

	//
	// Методы
	//

	showFunWindow = function(funId) {
		/*
		 * var layer, getLayerHeight = function() { return $(window).height() -
		 * 40; }, height = getLayerHeight();
		 * 
		 * $(window).unbind('resize');
		 * 
		 * layer = $('<div id="funViewWindow" class="funViewWindow">' + '<button
		 * class="btnClose">Закрыть</button>' + '<iframe
		 * id="funViewWindowContent" style="border: 0; width: 970px; height:' +
		 * (height - 25) + 'px; overflow-x: hidden; overflow-y: auto;" />' + '</div>').appendTo('body');
		 * 
		 * layer.dialog({ modal : true, width : 1005, height : height, resizable :
		 * false });
		 * 
		 * $('.btnClose', layer).click(function(event) {
		 * layer.dialog('destroy'); });
		 * 
		 * $(window).resize(function() {
		 * 
		 * height = getLayerHeight(); layer.dialog('option', 'height', height);
		 * layer.dialog('option', 'position', 'center'); $('iframe',
		 * layer).css('height', (height - 25) + 'px');
		 * 
		 * });
		 * 
		 * $('iframe', layer).attr('src', 'story' + funId);
		 */
	},

	renderSingleFun = function(fun) {
		var singleFun = $('<div class="fun" id="funLarge' + fun.id + '"></div>');
		
		$('<a class="wrapperLink" target="_blank" href="story' + fun.id + '">' + 
							'<img src="resources/images/fununits/' + fun.pic + '" alt="" class="funImage">' +
						'</a>')
						.append('<div class="caption">' +
									'<h2>' + fun.largeText + '</h2>' +
									'<p class="profile-p"><a id="profile-link' + fun.id + '" class="profile-link" href="/profile?id=' +	fun.authorid + '">' + fun.smallText + '</a></p>' +
								'</div>')
						.appendTo(singleFun);
		
		singleFun.data('id', fun.id);
		singleFun.data('name', fun.largeText);
		singleFun.click(function(event) {
			//showFunWindow(singleFun.data('id'));
		});
		singleFun.mouseover(function() {
			stopTimer();
		});
		singleFun.mouseout(function() {
			resumeTimer();
		});

		$(".profile-link", singleFun).click(function(event) {
			event.stopPropagation();
		});

		$("a.wrapperLink", singleFun).click(function(event) {
			event.stopPropagation();
		});
		
		if (logged && fun.authorid != ownid) {

			$(".profile-link", singleFun).data('authorid', fun.authorid);
			$(".profile-link", singleFun).data('hasMessageSendAction', false);
			$(".profile-link", singleFun).mouseenter(function(event) {
				authorLinkMouseOver(this, event);
			});

			$("#authorWindow").mouseover(function(event) {
				stopTimer();
			});

			$("#authorWindow").mouseleave(function(event) {
				$("#authorWindow").hide();
				if (!message) {
					resumeTimer();
				}
			});
		}

		return singleFun;

	},

	renderAllFuns = function(funs) {
		$("body")
				.append(
						'<div id="authorWindow" class="authorWindow"><span class="authorImg" ><img id="authorPic" src=""></span><span class="authorActions"><a id="authorActionProfile" class="authorActionLink-profile" href="javascript:;">перейти на страницу</a> <a id="authorActionSend" class="authorActionLink" href="javascript:;">отправить сообщение</a> <a id="authorActionStories" class="authorActionLink-stories" href="javascript:;">истории успеха</a></span></div>');
		$('#authorWindow').hide();
		$("body")
				.append(
						'<div id="writeOneMessageWindow" class="writeOneMessageWindow"><div class="newMsg"><label>Новое сообщение:</label>'
						+ '<textarea cols="30" style="" rows="5" id="oneMessageAnswerText"></textarea>'
						+ '<div class="limitOne">Осталось символов: <span id="limitOne">250</span></div><button class="submit" id="writeOneMessageWindowSend">Отправить</button></div>'
						+ '<button id="writeOneMessageWindowClose" class="btnClose" title="Закрыть">Закрыть</button></div>');
		$('#writeOneMessageWindow').hide();
		
		$('#oneMessageAnswerText').keypress(function(event) {
			doKeyPress(event);
		});
		
		$('#oneMessageAnswerText').keyup(function(event) {
			doKeyUp(event);
		});
		
		$('#oneMessageAnswerText').bind('paste', function(event) {
			doKeyUp(event);
		});
		
		$('#oneMessageAnswerText').bind('blur', function(event) {
			doKeyUp(event);
		});

		wrapper.empty();

		$.each(funs, function() {
			wrapper.append(renderSingleFun(this));
		});

	},

	getStarFuns = function() {

		// TODO: В боевом режиме, поставить thread1, чтобы получить список
		// звёздных фанов
		var tsTimeStamp= new Date().getTime();
		
		$.getJSON('ajax/sliderFuns?&size=3', {data : tsTimeStamp}, function(data) {
			funs = [];
			$.each(data, function(key, fun) {
				funs.push({
					id : fun.id,
					pic : fun.pic,
					authorid : fun.authorid,
					largeText : fun.name,
					smallText : fun.author
				});

			});

			renderAllFuns(funs);
			findSlides();
			attachEvents();

		});

	},

	getNextFun = function() {
		var tsTimeStamp= new Date().getTime();
		
		$.getJSON('ajax/nextSliderFun', {data : tsTimeStamp}, function(fun) {

			if (fun && currentFunid !== fun.id) {
				funs.shift();
				currentFunid = fun.id;
				funs.push({
					id : fun.id,
					pic : fun.pic,
					authorid : fun.authorid,
					largeText : fun.name,
					smallText : fun.author
				});
				
			//	console.log('getNextFun success');

				onGetNextFunSuccess();
				
			}

		});

	},

	onGetNextFunSuccess = function() {

		checkLeftSlides();

	},

	findSlides = function() {

		slides = $('.fun', wrapper);

		return slides.length;

	},

	attachEvents = function() {

		/*
		 * arrowLeft.click(function() { scrollRight(); return false; });
		 * arrowRight.click(function() { scrollLeft(); return false; });
		 */

		setTimer();

	},

	setTimer = function() {

		if (!stopped) {
			timer = setInterval(function() {
				getNextFun();
			}, 5000);
		}

	},

	stopTimer = function() {

		clearInterval(timer);
		stopped = true;

	},

	resumeTimer = function() {

		if (stopped) {
			stopped = false;
			setTimer();
		}

	},

	scrollLeft = function() {

		if (!wrapper.is(':animated')) {

			wrapper.animate({
				left : '-=' + funWidth() + 'px'
			}, 1000, function() {
				slides.eq(0).remove();
				wrapper.css('left', wrapper.position().left + funWidth());
			});

		}

	},

	scrollRight = function() {

		if (!wrapper.is(':animated')) {

			do {
				checkRightSlides();
			} while (wrapper.position().left - funWidth() > 0);

			wrapper.animate({
				left : '+=' + funWidth() + 'px'
			}, 1000);

		}

	},

	checkLeftSlides = function() {

		wrapper.append(renderSingleFun(funs[funs.length - 1]));
		findSlides();
		scrollLeft();

	},

	checkRightSlides = function() {

		findSlides();
		wrapper.prepend(slides.last()).css("left",
				wrapper.get(0).offsetLeft - funWidth());

	},

	funWidth = function() {

		var slide = slides.eq(1);

		return slide.width() + parseInt(slide.css('marginRight'), 10);

	},

	init = function() {

		slider = $('.sliderFuns');
		wrapper = $('.wrapper', slider);
		arrowLeft = $('.left', slider);
		arrowRight = $('.right', slider);

		getStarFuns();

	};

	// Открытие некоторых свойств и методов для вызова извне
	return {

		init : init,
		showFunWindow : showFunWindow,
		resumeTimer : resumeTimer,
		stopTimer : stopTimer

	};

}());
