var ActiveLanguage = 0;

function SetbackColor(elmnt, bckcolor) {
	document.getElementById(elmnt).style.background = bckcolor;
}

//-----------------------------------------------------------------------------
//Globals
//Major version of Flash required
var requiredMajorVersion = 9;
//Minor version of Flash required
var requiredMinorVersion = 0;
//Minor version of Flash required
var requiredRevision = 0;
//-----------------------------------------------------------------------------

var player;
var currentitem;
var firstitem;
var lastitem;

function stateplayer(obj) {
	$('.videotitle').hide();
	$('.videodescription').hide();
	$('.videotitle').eq(player.getConfig().item).show();
	$('.videodescription').eq(player.getConfig().item).show();
}

function playerReady(obj) {
	var id = obj['id'];
	var version = obj['version'];
	var client = obj['client'];
	// alert('the videoplayer \''+id+'\' has been instantiated.\nVersion : ' +
	// version + '\nClient : ' + client);
	player = document.getElementById(id);

	switch (id) {
	case 'playerID': // mediaTVcenter
		player.addModelListener('STATE', 'stateplayer');

	}
};

function MediaTVcenterInitPlayer(filename) {
	height=$('#player').css('height');
	width=$('#player').css('width'); 
	
	if (filename.indexOf('-1') != 0) {
		if (filename.indexOf('.php') >= 0) {
			//filetoplay = '/player/playlist.php?playlist=webtv';
			filetoplay = '/webtv.xml';
			repeat = 'always';
		} else {
			filetoplay = '/player/playlist.php?playlist=video&id=' + filename;
			repeat = 'none';
		}
	}
	
	jwplayer('player').setup({
		flashplayer: '/player/player.swf',
		file: filetoplay,
		config: './player/config.xml.php',
	  width: width,
	  height: height,
	  stretching: 'uniform',
		repeat: repeat,
		events: {
			onReady: function(){
				this.playlistItem(firstvideo);
			},
			onPlaylistItem: function(event) {
				$('.videodescription').hide();
				$('.videodescription').eq(event.index).show();
				currentitem = event.index;
				
				/* Analytics */
				Ajax('analytics/callback.php', 'file='+this.getPlaylist()[event.index]['file']+'&state=play', DoNothing());
			}
    }
	});
}

function MediaTVcenterInit(filename, lastvideo, highlights) {
	MediaTVcenterInitPlayer(filename);
	currentitem = -1;
	lastitem = lastvideo;
	if (highlights == 1) {
		$('.videotitle').eq(0).show();
		$('.videodescription').eq(0).show();
	}
}

function SimpleViewerInitPlayer(video) {
	// Version check based upon the values entered above in "Globals"
	var hasReqestedVersion = DetectFlashVer(requiredMajorVersion,
			requiredMinorVersion, requiredRevision);

	// Check to see if the version meets the requirements for playback
	if (hasReqestedVersion) { // if we've detected an acceptable version

		height = $('#placeholder').css('height');
		height = height.substr(0, height.length - 2);
		width = $('#placeholder').css('width');
		width = width.substr(0, width.length - 2);

		var s1 = new SWFObject('./player/player.swf', 'playerIDSimpleViewer',
				width, height, '9');

		s1.addParam('allowfullscreen', 'true');
		s1.addParam('allowscriptaccess', 'always');
		s1.addParam('wmode', 'transparent'); // opaque
		s1.addVariable('enablejs', 'true');
		s1.addVariable('javascriptid', 'playerIDSimpleViewer');

		s1.addVariable('config', './player/config.xml.php');

		s1.addVariable('plugins', 'yourlytics-1');
		s1.addVariable('yourlytics.callback', './analytics/callback.php');

		s1.addVariable('repeat', 'none');

		s1.addVariable('file', '../videos/' + video + '.flv');

		s1.write('placeholder');
	} else { // flash is too old or we can't detect the plugin
		document.getElementById('NoFlashInstalled').style.display = 'inline';
	}
}

function SimpleViewerInit(video) {
	SimpleViewerInitPlayer(video);
}

/** *************************************************************************** */
//stores the reference to the XMLHttpRequest object
var xmlHttp = createXmlHttpRequestObject();

//retrieves the XMLHttpRequest object
function createXmlHttpRequestObject() {
	// will store the reference to the XMLHttpRequest object
	var xmlHttp;
	// this should work for all browsers except IE6 and older
	try {
		// try to create XMLHttpRequest object
		xmlHttp = new XMLHttpRequest();
	} catch (e) {
		// assume IE6 or older
		var XmlHttpVersions = new Array('MSXML2.XMLHTTP.6.0',
				'MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0',
				'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP');
		// try every prog id until one works
		for ( var i = 0; i < XmlHttpVersions.length && !xmlHttp; i++) {
			try {
				// try to create XMLHttpRequest object
				xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
			} catch (e) {
			}
		}
	}
	// return the created object or display an error message
	if (!xmlHttp)
		alert("Error creating the XMLHttpRequest object.");
	else
		return xmlHttp;
}

function Ajax(serverAddress, params, handleServerResponsefunction) {

	// proceed only if the xmlHttp object isn't busy
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
		// execute the page from the server
		xmlHttp.open("POST", serverAddress, true);

		// send the proper header information along with the request
		xmlHttp.setRequestHeader("Content-type",
		"application/x-www-form-urlencoded");
		xmlHttp
		.setRequestHeader("Content-length",
				(params ? params.length : 0));
		xmlHttp.setRequestHeader("Connection", "close");

		// define the method to handle server responses
		xmlHttp.onreadystatechange = handleServerResponsefunction;

		// make the server request
		xmlHttp.send(params);
	} else
		// if the connection is busy, try again after one half second
		setTimeout('Ajax(\'' + serverAddress + '\', \'' + params + '\', '
				+ handleServerResponsefunction + ')', 500);
}

function mycarousel_itemVisibleInCallback(carousel, item, i, state, evt) {
	// The index() method calculates the index from a given index who is out of
	// the actual item range.
	var idx = carousel.index(i, mycarousel_itemList.length);
	carousel.add(i, mycarousel_getItemHTML(mycarousel_itemList[idx - 1]));
};

function mycarousel_itemVisibleOutCallback(carousel, item, i, state, evt) {
	carousel.remove(i);
};

function mycarousel_itemLoadCallback(carousel, state) {
	for ( var i = carousel.first; i <= carousel.last; i++) {
		if (carousel.has(i)) {
			continue;
		}

		if (i > mycarousel_itemList.length) {
			break;
		}

		carousel.add(i, mycarousel_getItemHTML(mycarousel_itemList[i - 1]));
	}
};

/**
 * Item html creation helper.
 */
function mycarousel_getItemHTML(item) {
	retour = '<a href="' + item.url + '" title="' + item.title + '">';
	retour += '<img src="' + item.picture + '" alt="' + item.title + '"/>';
	retour += '</a>';

	return retour;

};

function traduction(message) {
	switch (ActiveLanguage) {
	case 2: // Deutsch
		switch (message) {
		case 'Chargement en cours':
			returnmessage = 'Die Seite wird geladen';
			break;
		}
		break;
	case 1: // english
		switch (message) {
		case 'Chargement en cours':
			returnmessage = 'Loading';
			break;
		}
		break;
	default:
		returnmessage = message;
	}
	return returnmessage;
}

function handleGridPageLoad() {
	// move forward only if the transaction has completed
	if (xmlHttp.readyState == 4) {
		// status of 200 indicates the transaction completed successfully
		if (xmlHttp.status == 200) {
			// read the message from the server
			var xmlResponse = xmlHttp.responseXML;
			// obtain the XML's document element
			xmlRoot = xmlResponse.documentElement;

			multimediaArray = xmlRoot.getElementsByTagName("multimedia");
			html = '';

			for ( var i = 0; i < multimediaArray.length; i++) {
				html += multimediaArray.item(i).firstChild.data;
			}

			document.getElementById("Container-content").innerHTML = html;

			var myScripts = document.getElementById("Container-content")
			.getElementsByTagName("script");
			for ( var i = 0; i < myScripts.length; i++) {
				if (myScripts[i].innerHTML != '')
					eval(myScripts[i].innerHTML);
			}

		}
		// a HTTP status different than 200 signals an error
		else {
			alert("There was a problem accessing the server: "
					+ xmlHttp.statusText);
		}
	}
}

function load(ContainerId, MediaId, index) {
	$('#Container-menu li a').css( {'color' : '#dfe0df'});
	$('#Container-menu li a').eq(index).css( {'color' : '#f7d715'});
	width = document.getElementById("Container-content").style.width;

	html = '<table style="width: ' + width + ';"><tbody><tr><td class="center"><br/><img src="./ressources/loading.gif" alt=""/>';
	html += '<br/>' + traduction('Chargement en cours') + '<br/><br/></td></tr></tbody></table>';

	document.getElementById("Container-content").innerHTML = html;

	$.get('./multi.php?id=' + MediaId, function(data) {
		document.getElementById("Container-content").innerHTML = data;
		myScripts = document.getElementById("Container-content").getElementsByTagName("script");
		for ( var i = 0; i < myScripts.length; i++) {
			if (myScripts[i].innerHTML != '')
				eval(myScripts[i].innerHTML);
		}

		if (data == '') {
			$("#detail-bg-video").css( {'background-color' : '#000000'});
			$("#detail-bg-video").css( {'background-image' : 'none'	});
		} else {
			/*
			if (index == 2)
				$("#detail-bg-video").css( {'background-image' : 'url(images/bg-detail-video.gif)'});
			else
				$("#detail-bg-video").css( {'background-image' : 'url(images/bg-detail.gif)'});
			*/
			if(data.indexOf('class="Multimedia-bg-Video"')!=-1)
				$("#detail-bg-video").css( {'background-image' : 'url(images/bg-detail-video.gif)'});
			else
				$("#detail-bg-video").css( {'background-image' : 'url(images/bg-detail.gif)'});
		}
	});
}

function MM_swapImgRestore() { //v3.0
	var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
	var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
	var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
		if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
	var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
		d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
	if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
	for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
	if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
	var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
		if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

//Returns array with page width, height and window width, height
//Core code from - quirksmode.org
//Edit for Firefox by pHaez

function getPageSize(){

	var xScroll, yScroll;

	if (window.innerHeight && window.scrollMaxY) {    
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}

	var windowWidth, windowHeight;
	if (self.innerHeight) {    // all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}    

	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else {          pageHeight = yScroll;
	}      // for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){    
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}  
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
	return arrayPageSize;
}

//getPageScroll() by quirksmode.com
function getPageScroll() {
	var xScroll, yScroll;
	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
		xScroll = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
		xScroll = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
		xScroll = document.body.scrollLeft;	
	}
	return new Array(xScroll,yScroll) 
}


jQuery(document).ready(
	function() {
		$('#accordion').accordion( { header : 'h3'});
		$('.accordion .head').click(function() {
			$(this).next().toggle('slow');
			return false;
		}).next().hide();

		$('#mute-button img').hover(
				function() {
					if ($(this).attr('src').substring($(this).attr('src').length - 10) != '_hover.gif')
						$(this).attr('src',	$(this).attr('src').substring(0, $(this).attr('src').length - 4) + '_hover.gif');
				},
				function() {
					if ($(this).attr('src').substring($(this).attr('src').length - 10) == '_hover.gif')
						$(this).attr('src',	$(this).attr('src').substring(0, $(this).attr('src').length - 10) + '.gif');
				}
		);

		$('#mute-button img').click(
				function() {
					player = document.getElementById('playerID');

					if ($('#mute-button img').attr('src').indexOf('off') >= 0) {
						player.sendEvent('MUTE', 'true');
						
						$('#mute-button img').attr({src : '/ressources/b_mute_on_hover.gif'});
					} else {
						player.sendEvent('MUTE');
						$('#mute-button img').attr('src', '/ressources/b_mute_off_hover.gif');
					}
				}
		);

		//select all the a tag with name like to modal
		for(i=0;i<$('a').length;i++){
			if($('a').eq(i).attr('name') != undefined)
			if($('a').eq(i).attr('name').indexOf('modal')!=-1){
				$('a').eq(i).click(function(e) {
					//Cancel the link behavior
					e.preventDefault();

					//Get the A tag
					var id = $(this).attr('href');

					//Get the screen height and width
					var maskHeight = $(document).height();
					var maskWidth = $(window).width();

					//Set heigth and width to mask to fill up the whole screen
					$('#mask').css({'width':maskWidth,'height':maskHeight});

					//transition effect     
					$('#mask').fadeIn(1000);    
					$('#mask').fadeTo("slow",0.8);  

					/*
					//Get the window height and width
					var winH = $(window).height();
					var winW = $(window).width();
					*/

					pagesize= new Array();
					pagesize=getPageSize();
					pagescroll= new Array();
					pagescroll=getPageScroll();
					
					var winH = pagescroll[1] + pagesize[3]/2 - $(id).height()/2;
					var winW = pagescroll[0] + pagesize[2]/2 - $(id).width()/2;
					
					/*
					//Set the popup window to center
					$(id).css('top',  winH/2-$(id).height()/2);
					$(id).css('left', winW/2-$(id).width()/2);
					*/
					
					//Set the popup window to center
					$(id).css('top',  winH);
					$(id).css('left', winW);
					
					//transition effect
					//$(id).fadeIn(2000);
					$(id).show(); 
				})
			}
		}

		//if close button is clicked
		$('.window .close').click(function (e) {
			//Cancel the link behavior
			e.preventDefault();

			$('#mask').hide();
			$('.window').hide();
		});     

		//if mask is clicked
		$('#mask').click(function () {
			$(this).hide();
			$('.window').hide();
		});
	}
);

function adjustIFrameSize (iframeWindow) {
	if (iframeWindow.document.height) {
		var iframeElement = document.getElementById
		(iframeWindow.name);
		iframeElement.style.height = iframeWindow.document.height + 'px';
//		iframeElement.style.width = iframeWindow.document.width + 'px';
	}
	else if (document.all) {
		var iframeElement = document.all[iframeWindow.name];
		if (iframeWindow.document.compatMode &&
				iframeWindow.document.compatMode != 'BackCompat') 
		{
			iframeElement.style.height = 
				iframeWindow.document.documentElement.scrollHeight + 5 + 'px';
//			iframeElement.style.width = 
//				iframeWindow.document.documentElement.scrollWidth + 5 + 'px';
		}
		else {
			iframeElement.style.height = 
				iframeWindow.document.body.scrollHeight + 5 + 'px';
//			iframeElement.style.width = 
//				iframeWindow.document.body.scrollWidth + 5 + 'px';
		}
	}
}

