/*
	depends on jQuery	
	supported browsers: IE6 IE7 FF3 and opera 9
 */
if (top.frames.length!=0) { top.location=self.document.location;}
var DEBUG = false; 
// wszelakie komunikaty
var MESSAGES = {
	'favourites_added': 'Dodano do ulubionych',
	'favourites_exists': 'Artykuł znajduje się już w ulubionych',
	'favourites_error': 'Wystąpił błąd przy zapisywaniu do ulubionych. Proszę spróbować później.',

	'delete_profile': 'Czy na pewno chcesz usunąć swój profil?',

	'ajax_error': 'Wystąpił błąd. Proszę spróbować później.<br />Przepraszamy.',

	'close': 'zamknij',
	'login_header' : 'Proszę się zalogować',
	'login_content' : 'Aby dodać artykuł do ulubionych proszę się najpierw <a href="/login">zalogować</a>.'
};


try {
	if (!window.jQuery) {
		throw new Error("jQuery required");	
	}	
	
	(function ($) {		
		// logging function
		$.log = function(a){
			if (DEBUG) {
				if (window.console) {
					console.log(a);
				}
				else { alert(a); }
			}
		};
		$.fn.extend({
			blinder: function(){
				return $(this).filter('img').each(function(){
					
					if (!this.complete || (typeof (this.naturalWidth) != 'undefined' && this.naturalWidth === 0 ) || (this.width === 0 && this.height === 0) ) {
						var path = this.src.split('/'), folder = path[path.length-2];
						this.src = 'http://'+path[2]+'/img/blinders/'+path[path.length-2]+'/zaslepka.jpg';
					}
				})
			},
			submenu: function(opts){
				opts = $.extend({
					speed: 500,
					panel_selector: '.constellation_content'
				}, opts);				
				return $(this).each(function(){
					panel_visible = false;
					var timer, panel = $(this), content = $(opts.panel_selector, panel), link = $("a", panel).eq(0);
					var hide_panel = function() {
						content.fadeOut(function(){
							link.removeClass('hover');
						});
					};
					var start = function(){
						timer = setTimeout(hide_panel, opts.speed);
					};
					var stop = function(){
						clearTimeout(timer);
					};
					$(panel)
						.bind('mouseover',function(e){
							stop();
							if (content.is(":animated")) {								
								content.stop().css('opacity',1);
							}
							link.addClass('hover');
							content.show();
							panel_visible = true;
						})
						.bind("mouseout", start);
				});
			},
			scrollable: function(opts){
				opts = $.extend({
					rootClass: 'scrollable',
					loop: false,
					showOnLoad: null
				}, opts);
				var prevHTML = '<span style="position: absolute; left: 0px; display: block; z-index:2" class="nav prev"><a href="#">poprzednie</a></span>', 
					nextHTML = '<span style="position: absolute; right: 0px; display: block; z-index:2" class="nav next"><a href="#">następne</a></span>';
				return this.each(function(){
					var rootElem = $(this), 
						scrollElem = $("ul", rootElem),
						sliding = false;
					
					// calculate visible width
					var elems = scrollElem.children();
					
					if ((elems.length * elems.width()) <= rootElem.width()) {
						scrollElem.width(elems.length * elems.width()).css({margin:'auto'});
						// no scroll required
						return true;
					}
					
					scrollElem.css({'position':'absolute', 'z-index':'1', 'width':elems.length * elems.width()});
					rootElem.addClass(opts.rootClass);
					var next = $(nextHTML).prependTo(rootElem), prev = $(prevHTML).prependTo(rootElem);
					var section = rootElem.width() - prev.width() - next.width();
					var scrollWidth = scrollElem.width();
					var maxOffset = -scrollWidth + rootElem.width();
					next.click(function(e){
						e.preventDefault();
						if (!sliding) {
							if (opts.loop) {
								loop(1);
							}
							else {
								move(1);
							}
						}
					});
					prev.click(function(e){
						e.preventDefault();
						if (!sliding) {
							if (opts.loop) {
								loop(0);
							}
							else {
								move(0);
							}
						}
					});
					
					if (opts.showOnLoad && $(opts.showOnLoad, scrollElem).length){
						//scroll to the specified element
						var p_elem = $(opts.showOnLoad, scrollElem), offset = 0;
						if (p_elem.length) {
							var addPrevWidth = function(el){
								offset += el.width();
								if (el.prev().length) {
									addPrevWidth(el.prev());
								}
							};
							addPrevWidth(p_elem);
						}
						if (offset > section) {
							for (var i=0,l=parseInt( offset / section, 10);i<l;i++) {
								loop(1, {animate:false});
							}
						}
					}
					
					function move(next){
						var leftOffset = parseInt(scrollElem.css('left'),10) || 0;
						var offset;
						if (next) {
							offset = leftOffset-section < maxOffset ? maxOffset : leftOffset-section;
							scrollElem.animate({'left': offset});
						}
						else {
							offset = leftOffset+section > 0 ? 0 : leftOffset+section;
							scrollElem.animate({'left': offset});
						}
					}
					function loop(next, opts){
						opts = $.extend({ speed: 2000, animate: true }, opts);
						var leftOffset = parseInt(scrollElem.css('left'),10) || 0, 
							offset, newElems,
							curScrollWidth = parseInt(scrollElem.width(),10);
						sliding = true;
						if (next) {
							offset = leftOffset-section;
							if (leftOffset-section < maxOffset) { // brakuje ikonek z przodu
								newElems = elems.clone();
								scrollElem.append(newElems).css({width: curScrollWidth + scrollWidth});
							}
							if (opts.animate) {
								scrollElem.animate({'left': offset}, opts.speed, function(){
									sliding = false;
								});
							}
							else {
								scrollElem.css({'left': offset});
								sliding = false;
							}
						}
						else {
							offset = leftOffset+section;
							if (leftOffset+section > 0) { // brakuje ikonek na koncu
								newElems = elems.clone();
								scrollElem.prepend(newElems).css({'left': leftOffset-scrollWidth, width: curScrollWidth + scrollWidth});
								offset = offset-scrollWidth;
							}
							if (opts.animate) {
								scrollElem.animate({'left': offset}, opts.speed, function(){
									sliding = false;
								});
							}
							else {
								scrollElem.css({'left': offset});
								sliding = false;
							}
						}
						// cleanup items not visible
					}
				});
			}
		});
		$.fn.showAll = function(){
			return this.each(function(){
				var link = $(this);
				var orig_label = link.text();
				var new_label = 'Ukryj';
				var container = link.prev();
				var orig_height = container.height();
				var new_height = container.children(".hiddden").length * 18 + orig_height;
				link.click(function(e){
					e.preventDefault();
					if (!link.is(".open")){
						container.animate({'height':new_height}, 600);
						link.text(new_label);
					}
					else {
						container.animate({'height': orig_height}, 600);
						link.text(orig_label);
					}
					link.toggleClass('open');
				});
			});
		};
		// jQuery plugin to generate tabs
		$.fn.tabbed = function(options) { 
			var opts = $.extend({
				selectedClass: 'tab_selected',
				hiddenClass:   'hidden',
				panelClass:    'tab',
				tabbedPanelClass: 'ui-tabs-panel'
			}, options);
			this.counter = 0;
	
			//hide all tab panels while building
			//$(".ui-tabs-panel").addClass(opts.hiddenClass);
			var self = this;
			return this.each(function() {
				var root = $(this);
				var nav = $("<ul class='ui-tabs-nav'></ul>");
				
				$("."+opts.panelClass, root).each(function(i){
					$(this).addClass(opts.tabbedPanelClass);
					if (!$(this).attr('id')) {
						
						$(this).attr('id','tab_'+self.counter);
						self.counter++;
					}
					var tab_title = $(this).attr('title') || 'default title';
					//create a tab for each tabbed module
					nav.append("<li tab='"+$(this).attr('id')+"' class='tab_"+i+"' id='tab_"+$(this).attr('id')+"'><a href='#'><span>"+ tab_title  +"</span></a></li>");
					
				});
				
				root.prepend(nav);
				//default to the first tab to be selected  
				var selectedTab = $(".ui-tabs-nav li:first", root);     

				var activate = function(elem) {
					var activeTab = $(elem);
					var activePanel = $("#" + activeTab.attr('tab'));
					
					//move selected css class to newly selected tab
					selectedTab.removeClass(opts.selectedClass);   
					activeTab.addClass(opts.selectedClass);
					
					//hide tab panels and display selected panel 
					$("."+opts.tabbedPanelClass, root).addClass(opts.hiddenClass);
					activePanel.removeClass(opts.hiddenClass); 
					selectedTab = activeTab;
				};
								
				$('li', nav).click(function() {
					activate(this);
					return false;  
				}); 
				activate(selectedTab);
			});            
		};
	})(jQuery);
	
	(function(){

		/*
		 * hides and shows the default value in text input elements
		 */
		function prompt(dir, elem){
			if (dir) {
				if (elem.value == elem.defaultValue) {
					elem.value = '';
				}
			}
			else {
				if (elem.value == elem.defaultValue || elem.value === '') {
					elem.value = elem.defaultValue;
				}
			}
		}
		
		/*
		 * Slider prototype
		 * By default it powers the highlights on the home page
		 * By setting some parameters when creating an instance it can be reused for any sliding animations
		 */
		function Slider(settings){
			this.settings = $.extend({
				container: "#highlights",
				elems_root: "ul",
				elems_items: "li",
				interval: 8000,
				speed: 1000,
				auto_rotate: true,
				prev_trigger: ".nav .prev",
				next_trigger: ".nav .next"
			}, settings);

			this.started = false;
			this.running = false;
			
			this.root = $(this.settings.container);
		
			this.prev = $(this.settings.prev_trigger,this.root);
			this.next = $(this.settings.next_trigger,this.root);
			// check if not initialised on this element already
			if (!this.root.attr("slider")) {			
				this.curItem = 0;
				this.elemsRoot = $(this.settings.elems_root, this.root).eq(0).css({position:"relative"});	
				this.itemWidth = $(this.settings.elems_root +' '+ this.settings.elems_items, this.root).eq(this.curItem).width();

				var self = this;
				// rotate only if more than one element				
				if ($(self.settings.elems_root +' '+ self.settings.elems_items, self.root).length > 1) {
	
					// attach handlers to controls				
					this.prev.bind("click", function(e) {
						e.preventDefault();
						self.go('prev');
					});
					this.next.bind("click", function(e) {
						e.preventDefault();
						self.go('next');
					});
					
					if (this.settings.auto_rotate) {
						// start autoslider
						this.start();
						this.root.hover(function(){
							self.stop();
						}, function(){
							self.start();
						});
						this.root.blur(function(){
							self.start();
						});
						this.root.focus(function(){
							self.stop();
						});
					}
					
					// display the 2nd news header
					if (self.settings.teaser_container && self.settings.teaser_content) {
						var content = $(this.settings.elems_root +' '+ this.settings.elems_items, this.root).eq(1).text();
						$(self.settings.teaser_container, self.root).text(content);
					}
				}
				else {
					this.next.click(function(e) {
						e.preventDefault();
					});
					this.prev.click(function(e) {
						e.preventDefault();
					});	
				}
				this.root.attr("slider","true");
				this.started = true;
			}
		}
		Slider.prototype = {
			start : function(){
				this.started = true;
				var self = this;
				if (self.timer) {
					clearInterval(self.timer);
				}
				self.timer = setInterval(function(){
					self.go('next');
				}, this.settings.interval);
				if (DEBUG){
					$.log('started');
				}
			},
			stop: function(){
				var self = this;
				if (self.timer) {
					clearInterval(self.timer);
				}
				this.started = false;
				if (DEBUG){
					$.log('stopped');
				}				
			},
			go: function(dir){
				dir = dir || 'next';
				var self = this;
				var allItems = $(self.settings.elems_root +' '+ self.settings.elems_items, self.root);
				var firstItem = allItems.filter(":first");
				if (self.settings.teaser_container && self.settings.teaser_content) {
				// display the following news header
					var callback = function(nextItem){
						var content = $(self.settings.teaser_content, nextItem).text();
						$(self.settings.teaser_container, self.root).text(content);
					};
				}
				self.running = true;
				
				if (dir == 'prev') {
					var lastItem = allItems.filter(":last");
					self.elemsRoot.css({left: -self.itemWidth+"px"}).prepend(lastItem).animate({left: "0px"}, 
						{
							duration: self.settings.speed,
							complete: function(){

								if (callback && typeof(callback)=='function') {
									callback(firstItem);
								}
								self.running = false;
							}
						});
					if (self.curItem > 0){
						self.curItem--;
					}
					else {
						self.curItem = allItems.length-1;
					}
				}
				else {
					var nextItem;
					if (allItems.length > 2){
						nextItem = firstItem.next().next();
					}
					else {
						nextItem = firstItem;
					}
					self.elemsRoot.animate({left: -self.itemWidth+"px"}, 
						{
							duration: self.settings.speed,
							complete: function(){
								self.elemsRoot.append(firstItem);
								if (callback && typeof(callback)=='function') {
									callback(nextItem);
								}
								self.elemsRoot.css({left:"0px"});
								self.running = false;
							}
						});
					
					if (this.curItem < allItems.length -1){
						self.curItem++;
					}

					else {
						self.curItem = 0;
					}
				}				
			},
			destroy: function(){
				this.stop();
				this.prev.click = null;
				this.next.click =  null;
				if (this.timer) {
					clearInterval(this.timer);
				}
				this.running = false;
				this.started = false;
			}
		};
		
		/** add to favourites handler **/
		var msgCSS = "height: 35px;" +
					"background-color: #D12727;" +
					"color: #fff;" +
					"line-height: 35px;" +
					"display: none;" +
					"font-weight: bold;" +
					"font-size: 14px;" +
					"text-align: center;";
		var msgHTML = '<div style="'+msgCSS+'">';
		var panelHTML = '<h1>'+MESSAGES.login_header+'</h1><p>'+MESSAGES.login_content+'</p>';
		function addToFavourites(e){
			e.preventDefault();
			var elem = $(this);
			if (elem.attr('href') && elem.attr('href') != '#') {
				var container = elem.parents(".articleActions:first");
				var _response = function(json){
					var msg;
					if (json && (json.result == 'true' || json.result === true)) {
						msg = $(msgHTML + MESSAGES.favourites_added + '</div>').insertBefore(container).fadeIn("slow");
					}
					else if (json && json.result == 'comment exists') {
						msg = $(msgHTML + MESSAGES.favourites_exists + '</div>').insertBefore(container).fadeIn("slow");
					}
					else {
						msg = $(msgHTML + MESSAGES.favourites_error + '</div>').insertBefore(container).fadeIn("slow");
					}
					setTimeout(function(){ msg.fadeOut("slow", function(){msg.remove();}); }, 10000);
				};
				$.ajax({
					type: 'GET',
					dataType: 'json',
					success: _response,
					error: _response,
					url: elem.attr('href')
				});
			}
			else {
				if (!app.loginPanel){
					app.loginPanel = new app.Modal({content:panelHTML, className: 'loginRequired'});
				}
				app.loginPanel.load();
			}
			return false;
		}
		
		
		/** recommend handler **/
		function recommendLink(e){
			e.preventDefault();
			if (!app.sendtoPanel){
				app.sendtoPanel = new app.Modal({url:$(this).attr('href'), className: 'recommend'});
			}
			app.sendtoPanel.load({
				vars: { "#link": window.location }
			});
			return false;
		}
		/** abuse handler **/
		function abuseLink(e){
			e.preventDefault();
			if (!app.abusePanel){
				app.abusePanel = new app.Modal({url:$(this).attr('href'), className: 'abuse'});
			}
			app.abusePanel.load({
				vars: {"#link": window.location }
			});
			return false;
		}
		function deleteProfile(e){
			e.preventDefault();
			var url = $(this).attr("href");
			var html = '<p>'+MESSAGES.delete_profile+'</p><p><a class="yes" href="'+url+'">Tak</a><a href="#" class="no">Nie</a>';
			if (!app.abusePanel){
				app.delPanel = new app.Modal({content: html, className: 'warning', clickClose: false});
			}
			app.delPanel.load();
			$("a.no", app.delPanel.modal).bind('click', {self: app.delPanel}, app.delPanel.close);
		}
		var modalHTML = [];
		modalHTML[0] = '<div class="modalPanel" style="display: none;">';
		modalHTML[1] = '<div class="control"><a class="close" title="' + MESSAGES.close + '" href="#">' + MESSAGES.close + '</a></div><div class="content"></div>';
		modalHTML[2] = '</div>';
		var errorHTML = '<p class="error">'+ MESSAGES.ajax_error + '</p>';
		
		function Modal(opts){
			if (!app) {
				return false;
			}
			this.opts = opts;
			var self = this;
			if (!app._modal_initialized) {
				// reuse the same DOM panel for all modal panels
				var html = modalHTML.join('');
				this.modal = app.modal_panel = $(html).appendTo("body"); 
				app._modal_initialized = true;
				
				if ( $.browser.msie && parseInt($.browser.version, 10) < 7) {
					// fix 'position: fixed'
					var top = $(window).scrollTop() + $(window).height() / 2;
					var left = $(window).scrollLeft() + $(window).width() / 2;
					this.modal.css({'z-index': '1000', 'position': 'absolute', 'top': top, 'left': left});
				}
			}
			else {				
				this.modal = app.modal_panel;
			}
			this.close_ctrl = $(".control a", this.modal);
			this.close_ctrl.bind('click', {self: self}, this.close);
			return true;
		}
		Modal.prototype= {
			load: function(opts){			
				if (!app._modal_visible) {
					var self = this;
					var settings = self.opts || {};
					if (settings.className) {
						self.modal.attr('class', 'modalPanel '+self.opts.className);
					}
					
					$(".content", self.modal).html('');
					if (!app._mask) {
						app._mask = new app.Mask({clickClose: false, onClose: 'hide'});
					}
					if (settings.url) {
						$(".content *", self.modal).unbind();
						$.ajax({
							type: 'GET',
							url: this.opts.url,
							cache: false,
							dataType: 'html',
							success: function(html){
								$(".content", self.modal).html(html.replace(/&nbsp;/g,''));
								$("#modal_form", self.modal).bind('submit', {self: self}, self.submit);
								$(".close", self.modal).bind('click', {self: self}, self.close);
								if (opts && opts.vars) {
									for (key in opts.vars) {
										if (typeof opts.vars[key] !== 'function') {
											$(key, self.modal).val(opts.vars[key]);
										}
									}
								}
							},
							error: function(){
								$(".content", self.modal).html(errorHTML);
							}
						});
					}
					else if(settings.content) {
						$(".content *", self.modal).unbind();
						$(".content", self.modal).html(self.opts.content);
					}
					app._mask.maskElement.bind('click', {self: self}, self.close );
					app._mask.add(this.modal.show());
					app._modal_visible = true;
				}
			},
			close: function(e){

				e.preventDefault();
				var self = e.data.self;
				
				app._mask.maskElement.unbind();
				$(".content *", self.modal).unbind();
				app._mask.remove(self.modal.hide());			
				app._modal_visible = false;
			},
			submit: function(e){
				e.preventDefault();
				var self = e.data.self;
				var form = $(this);
				
				// unbind handlers to current html content
				$(".content *", self.modal).unbind();
				self.modal.addClass('loading');
				$.ajax({
					type: 'POST',
					url: self.opts.url,
					data: form.serialize(),
					cache: false,
					dataType: 'html',
					success: function(html){
						self.modal.removeClass('loading');
						$(".content", self.modal).html(html.replace(/&nbsp;/g,''));
						$("#modal_form", self.modal).bind('submit', {self: self}, self.submit);
						$("input#close", self.modal).bind('click', {self: self}, self.close);
						$(".close", self.modal).bind('click', {self: self}, self.close);
					},
					error: function(){
						self.modal.removeClass('loading');
						$(".content", self.modal).html(errorHTML);
					}
				});
			}
		};
		
		
		var htmlStr = '<div class="mask" style="margin:0;padding:0;position:absolute;width:100%;top:0;left:0;', //reusable html string
		iframeSrc = '<iframe class="mask" style="margin:0;padding:0;position:absolute;top:0;left:0;filter:alpha(opacity=0);display:none"></iframe>';
		
		function Mask(opts) {
			this.opts = $.extend({
				color: '#000',
				opacity: 0.5,
				zIndex: 9900,
				clickClose: true
			}, opts);
			
			/*
			Property: maskElement
				The node overlayed to create the mask. Access this if you want to
				change its properties on the fly
			*/
			var mask = $(htmlStr + 'z-index:' + this.opts.zIndex + ';background:' + this.opts.color + ';visibility:hidden"></div>').appendTo('body'),				
				hiddenElements = [],
				flashUrlTest = /.swf($|\?)/i,
				wmodeTest = /<param\s+(?:[^>]*(?:name=["'?]\bwmode["'?][\s\/>]|\bvalue=["'?](?:opaque|transparent)["'?][\s\/>])[^>]*){2}/i, //"
				that = this;
			this.maskElement = mask;
			mask.css("opacity", this.opts.opacity);
	
			if ($.browser.msie && $.browser.version < 7) {
				this._iframe = $(iframeSrc).css("z-index", this.opts.zIndex - 1).prependTo('body');
			}
			//hide flash objects that don't have wmode set
			this.hideElms = function(overlay) {
				//return if elements have already been hidden, saves time
				//if (hiddenElements.length) { return; }
				
				var thingsToHide = [];	
	
				thingsToHide.push(
					$("object, embed").filter(function() {
						var that = this, wmode;
						// we need to use getAttribute here because Opera & Safari don't copy the data to properties
						if (
							( that.getAttribute("type") == "application/x-shockwave-flash" ||
							flashUrlTest.test(that.getAttribute("data") || that.getAttribute("src") || "") ||
							(that.getAttribute("classid") || "").toLowerCase() == "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000")
						) {
							wmode = that.getAttribute("wmode");
			
							return (that.nodeName == "OBJECT" && !wmodeTest.test(that.innerHTML)) ||
								(that.nodeName != "OBJECT" && wmode != "transparent" && wmode != "opaque");
			
						}
						return false;
					})
				);
	
	
				for (var i = 0, thingsToHideLen = thingsToHide.length; i < thingsToHideLen; i++) {
					hiddenElements[i] = [thingsToHide[i], thingsToHide[i].css("visibility")];
					thingsToHide[i].css("visibility", "hidden");
				}
			};
			this.revertHiddenElms = function() {
				for (var i = 0, len = hiddenElements.length; i < len; i++) {
					hiddenElements[i][0].css("visibility", hiddenElements[i][1]);
				}
				hiddenElements = [];
			};
			if (this.opts.clickClose) {
				mask.click(function(){
					that.remove(this.curTopBox);
				});
			}
		}
		Mask.prototype = {
			add: function (topBox) {
				var body = $("body"),
					win = $(window),
					that = this;
				if(topBox){
					if (topBox.css("position") == 'static' || topBox.css("position") === '' ) {
						topBox.css({"position" : "relative"});
					}
					else {
						this.old_css = {
							position: topBox.css("position"),
							'z-index': topBox.css("z-index")
						};
					}
					topBox.css({"zIndex" : "10000"});
				}
				
				this.curTopBox = topBox;
				function resizeMask() {
					var bodyHeight = body.outerHeight(), bodyWidth = body.outerWidth();
					var dim = {
						height: $(document).height(),
						width:  $(document).width()
					};
					// opera has ridiculous document width. the body width is the correct document width tho
					if ($.browser.opera) {
						dim.width = $("body").width();
					}
					
					that.maskElement.css("width", Math.max(bodyWidth, win.width(), dim.width) + "px").css("height", Math.max(bodyHeight, win.height(), dim.height) + "px");
					
					// resize the iframe for ie to match the mask
					if ($.browser.msie && $.browser.version < 7) {
						var maskStyle = that.maskElement[0].style;
						that._iframe.css("width", maskStyle.width).css("height", maskStyle.height);
					}
				}
				this.maskElement.css("visibility", "visible").css("display", "block");
				if ($.browser.msie && $.browser.version < 7) {
					this._iframe.css("display", "block");
				}
				this.hideElms();
				resizeMask();
				win.bind("resize", resizeMask);
				return false;
			},
			remove : function (topBox) {
				topBox = topBox || this.curTopBox;
				this.maskElement.css("visibility", "hidden").css("display", "none");
				if ($.browser.msie && $.browser.version < 7) {
					this._iframe.css("display", "none");
				}
				if(topBox){
					if (this.old_css) {
						topBox.css({
							'z-index': this.old_css['z-index'],
							position: this.old_css.position
						});
					}
					else {
						topBox.css({"zIndex" : "", "position" : ""});
					}
					if (this.opts.onClose == 'remove') {
						topBox.remove();
					}
					else {
						topBox.hide();
					}
				}
				$(window).unbind("resize");
				this.revertHiddenElms();
				this.curTopBox = null;
				return false;
			}
		};

		// create application namespace if doesn't exist
		if (!window.app) { window.app = {}; }
		// append to app namespace
		window.app = {
			Slider: Slider,
			Mask: Mask,
			Modal: Modal,
			handlers: {
				addToFavourites: addToFavourites,
				recommendLink: recommendLink,
				prompt: prompt,
				abuseLink: abuseLink,
				deleteProfile: deleteProfile
			}
		};
	})();
	
	
	// function to run on DOM ready
	app.init = function(){

		// input prompt
		$("#newsletter input[type='text'], #searchForm input[type='text']").bind("focus", function(e){
			app.handlers.prompt(true, e.target);
		}).bind("blur", function(e){
			app.handlers.prompt(false, e.target);
		});
		
		
		// enable gallery scrolling
		app.sliders = [];		
		app.sliders.push(new app.Slider({
			container: "#highlights",
			elems_root: "ul",
			elems_items: "li",
			interval: 8000,
			speed: "fast",
			auto_rotate: true,
			prev_trigger: ".nav .prev",
			next_trigger: ".nav .next",
			teaser_container: ".nav .teaser #nextNews",
			teaser_content: "h1"
		}));		
		$(".videogallery, .photogallery").each(function(i){
			app.sliders.push(new app.Slider({
				container: $(this),
				elems_root: "ul",
				elems_items: "li",
				interval: 8000,
				speed: "fast",
				auto_rotate: true,
				prev_trigger: ".seePrev",
				next_trigger: ".seeNext"
			}));
			$(".seePrev", this).show();
			$(".seeNext", this).show();
		});
		
		// generate tabs
		$(".tabbed").tabbed();
		// footer links
		$(".footerlinks .collapse").showAll();
		// bind favourites links
		$("a.favoritesLink").bind('click', app.handlers.addToFavourites);
		
		// bind abuse link
		$(".abuseLink").bind('click', app.handlers.abuseLink);
		
		// bind recommend link
		$(".recommendLink").bind('click', app.handlers.recommendLink);
		
		// bind delete profile link
		$(".delete_profile").bind('click', app.handlers.deleteProfile);
		
		// scrollable gallery
		$("#albumThumbs").scrollable({loop:true, showOnLoad: '.active'});
		
		$(".constellation").submenu();
		
		

		
	};
	$(window).load(function(){
													
		$('img').blinder();
	})
	$(document).ready(function(){
		if(typeof(app.init) == 'function') {
			app.init();
		}
	});
	
	$(window).unload(function(){
		// destroy all sliders
		if (typeof (app.sliders) != 'undefined') {
			for (var i = 0, len = app.sliders.length; i < len; i++) {
				app.sliders[i].destroy();
			}
		}
	});
}
catch(e) {
	// $.log(e.message);
}
