function _(messageId) {
	return typeof(translate[messageId]) === 'undefined' ? messageId : translate[messageId];
}

var Core = {

	controller: '',
	action: '',
	webHost: '',
	webView: '',
	webImg: '',
	dateTime: '',
	lang: '',

	init : function() {
		$('a.fancybox').fancybox({
			'titlePosition'	: 'inside'
		});
		
		// dla newslettera
		$('a[href="#dlgNewsletter"]').fancybox({
			'titleShow'	: false
		});

		// CK
		$('.ck .tooltip').wTooltip();
		
		//CK - cellpadding na padding
		$('.ck td, .ck th').each( function() {
			if ($(this).parent().parent().parent('table').attr('cellpadding')) {
				var padding = $(this).parent().parent().parent('table').attr('cellpadding');
				padding += 'px';
				$(this).css( 'padding', padding );
			}
		})
		
		// logo pp
		$('#footer .createdby img').hover(
			function(){
				$(this).attr('src', $(this).attr('src').replace('.gif', '_over.gif') );
			},
			function() {
				$(this).attr('src', $(this).attr('src').replace('_over.gif', '.gif') );
			}
		);
		
		
		Core.searchbox();
		Core.dialog('dlgRecommend', '#btnOpenRecommend');
		Core.newsletter('dlgNewsletter', '#btnOpenNewsletter');
		Core.tabs();
		Core.banners();
		Core.hoverImage();
		Core.print();
		//Core.menutextbox($('#menu a'));
		Cufon.replace('#menu a', { fontFamily: 'Liberation Sans', 'hover': true });
		//Core.textbox($('span.textbox'));
		Cufon.replace('.textbox', { fontFamily: 'Liberation Sans' });
		Core.preventSubmit($('form.preventSubmit'));
	},

	/**
	 * Blokoda ponownego wysłania formularz.
	 */
	preventSubmit: function(element) {
		element.submit(function(){

			if ($(this).data('submitted') === true) {
				alert('Formularz został już wysłany. Proszę czekać...');

				return false;
			}
			else
				$(this).data('submitted', true);

			return true;
		});
	},

	/**
	 * Osadzanie nagłówków Flash.
	 */
	textbox: function(element) {
		element.each(function(k, v){
			var id = 'textbox' + k;
			var width = element.width();
			$(v).attr('id', id);
			swfobject.embedSWF(Core.webView + 'flash/textbox.swf', id, width, 25, '9.0.0', 'expressInstall.swf',
				{ tekst: encodeURIComponent($(v).text()) }, { menu: false, scale: 'noscale', salign: 'lt', wmode: 'transparent' }, { }
			);
		});
		
		$('.textbox').show();
	},
	
	/**
	 * Osadzanie elementów menu Flash.
	 */
	menutextbox: function(element) {
		element.each(function(k, v){
			var id = 'menutextbox' + k;
			var width = $(v).width() + 30;
			$(v).attr('id', id);

			var text = trim($(v).text());
			
			swfobject.embedSWF(Core.webView + 'flash/menu_position.swf', id, width, 18, '9.0.0', 'expressInstall.swf',
				{ tekst: encodeURIComponent(text), link : encodeURIComponent(Core.webHost+$(v).attr('href')) }, { menu: false, scale: 'noscale', salign: 'lt', wmode: 'transparent' }, { }
			);
			
			$('#menu a').show();
		});
	},

	/**
	 * Wyświetlenie okna z poglądem wydruku.
	 */
	print: function() {
		$('.btnPrint').click(function(){
			xferWindow = Core.openWindow(Core.webHost + 'print,index.html', 640, 280);
			xferWindow.opener = self;

			return false;
		});
	},

	/**
	 * Zmiana obrazka po wskazaniu kursorem.
	 */
	hoverImage: function() {
		$('img.hoverImage, input.hoverImage').mouseenter(function(){
			if ($(this).hasClass('active') === false) {
				$(this).attr('src', $(this).attr('src').replace('.gif', '_on.gif'));
				$(this).attr('src', $(this).attr('src').replace('.jpg', '_on.jpg'));
				$(this).attr('src', $(this).attr('src').replace('.png', '_on.png'));
			}
		}).mouseleave(function(){
			if ($(this).hasClass('active') === false) {
				$(this).attr('src', $(this).attr('src').replace('_on.gif', '.gif'));
				$(this).attr('src', $(this).attr('src').replace('_on.jpg', '.jpg'));
				$(this).attr('src', $(this).attr('src').replace('_on.png', '.png'));
			}
		});
	},

	/**
	 * Opis w polach tekstowych.
	 */
	inputDescription: function(form, element, description) {
		if (element.val() === '') {
			element.val(description);
		}

		element.focus(function(){
			if ($(this).val() === description) {
				$(this).val('');
			}
		}).blur(function(){
			if ($(this).val() === '') {
				$(this).val(description);
			}
		});

		form.submit(function(){
			if (element.val() === description) {
				element.val('');
			}
		});
	},

	banners: function() {

		$('.banner.swf').each(function(k, v){
			var id = 'banner_swf_' + k;
			$(v).attr('id', id);
			
			var swf = $(this).find('img').attr('src');
			//var swf = $(this).find('img').attr('src').replace(/\\/g,'/').replace( /.*\//, '' );
			

			swfobject.embedSWF(swf, id, 296, 44, '9.0.0', 'expressInstall.swf',
				{}, { menu: false, scale: 'noscale', salign: 'lt', wmode: 'transpanret' }, { }
			);
		});
		
		$('div.advImageContent div.advImagePlaceholder').each(function(){

			swfobject.embedSWF(
				$(this).children('.path').text(), 'b' +
				$(this).attr('id').substr(1),
				$(this).children('.width').text(),
				$(this).children('.height').text(), '9.0.0', '', { }, { wmode: 'opaque' }, { }
			);

		});

		if ($.cookie('advTopLayer') !== '1') {

			var advTopLayer = $('#advTopLayer'),
				advImagePlaceholder = advTopLayer.find('.advImagePlaceholder');

			if (advTopLayer.length > 0 && advImagePlaceholder.length > 0) {

				$.fancybox({
					autoScale: false,
					autoDimensions: true,
					enableEscapeButton: false,
					hideOnOverlayClick: false,
					href: advSwf.children('.path').text(),
					margin: 0,
					overlayOpacity: 0,
					padding: 0,
					scrolling: 'no',
					swf: { wmode: 'opaque' },
					titleShow: false,
					type: 'swf',
					transitionIn: 'none',
					transitionOut: 'none',

					onStart: function() {
						$.cookie('advTopLayer', 1);
					}
				});

			}
			else if (advTopLayer.length > 0) {

				$.fancybox({
					autoScale: false,
					autoDimensions: true,
					enableEscapeButton: false,
					hideOnOverlayClick: false,
					href: '#advTopLayer',
					margin: 0,
					overlayOpacity: 0,
					padding: 0,
					scrolling: 'no',
					titleShow: false,
					transitionIn: 'none',
					transitionOut: 'none',

					onStart: function() {
						$.cookie('advTopLayer', 1);
					}
				});
			}
		}

	},

	dialog: function(dialogName, buttonOpenName) {

		var dialog = $('#' + dialogName),
			form = dialog.find('form'),
			messages = dialog.find('.messageList'),
			inputs = dialog.find('input.text, textarea');

		dialog.submit(function(){

			// Komunikat lub animacja ładowania.
			messages.html('<p>' + _('Proszę czekać...') + '</p>');
			messages.show();

			// Przeskaluj okno.
			$.fancybox.resize();

			// Wyślij żądanie.
			$.post(form.attr('action'), form.serialize(), function(data){

				if ('OK' === data.status) {
					inputs.not('input[type="checkbox"]').val('');
					inputs.removeAttr('checked');
				}
				else if ('ERROR' === data.status) {
					//$.each(data.fields, function(k, v){
					//	dialog.find('[id*=' + k + ']').addClass('error');
					//});
				}

				var html = '';

				for (var i in data.messages) {
					html += '<p class="' + data.status + '">' + data.messages[i] + '</p>';
				}

				messages.html(html);

				// Przeskaluj okno.
				$.fancybox.resize();

			}, 'json');

			return false;
		});

		inputs.blur(function(){
			$(this).removeClass('error');
		});

		$(buttonOpenName).fancybox({
			href: '#' + dialogName,
			titleShow: false,
			margin: 0,
			padding: 0,

			onStart: function() {

				// Usuń poprzednio wpisane wartości.
				inputs.not('input[type="checkbox"]').val('');
				inputs.removeAttr('checked');

				// Usuń poprzednie komunikaty.
				messages.html('');
				messages.hide();
			}
		});

		form.find('.btnClose').click(function(){
			$.fancybox.close();

			return false;
		});
	},

	newsletter: function(dialogName, buttonOpenName) {

		Core.dialog(dialogName, buttonOpenName);

		var dialog = $('#' + dialogName),
			form = dialog.find('form'),
			messages = dialog.find('.messageList'),
			inputs = dialog.find('input.text, textarea');

		$('#btnSignout').click(function(){

			// Komunikat lub animacja ładowania.
			messages.html('<p>Proszę czekać...</p>');
			messages.show();

			// Przeskaluj okno.
			$.fancybox.resize();

			// Wyślij żądanie.
			$.post(Core.webHost + 'newsletters_ajax,signout.html', form.serialize(), function(data){

				if ('OK' === data.status) {
					inputs.not('input[type="checkbox"]').val('');
					inputs.removeAttr('checked');
				}

				var html = '';

				for (var i in data.messages) {
					html += '<p class="' + data.status + '">' + data.messages[i] + '</p>';
				}

				messages.html(html);

				// Przeskaluj okno.
				$.fancybox.resize();

			}, 'json');

			return false;
		});

		$(buttonOpenName).fancybox({
			href: '#' + dialogName,
			titleShow: false,
			margin: 0,
			padding: 0,

			onStart: function() {

				// Usuń poprzednio wpisane wartości.
				inputs.not('input[type="checkbox"]').val('');
				inputs.removeAttr('checked');

				// Usuń poprzednie komunikaty.
				messages.html('');
				messages.hide();
			}
		});

		form.find('.btnClose').click(function(){
			$.fancybox.close();

			return false;
		});
	},

	/**
	 * Dynamiczne zakładki. Zapamiętywanie aktywnej zakładki w ciastkach.
	 */
	tabs: function () {
		$('.buttons.ajax a').click(function() {

			// Pobierz zapamiętane zakładki.
			var activeTabs = $.cookie('ACTIVE_TABS');

			if (activeTabs)
				activeTabs = activeTabs.split(',');
			else
				activeTabs = new Array();

			var id = 0;

			for (var i = 0; i < activeTabs.length; ++i) {
				if ($(this).parent().children('a.active').attr('href') === activeTabs[i]) {
					id = i;
					break;
				}
			}

			if (typeof id != 'undefined')
				activeTabs.splice(id, 1);

			// Zmień zakładki.
			$(this).parent().next('.tabs').children('div.tab').hide();
			$($(this).attr('href')).show();

			$(this).parent().children('a').removeClass('active');
			$(this).addClass('active');

			// Zapamiętaj aktywane zakładki.
			activeTabs.push($(this).attr('href'));

			$.cookie('ACTIVE_TABS', activeTabs.join(','));

			return false;
		});

		// Przywróć zakładki.
		var activeTabs = $.cookie('ACTIVE_TABS');

		if (activeTabs)
			activeTabs = activeTabs.split(',');
		else
			activeTabs = new Array();

		for (var i in activeTabs) {

			var button = $('.buttons.ajax a[href="' + activeTabs[i] + '"]');

			button.parent().next('.tabs').children('div.tab').hide();
			$(button.attr('href')).show();

			button.parent().children('a').removeClass('active');
			button.addClass('active');
		}
	},

	openWindow : function( href, width, height ) {
		return window.open(href, 'window', 'width=' + (width | 650) + ', height=' + (height | 650) +
			', menubar=no, toolbar=no, location=no, scrollbars=yes, resizable=no, status=no');
	},
	
	searchbox : function() {
		
		var default_val = $('#search_box .text').val();
		$('#search_box .text').click( function() {
			if ($(this).val() == default_val) {
				$(this).val('');
			}
		})
		
	}
}

$(document).ready(function() {

	// Zamień pierwszą literę oraz każdą przed "_" na wielkie.
	var controller = Core.controller.replace(/(^|_)([a-z])/g, function(m, p1, p2) {
		return p1 + p2.toUpperCase();
	});

	Core.init();

	if (window[controller] != undefined) {

		if (typeof window[controller]['init'] == 'function') {
			window[controller]['init']();
		}

		if (typeof window[controller][Core.action] == 'function') {
			window[controller][Core.action]();
		}
	}
});

function trim (str, charlist) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: mdsjack (http://www.mdsjack.bo.it)
    // +   improved by: Alexander Ermolaev (http://snippets.dzone.com/user/AlexanderErmolaev)
    // +      input by: Erkekjetter
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: DxGx
    // +   improved by: Steven Levithan (http://blog.stevenlevithan.com)
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // *     example 1: trim('    Kevin van Zonneveld    ');
    // *     returns 1: 'Kevin van Zonneveld'
    // *     example 2: trim('Hello World', 'Hdle');
    // *     returns 2: 'o Wor'
    // *     example 3: trim(16, 1);
    // *     returns 3: 6
    var whitespace, l = 0,
        i = 0;
    str += '';

    if (!charlist) {
        // default list
        whitespace = " \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000";
    } else {
        // preg_quote custom list
        charlist += '';
        whitespace = charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1');
    }

    l = str.length;
    for (i = 0; i < l; i++) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(i);
            break;
        }
    }

    l = str.length;
    for (i = l - 1; i >= 0; i--) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(0, i + 1);
            break;
        }
    }

    return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}

