
var domainURL = 'http://' + document.domain + '/';
var imgDomainURL = '';
var iconWait = '<img src="'+domainURL+'static/im/wait.gif" alt="Proszę czekać..."/>';

var APP_URL = 'http://'+document.domain+'/';
var ICON_WAIT = 'http://' + document.domain + '/static/im/wait.gif';
var ICON_IMG = '<img src="'+ICON_WAIT+'" alt="Proszę czekać"/>';

var fhelpers = new Array(70);

function loginForm()
{
	$("#login_button").attr('src',"/static/im/loader.gif");
	$("#err_login_form").html('');
	$.post("/user/login/",
		  $("form[name='login_form']").serialize(),
		  function(data)
		  {
		  	//alert(data.result);
			if (data.result == 1)
			{
				if ($("#backurl").val())
					location.href = baseURL +$("#backurl").val();
				else
					location.reload(true);
			}
			else if (data.result == -1)
			{
				$("#login_button").attr('src',"/static/im/log_btn.png");
				$("#err_login_form").html('Twoje konto zostało zablokowane.');
			}					
			else if (data.result == -2)
			{
				$("#login_button").attr('src',"/static/im/log_btn.png");
				$("#err_login_form").html('Twoje konto nie zostało jeszcze aktywowane. Podczas rejestracji wysłaliśmy do Ciebie email z linkiem aktywacyjnym. Jeśli chcesz abyśmy jeszcze raz wysłali emaila, <a href="#" onclick="javascript:resendActivationEmailForm();return false;">kliknij tutaj</a>.');
			}					
			else
			{
				$("#login_button").attr('src',"/static/im/log_btn.png");
				$("#err_login_form").html('Niepoprawne dane logowania');
			}
	
		  },
		  'json');	 
	return false;
}
function resendActivationEmailForm()
{
	$("#login_button").attr('src',"/static/im/loader.gif");
	$("#err_login_form").html('');
	$.post("/registration/resendactivationemail/",
		  $("form[name='login_form']").serialize(),
		  function(data)
		  {
		  	if (data.result == 1)
			{
				$("#login_button").attr('src',"/static/im/log_btn.png");
				$("#err_login_form").html('Link aktywacyjny został wysłany emailem. Sprawdź swoją skrzynkę pocztową. Jeśli nie znajdujesz tam emaila, sprawdź skrzynkę SPAM, niekótre systemy błędnie klasyfikują emaile rejestracyjne.');
			}
			else if (data.result == 2)
			{
				$("#login_button").attr('src',"/static/im/log_btn.png");
				$("#err_login_form").html('Niepoprawne dane logowania');
			}						
			else
			{
				$("#login_button").attr('src',"/static/im/log_btn.png");
				$("#err_login_form").html('Błąd podczas wysyłania emaila aktywacyjnego');
			}
	
		  },
		  'json');	 
	return false;
}


function url(u,a)
{
	a = a.length == 0?u:a;
	u = u.substring(0,7) == 'http://'?u:('http://'+u);
	document.write('<a href="'+u+'">'+a+'</a>');
}

function goto(url)
{
	if (url.length > 3)
		document.location.href='http://'+url;
}




function deleteMBPost(uid,id)
{
	if(!confirm('Czy na pewno usunąć tą wiadomość?'))return;
	$('#miniblog_'+id).html('czekaj...');
	$.ajax({type:'POST',url:APP_URL+'/profile/deletembmsg/',data:{msg_id:id,uid:uid},
	success:function(txt)
	{
		if (txt == '1')
			$('#miniblog_'+id).html('Wiadomość usunięta');
		else
			$('#miniblog_'+id).html('Błąd');
	}});
}

function url(u,a)
{
	a = a.length == 0?u:a;
	u = u.substring(0,7) == 'http://'?u:('http://'+u);
	document.write('<a href="'+u+'">'+a+'</a>');
}

function addMBMsg()
{
	var isValid=true;
	$('#err_mb_msg').html('');
	var msg=$('#mb_msg').attr('value');
	if(!msg || msg.length<2)
	{
		$('#err_mb_msg').html('Minimalna długość to 2 znaki');
		isValid=false;
	}
	
	return isValid;
}

function editHeadThought()
{
	if ($('#head_thought').css('display') == 'block')
	{
		$('#head_thought').css({display:'none'});
		$('#head_thought_edit').css({display:'block'});
	}
	else
	{
		$('#head_thought').css({display:'block'});
		$('#head_thought_edit').css({display:'none'});
	}
}

function saveHeadThought()
{
	var hdt=$('#ht_text').attr('value');
	$('#ht_text_button').attr('disabled','true');
	$('#err_ht_text').html(ICON_IMG);
	$.ajax({type:'POST',url:APP_URL+'/profile/addhdtxt/',data:{hdt:hdt},
	success:function(txt){
		$('#err_ht_text').html('Zapisano');
		$('#head_thought').html(hdt);
		$('#ht_text_button').attr('disabled','');
		editHeadThought();
	}});
}

function deleteMessage(id, directory)
{
	if (directory == 0)
	{
		if(!confirm('Czy na pewno usunąć tą wiadomość?'))return;
		$('#message_'+id).html(ICON_IMG);
		$.ajax({type:'POST',url:APP_URL+'/messages/handler/',data:{id:id,directory:directory},
		success:function(txt){
			$('#message_'+id).html('Usunięto');
		}});
	}
	else
	{
		if(!confirm('Czy na pewno przenieść tą wiadomość do kosza?'))return;
		$('#message_'+id).html(ICON_IMG);
		$.ajax({type:'POST',url:APP_URL+'/messages/handler/',data:{id:id,directory:directory},
		success:function(txt){
			$('#message_'+id).html('Przeniesiono do kosza');
		}});
	}
}

function rejectInvitation(uid,id)
{
	$('#friend_request_opt_'+id).html('czekaj...');
	$.ajax({type:'POST',url:APP_URL+'/account/friendsrequests/',data:{kind:1,id:id,uid:uid},
	success:function(txt)
	{
		if (txt == null || txt.length == 0)
			$('#friend_request_'+id).html('Błąd');
		else
			$('#friend_request_'+id).html('Zaproszenie odrzucone');
	}});
}

function deleteInvitation(uid,id)
{
	$('#friend_request_opt_'+id).html('czekaj...');
	$.ajax({type:'POST',url:APP_URL+'/account/friendsrequests/',data:{kind:2,id:id,uid:uid},
	success:function(txt)
	{
		if (txt == null || txt.length == 0)
			$('#friend_request_'+id).html('Błąd');
		else
			$('#friend_request_'+id).html('Zaproszenie usunięto');
	}});
}

function acceptInvitation(uid,id)
{
	$('#friend_request_opt_'+id).html('czekaj...');
	$.ajax({type:'POST',url:APP_URL+'/account/friendsrequests/',data:{kind:3,id:id,uid:uid},
	success:function(txt)
	{
		if (txt == null || txt.length == 0)
			$('#friend_request_'+id).html('Błąd');
		else
			$('#friend_request_'+id).html('Jesteście znajomymi!');
	}});
}

function deleteFriendGroup(id)
{
	$('#friend_request_opt_'+id).html('czekaj...');
	$.ajax({type:'POST',url:APP_URL+'/account/friendsrequests/',data:{kind:3,id:id,uid:uid},
	success:function(txt)
	{
		if (txt == null || txt.length == 0)
			$('#friend_request_'+id).html('Błąd');
		else
			$('#friend_request_'+id).html('Jesteście znajomymi!');
	}});
}

function deleteFriendGroup(id)
{
	$('#friend_group_opt_'+id).html('czekaj...');
	$.ajax({type:'POST',url:APP_URL+'/account/friendsrequests/',data:{kind:4,id:id},
	success:function(txt)
	{
		if (txt == null || txt.length == 0)
			$('#friend_group_'+id).html('Błąd');
		else
			$('#friend_group_'+id).html('Grupa została usunięta a jej członkowie przeniesieni do grupy głównej');
	}});
}

function editFriendGroup(id)
{
	$('#friend_group_opt_'+id).html('jeszcze nie ma');
}


function removeFriend(id)
{
	if(!confirm('Czy na pewno usunąć z listy znajomych?'))return;
	$('#friend_opt_'+id).html(ICON_IMG+' czekaj...');
	$.ajax({type:'POST',url:APP_URL+'/account/friendsrequests/',data:{kind:5,id:id},
	success:function(txt)
	{
		if (txt == null || txt.length == 0)
			$('#friend_'+id).html('Błąd');
		else
			$('#friend_'+id).html('Usunięty ze znajomych');
	}});
}

function showBox(open,close)
{
	$('#'+open).slideDown('slow');
	$('#'+close).hide('slow');
}

function showInfo(id)
{
	alert('Pomoc chwilowo niedostępna...');
}

function autoKredytowanie()
{
	var isChecked = $('#nowy').attr('checked');
	if(isChecked == true)
	{
		$('#rocznik').attr('value', '');
		$('#rocznik').attr('readonly', 'readonly');
	}
	else
	{
		$('#rocznik').attr('readonly', '');
	}
}

var ie=(document.all)?true:false;
if(!ie){document.addEventListener('mousemove', mpos, false);var pozX,pozY;}

function mpos(e){pozX=e.pageX;pozY=e.pageY;}
function bout(){$('#bubble').css('display','none');}

function bmov()
{
	scrolly=0;
	if(document.documentElement.scrollTop)scrolly=document.documentElement.scrollTop;
	if(document.body.scrollTop)scrolly=document.body.scrollTop;
	var x=(!ie)?pozX:event.x+document.body.scrollLeft;
	var y=(!ie)?pozY:event.y+scrolly;
	$('#bubble').css({left:x+5+'px', top:y+2+'px'});
}

function bover(id)
{
	bmov();
	initBubble(id);
	$('#bubble').css('display','block');
	return true;
}

function b_txtover(btxt)
{
	if(btxt.length>0)
	{
		setBubble('',btxt);
		bmov();
		$('#bubble').css('display','block');
	}
	return true;
}

function setBubble(t,info)
{
	$('#bubble_t').text(t);
	$('#bubble_info').html(info);
}

function initBubble(id)
{
	if(id>0)
	{
		if(typeof fhelpers[id] === 'undefined')
		{
			setBubble('Wczytuję...',ICON_IMG);
			$.getJSON(APP_URL+'objasnienie/pobierz/'+id,function(json){
				setBubble(json.name,json.description);
				fhelpers[id] = [json.name,json.description];
			});
		}else setBubble(fhelpers[id][0],fhelpers[id][1]);
	}else setBubble('Wczytuję...',ICON_IMG);
}


function dForum(id,kind)
{
	if(!confirm('Czy na pewno?'))return;
	$('#moderator_'+id).html(ICON_IMG);
	$.ajax({type:'POST',url:APP_URL+'forum/delete/id/'+id,data:{kind:kind},
	success:function(txt)
	{
		if (txt == '1')
			$('#moderator_'+id).html('Usunięto');
		else
			$('#moderator_'+id).html('Błąd');
	}});
}

function dOpinion(id,tn,tid)
{
	if(!confirm('Czy na pewno?'))return;
	$('#moderator_'+id).html(ICON_IMG);
	$.ajax({type:'POST',url:APP_URL+'opinions/delete/id/'+id,data:{tn:tn,tid:tid},
	success:function(txt)
	{
		alert(txt);
		if (txt == '1')
			$('#moderator_'+id).html('Usunięto');
		else
			$('#moderator_'+id).html('Błąd');
	}});
}

function dArtComment(id)
{
	if(!confirm('Czy na pewno?'))return;
	$('#moderator_'+id).html(ICON_IMG);
	$.ajax({type:'POST',url:APP_URL+'news/delete/',data:{id:id},
	success:function(txt)
	{
		alert(txt);
		if (txt == '1')
			$('#moderator_'+id).html('Usunięto');
		else
			$('#moderator_'+id).html('Błąd');
	}});
}

function validateSavingAccounts()
{
	var kwota=$('#kwota').attr('value');
	$('#kwota_err').text('');
	if (kwota <= 0)
	{
		$('#kwota_err').text('Musisz podać kwotę');
		return false;
	}
	return true;
}

function valArtComment()
{
	var isValid=true;
	$('#err_comment').html('');
	if($('#comment').val().length < 3)
	{
		$('#err_comment').html('Minimalna długość komentarza to 3 znaki');
		isValid=false;
	}
	return isValid;
}

function valOpinion()
{
	var isValid=true;
	$('#err_comment').html('');
	$('#err_title').html('');
	if($('#comment').val().length < 3)
	{
		$('#err_comment').html('Treść musi zawierać co najmniej 3 znaki');
		isValid=false;
	}
	if($('#title').val().length < 3)
	{
		$('#err_title').html('Tytuł musi zawierać co najmniej 3 znaki');
		isValid=false;
	}
	return isValid;
}

function validateTermDeposits()
{
	var kwota=$('#kwota').attr('value');
	$('#kwota_err').text('');
	if (kwota <= 0)
	{
		$('#kwota_err').text('Musisz podać kwotę lokaty');
		return false;
	}
	return true;
}

function validateKredytHipoteczny()
{
	var kwota=$('#kwota').attr('value');
	$('#kwota_err').text('');
	if (kwota <= 0)
	{
		$('#kwota_err').text('Musisz podać kwotę kredytu');
		return false;
	}
	return true;
}

function showAllElems(elemClass, elemID)
{
	$('#'+elemID).hide('slow');
	$('.'+elemClass).slideDown('slow');
}

function valRegistration(isCompetition)
{
var isValid = true;
clearField('err_login');
clearField('err_email');
clearField('err_password');
clearField('err_re_password');
clearField('err_gender');

if ($('#login_reg').val().length <= 2)
{
	$('#err_login').text('Minimalna długość to 3 znaki');
	isValid = false;
}

if ($("input[name='gender']:checked").val() == undefined)
{
	$('#err_gender').text('Wybierz płeć');
	isValid = false;
}

if (isCompetition == 1)
{
clearField('err_first_name');
clearField('err_surname');
clearField('err_provinces_id');
clearField('err_city');
clearField('err_err_phone_no');

if ($('#first_name').val().length <= 2)
{
	$('#err_first_name').text('Minimalna długość to 3 znaki');
	isValid = false;
}

if ($('#surname').val().length <= 2)
{
	$('#err_surname').text('Minimalna długość to 3 znaki');
	isValid = false;
}

if ($('#city').val().length <= 2)
{
	$('#err_city').text('Minimalna długość to 3 znaki');
	isValid = false;
}

if ($('#phone_no').val().length <= 2)
{
	$('#err_phone_no').text('Wprowadz numer telefonu');
	isValid = false;
}

if (!($('#birthday_date_dd').val() > 0 && $('#birthday_date_mm').val() > 0 && $('#birthday_date_yyyy').val() > 0))
{
	$('#err_birthday_date').text('Podaj pełną datę urodzenia');
	isValid = false;
}

if ($('#provinces_id').val() <= 0)
{
	$('#err_provinces_id').text('Wybierz z listy');
	isValid = false;
}

}
	return isValid;
}

function clearField(id)
{
	/*$('#'+id).hide('slow');*/
	$('#'+id).html('');
}

function deleteUserImage(id)
{
	if(!confirm('Czy na pewno chcesz usunąć to zdjęcie?'))return;
	$('#userImageWait_'+id).html(ICON_IMG+' Usuwanie. Proszę czekać...');
	$.ajax({type:'POST',url:APP_URL+'uzytkownik/deleteuserimage/',data:{f:'fpp',pid:id},
	success:function(txt)
	{
		alert(txt);
		if (txt == '1')
			$('#userImage_'+id).html('Zdjęcie usunięte');
		else
			$('#userImage_'+id).html('Błąd podczas usuwania zdjęcia.');
	}});
}

function setUserAvatar(id)
{
	$('#userAvatarWait_'+id).html(ICON_IMG+' Proszę czekać...');
	var imgsrc = $('#userImageSrc_'+id).attr('src');
	imgsrc = imgsrc.replace('_160', '_90');
	$.ajax({type:'POST',url:APP_URL+'uzytkownik/setuseravatar/',data:{f:'fpp',pid:id},
	success:function(txt)
	{
		$('#userAvatarWait_'+id).hide();
		alert(txt);
		if (txt == '1')
		{
			$('#userAvatar').attr('src', imgsrc);
			alert('Avatar zmieniony');
		}
		else
			alert('Błąd podczas ustawiania Avatara');
	}});
}

function showFmbOption(id)
{
	$('#fmb_icon'+id).hide();
	$('#fmb_option'+id).show('slow');
}



var prototype = {};
prototype.string = {};

prototype.string.autolink = function (string, options){
    if(!options) options = {};
    if(!options.limit) options.limit;
    if(!options.tagFill) options.tagFill = '';
    
    var regex = /((http\:\/\/|https\:\/\/|ftp\:\/\/)|(www\.))+(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi;
    
    string = string.replace(regex, function(value){
       // value = value.toLowerCase();
        var m = value.match(/^([a-z]+:\/\/)/);
        var nice;
        var url;
        
        if(m)
        {
            nice = value.replace(m[1],'');
            url = value;
        }
        else
        {
            nice = value;
            url = 'http://' + nice;
        }
        
        return '<a href="' + url + '"' + (options.tagFill != '' ? (' ' + options.tagFill) : '')+ ' ref="nofollow" >' + prototype.string.autolinkLabel(nice, options.limit) + '</a>';
    });
    return string;
};


prototype.string.autolinkLabel = function (text, limit){

    if (!limit){ return text; }

    if (text.length > limit){
        return text.substr(0, limit - 3) + '...';
    }

    return text;
};

$(function(){
	 jQuery.each($('.news_content'), function() {
	$(this).html((prototype.string.autolink($(this).html())));
    });
});

function setAward(tn,tid)
{
	var a=$('#award_ac').val();
	$('#set_award').html(ICON_IMG);
	$.ajax({type:'POST',url:APP_URL+'informacje/setaward/',data:{f:'fsa',a:a,tn:tn,tid:tid},
	success:function(txt)
	{
		if (txt == '1')
			$('#set_award').html('Ustawiono. Odśwież stronę.');
		else $('#set_award').html('Błąd');
	}});
}

function delAvatarSubmit()
{
	return confirm('Na pewno usunąć aktualny Avatar?');
}
