var timeout = 500;
var closetimer = 0;
var rotatorTimeout = 5000;
var rotatorInterval;
var fancyboxDefOptions = { overlayOpacity: 0.70, padding: 5};
var validatorValues = [];
var loginError = false;
var curvyCornersSettings = { tl: { radius: 10 },tr: { radius: 10 },bl: { radius: 10 },br: { radius: 10 },antiAlias: false} 
var urlPart = '';

$(function() {
	$.preloadImages(
		_appRoot + "/assets/background/pollbar-left.png", 
		_appRoot + "/assets/background/pollbar-middle.gif", 
		_appRoot + "/assets/background/pollbar-right.png"
	);
	
	// tabs
	$(".tab-control .tab-selector a:not(.disabled)").click(function() {
		current = $(this).parents(".tab-selector").find("a").index($(this));
		$(this).parents(".tab-selector").find("li").removeClass("active").end().end().parents("li").addClass("active");
		$(this).closest(".tab-control").find(".tab-content").find("> li").hide().eq(current).show();
		$(this).parents(".tab-selector").removeClass().addClass("state"+current).addClass("tab-selector");
		return false;
	});
	$(".tab-control .tab-selector").each(function(){ $(this).find("a:first").trigger("click"); })
	
	// rotator
	$(".rotator .selector a:not(.first, .last)").click(function() { 
		limit = 5;
		total = $(this).parent().find("a:not(.first, .last)").size();
		current = $(this).parent().find("a:not(.first, .last)").index($(this));
		mid = parseInt(limit/2);
		var left = current - mid;
		var right = current + mid;
		if (left < 0) {
			right = right - left;
			left = 0;
		}
		if (right > total - 1) {
			left = left + (total - right - 1);
			right = total;
		}
		$(this).parent().find("a:not(.first, .last)").show().filter(":lt("+left+")").hide().end().filter(":gt("+right+")").hide();
		$(this).parent().find("a").removeClass("active").end().end().addClass("active").parent().parent().find("li").hide().eq(current).show();
		});
	$(".rotator .selector a.first").click(function() { 
		current = $(this).parent().find("a:not(.first, .last)").index($(this).parent().find("a.active"));
		if (current > 0) { $(this).parent().find("a:not(.first, .last)").eq(current-1).trigger("click"); }
		});
	$(".rotator .selector a.last").click(function() { $(this).parent().find("a:not(.first, .last)").eq($(this).parent().find("a:not(.first, .last)").index($(this).parent().find("a.active"))+1).trigger("click"); });
	$(".rotator .selector").each(function(){ $(this).find("a:not(.first, .last):first").trigger("click"); })
	rotatorInterval = setInterval('autoRotate()', rotatorTimeout);
	
	// png fix for ie6
   $('.vip, .png, h3 span, .separator-green, .separator-green-small, .separator-orange, .separator-orange-small, .round-link').supersleight({ shim: _appRoot + '/assets/img/x.gif' });
		
	// fancybox
	if ($.isFunction($.fn.fancybox)) {
		$(".gallery a, a.main-img").fancybox(fancyboxDefOptions);
		$("a.popup").fancybox($.extend(fancyboxDefOptions, {}));
	}
	
	// ddl
	$('.ddl').bind('mouseover', ddmenu_open);
	$('.ddl').bind('mouseout',  ddmenu_closetimer);
	
	// vote
	$(".contestVote").click(function(){
		if (_logged) {
			id = $(this).attr('rel');
			result = $(this).parent().find("p span");
			$.get(_appRoot+"/ajax.php", { section: 'voting', action: 'vote', imgId: id},
			 function(data){
				result.text(data);
			});
		} else {
			alert("За да гласувате е нужно да сте регистрирани!");
		}
		return false;
	});
	
	// comments
	if (isDefined("newsId")) {
		commentInit();
		$("#showAddComment").click(function() { $("#comments").hide(); $("#addComment").slideDown("fast", redrawFrameEffects); return false; });
		$("#showComments").click(function() { $("#addComment").hide(); $("#comments").slideDown("fast", redrawFrameEffects); return false; });
	}
	
	// validation
	$("form.validate").validate();
	
	// login
	if (loginError) {
		alert("Невалидно потребителско име или парола!");
	}
	
	// selectbox
	$(".selectbox").selectbox();
	
	// category filter
	$("#categorySelect").change(function() {
		var val = $(this).find(":selected").val();
		window.location = urlPart + '/category:' + val;
	});
	
	 $(".frame-orange, .frame-blue").dropShadow({left: -3, top: 5, blur: 2, opacity: 0.9});
});
function redrawFrameEffects() {
	curvyCorners.redraw();
	$(".frame-orange, .frame-blue").redrawShadow();
}
function autoRotate() {
	$(".rotator .selector").each(function(){
		total = $(this).find("a:not(.first, .last)").size();
		current = $(this).find("a:not(.first, .last)").index($(this).find("a.active"));
		current = (current >= total - 1 ? 0 : current + 1);
		$(this).find("a:not(.first, .last)").eq(current).trigger("click");
	});
}
function commentInit() {
	commentLoad(newsId);
	$("#addComment a").one("click", commentAdd);
}
function commentLoad(id) {
	$("#comments ul").remove();
	$("#comments .loader").show();
	$.post(_appRoot+'/ajaxR2.php', {method:'getComments',id:id} , function(data){ 
		$("#comments ul").remove();
		$("#comments .loader").hide();
		if (data.items.length > 0) {
			$("#comments").append($("<ul>"));
			$.each(data.items, function(i,item){
				$("#comments ul").append($("<li>").addClass("curvyRedraw round").html(item));
			});
			$("#comments ul").show();
			$("#showComments span").text(data.items.length);
			curvyCorners.redraw();
			curvyCorners(curvyCornersSettings, ".curvyRedraw");
		}
		$(".frame-orange, .frame-blue").redrawShadow();
		if (data.items.length > 0 || _logged) {
			$("#commentHeading").show();
		} else {
			$("#commentHeading").hide();
		}
	}, "json");
}
function commentAdd() {
	var text = $.trim($("#addComment textarea").val());
	if (text.length > 5) {
		$("#addComment textarea").attr("disabled", "disabled");
		$.post(_appRoot+'/ajaxR2.php', {method:'addComment',id:newsId,text:text} , function(data){ 
			commentLoad(newsId);
			$("#addComment").hide();
			$("#showComments").trigger('click');
		});
	} else {
		alert("Невалиден коментар!");
	}
}
function ddmenu_open(){ ddmenu_canceltimer(); $(this).find("> ul").show();}
function ddmenu_close(obj) { obj.find("> ul").hide(); }
function ddmenu_closetimer(){ obj=$(this);closetimer = window.setTimeout(function(){ddmenu_close(obj);}, timeout);}
function ddmenu_canceltimer(){ if(closetimer){ window.clearTimeout(closetimer); } }

function isDefined(variable) {
	return (typeof(window[variable]) == 'undefined') ? false : true;
}
jQuery.preloadImages = function() {
  for(var i = 0; i<arguments.length; i++) {
    jQuery("<img>").attr("src", arguments[i]);
  }
}

jQuery.validator.addMethod("usernameavailable", function(value, element) {
	$.get(_appRoot+"/ajax.php", { section: 'userCheck', action: 'username', value: value},
	 function(data){
		validatorValues['username'] = (data === 'false');
	});
	return validatorValues['username'];
}, "Потребителското име е заето");
jQuery.validator.addMethod("emailavailable", function(value, element) {
	$.get(_appRoot+"/ajax.php", { section: 'userCheck', action: 'email', value: value},
	 function(data){
		validatorValues['email'] = (data === 'false');
	});
	return validatorValues['email'];
}, "Имейлът е зает");
jQuery.validator.addMethod("subscriberavailable", function(value, element) {
	$.get(_appRoot+"/ajax.php", { section: 'subscriberCheck', action: 'email', value: value},
	 function(data){
		validatorValues['email'] = (data === 'false');
	});
	return validatorValues['email'];
}, "Имейлът е зает");
jQuery.validator.addMethod("validatecity", function(value, element) {
	return value != 0;
}, "Изберете град");


