$(document).ready(function () {

	if(navigator.platform.indexOf("Mac") != -1 ) {
		$('body').addClass('mac');
		
	}
	
	// Init Main menu
	initMainMenu();

	// Call functions specific to each page
	switch (getUrlVarsFrom(document.location.href, true)['tabid']) {

	case '1':
		fixBlogTitles();
		initHome();
		break;
	case undefined:
		fixBlogTitles();
		initHome();
		break;
	case '10':
		initDealerOnFair();
		break;
	case '15':
		initPressReleaseDetail();
		break;
	case '17':
		initDealersByName();
		break;
	/*case '21':
		loadMap();
		break;*/
	case '148':
		fixBlogTitles();
		initPostList();
		adjustPostImage();
		break;
	case '149':
		fixBlogTitles();
		adjustPostImage();
		break;
	}
	
	
	handlePlaceHolderText();
	handleLanguageMenu();
	addShadowToFeatured();
})


function cleanEmptySpans(){
	
	$('span').each(function(index,domEle){
		if ($(domEle).html() == '') $(domEle).remove();
	})
	
}

function initPressReleaseDetail(){

	cleanEmptySpans();	

}

// Put line breaks on titles
function fixBlogTitles() {
	$('.event-title-container').each(function (index, domEle) {
		
		var 
		parts = $(domEle).html().split('|'),
		output = '';
		
		for (var i=0; i < parts.length; i++) {
			if (i == 0) { output += '<span class="event-title bold">'; } else {
				output +='</span><span class="secondary-text">';
			}
			output += parts[i];
			
		}
		output +='</span>';
		$(domEle).html(output)
	})
}

//Add shadow to featured
function addShadowToFeatured() {
	
	$('.featured-container').addClass('featured-shadow').wrap('<div class="shadow-cutter" />')
	
}

// Gallery description page
function showAddress(address) {
	var map = new Array(), geocoder = new Array();
	
		if (address[0] != '') {
			$('div.left-area').append('<div class="map" id="map' + 0 + '" />');
			$('div.left-area').append('<a class="large-map" target="_blank" href="http://maps.google.com/maps?f=d&hl=fr&saddr=' + address[0] + '">Afficher sur une carte plus grande</a>');
			
			map[0] = new GMap2(document.getElementById("map" + 0));
			
			var mapb = map[0];
			
			
			
			geocoder[0] = new GClientGeocoder();
			
			
			geocoder[0].getLatLng(
			address[0], function (point) {
				
				
				
				if (!point) {
					$('div#map' + 0).remove();
				} else {
					
					map[0].setCenter(point, 14);
					var marker = new GMarker(point);
					map[0].addOverlay(marker);
		
				}
			});
		
		
	}
	
	
	
	if (address[1] != '' && address[1] != null) {
			$('div.left-area').append('<div class="map" id="map' + 1 + '" />');
			$('div.left-area').append('<a class="large-map" target="_blank" href="http://maps.google.com/maps?f=d&hl=fr&saddr=' + address[1] + '">Afficher sur une carte plus grande</a>');
			
			map[1] = new GMap2(document.getElementById("map" + 1));
			
			var mapb = map[1];
			
			
			
			geocoder[1] = new GClientGeocoder();
			
			
			geocoder[1].getLatLng(
			address[1], function (point) {
				
				
				
				if (!point) {
					$('div#map' + 0).remove();
				} else {
					
					map[1].setCenter(point, 14);
					var marker = new GMarker(point);
					map[1].addOverlay(marker);
		
				}
			});
		
		
	}
	
}




// map functions (contact page)

function loadMap() {
	if (GBrowserIsCompatible()) {
		var map1 = new GMap2(document.getElementById("map"));
		var point = new GLatLng(51.508687, -0.151518);
		map1.setCenter(point, 15);
		var marker = new GMarker(point);
		map1.addOverlay(marker);
		map1.addControl(new GSmallMapControl());

	}
}

// Language menu
function handleLanguageMenu() {

	$("ul.lang-menu > li > a").each(function (index, domEle) {

		var currentLg = getUrlVarsFrom(window.location.href, false)['lg'],
			newLg = getUrlVarsFrom($(domEle).attr('href'), false)['lg'];
		if (currentLg != newLg) {

			if (currentLg === undefined) {
				if (getUrlVarsFrom(window.location.href, false)['tabid'] != undefined) {
					
					$(domEle).bind('click', function () {
						window.location = window.location.href + '&lg=' + newLg;
						return false;
					})
				}
			} else {
				$(domEle).bind('click', function () {
					window.location = window.location.href.replace('lg=' + currentLg, 'lg=' + newLg);
					return false;
				})
			}

		} else {
			$(domEle).bind('click', function () {
				window.location = window.location.href;
				return false;
			})

		}

	})

}

/* Search Functions */

function submitQuickSearch() {
    var keyWords = document.getElementById('inpQuickSearch').value;
    document.location.href = document.location.href.split('?')[0] + '?tabid=82&keyword=' + keyWords;
}

function submitCategory() {
    var url = document.getElementById('selCategory').value;
    document.location.href = document.location.href.substr(0, document.location.href.indexOf('DesktopDefault.aspx')) + url;
}

function entsub(e) {
    var evt = window.event ? e.keyCode : e.which;
    var keyPressed = evt;

    if (keyPressed == 13) {
        submitQuickSearch();
        return false;
    } else {
        return true;
    }
}

function handlePlaceHolderText() {
    $('input[type=text]').focus(function () {
        if ($(this).val() == $(this).attr('defaultValue')) {
            $(this).val('');

        }
    });

    $('input[type=text]').blur(function () {
        if ($(this).val() == '') {
            $(this).val($(this).attr('defaultValue'));

        }
    });


    $('textarea').focus(function () {
        if ($(this).val() == $(this).attr('defaultValue')) {
            $(this).val('');

        }
    });

    $('textarea').blur(function () {
        if ($(this).val() == '') {
            $(this).val($(this).attr('defaultValue'));

        }
    });

}


// Posts
function initPostList(){
	
	// Distribute the images on the featured block
	$('.featured').data('loadedImages', 0);

	distributeMarginsEvenly('.featured .item', '.featured');

	$('.featured .item img').load(function () {

		$('.featured').data('loadedImages', $('.featured').data('loadedImages') + 1);

		if ($('.featured').data('loadedImages') == $('.featured .item img').length) {

			distributeMarginsEvenly('.featured .item', '.featured');

		}

	})
	
	// Set category names on title
	
	if (getUrlVarsFrom(document.location.href, true)['postcategoryid'] == 201 && $('a#fr').hasClass('active')) {
		
		$('h3 span.title-3').html('expositions');
	
	}
	
	if (getUrlVarsFrom(document.location.href, true)['postcategoryid'] == 201 && $('a#en').hasClass('active')) {
		
		$('h3 span.title-3').html('exhibitions');
	
	}
	
}


// Dealer on Fair 
function initDealerOnFair(){
	
	// translate
	if ($('a#en').hasClass('active'))	$('h3.title-3').html('galleries');
	
	// remove text over map
	$(window).load(function(){
		
		$('div.map span').remove();
		$('div.map a').remove();
		for (var i = 0; i < $('div.map').length; i++) {
			$('div.map').eq(i).next('a.large-map').appendTo('div.map:eq(' + i + ') .gmnoprint');
		}
		$('div.map .gmnoprint').show();
		$('div.map .gmnoprint a').show();
	})
	
	
	$('table.image-table div.item').each(function(index, domEle){
		
		$(domEle).appendTo('div.featured div.slider');
		
	})
	var
	currentImage, 
	currentIndex = -1,
	myTimer, 
	totalScreens = 1,
	currentScreen = 1,
	screenSeparator = 65,
	images = [];
	
	// init slider
	var loadedThumbs = 0;

	if ($('div.slider div.item img').length == 0) {
		$('div.featured-container').addClass('empty');
	} else
	
	$(window).load(
    function() {
					var
						serieWidth = 0;
					for (var i = 0; i < $('div.slider div.item img').length; i ++) {

						serieWidth += $($('div.slider div.item img')[i]).width()

						+ parseInt($($('div.slider div.item img')[i]).css('margin-right').replace('px', ''))

						+ parseInt($($('div.slider div.item img')[i]).css('margin-left').replace('px', ''));

						
						if (serieWidth >= 900) {

							totalScreens++;
							
							$($('div.slider div.item')[i]).css('margin-left', screenSeparator);

							serieWidth = $($('div.slider div.item img')[i]).width()

							+ parseInt($($('div.slider div.item img')[i]).css('margin-right').replace('px', ''))

							+ parseInt($($('div.slider div.item img')[i]).css('margin-left').replace('px', ''));
						}
						
						$($('div.slider div.item img')[i]).data('serie', totalScreens);
						$($('div.slider div.item')[i]).addClass('serie' + totalScreens);


					}
					
					
					if (totalScreens == 1) {
					
						$('div.controls-1').hide();
						
						$('div.slider-container').css('width', 960);
						$('div.slider').css('width', 960);
						
						distributeMarginsEvenly('.serie1', 'div.slider-container');
						
						screenSeparator = 0;
						
					} else {
						
						// set container size
						$('div.featured div.slider').width(totalScreens * (900 + screenSeparator));
					
						for (var i = 1; i <= totalScreens; i++) {
						
							//$('.serie' + i).wrapAll('<div class="screen' + i + '" />');
							
							distributeMarginsEvenly('.serie' + i, 'div.slider-container');

						}
						
					
					
					
					

					// setup navigation button events
					if (totalScreens > 1) {

						$('div.controls-1 a.previous').click(function () {
						
							if (currentScreen > 1) {
								$('div.featured div.slider').animate({
									marginLeft: "+=" + ($('div.slider-container').width() + screenSeparator)
								}, 1500);
								
								currentScreen--;
								
								if (currentScreen == 1) { $('a.previous').hide(); $('a.next').show();}
								
								
								//Show first image of this serie
								$('div#navigation img').removeClass('active');
								$('div.slider div.item img.serie' + currentScreen + ':first').addClass('active');
								

								showImage($('div.slider div.item img.active').index(), false, 1500);
								
							}
							return false;
						});
						$('div.controls-1 a.next').click(function () {
							if (currentScreen < totalScreens) {
								$('div.featured div.slider').animate({

									marginLeft: '-=' + ($('div.slider-container').width() + screenSeparator)

								}, 1500);
								currentScreen++;
							
								if (currentScreen == totalScreens) { $('a.previous').show(); $('a.next').hide(); }
							
								//Show first image of this serie
								$('div#navigation img').removeClass('active');
								$('div.slider div.item img.serie' + currentScreen + ':first').addClass('active');
								

								
							
							}
							return false;
						});

					} 
					
				}
			})
	
	
}

// Distribute margins evenly

function distributeMarginsEvenly(el, parent) {
	totalWidth = 0;

	$(el).each(function (index, domEle) {

		totalWidth += $(domEle).width();

	})

	margins = ($(parent).width() - totalWidth) / ($(el).length - 1);

	$(el).css('margin-right', Math.floor(margins));
	$(el).last().css('margin-right', '0');
}

function initDealersByName() {

	

	// Calculate margins on slider to distribute the images evenly
	$('.slider').each(function (index, domEle) {

		$(domEle).data('loadedImages', 0);

		if ($('.object img', domEle).length == 3) {

			distributeMarginsEvenly($('.object', domEle), domEle);

			$('.object img', domEle).load(function () {

				$(domEle).data('loadedImages', $(domEle).data('loadedImages') + 1);

				if ($(domEle).data('loadedImages') == 3) {


					distributeMarginsEvenly($('.object', domEle), domEle);


				}

			})

		}

	})


	// Calculate margins on letter index to distribute the letters evenly
	$(window).load(function () {
		distributeMarginsEvenly('ul.letter-index li', '.featured');
	})

	// Add Class that indicates first letter of item
	$('div.block').each(function (index, domEle) {
		if ($('a.title-2 b', domEle).length > 0) $(domEle).addClass($('a.title-2 b', domEle).html().substring(0, 1));
	});

	// Insert anchor at first item with each letter
	$('ul.letter-index a').each(function (index, domEle) {
		$(domEle).attr('href', '#' + $(domEle).text().replace(/^\s+|\s+$/g, ""));
		$('div.block.' + $(domEle).text().replace(/^\s+|\s+$/g, "")).first().prepend('<a name="' + $(domEle).text().replace(/^\s+|\s+$/g, "") + '"></a>');
	})


}



// Set Blog image margins

function adjustPostImage() {

	$('p.blogImageStyle img').each(function (index, domEle) {

		if ($(domEle).css('float') == 'right') $(domEle).css('margin-right', 10);
		if ($(domEle).css('float') == 'left') $(domEle).css('margin-left', 0);
	});
}


//MENU FUNCTIONS

function nrKeys(a) {
	var i = 0;
	for (key in a) {
		i++;
	}
	return i;
}

function compareAssociativeArrays(a, b) {
	if (a == b) {
		return true;
	}
	if (nrKeys(a) != nrKeys(b)) {
		return false;
	}
	for (key in a) {
		if (a[key] != b[key]) {
			return false;
		}
	}
	return true;
}



var submenu;

function setInitialPosition() {

	showSub(submenu);


}

function showSub(index) {

	$('div#submenu .tab').hide();

	if ($('div#submenu .tabs-' + (index + 1) + ' li').length > 0) {

		$('div#submenu-container').css('visibility', 'visible');

		$('div#submenu .tabs-' + (index + 1)).show();

	} else {

		$('div#submenu-container').css('visibility', 'hidden');
	}

}

// Main menu

function initMainMenu() {
	var timeout;


	$('ul.main-menu a').each(function (index, domEle) {
		//check if menu directs to current page
		if (compareAssociativeArrays(getUrlVarsFrom(window.location.href, 1), getUrlVarsFrom($(domEle).attr('href'), 1))) {
			$(domEle).addClass('active');
		}

		// Align sub menu with it's parent
		$('div#submenu .tabs-' + (index + 1)).css('margin-left', $(domEle).offset().left - $('div.top').offset().left)

		$(window).load(function(){
			
			$('div#submenu .tabs-' + (index + 1)).css('margin-left', $(domEle).offset().left - $('div.top').offset().left);
			
		})

		// Show submenu when parent element is hovered
		$(domEle).hover(

		function () {

			if (timeout) clearTimeout(timeout);
			setInitialPosition();

			showSub(index);

		}, function () {
			if (timeout) clearTimeout(timeout);
			timeout = setTimeout("setInitialPosition()", 6200);


		}

		);

	});

	$('div#submenu .tab').each(function (index, domEle) {


		$(domEle).hover(

		function () {
			if (timeout) clearTimeout(timeout);

		}, function () {
			if (timeout) clearTimeout(timeout);
			timeout = setTimeout("setInitialPosition()", 6200);
		}

		);

	});
	switch (getUrlVarsFrom(document.location.href, true)['tabid']) {

case '20':
		submenu = 0;
		break;
	case '25':
		submenu = 0;
		break;
	case '26':
		submenu = 0;
		break;
	case '17':
		submenu = 1;
		break;
	case '10':
		submenu = 1;
		break;
	case '36':
		submenu = 1;
		break;
	case '38':
		submenu = 1;
		break;
	case '148':
		submenu = 2;
		break;
	case '149':
		submenu = 2;
		break;
	case '166':
		submenu = 2;
		break;
	case '24':
		submenu = 2;
		break;
	
	case '21':
		submenu = 3;
		break;
	case '22':
		submenu = 4;
		break;
	case '23':
		submenu = 5;
		break;
	}

	setInitialPosition();

}
// Home Page

// timer to make arrows blink
var blinkTimer=new Array();

function initHome() {

	// Distribute the images on the featured block
	distributeMarginsEvenly('.featured .item', '.featured');

	// Repeat margin distribuition after images are loaded
	$(window).load(function () {


		distributeMarginsEvenly('.featured .item', '.featured');

	})


	// Init Categories slider
	$(window).load(function () {

		// Take categories from footer and put them in columns
		$('div.right-area.categories div.slider-container div.slider').append('<ul class="col" />');

		totalHeight = 0;

		for (var i = 0; i < $('td#BottomPane .col-1 li').length; i++) {

			domEle = $($('td#BottomPane .col-1 li')[i]);

			$(domEle).clone().appendTo('div.right-area.categories div.slider-container div.slider ul:last');

			totalHeight += $($('div.right-area.categories div.slider-container div.slider li')[i]).outerHeight(true);

			if (totalHeight >= $('div.right-area.categories').height() - 15) {

				$('div.right-area.categories div.slider-container div.slider').append('<ul class="col" />');

				$($('div.right-area.categories div.slider-container div.slider li')[i]).appendTo('div.right-area.categories div.slider-container ul:last');

				totalHeight = $($('div.right-area.categories div.slider-container div.slider li')[i]).outerHeight(true);

			}



		}

		// Set the slider width
		var totalWidth = 0;

		$('div.right-area.categories div.slider-container div.slider ul').each(function () {

			totalWidth += $(domEle).width();

		})

		$('div.right-area.categories div.slider-container div.slider').width(totalWidth);

		// Hide back arrow
		$('div.block-1 div.controls-1 a.previous').css('visibility', 'hidden');

		// navigation controls
		var direction, position = 0;

		$('div.block-1 div.controls-1 a').click(function () {
			
			if (blinkTimer[$(this).data('index')])
			clearTimeout(blinkTimer[$(this).data('index')]);

			$(this).hasClass('previous') ? direction = 1 : direction = -1;


			$('div.right-area.categories div.slider-container div.slider').animate({

				marginLeft: '+=' + (direction * 229 * 3)

			});

			position -= direction * 3;

			// Show / Hide proper controls
			position == 0 ? $('div.block-1 div.controls-1 a.previous').css('visibility', 'hidden') : $('div.block-1 div.controls-1 a.previous').css('visibility', 'visible');

			position >= $('div.right-area.categories div.slider-container div.slider ul').length - 3 ? $('div.block-1 div.controls-1 a.next').css('visibility', 'hidden') : $('div.block-1 div.controls-1 a.next').css('visibility', 'visible');

			return false;

		});
	})

	$('div.slider-block').each(function (index, domEle) {
		initHomeSliders(domEle);
	})
	
	// Make arrows blink
	
	$('div.controls-1 a.next').each(function(index,domEle){
	
		$(domEle).addClass('index' + index);
		
		$(domEle).data('index', index);
		
		blinkTimer[index] = setTimeout('makeBlink("' + index + '")', 2000);
		
	})

}


function initHomeSliders(block) {
	
	//Init the exhibitions slider
	$(block).data('loaded-images', '0');

	//Remove invalid images
	$('table.post-table td div.object', block).each(function (index, domEle) {

		if (
			(
				($('img', domEle).attr('src') != undefined && $('img', domEle).attr('src').match(/jpg|gif/i) == null) 
				
			) || 
			
			$('img', domEle).attr('src') == undefined
			
		) {
			$('img', domEle).remove();
			
		} 
	})


	var totalImages= $('table.post-table td div.object', block).find('img:first').length;

	// Create slider
	$('table.post-table td div.object', block).each(function (index, domEle) {


		// if there is an image
		if ($('img', domEle).length > 0) {

			// add class used to the image block, so that it aquires the right margin
			$('div.image-area', domEle).addClass('used');

			// On blog, add image
			if ($('div.post-body img:first', domEle).length > 0) $('div.image-area', domEle).append($('div.post-body img:first', domEle));

			// When image is loaded
			$('div.image-area img', domEle).load(function () {
				
				$(this).removeAttr("width").removeAttr("height");
				
				if ($(this).width() > 340) $(this).css("height", 'auto');


				// Calculate the width of the container to fit the image and the text
				$(domEle).css('width', Math.ceil(
				$('div.image-area', domEle).width() + $('div.image-area', domEle).css('margin-right') + $('div.text-area', domEle).outerWidth(true)))

				// Increment loaded images counter
				$(block).data('loaded-images', parseInt($(block).data('loaded-images')) + 1);


				

				// If all images are loaded
				if ($(block).data('loaded-images') == totalImages) {
					
					
					// total width of the slider
					var slideWidth = 0;

					// number of slides
					$(block).data('total-slides', 0);

					// outer width of the current object
					var outerWidth = 0;
					
					// number of items in current slide
					var items = -1;
					
					$('div.object', block).each(function (index, domEle) {
						
						items ++;
						
						// calculate total width
						outerWidth =
						$(domEle).width() + 
						parseFloat($(domEle).css('margin-right').replace('px', '')) +
						parseFloat($(domEle).css('margin-left').replace('px', '')) +
						parseFloat($(domEle).css('padding-right').replace('px', '')) +
						parseFloat($(domEle).css('padding-left').replace('px', ''));
						
						
						slideWidth += outerWidth + 1;

						// if the current image doesn't fit in the current slide, pull it to the next one
						if (slideWidth >= $('div.right-area div.slider', block).width()) {

							// calculate room left
							var roomLeft = $('div.right-area div.slider', block).width() - slideWidth + outerWidth;
							
							// distribute the room left among the last objects
							for (var i = 1; i <= items; i++) {
								
								$('div.object .text-area', block).eq(index-i).css('width', $('div.object .text-area', block).eq(index-i).width() + (roomLeft / (items)));
								
							}
							
							
							/*$('div.block-exhibitions div.object .text-area').eq(index-2).css('width', $('div.block-exhibitions div.object .text-area').eq(index-2).width() + (roomLeft / 2));*/
							
							//$('div.block-exhibitions div.object .text-area').eq(index - 1).css('width', $('div.block-exhibitions div.object .text-area').eq(index - 1).css('width') + (roomLeft / 2));

							$(block).data('total-slides', parseFloat($(block).data('total-slides')) + 1);

							slideWidth = outerWidth;
							
							$('div.object', block).eq(index-1).addClass('last');
							
							items = 0;					}
						

					})

					// apply the total width to the slider
					$('div.slider', block).css('width', (parseFloat($(block).data('total-slides')) + 1) * $('div.slider-container', block).width());
					
					

					// Show controls
					$('.controls-1').fadeIn();
				}

			})
			
		}

		// Move the slider 
		
	$('div.right-area div.slider', block).append(domEle);

		$('div.object', block).last().addClass('last');


	})
	


	// Hide back arrow initialy
	$('div.controls-1 a.previous', block).css('visibility', 'hidden');

	// navigation controls
	var exhibitionsDirection, exhibitionsPosition = 0;

	$('div.controls-1 a', block).click(function () {

		if (blinkTimer[$(this).data('index')])
		clearTimeout(blinkTimer[$(this).data('index')]);
		

		$(this).hasClass('previous') ? exhibitionsDirection = 1 : exhibitionsDirection = -1;


		$('div.right-area div.slider-container div.slider', block).animate({

			marginLeft: '+=' + (exhibitionsDirection * 229 * 3)

		}, function() {
			
			exhibitionsPosition -= exhibitionsDirection * 3;

			// Show / Hide proper controls
			exhibitionsPosition == 0 ? 
			$('div.controls-1 a.previous', block).css('visibility', 'hidden') : 
			$('div.controls-1 a.previous', block).css('visibility', 'visible');
	
			if (
				$('div.object:last', block).offset().left +
				$('div.object:last', block).outerWidth(true) <
				$('div.slider-container', block).offset().left + 
				$('div.slider-container', block).outerWidth(true)
			) {
				$('div.controls-1 a.next', block).css('visibility', 'hidden');
				
			} else {
			
				$('div.controls-1 a.next', block).css('visibility', 'visible');
				
			}
			
		});

	

		return false;

	});
	
	
	
	
}

function makeBlink(index){
	
	
	clearTimeout(blinkTimer[index]);
	$('div.controls-1 a.next.index' + index).fadeOut(400).fadeIn(400).fadeOut(400).fadeIn(400);	
	blinkTimer[index] = setTimeout('makeBlink("' + index + '")', 4000);
	
}

// Get variables from the url

function getUrlVarsFrom(url, preventUnwantedVars) {
	var vars = [],
		hash;
	var hashes = url.split('#')[0].slice(url.indexOf('?') + 1).split('&');
	for (var i = 0; i < hashes.length; i++) {
		hash = hashes[i].split('=');
		if (preventUnwantedVars == 1) {
			if (hash[0] != 'lg' && hash[0] != 'objectid' && hash[0] != 'tabindex' && hash[0] != 'page' && hash[0] != 'keyword' && hash[0] != 'mediaid') {
				if (hash[0] == 'categoryid' && hash[1] == 0) {} else {
					vars.push(hash[0]);
					vars[hash[0]] = hash[1];
				}
			}
		} else {
			vars.push(hash[0]);
			vars[hash[0]] = hash[1];
		}
	}
	return vars;
}
