/* scripts.js */

function ssd() {

	var max_height = 0;
	if ($('#column_left') && $('#column_left').height() > max_height)
		max_height = $('#column_left').height();
	if ($('#column_right') && $('#column_right').height() > max_height)
		max_height = $('#column_right').height();

	if (max_height > 0)
		$('#main_vr').css('height', max_height);

	max_height = 0;

	if ($('#recommended_left') && $('#recommended_left').height() > max_height)
		max_height = $('#recommended_left').height();
	if ($('#recommended_right') && $('#recommended_right').height() > max_height)
		max_height = $('#recommended_right').height();

	if (max_height > 0)
		$('#recommended_vr').css('height', max_height);

	max_height = 0;

	if ($('#two_columns_left') && $('#two_columns_left').height() > max_height)
		max_height = $('#two_columns_left').height();
	if ($('#two_columns_right') && $('#two_columns_right').height() > max_height)
		max_height = $('#two_columns_right').height();

	if (max_height > 0)
		$('#two_columns_vr').css('height', max_height);
}

function show_permalink(e) {
	e.preventDefault();
	prompt('Ręcznie skopiuj poniższy link do schowka.\nDzięki niemu wybrany komentarz będzie można jednoznacznie wskazać.', $(this).attr('href'));
}

function addBookmarkForBrowser(url) {

	if ((navigator.userAgent.toLowerCase().indexOf('msie') > 0) && window.external) {
		window.external.AddFavorite(url, document.title);
	}
	else if (window.sidebar) {
		window.sidebar.addPanel(document.title, url, "");
	}
	else {
		alert('Naciśnij Ctrl+D');
	}
	return false;
}

if (typeof String.prototype.trim == 'undefined') {
	String.prototype.trim = $.trim;
}

function comment_reply(e) {
	e.preventDefault();	
	var id = /komentarz_(\d+)/.exec($(this).parent().attr('id'))[1];
	var comment_field = $('#fContent');
	
	$.get('/ajax/ajax_komentarz/', { 'id': id }, function(answer) {
		comment_field.val(answer);
		comment_field.attr('scrollTop', comment_field.attr('scrollHeight'));
		
		var targetOffset = $('#comment_form').offset().top;
		$('html,body').animate({scrollTop: targetOffset}, 1000, function() {
			$('#fContent').focus();
		});
	});
}

function raportuj(e) {
	e.preventDefault();	
	var id = /komentarz_(\d+)/.exec($(this).parent().parent().attr('id'))[1];

	if (!confirm("Na pewno chcesz zgłosić ten komentarz do usunięcia?")) {
		return;
	}

	var url = '/moderacja/ajax_raportuj';
	var pars = { co: 'komentarz', dane: id };

	$.post(url, pars, function(answer) {
		alert(answer);
	});
}

function init_comm_emails() {
	$("a.comment_email").each(function() {
		var regex = /(.*)#(.*)/i;
		var matches = $(this).text().match(regex);
		$(this).attr('href', 'mailto:'+matches[1]+'@'+matches[2]);
		$(this).text(matches[1]+'@'+matches[2]);
	});
}

var reg_fields = {};
var reg_status = {};
var reg_ok = {};

function init_reg_form() {
	if (arguments.callee.done) return;
	arguments.callee.done = true;

	// Collect handlers

	if (!edit_page) {
		reg_fields.username = $("#fProfileLogin");
		reg_status.username = $("#login_status");
	}

	reg_fields.passwd = $("#fProfilePass");
	reg_fields.passwd2 = $("#fPass2");
	reg_status.passwd = $("#pass_status");

	reg_fields.question = $("#fQuestion");
	reg_fields.answer = $("#fAnswer");
	reg_status.question = $("#question_status");

	reg_fields.nick = $("#fNick");
	reg_status.nick = $("#nick_status");


	reg_fields.email = $("#fEmail");
	reg_status.email = $("#email_status");


	reg_fields.bday = $("#fBday");
	reg_fields.bmonth = $("#fBmonth");
	reg_fields.byear = $("#fByear");
	reg_status.bday = $("#bday_status");

	// Attach events

	if (!edit_page) {
		reg_fields.username.onblur = reg_check_username;
	}

	reg_fields.passwd.onblur = reg_check_passwd;
	reg_fields.passwd2.onblur = reg_check_passwd;

//	reg_fields.question.onblur = reg_check_qa;
//	reg_fields.answer.onblur = reg_check_qa;

	reg_fields.nick.onblur = reg_check_nick;

	reg_fields.email.onblur = reg_check_email;

	reg_fields.bday.onblur = reg_check_bday;
	reg_fields.bmonth.onblur = reg_check_bday;
	reg_fields.byear.onblur = reg_check_bday;

	$("#form-register").onsubmit = reg_check_form;

}

function reg_set_status(obj, status, msg) {
	if (status) {
		removeClass(obj, 'status-bad');
		addClass(obj, 'status-ok');
		reg_ok[obj.id] = true;
	} else {
		removeClass(obj, 'status-ok');
		addClass(obj, 'status-bad');
		reg_ok[obj.id] = false;
	}
}

function reg_check_username() {
	if (reg_fields.username.value.length < 3 || reg_fields.username.value.length > 32) {
		reg_set_status(reg_status.username, false);
		return;
	}

	var url = 'ajax_sprawdz';
	var pars = 'co=username&dane=' + encodeURIComponent(reg_fields.username.value);

	var myAjax = new Ajax.Request(
		url,
		{
			method: 'get',
			parameters: pars,
			onComplete: reg_check_username_done
		});
}

function reg_check_username_done(originalRequest) {
	var answer = originalRequest.responseText;
	reg_set_status(reg_status.username, answer == '1' ? false : true);
}

function reg_check_nick() {
	if (reg_fields.nick.value.length < 3 || reg_fields.nick.value.length > 32) {
		reg_set_status(reg_status.nick, false);
		return;
	}

	var url = 'ajax_sprawdz';
	var pars = 'co=username&dane=' + encodeURIComponent(reg_fields.nick.value);

	if (edit_page) {
		pars += '&edit=1';
	}

	var myAjax = new Ajax.Request(
		url,
		{
			method: 'get',
			parameters: pars,
			onComplete: reg_check_nick_done
		});
}

function reg_check_nick_done(originalRequest) {
	var answer = originalRequest.responseText;
	reg_set_status(reg_status.nick, answer == '1' ? false : true);
}

function reg_check_passwd() {
	if (edit_page && reg_fields.passwd.value.length == 0) {
		reg_set_status(reg_status.passwd, true);
		return;
	}

	if (reg_fields.passwd.value == reg_fields.passwd2.value && reg_fields.passwd.value.length >= 5 && reg_fields.passwd.value.length <= 16) {
		reg_set_status(reg_status.passwd, true);
	} else {
		reg_set_status(reg_status.passwd, false);
	}
}

function reg_check_qa() {
	if (reg_fields.question.value.length == 0 || reg_fields.answer.value.length == 0) {
		reg_set_status(reg_status.question, false);
	} else {
		reg_set_status(reg_status.question, true);
	}
}

function isValidEMail(adres) {
	var urlRegex = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/i;
	var match = adres.match(urlRegex);

	if (match != null) {
		return true;
	} else {
		return false;
	}
}

function reg_check_email() {
	if (isValidEMail(reg_fields.email.value)) {
		reg_set_status(reg_status.email, true);
	} else {
		reg_set_status(reg_status.email, false);
	}
}

function reg_check_bday() {

	if (reg_fields.bday.value != 0 && reg_fields.bmonth.value != 0 && reg_fields.byear.value != 0) {

		var url = 'ajax_sprawdz';
		var pars = 'co=date&year=' + reg_fields.byear.value + "&month=" + reg_fields.bmonth.value + "&day=" + reg_fields.bday.value;

		var myAjax = new Ajax.Request(
			url,
			{
				method: 'get',
				parameters: pars,
				onComplete: reg_check_bday_done
			});

	} else if (reg_fields.bday.value != 0 || reg_fields.bmonth.value != 0 || reg_fields.byear.value != 0) {
		reg_set_status(reg_status.bday, false);
	} else {
		reg_set_status(reg_status.bday, true);
	}
}

function reg_check_bday_done(originalRequest) {
	var answer = originalRequest.responseText;
	reg_set_status(reg_status.bday, answer == '1' ? false : true);
}

function reg_start_magic() {
	if (arguments.callee.done) return;
	arguments.callee.done = true;

	init_reg_form();

	var sDate = new Date();
}

function reg_check_form() {
	if (!edit_page) {
		reg_check_username();
	}
	reg_check_passwd();
	reg_check_qa();
	reg_check_nick();
	reg_check_email();
	reg_check_bday();

	if (!edit_page) {
		if (reg_ok.login_status == false) return false;
	}
	if (reg_ok.pass_status == false) return false;
	if (reg_ok.question_status == false) return false;
	if (reg_ok.email_status == false) return false;
	if (reg_ok.nick_status == false) return false;
	if (reg_ok.bday_status == false) return false;

	return true;
}

function facebook_disconnect(e) {
	if (!confirm('Rozłączenie kont w przypadku, gdy nie ustawiono hasła spowoduje brak możliwości zalogowania się.\n\nCzy na pewno chcesz usunąć powiązanie z kontem Facebook?')) {
		e.preventDefault();
	}
}

function init_logo() {
	function pad(n){return n<10 ? '0'+n : n}
	var data = new Date();
	var ymd = data.getFullYear() + '' + pad(data.getMonth()+1) + '' + pad(data.getDate());
	var md = pad(data.getMonth()+1) + '' + pad(data.getDate());
	if (ymd == '20100301') {
		$('#top_logo').style.backgroundImage = 'url(/img/logo_snobka_chopin.gif)';
	}
	if (md == '0308') {
		$('#top_logo').style.backgroundImage = 'url(/img/logo_snobka_kobiety.gif)';
	}
	if (ymd >= '20100331' && ymd <= '20100405') {
		$('#top_logo').style.backgroundImage = 'url(/img/logo_snobka_wielkanoc.gif)';
	}
	if (ymd <= '20100418') {
		$('#top_logo').style.backgroundImage = 'url(/img/logo_snobka_zaloba.jpg)';
	}
	if (md >= '0502' && md <= '0503') {
		$('#top_logo').style.backgroundImage = 'url(/img/logo_snobka_maj.gif)';
	}
	if (md == '0526') {
		$('#top_logo').style.backgroundImage = 'url(/img/logo_snobka_dzienmatki.gif)';
	}
}

/*
 * Translated default messages for the jQuery validation plugin.
 * Locale: PL
 */
jQuery.extend(jQuery.validator.messages, {
	required: "To pole jest wymagane.",
	remote: "Proszę o wypełnienie tego pola.",
	email: "Proszę o podanie prawidłowego adresu email.",
	url: "Proszę o podanie prawidłowego URL.",
	date: "Proszę o podanie prawidłowej daty.",
	dateISO: "Proszę o podanie prawidłowej daty (ISO).",
	number: "Proszę o podanie prawidłowej liczby.",
	digits: "Proszę o podanie samych cyfr.",
	creditcard: "Proszę o podanie prawidłowej karty kredytowej.",
	equalTo: "Proszę o podanie tej samej wartości ponownie.",
	accept: "Proszę o podanie wartości z prawidłowym rozszerzeniem.",
	maxlength: jQuery.validator.format("Proszę o podanie nie więcej niż {0} znaków."),
	minlength: jQuery.validator.format("Proszę o podanie przynajmniej {0} znaków."),
	rangelength: jQuery.validator.format("Proszę o podanie wartości o długości od {0} do {1} znaków."),
	range: jQuery.validator.format("Proszę o podanie wartości z przedziału od {0} do {1}."),
	max: jQuery.validator.format("Proszę o podanie wartości mniejszej bądź równej {0}."),
	min: jQuery.validator.format("Proszę o podanie wartości większej bądź równej {0}.")
});

$(window).load(ssd);
$(document).ready(init_comm_emails);
$(document).ready(init_logo);

$(document).ready(function() {
	window.fbAsyncInit = function() {
		FB.init({appId: '31e05351fed7c1688a2565fcb36e1fff', status: true, cookie: true, xfbml: true});
		FB.Event.subscribe('auth.sessionChange', function(response) {
			if (response.session) {
				window.location.reload();
			} else {
				window.location.href="/profil/wylogowanie";
			}
		});
	};
	
	(function() {
		var e = document.createElement('script'); e.async = true;
		e.src = document.location.protocol +
		'//connect.facebook.net/pl_PL/all.js';
		$('#fb-root').append(e);
	}());

	$('#facebook_disconnect').click(facebook_disconnect);

	$('a.big_image').fancybox({type: 'image'});
	$('.fancybox_comment').fancybox({type: 'image', titleShow: false});
		
	$('.reply').click(comment_reply);
	$('.report_comm').click(raportuj);
	$('.permalink').click(show_permalink);

	$('#fTopLogin').focus(function() {
		if ($(this).val() == 'login') {
			$(this).val('');
			$(this).css('color', '#000');
		}
	});

	$('#fTopLogin').blur(function() {
		if ($(this).val() == '') {
			$(this).removeAttr('style');
			$(this).val('login');
		}
	});

	$('#fTopPass').focus(function() {
		if ($(this).val() == 'hasło') {
			$(this).val('');
			$(this).css('color', '#000');
		}
	});

	$('#fTopPass').blur(function() {
		if ($(this).val() == '') {
			$(this).removeAttr('style');
			$(this).val('hasło');
		}
	});

});
