
$(function(){
	var imgs = [];
	$('*').each(function(){
		var e = $(this);
		if(e.is('img')) imgs.push(e.attr('src'));
		var bg = $(e).css('background-image');
		if(bg && bg != 'none'){
			imgs.push(bg.replace(/^url\([\"\']?([^\"\']+)[\"\']?\)$/, '$1'));
		}
	});
	disableScroll(window);
	showPageLoading();
	preloadImages(imgs, function(){
		hidePageLoading();
		enableScroll(window);
		documentReady();
	});
});

function documentReady(){
	parseXFBML('.fbml');
	
	if(swfobject.hasFlashPlayerVersion("9.0.0")){
    swfobject.embedSWF("/home.swf", "page_home_swf", "1152", "715", "9.0.0", null, null, {wmode: 'transparent'});
		swfobject.embedSWF("/products.swf", "page_products_swf", "1152", "803", "9.0.0", null, null, {wmode: 'transparent'});
	}else{
		callJava();
		productsCarousel.init();
	}
	
	var page = (new String(window.location)).match(/^.*\#(.+)$/);
	goToPage(page ? page[1] : 'home')
	
	pageAboutInit();
	pageUrlInit();
	paralaxInit();
	pagePromoInit();
	
	
	new animatedLines($('#fb_page_container .animated_lines'));
	new animatedLines($('#stuff_page_container .animated_lines'), 2500, 85, 85, function(){
		$('#about_page_container .page_waves div').fadeIn('fast');
	});
	animatedLinesInit();
	
}//documentReady

function getEmbed(embed_code){$("#player").html(embed_code);}

function getPagePosition(id){
	if(id == 'music' || id == 'dudl') id = 'promo';
	var top = $('#'+id+'_page_container').offset().top;
	switch(id){
		case 'promo':
			//top += 270;
			top += ($('#'+id+'_page_container').outerHeight() - $(window).height())/2;
			break;
		case 'about': top += 80; break;
		case 'stuff': top += 690; break;
		case 'products':
			var c = $('#productsCarousel');
			if(!c.length) c = $('#page_products_swf');
			top = c.offset().top + (c.outerHeight() - $(window).height())/2;
			//top += 356;
			break;
	}
	return top;
}//getPagePosition

function setPageUrl(id, donttrack){
	if(!donttrack && current_page != id) GAVirtualPageview('/'+id);
	current_page = id;
	var url = (new String(window.location)).replace(/\#.*$/, '');
	window.location.assign(url+'#'+id);
}//setPageUrl

var animateDone = true;
var current_page = 'home';
function goToPage(id){
	if(id != 'promo') closeIframeNew();
	if(id != 'home') callJavaOn = false;
	if(current_page != id) GAVirtualPageview('/'+id);
	if(id == 'music' || id == 'dudl'){
		id = 'music';
		setPageUrl(id, true);
		animateDone = false;
		$('html,body').scrollTop(getPagePosition(current_page));
		_openPromoIframe();
		animateDone = true;
		return;
	}else{
		setPageUrl(id, true);
		var top = getPagePosition(current_page);
		var time = Math.abs($(window).scrollTop() - top)*2;// * 6 / 10;
		animateDone = false;
		$('html,body').animate({scrollTop: top}, time, function(){
			animateDone = true;
		});
	}
}//goToPage

var callJavaOn = true;
function callJava(){
	homeLines();
	if(callJavaOn) goToPage('promo'); 
}//callJava

function px2int(px){return px=='auto'?0:parseInt(px.replace('px', ''));}
function windowCenter(){return $(window).scrollTop() + Math.min($(window).height(), 700)/2;}
function homeLines(){
	//new animatedLines($('#home_page_container .animated_lines'), 300, 100);
	$('#home_page_container .animated_lines div').css({visibility: 'visible', top: -2100}).delay(200).animate({top: -1000}, 2500, function(){
		$('#promo_page_container .page_waves div').fadeIn('fast');
	});
}//homeLines

function animatedLines(o, d, m, s, c){
	var This = this;
	This.element = $('div', o);
	This.delay = d || 2500;
	This.callback = c;
	This.height = This.element.outerHeight();
	This.dif = This.height + This.element.offset().top;
	This.min = (m || 0) - This.height;
	This.prev = (s ? s : 0) - This.height;
	This.element.css({visibility: 'visible', top: This.prev});
	This.element.data('animatedLines', This);
}//animatedLines

function animatedLinesInit(){
	$(window).scroll(function(){
		$('.animated_lines div').each(function(i, e){
			var This = $(e).data('animatedLines');
			if(This){
				var top = windowCenter() - This.dif;
				if(This.prev > top) top = Math.max(top, This.min);
				if(top > This.min && top < 0){
					//top = Math.min(top, 0);
					//This.prev = top;
					//This.element.stop().animate({top: This.prev}, 'fast');
					This.element.stop().animate({top: 0}, This.delay, function(){
						if(This.callback) This.callback();
					});
					This.element.data('animatedLines', null);
				}
			}
		});
	});
}//animatedLinesInit

var pageLoadingInterval;
var pageLoadingTimeout;
var pageLoadingCount;
var pageLoadingStatus;
function showPageLoading(){
	pageLoadingStatus = true;
	pageLoadingTimeout = setTimeout(pageLoadingTimeoutlCallback, 500);
}//showPageLoading
function hidePageLoading(){
	if(pageLoadingTimeout){
		clearTimeout(pageLoadingTimeout);
		pageLoadingTimeout = null;
	}
	if(pageLoadingInterval){
		clearInterval(pageLoadingInterval);
		pageLoadingInterval = null;
	}
	$('#page_loading').hide();
	pageLoadingStatus = false;
}//hidePageLoading
function pageLoadingIntervalCallback(){
	pageLoadingCount = (pageLoadingCount + 1) % 4;
	var t = 'Loading';
	for(var i = 0; i < 4; i++) t += i < pageLoadingCount ? '.' : '&nbsp;';
	$('#page_loading').html(t)
}//pageLoadingIntervalCallback
function pageLoadingTimeoutlCallback(){
	pageLoadingCount = 0;
	$('#page_loading').show();
	pageLoadingInterval = setInterval(pageLoadingIntervalCallback, 400);
}//pageLoadingTimeoutlCallback

function mainSubnav(id, i){
	$('#'+id+'_nav > a').removeClass('active').filter(':eq('+i+')').addClass('active');
	$('#'+id+'_content > div').hide().filter(':eq('+i+')').show();
}//mainSubnav

function pageAboutInit(){
	jScrollPane('#page_about_content > div');
	var pages = Math.ceil($('#page_videos_thumbs > div').length/4), position = 1, prev, next;
	if(pages > 1){
		prev = $('#page_videos_nav_prev');
		next = $('#page_videos_nav_next');
		function pageVideoGo(page){
			page = Math.max(Math.min(page || 1, pages), 1)
			position = page;
			var s = (position-1)*4, e = s+3;
			$('#page_videos_thumbs > div').hide().filter(':eq('+s+'),:gt('+s+'):lt('+e+')').show();
		}//pageVideoGo
		prev.click(function(){pageVideoGo(position-1);return false;});
		next.click(function(){pageVideoGo(position+1);return false;});
		pageVideoGo();
	}
}//pageAboutInit

var current_fixed_page;
var fixedPageInProgres;
function showFixedPage(id){
	if(fixedPageInProgres || id == current_fixed_page || pageLoadingStatus) return false;
	fixedPageInProgres = true;
	fixed_page = id;
	showPageLoading();
	hideFixedPage();
	$('#main_footer .nav a').removeClass('active').filter('.main_footer_nav_'+id).addClass('active');
	getPageContent(id, function(page){
		fixedPageInProgres = false;
		$('#fixed_pages').show().append(page);
		jScrollPane(page);
		hidePageLoading();
	});
	return false;
}//showFixedPage
function hideFixedPage(){
	current_fixed_page = null;
	$('#fixed_pages').hide();
	$('#main_footer .nav a').removeClass('active')
	savePageContent($('#fixed_pages .fixed_page'));
}//hideFixedPage


function getPageContent(id, callback){
	var page_content = $('#page_content_'+id);
	if(page_content.length) callback(page_content, id);
	else $.get('/ajax/page/'+id, function(data){
		$('#pages_cache').append($('<div id="page_content_'+id+'" class="fixed_page"></div>').html(data));
		getPageContent(id, callback);
	});
}//getPageContent
function savePageContent(page){
	$('#pages_cache').append(page);
}//savePageContent


function overlayWindowOpen(options){
	if(pageLoadingStatus) return;
	showPageLoading();
	overlayWindowClose();
	var w = $('#overlayWindow');
	var d = $('> div', w);
	var c = $('#overlayWindowContent').empty();
	var t = $('#overlayWindowTitle');
	var contentHtml = function(html){
		hidePageLoading();
		if(html) jScrollPane(c.html(html));
	}
	var size = {width: $(window).width()-190, height: $(window).height()-340};
	var position = {left: 55, top: 115};
	w.show();
	
	if(options.width){
		position.left += (size.width - options.width) / 2;
		size.width = options.width;
	}
	if(options.height){
		position.top += (size.height - options.height) / 2;
		size.height = options.height;
	}
	
	d.css(size).css(position);
	if(options.title){
		size.height -= 100;
		t.show().html(options.title);
	}
	c.css(size);
	if(options.url){
		options.html = $('<iframe src="'+options.url+'" frameborder="0" scrolling="auto"></iframe>').css(size);
		options.html.css(options.css);
	}
	if(options.get || options.post){
		var p = {
			type: options.post ? 'POST' : 'GET',
			success: contentHtml,
			error: function(){contentHtml();}
		};
		if(options.post) p.data = options.data;
		$.ajax(options.get || options.post, p);
	}
	else contentHtml(options.html);
}//overlayWindowOpen
function overlayWindowClose(){
	$('#overlayWindow').hide();
	$('#overlayWindowTitle').hide();
	var c = $('#overlayWindowContent');
	var jsp = c.data('jsp');
	if(jsp) jsp.destroy();
	c.empty();
}//overlayWindowClose


function openIframe(url){
	$('html').css({overflow: 'hidden'});
	$('body').append($('<iframe id="overlayIframe" src="'+url+'" frameborder="0" scrolling="auto"></iframe>')
			 .css({ width: $(window).width(), height: $(window).height()}), 
			 $('<div id="overlayIframeX" onclick="closeIframe();" class="overlayWindowX">x</div>'));
}//openIframe
function closeIframe(){$('#overlayIframe,#overlayIframeX').remove();}
function closeIframeNew(){
	PromoIframeOpened = false;
	enableScroll(window);
	$(window).unbind('resize', resizeIframeNew);
	var box = $('#promo_page_iframe');
	box.fadeOut(500, function(){
		box.remove()
	});
}//closeIframeNew
function openIframeNew(url){
	showPageLoading();
	var box = $('<div id="promo_page_iframe"></div>');
	var ifr = $("<iframe frameborder='0' scrolling='auto'></iframe>");
	var x = $('<div id="promo_page_iframe_X" class="overlayWindowClose"></div>');
	x.click(closeIframeNew);
	box.append(ifr, x)
	$('body').append(box);
	ifr.load(function(){
		hidePageLoading();
		disableScroll(window);
		resizeIframeNew();
		$(window).bind('resize', resizeIframeNew);
		box.fadeIn(500);
	}).attr('src', url);
}
function resizeIframeNew(){
	var box = $('#promo_page_iframe');
	var x = $('#promo_page_iframe_X');
	var sw = scrollbarWidth();
	var ww = $(window).width();
	if(box.length) box.css({width: ww, height: $(window).height() - 108});
	x.css({right: sw + (ww - sw - 1152) / 2 - 35});
}//resizeIframeNew
function openPromoIframe(){
	setPageUrl('music');
	_openPromoIframe();
}
var PromoIframeOpened = false;
function _openPromoIframe(){
	if(PromoIframeOpened) return;
	PromoIframeOpened = true;
	openIframeNew('http://dudl.sunnyd.com');
}
function popupOpen(options){window.open(options.url, options.name, options.specs);}

function disableScrollHandler(){$(this).scrollTop($(this).data('disableScroll'))};
function disableScroll(e){$(e).data('disableScroll', $(e).scrollTop()).bind("scroll", disableScrollHandler);};
function enableScroll(e){$(e).unbind("scroll", disableScrollHandler);}




function fbInit(AppID){
	 window.fbAsyncInit = function() {
    FB.init({
      appId: AppID,
      //channelUrl: '//'+window.location.host+'/fb_channel.php',
      status: true,
      cookie: true,
      xfbml: true
    });
  };
  (function(d){
     var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
     js = d.createElement('script'); js.id = id; js.async = true;
     js.src = "//connect.facebook.net/en_US/all.js";
     d.getElementsByTagName('head')[0].appendChild(js);
   }(document));
}//fbInit
function parseXFBML(e){
	$(e).each(function(){FB.XFBML.parse(this);});
}//parseXFBML

function commentHerePopup(accessToken){
	overlayWindowOpen({get: '/ajax/add_comment/'+accessToken, width: 600, height: 170});
}//commentHerePopup
function commentHere(){
	FB.getLoginStatus(function(loginResponse){
		if(loginResponse.status === 'connected'){
			FB.api('/me/permissions', function(response){
			  if(response.data[0].publish_stream == 1) commentHerePopup(loginResponse.authResponse.accessToken);
			  else FBLogin();
			});
		}else FBLogin();
	});
}//commentHere
function FBLogin(){
	FB.login(function(response){
		if(response.status === 'connected') commentHerePopup(response.authResponse.accessToken);
	}, {scope: 'publish_stream'});
}//FBLogin
function addComment(frm){
	var data = {
		comment: $('textarea', frm).val(),
		post_to_wall: $('[name=post_to_wall]:checked', frm).length,
		accessToken: $('[name=accessToken]', frm).val()
	};
	if(!data.comment) return alert('Comment is missing.');
	if(data.post_to_wall){
		FB.api('/me/permissions', function(response){
		  if(response.data[0].publish_stream == 1) postComment(data);
		  else FB.login(function(response){
				if(response.status === 'connected'){
					data.accessToken = response.authResponse.accessToken;
					postComment(data);
				}
			}, {scope: 'publish_stream'});
		});
	}else postComment(data);
}//addComment
function postComment(data){
	overlayWindowOpen({post: '/ajax/add_comment/'+data.accessToken, data: data, width: 600, height: 170});
}//postComment
function updateComments(uid, datetime, comment){
	var items = $('.page_fb_item'), hidden = items.filter(':hidden'), last;
	if(!hidden.length){
		var item0;
		items.each(function(i,e){e=$(e);
			if(i==0){
				item0 = $('> div', e).hide();
				$('body').append(item0);
			}else items.filter(':eq('+(i-1)+')').append($('> div', e));
			if(i==2){
				e.append(item0);
				item0.show();
			}
		});
		last = items.last();
	}else last = hidden.first();
	datetime = datetime.split(';');
	$('td.fbml', last).html('<fb:profile-pic uid="'+uid+'" linked="true" size="square" linked="false" />');
	$('.title', last).html('<b class="fbml"><fb:name uid="'+uid+'" useyou="false" linked="false"></fb:name></b> on <b>'+datetime[0]+'</b> at '+datetime[1]+' said:');
	$('.description', last).text(comment);
	parseXFBML($('.fbml', last));
	last.show();
}//updateComments


function jScrollPaneInterval(){
	$('.jScrollPaneInterval').each(function(){
		$(this).data('jsp').reinitialise();
	});
}//jScrollPaneInterval
setInterval(jScrollPaneInterval, 2000);
function jScrollPane(e){
	$(function(){
		$(e).each(function(){
			$(this).jScrollPane().addClass('jScrollPaneInterval').data('jsp').reinitialise();
		});
	});
}//jScrollPane


var PAGES = ['home', 'promo', 'products', 'stuff', 'about'];
var PAGES_BORDER = [];
function pageUrlInit(){
	for(var i = 0; i < PAGES.length; i++){
		PAGES_BORDER[PAGES[i]] = (getPagePosition(PAGES[i]) + (i+1 < PAGES.length ? getPagePosition(PAGES[i+1]) : $(document).height())) / 2;
	}
	$(window).scroll(pageUrlUpdate);
}//pageUrlInit
function pageUrlUpdate(){
	if(!animateDone) return;
	var center = $(window).scrollTop()+$(window).height()/2;
	var page = 'home';
	var pos = 50000;
	for(var i = 0; i < PAGES.length; i++){
		var p = Math.abs(PAGES_BORDER[PAGES[i]] - center);
		if(p < pos){
			page = PAGES[i];
			pos = p;
		}
	}
	if(current_page != 'music' && current_page != 'dudl' || page != 'promo') setPageUrl(page);
}//pageUrlUpdate

function funStuffPlayer(code, title, a){
	var videos = $('#fun_stuff_videos');
	var player = $('#fun_stuff_player');
	videos.hide();
	var position = 0;
	var prev = $('.prev', player);
	var next = $('.next', player);
	var links = $('tr td:first-child a[onclick^=funStuffPlayer]', videos).each(function(i){
		if(this == a) position = i;
	});
	player.show();
	prev.unbind();
	next.unbind();
	if(position > 0) prev.removeClass('inactive').click(function(){
		links.filter(':eq('+(position-1)+')').click();
	});
	else prev.addClass('inactive');
	if(position+1 < links.length) next.removeClass('inactive').click(function(){
		links.filter(':eq('+(position+1)+')').click();
	});
	else next.addClass('inactive');
	$('.player', player).html(code);
	$('.title', player).html(title);
	$('.pages', player).html((position+1)+' of '+links.length);
	jScrollPane('#overlayWindowContent');
}//funStuffPlayer
function funStuffPlayerClose(){
	var videos = $('#fun_stuff_videos');
	var player = $('#fun_stuff_player');
	player.hide();
	videos.show();
	jScrollPane('#overlayWindowContent');
}//funStuffPlayerClose


function pagePromoInit(){
	var fx = $('#page_promo_fx_waves');
	fx.data('top', px2int(fx.css('top')));
	fx.data('center', fx.offset().top);
	$(window).scroll(pagePromoUpdate);
}//pagePromoInit
function pagePromoUpdate(){
	var fx = $('#page_promo_fx_waves');
	var scrollTop = $(window).scrollTop();
	var center = scrollTop + $(window).height() - 300;
	//-19 - 864
	var dif = center - fx.data('center');
	fx.stop().animate({top: fx.data('top') + (dif < 0 ? dif : 0)}, 'fast');
}//pagePromoUpdate


var paralax_layers, paralax_multipliers = [0.05, 0.12, 0.25, 0.5, 1];
function paralaxInit(){
	$('#root').css({position: 'relative', overflow: 'hidden', height: $(document).height()});
	paralax_layers = $('.layer');
	for(var i = 0; i < paralax_multipliers.length; i++){
		paralax_layers.filter('.layer'+i).each(function(){
			var e = $(this);
			//var top = px2int(e.css('top'));
			var top = e.offset().top;
			e.data('multiplier', paralax_multipliers[i]);
			e.data('center', top + e.outerHeight()/2);
			e.data('top', top);
			e.data('dif', top - px2int(e.css('top')));
		});
	}
	$(window).scroll(paralaxUpdate);
	paralaxUpdate();
}//paralaxInit
function paralaxUpdate(){
	var center = windowCenter();
	var max = 200;
	paralax_layers.each(function(){
		var e = $(this);
		var dif = e.data('center') - center;
		//var p = Math.min(Math.abs(dif), max * e.data('multiplier'));
		dif = dif * e.data('multiplier');
		//var adif = Math.abs(dif);
		//var direction = dif/adif;
		e.stop().animate({
			//top: e.data('top') + (dif/Math.abs(dif)) * p * e.data('multiplier') - e.data('dif')
			top: e.data('top') - e.data('dif') + dif
		}, 1000);
	});
}//paralaxUpdate

function scrollbarWidth(){return $.getScrollbarWidth();}
function preloadImage(s,h){$('<img/>').load(h).attr('src',s);}
function preloadImages(a,h){var c=0,i;for(i=0;i<a.length;i++)preloadImage(a[i],function(){c++;if(c==a.length)h();});}

/*	['orangeCherry', 'red', 'Orange Cherry', 1],
	['orangeCitricos', 'yellow', 'Orange Citricos', 1],
*/

var productsCarouselBottles = [];
var productsCarouselImgPath = '/img/main/products/carousel'
var productsCarouselColors = ['red_dark', 'red', 'orange_dark', 'orange', 'yellow_dark', 'yellow', 'pink', 'green'];
var productsCarouselDelay = 1000;

var productsTab = new function(){
	var This = this, Private = {busy: 0};
	This.init = function(){
		This.position = 0;
		This.container = $('#productsTab');
		$('#productsTabNavMap area').each(function(i){
			$(this).click(function(){This.show(i);});
		});
		$('#productsTabX').click(This.hide);
		This.container.show();
		Private.info = $('.product_info', productsTab.container);
	}
	This.hide = function(){
		This.container.animate({right: -323}, 'slow');
	}
	This.show = function(index){
		This.position = index;
		This.container.attr('class', 'tab'+This.position).animate({right: 0}, 'slow');
		$('#productsTabContent'+This.position).jScrollPane().data('jsp').reinitialise();
	}
	This.product = function(index){
		Private.info.hide();
		Private.info.filter('.product_'+index).show();
		$('#productsTabContent'+This.position).jScrollPane().data('jsp').reinitialise();
	}
}//productsTab

var productsNav = new function(){
	var This = this, Private = {busy: 0};
	Private.update = function(){
		This.elements.prev.attr('class', This.position == 0 ? 'inactive' : '');
		This.elements.next.attr('class', This.position == This.length - 1 ? 'inactive' : '');
	}
	Private.go = function(index){
		if(Private.busy) return false;
		This.position = Math.min(Math.max(0, index), This.length-1);
		Private.update();
		Private.items.each(function(index){
			Private.busy++;
			$(this).stop().animate({top: (index-This.position)*Private.height}, productsCarouselDelay, function(){
				Private.busy--;
			});
		});
		var i, pos = 0, count = 0, cat = productsCarouselBottles[This.position][1];
		for(i = 0; i < productsCarouselBottles.length; i++){
			if(productsCarouselBottles[i][1] == cat){
				count++;
				if(i == This.position) pos = count;
			}
		}
		productsSubNav.text(pos+'/'+count);
		productsSubNav.go(cat);
	}
	This.go = function(index){
		Private.go(index);productsCarousel.go(index);
	}
	This.prev = function(){
		Private.go(This.position-1);productsCarousel.prev();
	}
	This.next = function(){
		Private.go(This.position+1);productsCarousel.next();
	}
	This.init = function(){
		This.position = 0;
		This.elements = {
			prev: $('#productsNavPrev'),
			title: $('#productsNavTitle'),
			next: $('#productsNavNext')
		};
		var title, i, item;
		for(i = 0; i < productsCarouselBottles.length; i++){
			title = productsCarouselBottles[i][0].split(' ');
			item = $('<div></div>');
			item.css('background', 'transparent url('+productsCarouselBottles[i][5]+') no-repeat center center');
			item.append('<div>'+title[0]+'</div>');
			if(title.length > 1) item.append('<div>'+title[1]+'</div>');
			This.elements.title.append(item);
		}
		Private.items = $('> div', This.elements.title);
		Private.height = Private.items.outerHeight();
		Private.items.each(function(index){$(this).css({position: 'absolute',left: 0, top: index*Private.height});});
		This.length = Private.items.length;
		This.elements.prev.click(This.prev);
		This.elements.next.click(This.next);
		Private.update();
	}
}//productsNav

var productsSubNav = new function(){
	var This = this, Private = {};
	This.go = function(index){
		index = Math.min(Math.max(0, index), This.length-1);
		if(index == This.position) return;
		This.position = index;
		var active = This.elements.items.removeClass('active').filter(':eq('+This.position+')').addClass('active');
		This.elements.position.animate({
			left: active.offset().left + active.width()/2
		}, 'slow');
	}
	This.text = function(value){
		if(value) This.elements.position.show().text(value);
		else This.elements.position.hide();
	}
	This.init = function(){
		This.container = $('#productsSubNav');
		This.elements = {
			position: $('#productsSubNavPosition'),
			items: $('a', This.container)
		};
		This.position = -1;
		This.length = This.elements.items.length;
		This.elements.items.each(function(index){
			$(this).click(function(){
				for(i = 0; i < productsCarouselBottles.length; i++){
					if(productsCarouselBottles[i][1] == index) return productsNav.go(i);
				}
			});
		});
		This.container.show();
	}
}//productsSubNav

var productsCarousel = new function(){
	var This = this, Private = {
		busy: 0,
		cssCache: []
	};
	Private.reOrder = function(){
		var i;
		for(i = 0; i < This.position; i++) This.container.append(This.items[i].container);
		for(i = This.length-1; i > This.position; i--) This.container.append(This.items[i].container);
		This.container.append($('#productsCarouselSplashBack'));
		This.container.append(This.items[This.position].container);
		This.container.append($('#productsCarouselSplashFront'));
	}
	Private.getCssByPosition = function(index){
		index = Math.min(Math.max(-3, index), 3);
		if(typeof Private.cssCache[index] == 'undefined'){
			var abs = Math.abs(index);
			var dir = index/abs;
			var css = {};
			var size = {width: 229, height: 510};
			switch(abs){
				case 0: css.width = 229; css.height = 510; css.opacity = 1; break;
				case 1: css.width = 160; css.height = 357; css.opacity = 0.6; break;
				case 2: css.width = 104; css.height = 232; css.opacity = 0.3; break;
				default: css.width = 68; css.height = 151; css.opacity = 0; break;
			}
			css.left = Private.center.left - css.width/2;
			css.top = Private.center.top - css.height/2;
			switch(abs){
				case 0: break;
				case 1: css.left += dir*160; break;
				case 2: css.left += dir*270; break;
				default: css.left += dir*340; break;
			}
			Private.cssCache[index] = css;
		}
		return Private.cssCache[index];
	}//getCssByPosition
	Private.splashFx = function(){
		Private.splash.each(function(){
			var e = $(this);
			e.attr('src', productsCarouselImgPath+'/splash/'+(e.is('#productsCarouselSplashBack')?'back':'front')+'/'+(This.position % 2 ? 'odd' : 'even')+'/'+This.items[This.position].color+'.png')
				.css({opacity: 0, width: 0, height: 0}).css(Private.center)
				.show().animate(e.data('css'), 'slow');
		});
	}//splashFx
	Private.go = function(index){
		if(Private.busy) return false;
		index = Math.min(Math.max(0, index), This.length-1);
		if(index == This.position) return;
		This.position = index;
		productsTab.product(This.position);
		Private.splash.hide();
						Private.reOrder();
		for(i = 0; i < This.length; i++){
			Private.busy++;
			This.items[i].container.show()
				.animate(Private.getCssByPosition(i - This.position), {
					duration: productsCarouselDelay,
					//step: function(){this.css("overflow","visible");},
					complete: function(){
						//this.css("overflow","visible");
						Private.busy--;
						if(!Private.busy) Private.splashFx();
					}
				});
			if(i == This.position) This.items[i].active();
			else This.items[i].inactive();
		}
	}//go
	This.go = function(index){
		index = Math.min(Math.max(0, index), This.length-1);
		if(index == This.position) return;
		This.position = index;
		productsTab.product(This.position);
		Private.splash.hide();
		Private.reOrder();
		for(i = 0; i < This.length; i++){
			This.items[i].container.show().css(Private.getCssByPosition(i - This.position));
			if(i == This.position) This.items[i].active();
			else This.items[i].inactive();
		}
		Private.splashFx();
	}//go
	This.prev = function(callback){Private.go(This.position-1, callback);}
	This.next = function(callback){Private.go(This.position+1, callback);}
	This.init = function(){
		Private.splash = $('#productsCarouselSplashFront,#productsCarouselSplashBack');
		Private.splash.each(function(){
			var e = $(this);
			e.data('css', {opacity: 1, width: e.width(), height: e.height(), left: px2int(e.css('left')), top: px2int(e.css('top'))});
		});
		This.container = $('#productsCarousel');
		This.container.addClass('loading');
		Private.center = {
			left: This.container.innerWidth()/2,
			top: This.container.innerHeight()/2
		};
		This.items = [];
		var i, bottle, imgs = [];
		for(i = 0; i < productsCarouselBottles.length; i++){
			bottle = new productsBottle(productsCarouselBottles[i]);
			This.container.append(bottle.container);
			This.items.push(bottle);
		}
		This.position = -1;
		This.length = This.items.length;
		imgs.push(productsCarouselImgPath+'/shadow.png');
		for(i = 0; i < productsCarouselColors.length; i++){
			imgs.push(productsCarouselImgPath+'/splash/back/even/'+productsCarouselColors[i]+'.png');
			imgs.push(productsCarouselImgPath+'/splash/front/even/'+productsCarouselColors[i]+'.png');
			imgs.push(productsCarouselImgPath+'/splash/back/odd/'+productsCarouselColors[i]+'.png');
			imgs.push(productsCarouselImgPath+'/splash/front/odd/'+productsCarouselColors[i]+'.png');
		}
		for(i = 0; i < productsCarouselBottles.length; i++){
			imgs.push(productsCarouselBottles[i][3]);
			imgs.push(productsCarouselBottles[i][4]);
			imgs.push(productsCarouselBottles[i][5]);
		}
		preloadImages(imgs, function(){
			productsSubNav.init();
			productsNav.init();
			productsTab.init();
			This.container.removeClass('loading');
			productsNav.go(2);
			This.go(2);
		});
	};
}//productsCarousel

function productsBottle(options){
	var This = this, Private = {delay: productsCarouselDelay};
	This.title = options[0];
	This.category = options[1];
	This.description = options[6] || '';
	This.color = 'yellow_dark';
	This.status = false;
	for(var i = 0; i < productsCarouselColors.length; i++) if(productsCarouselColors[i] === options[2]) This.color = options[2];
	Private.tooltip = function(){
		var area = {
			left: This.container.offset().left,
			top: This.container.offset().top
		};
		area.right = area.left+This.container.innerWidth();
		area.bottom = area.top+This.container.innerHeight();
		productsBottleTooltip.set(This.description, area);
	}
	This.active = function(){
		This.status = true;
		Private.active.fadeIn(Private.delay, Private.tooltip);
		Private.inactive.fadeOut(Private.delay);
	}
	This.inactive = function(){
		This.status = false;
		Private.inactive.fadeIn(Private.delay);
		Private.active.fadeOut(Private.delay);
	}
	This.container = $('<div class="productsCarouselBottle"></div>');
	Private.shadow = $('<img class="shadow" src="'+productsCarouselImgPath+'/shadow.png" alt="" title="" />');
	Private.active = $('<img class="inactive" src="'+options[3]+'" alt="" title="" />');
	Private.inactive = $('<img src="'+options[4]+'" alt="" title="" />');
	This.container.append(Private.shadow, Private.active, Private.inactive);
}//productsBottle

var productsBottleTooltip = new function(){
	var This = this, Private = {};
	This.area = null;
	Private.mousemove = function(event){
		if(This.area && This.area.left < event.pageX && This.area.right > event.pageX && This.area.top < event.pageY && This.area.bottom > event.pageY) This.element.show().css({
			left: event.pageX,
			top: event.pageY - This.element.outerHeight() - 28
		});
		else This.element.hide();
	}
	This.set = function(html, area){
		$('span', This.element).html(html);
		This.area = area;
	}
	This.init = function(){
		This.element = $('<div id="productsBottleTooltip"><span></span><div></div></div>');
		$('body').append(This.element);
		$(document).mousemove(Private.mousemove);
	}
	$(This.init);
}//productsBottleTooltip

var afterItemStartCount = 0;
function afterItemStart(){
	if(afterItemStartCount == 0) disableScroll(window);
	afterItemStartCount++;
	$('#fbContentWrapper').css('overflow', 'auto');
}
function afterItemEnd(){
	afterItemStartCount--;
	if(afterItemStartCount == 0) enableScroll(window);
}
function ajaxFloatbox(url, title, width, height){
	var opt = {
		captionPos: 'tl',
		type: 'ajax',
		afterItemStart: afterItemStart,
		afterItemEnd: afterItemEnd
	};
	if(title) opt.caption = '<div class="myFbCaption">'+title+'</div>';
	if(width && height){
		opt.width = width;
		opt.height = height;
	}
	fb.start(url, opt);
}//ajaxFloatbox
function openFloatbox(url, title, width, height){
	var opt = {
		captionPos: 'tl',
		afterItemStart: afterItemStart,
		afterItemEnd: afterItemEnd
	};
	if(title) opt.caption = '<div class="myFbCaption">'+title+'</div>';
	if(width && height){
		opt.width = width;
		opt.height = height;
	}
	fb.start(url, opt);
}//openFloatbox
function openGame(url, width, height){
	var opt = {
		captionPos: 'bl',
		sameBox: true,
		afterItemStart: function(){
			afterItemStart();
			fb.resize(width, height);
		},
		afterItemEnd: afterItemEnd,
		caption: '<span class="myFbBack" onclick="fb.goBack(fb.ownerInstance(this));">Back</span>'
	};
	if(width && height){
		opt.width = width;
		opt.height = height;
		url = '<iframe align="middle" width="'+width+'" scrolling="auto" height="'+height+'" frameborder="0" src="'+url+'">';
	}
	parent.fb.start(url, opt); 
}//openGame

var _gaq = _gaq || [];
function GAVirtualPageview(url){
	_gaq.push(['_trackPageview', url]);
}//GAVirtualPageview




