var base = '';
var theme = '';

/* Przegladarka zdjec */
$(document).ready(function () {
	theme = $('script[src$="default.js"]').attr('src').replace('Scripts/default.js', '');
	base = theme.replace(new RegExp("Themes/.+", "i"), '');

	var settings = {
		imageLoading: theme + 'Images/lightbox/lightbox-ico-loading.gif',
		imageBtnPrev: theme + 'Images/lightbox/lightbox-btn-prev.gif',
		imageBtnNext: theme + 'Images/lightbox/lightbox-btn-next.gif',
		imageBtnClose: theme + 'Images/lightbox/lightbox-btn-close.gif',
		imageBlank: theme + 'Images/lightbox/lightbox-blank.gif',
		imageBtnPlay: theme + 'Images/lightbox/lightbox-btn-play.gif',
		imageBtnStop: theme + 'Images/lightbox/lightbox-btn-stop.gif'
	};
	$('a[rel*=lightbox]').lightBox(settings);
	$('a[class*=lightbox]').lightBox(settings);
});

/* Sterowanie szerokoscia kolumn */
$(document).ready(function () {
	var width = 0;
	var reg4 = $('.reg4');
	var reg6 = $('.regprawy');
	var reg8 = $('.reg8');

	if (reg4.length == 0 && reg6.length == 0 && reg8.length == 0) {
		width = 943;
	}
	else if (reg4.length == 0 && reg8.length == 0) {
		width = 654;
	}
	else if (reg6.length == 0) {
		width = 732;
	}

	if (width > 0) {
		$('.regsrodkowy').width(width);
	}
});

/* Ocena */
$(document).ready(function () {
	var getRating = function (sender, e) {
		if (typeof (sender.position) == 'undefined')
			sender.position = $(sender).offset();

		var rating = 1 + parseInt((e.pageX - sender.position.left) / 12);

		return rating;
	}

	var setRating = function (sender, rating) {
		$(sender).find('span').width(Math.round(rating * 12));
	}

	$('span.rating').each(function () {
		var stars = $(this);
		var current = $(this).find('span').attr('rel').replace(',', '.');

		setRating(this, current);

		if ($(this).attr('rel')) {
			stars.mousemove(function (e) {
				var rating = getRating(this, e);
				setRating(this, rating);
			});

			stars.mouseleave(function (e) {
				setRating(this, current);
			});

			stars.click(function (e) {
				var rating = getRating(this, e);
				var link = $(this).attr('rel') + '/' + rating;

				$.ajax({
					type: 'POST',
					data: '{}',
					url: link,
					contentType: 'application/json; charset=utf-8',
					dataType: 'json',
					success: function (data, status) {
						if (data.d.Status == true) {
							current = data.d.Rating;
							setRating(stars.get(0), current);
							stars.find('span').attr('rel', current);
						}

						$('<div class="rating-message"></div>')
							.html(data.d.Message)
							.hide()
							.insertAfter(stars)
							.fadeIn('slow')
							.animate({ opacity: 1.0 }, 3000)
							.fadeOut('slow');
					}
				});

				$(this)
					.css('cursor', 'default')
					.trigger('mouseout', e)
					.unbind('mousemove')
					.unbind('click');
			});
		}
		else {
			$(this).css('cursor', 'default');
		}
	});
});

/* W przypadku naciśnięcia klawisza enter wywołuje akcję podpiętą pod dany przycisk */
function Exec(e, xpath) {
	e = e || window.event;

	if (e.keyCode == 13) {
		var button = $(xpath).get(0);

		if (button != null) {
			if (button.href != null && button.href != "") {
				location.href = button.href;
			}
			else {
				button.click();
			}
		}

		return false;
	}
}


var EditoCalendar = new Object();

/* wywolanie kalendarza */
EditoCalendar.showCalendar = function (obj, field, btn) {
	Calendar.setup({
		inputField: field,
		ifFormat: "%Y-%m-%d",
		button: btn,
		singleClick: true,
		align: "Lt"
	});
	obj.onclick();
	return false;
}

/* ServiceLine */
$(document).ready(function () {
	$('div.service-line-block').each(function () {
		var parent = this;
		$(this).children('div.tabs').children('div').click(function () {
			var id = $(this).prevAll().size();
			$(parent).children('div.content').children('div').css('display', 'none');
			$(parent).children('div.content').children('div').eq(id).css('display', '');
			$(parent).children('div.tabs').children('div').removeClass("active");
			$(parent).children('div.tabs').children('div').eq(id).addClass("active");
		});
	});
});

/* Ajax Indicator */
jQuery.fn.extend({
	showAjaxIndicator: function () {
		var div = $('<div class="jq-ajax-indicator"></div>');
		this.before(div);

		div.css('width', this.get(0).offsetWidth + 'px');
		div.css('height', this.get(0).offsetHeight + 'px');
		div.css('top', this.get(0).offsetTop + 'px');
		div.css('left', this.get(0).offsetLeft + 'px');
	},

	hideAjaxIndicator: function () {
		$(this).prev('div.jq-ajax-indicator').remove();
	}
});


/* Komentarze */
$(document).ready(function () {
	var ajaxurl = $('#jq-comments-url').val();
	var token = $('#jq-comments-token').val();

	var getComments = function (token, pageIndex) {
		$.ajax({
			type: 'POST',
			data: '{token: "' + token + '", pageIndex: "' + pageIndex + '"}',
			url: ajaxurl,
			contentType: 'application/json; charset=utf-8',
			dataType: 'json',
			success: function (data, status) {
				$('#jq-comments').hideAjaxIndicator();
				$('#jq-comments').html(data.d.Content);
			}
		});
	}

	$('#jq-comments a[href^=#comments-page]').live('click', function () {
		$('#jq-comments').showAjaxIndicator();
		var pageIndex = $(this).attr('href').replace('#comments-page', '');
		getComments(token, pageIndex);
	});

	if (location.hash.length > 0) {
		var pageIndex = parseInt(location.hash.replace('#comments-page', ''));
		if (!isNaN(pageIndex) && location.hash == '#comments-page' + pageIndex) {
			$('#jq-comments').showAjaxIndicator();
			getComments(token, pageIndex);
		}
	}

	$('form[name=frmAddComment]').ajaxForm({
		beforeSubmit: function (arr, form, options) {
			form.find('.komunikat').remove();
			form.find('span.error').remove();
		},
		success: function (data, status) {
			// Odswiezenie listy komentarzy
			if ($(data).find('Status').text() == 'true') {
				$('[name=comment]').val('');
				$('[name=nick]').val('');

				var pageIndex = parseInt(location.hash.replace('#comments-page', ''));
				if (isNaN(pageIndex) || location.hash != '#comments-page' + pageIndex) {
					pageIndex = 1;
				}

				$('#jq-comments').showAjaxIndicator();
				getComments(token, pageIndex);
			}
			// Pokazanie walidatorow
			else {
				$(data).find('Errors CommentError').each(function () {
					var key = $(this).find('Key').text();
					var value = $(this).find('Value').text();
					var control = $('[name=' + key + ']');

					// Pokazanie walidatora
					control.after('<span class="error" rel="Error.' + key + '">' + value + '</span>');

					// Skrocenie tekstu jesli rozmiar zostal przekroczony
					if (control.val().length > control.attr('maxlength')) {
						control.val(control.val().substring(0, control.attr('maxlength')));
					}
				});
			}

			// Pokazanie komunikatu
			var content = $(data).find('Content').text();
			if (content.length > 0) {
				$('#jq-add-comment').prepend($(data).find('Content').text());
				$('#jq-add-comment')
					.find('.komunikat')
					.animate({ opacity: 1.0 }, 3000)
					.fadeOut('slow');
			}
		}
	});
});


/* Dynamic Form */
$(document).ready(function () {
	var panels = $('.df-main');

	panels.hide().eq(0).show();

	panels.each(function (i) {
		if ($(this).find('span.error').length > 0) {
			panels.hide().eq(i).show();
			return false;
		}
	})

	panels.find('.df-button-prev').click(function () {
		panels.filter(':visible').hide().prev().show();
	});

	panels.find('.df-button-next').click(function () {
		panels.filter(':visible').hide().next().show();
	});
});

/* Chat */
var Chat =
{
	options: {},
	timeout: 10000,
	timer: null,
	lastupdate: 0,

	init: function (options) {
		this.options = options;
		this.updateTimer();
		this.getMessages();
	},

	updateTimer: function () {
		var now = new Date();
		var end = Date.parse(Chat.options.End) + now.getTimezoneOffset() * 60 * 1000;
		var timeleft = end - now.getTime();

		if (timeleft > 0) {
			$('.jq-chat-timer').html(Chat.formatTimer(timeleft));
			setTimeout(Chat.updateTimer, 1000);
		}
	},

	formatTimer: function (timeleft) {
		var seconds = parseInt(timeleft / 1000);
		var hours = parseInt(seconds / 3600);
		seconds = seconds - hours * 3600;
		var minutes = parseInt(seconds / 60);
		seconds = seconds - minutes * 60;

		return hours + ":" + Chat.zeroPad(minutes) + ":" + Chat.zeroPad(seconds);
	},

	addMessage: function (message) {
		if (message == undefined)
			message = $('.jq-chat-input').val();

		if (message.length > 0) {
			$('.jq-chat-input').val('');
			$('.jq-chat-input').attr('disabled', 'disabled');
			$('.jq-chat-button').attr('disabled', 'disabled');

			message = message.replace(/\\/g, '\\\\').replace(/"/g, '\\"');

			$.ajax({
				type: 'POST',
				data: '{pageId: "' + Chat.options.PageId + '", message: "' + message + '"}',
				url: Chat.options.AddMessage,
				contentType: 'application/json; charset=utf-8',
				dataType: 'json',
				success: function (data, status) {
					$('.jq-chat-button').removeAttr("disabled");
					$('.jq-chat-input').removeAttr("disabled");
					$('.jq-chat-input').get(0).focus();

					if (Chat.timer != null)
						clearTimeout(Chat.timer);

					Chat.timer = Chat.getMessages();
				}
			});
		}

		return false;
	},

	getMessages: function () {
		$.ajax({
			type: 'GET',
			url: Chat.options.GetMessages + '/' + Chat.options.PageId + '/' + Chat.lastupdate,
			contentType: 'text/xml; charset=utf-8',
			dataType: 'xml',
			success: function (data, status) {
				Chat.viewMessages(data);
				Chat.timer = setTimeout(Chat.getMessages, Chat.timeout);
			}
		});
	},

	viewMessages: function (xml) {
		Chat.lastupdate = parseInt($(xml).find('messages').attr('date'));

		var entries = $(xml).find('entry');
		var moderator = $(xml).find('messages').attr('moderator') == 'true';

		var wnd = $('.jq-chat-wnd').get(0);
		var scrollHeight = wnd.scrollHeight;

		for (var i = 0; i < entries.length; i++) {
			Chat.showEntry(wnd, entries[i], moderator);
		}

		if (wnd.scrollTop >= scrollHeight - wnd.offsetHeight) {
			wnd.scrollTop = wnd.scrollHeight;
		}
	},

	showEntry: function (wnd, entry, moderator) {
		Chat.lastupdate = parseInt($(entry).find('date').text());

		if ($(entry).find('priv').length > 0) {
			var command = $(entry).find('text').text();

			if ($(entry).find('priv').text() == Chat.options.Token) {
				if (command == 'kick' || command == 'ban') {
					Chat.reload();
					return;
				}

				// Wyswietlenie komunikatu
				$(entry).find('priv').text('system');
			}
			if ($(entry).find('priv').text() == 'moderator') {
				// Dodanie moderatora na liste uzytkownikow
				if (command == 'enter') {
					this.showModerator(entry, moderator);
					return;
				}
			}
			if ($(entry).find('priv').text() == 'highlight') {
				// Wyswietlenie komunikatu od moderatora
				this.showMessage(wnd, entry, moderator);
			}
			if ($(entry).find('priv').text() == 'system') {
				// Dodanie uzytkownika na liste uzytkownikow
				if (command == 'enter') {
					this.showUser(entry, moderator);
					return;
				}
				// Usuniecie moderatora lub uzytkownika z listy
				if (command == 'leave') {
					this.removeUser(entry);
					return;
				}

				// Wyswietlenie komunikatu od uzytkownika
				this.showMessage(wnd, entry, moderator);
			}
		}
		else {
			this.showMessage(wnd, entry, moderator);
		}
	},

	showMessage: function (wnd, entry, moderator) {
		var row = $('.jq-chat-tpl').clone();

		if ($(entry).find('priv').length > 0 && $(entry).find('priv').text() == 'system') {
			// Komunikaty systemowe
			var cssclass = 'chat-row-system';
			row.find('.jq-chat-nick').parent().hide();
		}
		else if ($(entry).find('priv').length > 0 && $(entry).find('priv').text() == 'highlight') {
			// Wiadomosci od moderatora
			var cssclass = 'chat-row-highlight';
		}
		else if (moderator == true && $(entry).find('publish').text() == 'false') {
			// Wiadomosci nieopublikowane w widoku moderatora
			var cssclass = 'chat-row-publish';
		}
		else {
			// Wiadomosci opublikowane
			var cssclass = '';
		}

		row.removeClass('jq-chat-tpl').addClass(cssclass);
		row.find('.jq-chat-date').html(Chat.formatTime(new Date(Chat.lastupdate)));
		row.find('.jq-chat-nick').html($(entry).find('nick').text());
		row.find('.jq-chat-text').html($(entry).find('text').text());

		if (moderator == true && $(entry).find('publish').text() == 'false') {
			Chat.addIcons(row, entry);
		}
		else {
			Chat.removeIcons(row);

			if ($(entry).find('priv').length == 0)
				Chat.changeStatus(wnd, entry);
		}

		$(wnd).append(row);
	},

	showModerator: function (entry, moderator) {
		var wnd = $('.jq-chat-moderators').get(0);
		var row = $('.jq-chat-user-tpl').clone();
		var cssclass = 'chat-row-moderator';

		row.removeClass('jq-chat-user-tpl')
		   .attr('rel', $(entry).find('userid').text())
		   .addClass(cssclass);
		row.find('.jq-chat-user')
		   .html($(entry).find('nick').text())

		if (moderator == true)
			Chat.addIcons(row, entry);
		else
			Chat.removeIcons(row);

		$(wnd).append(row);

		var rows = $(wnd).find('>div').get();

		rows.sort(function (a, b) {
			var keyA = $(a).find('.jq-chat-user').text().toUpperCase();
			var keyB = $(b).find('.jq-chat-user').text().toUpperCase();
			if (keyA < keyB) return -1;
			if (keyA > keyB) return 1;
			return 0;
		});

		$(rows).each(function (index, row) {
			$(wnd).append(row);
		});
	},

	showUser: function (entry, moderator) {
		var wnd = $('.jq-chat-users').get(0);
		var row = $('.jq-chat-user-tpl').clone();
		var cssclass = 'chat-row-even';

		row.removeClass('jq-chat-user-tpl')
		   .attr('rel', $(entry).find('userid').text())
		   .addClass(cssclass);
		row.find('.jq-chat-user')
		   .html($(entry).find('nick').text())

		if (moderator == true)
			Chat.addIcons(row, entry);
		else
			Chat.removeIcons(row);

		$(wnd).append(row);

		var rows = $(wnd).find('>div').get();

		rows.sort(function (a, b) {
			var keyA = $(a).find('.jq-chat-user').text().toUpperCase();
			var keyB = $(b).find('.jq-chat-user').text().toUpperCase();
			if (keyA < keyB) return -1;
			if (keyA > keyB) return 1;
			return 0;
		});

		$(rows).each(function (index, row) {
			$(wnd).append(row);
		});
	},

	removeUser: function (entry) {
		var id = $(entry).find('userid').text();

		var wnd = $('.jq-chat-users').get(0);
		$(wnd).find('[rel=' + id + ']').remove();

		var wnd = $('.jq-chat-moderators').get(0);
		$(wnd).find('[rel=' + id + ']').remove();
	},

	addIcons: function (row, entry) {
		row.find('.jq-chat-kick')
			.click(function () {
				Chat.addMessage('kick -a ' + $(entry).find('userid').text());

				var btn = this;
				$(btn).removeClass('jq-chat-kick').addClass('jq-chat-kick-off');
				setTimeout(function () {
					$(btn).removeClass('jq-chat-kick-off').addClass('jq-chat-kick');
				}, 5000);
			});

		row.find('.jq-chat-ban')
			.click(function () {
				$(this).removeClass('jq-chat-ban').addClass('jq-chat-ban-off').unbind('click');
				Chat.addMessage('ban -a ' + $(entry).find('userid').text());
			});

		row.find('.jq-chat-publish')
			.click(function () {
				$(this).removeClass('jq-chat-publish-off').addClass('jq-chat-publish').unbind('click');
				Chat.addMessage('publish -a ' + $(entry).find('msgid').text());
			})
			.each(function (i) {
				if ($(entry).find('publish').text() == 'false')
					$(this).removeClass('jq-chat-publish').addClass('jq-chat-publish-off').attr('rel', $(entry).find('msgid').text());
				else
					$(this).unbind('click');
			});
	},

	removeIcons: function (row) {
		row.find('.jq-chat-kick').remove();
		row.find('.jq-chat-ban').remove();
		row.find('.jq-chat-publish').remove();
	},

	changeStatus: function (wnd, entry) {
		$(wnd).find('.jq-chat-publish-off[rel=' + $(entry).find('msgid').text() + ']')
			  .removeClass('jq-chat-publish-off')
			  .addClass('jq-chat-publish')
			  .unbind('click');
	},

	logout: function () {
		$.ajax({
			type: 'POST',
			data: '{pageId: "' + Chat.options.PageId + '"}',
			url: Chat.options.Logout,
			contentType: 'application/json; charset=utf-8',
			dataType: 'json',
			success: function (data, status) {
				Chat.reload();
			}
		});
	},

	reload: function () {
		location.reload(true);
	},

	formatTime: function (date) {
		var now = new Date();
		date.setMinutes(date.getMinutes() + date.getTimezoneOffset());

		var sec = date.getSeconds();
		var min = date.getMinutes();
		var hour = date.getHours();

		return hour + ':' + Chat.zeroPad(min) + ':' + Chat.zeroPad(sec);
	},

	zeroPad: function (number) {
		return number > 9 ? number : '0' + number;
	}
}

var currentPosition = 0;

$(document).ready(function () {
	$('.InformationFieldBlue').append('<div class="r1"></div><div class="r2"></div><div class="r3"></div><div class="r4"></div>');
	$('.InformationFieldRed').append('<div class="r1"></div><div class="r2"></div><div class="r3"></div><div class="r4"></div>');

	Cufon.replace('.menu-container', {
		hover: true,
		hoverables: { li: true, div: true },
		ignore: { spacer: true }
	});

	var crimesPositions = $('.crimes-menu-container > ul > li').size();

	/// Pager instytucji
	$('.crimes-pager div.next img').click(function () {
		if (currentPosition < crimesPositions - 4) {
			$('.menu-crimes ul.list-lvl1').animate({ 'margin-left': '-=150px' }, 300);
			currentPosition++;
		}
	});

	$('.crimes-pager div.prev img').click(function () {
		if (currentPosition > 0) {
			$('.menu-crimes ul.list-lvl1').animate({ 'margin-left': '+=150px' }, 300);
			currentPosition--;
		}
	});

	if ($('#institutions').length) {
		$('.right-menu-container-3').css({ 'display': 'none' });
		$('.right-menu-container-2').css({ 'display': 'none' });
		$('.right-menu-container').css({ 'display': 'none' });
	}

	$('#page_container_5 div:first-child').css({ 'margin': '0' });

	$('.df-left-half-margin-148 span span.df-required').css({ 'right': '-10px', 'top': '0' });
	$('.df-element label').css({ 'float': 'left' });
	$('#page_container_5 .right-menu-container').css({ 'margin-left': '10px' });

	/// Usunięcie klasy pomocniczej z niektórych pozycji w tekscie
	$('li a span.dc').removeClass('dc');
	$('.title-2 span.dc').removeClass('dc');
	$('.info-title span.dc').removeClass('dc');

	/// Kliknięcię w menu modułu jednostek pomocy - zmiana zakładki
	$('div.tabbed-content .over-map-menu ul li a').click(function () {
		var currId = $(this).attr('href');
		var target = $(currId);

		if (target.size() > 0) {
			$('#tabs').children('div').children('div').css({ 'display': 'none' });
			$('#map').parent().parent().css('position', 'relative');
			$('#map').parent().parent().css('top', '0px');
			target.fadeIn('fast');
		}
		return false;
	});

	/// Kliknięcię w menu modułu jednostek pomocy - zmiana stanu przycisku
	$('.over-map-menu .list-lvl1 li a').click(function () {
		var n = $(this).lenght;
		$('.over-map-menu .list-lvl1 li a').removeClass("active-tab");
		$('.over-map-menu .list-lvl1 li span').removeClass("active-tab");
		$(this).addClass("active-tab");
		$(this).next().addClass("active-tab");

		Cufon(".over-map-menu a", { color: '#ffffff' });
		Cufon(".over-map-menu a.active-tab", { color: '#205070' });
	});

	/// Zwijane akapity strony opisowej
	$('.title-cont-page.jq-rollable').toggle(
	function () {
		$(this).next('div').stop().fadeIn('fast');
	},
	function () {
		$(this).next('div').stop().fadeOut('fast');
	});

	// Pager instytucji
	$('.map-institutions .pager .prev').live("click", function () {
		var curr = $('.map-institutions .tabs .tab:visible');
		if (curr.size() > 0 && curr.prev().size() > 0) {
			curr.hide().prev().show();
			CalcPage();
		}
		return false;
	});

	$('.map-institutions .pager .next').live("click", function () {
		var curr = $('.map-institutions .tabs .tab:visible');
		if (curr.size() > 0 && curr.next().size() > 0) {
			curr.hide().next().show();
			CalcPage();
		}
		return false;
	});

	$('.jq-institution-error a').live("click", function () {
		var rel = $(this).attr('rel');
		ShowSugestionForm(rel);
		return false;
	});

	$('.jq-institution-add a').live("click", function () {
		var rel = $(this).attr('rel');
		ShowAddInstitutionForm(rel);
		return false;
	});
});

function CalcPage() {
	$('.map-institutions .pager .current').html(
		$('.map-institutions .tabs .tab:visible').prevAll().size() + 1 + '/' +
		$('.map-institutions .tabs .tab').size()
		);
}

function HideOverlay() {
	$('.white-overlay').remove();
	$('.sugestion-form').remove();
}

function ShowAddInstitutionForm(ref) {
	$('body').append('<div class="white-overlay"></div>');
	$('.white-overlay').height($(document).height());
	$('.white-overlay').fadeIn();

	$('.sugestion-form').each(function () {
		$(this).remove();
	});

	var url = base.replace('Themes/pokrzywdzeni/', '') + 'API/pl/Custom.SupportInstitutions/GetAddForm/' + ref;

	$.ajax({
		type: 'GET',
		url: url,
		dataType: 'text',
		success: function (html) {
			$('body').append(html);
			$('.sugestion-form #institutionId').val(ref);
			$('.sugestion-form').fadeIn();
			EnableAdding();
		}
	});

	$('.white-overlay').click(function () {
		HideOverlay();
	});

	$('.close-button').click(function () {
		HideOverlay();
	});
}

function ShowSugestionForm(ref) {
	$('body').append('<div class="white-overlay"></div>');
	$('.white-overlay').height($(document).height());
	$('.white-overlay').fadeIn();

	$('.sugestion-form').each(function () {
		$(this).remove();
	});

	var url = base.replace('Themes/pokrzywdzeni/', '') + 'API/pl/Custom.SupportInstitutions/GetForm/' + ref;

	$.ajax({
		type: 'GET',
		url: url,
		dataType: 'text',
		success: function (html) {
			$('body').append(html);
			$('.sugestion-form #institutionId').val(ref);
			$('.sugestion-form').fadeIn();
			EnableSending();
		}
	});

	$('.white-overlay').click(function () {
		HideOverlay();
	});
}

function EnableAdding() {
	$('.sugestion-form #btnSendSugestion').click(function () {
		var form = $('.sugestion-form');
		// pobranie wartości z formy
		var email = form.find('#user_email').val();
		var name = form.find('#institution_name').val();
		var city = form.find('#institution_city').val();
		var address = form.find('#institution_address').val();
		var postal = form.find('#institution_code').val();
		var phone = form.find('#institution_phone').val();
		var description = form.find('#user_sugestion').val();
		var codePic = form.find('#codePic').val();
		var link = form.find('#urlHelper').val();
		var crime = form.find('#crimeId').val();

		// walidacja danych
		var requiredForms = ['#user_email', '#institution_name', '#institution_address', '#institution_city', '#codePic'];

		for (var i in requiredForms) {
			var input = form.find(requiredForms[i]);
			if (input.val().length == 0) {
				input.addClass("error");
				error = true;
			} else {
				input.removeClass("error");
			}
		}

		$('.sugestion-form .message').fadeIn();
		$.ajax({
			type: 'POST',
			data: JSON.stringify({ email: email, name: name, city: city, address: address, postal: postal, phone: phone, description: description, crimeId: crime, code: codePic }),
			url: link,
			contentType: 'application/json; charset=utf-8',
			dataType: 'json',
			success: function (data, status) {
				$('.sugestion-form .message').html(data.d);
				$('.sugestion-form .captha-frame').attr('src', $('.sugestion-form .captha-frame').attr('src'));
			},
			error: function () {
				alert("Error sending data")
			}
		});
	});
}

function EnableSending() {
	$('.sugestion-form #btnSendSugestion').click(function () {
		var form = $('.sugestion-form');
		var email1 = form.find('#user_email').val();
		var sugestion = form.find('#user_sugestion').val();
		var codePic = form.find('#codePic').val();
		var link = form.find('#urlHelper').val();
		var institution = form.find('#institutionId').val();

		var requiredForms = ['#user_email', '#user_sugestion', '#codePic'];

		for (var i in requiredForms) {
			var input = form.find(requiredForms[i]);
			if (input.val().length == 0) {
				input.addClass("error");
				error = true;
			} else {
				input.removeClass("error");
			}
		}

		$('.sugestion-form .message').fadeIn();
		$.ajax({
			type: 'POST',
			data: JSON.stringify({ institution: institution, email: email1, content: sugestion, code: codePic }),
			url: link,
			contentType: 'application/json; charset=utf-8',
			dataType: 'json',
			success: function (data, status) {
				$('.sugestion-form .message').html(data.d);
				$('.sugestion-form .captha-frame').attr('src', $('.sugestion-form .captha-frame').attr('src'));
			},
			error: function () {
				alert("Error sending data")
			}
		});
	});
}

$(document).ready(function () {
	$('.dc').mouseover(function (e) {
		getEntryData($(this), e);
	});
});

function setPopupPosition(dictEntry, popup, e) {
	var bottom = true;
	var right = true;

	var pos = dictEntry.offset();
	popup.css({ 'left': pos.left, 'top': pos.top }).show();

	// obliczanie pozycji popup
	var clientWidth = (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth);
	var clientHeight = (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight);
	var scrollLeft = (window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft);
	var scrollTop = (window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop);

	var positionX = pos.left;
	var popupW = popup.width();
	//czy wyskakuje za ekran
	if (clientWidth < e.pageX + popupW - scrollLeft) {
		var positionX = positionX - popupW - 1;
		right = false;
	}

	var positionY = pos.top - 12;
	var popupH = popup.height();
	if (clientHeight < e.pageY + popupH - scrollTop) {
		var positionY = positionY + 12 - popupH - 20;
		bottom = false;
	}

	// ponowne spozycjonowanie popup
	popup.css({ 'left': positionX, 'top': positionY });

	if (bottom && right) popup.addClass('posDefault');
	if (bottom && !right) popup.addClass('posBottomLeft');
	if (!bottom && !right) popup.addClass('posTopLeft');
	if (!bottom && right) popup.addClass('posTopRight');
}

function removePopup() {
	$('.dict-popup').each(function () {
		$(this).remove();
	});
}



function getEntryData(dictEntry, e) {
	entryId = dictEntry.attr('rel');

	// usuniecie poprzednich widoków chmurki (powodowało błędy wyświetlania przy róznych typach chmurek)
	$('.dict-popup').each(function () {
		$(this).remove();
	});

	var url = base.replace('Themes/pokrzywdzeni/', '') + 'API/pl/Custom.PopupDictionary/GetEntryData/' + entryId;

	$.ajax({
		type: 'GET',
		url: url,
		dataType: 'text',
		success: function (html) {
			$('body').append(
			'<div class=\"dict-popup\">' +
			'</div>');
			$('.dict-popup').html(html);
			setPopupPosition(dictEntry, $('.dict-popup'), e);
		}
	});
}
