function searchForm() {
	$("#topSearch input[name=q]").focus(function() {
		if ($(this).val() == 'Szukaj...') {
			$(this).val('');
		}
	});
	$("#topSearch input[name=q]").blur(function() {
		if ($(this).val() == '') {
			$(this).val('Szukaj...');
		}
	});

	$('#topSearch').submit(function() {
		var q = $("#topSearch input[name=q]").val();
		var filter = $("#topSearch select[name=filter]").val();

		if (filter != '' && q != '' && q != 'Szukaj...') {
			var url = $('#topSearch').attr('action');
			url += '/' + filter + '/' + q;

			location.href = url;
		}
		return false;
	});
}

var stopClick = false;
function phoneFormSelect() {
    $("select#phoneModel").attr("disabled","disabled");
    var phoneWorking = false;
	var phones = {};
	$("select#phoneBrand").change(function() {
	    var that = $(this);
	    if($(that).val() != 0) {
	        $("select#phoneModel").ajaxSubmit({
				dataType:'json',
				type:'post',
				url:'/telefony/'+$(that).val(),
				beforeSubmit:function(d,f,o){
				    $("select#phoneModel").html('<option value="0">Wybierz</option>');
				    $("select#phoneModel").attr("disabled","disabled");
					phoneWorking = true;
				},success:function(re,st){
					phoneWorking = false;
					phones = re;
					for(i in re) {
						$("select#phoneModel").append('<option value="'+i+'">'+re[i].name+'</option>');
					}
					$("select#phoneModel").attr("disabled","");
				},error:function(){
				    phoneWorking = false;
				}
			});
	    } else {
	        $("select#phoneModel").html('<option value="0">Wybierz</option>');
	        $("select#phoneModel").attr("disabled","disabled");
	    }
	});
}
function phoneModel(phones) {
    $("dl#phoneModel div.phoneList div").unbind("click").click(function() {
		$("dl#phoneModel .active").removeClass("active");
		$(this).addClass("active");
		$(this).parents("dl").eq(0).find("input.hdn").val($(this).attr("rel"));
		if(phones != null) {
			$("dl#phonePic img").attr("src",phones[$(this).attr("rel")].image);
			$("dl#phonePic").show();
		} else {
		    var that = $(this);
		    $.ajax({
		        url: '/admin/telefon/' + $(that).attr("rel"),
		        type: 'get',
		        dataType: 'txt',
		        success: function (re) {
		            $("#phonePic img").attr("src",re);
		        }
			});
		}
	});
}

function phoneForm() {
	if($("dl#phoneBrand .phoneList .active").length > 0) {
	    $("dl#phoneBrand .phoneList").scrollTo($("dl#phoneBrand .phoneList .active"));
	}
	if($("dl#phoneModel .phoneList .active").length == 0) {
		$("dl#phoneModel").hide();
	} else {
	    $("dl#phoneModel .phoneList").scrollTo($("dl#phoneModel .phoneList .active"));
	}
	var phoneWorking = false;
	var phones = {};
	$("dl#phoneModel .wiatrak").hide();
	$("dl#phoneBrand div.phoneList div").click(function() {
		if(phoneWorking) return false;
		$("dl#phoneBrand .active").removeClass("active");
		$("dl#phoneModel div.even").remove();
		$("dl#phoneModel div.odd").remove();
		$("dl#phonePic img").attr("src","/global/img/blank.gif");
		$("dl#phonePic").hide();
		$(this).addClass("active");
		var id = $(this).attr("rel");
		$(this).parents("dl").eq(0).find("input.hdn").val(id);
		$("input.hdn[name='phoneModel']").val('');
		if(id != 0) {
			$("dl#phoneModel").ajaxSubmit({
				dataType:'json',
				type:'post',
				url:'/telefony/'+id,
				beforeSubmit:function(d,f,o){
					$("dl#phoneModel").show();
					$("dl#phoneModel .wiatrak").show();
					phoneWorking = true;
				},success:function(re,st){
					phoneWorking = false;
					var c = 0;
					$("dl#phoneModel .wiatrak").hide();
					phones = re;
					for(i in re) {
						$("dl#phoneModel div.phoneList").append('<div class="'+((c++)%2 == 0 ? "even" : "odd")+'" rel="'+i+'">'+re[i].name+'</div>');
					}
					phoneModel(phones);

				},error:function(){
				    phoneWorking = false;
					$("dl#phoneModel").hide();
					$("dl#phoneModel div.even").remove();
					$("dl#phoneModel div.odd").remove();
					$("dl#phonePic img").attr("src","/global/img/blank.gif");
					$("dl#phonePic").hide();
				}
			});
		} else {
		    $("dl#phoneBrand input.hdn").val("0");
		    $("dl#phoneModel input.hdn").val("0");
		}
	});
}

function commentSuccess(form,params) {
	var cont = $(form).parents(".box,.cloud").find(".content");
	if(cont.length < 1) {
		cont = $(form).parents(".profileBox").find(".content");
	}
	var list = $(cont).eq(0).find("ul.comments");
	var cl = "odd";
	// console.log($(list).eq(0).find("li:last").length);
	if(list.length < 1) {
		$(cont).eq(0).find("dfn").remove();
		$(cont).eq(0).append('<ul class="comments"></ul>');
		list = $(cont).eq(0).find("ul.comments");
	} else if($(list).eq(0).find("li:last").length > 0) {
		cl = $(list).eq(0).find("li:last").attr("class").indexOf("even") >= 0 ? "odd" : "even";
	}

	if(!params.isOwner) {
		$(list).find("p.remove").remove();
	}
	$(list).append(params.html);
	var li = $(list).find("li:last");
	$(li).slideDown(300);
	$(li).attr("class",cl);
	$(li).find("p.remove a").removeLink();
	$(li).find("p.abuse a").abuseLink();
	var cnt = $(cont).eq(0).find("h4 .count strong").eq(0);
	if(cnt.length < 1) {
	    $(cont).eq(0).prepend('<h4><span class="count">Dodano: <strong>1</strong></span>Komentarze</h4>')
	} else {
		$(cnt).text(""+(parseInt($(cnt).text())+1));
	}
	$(form).find("textarea").val("");
}

function messageSuccess(form,params) {
	$(form).find("input").hide();
	$(form).find("textarea").slideUp(200,function() {
		$(form).find("p").text(params.response);
	});
	if(params.secondaryFunction != null) {
	    eval(params.secondaryFunction+'(form);');
	}
}

function passChangeSuccess(form) {
	$(form).parent().prepend('<p id="passSuccess" style="font-size: 12px; padding-top: 20px; font-weight: bold;display: none;">Hasło zostało zmienione</p>');
	$("#passSuccess").slideDown(300);
	$(form).find("input[type='password']").val('');
	setTimeout('$("#passSuccess").slideUp(300,function(){$(this).remove()});',2000);
}

function disableInvite(f) {
	$(".addFriend a").removeAttr("href");
}

function abuseSuccess(form,params) {
	var parent = $(form).parent();
	$(parent).append('<div class="abuseSuccess"><a class="close"></a>'+params+'</div>');
	$("#abuseForm .abuseSuccess a.close").abuseCloseLink();
	$(parent).find("form").slideUp('300');
}

function remindSuccess(form,params) {
	$(form).slideUp(300,function() {
		$(form).parent().append('<p>'+params+'</p>');
		$(form).remove();
	});
}

function redirect(form,params) {
	if(window.location.href == params.url) {
	    window.location.reload();
	} else {
		window.location.assign(params.url);
		var reload = (window.location.href === params.url) ? true : false;
		if (reload === true) {
			window.location.reload();
		}
	}
}

function activationRedirect(form,params) {
	var parent = $(form).parent();
	$(parent).append('<img src="http://al.system3.pl/l/?s3fp=' + params.s3fp + '&webid=' + params.webId + '&AdvertiserId=26&OrderId=' + params.id + '&TotalPrice=0" align="bottom" width="1" height = "1" border="0" hspace="1" />');
	params.response = 'Za chwilę zostaniesz przekierowany na stronę administracyjną.';
	redirectDelay(form,params);
}

function redirectDelay(form,params) {
	$(form).slideUp(300,function() {
		$(this).before('<p>'+params.response+'</p>');
		$(this).remove();
		setTimeout(function() {
			redirect(form,params);
		},1500);
	});
}

function surveyShowVotes(form,params) {
	$(form).parent().hide(1,function(){
	    $(form).parent().parent().prepend(params.value);
	});
}

jQuery.fn.surveyShowVotesBefore = function() {
	return this.each(function(){
	    $(this).click(function() {
	        if($("#pollResults:visible").length > 0) {
	            $("#pollResults").slideUp(500,function() {
				    $(".surveyShow").slideDown(500);
				});
	        } else {
				$(".surveyShow").slideUp(500,function() {
        			$("#pollResults .surveyShow").show();
				    $("#pollResults").slideDown(500);
				});
			}
	    });
	});
}

jQuery.fn.showPreviewBtn = function() {
	return this.each(function(){
	    $(this).click(function() {
	        if(!stopClick) {
		        var href = $(this).attr("alt");
				var orgAction = $(this).parents("form").attr("action");
				$(this).parents("form").attr("action",href);
				$(this).parents("form").submit();
				$(this).parents("form").attr("action",orgAction);
			} else {
			    stopClick = false;
			}
		});
	})
};

jQuery.fn.markAllAsRead = function() {
	return this.each(function(){
		$(this).click(function() {
            var link = this;
			$(this).ajaxSubmit({
				url: $(link).attr("href"),
				success: function() {
					$("#content ul.forumList li").removeClass("unread");
				}
			});
			return false;
		});
	});
};


jQuery.fn.removeTP = function(type) {
	return this.each(function(){
		$(this).click(function() {
		    var what = "";
			(type=='topic') ? what='temat' : what='odpowiedź';
		    var ok = window.confirm('Czy napewno chcesz usunąć '+what+' ?');
		    if(!ok) return false;
		    var link = $(this);
		    $.ajax({
		        url: $(link).attr("href"),
		        type: 'get',
		        dataType:'json',
		        success: function(resp) {
		            if(resp.result == "ok") {
		                if(resp.functionName != null) {
							eval(resp.functionName+'("",resp.params);');
						} else {
							alert(resp.value);
						}
		            }
		        }
			});
		    return false;
		});
	});
}

jQuery.fn.removeFiendAjax = function(type) {
	return this.each(function(){
		$(this).click(function() {
		    var link = $(this);
		    $.ajax({
		        url: $(link).attr("href"),
		        type: 'get',
		        dataType:'json',
		        success: function(resp) {
		            if(resp.functionName != null) {
						eval(resp.functionName+'("",resp.params);');
					} else {
						alert(resp.value);
					}
		        }
			});
			return false;
		});
	});
}


function showPreview(f,p) {
	if($("#postPreview").length == 0) {
        $(f).append("<dl id='postPreview' style='margin: 0; display: none; clear:both;'></dl>")
        $("#postPreview").append(p.value);
        $("#postPreview").slideDown(300);
	} else {
	    $("#postPreview").fadeOut(100,function() {
	        $("#postPreview").html('');
		    $("#postPreview").append(p.value);
			$("#postPreview").fadeIn(100);
		});
	}

}

function alertReload(form,params) {
	alert(params.message);
	window.location.reload();	
}

function refreshAvatar(form,params) {
	$(form).find("#avatarImage").attr("src",params.url);
	$(form).find("#avatarId").val('');
}

jQuery.fn.doForm = function() {
	this.ajaxForm({
		dataType:'json',
		beforeSubmit:function(d,f,o){
			if($(f).attr("class").indexOf("ajaxWorking") >= 0) return false;
			$(f).find(".verif").hide();
			$(f).find("wiatrak").show();
			$(f).addClass("ajaxWorking");
			o.success = function(re,st) {
				$(f).find("wiatrak").hide();
				$(f).removeClass("ajaxWorking");
				if(re.result == "ok") {
					if(re.functionName != null) {
						eval(re.functionName+'(f,re.params);');
					} else {
						alert(re.value);
					}
				} else if(re.result == "error_validation") {
					for(i in re.value) {
						$(f).find(".vrf_"+i).html("! BŁĄD ! "+re.value[i]).show();
					}
					$.scrollTo($(".verif:visible").eq(0).parent());
				} else if(re.result == "error") {
					$(f).find(".vrf_global").html("! BŁĄD ! "+re.value).show();
				} else {
					$(f).find(".vrf_global").text("! BŁĄD ! Wystąpiły problemy techniczne").show();
				}
			};
			o.error = function() {
				$(f).find("wiatrak").hide();
				$(f).removeClass("ajaxWorking");
				$(f).find(".vrf_global").text("! BŁĄD ! Wystąpiły problemy techniczne").show();
			}
		}
	});
}

$(function(){
	$("#content .verif").hide();
	$(".markAll").markAllAsRead();
	phoneForm();
	phoneFormSelect();
	phoneModel();
	$(".sSR").surveyShowVotesBefore();
	$(".removeFriend").removeFiendAjax();
	$("form .preview").showPreviewBtn();
	$("a.removeTopic").removeTP('topic');
	$("a.removePost").removeTP('post');
	$("form").not("form.noAjax").doForm();
});

/** society **/

function showUsersForm(link,page) {
    if($("form.userForm input:checked").length < 1) {
	    $(link).attr("checked","checked");
	    return false;
	}
	var allPage = 1;
	if(page != undefined) {
	    allPage = 0;
	    var locA = $(link).parents("form").eq(0).attr("action");
	    $(link).parents("form").eq(0).attr("action",page);
	    // $(link).parents("form").eq(0).append('<input type="hidden" name="page" class="tmpPage" value="'+page+'"/>');
	}

	$(link).parents("form").eq(0).ajaxSubmit({
		beforeSubmit: function(d,f,o){
			if($(f).attr("class").indexOf("ajaxWorking") > 0) return false;
			$(f).addClass("ajaxWorking");
			o.success = function(re,st) {
			    if(allPage == 1) {
					$(f).parent().find("#filter").html(re);
				} else {
				    var act = $(f).parent().find("#filter .tab:visible");
				    $(act).after(re);
				    $(act).remove();
                    $.scrollTo($("#filter"));
				}
				// console.log(tabs);
				// $(tabs).not($(tabs).eq(0)).hide();
				$("div.box").doTabs("tabnav");
				$(f).removeClass("ajaxWorking");
				$(f).find(".tmpPage").remove();
                $(link).parents("form").eq(0).attr("action",locA);
				$(".societyPager .pager_next,.societyPager .pager_prev").click(function() {
				    showUsersForm($("form.userForm input:eq(0)"),$(this).attr("href"));
				    return false;
				});

			};
			o.error = function(re,st) {
			    $(f).removeClass("ajaxWorking");
			    $(f).find(".tmpPage").remove();
			}
		}
	});
}

$(function() {
	$("form.userForm input").click(function() {
		showUsersForm($(this));
	});
	$(".societyPager .pager_next,.societyPager .pager_prev").click(function() {
	    showUsersForm($("form.userForm input:eq(0)"),$(this).attr("href"));
	    return false;
	});
	var locH = window.location.hash;
	if(locH == "#nowo-zarejestrowani") {
	    $(".userBox .tabnav li:eq(1) a").trigger("click");
	}
	if(locH == "#najpopularniejsi") {
	    $(".userBox .tabnav li:eq(2) a").trigger("click");
	}
	if(locH == "#najbardziej-aktywni") {
	    $(".userBox .tabnav li:eq(3) a").trigger("click");
	}

});

/* *** START MAIL *** */

jQuery.fn.showMail = function(mail,h) {
	return this.each(function(){
		$(this).click(function() {
		    var link = this;
			$.ajax({
			    type:'get',
			    url:$(link).attr('href'),
			    dataType:'json',
			    beforeSend:function(main,h) {
			        showMailWiatrak(mail);
			    },
			    success: function(resp) {
			        if(resp.result == 'redirect') {
                        eval(resp.value);
			        } else if (resp.result == 'ok') {
				        $(mail).find("div.contentsTab").remove();
						$(mail).find("div.tab").hide();
						$(mail).find("div.content").append(resp.message);
						hideMailWiatrak(mail);
						$(mail).find("div.contentsTab").show();
						$(link).parents("li").eq(0).removeClass("unread");
						$(mail).find("div.content").css("height","auto");
						$(mail).find(".pager").hide();
						$(mail).find('div.contentsTab a.back').backLink(mail,h);
						$(mail).find('div.contentsTab a.trash').trashLink(mail,h);
						$(mail).find('div.contentsTab a.del').trashLink(mail,h,'confirm');
						$(mail).find('.reply,.forward').showMail(mail,h);
						var localTab = $(mail).find("div.contentsTab");
						$(mail).find("div.contentsTab .msgFormPost .recipientsBox .recipient").chooseRecipient(localTab);
						$(mail).find("div.contentsTab .msgFormPost .addRec").addRecipient(localTab);
						$(mail).find("div.contentsTab .msgFormPost .removeRec").removeRecipient(localTab);
						$(mail).find("div.contentsTab .msgFormPost input[type='submit']").sendMsg(mail,h,'resp');
					} else {
					    alert(resp.result);
					}
			    }
			});
			return false;
		});
	});
};

jQuery.fn.trashLink = function(mail,h,confirm) {
	return this.each(function() {
		$(this).click(function() {
		    var link = this;
		    var locA = $(mail).find(".tabnav li.active");
	        var locEq = $(mail).find(".tabnav li").index(locA);
			var locTab = $(mail).find(".content .tab:eq(" + locEq + ")");
			var orgRel = $(this).attr("rel");
		    if($(link).attr('rel') == "checkedOnly") {
				var locRel = "";
				$(locTab).find("input[type='checkbox']:checked").each(function() {
					locRel = locRel + $(this).attr("id") + ";";
				});
				if(locRel != ''){$(link).attr("rel",locRel);}
		    }
		    var curPage = $(locA).find("a").attr("title");
		    curPage = curPage.split("/");
		    if(curPage[1] == undefined) {curPage[1] = 1};
		    if($(link).attr('rel') != 'checkedOnly') {
		        if(confirm == 'confirm') {
		            var locText = 'wiadomość';
					var msgCount = $(link).attr('rel').split(";");
					if(msgCount.length > 1) {
					    locText = 'zaznaczone wiadomości';
					}
					var r=window.confirm("Czy napewno chcesz usunąć "+locText+"?");
					if(!r) {
					    $(link).attr("rel",orgRel);
						return false;
					}
			    }
				$.ajax({
				    type:'post',
				    url:$(link).attr('href'),
				    dataType:'json',
				    data:'id=' + $(link).attr('rel') + "&page=" + curPage[1],
				    beforeSend:function(main,h) {
				        showMailWiatrak(mail);
				    },
				    success: function(resp) {
						$(link).attr("rel",orgRel);
						if(resp.inbox != undefined) {reloadTab(mail,h,'inbox',resp.inbox,resp.inbox.page,resp.inbox.maxpage,resp.inbox.orderBy,resp.inbox.orderDirection);}
						if(resp.sent != undefined) {reloadTab(mail,h,'sent',resp.sent,resp.sent.page,resp.sent.maxpage,resp.sent.orderBy,resp.sent.orderDirection);}
						if(resp.trash != undefined) {reloadTab(mail,h,'trash',resp.trash,resp.trash.page,resp.trash.maxpage,resp.trash.orderBy,resp.trash.orderDirection);}
						hideMailWiatrak(mail);
						$(mail).find("div.content").css("height","auto");
						$(mail).find(".tabnav").find("li.active a").click();
				    }
				});
			}
			return false;
		});
	});
};

jQuery.fn.backLink = function(mail,h) {
	return this.each(function() {
		$(this).click(function() {
		    $(mail).find("div.content").css("height","auto");
			$(mail).find(".tabnav").find("li.active a").click();
		});
	});
};

jQuery.fn.chooseRecipient = function(localTab) {
	return this.each(function() {
		$(this).click(function() {
			$(this).toggleClass("choosen");
		});
	});
};

jQuery.fn.addRecipient = function(localTab) {
	return this.each(function() {
		$(this).click(function() {
			$(localTab).find("#knowRecipientsId div.choosen").appendTo($(localTab).find("#msgRecipientsId")).removeClass("choosen");;
		});
	});
};

jQuery.fn.removeRecipient = function(localTab) {
	return this.each(function() {
		$(this).click(function() {
			$(localTab).find("#msgRecipientsId div.choosen").appendTo($(localTab).find("#knowRecipientsId")).removeClass("choosen");;
		});
	});
};

jQuery.fn.reloadPageTab = function() {
	return this.each(function(){
	    $(this).unbind('click');
	    $(this).click(function() {
	        var link = this;
	        var mail = $("div.mail");
			var h = $(mail).find("div.content").css("height");
	        $.ajax({
			    type:'get',
			    url:$(link).attr('href'),
			    dataType:'json',
			    beforeSend:function(main,h) {
			        showMailWiatrak(mail);
			    },
			    success: function(resp) {
     				reloadTab(mail,h,'active',resp.tab,resp.tab.page,resp.tab.maxpage,resp.tab.orderBy,resp.tab.orderDirection);
     				hideMailWiatrak(mail);
			    }
			});
	        return false;
		});
	});
};

jQuery.fn.sendMsg = function(mail,h,type) {
	return this.each(function() {
		$(this).click(function() {
		    var form = $(this).parents("form").eq(0);
		    $(form).find("input#hdnRec").remove();
	        $(form).prepend('<input type="hidden" id="hdnRec" name="msgRec" value="" />');
	        var msgRec = "";
	        $(form).find("#msgRecipientsId div.recipient").each(function() {
	            msgRec = msgRec + $(this).attr("id") + ";";
	        });
	        $(form).find("input#hdnRec").val(msgRec);
	        $(form).ajaxSubmit({
			    dataType:'json',
			    type:'post',
			    beforeSubmit:function(){
			        showMailWiatrak(mail)
			    },
				success:function(resp){
				    if(resp.result == "ok") {
					    reloadTab(mail,h,'sent',resp.tab,resp.tab.page,resp.tab.maxpage,resp.tab.orderBy,resp.tab.orderDirection);
					    $(form).find("input#hdnRec").remove();
					    $(form).find("input#msgTitleId").val('');
					    $(form).find("textarea").val('');
					    $(form).find("#msgRecipientsId div").appendTo($(form).find("#knowRecipientsId"));
					    $(form).find("p.verif").html('');
					    hideMailWiatrak(mail)
					    $(mail).find(".tabnav li").find("a[title^='sent']").click();

				    } else {
				        if(typeof(resp.value) == 'object') {
					        var localError = '';
             				for(i in resp.value) {
             				    if(localError == '') {
					            	localError = localError + ' ' + resp.value[i];
					            }
							}
						} else {
						    var localError = resp.value;
						}
						$(form).find(".vrf_global").html('! BŁĄD ! ' + localError).show();
				        hideMailWiatrak(mail)
				    }
				}
			});
	        // $("#newMsgForm").submit();
		    return false;
		});
	});
}

function hideMailWiatrak(mail) {
    $(mail).find(".content .mailWiatrak").remove();
}

function showMailWiatrak(mail) {
    $(mail).find(".content").prepend('<div class="mailWiatrak" id="tmpWiatrak"><img alt="" src="/img/mail_wiatrak.gif"/></div>');
	var tmpw = $(mail).find("#tmpWiatrak");
	$(tmpw).width($(tmpw).parent().width());
	$(tmpw).height($(tmpw).parent().height());
	$(tmpw).find("img").css("margin-top","30px");
	$(tmpw).show();
}

function reloadTab(mail,h,tabname,content,page,maxPage,sortBy,sortOrder) {
// console.log(mail,h,tabname,content,page,maxPage,sortBy,sortOrder);
    var curPage = page;
    if(tabname == 'active') {
	    var locTab = "li.active a"
	    var visibleTab = ".tab:visible";
    } else {
        var locTab = "li a[title^='" + tabname + "']";
        var locA = $(mail).find(".tabnav li").find("a[title^='" + tabname + "']").parent();
		var locEq = $(mail).find(".tabnav li").index(locA);
		var visibleTab = ".tab:eq(" + locEq + ")";
    }
    $(".admin #content .content " + visibleTab).html(content.html);

    var locTitle = $("div.mail ul.tabnav " + locTab).attr("title");
    locTitle = locTitle.split("/");
    
    
    if (sortBy || sortOrder) {
			locTitle = locTitle[0] + "/" + curPage + "/" + sortBy + "/" + sortOrder;
			$("div.mail ul.tabnav " + locTab).attr("title",locTitle);
    }

    $("div.mail ul.tabnav " + locTab).attr("rel",maxPage);
    $("div.mail ul.tabnav " + locTab + " span").html("("+content.count+")");

	$(".admin #content .content " + visibleTab).find('a.back').backLink(mail,h);
	$(".admin #content .content " + visibleTab).find('a.trash').trashLink(mail,h);
	$(".admin #content .content " + visibleTab).find('a.del').trashLink(mail,h,'confirm');
    $(".admin #content .content " + visibleTab).find('.topic a').showMail(mail,h);

    $(".admin #content .content " + visibleTab).selectAll(".mailList li .chk",".mailBar dfn span");
    $(".admin #content .content " + visibleTab).find(".mailHead a").reloadPageTab();
    
    if (sortBy || sortOrder) {
			doMailPager($("div.mail ul.tabnav li.active a"));
    }
}

function doMailPager(a) {

	var newPager = '<div class="pager"></div>';
	var locTitle = $(a).attr("title");
	locTitle = locTitle.split("/");
	if(locTitle[1] == '' || locTitle[1] == undefined) {locTitle[1] = 1;}
	var linkBasePath = '/admin/poczta/tab/' + locTitle[0] + '/';
	if(locTitle[2] != null) {
    	linkBasePath += locTitle[2] + '/';
	} else {
	    linkBasePath += 'data/';
	}
	if(locTitle[3] != null) {
	    linkBasePath += locTitle[3] + '/';
	} else {
	    linkBasePath += 'm/';
	}

    $("#mailPager .pager").remove();
    if(parseInt($(a).attr("rel")) > 1) {
	    $("#mailPager").hide();
	    $("#mailPager").append(newPager);
	    var linkFirst = linkBasePath + 1;
	    var linkLast = linkBasePath + $(a).attr("rel");
	    var linkPrev = parseInt(locTitle[1]) - 1;
	    if(linkPrev < 1) { linkPrev = 1;}
	    linkPrev = linkBasePath + linkPrev;
	    var linkNext = parseInt(locTitle[1]) + 1;
	    if(linkNext > $(a).attr("rel")) {
			linkNext = linkLast;
		} else {
	    	linkNext = linkBasePath + linkNext;
	    }
	    var basicLinks = '<a href="' + linkFirst + '" class="first"/><a href="' + linkPrev + '" class="prev"/><a href="' + linkLast + '" class="last"/><a href="' + linkNext + '" class="next"/>';
     	$("#mailPager .pager").append(basicLinks);
	    var minPage = parseInt(locTitle[1]) - 3;
	    var maxPage = parseInt(locTitle[1]) + 3;
	    if(minPage < 1) {minPage = 1;}
	    if(maxPage > parseInt($(a).attr("rel"))) {
	        maxPage = parseInt($(a).attr("rel"));
	    }

	    var pageList = "";
	    if(minPage > 1) {
	        pageList = pageList + '<span><a href="'+linkFirst+'">1</a></span><span>...</span>';
	    }
	    for(i=minPage;i<=maxPage;i++) {
			if(i == locTitle[1]) {
				pageList = pageList + '<span class="active">' + i + '</span>';
			} else {
			    pageList = pageList + '<span><a href="' + linkBasePath + i + '">' + i + '</a></span>';
			}
	    }
	    if(maxPage < parseInt($(a).attr("rel"))) {
	        pageList = pageList + '<span>...</span><span><a href="'+linkLast+'">'+$(a).attr("rel")+'</a></span>';
	    }

	    $("#mailPager .pager").append(pageList);
	    $("#mailPager").show();
        $("#mailPager .pager a").reloadPageTab();
    }
};
/*
jQuery.fn.doSort = function(mail,h) {
	return this.each(function() {
		$(this).click(function() {
		    $.ajax({
		    });
		    return false;
		});
	});
}
*/

$(function() {

	var mail = $("div.mail");
	var h = $(mail).find("div.content").css("height");

	$(mail).find('ul.mailList').find('.topic a').showMail(mail,h);

	$(mail).find('.tabnav a').click(function() {
		$(mail).find("div.content").css("height","auto");
		$(mail).find("div.contentsTab").remove();
	});

	$(mail).find('a.back').backLink(mail,h);
	$(mail).find('a.trash').trashLink(mail,h);
	$(mail).find('a.del').trashLink(mail,h,'confirm');

    $("div.mail div.tab").selectAll(".mailList li .chk",".mailBar dfn span");

    $("div.mail ul.tabnav li a").click(function() {
		doMailPager($(this));
	});

	$("div.mail ul.tabnav li.first a").click();
	var mailTab = $(mail).find(".tab:last");
	$(".msgFormPost .recipientsBox .recipient").chooseRecipient(mailTab);
	$(".msgFormPost .addRec").addRecipient(mailTab);
	$(".msgFormPost .removeRec").removeRecipient(mailTab);
	$(".msgFormPost input[type='submit']").sendMsg(mail,h);

	$(".refresh").click(function() {
	    window.location.reload();
	});

	$(".mailHead a").reloadPageTab();
});

/* *** END MAIL *** */

jQuery.fn.rating = function() {
	return this.each(function(){
		$(this).hover(function() {
			if($(this).attr("class").indexOf("sending") >= 0) return false;
			$(this).append('<span><em></em></span>');
		}, function() {
			if($(this).attr("class").indexOf("sending") >= 0) return false;
			$(this).find("span").remove();
		});
		$(this).mousemove(function(e) {
			if($(this).attr("class").indexOf("sending") >= 0) return false;
			//var note = Math.ceil(e.originalEvent.layerX/10);
			var localOff = $(this).offset();
			var localOffX = localOff['left']
   			var pX = e.pageX - localOffX;
			var note = Math.ceil(pX/10);
			$(this).find("span em").width(note * 10);
		});

		$(this).click(function(e) {
			if($(this).attr("class").indexOf("sending") >= 0) return false;
			$(this).addClass("sending");
			var localOff = $(this).offset();
			var localOffX = localOff['left']
   			var pX = e.pageX - localOffX;
			var note = Math.ceil(pX/10);
			$(this).find("span em").width(note * 10);
			var link = this;
			$(this).ajaxSubmit({
			    type: 'post',
				url: $(link).attr("href"),
				beforeSubmit: function(d,f,o) {
					d.push({name:'note',value:note});
				}, success: function(re,st) {
					$(link).parent().append('<dfn><em style="width:'+(10*parseInt(re))+'px"></em></dfn>');
					$(link).remove();
				}, error: function() {
					$(link).find("span").remove();
					$(link).removeClass("sending");
				}
			});
			return false;
		});

	});
}

jQuery.fn.abuseLink = function() {
	return this.each(function() {
		$(this).click(function() {
			if($("#abuseForm").length < 1) return false;
			var off = $(this).position();
			var x = off['left'];
			var y = off['top'];
			$("#abuseForm").css('left',x+'px');
			$("#abuseForm").css('top',y+'px');
			$("#abuseForm form").attr("action",$(this).find("a").attr("rel"));
			if($("#abuseForm").height() + y > $("#content").height()) {
			    var newH = $("#abuseForm").height() + y + 10
			    $("#content .wrapper").css("height",newH + "px");
			}
			$("#abuseForm").slideDown(300);
			return false;
		});
	});
}

jQuery.fn.removeLink = function() {
	return this.each(function() {
		$(this).click(function() {
			var link = this;
			var ok = window.confirm("Czy napewno chcesz usunąć?");
			if(!ok) return false;
			$(this).ajaxSubmit({
				url: $(link).attr("href"),
				type:'post',
				dataType: 'json',
				beforeSubmit: function() {
					if($(link).attr("class").indexOf("ajaxWorking") >= 0) return false;
					$(link).addClass("ajaxWorking");
				}, success: function(re) {
				    if(re.result == "ok") {
						var li = $(link).parents("li").eq(0);
						var rest = $(li).nextAll("li");
						$(li).slideUp(300,function() {
							var cnt = $(this).parents(".content").eq(0).find("h4 .count strong").eq(0);
							$(cnt).text(""+(parseInt($(cnt).text())-1));
							$(this).remove();
						});
						if(rest.length > 0) {
							var i = $(rest).eq(0).attr("class").indexOf("odd") >= 0 ? 0 : 1;
							$(rest).each(function() {
								$(this).removeClass("even").removeClass("odd").addClass(i++%2 == 0 ? "even" : "odd");
							});
						}
					} else {
						    alert(re.value);
					}
				}, error: function() {
					$(link).removeClass("ajaxWorking");
				}
			});
			return false;
		});
	});
}

jQuery.fn.abuseCloseLink = function() {
	return this.each(function() {
		$(this).click(function() {
		    $("#abuseForm").slideUp(300);
			$("#abuseForm input.txt").val("");
			$("#abuseForm textarea").val("");
			$("#abuseForm .abuseSuccess").remove();
			$("#content .wrapper").css("height","auto");
			$("#abuseForm form").show();
		});
	});
};

jQuery.fn.checkAvilibity = function() {
	return this.each(function() {
		$(this).click(function() {
		    var link = $(this);
		    $.ajax({
			    type:'get',
			    url:$(link).attr('href'),
			    dataType:'html',
			    beforeSend:function() {
			    },
			    success: function(resp) {
			        var off = $(link).position();
					var x = off['left'];
					var y = off['top'];
					$("#checkAvilibityLayer").css('left',x+'px');
					$("#checkAvilibityLayer").css('top',y+'px');
			        $("#checkAvilibityLayer #chkAvOverlay").html(resp);
			        $("#checkAvilibityLayer").slideDown(300);
			    }
			});
			return false;
		});
	});
};

jQuery.fn.checkAvilibityClose = function() {
	return this.each(function() {
		$(this).click(function() {
		    $("#checkAvilibityLayer #chkAvOverlay").html('');
		    $("#checkAvilibityLayer").slideUp(300);
		    return false;
		});
	});
}

jQuery.fn.delItem = function() {
	return this.each(function() {
		$(this).click(function() {
		    var link = $(this);
		    $.ajax({
				url:$(link).attr('href'),
				type:'get',
				dataType: 'json',
				success:function(resp) {
				    if(resp.result == "ok") {
				    	window.location.reload();
					}
				}
		    });
		    return false;
		});
	});
}

jQuery.fn.changeAccess = function() {
	return this.each(function() {
		$(this).change(function() {
		    var form = $(this).parent();
		    var that = $(this);
		    $.ajax({
				url:$(form).attr('action'),
				type:'post',
				data:'access='+$(that).val()
		    });
		    return false;
		});
	});
}

function scrollY() {
	if (document.body && document.body.scrollTop) {
		return document.body.scrollTop;	/* DOM */
	}
	else if (document.documentElement && document.documentElement.scrollTop) {
		return document.documentElement.scrollTop; /* IE */
	}
	return 0;
}

jQuery.fn.overlayLink = function() {
	return this.each(function() {
		$(this).click(function() {
			if($("#overlayForm").length < 1) return false;
			$.blockUI({ message: $('#overlayForm'), css: { border: '0', left: '50%', top: '50%' } });
			return false;
		});
	});
}

jQuery.fn.overlayCloseLink = function() {
	return this.each(function() {
		$(this).click(function() {
			$.unblockUI();
			//$("#overlayForm").slideUp(300, function(){
				$("#overlayForm input.txt:not([name=phoneNumber])").val("");
				$("#overlayForm input.txt[name=phoneNumber]").val("+48");
				$("#overlayForm span.verif").hide().html("");
				$("#overlayForm .overlaySuccess").remove();
				$("#content .wrapper").css("height","auto");
				$("#overlayForm form").show();
			//});
		});
	});
};

function doDownload(f,obj){
	$.ajax({
		url: obj.url,
		type: "POST",
		dataType: "json",
		success: function(re, st){
			if (re.result == "ok") {
				$("#overlayForm a.close").click();
				$("div.slideMe").html('<p><strong>' + re.value + '</strong></p>').slideDown(300);
			} else if (re.result == "error") {
				$(f).find(".vrf_global").html("! BŁĄD ! "+re.value).show();
			}
		}
	});
	pageTracker._trackPageview('/pobierz-na-komorke/do-pobrania');
}

jQuery.fn.overlayAccept = function () {
 return this.each( function(){
	$.blockUI({ message: jQuery(this), css: { border: '0', left: '50%', top: '50%' } });
		var p = jQuery(this);
		jQuery(this).find(".close").click(function(){
			p.fadeOut(300, function(){
				$(this).find(".overlay2Success").remove();
				$.unblockUI();
				//$("#content .wrapper").css("height","auto");
			});
		});
  });
};

function sendWapSuccess(f,obj) {
	$("#overlayForm a.close").click();
	$("#overlayForm2 div.content").append('<div class="overlay2Success">' +obj + '</div>');
	$("#overlayForm2").overlayAccept();
	$("div.slideMe").html('<p><strong>' +obj + '</strong></p>').slideDown(300);
}

$(function() {
    $(".fileSetup a.delItem").delItem();
    $(".fileSetup form select").changeAccess();
	$("ul.items div.rating a").rating();
	$("p.checkAvilibity a").checkAvilibity();
	$("#checkAvilibityLayer #chkAvClose a").checkAvilibityClose();
	$("#abuseForm a.close").abuseCloseLink();
	$("#overlayForm a.close").overlayCloseLink();

	searchForm();
});