cookies = {
  set: function(name, value, expires, path, domain, secure){
    document.cookie = name + '=' + escape(value) +
      (expires ? ';expires=' + (new Date((new Date()).getTime() + (expires * 1000))).toGMTString() : '') +
      (path? ';path=' + path : '') +
      (domain ? ';domain=' + domain : '') +
      (secure ? ';secure' : '');
  },
  get: function(name){
    var allCookies = document.cookie.split(';');
    var cookiePair;
    if (!allCookies.length) {return null;}
    for (var i=0; i<allCookies.length; i++) {
      cookiePair = allCookies[i].split('=');
      if (name == cookiePair[0].replace(/^\s+|\s+$/g, '')) {
        return cookiePair[1].replace(/^\s+|\s+$/g, '');
      }
    }
    return null;
  }
};


skin = function(name){
  var logo = document.getElementById('logo');
  var stripe = document.getElementById('stripe');
  switch (name) {
    case 'winter':
      stripe.className = 'stripe_winter';
      logo.className = 'logo_trans';
      cookies.set('skin', 'mountain');
    break;
    case 'mountain':
      stripe.className = 'stripe_mountain';
      logo.className = 'logo_trans';
      cookies.set('skin', 'mountain');
    break;
    default:
      stripe.className = 'stripe_default';
      logo.className = 'logo_default';
      cookies.set('skin', 'default');
    break;
  }
}

skinName = cookies.get('skin');
if (skinName) {skin(skinName);}

showlang = function(name){
	var l=document.getElementById('langswitcher');
	l.className = (l.className == 'open' ? '' : 'open');
}


UniplayerGUIRadiolla = function(player){
	var lang = UniplayerLanguages[player.options.language];
	var HTMLControls = '<div class="rLogo" href="http://radiolla.com/"></div><div class="upGUIButtonSet"><a href="javascript:" class="upGUIButton upGUIButtonPlay" title="'+lang.controlsPlay+'"></a><a href="javascript:" class="upGUIButton upGUIButtonStop" title="'+lang.controlsStop+'"></a></div><div class="upGUIVolume"><div class="upGUISlider" title="'+lang.controlsVolume+'"><div class="upGUISliderTail"></div><a href="javascript:" class="upGUIButton upGUIPointer"></a></div></div><div class="upGUIState"></div><a class="rHigh" href="http://radiolla.com:8000/radiolla.128k.mp3.m3u" onclick="radiolla.uniplayer.load(\'http://radiolla.com:8000/radiolla.128k.mp3\'); radiolla.uniplayer.play(); this.blur(); return false;"><a class="rLow" href="http://radiolla.com:8000/radiolla.32k.mp3.m3u" onclick="radiolla.uniplayer.load(\'http://radiolla.com:8000/radiolla.32k.mp3\'); radiolla.uniplayer.play(); this.blur(); return false;"></a><div class="rPlaylists"><a class="rM3u" href="http://radiolla.com/radiolla.mp3.m3u">m3u</a><a class="rPls" href="http://radiolla.com/radiolla.mp3.pls">pls</a><a class="rRam" href="http://radiolla.com/radiolla.mp3.ram">ram</a><a class="rXspf" href="http://radiolla.com/radiolla.mp3.xspf">xspf</a></div>';
	this.getHTML = function(){
		if(player.options.showControls || player.options.showSupply){
			UniplayerUtils.loadCSS(player.options.guiPath + 'uniplayer.css');
		}
		return '<div class="upGUI"><div class="upGUIWrapper"><div class="upGUIMovie"></div><div class="upGUIControls" style="width: 468px; height: 60px; display: '+(player.options.showControls ? 'block' : 'none')+'">'+(player.options.showControls ? HTMLControls : '')+'</div></div></div>';
	};
};


Radiolla = function(conf){
	if(!conf){
		conf = {};
	}
	var self =  this;
	
	//-- settings
	this.updateURL = conf.updateURL || 'http://radiolla.com/status';
	this.historyURL = conf.historyURL || 'http://radiolla.com/history?type=json&amount=9&order=asc';
	this.updateInterval = conf.updateInterval || 30;	//-- seconds, used if current track's length and time are undefined
	this.updateTimeout = conf.updateTimeout || 1;		//-- seconds, used with play and stop methods to get actual data after connect/disconnect the radio
	this.loader = conf.loader || aloader;
	this.uniplayer = conf.uniplayer || new Uniplayer({
			src: 'http://radiolla.com:8000/radiolla.128k.mp3',
			mimetype: 'audio/mpeg',
			volume: .5,
			autoload: true,
			autoplay: typeof(conf.autoplay) != 'undefined' ? conf.autoplay : false,
			showSupply: false,
			showControls: true,
			background: '#000000',
			guiPath: 'http://play.radiolla.com/',
			noCache: true,
			repeat: true//,
			//logger: window.console || 'alert'
		});
	
	this.tracksHistory = conf.tracksHistory || document.getElementById('tracksHistory');	//-- should be an <ul> element
	this.tracksHistory.innerHTML = '';
	this.historySize = 9;
	this.status = {
		title: '',
		time: 0,
		length: 0
	};
	
	//-- status updater
	this.updateStatus = function(){
		self.loader.load(self.updateURL + (self.updateURL.indexOf('?') < 0 ? '?' : '&') + 'seed=' + Math.floor(Math.random()*100000000), function(){
			var timeout = self.updateInterval;
			if(self.status.length - self.status.time > 0){
				timeout = self.status.length - self.status.time + 1;
			}
			if(self.updater){
				clearTimeout(self.updater);
			}
			self.updater = setTimeout(self.updateStatus, timeout * 1000);
			if(self.onStatusUpdate){
				self.onStatusUpdate.call(self, self.status);
			}
		});
	};
	
	//-- playing indicator	
	var playingInterval = null;
	var playingIndicator = null;
	var playing = function(turn){
	    if(turn == 'on'){
	      if(!playingIndicator){
	        playingIndicator = UniplayerUtils.getElementsByClassName('upGUIState', 'div', self.uniplayer.holders.controls)[0];
	      }
	      if(playingInterval){
	   			clearInterval(playingInterval);
	   		}
	   		playingInterval = setInterval(function(){playing();}, 500);
	    }
	    if(turn == 'off'){
	      clearInterval(playingInterval);
	  		playingInterval = null;
	    }
	    if(playingIndicator){
	      if(turn == 'off' || playingIndicator.className.indexOf('active') >= 0){
	        playingIndicator.className = playingIndicator.className.replace(' active', '');
	      }
	      else{
	        playingIndicator.className += ' active';
	      }
	    }
	};
	
	this.uniplayer.addEventListener('state', function(state){
	    setTimeout(self.updateStatus, self.updateTimeout*1500);
	    if(state == self.uniplayer.states.stopped || state == self.uniplayer.states.failed){
	    	cookies.set('play', 0);
	  		playing('off');
	    }
	    else{
	      cookies.set('play', 1);
	      playing('on');
	    }
	});
	
	//-- tracks history listing
	this.toTracksHistory = function(data, nosave){
		if(!this.tracksHistory){return;}
		if((this.tracksHistory.childNodes.length && data.id != this.tracksHistory.firstChild.rel) || !this.tracksHistory.childNodes.length){
			// create new tracklist item
			var historyItem = document.createElement('li');
			var titleItem = document.createElement('span');
			var playedItem = document.createElement('span');
			playedItem.className = 'historyPlayed';
			titleItem.innerHTML = this.combineTitle(data);
			historyItem.rel = data.id;
			var playedDate = new Date(data.played*1000);
			var playedHours = playedDate.getHours();
			var playedMinutes = playedDate.getMinutes();
			playedItem.innerHTML = (playedHours > 9 ? playedHours : '0' + playedHours) +':'+ (playedMinutes > 9 ? playedMinutes : '0' + playedMinutes) + ' ';
			historyItem.appendChild(playedItem);
			historyItem.appendChild(titleItem);
			// prepend item
			if(this.tracksHistory.childNodes.length){
				this.tracksHistory.insertBefore(historyItem, this.tracksHistory.firstChild);
			}
			else{
				this.tracksHistory.appendChild(historyItem);
			}
			// remove outsider
			if(this.tracksHistory.childNodes.length > this.historySize){
				this.tracksHistory.removeChild(this.tracksHistory.lastChild);
			}
		}
	};
	
	//-- combineTitle
	this.combineTitle = function(data){
		if (!data.id) {return '';}
		var title = data.artist + ' - ' + data.title;
		if(data.album && data.year != '0000'){
			title += ' <small>(' + data.album + ' ' + data.year + ')</small>';
		}
		else if(data.album){
			title += ' <small>(' + data.album + ')</small>';
		}
		else if(data.year != '0000'){
			title += ' <small>(' + data.year + ')</small>';
		}
		return title;
	};

	//-- update status event
	this.onStatusUpdate = function(status){
		var lastfmArtistLink = true;
		//var statusArtist = '';
		document.title = status.artist + ' • Radiolla';
		var statusTitle = this.combineTitle(status);
		if(lastfmArtistLink){
			statusTitle = statusTitle.replace(status.artist, '<a href="http://www.last.fm/music/' +status.artist+ '" target="_blank" title="Read about ' +status.artist+ ' on Last.fm">' +status.artist+ '</a>');
		}
		with(document.getElementById('statusTitle')){
			innerHTML = statusTitle;
			title = status.listeners;
			style.background = 'none';
		}
		var nextTitle = this.combineTitle(status.next);
		if (nextTitle) {
			document.getElementById('nextTitle').innerHTML = nextTitle;
			document.getElementById('nextLabel').style.visibility = 'visible';
		}
		self.toTracksHistory(status);
	};
	
	//-- load history
	this.loader.load(this.historyURL, function(){
		document.getElementById('historyLinkTitle').innerHTML = document.getElementById('historyLinkTitle').title;	// replace 'loading...' with 'previous 9'
	});
	
	// uniplayer modules
	//this.uniplayer.addModule(new UniplayerFlashFlowplayer);      // hungry caching - even after STOP and PLAY it plays the same again
	this.uniplayer.addModule(new UniplayerFlashJWPlayer({swf: 'http://play.radiolla.com/jwplayer.swf', flashvars: {bufferlength: 3}}));
	if(navigator.userAgent.indexOf('MSIE')>=0){
		this.uniplayer.addModule(new UniplayerWindowsMedia);
	}
	this.uniplayer.addModule(new UniplayerVLC);
	this.uniplayer.write('listen', new UniplayerGUIRadiolla(this.uniplayer));

  //-- connect keyboard
  document.onkeypress = function(e){
  	var keynum = 0;
  	if(window.event){
  		keynum = window.event.keyCode;
  	}
  	else if(e.which){
  		keynum = e.which;
  	}
  	if(keynum == 32){	// space
  		if(radiolla.uniplayer.current.state == radiolla.uniplayer.states.stopped){
  			radiolla.uniplayer.play();
  		}
  		else{
  			radiolla.uniplayer.stop();
  		}
  		return false;
  	}
  	else{
  		return true;
  	}
  };
	
};

radiolla = new Radiolla({autoplay: cookies.get('play') > 0});

stat = function(speed){
	var stat = {};
	stat.browser = navigator.userAgent;
	var modules = [];
	for (var i in radiolla.uniplayer.modules) {
	  modules.push(radiolla.uniplayer.modules[i].name +':'+ (radiolla.uniplayer.modules[i].present?'on':'off'));
	}
	stat.modules = modules.join(', ');
	stat.module_current = radiolla.uniplayer.current.module.name;
	stat.screen_width = screen.width;
	stat.screen_height = screen.height;
	stat.skin = skinName;
	stat.lang = lang;
	stat.referrer = document.referrer || '';
	stat.speed = speed;
	//if(console)console.log(stat);
	var params = [];
	for (var i in stat) {
		params.push(i + '=' + escape(stat[i]));
	}
	radiolla.loader.load('http://radiolla.com/stat?' + params.join('&'));
}

window.onload = function() {
	new SpeedTest('speedtest', {onReady: stat});
}