jQuery.fn.doTabs = function(navClass) {
	return this.each(function(){
		var box = this;
    	var tabs = $(this).find("div.tab");
    	if(tabs.length > 0 && !$(this).hasClass("noTabs")) {
	    	var nav = $(this).find("ul."+navClass).eq(0);
	    	if(nav.attr('class').indexOf('noAjax') < 0) {
		    	var active = $(nav).find("li").index($(nav).find("li.active"));
		    	if(active < 0) active = 0;
		    	var max = 0;
		    	var tabMax = null;
		    	$(this).find(".content").eq(0).height('auto');
		    	$.each(tabs,function() {
		    		var h = $(this).height();
		    		if(h > max) {
						max = h;
						tabMax = this;
					}
				});
				if(tabMax == null) tabMax = tabs[0];

				$(tabs).hide();
				$(tabMax).show();

				max = $(this).find(".content").eq(0).height();

				$(this).find(".content").css('height',max+'px');
				$(nav).find("li").eq(0).addClass("first");
		    	$(nav).find("li").eq(active).addClass("active");
		    	
		    	$(nav).find("li:not(.noClick)").eq(active+1).addClass("afterActive");
		    	$(tabs).not($(tabs)[active]).hide();
		    	$(tabs).eq(active).show();
		    	
		    	if ($(tabs).eq(active).children(".noResults:visible").length) {
						$(nav).find("#delAlldownloads").hide();
					} else {
						$(nav).find("#delAlldownloads").show();
					}
		    	
		    	$(box).find("a.more").attr("href",$(nav).find("li.active a").eq(0).attr("href"));
		    	$(nav).find("li:not(.noClick):not(.notTab) a").click(function() {
		    	
						if ($(tabs).eq($(nav).find("li:not(.noClick) a").index(this)).children(".noResults:visible").length) {
							$(nav).find("#delAlldownloads").hide();
						} else {
							$(nav).find("#delAlldownloads").show();
						}
		    	
			    	$(nav).find("li").eq(active).removeClass("active");
			    	$(nav).find("li").eq(active+1).removeClass("afterActive");
			    	$(tabs).eq(active).hide();
			    	active = $(nav).find("li").index($(this).parent());
			    	$(tabs).eq(active).show();
			    	$(nav).find("li").eq(active).addClass("active");
			    	$(nav).find("li:not(.noClick)").eq(active+1).addClass("afterActive");
			    	$(nav).find("li").eq(0).addClass("first");
			    	$(box).find("a.more").attr("href",$(this).attr("href"));
			    	return false;
				});
			}
		}
  });
}

jQuery.fn.boxSlide = function() {

	jQuery.fn.slideWork = function() {
		return this.each(function() {
			$(this).click(function() {
				var link = this;
				if($(this).attr("class").indexOf("slideWork") >= 0) {
					return false;
				} else if($(this).attr("class").indexOf("slideDown") >= 0) {
					$(this).addClass("slideWork");
					$(this).parents(".box").eq(0).find(".bottom").show();
					$(this).parents(".box").eq(0).find(".content").slideDown(500,function() {
						$(link).attr("class","slideUp");
						$(link).text("zwiń");
					});
				} else if($(this).attr("class").indexOf("slideUp") >= 0) {
					$(this).addClass("slideWork");
					$(this).parents(".box").eq(0).find(".content").slideUp(500,function() {
						$(this).parents(".box").eq(0).find(".bottom").hide();
						$(link).attr("class","slideDown");
						$(link).text("rozwiń");
					});
				}
				return false;
			});
		});
	}

	return this.each(function() {

		if($(this).find(".slideDown").length > 0) {
			$(this).children().not(".top").hide();
		}

		$(this).find(".slideDown").slideWork();
		$(this).find(".slideUp").slideWork();

	});

}

jQuery.fn.helpSlide = function() {

	return this.each(function() {

		$(this).find("li dt").hide();
		$(this).find("li").addClass("slideDown");
		$(this).find("li dd").click(function() {
			if($(this).parents("li").eq(0).attr("class").indexOf("slideWork") >= 0) {
				return false;
			} else if($(this).parents("li").eq(0).attr("class").indexOf("slideDown") >= 0) {
				$(this).parents("li").eq(0).addClass("slideWork");
				$(this).parents("li").eq(0).find("dt").eq(0).slideDown(300,function() {
					$(this).parents("li").attr("class","slideUp");
				});
			} else if($(this).parents("li").eq(0).attr("class").indexOf("slideUp") >= 0) {
				$(this).parents("li").eq(0).addClass("slideWork");
				$(this).parents("li").eq(0).find("dt").eq(0).slideUp(300,function() {
					$(this).parents("li").attr("class","slideDown");
				});
			}
		});

		$(this).find("li.slideUp dd").click(function() {
			if($(this).parents("li").eq(0).attr("class").indexOf("slideWork") >= 0) return false;

		});
		$(this).find("li.slideDown dd").click(function() {
			if($(this).parents("li").eq(0).attr("class").indexOf("slideWork") >= 0) return false;
			$(this).parents("li").eq(0).attr("class","slideWork");
			$(this).parents("li").eq(0).find("dt").eq(0).slideDown(300,function() {
				$(this).parents("li").attr("class","slideUp");
			});
		});
	});
}

jQuery.fn.selectOne = function(cont,trigger,counter) {
	return this.each(function(){
		$(this).click(function(){
			var cnt = parseInt($(cont).find(counter).eq(0).text());
			if($(this).attr("checked")) {
				cnt += 1;
			} else {
				cnt -= 1;
			}
			$(cont).find(counter).text(cnt);
			if(cnt == $(cont).find(trigger).length) {
				$(cont).find("a.select").text("odznacz wszystkie");
			} else if(cnt == 0) {
				$(cont).find("a.select").text("zaznacz wszystkie");
			}
		});
	});
}

jQuery.fn.selectAll = function(trigger,counter) {
	return this.each(function(){
		var cont = this;
		$(cont).find(trigger).selectOne(cont,trigger,counter);
		$(cont).find("a.select").click(function() {
			if($(cont).find(trigger).length < 1) return false;
			if($(this).text().indexOf("zaznacz") >= 0) {
				$(cont).find(trigger).each(function() {
					if(!$(this).attr("checked")) {
				    	$(this).attr("checked","checked");
					}
				});
				$(cont).find(counter).text($(cont).find(trigger).length);
				$(cont).find("a.select").text("odznacz wszystkie");
			} else {
				$(cont).find(trigger).each(function() {
					if($(this).attr("checked")) {
				    	$(this).attr("checked","");
					}
				});
				$(cont).find(counter).text('0');
				$(cont).find("a.select").text("zaznacz wszystkie");
			}
			return false;
		});
	});
}
function slideShow(imgC) {
	var imgCn = imgC+1;
	var srcLoc = $("#thumbPreview img").attr("src");
	if($("#thumbPreview img").attr("src") == undefined) return false;
	srcLoc = srcLoc.substr(0,srcLoc.lastIndexOf("/")+1);
	$("#thumbPreview img").attr("src",srcLoc+imgC+'.jpg');
	if(imgC == 6) {
	    imgCn = 1;
	}
	setTimeout("slideShow("+imgCn+")",500);
}

jQuery.fn.showThumbs = function(type) {
	return this.each(function(){
		var clicked = false;
		$(this).hoverIntent(function() {
			if(clicked) return false;
			var link = this;
			var rel = $(this).attr("rel");

			if(rel.length <= 1) return false;
			if(type == 'slideShow') {
			    rel = rel + '1.jpg';
			}

			$("body #previewTemp").remove();
			$("body #thumbPreview").remove();
			$("body").append('<div id="previewTemp" style="height:0;overflow:hidden"><img src="'+rel+'" alt="thb"/></div>');
			$("#previewTemp img").load(function() {
				var iw = $(this).width();
				var tpiw = iw + 26;
				var ih = $(this).height();
				var aw = $(link).width();
				var ah = $(link).height();
				var dw = ((iw - aw) / 2) + 13;
				var dh = ((ih - ah) / 2) + 13;
				var off = $(link).offset();
				var x = off['left'];
				var y = off['top'];
				if(type != 'slideShow') {
				    x = x-dw;
				    y = y-dh;
					$("body").append('<div id="thumbPreview"><div class="top"><div></div></div>'
					+ '<div class="center"><div class="previewImg"><img src="'+rel+'" alt="" /></div></div>'
					+ '<div class="bottom"><div></div></div></div>');
					// $("body").append('<div id="thumbPreview" style="border:
					// solid 1px red;"><div class="top"><div></div></div><div
					// class="center"><div class="previewImg" style="border:
					// solid 1px blue;"><img src="'+rel+'" alt=""
					// /></div></div></div>');
				} else {
				    $("body").append('<div id="thumbPreview"><div class="previewImg"><img src="'+rel+'" alt="" /></div></div>');
				}
				$("#thumbPreview").hide();
    			$("#thumbPreview div.previewImg").css('width',iw+'px');
				$("#thumbPreview div.previewImg").css('height',ih+'px');
				$("#thumbPreview").css('width',tpiw+'px');
				$("#thumbPreview").css("left",x+"px");
				$("#thumbPreview").css("top",y+"px");

				$("#thumbPreview").show();
				$("#previewTemp").remove();
				if(type == 'slideShow') {
				    setTimeout("slideShow("+2+")",500);
				}
				$("#thumbPreview").click(function() {
					// $("#thumbPreview").remove();
					// console.log("asd");
					window.location=$(link).attr("href");
					clicked = true;
				});

				$("#thumbPreview").hover(function() {}, function() {
					$("#thumbPreview").remove();
					clicked = false;
				});
			});
			return false;
		},function() { clicked = false; });
	});
}

jQuery.fn.checkBDate = function(type) {
	return this.each(function(){
		$(this).change(function() {
		    if($("#dayBirth").val() != '' && $("#monthBirth").val() != '' && $("#yearBirth").val()) {
			    var locDate = new Date();
			    locDate.setDate(parseInt($("#dayBirth").val())+1);
			    locDate.setMonth(parseInt($("#monthBirth").val())-1);
			    locDate.setYear($("#yearBirth").val());
			    var newDate = locDate;
			    newDate.setYear(locDate.getFullYear()+18);
			    var today = new Date();
			    if(newDate > today) {
			        $("#parentalFilterOn").show()
			    } else {
			        $("#parentalFilterOn").hide()
			    }
			}
		});
	});
}

jQuery.fn.changeTheme = function() {
	var ajaxWorking = false;
	return this.each(function(){
	    $(this).click(function() {
	        var link = $(this).attr("href");
	        link = link.substring(0,link.indexOf("#"));
	        if($(".patternBox").length == 0 && !ajaxWorking) {
	            ajaxWorking = true;
	            $.ajax({
				    type:'get',
				    url:link,
				    dataType:'json',
				    success: function(resp) {
				        ajaxWorking = false;
				        var locSrc = "";
	     				$("#content .wrapper").prepend(resp.value);
	                    $("#content .wrapper .patternBox").slideDown('300');
                     	$("#content .wrapper .patternBox .patterns span a").hover(function() {
							locSrc = $("#content").css("background-image");
                            $("#content").css("background-image","url('"+$(this).attr("href")+"')");
						},function() {
						    $("#content").css("background-image",locSrc);
						});
						$("#content .wrapper .patternBox .patterns span a").click(function() {
						    var link = $(this);
                            $("#content .wrapper .patternBox .patterns span.active").each(function() {
                                var LocTmpSrc = $(this).find("img").attr("src");
                                $(this).find("img").attr("src",$(this).find("a").attr("rel"));
                                $(this).find("a").attr("rel",LocTmpSrc);
                                $(this).removeClass("active");
                            });
						    $(link).parent().addClass("active");
						    var locImgSrc = $(link).find("img").attr("src");
						    $(link).find("img").attr("src",$(link).attr("rel"));
						    $(link).attr("rel",locImgSrc);
						    return false;
						});
						$("#content .wrapper .patternBox .saveBtn a").click(function() {
						    if(ajaxWorking) return false;
						    ajaxWorking = true;
					        $.ajax({
							    type:'post',
							    url:$(this).attr("href"),
							    dataType:'json',
							    data:'id_skin=' + $("#content .wrapper .patternBox .patterns span.active a").attr("id"),
							    success: function(resp) {
				                    ajaxWorking = false;
				                    $("#content").css("background-image","url('"+$("#content .wrapper .patternBox .patterns span.active a").attr("href")+"')");
				                    $("#content .wrapper .patternBox").slideUp(300,function() {
				                        $("#content .wrapper .patternBox").remove();
									});

							    }
							});
						    return false;
						});
				    }
				});
			}
	        return false;
	    });
	});
};


jQuery.fn.cssCheckbox = function () {
	jQuery("#overlayForm input[@type='checkbox'] + label", this).each(function(){
			if (jQuery(this).prev().is(":checked"))
				jQuery(this).addClass("checked").prevAll(":checkbox").val("on");
			else
				jQuery(this).addClass("unchecked").prevAll(":checkbox").val("off");
	}).click(function(){
			jQuery(this).toggleClass("checked").prev().checked = !jQuery(this).prev()[0].checked;
			jQuery(this).toggleClass("unchecked").prev().checked = jQuery(this).prev()[0].checked;
			(jQuery(this).hasClass("checked")) ? jQuery(this).prevAll(":checkbox").val("on") : jQuery(this).prevAll(":checkbox").val("off");
	}).prev().css({
			position: "absolute",
			display: "none"
	});
};


	
jQuery.fn.setBG = function () {
	var i=0;
    return this.each(function(){
        var that = $(this);
        $(this).find(".tabnav a").click(function() {
			if($(this).attr("rel") != '') {
			    // console.log($(that).find(".content"));
			    $(that).find(".content").css("background","url('"+$(this).attr("rel")+"') 0 0 repeat");
			} else {
			    $(that).find(".content").css("background","url('/css/img/box_bkg.gif') 100% 100% repeat-x");
			}
			if($(this).attr("ga_label")!="") pageTracker._trackEvent('Zakladka', 'Klik', $(this).attr("ga_label"));
        });
        // zakomentowane by t.scislo@telecommedia.pl
        // $(this).find(".tabnav li.active a").trigger("click");
    });
};

jQuery.fn.getLogin = function() {
	return this.each(function() {
		var that = $(this);
		$.ajax({
			url: '/loginBox.php' + that.attr('rel'),
			type: 'post',
			dataType: 'html',
			success: function(html) {
				that.html(html);
			}
		});
	});
};

jQuery.fn.downloadBtn = function() {
	this.click(function() {
		var cl = $(this).attr("class");
		var that = $(this);
		if($(this).attr("href") != "#") {
			$.ajax({
			    url: $(this).attr("href"),
			    type: 'get',
			    dataType: 'json',
			    success: function(re) {
	          		if(re.result == "ok") {
	          		    $("div.product div."+cl).html('<p><strong>'+re.value+'<strong></p>');
				        $("div.product div."+cl).slideDown(300);
						$(that).addClass("active").unbind("click").click(function() {
						    return false;
						});
					} else {
					    // wysweitl komunikat, ze jzu masz go w koszyku
					}
			    }
	  		});
			} else {
			if((cl.length < 1) || (cl.indexOf("active") >= 0)) {
				$(this).removeClass("active");
				cl = $(this).attr("class");
				$("div.product div."+cl).slideUp(300);
			} else {
				$("div.product div."+cl).slideDown(300);
				$(this).addClass("active");
			}
		}
		return false;
	});
}

function changeFav() {
	var favWorking = false;
	$("a.buttonFav").click(function() {
	    if(favWorking) return false;
		var href = $(this).attr("href");
		var that = $(this);
		$(this).ajaxSubmit({
		    dataType:'json',
		    type:'post',
		    url:href,
		    beforeSubmit:function(){
		        favWorking = true;
		    },
			success:function(re){
			    favWorking = false;
			    $(that).removeClass(re[1]+'Fav');
			    $(that).addClass(re[0]+'Fav');
			}
		});
    	return false;
	});
}

jQuery.fn.getProductHtml = function() {
	return this.each(function() {
		var that = $(this);
		$.ajax({
			url: '/np/productProxy',
			type: 'post',
			data: 'id_content=' + $('div.productZone').attr('rel') + '&referer=' + $('div.productZone').attr('ref'),
			dataType: 'json',
			success: function(json) {
				$('#proxyFav').replaceWith(json.fav);
				changeFav();
				
				$('#proxyDownload').replaceWith(json.download);
				$("div.product div.btn:not(.rcmd) a").downloadBtn();
				$("div.description div.btn a.overlayDownload").overlayLink();
				
				/*
				 * $('#proxyComments').replaceWith(json.comments);
				 * $("ul.comments p.remove a").removeLink();
				 * $("p.abuse").abuseLink(); $('#commentForm').doForm();
				 */
				
				$('#proxyAbuse').replaceWith(json.abuse);
				$('#proxyOverlay').replaceWith(json.overlay);				
				$("#overlayForm form").doForm();

			}
		});
	});
};

$(function() {
	
	$("#homeLoginBox").getLogin();
	$("div.box").doTabs("tabnav");
	ContentPager();
	ProfilePager();
	
	$('#gfx').find("li a").click(function() {
	
		var id =$('#gfx').find("li.active a").eq(0).attr("id");
			$('#err_gfx').hide();
			$('#contenttabgfx').hide();
			$('.indicatorgfx').show();
    		$.ajax({
		            type: "POST",
		            url: "/gfxbox/"+id,
		            async: false,
		            success: function (msg) {
    			      
		    	 		$('#contenttabgfx').html(msg);
		    	 		$('#contenttabgfx').show();
		    	 		$('.indicatorgfx').hide();
		    	 		
		            },
	    			error:  function (msg) {
		    	 		$('.indicatorgfx').hide();
		    	 		$('#err_gfx').show();
		            }
		});
	})

	$('#rec').find("li a").click(function() {
		
		var id =$('#rec').find("li.active a").eq(0).attr("id");
		$('#err_rec').hide();
		$('#contenttab').hide();
		$('.indicator').show();
    	$.ajax({
	            type: "POST",
	            url: "/recommendedtabs/"+id,
	            async: false,
	            success: function (msg) {
	    	 		$('#contenttab').html(msg);
	    	 		$('.indicator').hide();
	    	 		$('#contenttab').show();
	            },
    			error:  function (msg) {
	    	 		$('.indicator').hide();
	    	 		$('#err_rec').show();
	            }
    	});	
	})
	
	$("div.cloud").doTabs("linksnav");
	$('#top10').find("li a").click(function() {
		
		var id =$('#top10').find("li.active a").eq(0).attr("id");
		$('#elita').hide();
		$('.indicatortop10').show();
    	$.ajax({
	            type: "POST",
	            url: "/top10/"+id,
	            async: false,
	            success: function (msg) {
    				$('#err_top10').hide();
	    	 		$('#elita').html(msg);
	    	 		$('.indicatortop10').hide();
	    	 		$('#elita').show();
	            },
    			error:  function (msg) {
	    	 		$('.indicatortop10').hide();
	    	 		$('#err_top10').show();
	            }
    	});	
	})

	var confirm_count=0;
	
	$('#potwierdz_mail').click(function() {
		$('#confirm_error_info').hide();
		$('#confirm_info').hide();
		$('#confirm_indicator').show();
		confirm_count++;
		$.ajax({
	        type: "POST",
	        url: "/admin/confirm_mail",
	        dataType:'json',
	        async: false,
	        success: function (re) {
				$('#confirm_indicator').hide();
				$('#confirm_info').html(re.msg);
				$('#confirm_info').show();
	        },
			error:  function (re) {
	        	$('#confirm_indicator').hide();
				$('#confirm_info').html('Wystąpił błąd. Spróbuj ponownie później.');
				$('#confirm_info').show();
            }
		})
		
	});	
	
	$('#peopletabs').find("li a").click(function() {
		var id =$('#peopletabs').find("li.active a").eq(0).attr("id");
		$('#userstabs').hide();
		$('.indicatorpeople').show();
		$.ajax({
	        type: "POST",
	        url: "/peoplecloud/"+id,
	        async: false,
	        success: function (msg) {
				$('#err_people').hide();
		 		$('#userstabs').html(msg);
		 		$('.indicatorpeople').hide();
		 		$('#userstabs').show();
		 	
	        },
			error:  function (msg) {
    	 		$('.indicatorpeople').hide();
    	 		$('#err_people').show();
            }
		})

	});	
	
	
	$("div.profileBox").doTabs("linksnav");
	$("div.box").boxSlide();
	$("ul.help").helpSlide();

	$("#dayBirth,#monthBirth,#yearBirth").checkBDate();

	$("ul.wallpapers a.cont").showThumbs('single');
	$("ul.themes a.cont").showThumbs('single');
	$("ul.animations a.cont").showThumbs('single');
	$("ul.videos a.cont").showThumbs('slideShow');

	$("ul.comments p.remove a").removeLink();
	$("p.abuse").abuseLink();

	// $("#phoneBox").show();
	$("div.phoneType a.changeBtn").click(function() {
		if($("#phoneBox").css("display") != "none") return false;
		$("#phoneBox").slideDown(500);
		var locPos = $("#phoneBox").position();
	    locPos = locPos['top'] + 225;
	    if($("#content > .wrapper").height() < locPos) {
		    $("#content > .wrapper").height(locPos+'px');
		}
		/*
		 * if ($("#content > .wrapper .leftCol").height() < locPos) {
		 * console.log(locPos); $("#content > .wrapper
		 * .leftCol").height(locPos+'px'); }
		 */
		return false;
	});

	$("div.productZone div.leftCol").getProductHtml();

	$("#content div.options a.changeBtn").click(function() {
		var form = $(this).parents(".options").eq(0).find("div#changeFilterForm").eq(0);
		if($(form).css("display") != "none") {
		    $("#changeFilterIframe").hide().remove();
			$(form).slideUp(200);
		} else {
		    $(this).parent().prepend('<iframe id="changeFilterIframe" FRAMEBORDER="0"></iframe>');
			$("#changeFilterIframe").show();
			$(form).slideDown(200);
		}
		return false;
	});

	var surH = $("div.survey .inside").css("height");
	$("#addQuery").click(function() {
		if($(this).attr("checked")) {
			$("div.survey .inside").css("height","auto");
			$(this).parents(".survey").eq(0).find(".target").show();
		} else {
			$("div.survey .inside").css("height",surH);
			$(this).parents(".survey").eq(0).find(".target").hide();
		}
	});

	if($("#addQuery:checked").lenght > 0) {
        $("#addQuery").trigger('click');
        $("#addQuery").attr("checked","checked");
	}


	$("div.survey a.addOne").click(function() {
	    $(".forum #content .messageForm .survey .inside").css("height","auto");
		$("div.survey .answers").append($("div.survey .answers").find('dt').eq(0).clone());
		$("div.survey .answers dt:last").find("p em").text(""+$("div.survey .answers dt").length);
		$("div.survey .answers dt:last").find("p a.sqDell").attr("rel",$("div.survey .answers dt").length);
		if($("div.survey .answers dt").length > 2) {
		    $("div.survey .answers dt:last").find("p a.sqDell").show();
		    $("div.survey .answers dt:last a.sqDell").click(function() {
	    		$(this).parents("dt").remove();
	    		$("div.survey .answers dt").each(function() {
					var locPos = $("div.survey .answers dt").index($(this)) + 1;
					$(this).find("p em").text(locPos);
					$(this).find("p a.sqDell").attr("rel",locPos);
				});
	    		return false;
			});
		}
	});

	$(".recomendedMain").setBG();

	$("#sortOptions").change(function() {
		location.href = $('#sortForm').attr('action').replace(/-JS-/, $(this).val());
	});

	$(".changeTheme").changeTheme();

	if(window.location.hash.indexOf("zmien-wyglad") > 0) {
	    $(".changeTheme").click();
	}
	if(window.location.hash.indexOf("pomoc") > 0) {
	    var locH = window.location.hash;
	    locH = locH.substring(1);
	    var locO = $(".help").find("a[name='"+locH+"']");
	    $(locO).parents("li").find("dd").trigger("click");

	}

	$(".admin #content .stats > li:eq(1)").css("border-top","none");
	$(".admin #content .stats > li:last").css("border-bottom","none");

	$(".admin #content .download .pager a, .admin #content .delContent, .admin #content #delAlldownloads a").live("click",function() {
	    var that = $(this);
	    var orgUrl = $(this).attr("href");
	    var locDataType = 'html';
	    if($(this).parent().attr("id") == "delAlldownloads") {
	        var locName = $(this).parent().siblings("li.active").find("a").attr("rel");
			$(this).attr("href",$(this).attr("href") + locName);
			locDataType = 'json';
	    }
		if($(this).hasClass("alertAll")) {
		    var alert = confirm('Czy chcesz usunąć wszystkie pobrane pliki ze wszystkich kategorii ?');
		} else if($(this).hasClass("delContent")) {
		    var alert = confirm('Czy napewno chesz usunąć ?');
		} else {
		    var alert = true;
		}
		if(!alert) {
		    $(this).attr("href",orgUrl);
			return false;
		}
		$('.indicator').show();
		$('.items').hide();
		$('#delAlldownloads').show();
		$.ajax({
		    url: $(this).attr("href"),
		    type: 'get',
		    dataType: locDataType,
		    success: function(re) {
				var act = $(".admin #content .download .tab");
				if(locDataType == 'html') {
				    $(act).after(re);
				    $(act).remove();;
				    $.scrollTo($(".admin #content .download"));
				    $("div.box").doTabs("tabnav");
				} else {
				    if(re.result == "ok") {
				        $(act).find("ul,p").remove();
				        $(act).find(".footer .pager").remove();
						$(act).prepend('<p class="noResults">Brak plików w tej kategorii</p>');
						$('.indicator').hide();
						$('#err_admin').hide();
						$('#delAlldownloads').hide();
				    }
				}
		    },
		    error: function() {
    	 		$('.indicator').hide();
    	 		$('#err_admin').show();
		    }
		});
		$(this).attr("href",orgUrl);
		return false;
	});


	if ($("#overlayForm").length > 0) $().cssCheckbox();

	$("div.description div.btn a.overlayRecommend").click(function() {
		var href= $("div.description div.btn a.overlayRecommend").attr("href");
		$.ajax({
			url: href,
			type: 'get',
			dataType: 'json',
			success: function(re) {
				if (re.result == "ok") {
					// pokaz overlay
					$.blockUI({message: re.value, css: {border: '0', left: '50%', top: '50%'}});
					$("#recommendForm").doForm();
					$("#recommendSendForm").doForm();
					$("#overlayRecommendLoginForm a.close").overlayRecommendLoginFormCloseLink();
					$("#overlayRecommendForm a.close").overlayRecommendLoginFormCloseLink();
					return false;
				}
			}
		});
		return false;
	});

	$("#importMailForm div.btn_odzaz a").click(function() {
		var status = $(this).hasClass("all-selected");
		$("#importMailForm input:checkbox").each(function() {
			this.checked = !status;
		});
		if (status) {
			$(this).removeClass("all-selected");
		} else {
			$(this).addClass("all-selected");
		}
		return false;
	});

	$("#peopleAdditionalLinks").click(function() {
		$(".initiallyHidden").show();
		return false;
	});

	$(".peopleHideAdditionalLinks").click(function() {
		$(".initiallyHidden").show();
		return false;
	});

	$("div.pointstab").click(function() {
		$("div.pointstab").removeClass('active');
		$(this).addClass('active');
		$("div.points").hide();

		if ($(this).hasClass('ptsW')) {
			$("div.pointsW").show();
		} else if ($(this).hasClass('ptsM')) {
			$("div.pointsM").show();
		} else if ($(this).hasClass('ptsY')) {
			$("div.pointsY").show();
		} else {
			$("div.pointsO").show();
		}

		return false;
	});

	$("div.pink_baner").click(function() {
		$.blockUI({message: $("#overlayInvite"), css: {border: '0', left: '50%', top: '50%'}});
		$("#overlayInvite a.close").click(function() {$.unblockUI();});
	});

	$("p.inviteOverlayTrigger").click(function() {
		$.blockUI({message: $("#overlayInvite"), css: {border: '0', left: '50%', top: '50%'}});
		$("#overlayInvite a.close").click(function() {$.unblockUI();});
		return false;
	});

});

function showRecommendForm(f, params) {
	var href= $("div.description div.btn a.overlayRecommend").attr("href");
	$.ajax({
		url: href,
		type: 'get',
		dataType: 'json',
		success: function(re) {
			if (re.result == "ok") {
				// pokaz overlay
				$.blockUI({message: re.value, css: {border: '0', left: '50%', top: '50%'}});
				$("#recommendForm").doForm();
				$("#recommendSendForm").doForm();
				$("#overlayRecommendLoginForm a.close").overlayRecommendLoginFormCloseLink();
				$("#overlayRecommendForm a.close").overlayRecommendLoginFormCloseLink();
				return false;
			}
		}
	});
}

function showRecommendSendForm(f, params) {
	$.blockUI({message: params, css: {border: '0', left: '50%', top: '50%'}});
	$("#recommendForm").doForm();
	$("#recommendSendForm").doForm();
	$("#overlayRecommendLoginForm a.close").overlayRecommendLoginFormCloseLink();
	$("#overlayRecommendForm a.close").overlayRecommendLoginFormCloseLink();
}

function sendRecommendSuccess(f, params) {
	$.blockUI({message: params, css: {border: '0', left: '50%', top: '50%'}});
}

jQuery.fn.overlayRecommendLoginFormCloseLink = function() {
	$("#overlayRecommendLoginForm a.close").click(function() {$.unblockUI();});
	$("#overlayRecommendForm a.close").click(function() {$.unblockUI();});

	$("#recommendSendForm #send_sms").click(function() {
		$("#recommendSendForm #mail_message_box").slideUp(500);
		$("#recipient_1, #recipient_2, #recipient_3, #recipient_4, #recipient_5").each(function() {
			if ($(this).val().substr(0, 3) != "+48") {
				if($(this).val().match(/^\d+$/i)) {
					$(this).val("+48" + $(this).val());
				} else {
					$(this).val("+48");
				}
			}
		});
		$(".did").hide();
	});

	$("#recommendSendForm #send_mail").click(function() {
		$("#recommendSendForm #mail_message_box").slideDown(500);
		$("#recipient_1, #recipient_2, #recipient_3, #recipient_4, #recipient_5").each(function() {
			if ($(this).val().substr(0, 3) == "+48") {
				$(this).val("");
			}
		});
	});

	$("#recipient_1, #recipient_2, #recipient_3, #recipient_4, #recipient_5").change(function() {
		$(".did_" + this.id).hide();
		if ($(this).val() != "") {
			var provider = $(this).val().toLowerCase().match(/@(.*)/);
			if (provider) {
				provider = provider[1];
				var expected = didYouMean(provider);
				if (expected != false) {
					$(".did_" + this.id).text("Czy chodzi ci o " + expected + "?").show();
				}
			}
		}
	});
};

jQuery.fn.recommendBtn = function() {
	this.click(function() {
		var cl = $(this).attr("class");
		var that = $(this);
		if($(this).attr("href") != "#") {
			$.ajax({
				url: $(this).attr("href"),
				type: 'get',
				dataType: 'json',
				success: function(re) {
					if(re.result == "ok") {
						$("div.product div."+cl).html('<p><strong>'+re.value+'<strong></p>');
						$("div.product div."+cl).slideDown(300);
					} else {
						// wysweitl komunikat, ze jzu masz go w koszyku
					}
				}
			});
		} else {
		}
		return false;
	});
}

function showInvitedSuccess(f, params) {
}

function didYouMean(mail) {
	var providers = new Array(
		// zbyt krótkie: "wp.pl", "o2.pl", "op.pl", "vp.pl", "go2.pl", "wp.eu",
		"interia.pl", "gmail.com", "tlen.pl", "buziaczek.pl", "onet.eu",
		"poczta.onet.pl", "amorki.pl", "interia.eu", "poczta.fm", "autograf.pl",
		"neostrada.pl", "gazeta.pl", "onet.pl", "poczta.onet.eu", "poczta.pl",
		"hotmail.com", "orange.pl", "yahoo.pl", "yahoo.com", "fotka.pl"
	);
	var bestGuess = null;
	var distance = -1;
	var localDistance;

	var len = providers.length;
	for(var i = 0; i < len; ++i) {
		localDistance = levenshtein(mail, providers[i]);
		if (localDistance == 0) {
			return false;
		}
		if (localDistance < distance || distance < 0) {
			bestGuess = providers[i];
			distance = localDistance;
		}
	}

	if (distance <= 2) {
		return bestGuess;
	}
	return false;
}

function levenshtein (s1, s2) {
      // http://kevin.vanzonneveld.net
      // + original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com)
      // + bugfixed by: Onno Marsman
      // + revised by: Andrea Giammarchi (http://webreflection.blogspot.com)
      // + reimplemented by: Brett Zamir (http://brett-zamir.me)
      // + reimplemented by: Alexander M Beedie
      // * example 1: levenshtein('Kevin van Zonneveld', 'Kevin van
		// Sommeveld');
      // * returns 1: 3

    if (s1 == s2) {
        return 0;
    }

    var s1_len = s1.length;
    var s2_len = s2.length;
    if (s1_len === 0) {
        return s2_len;
    }
    if (s2_len === 0) {
        return s1_len;
    }

    // BEGIN STATIC
    var split = false;
    try{
        split=!('0')[0];
    } catch (e){
        split=true; // Earlier IE may not support access by string index
    }
    // END STATIC
    if (split){
        s1 = s1.split('');
        s2 = s2.split('');
    }

    var v0 = new Array(s1_len+1);
    var v1 = new Array(s1_len+1);

    var s1_idx=0, s2_idx=0, cost=0;
    for (s1_idx=0; s1_idx<s1_len+1; s1_idx++) {
        v0[s1_idx] = s1_idx;
    }
    var char_s1='', char_s2='';
    for (s2_idx=1; s2_idx<=s2_len; s2_idx++) {
        v1[0] = s2_idx;
        char_s2 = s2[s2_idx - 1];

        for (s1_idx=0; s1_idx<s1_len;s1_idx++) {
            char_s1 = s1[s1_idx];
            cost = (char_s1 == char_s2) ? 0 : 1;
            var m_min = v0[s1_idx+1] + 1;
            var b = v1[s1_idx] + 1;
            var c = v0[s1_idx] + cost;
            if (b < m_min) {
                m_min = b;}
            if (c < m_min) {
                m_min = c;}
            v1[s1_idx+1] = m_min;
        }
        var v_tmp = v0;
        v0 = v1;
        v1 = v_tmp;
    }
    return v0[s1_len];
}

function ContentPager()
{
	$('#pager_content').find("a").click(function() {
		var id = $(this).attr("myid");
		var idcontent = $('#idcontent').attr("rel");
			$('#err_comment').hide();	
			$('.indicatorcomment').show();
			$.ajax({
		            type: "POST",
		            url: "/np/commentPager/"+id+"/"+idcontent,
		            dataType: 'json',
		            async: false,
		            success: function(json) {
						$('.indicatorcomment').hide();
		    	 		$('#commentsContent').html(json.comments);
		    	 		$('#commentsPager').html(json.pager);
		    	 		$('#err_comment').hide();	
		    	 		$("p.abuse").abuseLink(); $('#commentForm').doForm();
		            },
	    			error:  function (msg) { 
		            	$('.indicatorcomment').hide();
		    	 		$('#err_comment').show();
		            }
		});
		
	})
}

function ProfilePager()
{
	$('#pager_profile').find("a").click(function() {
		var id = $(this).attr("myid");
		var juser = $('#juser').attr("rel");
			$('#err_comment').hide();	
			$('.indicatorcomment').show();
			$.ajax({
		            type: "POST",
		            url: "/profilePager/"+id+"/"+juser,
		            dataType: 'json',
		            async: false,
		            success: function(json) {
						$('.indicatorcomment').hide();
		    	 		$('#commentsContent').html(json.comments);
		    	 		$('#commentsPager').html(json.pager);
		    	 		$('#err_comment').hide();	
		    	 		$("p.abuse").abuseLink(); $('#commentForm').doForm();
		            },
	    			error:  function (msg) { 
		            	$('.indicatorcomment').hide();
		    	 		$('#err_comment').show();
		            }
		});
		
	})
}
