var Site = {

	StartFunctions: [],

	// ======================================================================
	isAdmin: function() {
		return $('body').hasClass('admin-site');
	},
	isFrontend: function() {
		return $('body').hasClass('frontend-site');
	},
		
	// ======================================================================
	start: function() {
		$.fn.tagName = function(){ return this.get(0).tagName.toLowerCase(); }
		
		if (this.isFrontend()) {
			this.StartFadeOut();
			this.MakeConfirmLinks();
						
			this.wtwMain();
			this.RunStartFunctions();
		}

		if (this.isAdmin()) {
			this.MakeConfirmLinks();
			this.LangsPlugin();
			if ($.isFunction($.fn.pregImageUpload)) {
				$('.preg-image-upload').pregImageUpload();
			}
			this.tinyMCE();
		
			this.RunStartFunctions();
		}
		
	},
		
	// ======================================================================
	addStartFunction: function(f) {
		this.StartFunctions.push({
			f: f,
			started: false
		});
	},
		
	// ======================================================================
	RunStartFunctions: function() {
		for(var I in this.StartFunctions) {
			if (!this.StartFunctions[I].started) {
				this.StartFunctions[I].started = true;
				if ($.isFunction(this.StartFunctions[I].f)) {
					this.StartFunctions[I].f();
				}
			}
		}
	},
	
	// ======================================================================
	genID: function(n) { return 'id-' + parseInt(Math.round(Math.random()*100000)) + '-' + n; },

	// ======================================================================
	MakeConfirmLinks: function() {
		$('a.confirm-link').click(function(){
			var q = 'Czy napewno ?';
			var q2 = $(this).find('p').html();
			if (q2) q = q2;
			return confirm(q);
		});
	},
	
	// ======================================================================
	StartFadeOut: function() {
		$('.fadeout').each(function(){
			setTimeout(function(v) {
				$(v).fadeOut();
			},parseInt($(this).attr('preg:time')),this);
		});
	},

	// ======================================================================
	LangsPlugin: function() {
		$.fn.langs = function(options) {
			return this.each(function(){
				if (this.tagName.toLowerCase() == 'span') {
					var langs = [];
					var aLI = $(this).find('span');
					var that = this;
					$(aLI).each(function(){
						langs.push($(this).attr('lang'));
					});
					
					var fSel = function(l) {
						$(aLI).each(function(){
							if ($(this).attr('lang') == l) {
								$(this).show();
							} else {
								$(this).hide();
							}
						});
						$(that).find('.buttons a').each(function(){
							if ($(this).attr('lang') == l) {
								$(this).addClass('current');
							} else {
								$(this).removeClass('current');
							}
						});
					}
					var n = $('<span class="buttons"></span>');
					for(var I in langs) {
						var a = $('<a href="#" lang="' + langs[I] + '">' + langs[I] + '</a>');
						$(a).click(function(){
							fSel($(this).attr('lang'));
							return false;
						});
						$(n).append(a);
					}
					$(this).prepend(n);
					fSel(langs[0]);
				}
			});
		}
		
		$('.langs').langs();
	},
		
	// ======================================================================
	tinyMCE: function() {
		if (!$.isFunction($().tinymce)) return;
		
		$('textarea.tinymce').tinymce({
			// Location of TinyMCE script
			script_url : Settings.url + 'js/tiny_mce/tiny_mce.js',

			// General options
			theme : "advanced",
			plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,pregimage",

			// Theme options
			theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,formatselect,fontselect,fontsizeselect",
			theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,pregimage,image,cleanup,code,|,forecolor,backcolor",
			theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,fullscreen",
			//theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			theme_advanced_statusbar_location : "bottom",
			theme_advanced_resizing : true,
			relative_urls : false,
			convert_urls : false,
			extended_valid_elements: "style"
		});
		
	},	
	
	// ***********************************************************************************************
	wtwMain: function() {
	
		var searchInputValue = $('#input-search').val();
	
		$('#input-search').focusin(function(){
		
			if($(this).val() == searchInputValue)
			{
				$(this).val('');
			}
		
		});
	
		$('#input-search').focusout(function(){
		
			if($(this).val().length == 0)
			{
				$(this).val(searchInputValue);
			}
		
		});
	
		$('#top-menu-links li.with-submenu').mouseover(function(){
		
			$(this).find('.sub-menu').show();
		
		});
	
		$('#top-menu-links li.with-submenu').mouseleave(function(){
		
			$(this).find('.sub-menu').hide();
		
		});
	
		$('#top-menu-lang a#link-choose-lang').mouseover(function(){
		
			$(this).parent().find('.sub-menu').show();
		
		});
	
		$('#top-menu-lang').mouseleave(function(){
		
			$(this).parent().find('.sub-menu').hide();
		
		});	
	
		// newsletter
	
		var newsletterInputValue = $('#form-newsletter-input-email').val();
	
		$('#form-newsletter-input-email').focusin(function(){
		
			if($(this).val() == newsletterInputValue)
			{
				$(this).val('');
			}
		
		});
	
		$('#form-newsletter-input-email').focusout(function(){
		
			if($(this).val().length == 0)
			{
				$(this).val(newsletterInputValue);
			}
		
		});
	
		$('.newsletter .newsletter-switch.down').click(function(){
		
		
			$('.newsletter .newsletter-expand').slideDown();
			$('.newsletter .newsletter-non-expand').hide();
		
			return false;
		});
	
	
		$('.newsletter .newsletter-switch.up').click(function(){
		
			$('.newsletter .newsletter-non-expand').show();
			$('.newsletter .newsletter-expand').slideUp();
		
			return false;
		});
	
		$('#form-newsletter').submit(function(){
			var that = this;
			

			$.post($(this).attr('action'), $(this).serialize(), function(res) {
				if (res.status == 'ok') {
					$(that).hide();
					$('.newsletter .newsletter-expand #form-newsletter-success').show();
					setTimeout(function(){
						$('.newsletter .newsletter-switch.up').click();
					}, 1000);
				} else {
					alert(res.error);
				}
			}, 'json');
			
			return false;
		});
	
		// presentation box
	
		// init
		$('.presentation-box-image a:not(:first-child)').hide();
		$('.presentation-box-image a:first-child').show();
	
		$('.presentation-box-list > ul > li').removeClass('active');
		$('.presentation-box-list > ul > li:first-child').addClass('active');
	
		$('.presentation-box-list > ul > li').mouseover(function(){
		
			if(!$(this).hasClass('active'))
			{
				var id = $(this).index();
			
				var a = $('.presentation-box-image > a').eq(id);
			
				$('.presentation-box-image a').hide();
				a.show();
			
				$('.presentation-box-list > ul > li.active').removeClass('active');
				$(this).addClass('active');
			}
		
		});
	
		// tree
	
		// init
		$('.categories-tree ul:not(.first-lvl)').hide();
	
		$('.categories-tree ul > li > a.active').each(function(){
		
			$(this).parents('.categories-tree ul').show();
		
			if($(this).parent().hasClass('has-children'))
			{
				$(this).parent().children('ul').show();
			}
		});
	
		$('.categories-tree ul > li > a').click(function(){
		
			var parent_li = $(this).parent();
		
			if(parent_li.hasClass('has-children'))
			{
				if($(this).hasClass('active'))
				{
					parent_li.children('ul').slideUp('normal');
					$(this).removeClass('active');
				
					// musimy takze zamykajac biezaca zamkac wszystkie dzieci i
					// zabrac im active
					parent_li.find('a.active').removeClass('active');
					parent_li.find('ul').slideUp();
				}
				else
				{
					// rozwijajac zakladke musimy zamknac inne ktore sa na tym samym
					// poziomie i ich dzieci
					parent_li.parent().find('ul').slideUp('normal');
					parent_li.parent().find('a.active').removeClass('active');
				
					parent_li.children('ul').slideDown('normal');
					$(this).addClass('active');
				}
			}
			else
			{
				// jesli nie ma dzieci to pozwalamy na dzialanie href linku
				return true;
			}
		
			return false;
		});
	
		// download
	
		var searchDownloadInputValue = $('#download-search-input').val();
	
		$('#download-search-input').focusin(function(){
		
			if($(this).val() == searchDownloadInputValue)
			{
				$(this).val('');
			}
		
		});
	
		$('#download-search-input').focusout(function(){
		
			if($(this).val().length == 0)
			{
				$(this).val(searchDownloadInputValue);
			}
		
		});
	
		$('table.files-list .button-info').mouseover(function(){
		
			$(this).css('z-index', '100');
			$(this).parent().find('.infobox').show();
		
		});
	
	$('table.files-list .button-info').mouseleave(function(){
		
			$(this).parent().find('.infobox').hide();
			$(this).css('z-index', '0');
		
		});

	// offer

		var searchOfferInputValue = $('#offer-search-input').val();
	
		$('#offer-search-input').focusin(function(){
		
			if($(this).val() == searchOfferInputValue)
			{
				$(this).val('');
			}
		
		});
	
		$('#offer-search-input').focusout(function(){
		
			if($(this).val().length == 0)
			{
				$(this).val(searchOfferInputValue);
			}
		
		});
	
		// popup
	
		$('a.form-offer-query-link-open').click(function(){
			var productID = parseInt($(this).attr('preg:productid'));
			
			$('#form-offer-query').attr('action',formDefaultAction.replace('__ID__',productID));
			
			$('#overlay').show();
		
			$('#window-offer-query').show();
		
			$('#overlay').css('height', $('body').height());
		
			// usuniecie tematow jesli jakies byly i dodanie obecnego
			$('#window-offer-query #window-offer-query-topics .topic-div:not(:first-child)').remove();
		
			$('#window-offer-query #window-offer-query-topics .topic-div:first-child input.input-topic').val($(this).find('.topic-to-form').text());
			
			return false;
		});
	
		$('.popup-window .window-close a').click(function(){
		
			$('.popup-window').hide();
		
			$('#overlay').hide();
			
			return false;
		});

		var formOfferDefaults = {};
		var formDefaultAction = $('#form-offer-query').attr('action');
	
		$('#form-offer-query input:not(.input-topic), #form-offer-query textarea').each(function(){
		
			formOfferDefaults[$(this).attr('id')] = $(this).val();
		
		});
	
		$('#form-offer-query input:not(.input-topic), #form-offer-query textarea').focusin(function(){
		
			if($(this).val() == formOfferDefaults[$(this).attr('id')])
			{
				$(this).val('');
			}
		
		});
	
		$('#form-offer-query input:not(.input-topic), #form-offer-query textarea').focusout(function(){
		
			if($(this).val().length == 0)
			{
				$(this).val(formOfferDefaults[$(this).attr('id')]);
			}
		
		});
	
		function onEditTopic()
		{
			$(this).hide();
		
			$(this).parents('.topic-div').find('.button-topic-add').hide();
		
			$(this).parents('.topic-div').find('input.input-topic').attr('readonly', false).removeClass('inactive').focus();
			
			return false;
		}
	
		function onAddTopic(){
		
			var div = $('<div class="topic-div" />');
		
			var input = $('<input type="text" class="text input-topic" name="topics[]" value="" />');
			input.focusout(onFocusOut);
		
			div.append(input);
			var buttons = $('<div class="buttons" />');
		
			var button_edit = $('<a href="#" class="blue-button button-topic-change" title="Zmień temat"><strong><span>ZMIEŃ</span></strong></a>').hide();
			var button_add = $('<a href="#" class="blue-button button-topic-add" title="Dodaj kolejny temat"><strong><span>DODAJ</span></strong></a>').hide();
		
			buttons.append(button_edit).append(button_add);
		
			div.append(buttons);
		
			button_add.click(onAddTopic);
			button_edit.click(onEditTopic);
		
			$('#window-offer-query-topics').append(div);
		
			input.focus();
		
			return false;
		}
	
		function onFocusOut()
		{
			$(this).attr('readonly', true);
			$(this).addClass('inactive');
		
			$(this).parent().find('.button-topic-add, .button-topic-change').show();
		}
	
		$('#form-offer-query #window-offer-query-topics a.button-topic-add').click(onAddTopic);
		$('#form-offer-query #window-offer-query-topics a.button-topic-change').click(onEditTopic);
	
		$('#form-offer-query #window-offer-query-topics input.input-topic').focusout(onFocusOut);
	
		$('#form-offer-query').submit(function(){
			
			$('#form-offer-query input:not(.input-topic), #form-offer-query textarea').each(function(){
			
				if(($(this).attr('name') != 'DO') && ($(this).val() == formOfferDefaults[$(this).attr('id')]))
				{
					$(this).val('');
				}
		
			});
			
			
			$.post($(this).attr('action'), $(this).serialize(), function(res) {
				if (res.status == 'ok') {
					alert('Formularz został wysłany');
					
					$('.popup-window').hide();
					$('#overlay').hide();
					
				} else {
					var str = '';
					for(var I in res.errors) {
						str += res.errors[I] + "\n";
					}
					alert(str);
				}
			}, 'json');
			
			return false;
		});
	
		// kontakt
	
		var formContactDefaults = {};
	
		$('#form-contact input, #form-contact textarea').each(function(){
		
			formContactDefaults[$(this).attr('id')] = $(this).val();
		
		});
	
		$('#form-contact input, #form-contact textarea').focusin(function(){
		
			if($(this).val() == formContactDefaults[$(this).attr('id')])
			{
				$(this).val('');
			}
		
		});
	
		$('#form-contact input, #form-contact textarea').focusout(function(){
		
			if($(this).val().length == 0)
			{
				$(this).val(formContactDefaults[$(this).attr('id')]);
			}
		
		});
		
		$('#form-contact').submit(function(){
			
			$('#form-contact input, #form-contact textarea').each(function(){
				if(($(this).attr('name') != 'DO') && ($(this).val() == formContactDefaults[$(this).attr('id')]))
				{
					$(this).val('');
				}
			
			});
			
			$.post($(this).attr('action'), $(this).serialize(), function(res) {
				if (res.status == 'ok') {
					alert('Formularz został wysłany');
				}
				if (res.status == 'error') {
					var str = '';
					for(var I in res.errors) {
						str += res.errors[I] + " ";
					}
					alert(str);
				}
			}, 'json');
			
			return false;
		});		
	
	
		// serwis
		$('#service-texts .service-text').hide();
	
		$('#service-texts a.switch-text.down').click(function(){
		
			$(this).hide();
			$(this).parent().children('a.up').show();
		
			$($(this).attr('href')).slideDown('normal');
		
			return false;
		});
	
		$('#service-texts a.switch-text.up').click(function(){
		
			$(this).hide();
			$(this).parent().children('a.down').show();
		
			$($(this).attr('href')).slideUp('normal');
			return false;
		});	
		
		// back button
		$('.back-link').click(function(){
			history.back();
			return false;
		});
	}
}

$(function() {
	Site.start();
})


