var bocci;

function Bocci() {
	var self = this;
	this.img_path = '/themes/bocci/img';
	this.slide_timer;
	this.page_loading = false;
	
	this.showLoading = function() {
		var $loading = $('#loading');
		if (!$loading.get(0)) {
			$('body > header nav').append('<div id="loading"><img src="' + self.img_path + '/loading.gif" /></div>');
		}
		$loading.show();
	};
	
	this.hideLoading = function() {
		$('#loading').hide();
	};

	this.resizeVideo = function() {
		var $con = $('#content.videos');
		if (!$con.get(0)) return;
		var $iframe = $('iframe', $con);
		var w = $iframe.width();
		var h = $iframe.height();
		var new_w = $('.wrap', $con).width();
		var new_h = new_w * h / w;
		$iframe.width(new_w).height(new_h);
	};
	
	this.getPage = function(url, callback, get_slides) {
		self.showLoading();
		self.page_loading = true;
		if (get_slides) {
			ss.clearTimer();
		}
		_gaq.push(['_trackPageview', url]);
		$.getJSON(url, {ajax:1, slides: get_slides}, function(data) {
			if (data.title) {
				document.title = $("<div/>").html(data.title).text();
			}
			if (get_slides) {
				$('.slides').remove();
				if (data.slides) {
					$('body > header').after(data.slides);
					ss = new self.SlideShow();
				}
			}
			callback(data.content);
			self.hideLoading();
			self.page_loading = false;
		});
	};
	
	this.addUpArrow = function() {
		var $con = $('#content');
		var $arrow = $('<a href="" class="collapse"><span class="c-wrap"><span class="arrow"></span></span></a>');
		$con.wrapInner('<div class="collapsible"></div>');
		$con.append($arrow);
		$arrow.toggle(function() {
			var $anch = $(this);
			$('.collapsible', $con).slideUp(function() {
				$anch.addClass('down');
			});
			return false;
		},
		function() {
			var $anch = $(this);
			$('.collapsible', $con).slideDown(function() {
				$anch.removeClass('down');
			});
			return false;
		});
	};
	
	this.addAboutUpArrow = function() {
		var $con = $('#content');
		$('.up-arrow', $con).each(function() {
			var $el = $(this);
			var $arrow = $('<a href="" class="collapse-arrow"></a>');
			$el.append($arrow);
			$arrow.click(function() {
				$el.slideUp();
				return false;
			});
		});
	};
	
	this.pageLoad = function(page, id, href) {
		var $con = $('#content');
		var $anch = $('#' + id);

		if (page == 'about') {
			$('.nav', $con).removeClass('current section');
			$anch.addClass('current');
			$('.page .wrap', $con).slideUp();
			self.getPage(href, function(data) {
				$con.replaceWith(data);
				$('#content').position_below_header();
				$('#content .page .wrap').hide().slideDown();
				self.initContentEvents();
			});
		}
		else if (page == 'press') {
			$('.paging a', $con).removeClass('current section');
			$anch.addClass('current');
			self.getPage(href, function(data) {
				var replace = function() {
					$con.replaceWith(data);
					$('#content').position_below_header();
					$('#content .items').hide().slideDown();
					self.initContentEvents();
				};
				if ($('.items', $con).get(0)) {
					$('.items', $con).slideUp(replace);
				}
				else {
					replace();
				}
			});
		}
		else if (page == 'dealers') {
			$('#content .dealers').slideUp();
			self.getPage(href, function(data) {
				$con.replaceWith(data);
				$('#content').position_below_header();
				$('#content .dealers .wrap').hide().slideDown();
				self.initContentEvents();
			});
		}
		else if (page == 'collection-listing') {
			$('.menu-1 a', $con).removeClass('current section');
			$anch.addClass('current');
			$('.menu-2, .container', $con).slideUp();
			self.getPage(href, function(data) {
				$con.replaceWith(data);
				$('#content').position_below_header();
				$('#content .menu-2').hide().slideDown();
				self.initContentEvents();
			}, 1);
		}
		else if (page == 'collection') {
			$('.menu-2 a', $con).removeClass('current section');
			$anch.addClass('current');
			$('.container', $con).slideUp();
			self.getPage(href, function(data) {
				$con.replaceWith(data);
				$('#content').position_below_header();
				$('#content .container').hide().slideDown();
				self.initContentEvents();
			});
		}
		else if (page == 'collection-product') {
			$('.thumbs ul a', $con).removeClass('current section');
			$anch.addClass('current');
			self.getPage(href, function(data) {
				$('.products .wrap', $con).slideUp(function() {
					$con.replaceWith(data);
					$('#content').position_below_header();
					var $wrap = $('#content .products .wrap');
					$wrap.hide();

					$img = $('#content .products .wrap img');
					var img_obj = new Image();
					$(img_obj).load(function() {
						$wrap.slideDown();
					});
					var src = $img.attr('src');
					if ($.browser.msie) { // IE cached image bug
						src += '?' + new Date().getTime();
					}
					img_obj.src = src;
					
					self.initContentEvents();
				});
			});
		}
		else if (page == 'collection-gallery') {
			var old_pos;
			$('.thumbs ul a', $con).each(function(i) {
				if ($(this).hasClass('current')) {
					old_pos = i;
					return false;
				}
			});

			$('.thumbs ul a', $con).removeClass('current section');
			$anch.addClass('current');
			
			var new_pos;
			$('.thumbs ul a', $con).each(function(i) {
				if ($(this).hasClass('current')) {
					new_pos = i;
					return false;
				}
			});

			var reverse = (old_pos > new_pos);
			
			//self.carousel.revealCurrentItem();
			
			self.getPage(href, function(data) {
				var $wrap = $('.products .wrap'),
					$inner = $('.inner', $wrap),
					inner_width = $inner.width(),
					$old_photo = $('.photo-container', $inner),
					$new_photo = $(data);
				
				$old_photo.width(inner_width);
				if (reverse) {
					$new_photo.prependTo($inner);
					$inner.css('left', '-' + inner_width + 'px');
				}
				else {
					$new_photo.appendTo($inner);
				}
				$new_photo.width(inner_width);
				
				$inner.width(inner_width * 2);

				$img = $('img', $new_photo);
				var img_obj = new Image();
				$(img_obj).load(function() {
					var left = reverse ? '0' : '-' + inner_width;
					$inner.animate({'left' : left + 'px'}, 500, function() {
						$old_photo.remove();
						$new_photo.css('width', 'inherit');
						$inner.css({
							'width' : 'inherit',
							'left' : 'auto'
						});
						self.gallery.positionArrows();
					});
				});
				var src = $img.attr('src');
				if ($.browser.msie) { // IE cached image bug
					src += '?' + new Date().getTime();
				}
				img_obj.src = src;
			});
		}
		else if (page == 'video') {
			$('.thumbs ul a', $con).removeClass('current section');
			$anch.addClass('current');
			self.getPage(href, function(data) {
				$('.wrap', $con).slideUp(function() {
					$con.replaceWith(data);
					$con = $('#content');
					$con.position_below_header();
					$('.wrap', $con).hide().slideDown();
					self.initContentEvents();
				});
			}, 1);
		}
		else if (page == 'main') {
			$('body > header .menu a').removeClass('current section');
			$anch.addClass('current');
			$('#content').slideUp(function() {
				$(this).remove();
			});

			self.getPage(href, function(data) {
				$('body > header').after(data);
				$('#content')
					.hide()
					.position_below_header()
					.slideDown();
				self.initContentEvents();
			}, 1);
		}
		else if (page == 'home') {
			$('body > header .menu a').removeClass('current section');
			$('#content').slideUp(function() {
				$(this).remove();
			});
			
			self.getPage('/', function(data) {
				self.initContentEvents();
			}, 1);
		}
	};
	
	this.pageClick = function(func, id) {
		if (!supports_history_api()) return true;
		if (self.page_loading) return false;
		
		var href = $('#' + id).attr('href');
		href = href.replace(/&?ajax=1&?/, '');
		history.pushState({ 'func' : func, 'id' : id }, null, href);
		self.pageLoad(func, id, href);
		return false;
	};
	
	this.initContentEvents = function() {
		ss.addControls();
		
		var $con = $('#content');
		if (!$con.get(0)) return;
		
		$('body > .dealer-popmenu').remove();
		
		$('#content.about').each(function() {
			$('a.nav', $con).click(function() {
				if ($(this).hasClass('current')) {
					$(this).parents('.page').find('.up-arrow').slideUp();
					$(this).removeClass('current')
					return false;
				}
				else {
					return self.pageClick('about', $(this).attr('id'));
				}
			});

			//self.addAboutUpArrow();
		});
		
		$('#content.about.press').each(function() {
			$('.paging a', $con).click(function() {
				return self.pageClick('press', $(this).attr('id'));
			});			
		});
		
		$('#content.dealers').each(function() {
			$('.filter', $con).each(function() {
				$filter = $(this);
				$link = $('h2', $filter);
				$('.current', $filter).each(function() {
					$link.text($(this).text());
				});
				$('.dealer-popmenu').hide();
				$link.popmenu($('.dealer-popmenu', $filter));
			});
			
			$('.dealer-popmenu a').click(function() {
				return self.pageClick('dealers', $(this).attr('id'));
			});
			
			$('.dealers li', $con).gridify();
			
		});
		
		$('#content.videos').each(function() {
			self.carousel = new self.Carousel($('.thumbs', $con), 5);
			
			self.resizeVideo();
			
			$('.thumbs a', $con).not('.nav').click(function() {
				return self.pageClick('video', $(this).attr('id'));
			});
		});
		
		$('#content.collection').each(function() {
			self.carousel = new self.Carousel($('.products .thumbs', $con), 8);
			
			$('.specs .col-3 .more', $con).each(function() {
				var $div = $(this);
				$div.hide();
				var link = $('<p><a href="">More...</a></p>');
				var hide_link = $('<p><a href="">Hide</a></p>');
				hide_link.hide();
				$div.after(hide_link);
				$div.before(link);
				link.click(function() {
					$div.show();
					link.hide();
					hide_link.show();
					return false;
				});
				hide_link.click(function() {
					$div.hide();
					hide_link.hide();
					link.show();
					return false;
				});
			});
			
			$('.menu-1 a', $con).click(function() {
				ss.clearTimer();
				return self.pageClick('collection-listing', $(this).attr('id'));
			});
			
			$('.menu-2 a', $con).click(function() {
				return self.pageClick('collection', $(this).attr('id'));
			});

			if ($('.products.gallery').get(0)) {
				$('.products .thumbs a', $con).not('.nav').click(function() {
					return self.pageClick('collection-gallery', $(this).attr('id'));
				});
			
				ss.paused = true;
				ss.clearTimer();
				$('.slides').hide();
				$('header > .logo .controls').hide();

				self.gallery = new self.Gallery();
			}
			else {
				$('.products .thumbs a', $con).not('.nav').click(function() {
					return self.pageClick('collection-product', $(this).attr('id'));
				});
			
				ss.paused = false;
				ss.setTimer();
				$('.slides').fadeIn();
				$('header > .logo .controls').show();
			}
		});
		
		self.addUpArrow();

		$('.columnize').columnize({lastNeverTallest : true});
		
		$('#content').position_below_header();
	};
	
	this.Gallery = function() {
		var $wrap = $('.products .wrap'),
			$img = $('img', $wrap);

		var img_obj = new Image();
		$(img_obj).load(function() {
			
			$wrap.append('<nav class="controls"><a class="prev" href="">Previous</a><a class="next" href="">Next</a></nav>');
			self.gallery.positionArrows();

			$('.controls a', $wrap).click(function() {
				var $li = $('.products .thumbs a.current').parents('li'),
					$lis = $('.products .thumbs li');
				
				var $new_li;
				if ($(this).hasClass('prev')) {
					self.carousel.scroll(1);
					$new_li = $li.prev();
					if (!$new_li.get(0)) {
						$new_li = $lis.eq($lis.size()-1);
					}
				}
				else {
					self.carousel.scroll(-1);
					$new_li = $li.next();
					if (!$new_li.get(0)) {
						$new_li = $lis.eq(0);
					}
				}
				
				$('a', $new_li).trigger('click');
				
				return false;
			});

		});
		var src = $img.attr('src');
		if ($.browser.msie) { // IE cached image bug
			src += '?' + new Date().getTime();
		}
		img_obj.src = src;

		this.positionArrows = function() {
			$img = $('img', $wrap);
			$('.controls a', $wrap).height($img.height());
		};
	
	};

	this.Carousel = function($container, viewable_count) {
		if (!$container.get(0)) return;
		
		var CAR = this,
			animating = false,
			item_count = $('li', $container).size(),
			item_w = Math.floor($('li', $container).width()),
			item_margin = $('li', $container).css('padding-right');
			item_margin = parseInt(item_margin.replace('px', ''));
		
		var item_ow = item_w + item_margin;

		$('li', $container)
			.width(item_w)
			.css('padding-right', item_margin + 'px');
		
		if (item_count <= viewable_count) {
			$container.width(item_count * item_ow);
			return;
		}
		
		var item_count = $('li', $container).size(),
		carousel_width = viewable_count * item_ow - item_margin,
		ul_width = item_count * item_ow;
		
		$('ul', $container)
			.css({
				'left': 0 + 'px',
				'position': 'relative'
			})
			.wrap('<div class="clip">')
			.css('width', ul_width + 'px');

		$container
			.width(carousel_width)
			.append('<a href="#" class="nav prev"></a>')
			.append('<a href="#" class="nav next"></a>');
		
		$('li img', $container).each(function() {
			var $img = $(this);
			var img = new Image();
			$(img).load(function() {
				var item_h = Math.floor($img.height());
				$img.height(item_h);
				$('.nav', $container).css('top', item_h / 2 - $('.nav', $container).height() / 2);
			});
			var src = this.src;
			if ($.browser.msie) { // IE cached image bug
				src += '?' + new Date().getTime();
			}
			img.src = src;
		});

		$('.prev', $container).click(function() {
			CAR.scroll(1);
			return false;
		});
		
		$('.next', $container).click(function() {
			CAR.scroll(-1);
			return false;
		});
		
		this.currentLeft = function() {
			var current = $('ul', $container).css('left');
			return parseFloat(current.replace('px', ''));
		}
		
		this.scroll = function(direction) {
			if (animating) return;
			
			var current = CAR.currentLeft();
			var dist = (direction * item_ow) + current;

			if (dist > 0) {
				$('ul', $container).prepend($('li', $container).eq(item_count-1).detach());
				current = (-1 * item_ow);
				$('ul', $container).css('left', current + 'px')
				dist = 0;
			}
			else if (dist <= -1 * (ul_width - carousel_width - item_margin + item_ow)) {
				$('ul', $container).append($('li', $container).eq(0).detach());
				current = current + item_ow;
				$('ul', $container).css('left', current + 'px')
				dist = (direction * item_ow) + current;
			}
			
			animating = true;
			$('ul', $container).animate({
				left: dist + 'px'
			}, function() {
				animating = false;
				CAR.showHideControls();
			});
		};
		
		this.revealCurrentItem = function() {
			if (item_count <= viewable_count) return;
			
			var current = CAR.currentLeft();
			
			var pos = 0;
			$('li a', $container).each(function(i) {
				if ($(this).hasClass('current')) {
					pos = i;
				}
			});
			
			var item_pos = -1 * (pos+1) * item_ow;

			var dest = null;
			if (current > item_pos && current > carousel_width + item_pos) {
				dest = carousel_width + item_pos;
			}
			if (current < item_pos && current < carousel_width + item_pos) {
				dest = item_pos + item_ow;
			}
			
			if (dest != null) {
				$('ul', $container).css('left', dest + 'px');
			}
		};
		
		this.showHideControls = function() {
			var current = CAR.currentLeft();
			
			if (!current) {
				//$('.prev', $container).hide();
			}
			else {
				$('.prev', $container).show();
			}
			
			if (current <= Math.ceil(-1 * (ul_width - carousel_width - item_margin))) {
				//$('.next', $container).hide();
			}
			else {
				$('.next', $container).show();
			}
		};
		
		CAR.showHideControls();
		CAR.revealCurrentItem();
	};
	
	this.SlideShow = function() {
		var $div = $('.slides');
		if (!$div.get(0)) return;
	
		this.fadein_time = 1500;
		this.fadeout_time = 400;
		this.slide_time = 6000;
		this.transitioning = false;
		this.paused = false;
		
		this.nextSlide = function(reverse) {
			if (ss.transitioning || ss.paused) return;
			$current = $('.current', $div);
			
			if (!$current.get(0)) {
				ss.showSlide($('figure:first', $div));
				return;
			}
			
			$current.removeClass('current');
			
			if (reverse) {
				$next = $current.prev();

				if (!$next.get(0)) {
					$next = $('figure:last', $div);
				}
			}
			else {
				$next = $current.next();
			
				if (!$next.get(0)) {
					$next = $('figure:first', $div);
				}
			}

			ss.transitioning = true;
			$overlay.fadeIn(ss.fadeout_time, function () {
				$current.hide();
				ss.showSlide($next, reverse);
			});
		};
		
		this.showSlide = function($slide, reverse) {
			ss.updateNav(reverse);
			$slide
				.addClass('current')
				.hide()
				.show();
			$overlay
				.fadeOut(ss.fadein_time, function() {
					ss.setTimer();
					ss.transitioning = false;
				});

			
			$('img', $slide).fillwindow();
		};
		
		this.setTimer = function() {
			if ($('figure', $div).size() <= 1) return;
		
			var stime = ss.slide_time;
			if ($div.hasClass('listing') || !$('#content').get(0)) {
				stime = 4000; //3000;
			}
			
			ss.clearTimer();
			self.slide_timer = setTimeout(function() {
				ss.nextSlide();
			}, stime);
		};
		
		this.updateNav = function(reverse) {
			if (!$div.hasClass('listing')) return;

			$menu = $('.menu-1');
			var $current = $('.current', $menu);
			if (!$current.get(0)) {
				$('a:first', $menu).addClass('current');
				return;
			}
			
			var li = $current.removeClass('current').parents('li');
			
			if (reverse) {
				var $next = li.prev();

				if (!$next.get(0)) {
					$next = $('li:last', $menu);
				}
			}
			else {
				var $next = li.next();				

				if (!$next.get(0)) {
					$next = $('li:first', $menu);
				}
			}
			
			$('a', $next).addClass('current');
		};
		
		this.clearTimer = function() {
			clearTimeout(self.slide_timer);
		};
		
		this.addControls = function() {
			var $header = $('header > .logo');
			$('.controls', $header).remove();

			if ($('.slides figure').size() <= 1) return;
			
			var $prev = $('<a href="" class="prev"></a>'),
			$next = $('<a href="" class="next"></a>'),
			$pause = $('<a href="" class="pause"></a>');

			$controls = $('<div class="controls" title="Use back/forward keys to navigate and spacebar to pause"></div>').appendTo($header);
			$controls.append($prev).append($pause).append($next);
			
			$prev.click(function() {
				ss.unpause();
				ss.nextSlide(true);
				return false;
			});
	
			$next.click(function() {
				ss.unpause();
				ss.nextSlide();
				return false;
			});
	
			$pause.toggle(function() {
				ss.pause();
				return false;
			}, function() {
				ss.unpause();
				return false;
			});
		};
		
		this.pause = function() {
			ss.paused = true;
			ss.clearTimer();
			$('.pause', $controls).addClass('active');
		};
		
		this.unpause = function() {
			ss.paused = false;
			ss.setTimer();
			$('.pause', $controls).removeClass('active');
		};
		
		this.sizeOverlay = function() {
			var h = $(window).height();
			var w = $('body').width();
			$overlay.css({
				'width': w + 'px',
				'height': h + 'px'
			});
		};
		
		var $controls;

		$(window).smartresize(function() {
			$('.current img', $div).fillwindow();
			ss.sizeOverlay();
		});
		
		var $overlay = $('#overlay');
		if (!$overlay.get(0)) {
			$overlay = $('<div id="overlay"></div>');
			$div.after($overlay);
		}
		this.sizeOverlay();
		
		$('figure', $div).hide();
		
		var img_obj = new Image(),
		$img = $('figure:first img', $div);
		$(img_obj).load(function() {
			$div.show().position_below_header();
			ss.nextSlide();
		});
		var src = $img.attr('src');
		if ($.browser.msie) { // IE cached image bug
			src += '?' + new Date().getTime();
		}
		img_obj.src = src;
		
		// Preload the rest of the slideshow images
		$('figure', $div).not(':first').each(function() {
			var img = new Image();
			img.src = $('img', this).attr('src');
		});
	};

	if (supports_history_api()) {
		window.addEventListener("popstate", function(e) {
			try {
				bocci.pageLoad(e.state.func, e.state.id, location.href);
			}
			catch (e) {
				//console.log('error: ' + JSON.stringify(e));
			}
		}, true);
	}
	
	if (supports_touch()) {
		$('body > header').css('position', 'relative');
	}
	
	if (!$('#content').get(0) && supports_history_api()) {
		history.pushState({ 'func' : 'home', 'id' : 'page-home' }, null, '/');
	}

	$('body > header .menu a').click(function() {
		var href = $(this).attr('href');
		if (href.match(/^https?:\/\//) && !href.match(/bocci\.ca/)) return true;
		return self.pageClick('main', $(this).attr('id'));
	});
	
	var ss = new self.SlideShow();
	var gallery, carousel;
	
	this.initContentEvents();
	
	$('#MemberLoginForm_LoginForm').each(function() {
		$('header').append('<base href="/" />');
	});

	$('body > header .social li').eq(0).addClass('first');
		
	$('body > header .langs').each(function() {
		var $div = $(this);
		$('a', $div).each(function() {
			if ($.trim($(this).text()) == 'English (US)') {
				$(this).text('English');
			}
		});

		$('.current', $div).each(function() {
			var $li = $(this),
			$link = $('a', $li);
			if ($.trim($link.text()) == 'English') {
				$link.text('Language');
			}
			$div.prepend($link);
			$li.remove();
			$link.langpopmenu($('ul', $div));
		});
	});
	
	$(window).smartresize(function() {
		self.resizeVideo();
	});

	$(document).keydown(function(e) {
		//var $controls = $('#content.collection .controls');
		//if (!$controls.get(0)) return;

		// Right Arrow key
		if (e.keyCode == 39) {
			ss.unpause();
			ss.nextSlide();
		}
		// Left Arrow Key
		else if (e.keyCode == 37) {
			ss.unpause();
			ss.nextSlide(true);
		}
		// Spacebar
		else if (e.keyCode == 32) {
			if (ss.paused) {
				ss.unpause();
			}
			else {
				ss.pause();
			}
			return false;
		}
	});
}

function supports_history_api() {
	return !!(window.history && history.pushState);
}

function supports_touch() {
	return "ontouchstart" in window;
}

(function ($) {
	
	$(document).ready(function() {
		bocci = new Bocci;
	});
	
	$.fn.position_below_header = function() {
		var h = $('body > header').height();
		return this.each(function() {
			$(this).css('top', h + 'px');
		});
	};
	
    $.fn.fillwindow = function() {
		var img = this.get(0);
		if (!img) return;
        var window_w = $('body').width(),
        window_h = $(window).height() - $('body > header').height(),
        item_w = img.width,
        item_h = img.height;

        // Try fill width first
        var new_h = Math.ceil(window_w * item_h / item_w);
        if (new_h >= window_h) {
            this.width(window_w);
        }
        // Too short, fill height first
		else {
			var new_w = Math.ceil(window_h * item_w / item_h) + 2;
			this.width(new_w);
		}
		
		// Center image
		var leftOffset = ($('body').width() / 2) - (this.width() / 2);
		var topOffset = (window_h / 2) - (this.height() / 2);
		this.css({
			'left': leftOffset + 'px',
			'top' : topOffset + 'px'
		});
		
		// Position caption
		var $caption = $('.slides .current figcaption'),
		top = window_h - $caption.height() - 40;
		$caption.css({
			'top': top + 'px',
			'bottom': 'auto'
		});
		
		return this;
    };
	
	$.fn.popmenu = function(target, event) {
		return this.each(function() {
			var t = jQuery(this);
			
			if (typeof(target) == 'string') {
				target = $(target);
			}
			
			new_target = target.clone().appendTo('body').hide();
			target.remove();
			target = new_target;
	
			var timer = null;
			var settimer = function() {
				timer = setTimeout(function() { target.fadeOut(); }, 1500);
			};
			
			var cleartimer = function() {
				if (target.css('display') == 'none') {
					var pos = t.offset();
			
					var topOffset = pos.top + t.outerHeight();
					var leftOffset = pos.left;
					var width = t.width();
		
					target.css({
						position: 'absolute',
						left: leftOffset + 'px',
						top: topOffset + 'px',
						width: width + 'px'
					});
			
					target.fadeIn();
				}
				clearTimeout(timer);
			};
			
			t.toggle(cleartimer, function () {
				target.fadeOut();
			});
			//t.mouseout(settimer);
			target.hover(cleartimer, settimer);
		});
	}
		
	$.fn.langpopmenu = function(target) {
		return this.each(function() {
			var t = jQuery(this);
			
			if (typeof(target) == 'string') {
				target = $(target);
			}
			
			target = target.clone().appendTo('body').hide();
	
			var timer = null;
			var settimer = function() {
				timer = setTimeout(function() {
					target.fadeOut();
				}, 1500);
			};
			
			var cleartimer = function() {
				if (target.css('display') == 'none') {
					var pos = t.offset();
					var pos_right = pos.left + t.width();
			
					var topOffset = pos.top + t.outerHeight();
					var leftOffset = pos_right - target.outerWidth() + 10;
		
					target.css({
						position: 'absolute',
						left: leftOffset + 'px',
						top: (topOffset - 1) + 'px'
					});
			
					target.fadeIn();
				}
				clearTimeout(timer);
			};
			
			t.toggle(cleartimer, function () {
				target.fadeOut();
			});
			//t.mouseout(settimer);
			target.hover(cleartimer, settimer);
		});
	}
	
 	$.fn.label_as_input = function() {
		
		return this.each(function() {
			var input = $(this).siblings('input[type=text],textarea').eq(0);
			var txt = $(this).text();
			
			$(this).hide();
			
			var _focus = function() {
				if (input.val() == txt) {
					input.removeClass('dim');
					input.val('');
				}
			};
			
			var _blur = function() {
				if (input.val() == '') {
					input.addClass('dim');
					input.val(txt);
				}
			};
		
			input.focus(_focus);
			input.blur(_blur);
			
			_focus();
			_blur();
			
			input.parents('form').submit(_focus);
			
			return this;
		});
	};

    $.fn.center = function() {
        // Always return each...
        return this.each(function() {
            var t = $(this);

            var leftMargin = t.width() / 2;
            var topMargin = t.height() / 2;

            if( typeof( window.pageYOffset ) == 'number' ) {
                // Netscape
                var scrollOffset = window.pageYOffset;
            } else if( document.body && document.body.scrollTop ) {
                // DOM
                var scrollOffset = document.body.scrollTop;
            } else if( document.documentElement && document.documentElement.scrollTop ) {
                // IE6 standards compliant mode
                var scrollOffset = document.documentElement.scrollTop;
            }
            else {
                var scrollOffset = 0;
            }

            var topOffset = ($(window).height() / 2) + scrollOffset - topMargin;
            var leftOffset = ($('body').width() / 2) - leftMargin;
            
            if (topOffset < 0)
                topOffset = 0;

            t.css({
                position: 'absolute',
                left: leftOffset + 'px',
                top: topOffset + 'px'
            });
        });
    };

    $.fn.gridify = function(per_row) {
        if (!per_row && this.size()) {
            var container = this.parent();
            var item = this.eq(0);
            per_row = Math.floor(container.width() / item.width());
        }
        
		var row_num = 1;
        return this.each(function(i) {
            if ((i+1) % per_row == 0) {
                $(this).addClass('last');
                
                var max_height = 0;
                var el = $(this);
                for (var x = 1; x <= per_row; x++) {
                    var h = el.height();
                    if (h > max_height)
                        max_height = h;
                    el = el.prev();
                }
                
                var el = $(this);
                for (var x = 1; x <= per_row; x++) {
                    el.height(max_height);
					el.addClass('row-' + row_num);
					el.addClass('col-' + (per_row - x + 1));
                    el = el.prev();
                }
				
				row_num++;
            }
        });
    };
		
    (function($,sr){
     
        // debouncing function from John Hann
        // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
        var debounce = function (func, threshold, execAsap) {
            var timeout;
            
            return function debounced() {
                var obj = this, args = arguments;
                function delayed() {
                    if (!execAsap)
                        func.apply(obj, args);
                    timeout = null; 
                };
                
                if (timeout)
                    clearTimeout(timeout);
                else if (execAsap)
                    func.apply(obj, args);
                
                timeout = setTimeout(delayed, threshold || 50); 
            };
        }
        // smartresize 
        jQuery.fn[sr] = function(fn){  return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };
         
    })(jQuery,'smartresize');
    
})(jQuery);

