var browserAberation = 3;
var browserSubmenuAberation = 31;
var browserSubmenuListAberation = 46;

if($.browser.msie && parseInt($.browser.version, 10) == 7) {
	browserSubmenuListAberation = 44;
}

var staticPages = new Array();
var pictures = new Array();	
var scroller = 0;


$(document).ready(function(){
	var location = window.location.toString();
	var pathArray = location.split( '#' );
	
	if(typeof(pathArray[1])!="undefined" && pathArray[1]!=""){
		language = pathArray[1];
	}else language = "en";
	
	/*
	==============================
		Generate menu 
	==============================
	*/
	generateMenu();
	
	/*
	==========================================================
		Build rest of click triggers for menu functionality
	==========================================================
	// On click there are 5 possible actions		
	
		1. do nothing(just expand) (use last class selector)		
		
		.LAST CLASS
		------------
		2. loadGallery by ID 		(function: loadGallery)
		3. loadStatic by identifier	(function: loadStatic)
		4. standard URL 			(function: loadPage)
		5. loadVideo by video URL	(function: loadVideo)
	*/
	loadVideo('videos/GEORGES_HOBEIKA_PRESENTATION.mp4');
	
	$(".logo").hover(function(){
		$(this).stop(true, true).animate({opacity: 0.5}).animate({opacity: 1});
	},function(){});
	
});

function loadStaticHTML(identifier){
	$.ajax({
		type: "GET",
		url: "pages/"+language+"/"+identifier+".html",
		success: function(data) {
			var html = '<div class="staticPage">';
			html += data;
			html += '<div style="clear:both"></div></div>';
			$(".content").fadeOut(400, function(){
				$(".content").html(html).fadeIn(400);
			});
		},
		error: function(){
			alert("ERROR");
		}
	});
}
function loadVideo(video_link){
	var html = '<div class="staticPage" style="height: 510px;padding:0px;background: none;margin-top:0px;position:relative;top:-4px;">';
	html += '<!-- START OF THE PLAYER EMBEDDING TO COPY-PASTE -->';
	html += '<div id="mediaplayer">JW Player goes here</div>';
	html += '<script type="text/javascript" src="js/jwplayer.js"></script>';
	html += '<script type="text/javascript">';
	html += '	jwplayer("mediaplayer").setup({';
	html += '		file: "'+video_link+'",';
	html += '		width: 800,';
	html += '		height: 510,';
	html += '		repeat: "always",';
	html += '		"controlbar.position": "none",';
	html += '		dock: false,';
	html += '		icons: false,';
	html += '		players: [ { type: "html5" }, { type: "flash", src: "js/player.swf" }],';
	html += '		autostart: true,';
	html += '		shuffle: false';
	html += '	});';
	html += '</script>';
	html += '<!-- END OF THE PLAYER EMBEDDING -->';
	html += '</div>';
	
	$(".content").fadeOut(400, function(){
		$(".content").html(html).fadeIn(400);
	});
}

function loadGallery(category_id){
	/* 
	------------------
	 Get Gallery Data
	------------------
	*/
	var imageList = new Array();
	var collection_image = "";
	var collection_parent = "";
	var collection_name = "";
	$.ajax({
		type: "GET",
		url: "xml/galleries_new.xml",
		dataType: "xml",
		dataFilter: function(xml, dataType){
			$gallery = $(xml).find('gallery');
				$gallery.find('collection').each(function(){
					var ITEM_category_id = $(this).find('category_id').text();
					var title = $(this).find('title').text();
							
					if(category_id==ITEM_category_id){
						collection_image = $(this).find('collection_image').text();
						collection_parent = $(this).find('collection_name').text();
						collection_name = title;
						
						$pictures  = $(this).find('pictures');
						if(typeof($pictures)!="undefined"){ 
							$pictures.find('item').each(function(){
								$images  = $(this).find('images');
								if(typeof($images)!="undefined"){ 
									$zoom  = $images.find('zoomImage');
									if(typeof($zoom)!="undefined"){ 
										var temp_arr = new Array();
								
										temp_arr["file"] = $zoom.find('file').text();
										temp_arr["label"] = $zoom.find('label').text();
										temp_arr["url"] = $zoom.find('url').text();
										temp_arr["description"] = "";
										//alert(temp_arr["description"]);
										imageList.push(temp_arr);
									}
								}
							});
						}
					}
				});
		},
		success: function(xml){
			if(imageList.length>0){
				var content = '<div id="tS1" class="jThumbnailScroller">';
				content +='<div class="jTscrollerContainer">';
				content +=	'<div class="jTscroller">';
				for(var i=0;i<imageList.length;i++){
					var nr = i+1;
					if(i<9)
						nr="0"+(i+1);
					content+='<a href="'+imageList[i]["url"]+'"><img src="'+imageList[i]["url"]+'" alt="'+imageList[i]["description"]+'" title="'+imageList[i]["description"]+'" width="300" height="450" class="img_hover" /><span class="gallery_nr">'+nr+'</span></a>';
				}
				content += '</div>';
				content += '</div></div><div class="button_adjust">';
				content += '<a href="#" class="jTscrollerPrevButton"></a>';
				content += '<a href="#" class="jTscrollerNextButton"></a>';
				content += '</div>';
				
				if(typeof(collection_image)!="undefined" && collection_image!=""){ 
					content += '<div class="featured_image">';
					content += '<img src="'+collection_image+'" alt="Featured Image" title="Featured Image" /></div>';
				}
				content += '<div style="clear:both"></div>';
			}else{
				content = "<p class='no-images'> There are no images in this gallery</p>";
			}
			$(".content").html(content);
			
			
			// Activate the thumbnail scroller
			$("#tS1").thumbnailScroller({ 
				scrollerType:"hoverAccelerate", 
				scrollerOrientation:"horizontal", 
				scrollSpeed:2, 
				scrollEasing:"easeOutCirc", 
				scrollEasingAmount:600, 
				acceleration:4, 
				scrollSpeed:800, 
				noScrollCenterSpace:10, 
				autoScrolling:0, 
				autoScrollingSpeed:2000, 
				autoScrollingEasing:"easeInOutQuad", 
				autoScrollingDelay:500 
			});
			//Activate Colorbox for further image details
			$(".jTscroller a").colorbox({onComplete: function(){
				var src = $("#cboxLoadedContent img").attr("src");
				$("#cboxLoadedContent img").bind('click', function() {
					$("#cboxClose").trigger("click");
				});
				var icons = "<div class='icons_wrapper'>";
				icons += "<a class='print_icon' href='#' onclick=\"javascript:window.open(\'"+src+"\',\'mywindow\',\'width=322,height=323,left=650,top=-1\'); location.href=\'javascript:window.print()\'\">PRINT</a> ";
				icons += "<a class='email_icon' href='javascript:showEmail()'>EMAIL</a></div>";
				icons += "<div class='email_form'><table cellspacing='0' cellpadding='0'>";
				icons += "<tr><td>Name:</td><td><input type='text' class='name_elem' name='name'/></td></tr>";
				icons += "<tr><td>Email:</td><td><input type='text' class='email_elem' name='email'/><input type='hidden' class='image_elem' name='image' value='"+src+"'/><input type='hidden' class='collection_elem' name='collection' value='"+collection_parent+" - "+collection_name+"'/></td></tr>";
				icons += "</table>";
				icons += "<input type='hidden' value='"+src+"' name='image_elem' /></td><td><input type='button' onclick='sendEmail()' value='Send Email' style='background: none repeat scroll 0 0 white;border: 1px solid black;font:17px BertholdAkzidenzGroteskLtCn'/></div>";
				$("#cboxLoadedContent").append(icons);
			}});
				
			setTimeout("showGallery()",4000);	
		}, 
		complete: function(){
				
		}
	});	
	
}

function showEmail(){
	$(".email_form").fadeIn(700);			
}
function sendEmail() {
	var name = $(".name_elem").val();
	var email = $(".email_elem").val();
	var image = $(".image_elem").val();
	var collection = $(".collection_elem").val();
	
	if(typeof(name)=="undefined" || name == "" || typeof(email)=="undefined" || email == ""  || typeof(image)=="undefined" || image == ""){
		alert("All fields are mandatory!");
	}else{
		$.ajax({
			type: "POST",
			url: "sendEmail.php",
			data: {name: name, email: email, image: image, collection: collection},
			success: function(data) {
				$(".email_form").html("<p class='thank_you_email'>Your email has been sent!</p>");	
				setTimeout("$('.email_form').fadeOut(700);",2000);
				
			}
		});
	}
	
}

function showGallery(){
	$(".featured_image").stop().fadeOut(700,function(){
		$(".jThumbnailScroller").css("visibility","visible");
		$(".button_adjust").fadeIn();	
	});
	
	$(".jTscroller a").hover(function(){
		$(this).stop(true,true).animate({opacity: "0.5"},250).animate({opacity: "1"},250);
	},function(){
		
	});	
}

function loadPage(url){
	if(url != "" && typeof(url) != "undefined"){
		window.location=url;
	}else alert("Invalid URL !");
}
function displayHiddenContent(content){
	var html = '<div class="staticPage">';
	html += $('.'+content).html();
	html += '</div>';
	
	$(".content").fadeOut(400, function(){
		$(".content").html(html).fadeIn(400);
	});
}
function changeBackground(bg){
	/*if(typeof(bg)!="undefined" && bg!=""){
		if(bg!=background){
			background = bg;
			$(".page_wrapper").css("background","url('images/"+bg+"') repeat-x scroll 0 0 #4f4f4f");
			$("body").css("background","#4f4f4f");
			$("html").css("background","#4f4f4f");
		}
	}else{
		if(bg!=background){
			background = "background_new.png";
			$("body").css("background","black");
			$("html").css("background","black");
			$(".page_wrapper").css("background", "url('images/background_new.png') repeat-x scroll 0 -80px transparent");
		}
	}
	*/
}
/*
	INITIALIZATION AREA
*/
function Initialize(){	
	//Initialization to first menu item
	$(".main_slider").css("top","-1000px");
	$(".submenu_slider").css("top","-1000px");
}
function generateCallback(this_elem){
	var cb = "";
	var type = this_elem.find('type').text();
	if(typeof(type)!="undefined"){ 
		switch(type){
			case "static": 
				var identifier = this_elem.find('identifier').text();
				cb = "loadStaticHTML('"+identifier+"')";
			break;
			case "staticHTML": 
				var identifier = this_elem.find('identifier').text();
				cb = 'loadStaticHTML("'+identifier+'")';
			break;
			
			case "gallery": 
				var gallery_id = this_elem.find('gallery_id').text();
				cb = 'loadGallery("'+gallery_id+'")';
			break;
			
			case "link": 
				var link = this_elem.find('link').text();
				cb = 'loadPage("'+link+'")';
			break;
			
			case "contact": 
				cb = 'displayHiddenContent("contact")';
			break;
			
			case "login_register": 
				cb = 'displayHiddenContent("login_register")';
			break;
			
			case "points_sale": 
				cb = 'displayHiddenContent("points_sale")';
			break;
		}
	}
	return "onclick='"+cb+"'";
}
function generateMenu(){
	$.ajax({
		type: "GET",
		url: "xml/menu_"+language+".xml",
		dataType: "xml",
		success: function(xml) {
			$(xml).find('menu').each(function(){
				
				var menu_content = '<ul class="menu">';
				$(this).find("category").each(function(){
					var title = $(this).find('categ_title').text();
					var size = $(this).find('size').text();
					menu_content +='<li>';
					
					var callback = generateCallback($(this));
					if(typeof(callback)=="undefined"){
						callback="";
					}
					menu_content +='<a href="#'+language+'" '+callback+' class="headings">'+title+'</a>';
					
					$subcategories = $(this).find('subcategories');
					if(typeof($subcategories)!="undefined"){ 
						menu_content +='<ul class="submenu">';
						$subcategories.find('subcategory').each(function(){
							var title_subcateg = $(this).find('subcategory_title').text();
							var background = $(this).find('background').text();
							
							if(typeof(background)!="undefined" && background!=""){
								background = 'rel=\"'+background+'\"';
							}else background = '';
							
							menu_content += '<li class="submenu_item">';
							
							var callback = generateCallback($(this));
							if(typeof(callback)=="undefined"){
								callback="";
							}
							
							var elem_class = $(this).find('class').text();
							if(typeof(elem_class)=="undefined"){
								elem_class="";
							}
							menu_content += '<a href="#'+language+'" '+callback+' '+background+' class="link '+elem_class+'">'+title_subcateg+'</a>';
							
							$entries = $(this).find('entries');
							if(typeof($entries)!="undefined"){ 
								menu_content += '<ul class="submenu_list">';
								$entries.find('entry').each(function(){
									var entry_title = $(this).find('entry_title').text();
									var entry_class = $(this).find('class').text();
									if(typeof(entry_class)=="undefined"){
										entry_class="";
									}
									
									var callback = generateCallback($(this));
									if(typeof(callback)=="undefined"){
										callback="";
									}
									
									menu_content += '<li><a href="#'+language+'" '+background+' class="'+entry_class+'" '+callback+' >'+entry_title+'</a></li>';
								});
								menu_content += '</ul>';
							}
							menu_content += '</li>';
						});
						menu_content += '</ul>';
					}
					menu_content += '</li>';
				});
				menu_content += '</ul>';
				$(".menu_wrapper").html(menu_content);
			});
		}, 
		complete: function(){
			/*
			=====================================================
				After building the menu load other scripts etc.
			=====================================================
			*/
			Initialize();
			
			/*=====================================================
				Get static pages and build staticPage array   //getPages();
			=====================================================*/
			
			//Clicking on main menu items
			$(".menu .headings").click(function(){
				//Slide UP ALL 
				$(".submenu").slideUp(function(){});			
				
				var $menu_item = $(this);
				$menu_item.parent().children(".submenu").slideDown(function(){
					
					//Move the main slider to position
					$mainSlider  = $(".main_slider");
					$el = $menu_item;
					topPos = $el.position().top - browserAberation;
					$mainSlider.stop().animate({
						top: topPos
					}, 850);
					
					//Move the submenu slider to first element
					$submenuSlider  = $(".submenu_slider");
					$el = $menu_item.parent().children(".submenu").children("li").first();
					
					if($el.position()!=null){
						//alert("Heading has children ... ");
						topPos = $el.position().top - browserSubmenuAberation;
						$submenuSlider.show().stop().animate({
							top: topPos
						}, 850);
						
						$(".submenu li").removeClass("active");
						$el.addClass("active");
						
						
						// ------- Set BACKGROUND IMAGE -------
						var bg = $el.children("a").attr("rel");
						changeBackground(bg);
						
						
						//If there is a sub-submenu then position to the first element of that menu
						if($el.children(".submenu_list").html() != ""){
							$(".submenu_slider").show();
							$(".submenu_select_slider").css("top","topPos").slideDown(400);
							$submenuSelectSlider  = $(".submenu_select_slider");
							$el = $el.children(".submenu_list").children("li").first();
							$el.children("a").trigger("click");
							
							
							
							// ------- Set BACKGROUND IMAGE -------
							var bg = $el.children("a").attr("rel");
							changeBackground(bg);
							
							
							
							if(typeof($el.position())!='undefined' && $el.position() != null){
								topPos = $el.position().top - browserSubmenuListAberation;
								$submenuSelectSlider.stop().animate({
									top: topPos
								}, 850);
								
								$(".submenu_list li").fadeOut(400).removeClass("active");
								$el.fadeIn(400).addClass("active");
							}else{
								$submenuSelectSlider.hide();
							}
						}else{ 
							// Doesn't have sub-submenu items so trigger the action there
							$el.children("a").first().trigger("click");
							
							//Animate to the position of main item
							$submenuSelectSlider  = $(".submenu_select_slider");
							$submenuSelectSlider.stop().animate({
								top: topPos
							}, 850);
							//Hide
							$submenuSelectSlider.hide();
						}
												
						$(".jcarousel-skin-tango").fadeOut().fadeIn();
					}else{
						$(".submenu_slider").hide();
						$(".submenu_select_slider").hide();
					}
					$(".menu .headings").removeClass("active");
					$menu_item.addClass("active");
				});
				
			});
			
			//Clicking on submenu items
			$(".submenu .submenu_item .link").click(function(){
				
				//Move the main slider to position
				$parent_heading  = $(this).parent().parent().parent().children(".headings");
				$mainSlider  = $(".main_slider");
				
				if(!$parent_heading.hasClass("active")){
					topPos = $parent_heading.position().top - browserAberation;
					$mainSlider.stop().animate({
						top: topPos
					}, 850);
				}
				
				//Set element to active
				$(".menu .headings").removeClass("active");
				$parent_heading.addClass("active");
			
			
				//Move the submenu slider to first element
				$submenuSlider  = $(".submenu_slider");
				$el = $(this).parent();
				
				$(".submenu li").removeClass("active");
				$el.addClass("active");
				
				
				// ------- Set BACKGROUND IMAGE -------
				var bg = $el.children("a").attr("rel");
				changeBackground(bg);
				
				
				//If there is a submenu substract the submenu height from top position
				if($el.children(".submenu_list").length){
					topPos -= $el.children(".submenu_list").height();
				}
				
				topPos = $el.position().top - browserSubmenuAberation;
				$submenuSlider.stop().animate({
					top: topPos
				}, 850, function(){
					$el.children(".submenu_list").fadeIn(400);
				});
				
				
				//If there is a sub-submenu then position to the first element of that menu
				if($el.children(".submenu_list").html() != ""){
					$(".submenu_select_slider").css("top","topPos").slideDown(400);
					$submenuSelectSlider  = $(".submenu_select_slider");
					$el = $el.children(".submenu_list").children("li").first();
					$el.children("a").trigger("click");
					
					
					// ------- Set BACKGROUND IMAGE -------
					var bg = $el.children("a").attr("rel");
					changeBackground(bg);
				
				
					if(typeof($el)!='undefined' && $el != null){
						topPos = $el.position().top - browserSubmenuListAberation;
						$submenuSelectSlider.stop().animate({
							top: topPos
						}, 850);
						
						$(".submenu_list li").fadeOut(400).removeClass("active");
						$el.fadeIn(400).addClass("active");
					}else{
						$submenuSelectSlider.hide();
					}
				}else{
					//Animate to the position of main item
					$submenuSelectSlider  = $(".submenu_select_slider");
					if($.browser.msie && parseInt($.browser.version, 10) == 7) {
						topPos += 2;
					}
					$submenuSelectSlider.stop().animate({
						top: topPos
					}, 850);
					//Hide
					$submenuSelectSlider.hide();
				}
				
				$(".jcarousel-skin-tango").fadeOut().fadeIn();
				
			});
						
			//Clicking on submenu items
			$(".submenu_item .submenu_list li").click(function(){
				$submenuSelectSlider  = $(".submenu_select_slider");
				$el = $(this);
				
				
				// ------- Set BACKGROUND IMAGE -------
				var bg = $el.children("a").attr("rel");
				changeBackground(bg);
				
				topPos = $el.position().top - browserSubmenuListAberation;
				if($.browser.msie && parseInt($.browser.version, 10) == 7) {
					topPos -= 2;
				}
				$submenuSelectSlider.stop().animate({
					top: topPos
				}, 850);
				
				$(".submenu_list li").removeClass("active");
				$el.addClass("active");
				
				$(".jcarousel-skin-tango").fadeOut().fadeIn();
			});
		}
	});
}

/*
-------------------------------------------------------
	Mouse scroll event for triggering gallery move
-------------------------------------------------------
*/
/** This is high-level function.
 * It must react to delta being more/less than zero.
 */
function handle(delta) {
    if (delta < 0)
		$(".jcarousel-next").trigger("click");
    else
		$(".jcarousel-prev").trigger("click");
}

/** Event handler for mouse wheel event.
 */
function wheel(event){
        var delta = 0;
        if (!event) /* For IE. */
                event = window.event;
        if (event.wheelDelta) { /* IE/Opera. */
                delta = event.wheelDelta/120;
        } else if (event.detail) { /** Mozilla case. */
                /** In Mozilla, sign of delta is different than in IE.
                 * Also, delta is multiple of 3.
                 */
                delta = -event.detail/3;
        }
        /** If delta is nonzero, handle it.
         * Basically, delta is now positive if wheel was scrolled up,
         * and negative, if wheel was scrolled down.
         */
        if (delta)
                handle(delta);
        /** Prevent default actions caused by mouse wheel.
         * That might be ugly, but we handle scrolls somehow
         * anyway, so don't bother here..
         */
        if (event.preventDefault)
                event.preventDefault();
	event.returnValue = false;
}

/** Initialization code. 
 * If you use your own event management code, change it as required.
 */
if (window.addEventListener)
        /** DOMMouseScroll is for mozilla. */
        window.addEventListener('DOMMouseScroll', wheel, false);
/** IE/Opera. */
window.onmousewheel = document.onmousewheel = wheel;
