/////////////////////////////
//
//		script-helpers.js
//
//////////////////////////////


////////////////////
// HELPER FUNCTIONS
/////////////////////////

// because getSelection() is not cross-browser compatible
function textGetter() {
	var myseltext;
	if (window.getSelection) {
		myseltext = (window.getSelection());
	} else if (document.getSelection) {
		myseltext = (document.getSelection());
	} else if (document.selection) {
		myseltext = (document.selection.createRange().text);
	}
	return myseltext;
}

function setCookie(c_name, value, expiredays) {
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie = c_name + "=" + escape(value) + ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function getCookie(c_name) {
	if (document.cookie.length > 0) {
 		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start != -1) { 
			c_start = c_start + c_name.length+1; 
			c_end = document.cookie.indexOf(";",c_start);
			if (c_end == -1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		} 
	}
	return "";
}

function stripHTML(oldString) {
	var nohtml;
	//nohtml = oldString.replace(/<&#91;^>&#93;*>/ig, "");  
	nohtml = oldString.replace(/(<([^>]+)>)/ig,""); 
	nohtml = nohtml.replace(/&nbsp;/ig, " ");
	nohtml = nohtml.replace("&laquo;", "");
	nohtml = nohtml.replace("&raquo;", "");
	return nohtml;
}

/////////////////////
// EXTERNAL FUNCTIONS ie: found elsewhere and handy
////////////////////////////////////////////////////

/***********************************************
* Bookmark site script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/
function bookmarksite(title, url){
	if (window.sidebar) {	// firefox
		window.sidebar.addPanel(title, url, "");
	} else if(window.opera && window.print) {	// opera
		var elem = document.createElement('a');
		elem.setAttribute('href', url);
		elem.setAttribute('title', title);
		elem.setAttribute('rel', 'sidebar');
		elem.click();
	} else if(document.all) {	// ie
		window.external.AddFavorite(url, title);
	}
}

/*****************************************
* Scroll bars  positions and window size
* Credits: http://www.softcomplex.com/docs/get_window_size_and_scrollbar_position.html
******************************************/

function f_clientWidth() {
	return f_filterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}
function f_clientHeight() {
	return f_filterResults (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}
function f_scrollLeft() {
	return f_filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}





/****************************

		script-meaning.js

*****************************/

/////////////////////////////
// AJAX FUNCTIONS FOR MEANING
///////////////////////////////////////////

// DICTIONARY
function dictionary(query) {
var xmlHttp;
	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	}
	catch (e) {
		// Internet Explorer
		try {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e) {
			try {
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e) {
				alert("Your browser does not support AJAX!");
				return false;
			}
		}
	}
	xmlHttp.onreadystatechange=function() {
		if(xmlHttp.readyState==4) {
			document.getElementById("definition").innerHTML = xmlHttp.responseText;
		}
	}
	xmlHttp.open("GET", "http://www.bilingueanglais.com/musique/ajax_dictionary.php?q=" + query, true);
	xmlHttp.send(null);
}

// PRONUNCIATION
function pronunce(query, sex) {
var xmlHttp;
	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	}
	catch (e) {
		// Internet Explorer
		try {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e) {
			try {
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e) {
				alert("Your browser does not support AJAX!");
				return false;
			}
		}
	}
	xmlHttp.onreadystatechange=function() {
		if(xmlHttp.readyState==4) {
			document.getElementById("soundplayer").innerHTML = xmlHttp.responseText;
		}
	}
	if (query == "") {
		query = getCookie('musique_lastmeaning');
	}
	xmlHttp.open("GET", "http://www.bilingueanglais.com/musique/ajax_pronunciation.php?q=" + query + "&sex=" + sex, true);
	xmlHttp.send(null);
}

// IMAGES
function picture(query) {
	OnLoad("'" + query + "'");
}
google.load("search", "1", {"language" : "en"}); // the language option here only affects the UI
function OnLoad(query) {
	// Create a search control
	var searchControl = new google.search.SearchControl();

	// Draw options object, so that we can position the search form root
	var drawOptions = new google.search.DrawOptions();
	drawOptions.setSearchFormRoot(document.getElementById("searchForm"));

	// Searcher options object, so we can specify the open mode for results
	var searchOptions = new google.search.SearcherOptions();
	searchOptions.setExpandMode(google.search.SearchControl.EXPAND_MODE_PARTIAL);

	// Image search options and Moderate on/off (default behavior is Moderate search ON)
	var searcher = new google.search.ImageSearch();
	//searcher.setSiteRestriction("photobucket.com");
	//searcher.setRestriction(google.search.Search.RESTRICT_SAFESEARCH, google.search.Search.SAFESEARCH_OFF);
	searcher.setRestriction(google.search.Search.RESTRICT_SAFESEARCH, google.search.Search.SAFESEARCH_STRICT);

	// Add in searcher(s)
	searchControl.addSearcher(searcher, searchOptions);

	// Tell the searcher to draw itself, where and with what options
	searchControl.draw(document.getElementById("searchResults"), drawOptions);

	// Execute an inital search
	searchControl.execute(query);
}
google.setOnLoadCallback(OnLoad);


//////////////////////////////
// EXTRA FUNCTIONS FOR MEANING
////////////////////////////////////////

// call all meaning functions at once
function meaning(query) {
	var sex;
	if (!query) {
		query = textGetter();
	}
	if (query) {
		//keepText = query;
		setCookie('musique_lastmeaning', query, 1);
	}
	//alert(query + "!!!");
	dictionary(query);
	if (document.getElementById('voicemale').checked == true) {
		sex = "male";
	} else {
		sex = "female";
	}
	pronunce(query, sex);
	picture(query);
}

function zoomInDefinition() {
	var analyseDefinition;
	var nbLignes;
	analyseDefinition =  document.getElementById("definition").innerHTML.match(/<br>/gi);
	if (analyseDefinition) {
		nbLignes = analyseDefinition.length + 1;
		if (nbLignes >= 10) {
			;//document.getElementById("definition").style.height = nbLignes + "em";
			document.getElementById("definition").style.overflow = "scroll"; // trop moche
		}
	}
}

function zoomOutDefinition() {
	// cohérence avec le style de depart assuree via onload dans le code HTML
	;//document.getElementById("definition").style.height = "10em";	
	document.getElementById("definition").style.overflow = "hidden";
	document.getElementById("definition").scrollTop = 0;
}





/****************************

		script-music.js

*****************************/

/////////////////
// AJAX FUNCTIONS
//////////////////////

function list_artist(artist, page) {
var xmlHttp;
	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	}
	catch (e) {
		// Internet Explorer
		try {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e) {
			try {
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e) {
				alert("Your browser does not support AJAX!");
				return false;
			}
		}
	}
	xmlHttp.onreadystatechange=function() {
		if(xmlHttp.readyState==4) {
			document.getElementById("listing").innerHTML = xmlHttp.responseText;
		}
	}
	xmlHttp.open("GET", "ajax_list_artist.php?artist=" + artist + "&page=" + page, true);
	xmlHttp.send(null);
}

function list_songs(song) {
var xmlHttp;
	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	}
	catch (e) {
		// Internet Explorer
		try {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e) {
			try {
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e) {
				alert("Your browser does not support AJAX!");
				return false;
			}
		}
	}
	xmlHttp.onreadystatechange=function() {
		if(xmlHttp.readyState==4) {
			document.getElementById("listing").innerHTML = xmlHttp.responseText;
		}
	}
	xmlHttp.open("GET", "ajax_list_songs.php?song=" + song, true);
	xmlHttp.send(null);
}

function refreshLyricsContent(youtubeid) {
var xmlHttp;
	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	}
	catch (e) {
		// Internet Explorer
		try {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e) {
			try {
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e) {
				alert("Your browser does not support AJAX!");
				return false;
			}
		}
	}
	xmlHttp.onreadystatechange=function() {
		if(xmlHttp.readyState==4) {
			document.getElementById("lyrics").innerHTML = xmlHttp.responseText;
		}
	}
	xmlHttp.open("GET", "ajax_refreshlyricscontent.php?id=" + youtubeid, true);
	xmlHttp.send(null);
}

function refreshLyricsTitle(youtubeid) {
var xmlHttp;
	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	}
	catch (e) {
		// Internet Explorer
		try {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e) {
			try {
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e) {
				alert("Your browser does not support AJAX!");
				return false;
			}
		}
	}
	xmlHttp.onreadystatechange=function() {
		if(xmlHttp.readyState==4) {
			document.getElementById("title").innerHTML = xmlHttp.responseText;
			document.title = stripHTML(xmlHttp.responseText);
		}
	}
	xmlHttp.open("GET", "ajax_refreshlyricstitle.php?id=" + youtubeid, true);
	xmlHttp.send(null);
}

function refreshPlaylist(action, index, artist, song) {
var xmlHttp;
	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	}
	catch (e) {
		// Internet Explorer
		try {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e) {
			try {
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e) {
				alert("Your browser does not support AJAX!");
				return false;
			}
		}
	}
	xmlHttp.onreadystatechange=function() {
		if(xmlHttp.readyState==4) {
			document.getElementById("playlist").innerHTML = xmlHttp.responseText;
		}
	}

	// rafraichissement ou vertiable action?
	var url;
	switch (action) {
		case "remove" :
		case "moveup" :
		case "movedown" :
			url = "playlist.php?action=playlist&edit=" + action + "&index=" + index;
			break;
		case "add" :
			url = "playlist.php?action=playlist&edit=" + action + "&artist=" + artist + "&song=" + song;
			break;
		case "empty" :
			url = "playlist.php?action=playlist&edit=" + action;
			break;
		default:
			url = "playlist.php?action=playlist";
	}

	xmlHttp.open("GET", url, true);
	xmlHttp.send(null);
}


/////////////////////////////
// YOUTUBE PLAYER, PLAYLIST AND STATUS BAR FUNCTIONS
///////////////////////////////////////////////////////

function GetVideoID() {
	var id;
	id = document.getElementById("myytplayer").getVideoUrl();
	id = id.substr(id.indexOf("v=")+2);
	id = id.substr(0, id.indexOf("&"));
	return id;
}

function onYouTubePlayerReady(playerId) {
	ytplayer = document.getElementById("myytplayer");
	ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
	globalOriginalYoutubeId = GetVideoID();

	// Mode playlist ?
	if ( getCookie("playlistStatus") == "play" ) {
		ytplayer.playVideo()
	}
}

function onytplayerStateChange(newState) {
	// Changement de clip via click dans la video youtube
	if (GetVideoID() != globalOriginalYoutubeId) {
		globalOriginalYoutubeId = GetVideoID();
		refreshLyricsContent(globalOriginalYoutubeId);
		refreshLyricsTitle(globalOriginalYoutubeId);
	}

	// Fin du clip et mode playlist active
	if ( newState == 0) {	// "0 = "ended"
		if ( getCookie("playlistStatus") == "play" ) {
			window.location = "http://www.bilingueanglais.com/musique/playlist.php?action=next";
		}
	}
}

function playlistInit() {
	var divTag = document.createElement("div");
	divTag.id = "playlist";
	divTag.style.display = "none";
	divTag.style.zIndex = "1";
	divTag.style.background = "gainsboro";
	divTag.style.color = "gray";	// and NOT "grey" with an "e"
	divTag.style.fontSize = "7pt";
	divTag.style.overflow = "scroll";
	divTag.style.whiteSpace = "nowrap";
	divTag.style.scrollbarBaseColor = "gainsboro";
	divTag.style.scrollbarArrowColor = "white";
	divTag.style.scrollbarFaceColor = "gainsboro";
	divTag.style.scrollbarTrackColor = "gainsboro";
	//divTag.style.scrollbarHighlightColor = "gainsboro";
	//divTag.style.scrollbar3dLightColor = "gainsboro";
	divTag.style.position = "absolute";
	divTag.style.width = "320px";
	divTag.style.height = "160px";
	divTag.style.top = "40px";
	divTag.style.right = "445px";
	divTag.style.margin = "0";
	divTag.style.padding = "2px";
	divTag.innerHTML = "Playlist here!";
	document.body.appendChild(divTag); 
	//divTag.setAttribute("onClick", "javascript:refreshPlaylist();");
	refreshPlaylist();
	repositionPlaylist();
}

function playlistPrevious() {
	window.location = "http://www.bilingueanglais.com/musique/playlist.php?action=previous";
}

function playlistPlay() {
	setCookie("playlistStatus", "play", 30);
	ytplayer = document.getElementById("myytplayer");
	ytplayer.playVideo()
}

function playlistStop() {
	setCookie("playlistStatus", "stop", 30);
	ytplayer = document.getElementById("myytplayer");
	ytplayer.stopVideo()
}

function playlistNext() {
	window.location = "http://www.bilingueanglais.com/musique/playlist.php?action=next";
}

function playlistGo(index) {
	window.location = "http://www.bilingueanglais.com/musique/playlist.php?action=go&index=" + index;
}

function playlistRemove(index) {
	refreshPlaylist("remove", index);
}
function playlistMoveUp(index) {
	refreshPlaylist("moveup", index);}
function playlistMoveDown(index) {
	refreshPlaylist("movedown", index);
}
function playlistAdd(artist, song) {
	//alert(artist + ":" + song);
	refreshPlaylist("add", 0, artist, song);
}
function playlistEmpty() {
	refreshPlaylist("empty");
}

function playlistToggleDisplay() {
	if (document.getElementById("playlist").style.display == "none") {
		document.getElementById("playlist").style.display = "block";
	} else {
		document.getElementById("playlist").style.display = "none";
	}
}

function repositionStatusBar() {
	document.getElementById("statusbar").style.bottom = - f_scrollTop() + "px";
	repositionPlaylist();
}
function repositionPlaylist() {
	document.getElementById("playlist").style.bottom = - f_scrollTop() + 24 + 2 + "px";
}
