



function hookPlayOutlinemenu() {
	UrlPlayNow = "http://www.tdc.dk/?page=update&amp;lmId="
		UrlPlayNext = "http://www.tdc.dk/?page=update&amp;lmId="
		UrlPlayLast = "http://www.tdc.dk/?page=update&amp;lmId="

		//Create index value
		var indIndex = 0;

		//Loop over all <a> tags with the class 'playSong'
		$(".preview a.playSong").each(function() {
			//Increment index value
			indIndex++;

			//Add id attribute to all <a> tags with the class 'playSong'
			var idelement = indIndex;
			$(this).attr("id", idelement);

			//Add onmouseover event to all <a> tags with the class 'playSong'
			jkoutlinemenu.definemenu(idelement, "mymenu", "mouseover", 180, 200)
		});
}

function loadGenreInPicker(selectedgenre)
{
	$('#frontpage-mycarousel').removeData();
	  $("#ajaxgenre").empty().html('<div id="genreContentSmall"><div align="center" style="margin-top: 150px"><img src="'+publicdir+'images/loading-darkbg.gif" /></div></div>');
	  $('#genreVaelgerSmall #genreContentSmall').corner('round tr br 10px cc:#1D1D1D');
	  $.ajax({
		url: url+"ajax/genrepicker_pager",
		data: "genre="+escape(selectedgenre),
		cache: true,
		success: function(res) {
		  $("#ajaxgenre").empty().html(res);
		  $('#genreVaelgerSmall #genreContentSmall').corner('round tr br 10px cc:#1D1D1D');
		  attachGenrePickerCarousel();
	  	}
	  });
}

/*
 * Put in functions that we might need all over the place ..
 */

 //Should figure out how to do with one / several (list) of elements to download
 function downloadToPc(e)
 {
  alert("Download me "+e);
 }

 function downloadToMobile(e)
 {
   alert("Download me "+e);
 }

 function makeFancy()
 {
    $("a.fancy").fancybox({
        'frameHeight': 193,
        'frameWidth': 456,
        'padding': 8,
        'hideOnContentClick': false,
        'overlayOpacity': 0.8
    });
    
    $("a.fancyVideo").fancybox({
        'frameHeight': 304,
        'frameWidth': 320,
        'padding': 8,
        'callbackOnClose' : function() {stopVideo()},
        'hideOnContentClick': false,
        'overlayOpacity': 0.8
    });
 }


// Ajax loading gif.
var ajax_load = "<img src='/hostshops/247/type_d/sites/tdcdk_redesign/./home/msh/html/tdcdk_redesign/public/img/loading.gif' alt='loading...' />";

//Returns the version of Internet Explorer or a -1
//(indicating the use of another browser).
function getInternetExplorerVersion()
{
	var rv = -1; // Return value assumes failure.
	if (navigator.appName == 'Microsoft Internet Explorer')
	{
		var ua = navigator.userAgent;
		var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
		if (re.exec(ua) != null)
			rv = parseFloat( RegExp.$1 );
	}
	return rv;
}

/**
* Update element with content from a url. Use callback to trigger a JS function _after_ content has loaded.
*
* Can also be called with just the url to trigger some backend funtionality to modify cookie data.
* http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/
*/
function updateElement(url, elementId, callback) {
	dt = "html";
	ver = getInternetExplorerVersion();

	//if ( ver > -1)
		//dt = "xml";
	
	//alert(callback);
	$("#"+elementId).html(ajax_load).removeClass("ajax");
	$.ajax({
		url: url,
		type: "get",
		dataType:	dt,
		success: function(html){
			if(elementId) {
				$("#"+elementId).html(html); // Only body part is used from html feed.
			}
			try {
				eval(callback);
			}
			catch (e) {
 				alert("updateElement failed to execute callback command: " + callback);
			}
		}
	});
}

/**
* Update all divs with class 'ajax'
*/
function loadAjaxDivs() {
	$('div.ajax').each(function(index, item){
		$(this).html(ajax_load).removeClass("ajax");
		$.ajax({
			url: item.title,
			success: function(html){
				$(item).html(html);
				// Trigger loadAjaxDivs as included html does not fire the ready event!
				// This is needed to update ajax divs on included page.
				loadAjaxDivs();
			}
		});
	});
}

function tsparam() {
	return "&__="+encodeURIComponent((new Date()).getTime());
}

function playPlaylist(plId) {
	$.get(url + "ajax/playPlaylist&plId=" + plId + tsparam(), function(data) {
		updatePlayerExt(data,0,true);
	});
}

function clearPlaylist(plId) {
	$.get(url + "ajax/playPlaylist&plId=" + plId + tsparam(), function(data) {
		updatePlayerExt(data,0,false);
	});
}

function addPlaylistOrder(lmId,typ) {
	var inspos = 0;
	var ppos = queueGetPos();
	if (typ==0) {
		inspos=queueGetPos()+2;
		ppos = inspos-1;
	}
	if (typ==1) inspos=queueGetPos()+2;
	if (typ==2) inspos=queueGetCount()+1;
	if (inspos>queueGetCount()+1) inspos=queueGetCount()+1;

	if (ppos==-1) ppos=0; // if none selected select first..

	$.get(url + "ajax/addItemToPlayer&lmId=" + lmId + "&insPos="+inspos + tsparam(), function(data) {
		updatePlayerExt(data,ppos,typ==0);
	});
}

function addBasket(lmId) {

	$.get(url + "ajax/updateBasket&lmId=" + lmId + tsparam(), function(data) {
		basketCount = $(data).text();
		//basketCount++;
		$('#counterBasket').text(basketCount);
		var i = 0;
		while(i < 3) {
			i++;
			$('#counterBasket').fadeOut('fast');
			$('#counterBasket').fadeIn('fast');
		}
	});
}

function moeAlert(msg) {
	showmsg('Bemærk','',msg);
}

var isIE = (navigator.userAgent.indexOf("MSIE") != -1) ? true : false;

function dopredelivery(purl,typ) {
	try {
        drmloaded = false;
        purl = purl.replace(/&amp;/g,"&");
		var objRMGetLicense = new ActiveXObject("DRM.GetLicense");
		drmloaded = true;
		objRMGetLicense.GetLicenseFromURL("<a></a>", purl+"&__="+encodeURIComponent((new Date()).getTime()));
	}
	catch (e) {
		var errormsg = ("exception: Error name: " + e.name + ". Error description: " + e.description + ". Error number: " + e.number + ". Error message: " + e.message);

		if (isIE)
		{
   		  if (typ==1 && drmloaded) moeAlert('Vi har et teknisk problem med at levere din licens, men du kan stadig godt downloade og afspille musik. I mange tilfælde skyldes fejlen, at du ikke har opdateret din Windows Media Player. <a href="'+url+'article&article_id=20517#ol_q61" target="_blank" style="text-decoration:underline">Klik her for mere information</a><br /><br />[Fejl kode: M '+e.number+']<br />');
    	  //if (typ==0 && drmloaded) moeAlert('En teknisk fejl under overførslen gjorde, at vi ikke kan levere den nødvendige licens til den musik, du har hentet ned. Det kan betyde, at du kan få problemer med at afspille musikken i Windows Media Player, hvis den ikke er opdateret. Prøv eventuelt at downloade materialet igen. <a href="'+url+'article&article_id=20517#ol_q61" target="_blank" style="text-decoration:underline">Klik her for mere information</a><br /><br />[Fejl kode: L '+e.number+']<br />');
    	  if (typ==1 && !drmloaded) moeAlert('Du har adgang til TDC PLAY, men før du kan bruge det på denne computer, skal du hente en nødvendig plug-in fra Microsoft. <a href="http://go.microsoft.com/fwlink/?LinkID=75378" target="_blank" style="text-decoration:underline">Klik her </a>.<br /><br />På Microsofts side skal du klikke på den gule bjælke øverst (se nedenstående illustration). Vælg "Installér ActiveX-objekt" og følg instruktionerne.<br /><a href="http://go.microsoft.com/fwlink/?LinkID=75378" target="_blank"><img src="'+publicdir+'images/pointer.gif" width="250" height="53" /></a>');
    	  if (typ==0 && !drmloaded) moeAlert('Før du kan bruge TDC PLAY på denne computer, skal du hente en nødvendig plug-in fra Microsoft. <a href="http://go.microsoft.com/fwlink/?LinkID=75378" target="_blank" style="text-decoration:underline">Klik her </a>. <br /><br />På Microsofts side skal du klikke på den gule bjælke øverst (se nedenstående illustration). Vælg "Installér ActiveX-objekt" og følg instruktionerne.<br /><a href="http://go.microsoft.com/fwlink/?LinkID=75378" target="_blank"><img src="'+publicdir+'images/pointer.gif" width="250" height="53" /></a>');
		  $("#fancy_outer").css('height','240px');
    	  //alert('Kunne ikke give master license: '+errormsg+" url: "+purl);
		}
	}
}

function valfilename(x) {
	  x = x.replace(/\#/g, "");      // delete #
	  x = x.replace(/\*/g, "");      // delete *
	  x = x.replace(/\[/g, "");      // delete [
	  x = x.replace(/\]/g, "");      // delete ]
	  x = x.replace(/\</g, "");      // delete <
	  x = x.replace(/\>/g, "");      // delete >
	  x = x.replace(/\=/g, "");      // delete =
	  x = x.replace(/\%/g, "");      // delete %
	  x = x.replace(/\+/g, "");      // delete +
	  x = x.replace(/\&/g, "");      // delete &
	  x = x.replace(/\?/g, "");      // delete ?
	  x = x.replace(/\'/g, "");      // delete '
	  x = x.replace(/\"/g, "");      // delete "
	  x = x.replace(/\\/g, "");      // delete \
	  x = x.replace(/\//g, "");      // delete /
	  x = x.replace(/\,/g, "");      // delete ,
	  x = x.replace(/\./g, "");      // delete .
	  x = x.replace(/\:/g, "");      // delete :
	  x = x.replace(/\;/g, "");      // delete ;
	  x = x.replace(/\|/g, "");      // delete |
	  x = x.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); // trim
	  x = x.replace(/ /g, "_");
	  x = x.replace(/__/g, "_");
	  return x;
}

function startDownload(aurl, atype, rid) {


	$.get(url + "ajax/playdownload"+ aurl + tsparam(), function(data) {

		if (atype=="umapfile") {
			dopredelivery($(data).find('#dllic').text()+"&amp;output=jsp",0);
		}

		if (($(data).find('#dlfile')) && ($(data).find('#dlfile').html()) && ($(data).find('#dlfile').html()!="") || 1==1) {

			$('#fancy_div').find("#dldownloadlink").text('Hent musikken');
			$('#fancy_div').find("#dldownloadlink").attr('href',$(data).find('#dlfile').text());
			$('#fancy_div').find("#dldownloadlink").unbind("click");
			$('#fancy_div').find("#dldownloadlink").bind("click", function(e){
				$('#fancy_close').click();
			});
		}
		else
			moeAlert('Der skete en server fejl, prøv venligst igen senere.');
	});
}

function playlistdl(plid, typ, dlname, discount) { // type 0 = PC, 1 = Mobile
	if (typ==0)
		playdl(3,plid,'','',dlname,discount,'');
	else
		playdl(13,plid,'','',dlname,discount,'');
}

function playdl(flag, ulmid, upaygrpid, upaysrcid, dlname, discount, rid) {

	//$('#globaldldiv').find(".konteksthelp").css('float','left');
	//$('#globaldldiv').find(".konteksthelp").css('margin-left','10px');

	if (parseInt(flag)<10) {
		$('#globaldldiv').find("#dltitle").text('Hent til PC');
		$('#globaldldiv').find(".download_mobil").css('background-image', 'url('+publicdir+'images/button_download_pc.gif)');
	}
	else {
		$('#globaldldiv').find("#dltitle").text('Hent til mobil');
		$('#globaldldiv').find(".download_mobil").css('background-image', 'url('+publicdir+'images/button_download_mobil.gif)');
	}

	if (discount!='')
		if (portal=='tdc') {
			$('#globaldldiv').find("#dldiscount").text('Du sparer '+discount+' kr - da musikken er betalt af TDC');
		} else {
			$('#globaldldiv').find("#dldiscount").text('Du sparer '+discount+' kr - da musikken er betalt af YouSee');
		}
	else
		$('#globaldldiv').find("#dldiscount").text('');

	if (parseInt(flag)==10)
		$('#globaldldiv').find("#dltext").text("Filtype: mp4.dcf. Gem filen på din pc og overfør den derefter til din mobiltelefon.")
	else
		if (parseInt(flag)==11 || parseInt(flag)==12 || parseInt(flag)==13)
			$('#globaldldiv').find("#dltext").text("Type: Zip-fil (skal udpakkes). Gem filerne på din pc eller mac og overfør dem derefter til din mobiltelefon.")
		else
			if (parseInt(flag)==0)
				$('#globaldldiv').find("#dltext").text("Type: WMA-fil. Placér WMA-filen i dit Windows Media Player-biblotek på PC'en for at afspille.");
			else
				$('#globaldldiv').find("#dltext").text("Type: ZIP-fil (skal udpakkes). Placér WMA-filen i dit Windows Media Player-biblotek på PC'en for at afspille.");

	$('#globaldldiv').find("#dldownloadlink").text('Musikken forberedes..');

	if (dlname=='' || dlname=='TDCPLAY__')
	  dlname = 'TDCPLAY_download.zip'
	else
	    dlname = valfilename(dlname)+'.zip';
	curdiscount = discount;

	if (flag == 0) {
		var params = '&ulmid=' + ulmid + '&upaygrpid=' + upaygrpid + '&upaysrcid=' + upaysrcid;
		startDownload(params, 'umapfile', rid);
	}
	else
	if (flag == 1) {
		var params = '&ulmid=' + ulmid + '&upaygrpid=' + upaygrpid + '&upaysrcid=' + upaysrcid + '&uretdllistlink=true&dlname='+dlname;
		startDownload(params, 'umapfile', rid);
	}
	else
	if (flag == 2) {
		var params = '&uaddlist=' + ulmid + '&uretdllistlink=true&dlname='+dlname;
		startDownload(params, 'umapfile', rid);
	}
	else
	if (flag == 3) {
		var params = '&ugetplid=' + ulmid + '&uretdllistlink=true&dlname='+dlname;
		startDownload(params, 'umapfile', rid);
	}
	else
	if (flag == 10) {
		var params = '&ulmid=' + ulmid + '&upaygrpid=' + upaygrpid + '&upaysrcid=' + upaysrcid+'&udlplatform=PHONE';
		startDownload(params, 'umapfilenolic', rid);
	}
	else
	if (flag == 11) {
		dlname=dlname.replace("TDCPLAY_", "TDCPLAY_MOBIL_");
		var params = '&ulmid=' + ulmid + '&upaygrpid=' + upaygrpid + '&upaysrcid=' + upaysrcid+'&uretdllistlink=true&dlname='+dlname+'&udlplatform=PHONE';
		startDownload(params, 'umapfilenolic', rid);
	}
	else
	if (flag == 12) {
		dlname=dlname.replace("TDCPLAY_", "TDCPLAY_MOBIL_");
		var params = '&uaddlist=' + ulmid + '&uretdllistlink=true&dlname='+dlname+'&udlplatform=PHONE';
		startDownload(params, 'umapfilenolic', rid);
	}
	else
	if (flag == 13) {
		dlname=dlname.replace("TDCPLAY_", "TDCPLAY_MOBIL_");
		var params = '&ugetplid=' + ulmid + '&uretdllistlink=true&dlname='+dlname+'&udlplatform=PHONE';
		startDownload(params, 'umapfilenolic', rid);
	}

}

function playPreview(purl, item, ele) {
    var kids = $(ele).children(); //find tds of row "ele"
    var imgbtn = $(item).children();

	function setInactive() {
        imgbtn.attr('src', publicdir+'images/icon_orange_play.gif');
        imgbtn.imghover({ suffix: '-hovered' });
        kids.css('background-color', '');
        kids.css('font-weight', 'normal');
        $(ele).removeClass("active");
	}
	function setActive() {
        $('.tbl_list tr').removeClass("active");
        $('.tbl_list tr td').css('background-color', '');
        $('.tbl_list tr td').css('font-weight', 'normal');
        $('.tbl_list tr td.preview .playSong img').attr('src', publicdir+'images/icon_orange_play.gif');
        $('.tbl_list tr td.preview .playSong img').imghover({ suffix: '-hovered' });
        imgbtn.attr('src', publicdir+'images/icon_pause.png');
        imgbtn.imghover({ suffix: '-hovered' });
        kids.css('background-color', '#d4d4d4');
        kids.css('font-weight', 'bold');
        $(ele).addClass("active");
	}



    if ($(ele).attr('class') == "active" || $(ele).attr('class') == "tr2 active") {
    	setInactive();
    	stopPreviewMedia();
    }
    else {
    	setActive();
        loadPlayPreviewMedia(purl);
        setTimeout(setInactive, 31000)
    }

}


function loadPlayPreviewMedia(url) {
	var $playerDiv = $("#previewplayer");

	if (navigator.userAgent.indexOf('Win') != -1) { // Windows
		$playerDiv.html('<object'
			+ ' height="1"'
			+ ' width="1"'
			+ ' type="application/x-oleobject"'
			+ ' classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6"'
			+ ' id="tdcmusicplayer">'
			+ '<param value="true" name="autostart">'
			+ '<param value="none" name="uiMode">'
			+ '<param value="false" name="enableContextMenu">'
			+ '<param value="'+url+'" name="filename">'
			+ '<param value="1" name="playCount">'
			+ '<param value="50" name="volume">'
			+ '<param value="false" name="Showcontrols">'
			+ '<param value="#000000" name="bgcolor">'
			+ '</object>'
			+ '<embed'
			+ ' height="1"'
			+ ' width="1"'
			+ ' volume="50"'
			+ ' src="'+url+'"'
			+ ' playcount="1"'
			+ ' enablecontextmenu="false"'
			+ ' showcontrols="false"'
			+ ' uimode="none"'
			+ ' autostart="true"'
			+ ' type="application/x-ms-wmp"'
			+ ' name="tdcmusicplayerff"'
			+ ' id="tdcmusicplayerff" />');
	} else { //REST
			$playerDiv.html('<object '
			+ 'classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" '
			+ 'width="160" height="144" id="tdcmusicplayer"'
			+ 'style="position:absolute;left:-1000px;top:-1000px"'
			+ 'codebase="http://www.apple.com/qtactivex/qtplugin.cab">'
			+ '<param name="SRC" value="'+url+'">'
			+ '<param name="AUTOPLAY" value="true">'
			+ '<param name="CONTROLLER" value="false">'
			+ '<param name="VOLUME" value="100">'
			+ '<param name="ENABLEJAVASCRIPT" value="true">'
			+ '<param name="TYPE" value="audio/wav">'
			+ '<embed classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"'
			+ 'name="tdcmusicplayer"'
			+ 'id="tdcmusicplayer"'
			+ 'src="'+url+'"'
			+ 'pluginspage="http://www.apple.com/quicktime/download/"'
			+ 'volume="100"'
			+ 'enablejavascript="true" '
			+ 'type="audio/mp3" '
			+ 'height="0" '
			+ 'width="0"'
			+ 'style="position:absolute;left:-1000px;top:-1000px"'
			+ 'autostart="true"'
			+ '> </embed>'
			+ '</object>');
	}
}


function stopPreviewMedia() {
	$("#previewplayer").empty();
}

function sleep(delay) 
{ 
    var start = new Date().getTime(); 
    while (new Date().getTime() < start + delay); 
} 

function playVideo(vurl) {
	setTimeout("playVideo2('"+vurl+"')",1000);
}

function startVideo() {
	$('#videoWrapper2').html('');
	if (isIE)
		tdcvideoplayer.controls.play();
	
}

var videoFixIntervalId = 0;

function stopVideo() {
	clearInterval(videoFixIntervalId);
	if (isIE && tdcvideoplayer && tdcvideoplayer.controls)
		tdcvideoplayer.controls.stop();
	
	$("#fancy_div").find("#videoWrapper2").html('');
	$("#fancy_div").find("#videoWrapper2").remove();
}

function fixVideoSize() {
	// not my proudest moment.. wmp seems to do uncontrolable resizing in IE8 after video has loaded 
		wid = (parseInt($('#tdcvideoplayer').css('width'))+16)+'px';
		hei = (parseInt($('#tdcvideoplayer').css('height'))+16)+'px';	
		$("#fancy_outer").css({'width': wid, 'height': hei});
		$("#videoWrapper2").fancybox.scrollBox();
}

function playVideo2(vurl) {
	var $playerDiv = $("#fancy_div").find("#videoWrapper2");
	if (isIE)
	$playerDiv.html('<center><object'
		+ ' height="304"'
		+ ' width="320"'
		+ ' type="application/x-oleobject"'
		+ ' classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6"'
		+ ' id="tdcvideoplayer" style="position:relative">'
		+ '<param value="true" name="autostart">'
		+ '<param value="full" name="uiMode">'
		+ '<param name="AllowChangeDisplaySize" value="False">'			
		+ '<param value="false" name="enableContextMenu">'
		+ '<param value="'+vurl+'" name="URL">'
		+ '<param value="1" name="playCount">'
		+ '<param value="50" name="volume">'
		+ '<param value="false" name="Showcontrols">'
		+ '<param value="#000000" name="bgcolor">'
		+ '</object></center>'
		)
		else 
			$playerDiv.html('<center><embed'
			+ ' height="304"'
			+ ' width="320"'
			+ ' volume="50"'
			+ ' src="'+vurl+'"'
			+ ' playcount="1"'
			+ ' enablecontextmenu="false"'
			+ ' uiMode="full"'
			+ ' autostart="true"'
			+ ' type="application/x-ms-wmp"'
			+ ' name="tdcvideoplayer"'
			+ ' id="tdcvideoplayer" /></center>');
		
		videoFixIntervalId = setInterval("fixVideoSize()",500);
}

function addManyBasket(lmlist) {

	$.get(url + "ajax/updateBasketList&lmlist="+ escape(lmlist) + tsparam(), function(data) {

		basketCount = $(data).text();

		$('#counterBasket').text(basketCount);
		var i = 0;
		while(i < 3) {
			i++;
			$('#counterBasket').fadeOut('fast');
			$('#counterBasket').fadeIn('fast');
		}
	});
}

function showmsg(msgtitle, msgsub, msgtext, callback) {
	var opts = {
	        'frameHeight': 193,
	        'frameWidth': 456,
	        'padding': 8,
	        'hideOnContentClick': false,
	        'overlayOpacity': 0.8
		}

	if (callback != null) {
        opts['callbackOnClose'] = callback;
	}

	$('#stdmsg').find('#msgtitle').html(msgtitle);
	$('#stdmsg').find('#msgsubtitle').html(msgsub);
	$('#stdmsg').find('#msgtext').html(msgtext);

	$('#stdmsgtrigger').fancybox(opts);
	$('#stdmsgtrigger').click();
}

/**
* Take comma seperated string and call addSingletag for each keyword.
* Note that this function works on the input object and not a text string. This is
* so that the input field can be cleared afterwards.
*
* We can file this as yet another missing JS function from ZUPA.
*/
function addMultipletag(obj) {
	text = obj.val();
	obj.val("");
	var keywords=new Array();
	keywords = text.split(",");
	for ( var i in keywords ) {
		// ZUPA function from base.js
		addSingletag(keywords[i]);
	}
}

/**
* Take object containing tags and parse them into a comma seperated string.
*/
function getSelectedKeywordsAsString(obj) {
    var chosenClickedTags = [];
	obj.each(
		function() {
			if ($(this).text() != null || typeof ($(this).text()) != "undefined" || $(this).text() != " " || $(this).text() != "") {
				chosenClickedTags.push($(this).text());
			}
		}
	);

	return chosenClickedTags.join(",");
}

/**
* Updating the clipboard with tag list.
*
* Note: This does currently not work due to a flaw in the DB design.
*/
function updateClipboardTags(obj) {
	// Update current clipboard content.
	updateElement(url+"ajax/updatePlaylist&tagList=" + getSelectedKeywordsAsString(obj));
}



function popup_rights(page, param) {
	//<a href="javascript:pop_rights('rights','lmtype=album&lmid=79122031&wmencpid=100')">Rettigheder</a>
	window.open(url + '' + page + '&' + param, 'rights', 'width=840,height=550,resizable=1,scrollbars=1toolbar=0');

}


/*
this is returned from serilized
playlistTbl[]=2&playlistTbl[]=1&playlistTbl[]=3
do a replace on playlistTbl[]= and convert & to ,
then we have a full comma sep. string with lm id's
*/

/**
* Convert serilized string from tableDnD to conform to shop API.
* http://www.bradino.com/javascript/string-replace/
*/
function convertSerilizedTabeDnD(serilizedTableDnd) {
	return serilizedTableDnd.replace(/playlistTbl\[\]=/g, "").replace(/&/g, ",");
}

/**
* Push a message to a phone.
*
* Look at ajax/pushUrlToPhone.jsp and you can see how it works.
*
* Due to the nature of the reusable popup dialog for pushing a message we must
* pass messagetype and id as global javascript variables.
* This really blows - but thats the only way...
*/
function pushUrlToPhone(msisdn) {
//	alert("messageType: " + messageType);
//	alert("id: " + id);
//	alert("msisdn: " + msisdn);
	updateElement(url+"ajax/pushUrlToPhone&msisdn=" + msisdn + "&ptype=" + messageType + "&id=" + id);
}
// Set global variables for use with pushUrlToPhone.
var messageType = null;
var id = null;
function pushUrlToPhoneInit(_messageType, _id) {
	messageType = _messageType;
	id = _id;
}

function findAndReplace(searchText, replacement, searchNode) {
    if (!searchText || typeof replacement === 'undefined') {
        return;
    }
    var regex = typeof searchText === 'string' ?
                new RegExp(searchText, 'g') : searchText,
        childNodes = (searchNode || document.body).childNodes,
        cnLength = childNodes.length,
        excludes = 'html,head,style,title,link,script,object,iframe';
    while (cnLength--) {
        var currentNode = childNodes[cnLength];
        if (currentNode.nodeType === 1 &&
            (excludes + ',').indexOf(currentNode.nodeName.toLowerCase() + ',') === -1) {
            arguments.callee(searchText, replacement, currentNode);
        }
        if (currentNode.nodeType !== 3 || !regex.test(currentNode.data) ) {
            continue;
        }
        var parent = currentNode.parentNode,
            frag = (function(){
                var html = currentNode.data.replace(regex, replacement),
                    wrap = document.createElement('div'),
                    frag = document.createDocumentFragment();
                wrap.innerHTML = html;
                while (wrap.firstChild) {
                    frag.appendChild(wrap.firstChild);
                }
                return frag;
            })();
        parent.insertBefore(frag, currentNode);
        parent.removeChild(currentNode);
    }
}

function setPageTitle() {
	if (!$('#contentContainer').find("h1:first").text() || $('#contentContainer').find("h1:first").text()=="")
		return false;
	if(portal == 'tdc' )
		document.title = "TDC Play - " + $('#contentContainer').find("h1:first").text();
	if(portal == 'yousee' || portal == 'dktv')
		document.title = "YouSee Play - " + $('#contentContainer').find("h1:first").text();
}

var TDCregexp = /TDC PLAY/gi
$(document).ready(function() {
	if (portal != null) {
		if (portal == 'yousee' || portal == 'dktv') {
			window.setTimeout('findAndReplace(TDCregexp, "YouSee Play", document.body);', 150);
			if (page == 'frontpage' || page == '') {
				if (isLoggedIn) {
					$("body").css("background", "url("+publicdir+"images/yousee/stripes_background2_fullon_tall.jpg) repeat-x scroll 0 0 #1D1D1D");
				} else {
					$("body").css("background", "url("+publicdir+"images/yousee/stripes_background2_fullon.jpg) repeat-x scroll 0 0 #1D1D1D");
				}
			} else {
				$("body").css("background", "url("+publicdir+"images/yousee/stripes_background2_smooth.jpg) top center repeat-x  #1D1D1D");
			}
		} else {
			if (isTopAdPage) {
				$("body").css("background", "url("+publicdir+"images/body_bg_with_ad.gif) repeat-x  scroll 0 0 #1D1D1D");
			} else {
				$("body").css("background", "url("+publicdir+"images/body_bg_no_ad.gif) repeat-x  scroll 0 0 #1D1D1D");
			}
		}
	}
	hookPlayOutlinemenu();
	// Append the page H1 to the title unless defined in the template. - Wait for the above replace to finish !
	window.setTimeout('setPageTitle()', 250);
	setUIAutoComplete();
});




/**
* This is a helper function to extract form data from the form id=tipenven using dom traversal as opposed to $('#id')
* as that is not possible due to ultra crappy ZUPA code.
*/
function collectSendTipFormData() {
	// Collect data from tipenven form.
	return "&" + asUrlParamFancy("pmsendname") + "&" + asUrlParamFancy("pmsendrname") + "&" + asUrlParamFancy("pmsendemail") + "&" + asUrlParamFancy("pmsendremail") + "&" + asUrlParamFancy("plid") + "&" + asUrlParamFancy("pmsendmsg") + "&" + asUrlParamFancy("pmsendsubject") + "&" + asUrlParamFancy("pmtitle") + "&" + asUrlParamFancy("pmurl") + "&" + asUrlParamFancy("emailtype");
}


// Get key, value pair formated as url parm string.
function asUrlParam(key, value) {
	return key + "=" + escape(value)
}

// Fancy version where value is looked up based on key value.
function asUrlParamFancy(key) {
	var value = $('#fancy_outer').find('#' + key).val();
	return asUrlParam(key, value);
}

/**
* Trigger fancybox behavior on a.fancy links.
* Usefull after updating a page using ajax with elements that needs to be fancyfied.
*/
function doFancybox() {
	$("a.fancy").fancybox({
		'frameHeight': 193,
		'frameWidth': 456,
		'padding': 8,
		'hideOnContentClick': false,
		'overlayOpacity': 0.8
	});
}

/**
* Register a global variable with the selected pl_id so fancybox dialog can refere to this.
*
* Yes this blows but it is the only way to do it...
*/
var deletePlaylistId = null;
function prepareDeletePlaylist(plId) {
	deletePlaylistId = plId;
}

function clearSearch(s) {
	   if (s.value == 'Søg på kunstner og/eller sang eller album')
	      s.value='';
}

function svalidation() {
    if (document.sform.searchquery.value=='' || document.sform.searchquery.value=='Søg på kunstner og/eller sang eller album')
	    moeAlert('Skriv kunstner, album eller titel i indtastningsfeltet')
	else
     	document.sform.submit();
	return false;
}


/* jcarousel methods */
function attachGenrePickerCarousel() {
	jQuery('#frontpage-mycarousel').jcarousel({
	    visible: 4,
	    scroll: 4,
	    start: 1,
	    size: $('#frontpage-mycarousel li').length,
	    itemLoadCallback: itemLoadCallback,
	    initCallback: initCarousel
	});
}

function findClosestContainsIdNode(node, id) {
	var $currNode = node;
	while(($currNode.length > 0) && ($currNode.children("#"+id).length == 0)) {
		$currNode = $currNode.parent();
	}

	return $currNode;
}

function itemLoadCallback(carousel, state)
{
	/* set index dot to active page */
	var currPage = Math.ceil(carousel.last / carousel.options.visible);
	var $carouselDiv = findClosestContainsIdNode(carousel.container, "carousel-current-slide");
    $('#carousel-current-slide li', $carouselDiv).removeClass("active");
    $('#carousel-current-slide .' + currPage + '-slide', $carouselDiv).addClass("active");
};

function initCarousel(carousel, state)
{
    var numPages = Math.ceil(carousel.options.size / carousel.options.visible);
    var $carouselDiv = findClosestContainsIdNode(carousel.container, "carousel-current-slide");
	/* generate page dots */
	$('#carousel-current-slide', $carouselDiv).html('<ul></ul>');
    for (var a = 1; a <= numPages; a++) {
        $('#carousel-current-slide ul', $carouselDiv).append('<li class="' + a + '-slide"> ');
    }
    $('#carousel-current-slide ul', $carouselDiv).css("width", 14*numPages + "px");
};


/**
* Generate a comma seperated list from a TABLE with id track_list and the TR elements with the id attribute set to the lm id.
*/
function getLmList() {
	var lmIds = [];

	var ids = $('#track_list tr');
	ids.each(function(index) {
		lmIds.push($(this).attr("id"));
	});
	return lmIds.join(",")
}

function delete_cookie( name, path, domain ) {
	document.cookie = name + "=" + ";path=" + path + ";domain=" + domain + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function forceLogout() {
	delete_cookie("SsoSessionData","/",".tdconline.dk");
	delete_cookie("SsoUserData","/",".tdconline.dk");
	window.location.reload();
}

function setUIAutoComplete() {
	$('input[name="searchquery"]').autocomplete({

		source: url + "ajax/uiAutocomplete",
		minLength: 2,
		select: function( event, ui ) {
			window.location=url+"search&searchquery="+ui.item.value;
		}
	})
}

