var globalSlideTimeout = 7000;
//var globalDebug = false;
var globalDebug = true;
var globalAutoplay = true;
var globalDict = new Dictionary();
var globalLinkOpacity = 0.7; 
var globalGalleryOpacity = 0.55

function Dictionary()
{
	this.lang = globalLanguage; // defined in HTML page
	
	this.i18n = {};

	this.i18n.en = {
		"click.toggle" : "Click to show or hide the index"
	}	
	this.i18n.fr = {
		"click.toggle" : "Cliquez pour afficher ou cacher l'index"
	}	
	
	this.translate = function(stringId)
	{
		return this.i18n[this.lang][stringId];
	}
}

function log(x)
{
	if( window.console && window.console.log)
	{
		window.console.log(x);
	}
	else
	{
		if( globalDebug)
		{
			alert(x);
		}
	}
}

function mainmenu()
{
    $(" #nav ul ").css({display: "none"}); // Opera Fix
    $(" #nav li").hover(
        function(){
            $(this).find('ul:first').css({visibility: "visible",display: "none"}).slideToggle(400);
		},
		function(){
            $(this).find('ul:first').slideToggle(200, function(){ $(this).css({visibility: "hidden"});} );
		});
}

$(function() {

    externalLinks();
    
    
    $('#menu-top-flags a')
    .css( {'opacity' : globalLinkOpacity})
	.hover( function(){
		$(this).stop().animate({ 'opacity': 1}, {duration:500})
	}
	,
	function(){
		$(this).stop().animate({'opacity': globalLinkOpacity}, {duration:500})
	});
    
    $('#menu-main a')
    .css( {'opacity' : globalLinkOpacity})
	.hover( function(){
		$(this).stop().animate({ 'opacity': 1}, {duration:500})
	}
	,
	function(){
		$(this).stop().animate({'opacity': globalLinkOpacity}, {duration:500})
	});

    if( !$.browser.msie)
    {
        $('#menu-main a').each(function()
        {
            applyShadow( this, "#000", {left:13,top:-10});
        });
	}
    
//    $('#left-wine').show().css('opacity', 0);
//    setTimeout( function(){
//    	log('left-wine animate');
//    	$('#left-wine').animate({'opacity': 1}, {duration:3000});
//    	$('#left-wine').animate({'opacity': 0}, {duration:3000});
//    },
//    1000);
/*   
	    $('#wrapper').cycle({
	        timeout:  globalSlideTimeout,
	        speed:    1500,
	        slideExpr: '.slide2',
	        fx:      'custom',
//	        cssFirst: {
//        		display: 'block',
//        		left: '-20px',   
//        		opacity: 0.7
//    		},
	  	    cssBefore: {  
//        		top: 0,
        		display: 'block',
        		left: 0,
        		top: 0,   
        		opacity: 0
        		 
    		},
	  	    cssAfter: {  
//        		left: -60,   
//        		display: 'none',
				left: 0,
				top: 0,
        		opacity: 0 
    		},
    		animIn: {  
		        opacity: 0.7,
		        left: '-20px'
		    }, 
		    animOut: {  
		        opacity: 0,
		        left: '-60px',
		    }
//			pauseOnPagerHover: true
	    });
*/    
 /*   
    var orient = 'left';
    
    if( orient == 'left')
    {
	   	$('.slide-desc h1 span.slide-g7').each(function()
		{
			applyShadow( this, "#000", {left:1,top:1});
		});
	
	   	$('.slide-desc h1 span.slide-cms').each(function()
		{
			applyShadow( this, "#000", {left:1,top:1});
		});
    }
    else
    {
	   	$('.slide-desc h1 span.slide-g7').each(function()
		{
			applyShadow( this, "#000", {left:182,top:1});
		});
	
	   	$('.slide-desc h1 span.slide-cms').each(function()
		{
			applyShadow( this, "#000", {left:78,top:1});
		});
    }
    
   	$('.slide-desc h2').each(function()
	{
		applyShadow( this, "#000", {left:1,top:1});
	});

   	$('.slide-desc li').each(function()
	{
		applyShadow( this, "#000", {left:1,top:1});
	});

   	$('.slide-desc p').each(function()
	{
		applyShadow( this, "#000", {left:1,top:1});
	});
	
   	$('.slide-desc h5').each(function()
	{
		applyShadow( this, "#000", {left:1,top:1});
	});
*/	
	$('.gallery a')
		.lightBox()
		.css( {'opacity' : globalGalleryOpacity})
		.hover( function(){
			$(this).stop().animate({ 'opacity': 1}, {duration:500})
		}
		,
		function(){
			$(this).stop().animate({'opacity': globalGalleryOpacity}, {duration:500})
		});
    
	$('.readmore a')
		.css( {backgroundPosition: "0 0"} )
		.hover( function(){
			$(this).stop().animate({ 'backgroundPosition': '(0 -200px)'}, {duration:500})
		}
		,
		function(){
			$(this).stop().animate({'backgroundPosition':"(0 0)"}, {duration:500})
		});
		
	if(globalAutoplay)
	{
//		$('#slideshow').hover(
//			function() { $('#controls').fadeIn(); },
//			function() { $('#controls').fadeOut(); }
//		);

	    // start slideshow
	    $('#slideshow').cycle({
			next:   '#next',
			prev:   '#prev',
	        timeout:  globalSlideTimeout,
	        speed:    500
	    });
/*
		$('#next').click(function(){
			$(this).css('opacity', 0.7);
			setTimeout(function(){
				$('#next').css('opacity', 1);
			},
			200);
		});
	
		$('#prev').click(function(){
			$(this).css('opacity', 0.7);
			setTimeout(function(){
				$('#prev').css('opacity', 1);
			},
			200);
		});
	
		$('#pause').click(function(){
			$('#slideshow').cycle('pause');
			$(this).css('opacity', 0.7);
			$('#play').css('opacity', 1);
			return false; 
		});
		
		$('#play').click(function() {
			$('#slideshow').cycle('resume');
			$(this).css('opacity', 0.7);
			$('#pause').css('opacity', 1);
			return false;
		});
		
		$('#play').css('opacity', 0.7);
*/		 
	}
    

});

        
function externalLinks()
{
	if (!document.getElementsByTagName)
		return;
		
	var anchors = document.getElementsByTagName("a");
	for (var i=0; i<anchors.length; i++)
	{
		var anchor = anchors[i];
		if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external")
			anchor.target = "_blank";
	}
}

function applyShadow(targetElement, shadowColor, offset) 
{
	if (typeof(targetElement) != 'object') 
	{
		targetElement = document.getElementById(targetElement);
	}
	
	var value = targetElement.firstChild.nodeValue;
	targetElement.style.position = 'relative';
	targetElement.style.zIndex = 1;
	
	var newEl = document.createElement('span');
	newEl.appendChild(document.createTextNode(value));
	newEl.className = 'shadowed';
	newEl.style.color = shadowColor;
	newEl.style.position = 'absolute';
	newEl.style.left = offset.left + 'px';
	newEl.style.top = offset.top + 'px';
	newEl.style.zIndex = -1;
	
	targetElement.appendChild(newEl);
}



(function($){ $.fn.fixedPosition = function(options){

    var defaults = {
	  vpos: null,    // posible values: "top", "middle", "bottom". if it is null the original position is taken
	  hpos: null     // posible values: "left", "center", "right". if it is null the original position is taken
	};
	
    var options = $.extend(defaults, options);
	
	return this.each(function(index) {
		
		
		var $this = $(this);
		$this.css("position","absolute");
		
		if(options.vpos === "top"){
		    $this.css("top","0");
		}
		else if(options.vpos === "middle"){
		    $this.css("top",((parseInt($(window).height())/2)-($(this).height()/2))+"px");
		}
		else if(options.vpos === "bottom"){
		    $this.css("bottom","0");
		}
		
		if(options.hpos === "left"){
		    $this.css("left","0");
		}
		else if(options.hpos === "center"){
		    $this.css("left",((parseInt($(window).width())/2)-($(this).width()/2))+"px");
		}
		else if(options.hpos === "right"){
		    $this.css("right","0");
		}
		
		var top = parseInt($this.offset().top);
		var left = parseInt($this.offset().left);
		
		$(window).scroll(
			function () {
				var newTop = top+$(document).scrollTop();
				$this.css("top",top+$(document).scrollTop()); //.css("left",left+$(document).scrollLeft());
			}
		);
	});

  
}})(jQuery);



function createTOC()
{
	function genId(domNode)
	{
		var text = $(domNode).text();
		return text.replace(/[^A-za-z0-9]/g,'-');
	}
	var options = {};
	options.top = 'INDEX';
	options.opacity = 0.3;
	
	$tocu = $('<div id="tocu" title="'+globalDict.translate('click.toggle')+'">'+
		'<p id="toc-title">'+options.top+'</p>'+
		'<div id="toc"></div>'+
		'<div id="tocu-close"></div>'+
		'</div>')
		.appendTo('#content');
		
	$tocuClose = $('#tocu-close');
		
	$toc = $('<ul></ul>').appendTo('#toc');

	$('#content h2').each( function(index){
		var id = genId(this);
		var idLink = id + '-ref';
		$h2 = $(this);
		this.id = id;
		$toc.append('<li><a id="' + idLink + '" href="javascript:void(0)">' + $h2.text() + '</a></li>');
		
		$('#'+idLink).bind('click', {'ref':id}, function(e){
			$.scrollTo( '#'+e.data.ref, 1000, { easing:'easeInOutCubic'});
		});

		$next = $(this).next();
		var $ul = null;
		do {
			if($next.is('h2'))
				break;

			if($next.is('h3'))
			{
				if( !$ul)
					$ul = $('<li><ul></ul></li>').appendTo( $toc).find('ul');

				id = genId($next[0]);
				idLink = id + '-ref';
				$next.attr('id', id);
				$ul.append('<li><a id="' + idLink + '" href="javascript:void(0)">' + $next.text() + '</a></li>');
				$('#'+idLink).data("scroll", "id");
				
				$('#'+idLink).bind('click', {'ref':id}, function(e){
					$.scrollTo( '#'+e.data.ref, 1000, { easing:'easeInOutCubic'});
				});
			}

			$next = $next.next();
			
		} while ($next.length);

		if(index)
		{		
			$('<div class="content-sep-line"><a href="javascript:void(0)">'+options.top+'</a></div>')
				.insertBefore(this)
				.find('a:first')
					.click( function(){$.scrollTo(0, 1000, { easing:'easeInOutCubic'});});
		}
		else
		{
			$('<div class="content-sep-line"><a href="javascript:void(0)">'+options.top+'</a></div>')
				.appendTo( $(this).parent())
				.find('a:first')
					.click( function(){$.scrollTo(0, 1000, { easing:'easeInOutCubic'});});
		}
	
	});

	$tocu
		.show()
		.hover(
			function()
			{
				$(this).css( {'opacity': 1});
				//log('hover in');
			}
			,
			function()
			{
				$(this).css( {'opacity': options.opacity});
				//log('hover out');
			}
		);
	
	var tocTitle = $('#toc-title').text();
	$('#toc-title').click(function(e){
		if( $tocuClose.is('.tocu-collapsed'))
		{
			var w = $tocu.data('w');
			var h = $tocu.data('h');
			$tocu.animate( 
				{width:w, height:h},
				'fast');
			$tocuClose.removeClass('tocu-collapsed');
		}
		else
		{
			if( typeof $tocu.data('h') == 'undefined')
			{
				$tocu
					.data('h', $tocu.height())
					.data('w', $tocu.width());
			}
			$tocu
				.css( {'opacity': 1})
				.animate( 
					{width:120, height:30},
					'fast',
					'linear',
					function(){
						$(this).css( {overflow: 'hidden'});
						$tocuClose.addClass('tocu-collapsed');
					});
				
		}
		e.stopPropagation();
	});
	
	$tocuClose.click(function(e){ 
		$('#toc-title').trigger('click')});
	
	setTimeout(function(){
		$('#toc-title').trigger('click');
		$tocu.css( {'opacity': options.opacity});
	},
	1000)
}


function ColorUtils() {
	
	var self = this;
	
	/* Various color utility functions */
	self.pack = function(rgb) {
		var r = Math.round(rgb[0] * 255);
		var g = Math.round(rgb[1] * 255);
		var b = Math.round(rgb[2] * 255);
		return '#' + (r < 16 ? '0' : '') + r.toString(16) + (g < 16 ? '0' : '')
				+ g.toString(16) + (b < 16 ? '0' : '') + b.toString(16);
	}

	self.pack2 = function(rgb) {
		var r = rgb[0];
		var g = rgb[1];
		var b = rgb[2];
		return '#' + (r < 16 ? '0' : '') + r.toString(16) + (g < 16 ? '0' : '')
				+ g.toString(16) + (b < 16 ? '0' : '') + b.toString(16);
	}

	self.unpack = function(color) {
		if (color.length == 7) {
			return [parseInt('0x' + color.substring(1, 3)) / 255,
					parseInt('0x' + color.substring(3, 5)) / 255,
					parseInt('0x' + color.substring(5, 7)) / 255];
		} else if (color.length == 4) {
			return [parseInt('0x' + color.substring(1, 2)) / 15,
					parseInt('0x' + color.substring(2, 3)) / 15,
					parseInt('0x' + color.substring(3, 4)) / 15];
		}
	}

	self.unpack2 = function(color) {
		if (color.length == 7) {
			return [parseInt('0x' + color.substring(1, 3)),
					parseInt('0x' + color.substring(3, 5)),
					parseInt('0x' + color.substring(5, 7))];
		} else if (color.length == 4) {
			return [parseInt('0x' + color.substring(1, 2) + color.substring(1, 2)),
					parseInt('0x' + color.substring(2, 3) + color.substring(2, 3)),
					parseInt('0x' + color.substring(3, 4) + color.substring(3, 4))];
		}
	}

	self.HSLToRGB = function(hsl) {
		var m1, m2, r, g, b;
		var h = hsl[0], s = hsl[1], l = hsl[2];
		m2 = (l <= 0.5) ? l * (s + 1) : l + s - l * s;
		m1 = l * 2 - m2;
		return [this.hueToRGB(m1, m2, h + 0.33333), this.hueToRGB(m1, m2, h),
				this.hueToRGB(m1, m2, h - 0.33333)];
	}

	self.hueToRGB = function(m1, m2, h) {
		h = (h < 0) ? h + 1 : ((h > 1) ? h - 1 : h);
		if (h * 6 < 1)
			return m1 + (m2 - m1) * h * 6;
		if (h * 2 < 1)
			return m2;
		if (h * 3 < 2)
			return m1 + (m2 - m1) * (0.66666 - h) * 6;
		return m1;
	}

	self.RGBToHSL = function(rgb) {
		var min, max, delta, h, s, l;
		var r = rgb[0], g = rgb[1], b = rgb[2];
		min = Math.min(r, Math.min(g, b));
		max = Math.max(r, Math.max(g, b));
		delta = max - min;
		l = (min + max) / 2;
		s = 0;
		if (l > 0 && l < 1) {
			s = delta / (l < 0.5 ? (2 * l) : (2 - 2 * l));
		}
		h = 0;
		if (delta > 0) {
			if (max == r && max != g)
				h += (g - b) / delta;
			if (max == g && max != b)
				h += (2 + (b - r) / delta);
			if (max == b && max != r)
				h += (4 + (r - g) / delta);
			h /= 6;
		}
		return [h, s, l];
	}
}

// gradientElements(".slide-desc h5")
function gradientElements(selector, color1, color2) 
{
    var count = $(selector).size();
    if( count==0)
    	return;

    var cu = new ColorUtils();
    var rgb1 = cu.unpack2(color1);
    var rgb2 = cu.unpack2(color2);
    var r = rgb1[0];
    var g = rgb1[1];
    var b = rgb1[2];
    var step_r = (rgb2[0] - rgb1[0]) / (count-1);
    var step_g = (rgb2[1] - rgb1[1]) / (count-1);
    var step_b = (rgb2[2] - rgb1[2]) / (count-1);
    
    $(selector).each( function(i) 
    {
	    var rgb = [];
	    rgb[0] = Math.round(r + step_r*i);
	    rgb[1] = Math.round(g + step_g*i);
	    rgb[2] = Math.round(b + step_b*i);
        var color = cu.pack2(rgb);
    	if( i== (count-1))
    	{
    		color = color2;
    	}
        $(this)	.css("color", color)
    });
}

function setAutoTooltip(selector)
{
	if( $(selector).length)
	{
		$(selector).hover(
			function(e){
				var idTT = $(this).attr('rel');
				var $idTT = $('#'+idTT);
                
                if($idTT.parent().get(0).tagName != 'BODY')
				{
                    $idTT.appendTo(document.body);
                }
                
				var dw = $(document).width();
				var tleft = e.pageX;
				if( tleft + $idTT.outerWidth() > dw)
					tleft -= $idTT.outerWidth();
                $idTT.css({top: e.pageY+30, left: tleft, zIndex: 999999});
				$idTT.fadeTo('normal', 0.9);
			}
			,
			function(){
				var idTT = $(this).attr('rel');
				var $idTT = $('#'+idTT);
				$idTT.css({zIndex: 0});
				$idTT.fadeTo('normal', 0);
			}
		);
	}
}

function cssAdd(pdocument, href)
{
	return;
	var pdocument2 = pdocument;
	if( typeof pdocument == "string")
	{
		pdocument = document.getElementById( pdocument).contentDocument;
		if( !pdocument)
		{
			if(!document.frames)
			{
				alert( 'document.frames null');
				return;
			}
			pdocument = document.frames[pdocument2].document;
		}
	}
	
	if( !document)
	{
		alert( 'cssAdd failed');
		return;
	}
	
	var cssNode = pdocument.createElement('link');
	cssNode.type = 'text/css';
	cssNode.rel = 'stylesheet';
	cssNode.href = href;
//	cssNode.media = 'screen';
//	cssNode.title = 'dynamicLoadedSheet';
	pdocument.getElementsByTagName("head")[0].appendChild(cssNode);
}

function doPrintIframe(iframe)
{
log('focus...');
	iframe.focus();
	
log('printing...');
	iframe.print();
//	print();
}

function doPrintDocument()
{
	if( $('#print-div').length)
	{
		$('#print-div').remove();
	}
	var location = ''+document.location;
	location = location.replace("#","");
	var d = new Date();
	location += '&random=' + d.getTime();
	location += '&action=print';
	if( globalDebug)
	{
		$('<div id="print-div" style="width:600px; height:600px; position:absolute; left:0; top:0; border:0 none; background:#ccc; z-index:999999;"> '+
			'<iframe src="'+ location + '" id="print-frame" name="print-frame" style="width:100%; height:100%;"></iframe> </div>').appendTo(document.body);
	}
	else
	{
		$('<div id="print-div" style="width:0px; height:0px; position:absolute; left:0; top:0; border:0 none; background:#ccc; z-index:999999;"> '+
			'<iframe src="'+ location + '" id="print-frame" name="print-frame" style="width:100%; height:100%;"></iframe> </div>').appendTo(document.body);
	}
	return;

	
	
	
	var $iframe = $('iframe');
    $iframe.load(function() 
    {
log('iframe loaded...');

		var $body = $iframe.contents().find('body');
		if( !$body.length)
		{
log('iframe no body...');
			return;
		}
		
		$body.css({ 
			'margin' : 0
			, 'padding' : 0
			, 'background' : '#fff'
			, 'text-align' : 'left'
		});
		
		$('script', $body).remove();
    	$('.content-sep-line', $body).remove();
    	$('.readmore', $body).remove();
    	$('#tocu', $body).remove();
    	$('#content', $body).appendTo($body);
    	$('#wrapper', $body).remove();
    	
    	
    	try{
    		//doPrintIframe( this); //$iframe.get(0));
    		doPrintIframe( frames["print-frame"]);
    	}
    	catch(err)
    	{
log('print failed...');
    	
    	}
    	
log('remove iframe...');

    	$iframe.parent().remove();
   	});
}

function doPreparePrint()
{
	var $body = $(document).find('body');
	$body.css({ 
		'margin' : 0
		, 'padding' : 0
		, 'background' : '#fff'
		, 'text-align' : 'left'
	});
	
	$('script').remove();
	$('.content-sep-line').remove();
	$('.readmore').remove();
	$('#tocu').remove();
	
	$('#content').appendTo($body);
	$('#wrapper').remove();

log('printing...');
	window.focus();
	print();
	
// in FF is Print() async .... so... don't close the hidden printing div
	
//	log('remove iframe...');	
//	$('#print-frame', window.top.document).parent().remove();
}
