;(function($) {
	
	var BEHAVIOUR_PREFIX = "fd";
	var BEHAVIOUR = {};
	
	
	BEHAVIOUR.logos = function()
	{
		var _this = $(this);
		if (_this.data("__autoscroll"))
			return this;
		_this.data("__autoscroll", "true");
		
		function init() 
		{
			_this.show();
			var w = 0;
			_this.find('li').each(function(i,k) {
				w += $(k).width() + 10;
			});
			_this._clones = 2;
			if(w<$(window).width())
				_this._clones = 3;
			var $ul = _this.find('ul');
			for (var i = 1; i<_this._clones; i++) {
				$ul.clone().appendTo(_this);
			}
			_this.find('ul').each(function(i,k) {
				$(k).css('left',w*i+'px').css('position','absolute').css('width',w)
			})
			_this.wrapInner('<div class="fd-logos-clip" style="width:'+w*_this._clones+'px" />')
			_this.show();
			_this.hover(stopMove,startMove);
			startMove();
		}
		
		function startMove() {
			_this._interval = setInterval (move,40);
		}
		
		function stopMove() {
			clearInterval(_this._interval)
		}
		
		function move() {
			_this.find('ul').each(function(i,k) {
				var ul = $(k),
					l = ul.position().left-1,
					w = ul.width();
				if(-l>w)
					l+=w*_this._clones
				ul.css('left',l+'px');
			})
		}

		if (!$.windowLoaded) {
			$(window).load(init);
		} else {
			init();
		}
		return this;
	}
	
	BEHAVIOUR.filters = function() {
		
		var _this = $(this);
		if (_this.data("__filters"))
			return this;
		_this.data("__filters", "true");
		
		$.require("jquery.isotope.js");
		
		function init()
		{

			_this.find('h3').append('<span class="switch"><span class="label">Vista</span><span class="icon grid active" title="Griglia"></span><span class="icon list" title="Lista"></span></span>');
			_this.find('.icon').click(function(){
				switchView($(this));
			})
			
			var cols = [5,5,5];
			$('.fd-brand-grid').parent().prepend('<div class="fd-brand-list"></div>');
			$('.fd-brand-list').hide();
			var set = "";
			var counter = 0;
			var col = 0;
			var $col = $('<div class="col"/>').appendTo('.fd-brand-list');
			
			$('.fd-brand-grid .brand-logo').each(function(i,k){
				var c = $(k).attr('class');
				var t = $(k).find('a').attr('title');
				var u = $(k).find('a').attr('href');
				var firstLetter = t.substring(0,1);
				if(!isNaN(firstLetter)) {
					firstLetter = '1';
				}
				if(set!=firstLetter) {
					set = firstLetter;
					counter++;
					if(counter>cols[col]) {
						counter = 1;
						$col = $('<div class="col" />').appendTo('.fd-brand-list');
					}
					$div = $('<div><h3>'+firstLetter+'</h3></div>').appendTo($col);
					$ul = $('<ul />').appendTo($div);
				}
				$li = $('<li class="'+c+'"><a href="'+u+'">'+t+'</a></li>').removeClass('brand-logo').appendTo($ul);
			})
			
			$('.fd-brand-grid').isotope();
			
			_this.find('a').click(function(ev){
				ev.preventDefault();
			  	filterBrand($(this));
			});
		}
		
		switchView = function(el)
		{
			if(!el.hasClass('active')){
				_this.find('.icon').removeClass('active');
				el.addClass('active');
				$('.fd-brand-grid, .fd-brand-list').hide();
				if(el.hasClass('grid')){
					$('.fd-brand-grid').show();
				} else {
					$('.fd-brand-list').show();
				}
			}
		}
		
		filterBrand = function(el)
		{
			$('.fd-filters a').removeClass('active');
			el.addClass('active');
			var filter = el.attr('data-filter');
			$('.fd-brand-grid').isotope({ filter: filter });
			$('.fd-brand-list ul, .fd-brand-list li').show(); 
			$('.fd-brand-list li:not('+filter+')').hide();
			$('.fd-brand-list div').each(function(i,k){
				var flag = false;
				$(k).find('li').each(function(i,j){
					if($(j).css('display')!='none') flag = true;
				})
				if(flag) {
					$(k).show();
				} else {
					$(k).hide();
				}
			})

		}
		
		init();
		return this;
	}
	
	
	BEHAVIOUR.roller = function() {
		
		var _this = $(this);
		if (_this.data("__roller"))
			return this;
		_this.data("__roller", "true");
		
		function init() 
		{
			_this.data('counter', 1);
			_this.data('step',$('#roller-content').height());
			_this.data('marker', 0);
			items = _this.find('.roller-item');
			items.each(function(i,k){
				$(k).css('position','absolute').css('top',i*_this.data('step'));
			})
			$('#roller-header').append('<span id="roller-date"></span><span id="roller-pager"><span id="roller-counter"></span>&nbsp;di '+items.length+'</span>');
			_this.prepend('<div id="roller-prev"><span class="roller-arrow"></span><span class="roller-title"></span></div>');
			_this.append('<div id="roller-next"><span class="roller-title"></span><span class="roller-arrow"></span></div>');
			$('#roller-content').wrapInner('<div id="roller-content-items">');
			$('#roller-prev .roller-arrow').click(function(){roll(-1)});
			$('#roller-next .roller-arrow').click(function(){roll(1)});
			update();
			
		}
		
		function update()
		{
			var c = _this.data('counter');
			$('#roller-counter').text(c);
			var nextItem  = $(items[(c==items.length) ? 0 : c]);
			var prevItem = $(items[(c==1) ? items.length-1 : c-2]);
			$('#roller-prev .roller-title').text(prevItem.find('h2').text());
			$('#roller-next .roller-title').text(nextItem.find('h2').text());
			var date = $(items[c-1]).find('p.date').text();
			$('#roller-date').text(date);
			
		}
		
		function roll(direction) 
		{
			var c = _this.data('counter');
			var currentX = $(items[c-1]).position().top;
			if(items.length>2 || (items.length==2 && direction == 1)) {
				var nextItem  = $(items[(c==items.length) ? 0 : c]);
				var nextX = nextItem.position().top;
				if(nextX<currentX) {	
					nextItem.css('top',nextX+(_this.data('step'))*items.length);
				}
			}
			if(items.length>2 || (items.length==2 && direction == -1)) {
				var prevItem = $(items[(c==1) ? items.length-1 : c-2]);
				var prevX = prevItem.position().top;
				if(prevX>currentX) {
					prevItem.css('top',prevX-(_this.data('step'))*items.length);
				}
			}
			var newCounter = c + direction;
			if(newCounter>items.length) newCounter = 1;
			if(newCounter<1) newCounter = items.length;
			_this.data('counter', newCounter);
			
			_this.data('marker', _this.data('marker')+direction);
			
			update();
			move(direction);
		}
		
		function move(direction) 
		{
			var el = $('#roller-content-items');
			var t = el.css('top');
			t = t.substring(0, t.length-2);
			el.stop().animate({
				top:-_this.data('step')*_this.data('marker')
			})
		}
		
		init();
		return this;
	}
	
	
	BEHAVIOUR.widegallery = function() {
		
		var _this = $(this);
		if (_this.data("__widegallery"))
			return this;
		_this.data("__widegallery", "true");
		
		$.require("jquery.scrollTo.js");
		
		var _counter = 0;
		var _images = _this.find('img').length;
		
		function init() 
		{
			var label = 'Visualizza immagine';
			if(_this.find('img').length>1)
				label = 'Visualizza gallery';
			_this.wrapInner('<div class="fd-widegallery-items"/>');
			_this.append('<div class="fd-widegallery-loading"><img src="img/loading.gif" /></div>');
			_this.append('<div class="fd-widegallery-preview"><div class="fd-widegallery-screen"></div><div class="fd-widegallery-open">'+label+'</div></div>');
			_this.append('<div class="fd-widegallery-shadow"></div>');
			_this.append('<div class="fd-widegallery-close"></div>');
			_this.append('<div class="fd-widegallery-nav"><div class="fd-widegallery-arrow fd-widegallery-prev"></div><div class="fd-widegallery-arrow fd-widegallery-next"></div><div class="fd-widegallery-title"></div><div class="fd-widegallery-subtitle"></div></div>');
			_this.find('.fd-widegallery-open').click(function(){
				showImages();
			})
			_this.find('.fd-widegallery-next').click(function(){
				nextImage();
			})
			_this.find('.fd-widegallery-prev').click(function(){
				prevImage();
			})
			_this.find('.fd-widegallery-close').click(function(){
				close();
			})
			_this._loading = _this.find('.fd-widegallery-loading');
			_this._preview = _this.find('.fd-widegallery-preview');
			_this._nav = _this.find('.fd-widegallery-nav');
			_this._items = _this.find('.fd-widegallery-items');
			_this._item = _this.find('.fd-widegallery-item');
			_this._images = _this.find('.fd-widegallery-item img');
			_this._close = _this.find('.fd-widegallery-close');
			if(_images==1) {
				_this.find('.fd-widegallery-arrow').hide()
				_this._nav.addClass('fd-widegallery-single')
			}	
			_this._preview.hide()
		}
		
		function setup()
		{
			_this._items.find('img:eq(0)').clone().prependTo(_this._preview);
			_this._preview.show().find('img').resizeImage({
				width: $(window).width(),
				center:true
			});
			_this._preview.hide();
			_this._items.css('visibility','hidden');
			_this._item.css('visibility','visible');
			_this._items.find('img').css('visibility','hidden');
			_this.hover(function() {
				if(_this._preview.css('display')=='none') {
					_this._close.show();
					_this._nav.show();
				}
			},function() {
				_this._close.hide();
				_this._nav.hide();
			})
			showPreview();
		}
		
		function showPreview ()
		{		
			_this._loading.hide();
			_this._preview.fadeIn();	
		}
		
		function showImages() 
		{
			_this._preview.hide();
			_this.animate({
				height:588},
				function() {
					_this._images.resizeImage({width:940,height:_this.height(),center:true});
					$.scrollTo(_this,300);
					showImage(0);
				}
			)
		}
		
		function showImage(n)
		{	
			_this._items.css('visibility','visible');
			_this._images.css('visibility','hidden');
			var item = _this._items.find('div:eq('+n+')');
			var title = item.find('h3').html();
			
			if(_images>1 || title) {
				_this.find('.fd-widegallery-title').html(title);
				_this.find('.fd-widegallery-subtitle').text(item.find('p').text());
				_this._nav.show();
				_this._nav.css('visibility','visible');
			} else {
				_this._nav.css('visibility','hidden');	
			}
			_this._close.show()
			item.find('img').css('visibility','visible').hide().fadeIn();
		}
		
		function nextImage() 
		{
			_counter++;
			if(_counter==_images)
				_counter=0;
			showImage(_counter)
		}
		
		function prevImage()
		{
			_counter--;
			if(_counter<0)
				_counter = _images-1;
			showImage(_counter)
		}
		
		function close() 
		{
			_this._items.css('visibility','hidden');
			_this._images.css('visibility','hidden');
			_this._nav.hide();
			_this._close.hide();
			$.scrollTo($('body'),200);
			_this.animate({
				height:200},
				function() {
					
					showPreview();
				}
			)	
		}
		
		init();
		
		if (!$.windowLoaded) {
			$(window).load(setup);
		} else {
			setup();
		}
			
		return this;
	}
	
	BEHAVIOUR.gmaps = function() {
		
		var _this = $(this);
		if (_this.data("__gmaps"))
			return this;
		_this.data("__gmaps", "true");
		
		$.require("jquery.scrollTo.js");
		$.require("jquery.toggleval.js");
		
		_this.data('open',false);
		
		function init()
		{
			var lan = Number(_this.find('.fd-gmaps-lat').text());
			var lng = Number(_this.find('.fd-gmaps-lng').text());
			_this.append('<div class="fd-gmaps-map" id="map_canvas"/>');
			_this.append('<div class="fd-gmaps-shadow"></div>');
			_this.append('<div class="fd-gmaps-screen"><div class="fd-gmaps-open">Visualizza mappa</div></div>');
			_this.append('<div class="fd-gmaps-close"></div>');
			
			_this.find('.fd-gmaps-open').click(function() {open()})
			_this.find('.fd-gmaps-close').click(function() {close()})
			
			_this._latlng = new google.maps.LatLng(lan, lng);
		    var myOptions = {
		      zoom: 13,
		      center: new google.maps.LatLng(lan, lng+0.04),
		      mapTypeId: google.maps.MapTypeId.ROADMAP
		    }
			_this.map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
			_this._directions = new google.maps.DirectionsRenderer();
			_this._directions.setMap(_this.map);
			
			
			var marker = new google.maps.Marker({
			      position: _this._latlng, 
			      map: _this.map
			  });
		    
			$('#fd-gmaps-search input').toggleVal();
			$('#fd-gmaps-search input').keydown(function() {
				$('#fd-gmaps-search .error').hide();
			})
			$('#fd-gmaps-search input').focus(function() {
				$('#fd-gmaps-search .error').hide();
			})
			$('#fd-gmaps-search span').click(function(){
				$('#fd-gmaps-search').submit();
			})
			$('#fd-gmaps-search').submit(function() {
				if($('#fd-gmaps-search input').hasClass('focused') || $('#fd-gmaps-search input').hasClass('changed')) {
					findDirection();
				}
				return false;
			})
		}
		
		function open(cb)
		{
			_this.find('.fd-gmaps-screen').hide();
			_this.find('.fd-gmaps-map').animate({
				height:600},
				function() {
					$.scrollTo(_this,300);
					google.maps.event.trigger(_this.map, "resize");
					_this.find('.fd-gmaps-close').show();
					_this.data('open',true);
					if(cb) {
						cb();
					}
				}
			)
		}
		
		function close()
		{
			_this.find('.fd-gmaps-close').hide();
			$.scrollTo($('body'),200);
			_this.find('.fd-gmaps-map').animate({
				height:200},
				function() {
					google.maps.event.trigger(_this.map, "resize");
					_this.find('.fd-gmaps-screen').show();
					_this.data('open',false);
				}
			)
		}
		
		function findDirection()
		{
			var from = $('#fd-gmaps-search input[type=text]').val();
			if(from) {
				var request = {
				  origin: from,
				  destination: _this._latlng,
				  travelMode: google.maps.TravelMode.DRIVING
				}
				var directions = new google.maps.DirectionsService();
				directions.route(request, function(result, status) {
					renderDirections(result, status)
				});
				
			}
		}
		
		function renderDirections(result, status)
		{
			$('#fd-gmaps-search .error').hide();
			if (status == google.maps.DirectionsStatus.OK) {
				if(_this.data('open')) {
					 _this._directions.setDirections(result);
				} else {
					_this._result = result;
					open(function() {
						_this._directions.setDirections(_this._result);
						delete _this._result;
					})
				}
		    } else {
				$('#fd-gmaps-search .error').show();
			}
		}
		
		if (!$.windowLoaded) {
			$(window).load(init);
		} else {
			init();
		}
		
		return this;
	}
	
	BEHAVIOUR.roundimage = function() {
		
		var _this = $(this);
		if (_this.data("__roundimage"))
			return this;
		_this.data("__roundimage", "true");
		
		$.require("jquery.fancybox.js");
		
		function init() 
		{
			_this.prepend('<div class="mask" />');
			if(_this.find('a').length>0)
			{
				_this.prepend('<div class="plus" />');
				_this.addClass('active');
				_this.click(function() {
					gallery();
				})
			}
		}
		
		function gallery()
		{
			var items = []
			_this.find('a').each(function(i, k) { 
				items[i] = {href:$(k).attr('href'),title:$(k).text()}
			});
			$.fancybox(items, {
				'cyclic':true,
				'centerOnScroll':true,
				'overlayColor':'#333',
				'overlayOpacity':0.4,
				'titlePosition':'inside',
				'padding':0,
				'titleFormat': function (title, currentArray, currentIndex, currentOpts) {
			    	return  '<span class="counter"><strong>' + (currentIndex + 1) + '</strong> di ' + currentArray.length + '</span>' + (title && title.length ? title : '' );
				}
			});
		}
		
		init();
		
		return this;
		
		
	}
	
	BEHAVIOUR.newsletterbar = function() {
		
		var _this = $(this);
		if (_this.data("__newsletterbar"))
			return this;
		_this.data("__newsletterbar", "true");
		
		$.require("jquery.toggleval.js");
		
		_this.find('input').toggleVal();
		_this.find('form').submit(function() {
			var input = _this.find('input');
			input.val(input.val().replace(/^\s+/, '').replace(/\s+$/, ''))
			if(!(input.hasClass('focused') || input.hasClass('changed')) || input.val()=="") {
				return false;
			}
		});
		_this.find('a').click(function(ev){
			ev.preventDefault();
			_this.find('form').submit();
		});
		
		return this;
	}
	
	BEHAVIOUR.loginbar = function() {
		
		var _this = $(this);
		if (_this.data("__loginbar"))
			return this;
		_this.data("__loginbar", "true");
		
		$.require("jquery.toggleval.js");
		
		
		_this._email = _this.find('input[name=email]');
		_this._password = _this.find('input[name=password]');
		_this._password.after('<input type="text" name="fakepassword" value="Password"/>');
		_this._fakepassword = _this.find('input[name=fakepassword]');
		_this._fakepassword.after('<input type="submit" class="submit" />');
		
		_this._email.toggleVal({
			populateFrom: "custom",
			text: "Username"
		});
		_this._password.toggleVal({
			populateFrom: "custom",
			text: ""
		});
		_this._password.hide();
		
		_this._fakepassword.focus(function() {
			_this._fakepassword.hide();
			_this._password.show();
			_this._password.focus();
		});
		_this._password.blur(function() {
			_this._password.val(_this._password.val().replace(/^\s+/, '').replace(/\s+$/, ''))
			if(_this._password.val()=="") {
				_this._fakepassword.show();
				_this._password.hide();
			}	
		});
		
		_this.find('form').submit(function() {
			_this._email.val(_this._email.val().replace(/^\s+/, '').replace(/\s+$/, ''));
			_this._password.val(_this._password.val().replace(/^\s+/, '').replace(/\s+$/, ''));
			if(!(_this._email.hasClass('focused') || _this._email.hasClass('changed')) || _this._email.val()=="" || _this._password.val()=="") {
				return false;
			}
			_this._fakepassword.remove();
		});
		
		_this.find('a').click(function(ev){
			ev.preventDefault();
			_this.find('form').submit();
		});
		
		return this;
	}
	
	BEHAVIOUR.newsfilter = function() {
		
		var _this = $(this);
		if (_this.data("__newsfilter"))
			return this;
		_this.data("__newsfilter", "true");
		
		_this.find('select').change(function() {
			_this.submit();
		});
		
		var m = $.getUrlVar('month');
		var y = $.getUrlVar('year');
		if(m)
			_this.find('select[name=month] option[value='+m+']').attr('selected','selected')
		if(y)
			_this.find('select[name=year] option[value='+y+']').attr('selected','selected')
		
		return this;
	}
	
	BEHAVIOUR.pressfilter = function() {
		
		var _this = $(this);
		if (_this.data("__pressfilter"))
			return this;
		_this.data("__pressfilter", "true");
		
		$fm = _this.find('select[name=from-month]');
		$fy = _this.find('select[name=from-year]');
		$tm = _this.find('select[name=to-month]');
		$ty = _this.find('select[name=to-year]');
		$k = _this.find('input');
		
		function init() 
		{
			_this.find('.submit a').click(function(ev) {
				ev.preventDefault();
				checkForm();
			});
			
			$k.keypress(function(ev){
			  	if(ev.keyCode == 13){
					ev.preventDefault();
			    	checkForm();
			  	}
			});
			$k.keydown(function(ev){
			  	if(ev.keyCode == 13){
					ev.preventDefault();
			    	checkForm();
			  	}
			});
			
			var fm = $.getUrlVar('from-month');
			var fy = $.getUrlVar('from-year');
			var tm = $.getUrlVar('to-month');
			var ty = $.getUrlVar('to-year');
			var k = $.getUrlVar('keyword');

			if(fm) $fm.val(fm);
			if(fy) $fy.val(fy);
			if(tm) $tm.val(tm);
			if(ty) $ty.val(ty);
			if(k) $k.val(k);
				
			$fm.change(function(){
				var fm = $fm.val(), fy = $fy.val(), tm = $tm.val(), ty = $ty.val();	
				if(fm==0) {
					$fy.val(0);
				} else{
					if(fy==0) {
						if(ty!=0) {
							$fy.val(ty);
							if(fm>tm) $fy.val($fy.find('option[value='+(ty-1)+']').length>0 ? (ty-1) : ty);	
						} else {
							$fy.val($fy.find('option:first').next().attr('value'));
						}
					}
				}
				checkDate('from');
			});
			
			$fy.change(function(){
				if($fy.val()==0) {
					$fm.val(0);
				} else if ($fm.val()==0) {
					$fm.val(1);
				}
				checkDate('from');
			});
			
			$tm.change(function(){
				var fm = $fm.val(), fy = $fy.val(), tm = $tm.val(), ty = $ty.val();
				if(tm==0) {
					$ty.val(0);
				} else {
					if(ty==0) {
						ty = $ty.find('option:first').next().attr('value');
						$ty.val(ty);
						if(fy!=0 && !ty>fm && fm>tm) $fm.val(tm);
					}
				}
				checkDate('to')
			});
			
			$ty.change(function(){
				if($ty.val()==0) {
					$tm.val(0);
				} else if ($tm.val()==0) {
					$tm.val(1);
				}
				checkDate('to')
			});
			
		}
		
		function checkDate(source)
		{
			var fm = $fm.val(), fy = $fy.val(), tm = $tm.val(), ty = $ty.val();
			if(ty!=0 && fy!=0) {
				if(source=='from') {
					if(ty<=fy) {
						$ty.val(fy);
						if(fm>tm) $tm.val(fm)
					}
				} else {
					if(ty<=fy) {
						$fy.val(ty);
						if(fm>tm) $fm.val(tm)
					}
				}
			}
		}
		
		function checkForm()
		{
			if($fy.val()!=0 || $ty.val()!=0 || $k.val()!='') _this.submit();
		}
		
		init();
		
		return this;
	}
	
	BEHAVIOUR.sharetool = function() {
		var _this = $(this);
		if (_this.data("__sharetool"))
			return this;
		_this.data("__sharetool", "true");
		
		function init()
		{
			var url = encodeURI(window.location.href);
			var title = $('title').text();
			var subject = "Fashion District";
			if($('body').hasClass('man')) subject+= " - Mantova Outlet";
			if($('body').hasClass('mol')) subject+= " - Molfetta Outlet";
			if($('body').hasClass('val')) subject+= " - Valmontone Outlet";
			var body = 'Un amico ti suggerisce questo link%0A%0A'+title+'%0A%0A'+url 
			_this.append('<a href="mailto:?subject='+subject+'&body='+body+'" class="mail-button" title="Invia questa pagina"></a>')
			_this.append('<a href="http://twitter.com/share" class="twitter-share-button" data-count="none"> </a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>')
			_this.append('<g:plusone size="medium" count="false"></g:plusone>');
			_this.append('<script type="text/javascript">(function() { var po = document.createElement(\'script\'); po.type = \'text/javascript\'; po.async = true; po.src = \'https://apis.google.com/js/plusone.js\'; var s = document.getElementsByTagName(\'script\')[0]; s.parentNode.insertBefore(po, s);})();</script>');
			_this.append('<iframe class="fb-button" src="http://www.facebook.com/plugins/like.php?href='+url+'&layout=button_count&show_faces=false&send=false&node_type=link&locale=en_US&width=90&font=verdana" scrolling="no" frameborder="0" style="border:none; width:90px; height:20px"></iframe>');
		}
		
		if (!$.windowLoaded) {
			$(window).load(init);
		} else {
			init();
		}
		
		return this;
	}
	
	BEHAVIOUR.newsletter = function() {
		
		var _this = $(this);
		if (_this.data("__newsletter"))
			return this;
		_this.data("__newsletter", "true");
		
		_this.data('__privacy',false);
		
		_this.find('p.privacy a').click(function(ev) {
			ev.preventDefault();
			var el = _this.find('#form-privacy-text');
			if(!_this.data('__privacy')) {
				el.slideDown();
				_this.data('__privacy',true);
			} else {
				el.slideUp();
				_this.data('__privacy',false);
			}
		})
		_this.find('#form-submit a').click(function(ev) {
			ev.preventDefault();
			_this.submit();
		});
		
		return this;
	}
	
	BEHAVIOUR.repository = function() {
		var _this = $(this);
		if (_this.data("__repository"))
			return this;
		_this.data("__repository", "true");
		
		init = function()
		{
			var $h2 = _this.find('h2');
			var $ul = _this.find('ul');
			$ul.last().addClass('last');
			$h2.last().addClass('last');
			$h2.wrapInner('<span class="toggle" />');
			$h2.each(function(i,k) {
				var n = $(k).next().find('li').length;
				var label = n>1 ? 'Files' : 'File';
				$(k).append('<span class="label" >'+n+' '+label+'</span>');
			})
			$h2.find('.toggle').prepend('<span class="icon" />').click(function(){
				toggle(this);
			})
			$ul.append('<li class="last" />');
			_this.find('a').each(function() {
				var url = $(this).attr('href');
				url = url.split('.');
				$(this).parent().addClass(url[url.length-1].toLowerCase());
			})
		}
		
		toggle = function(el)
		{
			var t = $(el).parent();
			if(!t.hasClass('open')) {
				closeAll();
				t.addClass('open');
				t.next().slideDown();
			} else {
				closeAll();
			}
		}
		
		closeAll = function()
		{
			_this.find('h2').removeClass('open');
			_this.find('ul').slideUp();
		}
		
		init();
		return this;
	}
	
	BEHAVIOUR.inputfile = function() {
		var _this = $(this);
		if (_this.data("__inputfile"))
			return this;
		_this.data("__inputfile", "true");
		
		init = function()
		{
			_this.wrap($("<span></span>").addClass("fileWrapper")); 
			var wrapper = _this.parent();
			var file = wrapper.find("input[type=file]");
			var label = $("<span></span>").html(file.val()).addClass("label").prependTo(wrapper);
			var button = $("<span></span>").html(file.attr("title")).addClass("button").css({ "cursor": "pointer", "display": "inline-block" }).prependTo(wrapper);
			wrapper.css({ "cursor": "pointer", "display": "inline-block", "overflow": "hidden", "position": "relative" }).addClass(file.attr("class"));
			file.css({ "filter": "alpha(opacity=1)", "-moz-opacity": 0.01, "-khtml-opacity": 0.01, "opacity": 0.01, "font-size": "100px", "height": "100%", "position": "absolute", "right": 0, "top": 0, "cursor": "pointer" });
			file.change(function () { 
				var p = file.val().split('\\');
				label.html(p[p.length-1]);
			});
		}
		init();
		return this;
	}
	
	BEHAVIOUR.career = function() {
		
		var _this = $(this);
		if (_this.data("__career"))
			return this;
		_this.data("__career", "true");
		
		_this.find('#form-submit a').click(function(ev) {
			ev.preventDefault();
			_this.submit();
		})
		return this;
	}
	
	BEHAVIOUR.coda = function() {
		
		var _this = $(this);
		if (_this.data("__coda"))
			return this;
		_this.data("__coda", "true");
		
		_this.data('counter',0);
		
		init = function()
		{
			$(window).blur(function(){
			    _this.WindowHasFocus =false;
			}).focus(function(){
			    _this.WindowHasFocus =true;
			});
			
			
			var w = _this.width();
			var h = 0;
			var $d = _this.find('div');
			$d.css('position','absolute').css('top','0').css('width',w+'px').addClass('fd-coda-item');
			$d.each(function(i,k){
				if($(k).height()>h) h = $(k).height();
				$(k).css('left',w*i+'px');
			})
			h+=20;
			newh = _this.parents('.page-cols').height()-_this.parents('.page-cols').find('h2').outerHeight(true);
			if(newh>h) h = newh;
			_this.css('overflow','hidden').css('position','relative').css('height',h+'px');
			var $nav = $('<div class="fd-coda-nav" />').appendTo(_this);
			for (var i=1;i<=$d.length;i++) {
				$nav.append('<span class="fd-coda-button" data="'+(i-1)+'"></span>');
			}
			_this.find('.fd-coda-button:first').addClass('active');
			_this.find('.fd-coda-button').click(function(){
				clearInterval(_this.interval);
				slide($(this));
				_this.interval = setInterval(autoRun,10000);
			});
			_this.interval = setInterval(autoRun,5000);
		}
		
		slide = function(el) {
			_this.data('counter',Number(el.attr('data')));
			_this.find('.fd-coda-button').removeClass('active');
			el.addClass('active');
			var w = _this.width();
			_this.find('.fd-coda-item').each(function(i,k){
				var l = (w*i)-(w*Number(el.attr('data')));
				$(k).animate({
					left:l
				},500)
			});
		}
		
		autoRun = function() {
			clearInterval(_this.interval);
			if(_this.WindowHasFocus) {
				var c = _this.data('counter');
				c++;
				if(c>_this.find('.fd-coda-button').length-1) {
					c = 0;
				}
				slide(_this.find('.fd-coda-button[data='+c+']'));
			}	
			_this.interval = setInterval(autoRun,5000);
		}
		
		init();
		return this;
	}
	
	/**
	 * bugfix
	 */
	
	$.fn.bugFix = function() {
		/* select bug con safari */
		if($.browser.webkit && !window.chrome)
		{
			$('select').css('font-family','"Lucida Grande",sans-serif');
		}
		$('.fd-widegallery').next().prepend('<span></span>');
	}
	
	
	/**
	 * common
	 */
	
	$.fn.resizeImage = function(params) {
		
		if(!params.width && !params.height)
			return this;
		
		this.removeAttr('height').removeAttr('width');
		this.css('height','auto').css('width','auto').css('top',0).css('left',0);
		
		this.each(function(i,k){
			_this = $(k)
			var h = _this.height();
			var w = _this.width();
			var ratio = w / h;
			if(params.width) 
			{
				_this.width(params.width);
				_this.height(Math.round(params.width / ratio))
				if(params.height && params.height<_this.height()) 
				{
					_this.height(params.height);
					_this.width(Math.round(params.height * ratio))
				}
			} else {
				_this.height(params.height);
				_this.width(Math.round(params.height * ratio))
			}

			//needs parent with css position absolute or relative
			if(params.center)
				_this.css('position','absolute').css('left',-Math.round((_this.width()-_this.parent().width())/2)+'px').css('top',-Math.round((_this.height() - _this.parent().height())/2)+'px');
		})
		
		return this;
	}
	
	$.getUrlVars = function()
	{
		var vars = [], hash;
		var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
		for(var i = 0; i < hashes.length; i++)
		{
			hash = hashes[i].split('=');
			vars.push(hash[0]);
			vars[hash[0]] = hash[1];
		}
		return vars;
	}
	
	$.getUrlVar = function(name)
	{
		return $.getUrlVars()[name];
	}
	
	$.getResourceBaseUri = function()
	{
		if (!$.cmResourceBaseUri)
		{
			var s = $("head>link").attr("href");
			$.cmResourceBaseUri = s.substring(0,s.lastIndexOf("/res/")+5);
		}
		return $.cmResourceBaseUri;
	}

	$.require = function(scr)
	{
		if (!$.require[scr])
		{
			$.require[scr] = true;
			var scriptBase = $.getResourceBaseUri() + "js/lib/";
			//var scriptBase = "js/lib/"
			$("head").append("<scr" + "ipt type=\"text/javascript\" src=\"" + scriptBase + scr + "\"></script>");
		}
	}
	
	if (!window.console)
		window.console = {log:function(){}}
	
	$.fn.GUI = function()
	{
	
		// setup plugins	
		for (var p in BEHAVIOUR)
		{
			$.fn[BEHAVIOUR_PREFIX + p] = BEHAVIOUR[p];
			$(this).find("." + BEHAVIOUR_PREFIX + "-" + p).each(function()
			{
				$(this)[BEHAVIOUR_PREFIX + p]();
			})
		}
	}
	
	$(document).ready(function()
	{
		$('html').GUI();
		$('html').bugFix();
	})
	
	$(window).load(function()
	{
		$.windowLoaded = true;
	})
	
	
})(jQuery);






