/**
 * 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,
	/*lang :null,*/
	ip :null,
	sesja :null,

	/* operacje wykonywane po załadowaniu dokumentu */
	init_common : function(){
		// bazowy URL strony
		this.base_url = location.href.match(/^(https?:\/\/[^\/]*\/)/)[1];
	
		// 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(){
		
		$('#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)
			$('#polecenie .general_recommend_error').css('display','none');
			return false;
		});
		
		$('#nav').droppy({speed:100});
		
		//$('#nav').droppy({speed:100});
		
		// ogolne submity
		$('#submit').bind('click',function(){
			$(this).parents('form:first').submit();
			return false;
		});
		
		// przycisk wyszukiwarki
		$('#search_button').bind('click',function(e){
			e.preventDefault();
			document.getElementById('searchForm').submit();
			return false;
		});

		// klikniecie entera w polu wyszukiwarki
		var search_phrase = $('#search_phrase');
		
		search_phrase.bind('keypress',function(e){
			if($.browser.msie && (window.event && window.event.keyCode == 13)){
				document.getElementById('searchForm').submit();
			}
		});

		// klikniecie myszka pola wyszukiwarki
		search_phrase.bind('click',function(e){
			if ($("#search_phrase").val() == "szukana fraza")     search_phrase.val("");
			return false;
		});

		//prawe górne menu...
		$('#top_menu_right a').hover(function(){
			$(this).find('img').attr('src',
				$(this).find('img').attr('src').replace('.gif', '_on.gif'));
		}, function() {
			$(this).find('img').attr('src',
				$(this).find('img').attr('src').replace('_on.gif', '.gif'));
		})

		$('.promoBox div.box').each(function() {
			var href = $(this).find('a').attr('href');
			$(this).find('*').each(function() {
				$(this).css('cursor', 'pointer');
				$(this).click(function() {
					window.location = href;
				})
			})
		})
		
		$('#bookmarksite').bind('click',function(){
			_main.bookmarksite();
		});
		$('#artykul div.pag a.inactive, a.empty').bind('click',function(){ return false; });
		
		if($.browser.msie){
			$('#artykul .galeria a').hover(
					function(){ $(this).children('img.lupa').css({'height':'144px','width':'144px','display':'block'}); },
					function(){ $(this).children('img.lupa').css({'height':'0px','width':'144px','display':'none'}); }
			);
		}

		// Podpowiedzi do wyszukiwarki.
		$.ajaxSetup({
			cache: false
		});
		
		search_phrase.autocomplete('page,autocomplete.html', {
			matchContains: true,
			selectFirst: false,
			max: 100
		});

		// Rejestracja i logowanie

		$('.rejestracja_box.bottom .button.submit').click(function(e) {
			e.preventDefault();
			$('#form_rejestracja').submit();
		})

		$('#loginAction .button.submit').click(function(e) {
			e.preventDefault();
			$('#loginAction form').submit();
		})

		$('#form_rejestracja').each(function() {

		if (wysylka_on != 1) {
			$('.rejestracja_box.dane_do_wysylki').addClass('disabled');

			$('.rejestracja_box.dane_do_wysylki input').each(function() {
				if (!$(this).hasClass('checkbox'))
					$(this).attr('disabled', 'disabled');

			 })
			}

			if (faktura_on != 1) {
			$('.rejestracja_box.dane_do_faktury').addClass('disabled');

			$('.rejestracja_box.dane_do_faktury input').each(function() {
				if (!$(this).hasClass('checkbox'))
					$(this).attr('disabled', 'disabled');

			 })
			}

			 $('.rejestracja_box.dane_do_wysylki input.checkbox'
				).click(function() {
				var cont = $('.rejestracja_box.dane_do_wysylki');
				if (cont.hasClass('disabled')) {
					cont.removeClass('disabled');
					cont.find('input').removeAttr('disabled');
				} else {
					cont.addClass('disabled');
					cont.find('input').each(function() {
						if (!$(this).hasClass('checkbox'))
							$(this).attr('disabled', 'disabled');
					})
				}
			 })

			 $('.rejestracja_box.dane_do_faktury input.checkbox'
				).click(function() {
				var cont = $('.rejestracja_box.dane_do_faktury');
				if (cont.hasClass('disabled')) {
					cont.removeClass('disabled');
					cont.find('input').removeAttr('disabled');
				} else {
					cont.addClass('disabled');
					cont.find('input').each(function() {
						if (!$(this).hasClass('checkbox'))
							$(this).attr('disabled', 'disabled');
					})
				}
			 })
		 })
	},

	// 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";
		});
		$(".absmiddle").each( function(i){
			this.align = "absmiddle";
		});
	},
	
	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
		}
		//alert(_config.base_url);
		$.post(_config.base_url + "page,polec.html", dane, function(data){
			//$('#polecenie span').not('.button').html('').css('display','none');
			if(!data.ok){
			//alert('data not ok');
				for(x in data.bledy){
					//alert( x + ': ' + data.bledy[x] );
					//$('#'+x+'_error').css('display','block').text(data.bledy[x]);
					$('#polecenie #general_recommend_error').html(''+ data.bledy[x]).css('display','block');
					$('#'+x).css('border','1px #004178 solid').text(data.bledy[x]);
				}
			}else{
			     //alert('data ok');
				document.getElementById('polec-naglowek').innerHTML = 'Wiadomość wysłana pomyślnie';
				document.getElementById('polecenie').innerHTML = '<p style="text-align:left;padding-left:12px;">Dziękujemy za polecenie naszej strony</p>';
				
			}
		}, 'json');
		return false;
	},
	
	bookmarksite : function(){
		// <a id="bookmarksite" href="BASEURL" rel="sidebar" title="TYTUL">dodaj do ulubionych</a>
		// add a "rel" attrib if Opera 7+
		// don't overwrite the rel attrib if already set
		if(window.opera) if ($("#bookmarksite").attr("rel") != "") $("#bookmarksite").attr("rel","sidebar");
		
		$("#bookmarksite").click(function(event){
			event.preventDefault(); // prevent the anchor tag from sending the user off to the link
			var url = location.href;
			var title = this.title;
			
			if (window.sidebar) { // Mozilla Firefox Bookmark
				window.sidebar.addPanel(title, url,"");
			} else if( window.external ) { // IE Favorite
				window.external.AddFavorite( url, title);
			} else if(window.opera) { // Opera 7+
				return false; // do nothing - the rel="sidebar" should do the trick
			} else { // for Safari, Konq etc - browsers who do not support bookmarking scripts (that i could find anyway)
				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
				,'grup'		: '1'
				,'userid'	: '53'
				,'ip'		: _config.ip
				,'sesja'	: _config.sesja
				,'action'	: _config.newsletter_action
			};			
			// wywolujemy funckję mailproFeedback z obiektu _main
			$.getJSON( 'http://www.mailpro.pl/mailpro/ajaxact.php?object=_main&call=?', dane );
		}else{
			$('#newsletter_komunikat').css('display','none').text(Translator.newsletter['bledny_email']).show('slow').animate({opacity:1.0},2000).hide('slow');
		}
		
		return false;
	},
	
	mailproFeedback: function(data){
		var komunikat = Translator.newsletter[data.komunikat];
		komunikat = komunikat || 'brak tlumaczenia'
		$('#newsletter_komunikat').css('display','none').text(komunikat).show('slow').animate({opacity:1.0},2000).hide('slow');
	},
	// 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();

	//ie hack
	if ($.browser.msie && parseInt($.browser.version) < 7) {
		
		var left = $('#subsite_content_left');
		var wrapper = $(document);
		if (wrapper.height() > left.height()) {
			left.height(wrapper.height());
		}
	}
});

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){
		if (document.komunikaty_tpl[rodzaj]) {
			if (typeof (link_ok) == "undefined") {
				link_ok = location.href;
			}
			if (typeof (link_anuluj) == "undefined") {
				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>');
			$("#wrapper").prepend(komunikat);

			$('#over').css({'height':$(document).height(), 'opacity':'0.8' });
			_main.scrollToTop();
			var szerokosc = ( $(document).width() - $('#warstwa').width() ) / 2;
			$('#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;
				};
			});
		}
	}
};

function xshow(o) {
	s = '';
	for(e in o) {s += e+'='+o[e]+'\n';}
	alert( s );
}

function hoverRightMenu(idkat)
{
    $("#rightMenuAnchor"+idkat).css('fontWeight','bold');
    //document.getElementById('rightMenuAnchor'+idkat).style.fontWeight="bold";
}
function unhoverRightMenu(idkat)
{
    $("#rightMenuAnchor"+idkat).css('fontWeight','normal');
    //document.getElementById('rightMenuAnchor'+idkat).style.fontWeight="normal";
}

function email_validate(src)  {
	var regex = /^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
	return regex.test(src);
};
