//*** DOM ***//
/*	[onload] init
	|- load options
	|- show remember
	`- locationSearch
	   |- [number] setAll(number)
	   |- [url] setAll(url)
	   `- [true] checkCookie
	      |- [true] readCookie
	      |  `- (readValue)
	      |      `- setAll(number)
		  `- [false] setAll(default)
	
	[select] wminipSelect
	`- setAll(this number)
	
	[checkbox] wminipRemember
	|- [true] createCookie
	`- [false] eraseCookie
	
?	[onunload] init (als vinkje is gedaan)
?	|- [true] checkCookie
?	|  `- createCookie
?	`- [false] eraseCookie

		setAll
		|- set value
		`- createCookie
	
*/
try{
	console.log('test');
}
catch(e){
	console = new Object();
	console.log = function(){};
}
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");





//*** INIT ***//
function wminipInit(){
	sendRequest('http://jervw.freehostia.com/radiostations.xml');  /*/ displayData(); $hs($gi('wminipSelectForm'),1);*/
	$hs($gi('wminipRememberForm'),1);
	$hs($gi('wminipInfoForm'),1);
}


//*** XMLHttpRequest ***//
var xmlObj=null;
var radioData=new Array();

// Send crossbrowser xml request;
function sendRequest(doc){
	if(xmlObj!=null&&xmlObj.readyState!=0&&xmlObj.readyState!=4){
		xmlObj.abort();
	}
	try{  // Firefox, Opera, IE7, Nestcape, etc.
		xmlObj=new XMLHttpRequest();
	}
	catch(e){  // IE6, IE5
		try{
			xmlObj=new ActiveXObject('Microsoft.XMLHTTP');
		}
		catch(e){
			try{
				xmlObj=new ActiveXObject("Msxml2.XMLHTTP");
			}
			catch (e){  // other
				alert("Your browser does not support AJAX!");
				xmlObj=null;
				return false;
			}
		}
	}
	xmlObj.onreadystatechange=stateChecker;
	xmlObj.open('GET',doc,true);
	xmlObj.send(null);
}

// Checks which state and show loading when 1 and goes further when 4;
function stateChecker(){
	var wminipLoadingImage='data:image/gif;base64,R0lGODlhEgASALMPAKysqpWVk1RUUmJiYIqKiW9vbqCgnomJh35+faGhnnBwb39/fqGhn3FxcYCAgP///yH/C05FVFNDQVBFMi4wAwEAAAAh+QQFAAAPACwAAAAAEgASAAAEV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j.readyState==1) {  // loading...
		$hs($gi('wminipSelectForm'),1);
		if (!$gi("wminipLoading")) {
			var wminipLoading = $ce("IMG");
			$sa(wminipLoading,"src",wminipLoadingImage);
			$sa(wminipLoading,"id","wminipLoading");
			$ac($gi('wminipSelectForm'),wminipLoading);
			$sa($gi('wminipSelectForm'),"style","text-align: center;");
		}
	}
	if(xmlObj.readyState==4){
		if ($gi("wminipLoading")) {
			$re($gi("wminipLoading"));
		}
		if(xmlObj.status==200){
			radioData=xmlObj.responseXML.getElementsByTagName('radio');
			if(displayData()==true){
				locationSearch();
			}
		}
		else{
			$hs($gi('wminipSelectForm'),2);
			alert("[Status: "+xmlObj.statusText+" ("+xmlObj.status+")]; "+"[ResponsHeaders: "+xmlObj.responsHeaders+"]; "+"[Respons: "+xmlObj.responseText+"];");
		}
	}
}

// Empty nodes aren't supported;
function getNodeValue(obj,tagName,defVal){
	if(!defVal)defVal="";
	var elems = obj.getElementsByTagName(tagName);
	if(elems && elems[0] && elems[0].firstChild && elems[0].firstChild.nodeValue){
		return elems[0].firstChild.nodeValue;
	}
	return defVal;
}

// Displays data from file;
function displayData(){
	wminipSelect=$ce('select');
	$sa(wminipSelect,"id","wminipSelect");
	$addEvent(wminipSelect,"change",function(){setAll('','',true);});  // stupid IE!
	
	offOptien=$ce('option');
	offOptien.innerHTML = "&gt;".repeat(9) + "&nbsp;off&nbsp;" + "&lt;".repeat(9);
	$ac(wminipSelect,offOptien);
	
	for(var i=0;i<radioData.length;i++){
//		optGroups=$ce('optgroup');
//		$sa(optGroups,'label',radiostations[i][0]);
//		$ac(wminipSelect,optGroups);

		$ac($gi('wminipSelectForm'),wminipSelect);
		
		opTions=$ce('option');
		$sa(opTions,'value',getNodeValue(radioData[i],'url'));
		opTions.innerHTML = getNodeValue(radioData[i],'name');
		if(radioData[i].getAttribute("selected")=='true'){
			$sa(opTions,'selected','selected');
		}
		$ac(wminipSelect,opTions);
	}
//	window.setTimeout("sendRequest('http://jervw.freehostia.com/radiostations.xml');",5*1000);
//	window.setTimeout(function(){sendRequest('http://jervw.freehostia.com/radiostations.xml');},5*1000);
///////////////
	return true;
}

//*** URL VARS ***//
// Checks for correct variabelen in url;
// e.g.:	http://jervw.freehostia.com/wminip.html?player=71
// 			http://jervw.freehostia.com/wminip.html?speler=71
// 			http://jervw.freehostia.com/wminip.html?radio=71
// 			http://jervw.freehostia.com/wminip.html?url=http://ms.stream.garnierprojects.com/radio538 <-valid url
function locationSearch(){
	var hash = getUrlVars();
	var doCookie = true;
	names = ['player','speler','radio'];
	for(var i = 0; i < names.length; i++){
		name = names[i];
		if(hash[name]){
			if(isInt(hash[name])){
				setAll(hash[name]);
			}
			else if(isUrl(hash[name])){
				setAll(0,hash[name]);
			}
			doCookie = false;
			break;
		}
	}
	if(doCookie==true){
		checkCookie();
	}
}

// Returns variabelen in url;
function getUrlVars(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++){
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}


//*** COOKIE ***//
// Checks if cookie excist;
function checkCookie() {  // onload; kijkt of cookie bestaat en of onthouden is
	var x = readCookie();
	if (x) {
		var elements = readValue();
		var abc = new Array();
		abc = elements[0].split('=');
		if (abc[1] == 'true') {
			$gi("wminipRemember").checked = abc[1];
			setAll(abc[0]);
			updateCount(elements[1]);
		}
	}
	else {
		setAll(0,wminipDefault);
	}
}

// Returns whole cookie;
function readCookie() {  // leest de cookie
	var nameEQ = wminipName + "=";
	var ca = $d.cookie.split(';');
	var cookieExcisist = false;
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) var cookieExcisist = c.substring(nameEQ.length,c.length);
	}
	return cookieExcisist;
}

// Returns cookie values;
function readValue() {  // leest value in cookie
	var ab = readCookie();
	var elements = new Array();
	elements = ab.split('||');
	return elements;
}

// Creates cookie;
function createCookie(days) {  // creert een cookie
	if (days) { 
		var date = new Date(); 
		date.setTime(date.getTime()+(days*24*60*60*1000)); 
		var expires = "; expires="+date.toGMTString(); 
	} 
	else var expires = ""; 

	if ($gi("wminipRemember").checked == true) {
		valueA1 = $gi("wminipSelect").selectedIndex;
		valueB1 = true;
		valueC = valueA1 + '=' + valueB1 + '||' + "count";
	}
	else if ($gi("wminipRemember").checked == false) {
		valueA2 = 0;
		valueB2 = false;
		valueC = valueA2 + '=' + valueB2 + '||' + "count";
	}

	$d.cookie = wminipName+"="+valueC+expires+"; path=/"; 
} 

// Erase cookie;
function eraseCookie(days) {  // delete een cookie
	createCookie(-1);
}

// Toggle cookie on/off;
function toggleCookie(){
	$gi("wminipRemember").checked==true?createCookie(999):eraseCookie(-1);
}


//*** PLAYER ***//
// Set all settings for player;
function setAll(nr,url,xtra){
	if(!xtra){
		if(!nr || isInt(nr)==false){nr=0;};
		$gi("wminipSelect").selectedIndex = nr;
		if(!url || isUrl(url)==false){url=$gi("wminipSelect").value;};
	}
	else{
		url=$gi("wminipSelect").value;
	};
	importPlayer(url);
	
	addLink($gi("wminipSelect").selectedIndex);
	
	createCookie(999);
}

// Imports html code for player into page;
function importPlayer(url) {
		content='<object name="wminipPlayer" id="wminipPlayer" title="Hear me" ' +
				 'codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=6,4,5,715" ' +
				 'standby="Loading Windows Media Player component/plugin..." type="application/x-mplayer2" height="50" width="200">' +
					'<param name="autostart" value="1" />' +
					'<param name="filename" value="' + url + '" />' +
					'<param name="showaudiocontrols" value="1" />' +
					'<param name="showcontrols" value="1" />' +
					'<param name="showdisplay" value="0" />' +
					'<param name="showgotobar" value="0" />' +
					'<param name="showpositioncontrols" value="0" />' +
					'<param name="showstatusbar" value="1" />' +
					'<param name="showtracker" value="0" />' +
					'<param name="playcount" value="1" />' +
					'<param name="transparentatstart" value="1" />' +
					'<param name="volume" value="1" />' +
					'<param name="allowscan" value="0" />' +
					'<param name="stretchToFit" value="1" />' +
					'<div class="xMessage errorMessage">' +
						'<a href="http://www.microsoft.com/windows/windowsmedia/nl/player/download/download.aspx" title="WindowsMediaPlayer" style="float:right"><img src="images/get_wmp.gif" alt="WindowsMediaPlayer" width="55" height="44"/></a>' +
						'Error: the Windows Media Player plugin / component is not loaded!<br />' +
					'</div>' +
				'</object>';
	$gi('wminipSource').innerHTML=content;
}


//*** INFO ***//
// Add information;
function addLink(nr){
	if($gi('wminipInfoForm')){
		if($gi('blad1')){
			$gi('blad1').innerHTML = "";
			imgLink = $ce('img');
			$sa(imgLink,'id','wminipInfoImgLink');
			$sa(imgLink,'src',"images/world_go.png");
			$sa(imgLink,'style',"margin:2px; vertical-align:middle;");
			$ac($gi('blad1'),imgLink);
			
			aLink = $ce('a');
			$sa(aLink,'id','wminipInfoALink');
			$sa(aLink,'href',getNodeValue(radioData[nr-1],'site'));
			aLink.innerHTML = getNodeValue(radioData[nr-1],'name');
			$ac($gi('blad1'),aLink);
			
			if(getNodeValue(radioData[nr-1],'title').length > 0){
				$gi('blad1').innerHTML = $gi('blad1').innerHTML + "\n<br/>";
				txtTitle = $ct(getNodeValue(radioData[nr-1],'title'));
				$ac($gi('blad1'),txtTitle);
			}
			
			if(getNodeValue(radioData[nr-1],'image').length > 0){
				$gi('blad1').innerHTML = $gi('blad1').innerHTML + "\n<br/>";
				imgTitle = $ce('img');
				$sa(imgTitle,'id','wminipInfoImgTitle');
				$sa(imgTitle,'src',getNodeValue(radioData[nr-1],'image'));
				$sa(imgTitle,'style',"margin:2px; vertical-align:middle;");
				$ac($gi('blad1'),imgTitle);
			}
		}
	}
}

// Switch tabs;
function selectTabBlad(i){
	var n=1;
	while($gi("blad"+n)){
		$hs($gi("blad"+n),2);
		$sa($gi("tab"+n),"class",$ga($gi("tab"+n),"class").replace("wminiTabSelected","").replace("wminiTabSelectedRight",""));
		n++;
	}
	$hs($gi("blad"+i.match(/\d/g).join()),1);
	$sa($gi("tab"+i.match(/\d/g).join()),"class",$ga($gi("tab"+i.match(/\d/g).join()),"class") + " wminiTabSelected");
	if(i.match(/\d/g).join()>1){
		$sa($gi("tab"+(i.match(/\d/g).join()-1)),"class",$ga($gi("tab"+(i.match(/\d/g).join()-1)),"class") + " wminiTabSelectedRight");
	}
}

////////////////////////////
function updateCount(x){
// needs php to override :(
}
