var settings = {
	'language' : '',
	'loading': '<img src="/static/plugins/bubble/loading.gif" alt="Loading..." />',
	'userAdditionalPopupInformationLink' : '',
	'commentsVoteLink' : '',
	'nick' : 'nick'
};

var translates = {
	'nick'					: 'nick',
	'wait'					: 'wait',
	'comment_edit'			: 'comment_edit',
	'comment_delete'		: 'comment_delete',
	'video_delete'			: 'video_delete',
	'title_text'			: 'title_text',
	'config_edit'			: 'config_edit',
	'search_text_invalid'	: 'search_text_invalid'
};

var core = {
	'language'			: '',
	'logged'			: 0,
	'admin'				: 0,
	'commentTimeout'	: 0,
	'voted'				: 0,
	'onlineRefresh'		: 30000,
	'siteRefresh'		: 1800000
};

var site = new function() {
	
	// 
	//		Comments
	//
	
	var curQuote = 0;

	this.canComment = function() {
		var differ = core.commentTimeout - Math.round(new Date().getTime()/1000);
		if (differ > 0) {
			apprise('Wait ' + differ);
		}
		return (differ <= 0); 
	}
	
	this.commentModify = function(commentId) {
		$.post(window.location.pathname, { commentGet: commentId }, function(data) {
			apprise(translates.comment_edit, {'confirm' : true, 'input' : data}, function(result) {
				if (result) {
					$.post(window.location.pathname, { commentModify: commentId, comment: result }, function(anchor) {
						document.location.href = window.location.pathname + '#' + parseInt(anchor);
						document.location.reload(true);
					});
				}
			});
		});
	}
	
	this.commentDelete = function(commentId) {
		apprise(translates.comment_delete, {'verify' : true}, function(result) {
			if (result) {
				$.post(window.location.pathname, { commentDelete: commentId }, function(data) {
					document.location.reload(true);
				});
			}
		});
	}
	
	this.commentQuote = function(quoteId) {
		$('#comment_quote').val(quoteId);
		var lastimg = document.getElementById('q' + curQuote);
		if (lastimg != null) {
			lastimg.src = "/templates/v1/img/comments/quote.gif";
		}
		var curimg = document.getElementById('q' + quoteId);
		if (curimg != null) {
			curimg.src = "/templates/v1/img/comments/quote_selected.gif";
		}
		curQuote = quoteId;
	}
	
	//
	//		Vote
	//
	
	var voteLink = '/ajax/AJAXVote/';
	var voteSelector = '#vote_layer';
	
	this.doVote = function(voteId) {
		var answerId = $("input[type=radio]:checked").val();
		if (voteId && answerId) {
			$.get("/" + core.language + voteLink + voteId + "/" + answerId, function(data) {
				$(voteSelector).html(data);
			});
		}
	}
	
	//
	//		Videos
	//
	
	var videosLink = '/ajax/AJAXGetVideos/';
	var videosSelector = '#video_update';
	var videosPageSelector = '.videoPage';
	
	this.videoDelete = function(videoId) {
		apprise(translates.video_delete, {'verify' : true}, function(result) {
			if (result) {
				$.post(window.location.pathname, { videoDelete: videoId }, function(data) {
					document.location.reload(true);
				});
			}
		});
	}
	
	this.videosGetPage = function(pageNumber, pageObj) {
		$(videosPageSelector).removeClass('b');
		pageObj.addClass('b');
		$.get("/" + core.language + videosLink + pageNumber, function(data) {
			$(videosSelector).html(data);
		});
	}
	
	//
	//		Downloads
	//
	
	this.toggle = function(id) {
		$('#' + id).toggle('fast');
	}
	
	//
	//		Gallery
	//
	
	var galleryLastPage = 0;
	var galleryTotalPages = 0;
	var galleryThumbnailPrefixClass = '.thumbnail';
	var galleryCurPageSelector = '#galleryCurPage';
	
	this.gallerySetTotalPages = function(number) {
		galleryTotalPages = number;
	}
	
	this.galleryPrevThumbnailPage = function() {
		if (galleryLastPage > 0) {
			this.gallerySetThumbnailPage(Math.round(galleryLastPage) - 1);
		}
	}
	
	this.galleryNextThumbnailPage = function() {
		if (galleryLastPage < (galleryTotalPages - 1)) {
			this.gallerySetThumbnailPage(Math.round(galleryLastPage) + 1);
		}
	}
	
	this.gallerySetThumbnailPage = function(number) {
		$(galleryThumbnailPrefixClass + galleryLastPage).css('display', 'none');
		$(galleryThumbnailPrefixClass + number).css('display','block');
		$(galleryCurPageSelector).html(Math.round(number) + 1);
		galleryLastPage = number;
	}
	
	//
	//		Stuff
	//
	
	this.escapeHtml = function(str) {
		//return str.replace(/<([^>]+)>/g, "");
		return str.replace(/</g, "&lt;").replace(/>/, "&gt;");
	}
	
	this.enableBBCode = function(str) {
		return str.
				// bold && italic && underline
				replace(/\[b\]/gi,'<b>').
				replace(/\[i\]/gi,'<i>').
				replace(/\[u\]/gi,'<u>').
				replace(/\[s\]/gi,'<s>').
				replace(/\[link\]/gi,'<a href"=').
				replace(/\[img\]/gi,'<img src"=').
				replace(/\[red\]/gi,'<span style="color:red">').
				replace(/\[blue\]/gi,'<span style="color:blue">').
				replace(/\[lv\]/gi,'<img src="/templates/v1/img/flags//lv.gif" alt="Latvia" />').
				replace(/\[ee\]/gi,'<img src="/templates/v1/img/flags//ee.gif" alt="Estonia" />').
				replace(/\[lt\]/gi,'<img src="/templates/v1/img/flags//lt.gif" alt="Lithuania" />').
				replace(/\[ru\]/gi,'<img src="/templates/v1/img/flags//ru.gif" alt="Russia" />').
				replace(/\[eu\]/gi,'<img src="/templates/v1/img/flags//eu.gif" alt="Europe" />').
				replace(/\[\/b\]/gi,'</b>').
				replace(/\[\/i\]/gi,'</i>').
				replace(/\[\/u\]/gi,'</u>').
				replace(/\[\/s\]/gi,'</s>').				
				replace(/\[\/link\]/gi,'" target="_blank"\><strong><span style="color:blue">[Link]</span></strong></a>').
				replace(/\[\/img\]/gi,'" alt="skillz.lv blog image" border="0"></img>').
				replace(/\[\/red\]/gi,'</span>').
				replace(/\[\/blue\]/gi,'</span>').
				replace(/\[jhz\]/gi,'<object align="bottom" width="796" height="448"><param name="allowscriptaccess" value="always" /><param name="movie" value="http://www.own3d.tv/livestream/17226" /><param name="allowfullscreen" value="true" /><param name="wmode" value="transparent" /><embed src="http://www.own3d.tv/livestream/17226" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="796" height="448" wmode="transparent"></embed></object>').
				replace(/\[hola\]/gi,'<object align="bottom" width="796" height="448"><param name="allowscriptaccess" value="always" /><param name="movie" value="http://www.own3d.tv/livestream/54009" /><param name="allowfullscreen" value="true" /><param name="wmode" value="transparent" /><embed src="http://www.own3d.tv/livestream/54009" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="796" height="448" wmode="transparent"></embed></object>').
				// nl2br
				replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br />$2');
	}
	
	this.follow = function(from, to, enablebb) {
		var f = $(from);
		var t = $(to);
		if (f != null && t != null) {
			if (enablebb) {
				t.html(site.enableBBCode(site.escapeHtml(f.val())));
			}
			else {
				t.html(site.escapeHtml(f.val()));
			}
			setTimeout('site.follow("' + from + '", "' + to + '", ' + enablebb + ')', 100);
		}
	}
	
	//
	//		Online users
	//
	
	var memberLinkSelector = '.member img';
	
	var onlineUsersSelector = '#online';
	var onlineUsersCountSelector = '#onlineCount';
	var onlineUsersLink = '/ajax/AJAXUsersOnline';
	
	this.updateOnlineUsers = function() {
		var selector = $(onlineUsersSelector);
		if (selector.size() > 0) {
			$.get("/" + core.language + onlineUsersLink, function(data) {
				$(memberLinkSelector).RemoveBubblePopup();
				$(selector).html(data);
				site.updateOnlineUsersCount();
				site.onlineSetUserTips();
				setTimeout("site.updateOnlineUsers();", core.onlineRefresh);
			});
		}
	}
	
	this.updateOnlineUsersCount = function() {
		var selector = $(onlineUsersCountSelector);
		if (selector.size() > 0) {
			selector.html($(onlineUsersSelector + " .member").size());
		}
	}
	
	//
	//		On load methods
	//
	
	this.titleOnLoad = function() {
		if ($("input[name=title]").val() == '') {
			$("input[name=title]").val(translates.title_text);
		}
		$("input[name=title]").blur(function() {
			if ($(this).val() == '') {
				$(this).val(translates.title_text);
			}
		});
		$("input[name=title]").focus(function() {
			if (($(this).val() == translates.title_text) || ($(this).val() == ''))  {
				$(this).val('');
			}
		});
	}

	this.onlineSetUserTips = function() {
		$(memberLinkSelector).RemoveBubblePopup();
		// add bubble to user link
		$(memberLinkSelector).CreateBubblePopup({
			selectable: false,
			
			position : 'right',
			align	 : 'center',
											
			innerHtml: settings.loading,
		
			innerHtmlStyle: {
				'color':'#FFFFFF', 
				'text-align':'left',
				'width':'160px'
			},
																				
			themeName: 	'all-black',
			themePath: 	'/static/plugins/bubble/jquerybubblepopup-theme/',
			
			openingSpeed:	50,
			closingSpeed:	50
										 
		});
		
		$(memberLinkSelector).mouseover(function(){
			var member = $(this);
			var nick = (member.attr('href') != undefined) ? member.attr('href'): member.parent().attr('href');
			if (nick != undefined) {
				nick = nick.replace(/^(.*)\/(.*)$/,'$2');
				var response = '<b>' + settings.nick + ':</b> ' + nick;
				member.SetBubblePopupInnerHtml(response, true);
			}
		});
	}
	
	//
	//	Comments
	//
	
	var commentsRateLink = '/ajax/AJAXCommentRate';
	var commentsRateSummaryLink = '/ajax/AJAXGetRateUsers';
	var commentsRateSummarySelector = '.comment_summary_rate';
	
	this.commentsOnLoad = function() {
		// comment vote
		$(".vote_plus").click(function() {
			var commentId = $(this).attr('comment');
			if (commentId > 0) {
				$.get("/" + core.language + commentsRateLink + '/' + $(this).attr('comment') + '/1', function(data) {
					$("#rate" + commentId).html(data);
				});
			}
		});
		$(".vote_minus").click(function() {
			var commentId = $(this).attr('comment');
			if (commentId > 0) {
				$.get("/" + core.language + commentsRateLink + '/' + $(this).attr('comment') + '/-1', function(data) {
					$("#rate" + commentId).html(data);
				});
			}
		});
		
		// comments rate users
		$(commentsRateSummarySelector).CreateBubblePopup({
			selectable: true,
			
			position : 'right',
			align	 : 'center',
											
			innerHtml: settings.loading,
		
			innerHtmlStyle: {
				'color':'#FFFFFF', 
				'text-align':'left',
				'width':'170px'
			},
																				
			themeName: 	'all-black',
			themePath: 	'/static/plugins/bubble/jquerybubblepopup-theme/',		 
		});
		$(commentsRateSummarySelector).mouseover(function(){
			var rateSummary = $(this);
			var commentId = $(this).attr('id').replace(/rate/i,"");
			$.get("/" + core.language + commentsRateSummaryLink + '/' + commentId, function(data) {
				if (data == '') {
					rateSummary.RemoveBubblePopup();
				}
				else {
					rateSummary.SetBubblePopupInnerHtml(data, true);
				}
			});
		});
		
		// comment visibility
		if (core.logged > 0) {
			$(".auth_not_logged").css('display', 'none');
		}
		else {
			$(".auth_logged").css('display', 'none');
		}
	}
	
	//
	// Search
	//
	var searchBoxSelector = '#search_text';
	var searchButtonSelector = '#search_button';
	var searchLink = '/search/news/';
	
	this.searchSubmit = function() {
		if ($(searchBoxSelector).val().length >= 3) {
			document.location.href = "/" + core.language + searchLink + $(searchBoxSelector).val();
		}
		else {
			apprise(translates.search_text_invalid);
		}
	}
	
	this.searchOnLoad = function () {
		$(searchBoxSelector).keypress(function(e) {
			if(e.which == 13) {
				site.searchSubmit();
			}
		});

		$(searchButtonSelector).click(function() {
			if ($(searchBoxSelector).val().length >= 3) {
				document.location.href = "/" + core.language + searchLink + $(searchBoxSelector).val();
			}
			else {
				apprise(translates.search_text_invalid);
			}
		});
	}
	
	this.refreshTimeout = function() {
	setTimeout("site.pageRefreshDo();", core.siteRefresh);
	}

	this.pageRefreshDo = function() {
		location.reload(true);
	}
	
};

$(document).ready(function() {
	// set user tips
	site.onlineSetUserTips();
	
	// set site refresh
	site.refreshTimeout();
	
	// set title
	site.titleOnLoad();
	// set visible|invisible logged|notlogged elems
	site.commentsOnLoad();
	
	// set online users
	site.updateOnlineUsersCount();
	setTimeout("site.updateOnlineUsers();", core.onlineRefresh);
	
	// set search handler
	site.searchOnLoad();
	
	// vote handler
	if (core.voted == 1) {
		$("#vote_answers").css('display', 'block');
	}
	else {
		$("#vote_form").css('display', 'block');
	}
	
	// round corners
	$(".title").corner("4px"); 
	$(".menu").corner("4px"); 
	$(".article .image img").corner("6px");
	$(".movie_vlocal img").corner("6px");
});
