var hasRotated = false;
var lastPlayedId = false;
var displayDate = false;
var comId = 0;
var comTitle = '';
var comInfo = '';
var comEndPlakat = 0;
var endplakatId = 0;
var hasCountedSp = 0;
var countedUrls = 0;
var sponsorCounted = 0;
var sponsorUrl = '';
var sponsorId = 0;


//var playerUrl = "http://mediamaker.dk/dagbladet/mediamaker_big.php";

function openNewsAlertWin() {
	window.location='maillist.php?sid='+sid;
}

function setInfo(_clip) {
	if (_clip.titel==null) 
		return null;
		
	//postpend dato in front of titel if it should be shown
	if (displayDate) {
		dispTitel = _clip.oprettetDen + " " + _clip.titel; 
	} else {
		dispTitel = _clip.titel;
	}

	//short titel Length so it won't break
	var titelLength = 60;
	if (dispTitel.length>titelLength) {
		dispTitel = dispTitel.substring(0, titelLength-3) + '...';
	}

	var infoHead = document.getElementById('infoHead');
	
	var header = document.createTextNode(dispTitel);
	infoHead.appendChild(header);
	
	var infoCont = document.getElementById('infoBody');
	var lineBreak = document.createElement("br");
	//[br] skal erstattes med html linieskift



// istedet er følgende indsat

	var txt = document.createTextNode(_clip.info);
	infoCont.appendChild(txt);

}

function clearInfo() {
	
	var head = document.getElementById('infoHead');
	
	while ( head.hasChildNodes() ) {
		head.removeChild(head.firstChild);
	}
	
	var body = document.getElementById('infoBody');
	
	while (body.hasChildNodes()) {
		body.removeChild(body.firstChild);
	}
	
}

function setTitle(_clip) {
	window.status=_clip.titel;
	var titelCont = document.getElementById('titelCont');
	var header = document.createTextNode(_clip.titel);
	 titelCont.appendChild(header);
}

function clearTitle() {

	var titel = document.getElementById('titelCont');
	while (titel.hasChildNodes() ) {
		titel.removeChild(titel.firstChild);
	}
	
}

function countShowSponsor(sponsorurl) {

	html = '<iframe style="display:none" src="counter.php?loc=countShowSponsor&url=' + sponsorurl + '&sid=' + sid + '&req_uri=' + req_uri + '"></iframe>';

	document.getElementById('counterDiv').innerHTML=html;
}

function countShow(_clip) {
	//alert("TEST"+_clip.id);
	hasCountedSp = _clip.type;
	//alert('counter.php?loc=countShow&id=' + _clip.id + '&sid=' + sid + '&req_uri=' + req_uri + '');
	html = '<iframe style="display:none;" src="counter.php?loc=countShow&id=' + _clip.id + '&sid=' + sid + '&req_uri=' + req_uri + '"></iframe>';
	
	document.getElementById('counterDiv').innerHTML=html;
	
}


function openTipWin(clip_id) {

	popUp = window.open('./tip.php?action=tip&id='+ clip_id, "Tip","width=450,height=524,resizable=0,toolbar=0,scrollbars=0,location=0,status=0,menubar=0");
	popUp.focus();
	return popUp;
}

function openThumbWin(clip_id) {
	popUp = window.open('thumbnailChooser.php?clipID='+ clip_id, "ThumbnailChooser","width=468,height=90,resizable=0,toolbar=0,scrollbars=1,location=0,status=0,menubar=0");
	popUp.focus();
	return popUp;
}

function openKlagWin(clip_id) {
	popUp = window.open('tip.php?action=klag&id='+ clip_id, "Tip","width=450,height=524,resizable=0,toolbar=0,scrollbars=0,location=0,status=0,menubar=0");
	popUp.focus();
	return popUp;
}


function openTipWin_gammel() {
	if (!lastPlayedId) {
		alert('Du skal vælge et klip før du kan tippe en ven');
	} else {
	popUp = window.open('tip.php?id='+ lastPlayedId, "Tip","width=450,height=560,resizable=0,toolbar=0,scrollbars=0,location=0,status=0,menubar=0");
	popUp.focus();
	return popUp;
		//window.location='tip.php?id='+ lastPlayedId;
	}
}

function openRelatedClips() {
	popUp = window.open('relatedclips.php', "relatedclips","width=900,height=760,resizable=0,toolbar=0,scrollbars=0,location=0,status=0,menubar=0");
	popUp.focus();
	return popUp;
}

function runsCommercial() {
	
	try {
		var currentUrl = document.player1.currentMedia.sourceUrl;
	} catch (Exception) { return false; }; //netscape skal altid returnere false da den ikke kan se om een reklame kører .
	
	/*
	if(clip.type == 'live')
	{
		if (clip.url != currentUrl.substr(33)) {
			return true;
		}
	return false;		
	}		
	else if (clip.url != currentUrl) {
		return true;
	}
	return false;
	*/
	
	//alert(clip.url+'\n'+currentUrl);
	/*
	if (clip.url != currentUrl) {
	return true;
	}
	*/
	//alert( "Current: "+currentUrl.substr(24) + " Assumed: "+clip.url );
	   
	if(clip.type == 'live')
	{
		if (clip.url != currentUrl) {
			return true;
		}
		
		return false;		
	}		
	else if(clip.url != currentUrl.substr(27))
	{
		return true;
	}
	return false;	
}

var isSetComTitle = 0;
function infoPolle() {

	var cooptest1 = document.getElementById('testdiv').innerHTML;

	if(document.player1 != null)
		document.getElementById('testdiv').innerHTML = document.player1.currentMedia.sourceUrl;
	
	var cooptest2 = document.getElementById('testdiv').innerHTML;
	
	if(cooptest1 != cooptest2 && document.player1 != null)
	{
		if(countedUrls>0)
		{
		
			countShowSponsor(document.player1.currentMedia.sourceUrl);
			sponsorCounted++;
			
		}
	
	countedUrls++;				
	}

	if(runsCommercial()==true) 
	{

		var c = clipObj(comId, comTitle, ' ', comInfo, true, ' ', 'com', comEndPlakat);
		if (isSetComTitle == 0) 
		{
			//setTitle(c);
			//setInfo(c);
			isSetComTitle = 1;
			countShow(c);
			document.getElementById("playerCont").style.cursor = "hand";
		}
		setTimeout("infoPolle()",300);
		return;
	}

	/*
	clearInfo();
	clearTitle();
	if(clip.id) {

		setInfo(clip);
		setTitle(clip);
		setAnbefal();
		//lastPlayedId til newsAlert
		lastPlayedId = clip.id;
	}
	*/
}

function setAnbefal() {
	var anbefalCont = document.getElementById('tipLnk');
	anbefalCont.innerHTML = "<INPUT TYPE=\"image\" src=\"./images/icons/anbefal.gif\" onmouseover=\"this.src='./images/icons/anbefal-over.gif'; \" 	onmouseout=\"this.src='./images/icons/anbefal.gif'\"  title=\"Anbefal dette klip\" id=\"tipLnk\" class=\"lnk\" OnClick=\"openTipWin();\" Onfocus=\"this.blur()\">";
}

function isNull(a) 
 {
      return typeof a == 'object' && !a;
 }

function countClip() {
	if (!runsCommercial()) {
		if(hasCountedSp != clip.type) {
		countShow(clip);
		}
	} else {
		setTimeout("countClip()",2000);
	}
}


function clipObj(_id, _titel, _url, _info, _isCommercial, _oprettetDen, _type, _endplakat) {

	obj = new Object;
	
	obj.id = _id;
	obj.titel = _titel;
	obj.url = _url;
	obj.isCommercial = _isCommercial;
	obj.oprettetDen = _oprettetDen;
	obj.info = _info;
	obj.type = _type;
	obj.endplakat = _endplakat;
	
	return obj;
}

function openfaq() {
	window.open("http://www.fvn.no/video/article493681.ece","FAQ","resizable=1,toolbar=1,scrollbars=1,location=1,status=1,menubar=");
}

function openXstream() {
	window.open("http://www.xstream.dk","xstraemFaq","height=600, width=800, scrollbars=yes");
}

function openMediamakerBackendWmv( _width, _height, _player) {

	
	popUp = window.open(_player, "popUp", "top=0,left=" + ((screen.availWidth/2) - (_width / 2)) + ",width="+_width+",height="+_height+",resizable=0,toolbar=0,scrollbars=0,location=0,status=0,menubar=0");
	popUp.focus();
	return popUp;
	
}

function openMediamakerFlash( _width, _height, _parameter) {

	if (_parameter==undefined) {
		_parameter="";
	}
	
	popUp = window.open("players/mediamaker_flash.php"+_parameter, "popUpFlash", "top=0,left=" + ((screen.availWidth/2) - (_width / 2)) + ",width="+_width+",height="+_height+",resizable=0,toolbar=0,scrollbars=0,location=0,status=0,menubar=0");
	popUp.focus();
	return popUp;
	
}

function sureDelete(_id,_charName) {
	if(confirm("Er du sikker på du vil slette " + _charName +" !")) {
	 	window.location='?sLoc=del&id=' + _id;
	} else {
 		return false;
	}
}

// this function is used to empty the message sent confirmation

function emptySentConfirmation() {
	
	document.getElementById("email_sent").style.visibility = "hidden";
}


function disableKey( _key) {
	if (	window.event ) {
		if (window.event.keyCode==_key) {
			window.event.keyCode=0;
			window.event.returnValue=false;
		}
	}
}

function cutTofit( _size, object ) {
	if (object.value.length >_size) {
		object.value=object.value.substring(0,_size);
	}
}

function blinkIt() {
 if (!document.all) return;
 else {
   for(i=0;i<document.all.tags('blink').length;i++){
      s=document.all.tags('blink')[i];
      s.style.visibility=(s.style.visibility=='visible')?'hidden':'visible';
   }
 }
}

function checkClick(pos) {
	posx=pos.x;
	posy=pos.y;
	
	
	var player = document.getElementById('playerCont');
	var xStart = player.getAttribute('offsetLeft');
	var yStart = player.getAttribute('offsetTop');
	var width  = player.getAttribute('offsetWidth');
	var height = player.getAttribute('offsetHeight');
	
	
	
	if (runsCommercial() && posx > xStart && posx < xStart+width && posy > yStart && posy < yStart + height )
		videoClick();
	
}

function openWhenComRuns() {
	
	if (runsCommercial())
		videoClick();
}

function mouseEventHandler(mEvent) {
	obj = new Object;
	posx = 0;
	posy = 0;
	
	
  // Internet Explorer
  if (mEvent.srcElement)
  {
    
		posx = mEvent.clientX + document.body.scrollLeft;
		posy = mEvent.clientY + document.body.scrollTop;
   
    
  }
  // Netscape and Firefox
  else if (mEvent.target)
  {
		posx = mEvent.pageX;
		posy = mEvent.pageY;   
  	
  }
  obj.x =  posx;
  obj.y =  posy;
  
  //checkClick(obj);
}

var hasCounted = 0;
	
function videoClick() {
	
	
	
	//if (runsCommercial()) {
		if (!isPlaying()) {	
			return;
		}
		

		// we check the url being played and confirm whether we have this URL and then fetch the link and increment the hits
		
		var currentUrl = document.player1.currentMedia.sourceUrl;
		
		// get the link based on this Url
		recordID = fetchLinkAndId(currentUrl);
	
		if(recordID != -1) { // check if the no of hits is less than the max allowed hits <not needed now as logic clarified again :)>
			
			//if(DATA[recordID][4] > 0) {
			
				//if(DATA[recordID][3] < DATA[recordID][4]) {
				
					talAnnonce(DATA[recordID][0]); // pass the commercial id to increment the hits on it
					
					url = DATA[recordID][2];
					
					var annonceLink = ((url.indexOf('http://') != -1) || (url.indexOf('https://') != -1)) ? (url) : ('http://' + url);
				
					var _width = window.screen.width - 10;
					var _height = window.screen.height - 202;
					var startX = 0;
					var startY = 0;
					
					newwindow=window.open(annonceLink,'_blank','height='+ _height +',width='+ _width +',left='+ startX +',top='+ startY +',resizable=yes,scrollbars=yes,toolbar=yes,status=yes,menubar=yes,resizable=yes,location=yes');
					window.focus();
				
				//}
				
			//} else if(DATA[recordID][4] == 0) {
				
					/*talAnnonce(DATA[recordID][0]); // pass the commercial id to increment the hits on it
					
					url = DATA[recordID][2];
					
					var annonceLink = ((url.indexOf('http://') != -1) || (url.indexOf('https://') != -1)) ? (url) : ('http://' + url);
				
					var _width = window.screen.width - 10;
					var _height = window.screen.height - 202;
					var startX = 0;
					var startY = 0;
					
					newwindow=window.open(annonceLink,'_blank','height='+ _height +',width='+ _width +',left='+ startX +',top='+ startY +',resizable=yes,scrollbars=yes,toolbar=yes,status=yes,menubar=yes,resizable=yes,location=yes');
					window.focus();*/
				
				
			//}
		}		
		
		
		
/*	
		if (hasCounted == 0) 
		{
			talAnnonce();
			hasCounted = 1;
		}
*/
		
		//talAnnonce()
		// visAnnonce(); -> disabled as we do the thing here :)
	//}
		
}


// this function fetches the record unique ID which has the id and link based on the url of the clip

function fetchLinkAndId(URL) {
	
	var recordID = -1;
	
	for(i = 0; i < DATA.length; i++) {
		
		if(URL.indexOf(DATA[i][1]) != -1) { // this is the record :)
			
			recordID = i;			
			break;
		
		}
	}
	
	return recordID;
	
}


function talAnnonce()  {
	
	// tjekker om der er et sponsor ID
	if(sponsor_id.innerHTML != "") {
		comId = sponsor_id.innerHTML;
	}
	
	if(comId>0) 
	{
		
		html = '<iframe style="display:none" src="counter.php?loc=countClick&id=' + comId + '&sid=' + sid + '&req_uri=' + req_uri + '"></iframe>';
		document.getElementById('counterDiv').innerHTML=html;
	}
}

function isPlaying() {
	if (document.player1.playState==-1)
		return false;
	return true;
}

// if the current clip is of type radio
// hide player and show a picture

function switchBackgroundImage() {
	
	if ( !runsCommercial() ) {		
		hidePlayer();
		scaleScreener();
		showImage();
		centerImage();
		
	} else {
		showPlayer();
		hideImage();		
	}
	
	if (screener != null ) {
		setTimeout("switchBackgroundImage()",500);
	} 
}

function centerImage() {
	
	//center the image using padding
	var widthOffset = (document.player1.width - screenerWidth) / 2;
	var heightOffset = (document.player1.height - screenerHeight) / 2;
	
	
	canvas = document.getElementById('screenerImg');
	
	if (canvas.height<540) {
		document.getElementById('screenerImg').style.top= heightOffset;
		document.getElementById('screenerImg').style.left = widthOffset;
		
	}
}

function showImage() {
	
	canvas = document.getElementById('screenerImg');
	canvas.src = screener.src;
	canvas.width= screenerWidth;
	canvas.height= screenerHeight;	
}

function hideImage() {
	canvas = document.getElementById('screenerImg');
	canvas.src = screener.src;
	canvas.width= 0;
	canvas.height= 0;	
}

function hidePlayer() {
	
	if (document.player1.style.visibility != 'hidden' ) {
		document.player1.style.visibility='hidden';
	}
}


function showPlayer() {
	
	if (player1.style.visibility != '' ) {
		player1.style.visibility='';
	}
}

function restorePlayer() {
	if (document.player1.width == 0 ) {
		document.player1.width = playerWidth;
		document.player1.height = playerHeight;
	}
}

// hvis billedet er mindre en 320*240, rezise billedet op til 320*240 uden at skalere det.
// hvis billedet er større en 320*240,  rezise billedet op til 512*384 uden at skalere det.
// standarg jpg skal dog altid skalers til max størrlese.


function scaleScreener() {
	
	if ( screenerWidth<=320 && screenerHeight<=240 && screener.src.indexOf('standard.jpg')==-1) {
		
		wScale = 320/screenerWidth;
		hScale = 240/screenerHeight;
		
	} else {
		wScale = 512/screenerWidth;
		hScale = 384/screenerHeight;
		
	}
	if (wScale < hScale) {
		scale	= wScale;
	} else {
		scale	= hScale;
	}
	screenerWidth = screenerWidth*scale;
	screenerHeight = screenerHeight*scale;
	
}

function detectBrowser() {
  if ( strpos($_SERVER['HTTP_USER_AGENT'], 'Gecko') ) {
    if ( strpos($_SERVER['HTTP_USER_AGENT'], 'Netscape') ) {
      $browser = 'Netscape (Gecko/Netscape)';
    } else if ( strpos($_SERVER['HTTP_USER_AGENT'], 'Firefox') )   {
      $browser = 'Mozilla Firefox (Gecko/Firefox)';
    } else {
      $browser = 'Mozilla (Gecko/Mozilla)';
    }
  } else if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') ) {
    if ( strpos($_SERVER['HTTP_USER_AGENT'], 'Opera') )  {
      $browser = 'Opera (MSIE/Opera/Compatible)';
    } else {
      $browser = 'Internet Explorer (MSIE/Compatible)';
    }
  } else {
    $browser = 'Other browsers';
  }
  return $browser;
} //end func detect browser

function clearTnBorders() {
	for (i=0,n=document.images.length;i<n;i++){
		if (document.images[i].className == "thumb_current" || document.images[i].className == "thumb"){
			document.images[i].style.border = "2px solid white";
		}
	}
}

function toggleSplashDiv(id,flagit) {
	if (flagit=="1"){
		if (document.layers)
			document.layers[''+id+''].visibility = "show"
		else if (document.all)
			document.all[''+id+''].style.visibility = "visible"
		else if (document.getElementById)
			document.getElementById(''+id+'').style.visibility = "visible"
	} else	if (flagit=="0"){
		if (document.layers)
			document.layers[''+id+''].visibility = "hide"
		else if (document.all)
			document.all[''+id+''].style.visibility = "hidden"
		else if (document.getElementById)
			document.getElementById(''+id+'').style.visibility = "hidden"
	}
}

// this function pops up a window

function openWindowInMyFace(pageURL,width,height) {
	
	var left = (screen.width/2)-(width/2);
	var top = (screen.height/2)-(height/2);
	
	var targetWin = window.open ('showinfo.php?title=iframe&from=mediaplayer&text='+pageURL, "mywindow", 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+width+', height='+height+', top='+top+', left='+left);	

}

// this function pops up a window 

function openURLInMyFace(pageURL,width,height) {

	var left = (screen.width/2)-(width/2);
	var top = (screen.height/2)-(height/2);

	var targetWin = window.open ('showinfo.php?title=url&text='+pageURL, "mywindow", 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+width+', height='+height+', top='+top+', left='+left);	
	
	
}

// this function opens a window to send an email to a friend 

function openSendToFriendWindow(pageURL,width,height, clip_id, title) {

	var left = (screen.width/2)-(width/2);
	var top = (screen.height/2)-(height/2);

	var targetWin = window.open(pageURL+"?clip_id="+clip_id+"&title="+title, "friendwindow", 'toolbar=no, location=no, status=no, menubar=no, scrollbars=no, resizable=no, width='+width+', height='+height+', top='+top+', left='+left);	
	//window.open(pageURL, "friend window", 'width='+width+', height='+height+', top='+top+', left='+left);	
	//window.open("emailfriend.php", "friendwindow", 'width='+width+', height='+height+', top='+top+', left='+left);	
	
	
}

// this is the function used to send an email to a friend

function sendtofriend() {
	
		// we check if all the necessary fields have been filled
		
		var error = '';
		
		if(document.getElementById("your_email").value == "")
			error+= 'Skriv inn din e-post\n';
		if(document.getElementById("receiver_email").value == "")
			error+= 'Oppgi mottaker e-post\n';
		if(document.getElementById("message").value == "")
			error+= 'Oppgi Melding';

			
		if(error.length > 0) {
			
			alert("Vennligst oppgi følgende informasjon:: \n\n"+error);
			
			return false;
			
		}
		
		var sender_email = document.getElementById("your_email").value;
		var receiver_email = document.getElementById("receiver_email").value;
		var message = document.getElementById("message").value;
	
		var clip_id = document.getElementById("clip_id").value;
		var title = document.getElementById("title").value;
		
		http_request = '';

			if (window.XMLHttpRequest) { // Mozilla, Safari, ...

			    http_request = new XMLHttpRequest();

			} else if (window.ActiveXObject) { // IE

			    http_request = new ActiveXObject("Microsoft.XMLHTTP");

			}
// callback

	http_request.onreadystatechange = function() {

	if (http_request.readyState == 4) {

            if (http_request.status == 200){
			
            	//alert(http_request.responseText);
            	
				response = http_request.responseXML;
				
				if(response.getElementsByTagName("result")[0].firstChild.data == 1) {
					
					// we display the email sent confirmation
					
					document.getElementById("email_sent").style.visibility = "visible";
					
				} 		
				
			
				}
				
			}

		}

	http_request.open('POST', 'sendemailtofriend.php', true);

	http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	//alert(document.getElementById('catt').value)
	
	http_request.send('sender_email='+sender_email+'&receiver_email='+receiver_email+'&clip_id='+clip_id+'&title='+title+'&message='+message+'&choice=sendtofriend');
		
	return false;
	
	
}

function sendtofvn() {
	
		// we check if all the necessary fields have been filled
		var error = '';
	 
		if(document.getElementById("your_email").value == "")
			error+= 'Skriv inn din e-post\n';
		if(document.getElementById("your_number").value == "")
			error+= 'Skriv inn dit telefonnummer\n';
		if(document.getElementById("message").value == "")
			error+= 'Oppgi Melding';
		
		if(error.length > 0) {
			
			alert("Vennligst oppgi følgende informasjon:: \n\n"+error);
			
			return false;
			
		}

		var sender_email = document.getElementById("your_email").value;
		
		var sender_number = document.getElementById("your_number").value;
		var message = document.getElementById("message").value;
	
		var clip_id = document.getElementById("clip_id").value;
		
		http_request = '';

			if (window.XMLHttpRequest) { // Mozilla, Safari, ...

			    http_request = new XMLHttpRequest();

			} else if (window.ActiveXObject) { // IE

			    http_request = new ActiveXObject("Microsoft.XMLHTTP");

			}
// callback

	http_request.onreadystatechange = function() {

	if (http_request.readyState == 4) {

            if (http_request.status == 200){
			
            	//alert(http_request.responseText);
            	
				response = http_request.responseXML;
				
				if(response.getElementsByTagName("result")[0].firstChild.data == 1) {
					
					// we display the email sent confirmation
					
					
					document.getElementById("email_sent").style.visibility = "visible";
					
				} 		
				
			
				}
				
			}

		}

	http_request.open('POST', 'sendemailtofriend.php', true);

	http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	//alert(document.getElementById('catt').value)
	
	http_request.send('sender_email='+sender_email+'&sender_number='+sender_number+'&clip_id='+clip_id+'&message='+message+'&choice=sendtofvn');
		
	return false;

	
}

// this is the snippet that responds to myspace link click 

function openMySpace(T, C, U, L) {
	
	var targetUrl = "http://www.myspace.com/Modules/PostTo/Pages/?" + "t=" + encodeURIComponent(T)+ "&c=" + encodeURIComponent(C) + "&u=" + encodeURIComponent(U) + "&l=" + L;
	
	window.open(targetUrl);	
	
}




