/**
 * Zestaw parametrów i metod konfiguracyjnych
 */
var _config = {
	/* adres bazowy strony - wartość ustawiana w init */
	base_url :null,

	/* kontroler i akcja (wypełniane w head) */
	controller :null,
	action :null,

	user_logged :null,
	haslo :null,

	/* operacje wykonywane po załadowaniu dokumentu */
	init_common : function(){
		// bazowy URL strony
		this.base_url = self.location.protocol + '//' + self.location.host + '/';

		// konfiguracja AJAX-a
		$.ajaxSetup({
			cache :false
		});

		this.init();
	},

	/**
	 * Ta metoda jest wywoływana zawsze po init_common. Metodę nadpisujemy w
	 * rozszerzeniach poprzez: jQuery.extend( _config, { init: { <tutaj kod> } } );
	 */
	init : function(){
	}
};

/**
 * Główny zestaw metod
 */
var _main = {
	_this :null,

	/* operacje wykonywane po załadowaniu dokumentu */
	init_common : function(){
		/* nadanie linkom zewnetrznym atrybutu target="_blank" */
		this.external_links();

		this.init();

		/* inicjalizacja kodu dla kontrolera i akcji */
		var controller = _config.controller.charAt(0).toUpperCase() +
						 _config.controller.substr(1).replace(/-[a-z]/ig, function(s){ return s.substr(1, 1).toUpperCase(); });
		if (typeof (window[controller]) == "object") {
			this._this = window[controller];
			var action = _config.action.replace(/-[a-z]/ig, function(s){ return s.substr(1, 1).toUpperCase(); }) + "Action";
			if (typeof (window[controller]["init"]) == "function") { window[controller]["init"](); }
			if (typeof (window[controller][action]) == "function") { window[controller][action](); }
		}
	},

	/**
	 * Ta metoda jest wywoływana zawsze po init_common (ale przed wywołaniem
	 * akcji kontrolera). Metodę nadpisujemy w rozszerzeniach poprzez:
	 * jQuery.extend( _main, { init: { <tutaj kod> } } );
	 */
	init : function(){
		//$("img[src$=png], .png").pngfix();
		// inicjalizacja podpowiedzi dla formularzy
		/*$('#search_phrase').inputHint();*/
		$('#search input.submit').bind('click',function(){ document.getElementById('search').submit(); });

//		swfobject.embedSWF(_config.base_url+"template/flash/baner2_" + _config.lang + ".swf", "mainswf", "950", "310", "9.0.0", "expressInstall.swf",
//				/* FLASHVARS	*/	{ 'zmienna1' : 'test', 'zmienna2' : 'test2', 'autoplay':0/*_config.sesja*/ },
//				/* PARAMS 		*/	{ swliveconnect: true, wmode: "transparent", scale: "noScale" },
//				/* ATTRIBUTES	*/	{ id: "mainswf", name: "mainswf" }
//		);

		var slideButtons = $('#jCarousel .buttons .numbers a').map(function(i){
			return '#jCarousel .buttons .numbers a:eq(' + i + ')';
		}).get();

//		$('#jCarousel .buttons .numbers a').click(function(){
//			$('#jCarousel .buttons .numbers a').removeClass('active');
//			$(this).addClass('active');
//		});

		
		
		// jeśli jest tylko jeden element
		var c_numbers_count = 0;
		$('#jCarousel').find('.numbers a').each(function() {
			c_numbers_count++;
		})
		if (c_numbers_count < 2) {
		
			$('#jCarousel').find('.numbers').hide();
			$('#jCarousel').find('.prev, .next').hide();
			
		} else {
			
			$('#jCarousel').jCarouselLite({
				start: 0,
				visible: 1,
				circular: true,
				mouseWheel: true,
				auto: 7000,
				speed: 600,
				btnPrev: '#jCarousel .buttons .prev',
				btnNext: '#jCarousel .buttons .next',
				btnGo: slideButtons,
				beforeStart: function(a) {
	//				console.log(a);
	//				console.log(a.find('.full').attr('class'));
	//
	//				$('#jCarousel .buttons .numbers a').removeClass('active');
	//				$('#jCarousel .buttons .numbers a:eq(' + a.find('.full').attr('rel') + ')').addClass('active');
				}
			});
			
		}
		
		$('#jCarousel').find('.short .inner').each(function() {
			if ($(this).html() == '') {
				$(this).parent().css('background', 'transparent');
			}
		})

		$('.button').bind('mouseover',function(){ $(this).addClass('hover'); }).bind('mouseout',function(){ $(this).removeClass('hover'); });
		$('.button_wide').bind('mouseover',function(){ $(this).addClass('hover'); }).bind('mouseout',function(){ $(this).removeClass('hover'); });
		$('.button_superwide').bind('mouseover',function(){ $(this).addClass('hover'); }).bind('mouseout',function(){ $(this).removeClass('hover'); });

		$('.button_gbg').bind('mouseover',function(){ $(this).addClass('hover'); }).bind('mouseout',function(){ $(this).removeClass('hover'); });
		$('.button_wide_gbg').bind('mouseover',function(){ $(this).addClass('hover'); }).bind('mouseout',function(){ $(this).removeClass('hover'); });
		$('.button_superwide_gbg').bind('mouseover',function(){ $(this).addClass('hover'); }).bind('mouseout',function(){ $(this).removeClass('hover'); });

		$('#polec_znajomemu_a').bind('click',function(){
			komunikaty.pokaz('polec-znajomemu', '', '');
			$('#polecenie .button').bind('mouseover',function(){ $(this).addClass('hover'); }).bind('mouseout',function(){ $(this).removeClass('hover'); });
			$('#polecenie .button a').bind('click', _main.polec_znajomemu)
			return false;
		});

		$('#newsletter_a').bind('click',function(){
		//alert('newsletter_a');
			komunikaty.pokaz('newsletter', '', '');
			$('#polecenie .button').bind('mouseover',function(){ $(this).addClass('hover'); }).bind('mouseout',function(){ $(this).removeClass('hover'); });
			$('#newsletter_dodaj').bind('click', function(){ _config.newsletter_action = 'add'; _main.newsletter(); return false; });
			//$('#newsletter_usun').bind('click', function(){ _config.newsletter_action = 'dell'; _main.newsletter(); return false; });
			$('#polecenie').bind('submit', function(e) { e.preventDefault(); });
			return false;
		});

		$('#positive').bind('mouseover',function(){
            //$(this).attr('src', '');
            this.src = 'template/img/positive_on.jpg';
		});
		$('#positive').bind('mouseout',function(){
            this.src = 'template/img/positive.jpg';
		});

/*		$('#main_menu a').bind('click',function(e){
			$('#main_menu li').each(function(){this.className = '';});
			$(this).parents('li')[0].className = 'selected';
			return false;
		});*/

		$('#top h1').bind('click',function(e){
			location.href = _config.base_url;
		});

		$('#contact_form').submit(function(){
			return tryToContact();
		});

		$('#contactSend').click(function(){
			$('#contact_form').submit();
			return false;
		});

		if (typeof(contactSent) !== 'undefined') {
			_gaq.push(['_trackEvent', 'Kontakt', 'Formularz', 'Poprawnie']);
		}
	},

	// przewija stronę na samą górę (bez użycia "#")
	scrollToTop : function(){
		$(document).scrollTop(0);
	},

	/* nadanie linkom zewnetrznym atrybutu target="_blank" */
	external_links : function(){
		$("a[rel='external']").each( function(i){
			this.target = "_blank";
		});
	},

	polec_znajomemu : function(){
		var dane = {
			 'rodzaj_akcji'		: 'polec-znajomemu'
			,'email_odbiorcy'	: document.getElementById('email_odbiorcy').value
			,'imie_nazwisko'	: document.getElementById('imie_nazwisko').value
			,'email_nadawcy'	: document.getElementById('email_nadawcy').value
			,'tresc'			: document.getElementById('tresc').value
		}
		$.post(_config.base_url + "polec.html", dane, function(data){
			$('#polecenie span').not('.button').html('').css('display','none');
			if(!data.ok){
				for(x in data.bledy){
					//alert( x + ': ' + data.bledy[x] );
					$('#'+x+'_error').css('display','block').text(data.bledy[x]);
				}
			}else{
				document.getElementById('polec-naglowek').innerHTML = 'Wiadomość wysłana pomyślnie';
				document.getElementById('polecenie').innerHTML = '<p style="padding-left:15px;">Dziękujemy za polecenie naszej strony</p>';
			}
		}, 'json');
		return false;
	},

	newsletter: function(){
		if(_main.email(document.getElementById('newsletter_email').value)){
			//http://www.mailpro.pl/mailpro/ajaxact.php?mail=lp@positive-power.pl&grup=1&ip=1.1.1.1&sesja=08ddbe61f374676d26d505755ea9a7a7&userid=53&action=add
			var dane = {
				 'mail'		: document.getElementById('newsletter_email').value
				,'grupa'	: '1'
				,'name'		: 'Unilogo'
				,'subject'	: 'Newsletter www.unilogo.com.pl'
				,'receiverMail'	: document.getElementById('newsletter_email').value
/*				,'action'	: _config.newsletter_action*/
			};

			//$.post("newsletterPost.php", dane );

			$.post("newsletterPost.php", dane ,
			  function(dane){
			    //alert(dane.komunikat); // John
			    $('#newsletter_komunikat').css('display','none').text(/*Translator.newsletter['bledny_email']*/ dane.komunikat).show('slow').animate({opacity:1.0},2000).hide('slow');
			  }, "json");


		}else{
			//var komunikat = Translator.newsletter[dane.komunikat];
			$('#newsletter_komunikat').css('display','none').text(Translator.newsletter['bledny_email']).show('slow').animate({opacity:1.0},2000).hide('slow');
		}

		return false;
	},

	// email validation
	email: function(value, element) {
		// contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
		return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value);
	}

};

$(document).ready( function(){
	_config.init_common();
	_main.init_common();
});

try { document.execCommand('BackgroundImageCache', false, true); } catch (e) {}

/**
 * Komunikaty
 */

var komunikaty = {
	/* inicjalizacja komunikatu wyświetlonego przez skrypt po stronie serwera */
	init : function(){
		this.ustaw_przyciski();
	},

	/* wyświetla komunikat danego rodzaju */
	pokaz : function(rodzaj, tytul, tresc, link_ok, link_anuluj){
		//alert(rodzaj+"\n"+tytul+"\n"+tresc);
		if (document.komunikaty_tpl[rodzaj]) {
			if (typeof (link_ok) == "undefined") {
				var link_ok = location.href;
			}
			if (typeof (link_anuluj) == "undefined") {
				var link_anuluj = location.href;
			}

			/* pobranie szablonu komunikatu */
			var komunikat = document.komunikaty_tpl[rodzaj];
			/* ustawienie treści */
			komunikat = komunikat.replace('{TYTUL}', tytul).replace('{TRESC}',
					tresc).replace('{LINK_OK}', link_ok).replace(
					'{LINK_ANULUJ}', link_anuluj);

			/* usunięcie poprzedniego komunikatu, jeśli istnieje */
			if ($('#warstwa')[0]) {
				komunikaty.usun();
			}

			/* wyświetlenie komunikatu */
			$("body").prepend('<div id="over" class="overlay"></div>');
			$("#lo").prepend(komunikat);
			$("#warstwa").pngfix();

			$('#over').css('height', $(document).height());
			var szerokosc = ( $(window).width() - $('#warstwa').width() ) / 2;
			//alert($(window).width());
			$('#warstwa').css({'left':szerokosc});

			/* oprogramowanie przycisków */
			komunikaty.ustaw_przyciski();

			return true;
		}
		return false;
	},

	/* zamyka komunikat */
	usun : function(){
		if (o = document.getElementById('warstwa')) $(o).remove();
		if (o = document.getElementById('warstwa_')) $(o).remove();
		if (o = document.getElementById('over')) $(o).remove();
	},

	/* domyślne ustawienie przycisków */
	ustaw_przyciski : function(){
		if (!$(".kom_anuluj")[0]) {
			$('.kom_close,.kom_ok').each( function(i){
				this.onclick = function(e){
					if(typeof this.href != undefined && this.href != location.href){
						//alert(location.href+"\n"+this.href);
						location.href = this.href;
					}
					komunikaty.usun();
					return false;
				};
			});
		} else {
			$('.kom_anuluj').each( function(i){
				this.onclick = function(){
					komunikaty.usun();
					return false;
				};
			});
		}
	}
};

