document.domain = document.domain.split('.').slice(-2).join('.');
if (self == top) {
	window.name ='freedom';
}

if (!window.console || !console.firebug){
	var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
	"group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
	var ef = function(){};
	window.console = {};
	for (var i = 0; i < names.length; ++i) {
		window.console[names[i]] = ef;
	}
}

globalDebugLog = function (prefix, msg) {
	self.console.log(prefix+': '+msg);
};

self.gooeyLookup = function () {
	document.addScriptSrc('http://jsip.appspot.com/', {});
	var grabIp = window.setInterval(
		function(){
			if (typeof ip != 'undefined'){
				document.addScriptSrc('http://gooey.euro.real.com/jslookup.js?IP=' + ip, {});
				window.clearInterval(grabIp);
			}
		}, 40
	);
};

self.cookies = {
	get: function (name, win, exists) {
		win = win || self;
		try {
			var cookies = win.document.cookie && win.document.cookie.split('; ');
			for (var i=0; i<cookies.length; i++) {
				cookie = cookies[i].split('=');
				if (cookie.shift() == name) {
					if (exists) return true;
					return cookie.join('=');
				}
			}
		} catch(ex) { self.console.log('Exception: %o', ex); }
		return null;
	},
	set: function (p) {
		if (!p.name || !p.value) return;
		if (!p.path) p.path = '/';
		if (!p.domain) p.domain = document.domain.split('.').slice(-2).join('.');
		if (p.expiresInDays) p.expires = this.getExpiryFromDays(p.expireInDays || 365);
		document.cookie = p.name+'='+p.value+'; '+
			(p.path?'path='+p.path+'; ':'')+
			(p.domain?'domain='+p.domain+'; ':'')+
			(p.expires?'expires='+p.expires+'; ':'');
	},
	getExpiryFromDays: function (numberOfDays) {
		var somedate = new Date();
		somedate.setTime(somedate.getTime()+numberOfDays*24*60*60*1000);
		return somedate.toUTCString();
	}
};

/* blackberry trial check */

(function (){
	var isRealPlayer = /\(R1/.test( navigator.userAgent );
	if (isRealPlayer) {
		var plyrObj = parent.window.external;
		if (plyrObj) {
			var distCode = plyrObj.PlayerProperty("DISTRIBUTIONCODE");
			var isBlackberry = (distCode == 'R41UKB');
			
			if (isBlackberry) {
				var showStartPage = !self.cookies.get('RP_bbfirst');// startpage already shown? don't redirect
				//var isLoggedIn = self.cookies.get('darf');
				
				if ( showStartPage ) {
					self.cookies.set({name:'RP_bbfirst', value:'true' });
					location.replace('https://gapi.euro.real.com/darf/login/blackberry_switchboard.html?ec=uk');
				}
			}
		}
	}
})();

/* end blackberry trial check */

self.initFreedom = function () {
	self.pageEnv.previewmode = self.pageEnv.previewmode || self.urlhelper.getGetParamFromUrl(self.location.href,'previewmode');
	var matchedUrl = self.urlhelper.matchUrl(self.location.href);
	self.SECTION = matchedUrl['path'];  
	
	window.setTimeout("self.srcTracking.doCleanHref()", 500); //setTimeout due to the "FF3-real-bug"
	
	var local_href_base = self.location.href.split('/').slice(0,3).join('/')+'/';
	self.initFreedom.click_handler = function (e) {
		var elem = Event.element(e);
		var elemAnchor = null;
		[elem, elem.parentNode, elem.parentNode.parentNode].each(function (elem) {
				if (elem && elem.tagName == 'A') {
					elemAnchor = elem;					
				}
		});
		if (!elemAnchor || !elemAnchor.href) return;
		if (elemAnchor.href.indexOf('javascript:') == 0) return;
		var elemAnchor_href_base = elemAnchor.href.split('/').slice(0,3).join('/')+'/';
		var localhref = '';
		var exthref = '';
		var moohref = elemAnchor.href.replace(new RegExp("\/R\/R\..*?\.R\/"+self.location.host),'');
		if (moohref.substr(0,1) == '/')
			localhref = moohref;
		else {
			if(elemAnchor.href.substr(0,local_href_base.length) == local_href_base) localhref = elemAnchor.href.substr(local_href_base.length-1);
			else exthref = elemAnchor.href.substr(elemAnchor_href_base.length-1);
		}
		if (exthref) {
			var extpath = exthref.split('/');
			if (extpath[1] == 'darf'  && extpath[2]=='login' ) {
				if (!elemAnchor.target) Event.stop(e);				
				self.RTracking.trackDarfSignInClick({}, function() {
						if (!elemAnchor.target) window.location.href = elemAnchor.href;						
				});
			}
		}
		if (localhref) {
			var localpath = localhref.split('/');			
			if (localpath[1]  == 'order') {
				if (!elemAnchor.target) Event.stop(e);
				localhref = localhref.split('?')[0];
				self.RTracking.trackOrderpathClick({ /*ORDERPATH*/TITLE: localhref}, function() {
						if (!elemAnchor.target) window.location.href = elemAnchor.href;						
				});
			}
			var hashs = (localhref.split('#')[1] || '').split(':');
			if (hashs[0] == 'add2fav' && hashs[2]) {
				if (hashs[1] == 'station' || hashs[1] == 'musicvideo' || hashs[1] == 'videoclip') {
					// e.g. #station:1234:add2fav
					eval("var params = {'type':'"+hashs[1]+"', '"+hashs[1]+"_id':'"+hashs[2]+"', x: "+Event.pointerX(e)+", y: "+Event.pointerY(e)+" };");
					self.favos.handleAddToFavoritesClick(params);
				}
				Event.stop(e);
			}
			else if (hashs[0] == 'play' && hashs[2]) {
				if (hashs[1] == 'station') {
					eval("var params = {'type':'"+hashs[1]+"', '"+hashs[1]+"_id':'"+hashs[2]+"', brand:'"+hashs[3]+"' };");
					self.actions.playInPlayerPopup(params);
				}
				Event.stop(e);
			}
			else if (hashs[0] == 'player') {
				var params = { srcsec: (self.pageEnv['previewmode']) ? 'video' : self.SECTION};
				if (hashs[1] == 'partner' && hashs[2]) { // e.g. #player:partner:cnn
					params = { srcsec: (self.pageEnv['previewmode']) ? 'video' : self.SECTION, partner:hashs[2] };
				}
				self.actions.openPlayerPopup(params);
				Event.stop(e);
			}
			else if (hashs[0] == 'open' && hashs[1] == 'ringtones') { // e.g. #open:ringtones
				self.actions.openRingtones();
				Event.stop(e);
			}
			else if (hashs[0] == 'realmusic') {
				if (typeof hashs[1] != 'undefined') {
						var p = {};
						if (typeof hashs[2] != 'undefined') {
							(hashs[2].split(',')).each(function(v,i) {
									var pkv = v.split('=');
									p[pkv[0]] = pkv[1];
							})
						}
					if ( hashs[1]== 'signup') self.actions.openSignupPopup(p);
					else if ( hashs[1]== 'try') self.actions.openRealMusicTrialPopup(p);
				}
				Event.stop(e);
			}
		}
		var appendSrcCodes = false;
		if (!localhref) {
			var urlParts = self.urlhelper.matchUrl(elemAnchor.href);
			$A(['real.com', 'realnetworks.com', 'realplayer.com', 'realarcade.com', 'rhapsody.com']).each(function (value) {
				if (urlParts.host.substring(urlParts.host.indexOf(value)) == value) {
					appendSrcCodes = true;
				}
			});
			console.info('href: ', urlParts.host, appendSrcCodes);
		}
		else {
			$A(['music','player','video','games','live-news']).each(function (value) {
				if (localhref.indexOf('/'+value+'/') == 0){
					appendSrcCodes = false;
				}
			});
		}
		if (appendSrcCodes) {
			elemAnchor.href = self.srcTracking.appendSrcCodesToUrl(elemAnchor.href);
			self.console.info('appendSrcCodesToUrl on %o ', elemAnchor.href);
		}
	};
	Event.observe(document, 'click', self.initFreedom.click_handler);
	
};

self.darf = {
	getKeks: function() {
		var keks = self.cookies.get('darf', self.frames['darf_frame']) || '';
		if (keks.indexOf('%') > -1) keks = self.urlhelper.unescapeGetParamValue(keks);
		return keks;
	},
	getUserGuid: function() {
		return this.getKeks().split('@')[0] || '';
	},
	getUsersServices: function() {
		var keks =  this.getKeks(); 
		return (keks) ?((keks.split('@')[1].split('/')[0]) || 'NULL' ).split(':') : ['NULL'];
	},
	getUsersServicesByServiceStatus: function() {
		var keks =  self.cookies.get('serviceStatus');
		var services = [];
		
		if (keks){
			keks.split('|').each(function(v,k){
				p=v.split(':')[0].split('=')[1];
				if (p.indexOf('rmus')>-1) {
					p='rmus';
				}
				s=v.split(':')[1].split('=')[1];
				if (s=='A') {services.push(p);}
			});
		}
		return services;
	},
	isSubscriber: function() {
		var userServices = this.getUsersServices().without('NULL');
		return (userServices.length==0) ? false : true;  
	},
	hasAnyService: function(l,serviceStatus) {
		var s = (serviceStatus) ? this.getUsersServicesByServiceStatus(): this.getUsersServices();
		for (var i=0; i<l.length; i++) {
			if (s.indexOf(l[i])>-1) {return 1;}
		}
		return 0;
	},
	getServiceStatusCookie: function(full){
		return self.cookies.get('serviceStatus',false, full);
	},
	isPaidSubscriber: function(){
		var c = this.getServiceStatusCookie(false);
		if (!c || c=='null') return false;
		var subscriptions = c.split('|');
		for (var i = 0; i<subscriptions.length; i++) {
			var entitlement = subscriptions[i].split(':')[0].split('=')[1];
			var status = subscriptions[i].split(':')[1].substr(3,1);
			if (status == "A") {
				return true;break;
			}
		}
		return false;
	}
}

Event.observe(self, 'load', function() {
	self.isLoaded = true;
	//self.console.info('users services: %s', self.darf.getUsersServices());
});

self.favos = {
	toggleMyFavorites: function () {
		loadjs('favos', function () {
			self.favos.toggleMyFavorites();
		});
	},
	handleAddToFavoritesClick: function (p) {
		loadjs('favos', function () {
			self.favos.handleAddToFavoritesClick(p);
		});
	}
}

self.actions = {
	playInPlayerPopup: function (p) {
		var pp = { autostart: true, mediatype: 'audio', srcsec: (self.pageEnv['previewmode']) ? 'music' : self.SECTION , srctype: p.type, brand: p.brand };
		if (p.type == 'station') {
			pp.mediaid = p.station_id;
			pp.streamurl = p.stream_url || 'http://music.euro.real.com/start/darfstation/'+p.station_id+'.ram';
		}
		if (pp.streamurl) pp.streamurl = this.addStreamUrlParams(pp.streamurl);
		self.console.log('playInPlayerPopup(%o) : %s', p, pp.streamurl);
		this.openPlayerPopup(pp);
	},
	toggleMyFavorites: function () {
		self.favos.toggleMyFavorites();
	},
	quickPlay: function () {
		alert('quickPlay() \n Not Yet Implemented');
	},
	addStreamUrlParams: function (streamurl) {
		streamurl = self.urlhelper.replaceGetParamInUrl(streamurl, 'ep', 1);
		streamurl = self.urlhelper.replaceGetParamInUrl(streamurl, 'edition', self.pageEnv['edition_code']);
		streamurl = self.urlhelper.replaceGetParamInUrl(streamurl, 'keks', 'none');
		return streamurl;
	},
	playStation: function (params) {
		self.console.log('playStation(%s)', params);
		params = params.split(':');
		var stationUrl = 'http://music.euro.real.com/start/darfstation/'+params[1]+'.ram';
		this.openPlayerPopup({ autostart: true, streamurl: this.addStreamUrlParams(stationUrl), mediatype: 'audio', srcsec: (self.pageEnv['previewmode']) ? 'music' : self.SECTION, srctype: 'station', mediaid: params[1] || '', brand: params[2] || 'music' });
	},
	playVideoClip: function (params, videoclipUrl) {
		self.console.log('playVideoClip(%s, ... ) : %s', params, videoclipUrl);
		params = params.split(':');
		this.openPlayerPopup({ autostart: true, streamurl: this.addStreamUrlParams(videoclipUrl), mediatype: 'video', srcsec: (self.pageEnv['previewmode']) ? 'video' : self.SECTION, srctype: 'videoclip', mediaid: params[1] || '', brand: params[2] || 'video' });
	},
	playMusicVideo: function (params, musicvideoUrl) {
		self.console.log('playMusicVideo(%s, ... ) : %s', params, musicvideoUrl);
		params = params.split(':');
		this.openPlayerPopup({ autostart: true, streamurl: this.addStreamUrlParams(musicvideoUrl), mediatype: 'video', srcsec: (self.pageEnv['previewmode']) ? 'music' : self.SECTION, srctype: 'musicvideo', mediaid:  params[1] || '', brand:  'vidzone' });
	},
	playVideoStreamUrl: function ( videoStreamUrl, parameters) {
		self.console.log('playVideoStreamUrl() : %s', videoStreamUrl, parameters);
		var params = parameters || {};
		if (self.pageEnv['page_path'] == 'music/videos') {
			params['videotype'] = 'music_video';
			params['title'] = (self.vTitle)?self.vTitle.TITLE:'';
		}
		this.openPlayerPopup(Object.extend(params,{ autostart: true, streamurl: this.addStreamUrlParams(videoStreamUrl), mediatype: 'video', srcsec:  self.SECTION || '', srctype: 'url', brand: params.brand || 'video' }));
	},
	playAudioStreamUrl: function (audioStreamUrl, parameters) {
		self.console.log('playAudioStreamUrl() : %s', audioStreamUrl, parameters);
		var params = parameters || {};
		
		this.openPlayerPopup(Object.extend(params,{ autostart: true, streamurl: this.addStreamUrlParams(audioStreamUrl), mediatype: 'audio', srcsec:  self.SECTION || '', srctype: 'url', brand: params.brand || 'audio' }));
	},
	openPlayerPopup: function (p) {
		try {
			var playerParams = p || {};
			var playerUrl = self.pageEnv['FD_PATH']+'inc/freedomplayer/player.html?ec='+self.pageEnv['edition_code'];
			$H(playerParams).each(function(a){ playerUrl = self.urlhelper.replaceGetParamInUrl(playerUrl, a.key, a.value); });
			var debug = self.urlhelper.getGetParamFromUrl(document.location.href,'debug') || false;
			if (debug=='true') playerUrl = self.urlhelper.replaceGetParamInUrl(playerUrl,'debug', debug);
			if (self.pageEnv['previewmode']) playerUrl = self.urlhelper.replaceGetParamInUrl(playerUrl,'previewmode', '1');
			if (self.RTracking) playerUrl = self.urlhelper.replaceGetParamInUrl(playerUrl,'srcpage', self.RTracking.getPage());
			self.console.log('openPlayerPopup(%o) : %s', p, playerUrl);
			
			var height = (debug=='true') ? 690 : 540;
			
			var ec = self.pageEnv['edition_code'];
			height+=42;  /*popup-player-height increased due to the new rpplus-unit at the top*/
			
			var resizable = (debug=='true') ? 'yes' :'no'
			//var win = window.open(playerUrl, 'playerpopup', 'width=760,height='+((debug=='true') ? 690 : 540)+',resize=no,toolbar=no,resizable='+((debug=='true') ? 'yes' :'no')+',scrollbars=no');
			var win = window.open(
				playerUrl, 
				'playerpopup', 
				'width=760,height='+height+',resize=no,toolbar=no,resizable='+resizable+',scrollbars=no'
			);
			self.player_popup = win;
			if (win && win.focus) win.focus();
		}
		catch (e) { self.console.error('openPlayerPopup(...) %o', e); };
	},
	searchForRingtones: function (query) {
		var ec = self.pageEnv['edition_code'];
		var searchUrl = (ec =='uk' || ec=='de') ? '/wlw/go/?par=999580&componentTypes=9' : '/search?';
		searchUrl = (ec =='uk' || ec=='de') ? self.urlhelper.replaceGetParamInUrl(searchUrl,'search',query) : self.urlhelper.replaceGetParamInUrl(searchUrl,'searchQuery',query);
		this.openRingtones(searchUrl);
	},
	openRingtones: function(relativeUrl) {
		var relativeUrl = relativeUrl || '/';
		var ec = self.pageEnv['edition_code'];
		(ec =='uk' || ec=='de') ? this.openRingtonesPopup(relativeUrl) : this.openTonePassWindow(relativeUrl);
	},
	openTonePassWindow: function (relativeUrl) {
		try {
			var ec = self.pageEnv['edition_code'];
			var host = 'http://tonepass.euro.real.com';
			var relativeUrl = self.urlhelper.replaceGetParamInUrl(relativeUrl,'searchType','ringtones|wallpapers|screensavers|videos');
			var relativeUrl = self.urlhelper.replaceGetParamInUrl(relativeUrl,'src','tp_pp_'+ec);
			var relativeUrl = self.urlhelper.replaceGetParamInUrl(relativeUrl,'rsrc','tp_pp_'+ec);
			var targetUrl = host+relativeUrl;
			var win = window.open(targetUrl,"_blank");
			if (win && win.focus) win.focus();
		}
		catch (e) { self.console.error('openTonePassWindow("%s") %o', relativeUrl, e); };
	},
	openRingtonesPopup: function (relativeUrl) {
		try {
			var ec = self.pageEnv['edition_code'];
			var digestiveUrl ='http://digestive.euro.real.com/jamba/?f=realmusic-'+ec;
			var ringtonesUrl = 'http://'+ec+'.tonepass.music.euro.real.com'+(relativeUrl||'/');
			var targetUrl = self.urlhelper.replaceGetParamInUrl(digestiveUrl,'u',ringtonesUrl);
			var win = window.open(targetUrl,'ringtones', 'width=760,height=500,resize=yes,toolbar=yes,resizable=yes,scrollbars=yes');
			if (win && win.focus) win.focus();
		}
		catch (e) { self.console.error('openRingtonesPopup("%s") %o', ringtonesUrl, e); };
	},
	openSignupPopup: function (params) {
		try {
			var ec = self.pageEnv['edition_code'].toLowerCase();
			params = Object.extend( {src:'',	rsrc:''}, params || {});
			var cc = (ec == 'uk')? 'en_uk' : ((ec=='eu')? 'en_eu' : ec);
			
			var signUpUrl = '/order/realmusic/v11/14daytrial/'+cc+'/?src='+params.src+'&rsrc='+params.rsrc;
			
			self.console.log('openSignupPopup("%s")', signUpUrl); 
			var win = window.open(signUpUrl,'signup', 'width=782,height=544,resize=yes,toolbar=yes,resizable=yes,scrollbars=yes');
			if (win && win.focus) win.focus();
		}
		catch (e) { self.console.error('openSignupPopup("%s") %o', signUpUrl, e); };
	},
	openRealMusicTrialPopup: function (params) {
		try {
			params =  Object.extend({src:'',	rsrc:''}, params || {} );
			var ec = self.pageEnv['edition_code'];
			var host = document.location.host;
			
			var trylUrl = 'https://gapi.euro.real.com/darf/login/upsell/danceedition/simplify/index.html?ec='+ec+'&ft=no&src='+params.src+'&rsrc='+params.rsrc;
			
			var win = window.open(trylUrl,'try', 'width=760,height=570,resize=yes,toolbar=yes,resizable=yes,scrollbars=yes');
			if (win && win.focus) win.focus();
		}
		catch (e) { self.console.error('openRealMusicTrialPopup("%s") %o', trylUrl, e); };
	},
	slideShowAction: function(p) {
		self.console.log('slideShowAction(%o): ',p);
		if (p.title) {
			
			var ctp = {TITLE:escape(p.title.replace(/&\w+;/ig,'').replace(/(<([^>]+)>)/ig,""))};
			self.vTitle = ctp;
			var url = p.url || '';
			if (url.indexOf('javascript:') != 0) {
				// track using url modification
				p.url = self.RTracking.addRTrackingToUrl('teaserclick', p.url, ctp);
			}
			else { // track using trackimage
				self.RTracking.trackTeaserClick(ctp);
			}
		}
		var ec = self.pageEnv['edition_code'];
		var slideShowSrcCodes = {
			music: 'src={ec}_ttss_music&rsrc={ec}_ttss_music'.replace(/\{ec\}/g,ec),
			music_test: 'src={ec}_ttss_music'.replace(/\{ec\}/g,ec),
			musicvideo: 'src={ec}_ttss_musicvid&rsrc={ec}_ttss_musicvid'.replace(/\{ec\}/g,ec),
			musicvideo_test: 'src={ec}_ttss_musicvid&rsrc={ec}_ttss_musicvid'.replace(/\{ec\}/g,ec),
			video: 'src={ec}_ttss_video&rsrc={ec}_ttss_video'.replace(/\{ec\}/g,ec),
			video_superpass: 'src={ec}_ttss_videosp&rsrc={ec}_ttss_videosp'.replace(/\{ec\}/g,ec)
		}
		if (p.slideshow && slideShowSrcCodes[p.slideshow]) {
			self.srcTracking.storeSrcCodesByQueryString(slideShowSrcCodes[p.slideshow]);
		}
		if (p.url) self.location = p.url;
	}
}


var onLocationHashChange = (function (callback) {
	var lastHash = new String(location.hash);
	Event.observe(window,'focus',function(e){
		setTimeout(function(){
			if (lastHash != location.hash) {
				lastHash = new String(location.hash);
				callback(e);
			}
		},100);
	});
});


self.urlhelper = {
	self: self,
	getGetParam: function(varname) {
		return this.getGetParamFromUrl(this.self.location.href, varname);
	},
	getGetParamFromUrl: function(url, varname) {
		var qs=url.substring(url.indexOf("?")+1);
		var varvalue = this.getQsFormatValue(varname,qs).replace(/\+/g," ");
		return this.unescapeGetParamValue(varvalue);
	},
	addSlashToUrlParam: function (param, url) {
		qsRE = new RegExp("(\\\?|&)(" + param + ")\=([^&]*)(&|$)");
		var found = url.search(qsRE);
		if (found > -1){
			var oldParam = this.getGetParamFromUrl(url, param);
			if (!oldParam.match(/\/$/)){
				var newParam = oldParam + '/';
				url = this.removeGetParamInUrl(url, param);
				var parameterDivider = (url.match(/\?/)) ? '&' : '?';
				url += parameterDivider + param +'=' + newParam
			}
		}
		return url;
	},
	getQsFormatValue: function(varname,haystack) {
		var qsArray = new Array();
		var qsRE = new RegExp("(^|\\\?|&)(" + varname + ")\=([^&]*)(&|$|#)");
		qsArray = qsRE.exec(haystack);
		return ( qsArray!=null ) ? qsArray[3] : '';
	},
	replaceGetParamInUrl: function(url, varname, varvalue) {
		var url = new String(url);
		var qsRE = new RegExp("(\\\?|&)(" + varname + ")\=([^&]*)(&|$|#)");
		var found = url.search(qsRE);
		if (found == -1)
			url+= (url.indexOf('?')>-1?'&':'?')+varname+'='+this.escapeGetParamValue(varvalue);
		else 
			url = url.replace(qsRE,'$1$2='+this.escapeGetParamValue(varvalue)+'$4');
		return url;
	},
	removeGetParamInUrl: function(url, varname) {
		var qsRE = new RegExp("(\\\?|&)" + varname + "\=[^&]*?(&|($|#))");
		var paramRemoved = url.replace(qsRE, '$1$3');
		var qsRE2 = new RegExp("(&($|#))");// remove tailing &
		return paramRemoved.replace(qsRE2, '$2');
	},
	passthruGetParamsToUrl: function(url, params) {
		return this.passthruGetParamsFromUrlToUrl(this.self.location.href, url, params);
	},
	matchUrl: function(url) {
		var url = new String(url);
		var matches = url.match(/^((\w+):\/\/)?((\w+):?(\w+)?@)?([^\/\?:]+):?(\d+)?(\/?[^\?#]+)?\??([^#]+)?#?(\w*)/);
		if (matches) {
			var username = matches[4] || '';
			var password = matches[5] || '';
			var port = matches[7] || '';
			var prot = matches[2] || '';
			var host = matches[6] || '';
			var path = (matches[8]||'').replace(/^\/|\/$/g,'');
			var pathElements = path.split('/');
			var url = matches[0] || '';
			var params = matches[9] || '';
			var fragment = matches[10] || '';
			return {'username': username, 'password': password, 'port': port, 'prot': prot, 'host': host, 'path': path, 'path_elements': pathElements, 'url': url, 'params': params, 'fragment': fragment };
		}
		return false;
	},
	passthruGetParamsFromUrlToUrl: function(surl, durl, params)	{
		var that = this;
		var dsplit = durl.split('#');
		params.each(function(param, i) {
			var sParamValue = that.getGetParamFromUrl(surl,params[i]);
			var dParamValue = that.getGetParamFromUrl(durl,params[i]);
			if (sParamValue && !dParamValue) {
				dsplit[0]+= (dsplit[0].indexOf('?')>-1?'&':'?')+params[i]+'='+that.escapeGetParamValue(sParamValue);
			}
		});
		return dsplit.join('#');
	},
	escapeGetParamValue: function( varvalue )
	{
		return encodeURIComponent(varvalue).split('%2C').join(',');
	},
	unescapeGetParamValue: function( varvalue )
	{
		return (typeof decodeURIComponent == 'function') ? decodeURIComponent(varvalue) : varvalue;
	}
}

self.advert = {
	self: self,
	rand_num: Math.floor(Math.random()*10000000000),
	tile_count: 1,
	getSect: function () {
		return self.SECTION; 
	},
	adIFramesToRefresh: { },
	adRefreshInit: function () {
		var ec = this.self.pageEnv['edition_code'];
		var refresh = this.adRefreshTimes[ec] || 0;
		if (typeof refresh == 'string') refresh = this.adRefreshTimes[refresh] || 0;
		if (refresh) {
			var that = this;
			that.self.setInterval(function(){
				that.rand_num = Math.floor(Math.random()*10000000000);
				$H(that.adIFramesToRefresh).each(function(pair){
					var frame = that.self.frames[pair.value];
					self.console.log('Refresh adframe: %o ', frame);
					try{frame.location.reload();}catch(e){}
				});
			}, refresh);
		}
	},
	adRefreshTimes: {
		_long: 500000,
		_short: 180000,
		uk: '_short', eu: '_long',
		nl: '_long', fr: '_long', it: '_long', de: '_long', es: '_short'
	},
	adFormats: {
		minisky:     { width: 125, height: 125 },
		fullbanner:  { width: 468, height:  60, dcopt: 'ist' },
		button:      { width: 120, height:  60 },
		skyscraper:  { width: 120, height: 600 },
		rectangle:   { width: 300, height: 250 },
		square:      { width: 250, height: 250 },
		interstitial:{ width:   1, height:   1, dcopt: 'ist' },
		leaderboard: { width: 728, height:  90, dcopt: 'ist' },
		widebanner:  { width: 960, height:  90 }
	},
	getAdCode: function (p) {
		var win    = p.win || this.self;
		var format = p.format || 'button';
		var mode   = p.mode || null;
		var sect   = p.sect || this.getSect(this.self.location.href);
		var bid    = p.bid || this.self.pageEnv['buildid'];
		var ec     = p.edition || this.self.pageEnv['edition_code'];
		var f = this.adFormats[format];
		var adcode = '';
	
		if (format == 'widebanner') {
			//document.body.className = 'smallhead '+document.body.className;
			//fullwidth banner slot! 
			var services = self.darf.getUsersServices();
			var sns = (services) ? services.join(';sn=') : '';
			adcode = '<script language="JavaScript" type="text/javascript" src="http://ad.uk.doubleclick.net/adj/real.'+ec+'/guide/'+format+'_'+f.width+'x'+f.height+'/'+sect+'/'+(f.dcopt?';dcopt='+f.dcopt:'')+';sn='+sns+';sect='+sect+';sz='+f.width+'x'+f.height+';tile='+(this.tile_count++)+';pop=NO;ord='+this.rand_num+'?"><\/script>';
			//adcode += '?p=http://'+ec+'.real.com/realplayer-plus/realplayer-sp/';
			return adcode;
		}
		else if (win.isAdvertisementIFrame != true && f.iframe != false /*&& format != 'interstitial'*/) {
			this.adIFramesToRefresh[format] = 'adFrame_'+format;
			return '<iframe src="'+this.self.pageEnv['FD_PATH']+'js/advert_iframe.html?format='+format+'&amp;bid='+bid+'" width="'+f.width+'" height="'+f.height+'" scrolling="no" marginheight="0" marginwidth="0" frameborder="0" name="adFrame_'+format+'" id="adFrame_'+format+'"></iframe>';
		}
		if (this.self.pageEnv['previewmode'] == true && mode!='test') {
			var services = self.darf.getUsersServices();
			var sns = (services) ? services.join(';sn=') : '';
			return '<div style="font-family:sans-serif;font-size:11px;color:#000;background:#fff;height:'+f.height+'px;overflow:auto">'+
				'Ad format: <b>'+format+'</b>, Section: <b>'+sect+'</b>, Edition: <b>'+ec+'</b>'+
				(win.isAdvertisementIFrame == true ? ', <a href="'+this.self.pageEnv['FD_PATH']+'js/advert_iframe.html?format='+format+'&mode=test">Test</a>':'')+
				'<br><span style="color: silver;">'+this.getAdCode({format:format,win:win,mode:'test'}).toString().replace('<','&lt;')+'<br>&nbsp;</span>'+
				'<ul>'+
				'<li>dcopt='+(f.dcopt || '')+'</li>'+
				'<li>sn='+sns+'</li>'+
				'<li>sect='+self.pageEnv['page_path']+'</li>'+
				'<li>sz='+f.width+'x'+f.height+'</li>'+
				'<li>pop=NO</li>'+
				'</ul>'+
				'</div>';
		}
		else if (sect) {
			var services = self.darf.getUsersServices();
			var sns = (services) ? services.join(';sn=') : '';
			adcode = '<script language="JavaScript" type="text/javascript" src="http://ad.uk.doubleclick.net/adj/real.'+ec+'/guide/'+format+'_'+f.width+'x'+f.height+'/'+sect+'/'+(f.dcopt?';dcopt='+f.dcopt:'')+';sn='+sns+';sect='+sect+';sz='+f.width+'x'+f.height+';tile='+(this.tile_count++)+';pop=NO;ord='+this.rand_num+'?"><\/script>';
			return adcode;
		}
		return '';
	},
	addFullwidthBanner:function(params){
		var imgIndex = Math.ceil( Math.random() * params.imgSet.length) -1;
		var imgSet = params.imgSet;
		var imgUrl = params.baseImgPath +  imgSet[imgIndex].img;
		var srcString;
		
		if(params.clickUrl.indexOf('?') >= 0) {
			srcString = '&src=' +  imgSet[imgIndex].src + '&rsrc='+imgSet[imgIndex].src;
		} else {
			srcString = '?src=' +  imgSet[imgIndex].src + '&rsrc='+imgSet[imgIndex].src;
		}
		
		params.clickUrl += srcString;
		var cssOutput = ''+
		'html body.fullwidth_ad #page {  background: white; overflow: hidden; width: 960px; }'+
		'html body.fullwidth_ad #page div.page_bg { margin: 0 -5px 0 -5px; }'+
		'html body.fullwidth_ad .submenu { margin-left: 0px; }'+
		'';
		var style = document.createElement("style");
		style.setAttribute("type", "text/css");
		if(style.styleSheet) { // IE
			style.styleSheet.cssText = cssOutput;
		} else { // w3c
			var cssText = document.createTextNode(cssOutput);
			style.appendChild(cssText);
		}
		document.getElementsByTagName('head')[0].appendChild(style);
	
		self.fullWidthBannerClickAction = function(){
			self.srcTracking.storeSrcCodesByQueryString(srcString);
			self.RTracking.trackFullwidthBannerClick({TITLE:imgSet[imgIndex].src});
		}
		
/**
	params.position = Before|After
*/
		new Insertion[params.position](document.getElementById(params.target),
			'<div style="margin-left: 5px; height: '+params.height+'px;"><a href="'+params.clickUrl+'" onclick="self.fullWidthBannerClickAction();" target="_blank"><img src="'+imgUrl+'" width=960 height='+params.height+'></a></div>'
		);
		if (self.flyOutNav) {flyOutNav.fixSubmenuPositions();}
	}
}
Event.observe(window, 'load', function (e) {
	self.advert.adRefreshInit();
});

self.RTracking = {
	getHtmlCode: function (params) {
		var p = params || {};
		if (typeof p.autoload == 'undefined') p.autoload = true;
		//if (p.autoload) Event.observe(window, 'load', this.onPageLoaded.bind(this) );
		//if (p.autoload) Event.onDOMReady( this.onPageLoaded.bind(this) );
		if (p.autoload) this.onPageLoaded();
		return '';
	},
	getRTrackStr: function (type,trackParams) {
		var trackStr = '';
		$H(trackParams).each(function(pair){ trackStr+= pair.key+'='+pair.value+';' });
		return '/R/R.freedom.'+type+'.'+trackStr+'./R/';
	},
	getBasicRTrackParams: function (params) {
		return Object.extend( params || {}, {
			VID: this.getVisitorId() || '',
			UID: self.darf.getUserGuid() || '',
			SN: self.darf.getUsersServices() || 'NULL',
			EC: self.pageEnv['edition_code'],
			PG: this.getPage()
		});
	},
	loadTrackImage: function (type,trackParams, onloadHandler) {
		var trackParams = this.getBasicRTrackParams(trackParams);
		var trackStr = this.getRTrackStr(type,trackParams);
		var t = (new Date()).getTime();
		var trackUrl = location.protocol+"//"+location.host+trackStr+location.host+'/fd/img/track.png?t='+t;
		self.console.log('track %s: %o', type, trackParams);
		self.console.log('track-url  %s', trackUrl);
		if (!(self.pageEnv && self.pageEnv['previewmode']) ) {
			self['trackImg'+t] = new Image(); 
			if (typeof onloadHandler=='function') 
				self['trackImg'+t].onload = onloadHandler;
			self['trackImg'+t].src = trackUrl;
		}
	},
	addRTrackingToUrl: function (type, url, params) {
		var trackParams = this.getBasicRTrackParams(params);
		self.console.log('track %s: %o', type, trackParams);
		var trackStr = this.getRTrackStr(type,trackParams);
		url = trackStr+url.split('http://').slice(1).join('http://');
		self.console.log('track %s: %s', type, url);
		return url;
	},
	getPage: function () {
		var trackPage = self.location.pathname.split('&')[0];
		if (self.pageEnv && self.pageEnv.track_page_path) {
			trackPage = self.pageEnv.track_page_path;
			if (trackPage.charAt(0) != '/') trackPage = '/'+trackPage;
			if (trackPage.charAt(-1) != '/') trackPage = trackPage+'/';
		}
		return trackPage;
	},
	pageTrackType: 'page',
	setPageTrackType: function (ptt) {
		this.pageTrackType = ptt;
	},
	pageTrackParams: {},
	onPageLoaded: function () {
		var trackParams = Object.extend(
			self.pageEnv && self.pageEnv.page_path &&
			self.pageEnv['page_path'].indexOf('404') > -1 ? { ERROR:404 } : { }, {
			PG: self.RTracking.getPage(),
			OS: BrowserDetect.OS || 'unknown',
			BRO: BrowserDetect.browser || 'unknown',
			BROV: BrowserDetect.version || 'unknown'
		});
		this.pageTrackParams = this.getBasicRTrackParams(trackParams);
		this.loadTrackImage(this.pageTrackType,trackParams);
	},
	addClickTrackingToUrl: function (url, params) {
		return this.addRTrackingToUrl('click', url, params);
	},
	trackClick: function (params) {
		this.loadTrackImage('click',params);
	},
	trackWelcomeClick: function (params) {
		this.loadTrackImage('welcomeclick',params);
	},
	trackExitClick: function (params) {
		this.loadTrackImage('exitclick',params);
	},
	trackOrderpathClick: function (params, onTrackedHandler) {
		this.loadTrackImage('orderpathclick',params, onTrackedHandler);
	},
	trackDarfSignInClick: function (params, onTrackedHandler) {
		this.loadTrackImage('darfsigninclick',params, onTrackedHandler);
	},
	trackBlackberryDownloadClick: function (params) {
		this.loadTrackImage('blackberrydownloadclick',params);
	},
	trackBlackberryTeaserClick: function (params) {
		this.loadTrackImage('blackberryteaserclick',params);
	},
	trackBlackberryMoreContentClick: function (params) {
		this.loadTrackImage('blackberrymorecontentclick',params);
	},
	trackBlackberryVideoClipClick: function (params) {
		this.loadTrackImage('blackberryvideoclipclick',params);
	},
	trackTeaserClick: function (params) {
		this.loadTrackImage('teaserclick',params);
	},
	trackShopTeaserClick: function (params) {
		this.loadTrackImage('shopteaserclick',params);
	},
	trackRingtonesTeaserClick: function (params) {
		this.loadTrackImage('ringtonesteaserclick',params);
	},
	trackTuneInClick: function (params) {
		this.loadTrackImage('tuneinclick',params);
	},
	trackXboxTuneInClick: function (params) {
		this.loadTrackImage('xboxtuneinclick',params);
	},
	trackSuperpassPreviewPreroll: function (params) {
		this.loadTrackImage('sppreviewpre',params);
	},
	trackSuperpassPreviewPostroll: function (params) {
		this.loadTrackImage('sppreviewpost',params);
	},
	trackTrialPayClick: function (params) {
		this.loadTrackImage('rpplustrialpay',params);
	},
	trackFullwidthBannerClick: function (params) {
		this.loadTrackImage('fullwidthbanner',params);
	},
	
	getVisitorId: function () {
		var VID = self.cookies.get('euVID');
		if (VID) return VID;
		var today = new Date();
		var unique = Math.random().toString() + '_' + Date.parse(today).toString();
		var md5Crypter = new CrypterClass.MD5();
		var unique_MD5 = md5Crypter.hex_md5(unique);
		self.cookies.set({ name: 'euVID', value: unique_MD5, expireInDays: 365*5 });
		return self.cookies.get('euVID');
	}
}

self.srcTracking = {
	cookieName: 'euSRCcodes',
	srcCodes: 'opage,cpath,rsrc,tps,r1e,src,s',
	srcCodesMultiValue: 'src,rsrc',
	srcCodesSingleValue: 'opage,cpath,tps,r1e,s',
	doCleanHref: function () {
		var qstr = self.location.href.split('?').slice(1).join('?').split('#')[0];
		this.storeSrcCodesByQueryString(qstr);
		
		var cleanhref = self.location.href;
		this.srcCodes.split(',').each(function(key){
			cleanhref = self.urlhelper.removeGetParamInUrl(cleanhref,key);
		});
		
		var pcode = self.urlhelper.getGetParamFromUrl(qstr, 'pcode');
		if (pcode) {
			this.storePcode(pcode);
			cleanhref = self.urlhelper.removeGetParamInUrl(cleanhref,'pcode');
		}
		
		if (cleanhref.substr(-1) == '?') cleanhref = cleanhref.substr(0,cleanhref.length-1);
		if ( !(self.pageEnv && self.pageEnv['previewmode']) ) {
			if (cleanhref != self.location.href) { self.location.replace(cleanhref); return; }
		}
	},
	storePcode: function (pcode) {
		self.cookies.set({ name:'pcode', value: pcode, expiresInDays: 45 });
	},
	storeSrcCodesByQueryString: function (qstr) {
		var cookieCodes = cookieCodesBefore = self.cookies.get(this.cookieName) || '';
		cookieCodes = this.__appendSrcCodes(cookieCodes, qstr, 0);
		self.console.log(this.cookieName, ': ', cookieCodes);
		if (cookieCodes && cookieCodes != cookieCodesBefore) self.cookies.set({ name:this.cookieName, value: cookieCodes });
	},
	appendSrcCodesToUrl: function (url) {
		if ( self.pageEnv && self.pageEnv['previewmode']) return url;
		var cookieCodes = self.cookies.get(this.cookieName);
		var parts = url.split('#');
		if (cookieCodes) parts[0] = this.__appendSrcCodes(parts[0], cookieCodes, 1);
		if (!self.urlhelper.getGetParamFromUrl(url,'pcode')) {
			var pcode = self.cookies.get('pcode');
			if (pcode) {parts[0] = self.urlhelper.replaceGetParamInUrl(parts[0], 'pcode', pcode);}
		}
		return parts.join('#');
	},
	__appendSrcCodes: function (qstr1, qstr2, olderNew) {
		var qpar = $H();
		this.srcCodes.split(',').each(function(key){
			var value = self.urlhelper.getGetParamFromUrl(qstr2,key);
			if (value) qpar[key] = value;
		});
		this.srcCodesSingleValue.split(',').each(function(key){
			var newValue = qpar[key];
			if (!olderNew && newValue) {
				qstr1 = self.urlhelper.replaceGetParamInUrl(qstr1, key, newValue);
			} 
			else if (newValue){
				var value = self.urlhelper.getGetParamFromUrl(qstr1,key);
				if (!value) qstr1 = self.urlhelper.replaceGetParamInUrl(qstr1, key, newValue);
			}
		});
		this.srcCodesMultiValue.split(',').each(function(key){
			var values = [],
				oldValues = (self.urlhelper.getGetParamFromUrl(qstr1,key)||'').split(','),
				newValues = (qpar[key]||'').split(',');
			var addNewValues = function () {
				newValues.each(function(value){if(value){
					if (values.indexOf(value) == -1) {
						values[values.length] = value;
					}
				}});
			}
			var addOldValues = function () {
				oldValues.each(function(value){if(value){
					if (values.indexOf(value) == -1) {
						if (newValues.indexOf(value) == -1) {
							values[values.length] = value;
						}
					}
				}});
			}
			if (olderNew) {
				addNewValues(); addOldValues();
			} else {
				addOldValues(); addNewValues();
			}
			if (values.length >= 1) {
				qstr1 = self.urlhelper.replaceGetParamInUrl(qstr1, key, values.join(','));
			}
		});
		return qstr1;
	}
}
/* Translate helper*/
function _getTrObjectByPlaceholder(placeholder) {
	var placeholderPathElements = placeholder.split('/');
	if (placeholderPathElements.length!=2) return this;
	if (typeof locals == 'undefined') return '';

	var module = placeholderPathElements[0];
	var placeholder = '|'+placeholderPathElements[1]+'|';
	if (locals && locals[module] && locals[module][placeholder]) return locals[module][placeholder];
}

String.prototype.tr = function(substitutions) {
	var trObj = _getTrObjectByPlaceholder(this);
	if	(typeof trObj != 'object') return this;
	var translating = trObj['target'];
	for (var key in substitutions) {
		if (typeof substitutions[key] == 'string') {
			translating = translating.split('%_'+key+'_%').join(substitutions[key]);
		}
	}
	if (document.cookie.indexOf('TrDebugCookie=on') > -1)	translating = '<span style="color:#f00">'+translating+'</span>';
	return translating;
}; 

String.prototype.tra = function(substitutions) {
	var trObj = _getTrObjectByPlaceholder(this);
	if	(typeof trObj != 'object') return this;
	return '<a href="'+(trObj['link'] || '#' )+'" ' + (trObj['trg'] || '') +'>'+this.tr(substitutions)+'</a>';
}
document.addScriptSrc = function(src, args) {
	args = args || {};
	
	var script = document.createElement("script");
	script.setAttribute("type", 'text/javascript');
	script.src = src;	
	$H(args).each(
		function(e) { 
			script[e.key] = e.value;
		}
	);
	document.getElementsByTagName('head')[0].appendChild(script);
}
self.locals = self.locals || {};
self.locals.callback = function() {
	self.initFreedom();
}
Object.extend(Event, {
  _domReady : function() {
    if (arguments.callee.done) return;
    arguments.callee.done = true;

    if (this._timer)  clearInterval(this._timer);
    
    this._readyCallbacks.each(function(f) { f() });
    this._readyCallbacks = null;
	},
  onDOMReady : function(f) {
    if (!this._readyCallbacks) {
      var domReady = this._domReady.bind(this);
      if (document.addEventListener){
				document.addEventListener("DOMContentLoaded", domReady, false);
			}
			try {
        /*@cc_on @*/
        /*@if (@_win32)
            document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
            document.getElementById("__ie_onload").onreadystatechange = function() {
                if (this.readyState == "complete") domReady(); 
            };
        /*@end @*/
        
        if (/WebKit/i.test(navigator.userAgent)) { 
          this._timer = setInterval(function() {
            if (/loaded|complete/.test(document.readyState)) domReady(); 
          }, 10);
        }
      } catch (e){}
			
      Event.observe(window, 'load', domReady);
      Event._readyCallbacks =  [];
    }
    Event._readyCallbacks.push(f);
  }
});

self.shareit = {
	primaryShareServices: [
	{ c: 'shareit.bookmark(\'{title}\',\'{url}\');return false;', n: 'add to favorites', i: 'browser' },
		{ u: 'http://del.icio.us/post?v=4;url={url};title={title}', n: 'del.icio.us', i: 'delicious' },
		{ u: 'http://digg.com/submit?phase=2&url={url}&title={title}', n: 'digg.com', i:'digg' },
		{ u: 'http://www.google.com/bookmarks/mark?op=edit&bkmk={url}&title={title}',  n:'google.com', i: 'google'},
		{ u: 'https://favorites.live.com/quickadd.aspx?marklet=1&mkt=en-us&url={url}&title={title}&top=1',  n:'favorites.live.com', i: 'live'},
		{ u: 'http://www.facebook.com/share.php?u={url}&t={title}', n: 'facebook', i: 'facebook'}
	],
	moreShareServices: [
		{ u: 'http://slashdot.org/bookmark.pl?title={title}&url={url}', n: 'slashdot.org', i: 'slashdot'},
		{ u: 'http://www.technorati.com/faves?add={url}', n: 'technorati.com', i: 'technorati'},
		{ u: 'http://furl.net/storeIt.jsp?u={url}&t={title}', n: 'furl.net', i: 'furl'},
		{ u: 'http://www.netscape.com/submit/?U={url}&T={title}', n:'netscape.com', i:'netscape'},
		{ u: 'http://myweb2.search.yahoo.com/myresults/bookmarklet?u={url}&t={title}',  n:'yahoo.com', i: 'yahoo'},
		{ u: 'http://www.newsvine.com/_wine/save?u={url}&h={title}',  n:'newsvine.com', i: 'newsvine'},
		{ u: 'http://blinklist.com/index.php?Action=Blink/addblink.php&Url={url}&Title={title}',  n:'blinklist.com', i: 'blinklist'},
		{ u: 'http://reddit.com/submit?url={url}&title={title}',  n:'reddit.com', i: 'reddit'},
		{ u: 'http://blogmarks.net/my/new.php?mini=1&url={url}&title={title}',  n:'blogmarks.net', i: 'blogmarks'},
		{ u: 'http://ma.gnolia.com/bookmarklet/add?url={url}&title={title}',  n:'ma.gnolia.com', i: 'magnolia'},
		{ u: 'http://tailrank.com/share/?link_href={url}&title={title}',  n:'tailrank.com', i:'tailrank'},
		{ u: 'http://www.mister-wong.com/addurl/?bm_url={url}&bm_description={title}&plugin=soc',  n:'misterwong', i:'mrwong'}
	],
	showOther : function (divId) {
		var otherDiv = $(divId).getElementsBySelector('div.shareit-other')[0];
		Element.toggle(otherDiv);
	},
	showInfo : function (divId) {
		var otherDiv = $(divId).getElementsBySelector('div.shareit-info')[0];
		Element.toggle(otherDiv);
	},
	create : function (divId, url, title) {
		var href = '', onclick = '';
		var out = '<div class="shareit-primary"><ul class="shareit-panel"><li class="trail"></li>';
		this.primaryShareServices.each(function(s) {
				href = s['u'] ? s['u'].replace('{url}',escape(url)).replace('{title}', escape(title)) : '';
				onclick = s['c'] ? s['c'].replace('{url}', url.split("\'").join("\\\'")).replace('{title}', title.split("\'").join("\\\'")) : '';
				out += '<li><a id="'+s['i']+'" href="'+href+'" '+(onclick?'onclick="'+onclick+'"':'target="_blank"')+' title="'+s['n']+'">'+s['n']+'</a></li>';
		});
		out += '<li><a id="more" href="javascript:self.shareit.showOther(\''+divId+'\')">more</a></li>';
		out += '<li><a id="more" href="javascript:self.shareit.showInfo(\''+divId+'\')">what is this?</a></li>';
		out += '<li class="trail"></li></ul></div>';
		out += '<div class="shareit-other" style="display:none"><ul class="shareit-panel"><li class="trail"></li>';
		this.moreShareServices.each(function(s) {
			href = s['u'].replace('{url}',escape(url)).replace('{title}', escape(title));
			out += '<li><a id="'+s['i']+'" href="'+href+'" target="_blank" title="'+s['n']+'">'+s['n']+'</a></li>';
		});
		out += '<li class="trail"></li></ul></div>';
		out += '<div class="shareit-info" style="display:none"><p><b>Social Bookmarks: The Lowdown</b></p>';
		out += '<p>If you\'re reading this and scratching your head wondering what the bookmarking links which appear at the bottom of each blog entry mean, read on...</p>';
		out += '<p>Basically, they\'re links to a selection of social bookmarking sites: sites that enable you to tag, store and share links across the Internet - think <a href="http://del.icio.us/" target="_blank">del.icio.us</a>, <a href="http://digg.com/" target="_blank">digg.com</a>, <a href="http://www.facebook.com/" target="_blank">Facebook</a>, <a href="http://www.google.com/bookmarks/" target="_blank">Google</a>, <a href="http://myweb2.search.yahoo.com/myresults/bookmarklet" target="_blank">Yahoo</a> and a host of others.</p>';
		out += '<p>So, how do you use the sites and links? Well, first you have to register yourself with the site in question: so, Facebook, del.icio.us, digg.com, Google and so on. Registration is free, so take a look at the sites first and decide which one you like the best. Once you\'ve registered, you can then link from the RealMusic Blog to these sites and bookmark RealMusic Blog entries for others to see.</p>';
		out += '<p>Let\'s take a scenario to make it clearer: if you read a RealMusic Blog entry, love it and feel the need to share it with your friends - and say you have a Facebook account - then click on the Facebook bookmarking link, post it and a link to the RealMusic Blog entry that you loved will appear in your Facebook feed. Geddit? It really is as simple as that.</p></div>';
		out += '<div class="trail"></div>';
		$(divId).innerHTML = out;
	},
	bookmark: function(title, url){
		try {
			if (document.all)
				window.external.AddFavorite(url, title);
			else if (window.sidebar)
				window.sidebar.addPanel(title, url, "");
		} catch (e) {}
	}
};

self.detect = {
	// compVersions(v1,v2)
	// if  v1  is higher than  v2  return  2
	// if  v1  is equal to     v2  return  1
	// if  v1  is lower that   v2  return  0
	compVersions: function (v1,v2) {
		if (String(v1) == String(v2)) return 1;
		v1 = v1.split('.'); v2 = v2.split('.');
		if (v1[0] == v2[0]) return this.compVersions( v1.slice(1,v1.length).join('.'), v2.slice(1,v2.length).join('.') );
		return (parseInt(v1[0]?v1[0]:0,10) > parseInt(v2[0]?v2[0]:0,10)) ? 2 : 0;
	}
}

function set()  {
	var result = {};
	for (var i = 0; i < arguments.length; i++)
		result[arguments[i]] = true;
	return result;
}

function loadUnderPage(loadUnderPage) {
	window.setTimeout('this.location.href = "'+loadUnderPage+'"', 3000);
}

var flyOutNav = (function(){
	var menues = {};
	var activeMenu = null;
	function attachEvents() {
		var anchors = $A($('menu').getElementsByTagName('a'));
		anchors.each(function(anchorEl){
			var menuId = anchorEl.id.match('menuitem_([0-9]+)')[1];
			var menuEl = anchorEl.parentNode;
			var submenuEl = $('submenu_'+menuId);
			menues[menuId] = {
				id: menuId,
				visible: false,
				anchorEl: anchorEl,
				menuEl: menuEl,
				submenuEl: submenuEl
			};
				Event.observe(menuEl, 'mouseover', function() { showMenu(menuId); });
				Event.observe(menuEl, 'mouseout', function() { delayedHideMenu(menuId); });
			if (submenuEl) {
				Event.observe(submenuEl, 'mouseover', function() { showMenu(menuId); });
				Event.observe(submenuEl, 'mouseout', function() { delayedHideMenu(menuId); });
			}
		});
	}
	function fixSubmenuPositions() {
		var anchors = $A($('menu').getElementsByTagName('a'));
		var offset = 0;
		anchors.each(function(anchorEl){
			var menuId = anchorEl.id.match('menuitem_([0-9]+)')[1];
			var submenuEl = $('submenu_'+menuId);
			if (submenuEl) {
				style = { left: offset+'px' };
				Element.show(submenuEl);
				if (submenuEl.offsetWidth < anchorEl.parentNode.offsetWidth) {
					style.width = anchorEl.parentNode.offsetWidth+'px';
				}
				Element.hide(submenuEl);
				submenuEl.setStyle(style);
			}
			offset+= anchorEl.parentNode.offsetWidth;
		});
	}
	
	function showMenu(menuId) {
		var m = menues[menuId];
		if (m && m.hideTimer) clearTimeout(m.hideTimer);
		if (m && m.visible) return;
		if (activeMenu && activeMenu != menuId) {
			hideMenu(activeMenu);
		}
		activeMenu = menuId;
		m.visible = true;
		Element.addClassName(m.menuEl, 'active');
		if (m.submenuEl && !Element.visible(m.submenuEl)) {
			Element.show(m.submenuEl);
		}
	}
	
	function hideMenu(menuId) {
		var m = menues[menuId];
		if (!m || !m.visible) return;
		Element.removeClassName(m.menuEl, 'active');
		if (activeMenu && activeMenu == menuId) activeMenu = null;
		m.visible = false;
		if (m.submenuEl && Element.visible(m.submenuEl)) {
			Element.hide(m.submenuEl);
		}
	}
	
	function delayedHideMenu(menuId) {
		var m = menues[menuId];
		if (!m || !m.visible) return;
		m.hideTimer = setTimeout(function(){
			hideMenu(menuId);
		}, 500);
	}
	
	function addSearchBox() {
		$('menu').innerHTML = '<div id="header_search"><form id="header_search_form"><span class="bgl"><span class="bgr"><input type="submit" class="btn"><input name="q" type="text" class="text"></span></span></form></div>'+$('menu').innerHTML;
		
		var searchForm = $('header_search_form');
		if (searchForm) {
			Event.observe(searchForm.q, 'focus', function(){ Element.addClassName(searchForm, 'active'); });
			Event.observe(searchForm.q, 'blur', function(){  Element.removeClassName(searchForm, 'active'); });
			Event.observe(searchForm, 'submit', function(e){
				Event.stop(e);
				var q = searchForm.q.value;
				if (q) {
					self.location.href = '/music/search/?music_search_qt=artist&music_search_q='+encodeURIComponent(q);
				}
				else {
					searchForm.q.focus();
				}
			});
		}
		
	}
	
	Event.onDOMReady(function(){
		try{
		if (BrowserDetect && BrowserDetect.browser != 'Firefox') {
			if (self.pageEnv.page_path == 'music/adtest' 
					|| (self.pageEnv.page_path in set('music','video') && self.pageEnv.edition_code == 'de' )){
				var adUrl = 'http://ad.uk.doubleclick.net/adj/real.' + self.pageEnv.edition_code + '/guide/interstitial_1x1/'+self.pageEnv.page_path+'/'
					+';dcopt=ist;sn=null;sect='+self.pageEnv.page_path+';sz=1x1;tile=3;pop=NO;ord=5824853559?';
				document.addScriptSrc(	adUrl, {} );
			}
		}
		}catch(e){}
		if (!$('menu')) return;
		if (Element.hasClassName(document.body, 'sec_music')) addSearchBox();
		fixSubmenuPositions();
		attachEvents();
		
	});
	
	return {
		fixSubmenuPositions: fixSubmenuPositions,
		showMenu: showMenu,
		hideMenu: hideMenu
	};
})();

(function(){
	var localUrls = {  // for auto revisioning
		uk: "locals/uk--r16849.js", eu: "locals/eu--r16849.js", de: "locals/de--r16849.js", fr: "locals/fr--r16849.js", es: "locals/es--r16849.js", it: "locals/it--r16849.js", nl: "locals/nl--r16849.js"
	};
	if (self.pageEnv && localUrls[self.pageEnv['edition_code']]) {
		document.addScriptSrc(self.pageEnv['FD_IMGPATH']+'js/'+localUrls[self.pageEnv['edition_code']], {});

	}
	
	self.pageEnv.gooeyLoc = self.cookies.get('RNchewy');
	if (!self.pageEnv.gooeyLoc){
		self.gooeyCallback = function (){
			if (gooeyLookup && gooeyLookup.ec) {
				self.cookies.set({name:'RNchewy', value: gooeyLookup.ec, expiresInDays:7});
			}
		};
		self.gooeyLookup();
	}
})();

