var PPinit = false, showFullSrcPopup = false;

$(function() {
	
	$("#lv_0").show();
	$("span.video-pointer").click(function(e) {
		e.preventDefault();
		var i = this.getAttribute("id").charAt(this.getAttribute("id").length - 1);
		$("span.video-pointer").removeClass("active");
		$(this).addClass("active");
		$(".select-main-video").hide();
		$("#lv_" + i).show();
	});
	
	$("#video-filter select").change(function(e) {
		var url = window.location.pathname, u = '';
		var a = url.split("/");
		for(var i = 0; i < a.length; i++) {
			if(a[i] == "sort")
				u = '/' + a[i] + '/' + a[i + 1];
		}
		if(this.value == 0)
			window.location = '/index/gallery' + u;
		else
			window.location = '/index/gallery' + u + '/album/' + this.value;
	});
	
	$("#video-filter2 select").change(function(e) {
		var url = window.location.pathname, u = '';
		var a = url.split("/");
		for(var i = 0; i < a.length; i++) {
			if(a[i] == "sort")
				u = '/' + a[i] + '/' + a[i + 1];
		}
		
		if(this.value == 0)
			window.location = '/index/gallery' + u;
		else
			window.location = '/index/gallery' + u + '/album/' + this.value;
	});
	
	var index = 1;
	$('.relate-gallery-select-box .images-arr-left').click(function(e){
		var l = $('.gallery-images-list td');
		if(index > 1){
			$('.gallery-images-list').animate({
				marginLeft: '+=160'
			}, 200, function() {
				index--;
			});
		}
	});
	$('.relate-gallery-select-box .images-arr-right').click(function(e){
		var l = $('.gallery-images-list td');
		if(index <= (l.length - 4)){
			$('.gallery-images-list').animate({
				marginLeft: '-=160'
			}, 200, function() {
				index++;
			});
		}
	});
	
	var index2 = 1;
	$('.relate-gallery-select-box .video-arr-left').click(function(e){
		var l = $('.gallery-video-list td');
		if(index2 > 1){
			$('.gallery-video-list').animate({
				marginLeft: '+=160'
			}, 200, function() {
				index2--;
			});
		}
	});
	$('.relate-gallery-select-box .video-arr-right').click(function(e){
		var l = $('.gallery-images-list td');
		if(index2 <= (l.length - 4)){
			$('.gallery-video-list').animate({
				marginLeft: '-=160'
			}, 200, function() {
				index2++;
			});
		}
	});
	
	$("#general-comments-1").show();
	$("a.tabs-link").click(function(e){
		e.preventDefault();
		var i = this.getAttribute("id").charAt(this.getAttribute("id").length - 1);
		$("a.tabs-link").removeClass("active");
		$(this).addClass("active");
		$(".comments-box").hide();
		$("#general-comments-" + i).show();
	});
	
	var isFormActive = false;
	$("a.reply").click(function(e){
		e.preventDefault();
		if(isFormActive && $(this).hasClass("formActive")) {
			$("a.reply").removeClass("formActive");
			$("#new_comment_form").remove();
			isFormActive = false;
		}
		else {
			var p = this.offsetParent;
			var p_id = p.getAttribute("id");
			var post_id = p.getAttribute("post_id");
			var stype = p.getAttribute("stype");
			$("a.reply").removeClass("formActive");
			$(this).addClass("formActive");
			if($("#new_comment_form"))
				$("#new_comment_form").remove();
			
			$(p).after('<form method="post" id="new_comment_form"><textarea name="new_comment_body" id="new_comment_body" rows="5"></textarea><input type="hidden" name="parent_id" value="' + p_id + '"/><input type="hidden" name="post_id" value="' + post_id + '"/><input type="hidden" name="stype" value="' + stype + '"/><span class="button-wrapper fr"><input type="submit" name="submit" value="' + submit_title + '" /></span><div class="cl"></div></form>');
			addComment();
			isFormActive = true;
		}
	});
	
	$("body").append('<div id="pBoxUnderlayer"></div><div id="pBox"><div class="pBox-inner"><div class="title"></div><div class="close"></div><div id="pBox-content" class="content"></div></div></div>');
	$(".login-button").click(function(evt){
		evt.stopPropagation();
		evt.preventDefault();
		
		loadContent({
			url:"/auth/login/type/1",
			type:"GET",
			dataType:"text",
			callback:function(result){
				$("#pBoxUnderlayer").show();
				$("#pBox-content").html(result);
				//$("#pBox-content").append('<div id="controlsHolder"><span class="button-wrapper fl"><a  class="button">' + btn_login + '</a></span><span class="button-wrapper fl"><a class="button">' + btn_cancel + '</a></span></div>');
				$("#pBox .close").click(function(){
					$("#pBox").css("visibility", "hidden");
					$("#pBoxUnderlayer").hide();
				});
				
				var w = $(window).width();
				var h = $(window).height();
				var screenX, screenY;
				if (window.screenLeft) {
					// IE
					screenX = window.screenLeft;
					screenY = window.screenTop;
				} else {
					screenX = window.screenX;
					screenY = window.screenY;
				}
				var popW = $("#pBox").outerWidth(), popH = $("#pBox").outerHeight();
				var x = (w-popW)/2, y = (h-popH)/2;
				
				$("#pBox").css("top", y + "px");
				$("#pBox").css("left", x + "px");
				$("#pBox").css("visibility", "visible");
				
				$('#vk-auth').click(function(evt){
					evt.stopPropagation();
					evt.preventDefault();
					VK.init({apiId:2707939});
					VK.Auth.login(function(response){
						VK.api("getProfiles", {uids:response.session.user.id,fields:'uid,first_name,last_name,nickname,screen_name,sex,bdate,city,country,timezone,photo,photo_medium,photo_big,has_mobile,rate'}, function(data) {
							window.location = '/auth/vklogin?uid=' + data.response[0].uid + '&last_name=' + encodeURI(data.response[0].last_name) + '&first_name=' + encodeURI(data.response[0].first_name) + '&photo=' + encodeURI(data.response[0].photo);
						});
					});
				});
			}
		});
	});
	
	$('div.auth.logged-in').click(function(e) {
		$(this).toggleClass("active");
	});
	
	var scrubberPos = 0, lastcommentsPos = 0;
	$(".lastcomments .newslist .scrubber").mousedown(function(evt) {
		var h = $(".lastcomments .newslist .scrollbar").height() - 2;
		var ulh = $(".lastcomments .newslist ul").height();
		var d = $(".lastcomments .newslist ul").height()/($(".lastcomments .newslist .scrollbar").height() - 2);
		var mt = evt.pageY, t;
		
		$(window).mousemove(function(e) {
			if((e.pageY - mt) < 0) {
				scrubberPos = 0;
				lastcommentsPos = 0;
			}
			else if((scrubberPos + $(".lastcomments .newslist .scrubber").height()) > ($(".lastcomments .newslist .scrollbar").height() - 4)) {
				scrubberPos = scrubberPos;
				lastcommentsPos = lastcommentsPos;
			}
			else {
				scrubberPos = e.pageY - mt;
				lastcommentsPos = mt - e.pageY;
			}
			$(".lastcomments .newslist .scrubber").css("top", scrubberPos + "px");
			$(".lastcomments .newslist ul").css("top", lastcommentsPos * d + "px");
		});
	});
	
	$(window).mouseup(function(){ $(window).unbind('mousemove'); });
	
});

function reloadPage()
{
	window.location.reload();
}

/*--------------------------------------------------------------------------
 *
 * Set Cookie
 */
function setCookie(c_name,value,exdays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate() + exdays);
	var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
	document.cookie=c_name + "=" + c_value + "; path=/;";
}

/*--------------------------------------------------------------------------
 *
 * Set Language
 */
function setLanguage(name)
{
	setCookie("lang", name, 365);
	reloadPage();
}

/*--------------------------------------------------------------------------
 *
 * Set click
 */
var clicked = false;

function doClick(sel,type)
{
	if(!clicked)
	{
		var xhr = $.ajax({
			type: "GET",
			url: "/admin/set-click?id=" + sel + '&type=' + type,
			dataType: "html"
		});
	}
}

/*--------------------------------------------------------------------------
 *
 * Move window
 */
function moveWindow(anchor) {
	if(anchor == "comments")
		window.location.hash = "comments";
}

/*--------------------------------------------------------------------------
 *
 * Set Grade
 */
var evaluated = false;

function grade(vale, id, vote, generalVote)
{
	if(!evaluated)
	{
		evaluated = true;
		var xhr = $.ajax({
			type: "GET",
			url: "/admin/set-grade?grade=" + vale + '&id=' + id
		})
		.success(function(responce){
			if(responce == "1")
				resetGrade(vale, id, vote, generalVote);
		});
	}
}

function resetGrade(vale, id, vote, generalVote)
{
	if(generalVote > 0)
		vote ++;
	
	generalVote = parseInt(generalVote) + parseInt(vale);
	currentVote = Math.round(generalVote/vote);
	var vl = 1;
	for(i = 0; i < currentVote; i++)
	{
		document.getElementById("star_" + vl).src = "/public/images/design/star.png";
		vl++;
	}
	for(i=0; i<5-currentVote; i++)
	{
		document.getElementById("star_" + vl).src = "/public/images/design/grey_star.png";
		vl++;
	}
}

/*--------------------------------------------------------------------------
 *
 * Load Content
 */
function loadContent(options) {
	var defaults = {
		type: "GET",
		url: "404.html",
		dataType: "text",
		data: ""
	};
	var options = $.extend(defaults, options);
	
	var xhr = $.ajax({
			type: options.type,
			url: options.url,
			dataType: options.dataType,
			data: options.data
		})
		.success(function(result) {
			if(result.error != 1) {
				options.callback(result);
			}
			else if(typeof result == "object") {
				alert(error_notobject);
			}
			else {
				alert(error_message);
			}
		})
		.error(function() {
			alert(error_message);
		});
}

/*--------------------------------------------------------------------------
 *
 * Leave comment
 */
function addComment() {
	$('#new_comment_form').submit(function() {
		if($("#new_comment_body").val() == '') {
			alert(empty_comment);
			return false;
		}
		
		loadContent({
			url:"/index/replycomment",
			type:"POST",
			dataType:"json",
			data: $(this).serialize(),
			callback:function(result){
				$("#new_comment_form").remove();
				window.location.reload();
			}
		});
		return false;
	});
}

/*--------------------------------------------------------------------------
 *
 * Show full image
 */
function showFullSrc(src, alt, w, h) {
	if(!showFullSrcPopup) {
		$("body").append('<div id="popupBox"><div class="close">&times;</div><div class="content"></div></div>');
		$("#popupBox .close").click(function(){
			$("#popupBox").css("visibility", "hidden");
		});
		showFullSrcPopup = true;
	}
	
	$("#popupBox .content").html('').append('<img src="' + src + '" alt="' + alt + '" />');
	if($("#popupBox .content img").outerWidth() > 800) {
		$("#popupBox .content img").css("width", "800px");
	}
	else if($("#popupBox .content img").outerHeight() > window.innerHeight) {
		$("#popupBox .content img").css("height", window.innerHeight - 40 +"px");
	}
	
	if(window.innerHeight)
		$("#popupBox").css("top", window.innerHeight/2 - $("#popupBox").outerHeight()/2 + "px");
	else
		$("#popupBox").css("top", "100px");
	$("#popupBox").css("left", document.body.clientWidth/2 - $("#popupBox").outerWidth()/2 + "px");
	$("#popupBox").css("visibility", "visible");
	
	$(window).keypress(function(event) {
		if(event.keyCode == 27) {
			$("#popupBox").css("visibility", "hidden");
			$(window).unbind('keypress');
		}
	});
}
