// Baldi
if(!window.console) { window.console = { error:function() {}, warn:function() {}, log:function() {} }}

var current_lang = 'en';
var imgs_curr = 0;
var imgs_interval;
var created = false;
var base_folder = '';
var imgs;

var imgs_main = {
	'home': ['home-01.jpg', 'home-02.jpg', 'home-03.jpg'],
	'media': ['home-01.jpg'],
	'corporate': ['capocapitolo-01.jpg'],
	'collections': ['capocapitolo-02.jpg'],
	'the-product': ['capocapitolo-03.jpg'],
	'baldi-interiors': ['capocapitolo-04.jpg'],
	'baldi-worldwide': ['capocapitolo-05.jpg']
};

var aspectRatio = 1.333333333;
var wide_mode = true;

/*var links_tool = {
	/*'languages': { en:"Languages", it:"Lingue", zh:"Languages", ru:"Languages", ar:"Languages" },*
	'credits': { en:"Credits", it:"Crediti", zh:"信用", ru:"Aвторские права", ar:"Credits" },
	'contacts': { en:"Contacts", it:"Contatti", zh:"总部", ru:"связи", ar:"Contacts" },
	/*'media': { en:"Media", it:"Media", zh:"Media", ru:"Media", ar:"Media" },*
	'reserved': { en:"Reserved", it:"Area riservata", zh:"保留区", ru:"зона", ar:"Reserved" },
	'language': { en:"Language", it:"Lingue", zh:"语言", ru:"язык", ar:"Language" },
	'home': { en:"Home", it:"Homepage", zh:"首页", ru:"домашняя страница", ar:"Home" }
};*/

var links_tool = {
	'credits': { en:"Credits", it:"Crediti", zh:"信用", ru:"Aвторские права", ar:"الحقوق" },
	'contacts': { en:"Contacts", it:"Contacts", zh:"Contacts", ru:"Contacts", ar:"Contacts" },
	'media': { en:"Media", it:"Media", zh:"Media", ru:"Media", ar:"Media" },
	'reserved': { en:"Reserved", it:"Reserved", zh:"Reserved", ru:"Reserved", ar:"Reserved" },
	'language': { en:"Language", it:"Language", zh:"Language", ru:"Language", ar:"Language" },
	'home': { en:"Home", it:"Home", zh:"Home", ru:"Home", ar:"Home" }
};

var links_languages = { 'en':'English', 'it':'Italiano', 'zh':'中文', 'ru':'русский', 'ar':'العربية' };

var links_main = {
	'baldi-worldwide': { en:"Baldi worldwide", it:"Baldi worldwide", zh:"巴尔迪在全球", ru:"Baldi worldwide", ar:"بالدي في جميع أنحاء العالم",
		sub: {
			'baldi-boutiques': { en:"Baldi boutiques", it:"Boutique Baldi", zh:"巴尔迪精品店", ru:"Бутики Baldi", ar:"متاجر بالدي" },
			'authorized-dealers': { en:"Authorized dealers", it:"Rivenditori autorizzati", zh:"授权经销商", ru:"Уполномоченные дилеры", ar:"الموزعون المعتمدون" },
			'fairs': { en:"Fairs", it:"Fiere", zh:"Fairs", ru:"Fairs", ar:"Fairs" }
		}
	},
	'baldi-interiors': { en:"Baldi interiors", it:"Baldi interiors", zh:"巴尔迪内饰", ru:"Baldi interiors", ar:"ديكورات بالدي",
		sub:{
			'special-projects': { en:"Special projects", it:"Progetti Speciali", zh:"特殊项目", ru:"Специальные проекты", ar:"مشروعات خاصة" },
			'palaces-and-villas': { en:"Palaces and villas", it:"Palazzi e ville", zh:"宫殿与别墅", ru:"Дворцы и виллы", ar:"القصور والفيلات" }
		}
	},
	'the-product': { en:"The product", it:"Il prodotto", zh:"产品", ru:"продукта", ar:"المنتجات",
		sub: {
			'workmanship': { en:"Workmanship", it:"Artigianalità", zh:"手工艺", ru:"Мастерство", ar:"مهارة الصناعة" },
			'precious-materials': { en:"Precious materials", it:"Materiali preziosi", zh:"珍贵的材料", ru:"Драгоценные материалы", ar:"المواد الثمينة" },
			'rock-crystal': { en:"Rock crystal", it:"Cristallo di rocca", zh:"无色水晶", ru:"Горный хрусталь", ar:"الكريستال الصخري" },
			'design': { en:"Design", it:"Design", zh:"设计", ru:"ДИЗАЙН", ar:"التصميم" },
			'care-instructions': { en:"Care instructions", it:"Care instructions", zh:"Care instructions", ru:"Care instructions", ar:"Care instructions" }
		}
	},
	'collections': { en:"Collections", it:"Collezioni", zh:"收藏", ru:"Коллекции", ar:"المجموعات",
		sub: {
			'classic': { en:"Classic", it:"Classic", zh:"古典", ru:"Classic", ar:"كلاسيكي",
				sub: {
					'decorative-accessories': { en:"Decorative accessories", it:"Complementi d'arredo", zh:"装饰用品", ru:"Decorative accessories", ar:"Decorative accessories" },
					'collectibles': { en:"Collectibles", it:"Collectibles", zh:"收藏品", ru:"Collectibles", ar:"Collectibles" },
					'furnitures': { en:"Furniture", it:"Arredamento", zh:"家具", ru:"Мебель", ar:"Furniture" },
					'lighting-and-candlesticks': { en:"Lighting &amp; candlesticks", it:"Illuminazione", zh:"灯具&amp;烛台", ru:"Светильники", ar:"Lighting &amp; candlesticks" }
				}
			},
			'de-sign': { en:"De_sign", it:"De_sign", zh:"设计", ru:"De_sign", ar:"De_sign",
				sub: {
					'star': { en:"Star", it:"Star", zh:"Star 系列", ru:"Star", ar:"Star" },
					'aline': { en:"Aline", it:"Aline", zh:"Aline 系列", ru:"Aline", ar:"Aline" },
					'ice': { en:"Ice", it:"Ice", zh:"Ice 系列", ru:"Ice", ar:"Ice" },
					'furniture': { en:"Furniture", it:"Arredamento", zh:"家具", ru:"Мебель", ar:"Furniture" }
				}
			},
			'bathroom': { en:"Bathroom", it:"Bathroom", zh:"浴室", ru:"Ванная комната", ar:"الحمامات",
				sub: {
					'amaltea': { en:"Amaltea", it:"Amaltea", zh:"Amaltea 系列", ru:"Amaltea", ar:"Amaltea" },
					'noir': { en:"Noir", it:"Noir", zh:"Noir", ru:"Noir", ar:"Noir" }
				}
			}
		}
	},	
	'corporate': { en:"Corporate", it:"Corporate", zh:"公司", ru:"Корпоративный", ar:"الشركة",
		sub:{
			'baldi-ethos': { en:"Baldi Ethos", it:"Baldi Ethos", zh:"巴尔迪（Baldi）精神", ru:"Идеалы Baldi", ar:"روح بالدي" },
			'baldi-unique-style': { en:"Baldi Unique Style", it:"Lo stile unico Baldi", zh:"巴尔迪（ Baldi ）独一无二的风格", ru:"Уникальный стиль Baldi", ar:"أسلوب بالدي الفريد" },
			'generations-of-art': { en:"Generations of art", it:"Generazioni d'arte", zh:"艺术传承", ru:"Искусство в поколениях", ar:"أجيال من الفن" },
			'home-jewels': { en:"Home jewels", it:"Home jewels", zh:"Home Jewels 系列", ru:"Home jewels", ar:"Home jewels" },
			'headquarter': { en:"Headquarter", it:"Sede", zh:"总部", ru:"Штаб-квартира", ar:"المقر الرئيسي" }
		}
	},
	'etc': { skip:true, en:"Baldi", it:"Baldi", zh:"Baldi", ru:"Baldi", ar:"Baldi",
		sub:{
			'credits': { en:"Credits", it:"Credits", zh:"信用", ru:"Aвторские права", ar:"الحقوق" }
		}
	},
	'media': { skip:true, en:"Media", it:"Media", zh:"Media", ru:"Media", ar:"Media",
		sub: {
			'press': { en:"Press", it:"Press", zh:"Press", ru:"Press", ar:"Press" },
			'web': { en:"Web", it:"Web", zh:"Web", ru:"Web", ar:"Web" },
			'video': { en:"Video", it:"Video", zh:"Video", ru:"Video", ar:"Video" }
		}
	}
};

$.fn.wait = function(time, type) {
	time = time || 1000;
	type = type || "fx";

	return this.queue(type, function() {
		var self = this;
		setTimeout(function() {
		$(self).dequeue();
		}, time);
	});
};

// v = s / t
// t = s / v
// s = v * t
// vel = 10
function img_pan(img) {
	var w = $(window);
	var sh = wide_mode ? w.height() : w.width();
	var ih = wide_mode ? img.height() : img.width();
	var v = 30;
	var t = 4;
	var s;

	img.css({ top:0, left:0 }).animate({ opacity:"show" }, { queue:false, duration:2000, easing:'swing' });
	//if(ih > sh) img.animate({ top:-(ih - sh)}, 5000);
	if(ih > sh) {
		var s = ih - sh;
		s = Math.min(100, s);
		if(s < 30) return;
		t = s / v;
		img.animate(wide_mode ? { top:-s } : { left:-s }, t * 1000);
	}
}

function switch_img(i, t) {
	var el1 = $('.img' + i);
	created = true;
	var tw = $(window);

	if(el1.length > 0) {
		var el2 = $('.img' + ((i - 1) == -1 ? imgs.length - 1 : i - 1));
		if((tw.width() / tw.height()) < aspectRatio) {
			el2.removeClass('bg_width').addClass('bg_height');
			wide_mode = false;
		} else {
			el2.removeClass('bg_height').addClass('bg_width');
			wide_mode = true;
		}
		
		if(t) hover_toggle(el2, el1, false);
	} else {
		load_img('a/' + base_folder + '/' + imgs[i], function(img) {
			var c = "bg img" + i;
			if((tw.width() / tw.height()) < aspectRatio) {
				c = c + ' bg_height';
				wide_mode = false;
			} else {
				c = c + ' bg_width';
				wide_mode = true;
			}

			img.attr("class", c).prependTo("#wrapper");
			
			if(i == 0 && imgs.length != 1) {
				/*img.fadeIn(function() { */img_pan(img)/* })*/;
				imgs_interval = setInterval(function() {
					if(++imgs_curr == imgs.length) imgs_curr = 0;
					switch_img(imgs_curr, true);
				}, 6000);
			} else switch_img(i, true);
		});
	}
}

function slide(t) {
	if(created) {
		clearInterval(imgs_interval);
		$("#wrapper img.bg").each(function() {
			$(this).remove();
		});
	}
	
	base_folder = t;
	switch_img(0);
}

function build_url(sec, isec, url) {
	var ret = '#!/' + current_lang;

	if(sec != null) ret += '/' + sec;
	if(isec != null) ret += '/' + isec;
	if(url != 'home' && url != undefined) ret += '/' + url;
	
	return ret;
}

function recon_menu(menu, sec, arr) {
	var nm = ''; // 

	for(var x in arr) {
		if(arr[x]["skip"] == true) continue;
		var u;
		if(x == 'reserved') u = 'http://baldi.biz/priv/';
		else if(x == 'language') u = './';
		else if(x == 'credits') u = build_url('etc', null, 'credits');
		//else if(x == 'media') u = build_url('etc', null, 'media');
		else if(x == 'contacts') u = build_url('corporate', null, 'headquarter');
		else u = build_url(sec, null, x);
		nm += '<li><a id="menu_' + (sec ? sec + '_' : '') + x + '" href="' + u +'">' + arr[x][current_lang] + "</a></li>\n";
	}

	$(menu).html(nm);
	//rebuild_links(menu + " a");
}

function recon_menu_simple(menu, arr) {
	var nm = ''; // 
	
	for(var x in arr) {
		nm += '<li><a href="#!/' + x + '">' + arr[x] + "</a></li>\n";
	}

	$(menu).html(nm);
	//rebuild_links(menu + " a");
}

function recon_menu_a(sec, arr, simple) {	
	var nm = ''; // 
	
	for(var x in arr) {
		if(simple) {
			nm += '<h3><a href="' + build_url(sec, null, x) + '">' + arr[x][current_lang] + "</a></h3>\n";
		} else {
			nm += '<h2 class="accordion-' + x + '">' + arr[x][current_lang] + "</h2>\n";
			nm += '<div>' + recon_menu_a(sec + '/' + x, arr[x].sub, true) + '</div>';
		}
	}

	return nm;
}

var loaded = false;
var loaded2 = false;
function get_page(page) {
	var l = page;

	if(l.length >= 5 && l.substring(0, 3) == '#!/') {
		var arr = l.split('/');
		current_lang = arr[1];
		$("#home_menu").hide();
		$("#menu, #tool_menu, #bb").show();
		$("#wrapper").css("background", "black url('a/home-jewels.png') no-repeat center bottom");
		$("#copyright").hide();
		$("#h-baldi-2, #h-baldi-3").remove();
		if(!loaded2) {
			/*setInterval(function() {
				$("#logo").fadeOut(2000, function() {
					$("#logo2").fadeIn(2000).fadeOut(2000, function() { $("#logo").fadeIn() });
				});
			}, 7432);*/
			
			loaded2 = true;
		}

		// #!/en
		if(arr.length == 2) {
			imgs = imgs_main['home'];
			recon_menu("#tool_menu ul", null, links_tool);
			recon_menu("#menu ul", null, links_main);
			if($("#languages_menu").is(":visible")) $("#languages_menu").slideUp();
			//$("#sub_menu h1").removeAttr('class').html('');
			$("#sub_menu h1").hide();
			$("#accordion").hide();
			if(loaded) $("#response").remove();
			slide('home');
			return;
		}

		//imgs = imgs1;
		var first = arr[2]; // check
		var second = arr[3];
		var third = arr[4];
		
		recon_menu("#tool_menu ul", null, links_tool);
		recon_menu("#menu ul", null, links_main);

		if(first == "languages") $("#languages_menu").slideDown();
		else if((arr.length == 3 && (first == "baldi-worldwide" || first == "baldi-interiors" ||
			first == "the-product" || first == "collections" || first == "corporate" || first == "media")) || (arr.length == 4 && first == "collections")) {
			if(loaded) $("#response").remove();// console.log('in');
			var nm = '';
			var arr2 = links_main[first].sub;
			imgs = imgs_main[first];
			slide(first);
			var simple = first != "collections";
			$("#sub_menu h1").html(links_main[first][current_lang]).show();/*.removeAttr('class', 'internal')*/
			$("#sub_menu div.background").show();
			$("#accordion").html(recon_menu_a(first, links_main[first].sub, simple));
			$("#accordion").show();
			if(!simple) $("#accordion").accordion('destroy').accordion({ autoHeight: false, active:$('.accordion-' + second), collapsible:true });
			//}
		} else {
			$.get("a.php", { 'l': current_lang, 's': first, 'p': second, 'q': third }, function(response, status, xhr) {
				loaded = true;
				var nh1 = '<a href="' + build_url(first, null) + '">' + links_main[first][current_lang] + '</a>';
				var slp = second;
				var h1 = links_main[first].sub[second][current_lang];
				if(arr.length == 5) {
					nh1 += ' » ' //+ links_main[first].sub[second][current_lang]; //' » ' + links_main[first].sub[second].sub[arr[4]][current_lang];
					+ '<a href="' + build_url(first, second) + '">' + links_main[first].sub[second][current_lang] + '</a>';
					h1 = links_main[first].sub[second].sub[arr[4]][current_lang];
					slp = arr[4];
				}
				$("#sub_menu h1").hide();//.attr('class', 'internal').html(nh1);
				$("#sub_menu div.background").hide();
				$("#accordion").hide();

				var e = $("#response");					
				if(e.length) {
					e.replaceWith(response);
				} else {
					$("#wrapper").prepend(response);
				}
				
				$("#response h2").html(nh1);
				$("#response h1").html(h1);
				
				imgs = get_imgs();
				slide(slp);
				
				$("#wrapper .background").css({ opacity: 0.7 });

				response_init();
			});
		}
	} else {
		// Home page (maybe)
		// Language patch
		//recon_menu_simple("#menu ul", links_languages);
		var nm = ''; // 

		for(var x in links_languages) {
			nm += '<li><a href="#!/' + x + '">' + links_languages[x] + "</a></li>\n";
		}

		$("#menu ul").html(nm);
		
		load_img_s('h-baldi-1', 'a/firenze-1867.gif', function(img) {
			img.css({ position:"absolute",
				left:"50%", top:"40%",
				"margin-left":"-150px", "margin-top":"-15px",
				display:'none' }).prependTo("#wrapper");
			
			load_img_s('h-baldi-2', 'a/baldi.png', function(img2) {
				img2.css({ position:"absolute",
				left:"50%", top:"40%",
				"margin-left":"-203px", "margin-top":"-75px",
				display:'none' }).prependTo("#wrapper");
				img.fadeIn(2000, function() {
					img.fadeOut(2000, function() {
						img2.fadeIn(2000, function() {
							$('<img id="h-baldi-3" src="a/home-jewels.png">').prependTo("#wrapper").fadeIn();
						});
					});
					$('#menu').mouseenter();
				});
			});
		});
	}
}

function rebuild_links(sel) {
	$(sel).each(function() {
		$(this).unbind('click').click(function() {
			get_page($(this).attr('href'));
		});
	});
}

function hover_toggle(el1, el2, sync) {
	var el1 = $(el1);
	var el2 = $(el2);

	if(sync) {
		el2.css('z-index', 2);
		el2.fadeIn(2000);
		el1.fadeOut(2000);
	} else {
		el1.fadeOut(2000, function() {
			img_pan(el2);
		});
	}
}

function load_img(src, i) {
	var img = new Image();

	$(img).css({"position": "absolute", "display": "none"})
		.attr({"src": src })
		.load(function(response, status, xhr) { if(i) i($(this)); });
}

function load_img_s(iid, src, i) {
	var img = new Image();

	$(img).load(function () { i($(this)); })
	.attr({"src": src, "id": iid });
}

function rand_i(i) {
	return Math.floor(Math.random()*i);
}

function rand(i) {
	return Math.random()*i;
}

$(function () {

$(".background").animate({opacity:0.7}, 600, "easeInQuad");

function set_draggable(el) {
	$(el).draggable({ revert:true, cursor: 'mov', scroll:false,
		start:function(event, ui) {
		}, drag:function(event, ui) {
			var v = $(window);
			var w = v.width();
			var h = v.height();

			if(ui.position.left > -w/2) ui.position.left = -w/2;
			else if(ui.position.left < -(2000 - w/2)) ui.position.left = -(2000 - w/2);
			
			if(ui.position.top > 0) ui.position.top = 0;
			else if(ui.position.top < (h - 1500)) ui.position.top = (h - 1500);
		}
	});
}

$('#menu').hover(function() {
	$('#menu div.background').stop(true, true).animate({ width:"100%" }, function() {
		$('#menu_right').show();
		window.menu_anim = false;
	});
	}, function() {
		$('#menu_right').hide();
		$('#menu div.background').stop(true, true).animate({ width:0 }, { complete:function() {
			window.menu_anim = false;
		}});
	}
);

window.lang_menu_closed = false;
window.lang_menu_w = 0;
$('#tool_menu_right').click(function() {
	var tml = $('#tool_menu');
	
	if(window.lang_menu_closed) {
		tml.animate({ width:window.lang_menu_w }, { complete:function() {
			$("#tool_menu_left").fadeIn();
			$('#tool_menu_right').css('backgroundImage', "url(./a/next.gif)");
			window.lang_menu_closed = false;
		}});
	} else {
		window.lang_menu_w = tml.width();
		tml.css({ width:window.lang_menu_w, height:tml.height() });
		$("#tool_menu_left").fadeOut(function() {
			tml.animate({ width:30 }, { complete:function() {
				$('#tool_menu_right').css('backgroundImage', "url(./a/back.gif)");
			}});

			window.lang_menu_closed = true;
		});
	}
});

// New image

// New image

/*var imgs = [
	{ src:'01.jpg', w:1024, h:956, img:null },
	{ src:'02.jpg', w:1024, h:682, img:null },
	{ src:'03.jpg', w:1024, h:681, img:null },
	{ src:'04.jpg', w:1024, h:551, img:null },
	{ src:'05.jpg', w:1024, h:683, img:null },
	{ src:'06.jpg', w:1024, h:683, img:null }
];

function switch_img(i, t) {
	if(imgs[i].img != null) {
		var el1;
		var el2;
		
		if(i % 2 == 1) {
			el1 = '#container_inner_alt';
			el2 = '#container_inner';
		} else {
			el1 = '#container_inner';
			el2 = '#container_inner_alt';
		}
		
		$(el1)
		.css({ 'background-image': 'url("a/bg/' + imgs[i].src + '")',
			webkitBackgroundSize: imgs[i].w + 'px ' + imgs[i].h + 'px',
			width: imgs[i].w,
			height: imgs[i].h,
			left: -imgs[i].w / 2.0 });
		
		if(t) hover_toggle(el2, el1);
		set_draggable(el2);
	} else {
		load_img('#img' + i, 'a/bg/' + imgs[i].src, function(img) {
			imgs[i].img = img;
			switch_img(i, true);
		});
	}
}

var imgs_curr = 0;
load_img('#img0', 'a/bg/' + imgs[imgs_curr].src, function(i) {
	imgs[imgs_curr].img = i;	
	switch_img(imgs_curr, false);
	
	$('#container_inner').fadeIn(600);

	setInterval(function() {
		if(++imgs_curr == imgs.length) imgs_curr = 0;
		switch_img(imgs_curr);
	}, 6000);
});

//$('#container_inner').css({ 'background-image': "url('interiors/01.jpg')",  })*/

var h = window.location.hash;
get_page(h);
//slide();

// Tool menu
/*recon_menu("#tool_menu ul", null, links_tool);

$("#menu_languages").click(function() {
	$("#languages_menu").slideDown();
});

$(".menu_language").each(function() {
	$(this).click(function() {
		setTimeout(function() { $("#languages_menu").slideUp() }, 100);
	});
});*/

//rebuild_links("a");

$(document).delegate('a', 'click', function() { get_page($(this).attr('href')) });
$(document).delegate('img', 'mousedown', function(event) { if(event.which == 3) { event.stopPropagation(); event.preventDefault(); return false; } });

$(window).resize(function() {
	var w = $(window);
	if((w.width() / w.height()) < aspectRatio) {
		$(".bg").removeClass('bg_width').addClass('bg_height');
		wide_mode = false;
	} else {
		$(".bg").removeClass('bg_height').addClass('bg_width');
		wide_mode = true;
	}
}).trigger("resize");

});
