var player;
var currentPosition = 0;
var host = document.location.host; //jQuery.url.attr("host");

var broadcast_abort = false;
var abort_counter = 0;
var aborted;

// cookie kezelő függvények
	
function setCookie(name, value, expire ){
	
	var host_array = host.split(".");
	if (host_array.length>2){
		c_host="";
		for (i=1;i<host_array.length;i++) 
		{
			c_host+="."+host_array[i];
		}
	} else {
		c_host="."+host;
	}
	
	document.cookie = name + "=" + escape(value) + "; path=/ ; domain="+ c_host + ((expire==null ? "":("; expires=" + expire.toGMTString())));
}

function getCookie(c_name)
{
  if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    { 
    c_start=c_start + c_name.length+1; 
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    } 
  }
return "";

}

function checkCookie(cookie_text)
{
	var c_cookie=getCookie(cookie_text);
	
	if (c_cookie!=null && c_cookie!="")
	{
		return true;
	}
	else 
	{
		return false 
	}
}


// this deletes the cookie when called
function DeleteCookie( name, path, domain ) {
	document.cookie = name + "=" +
	( ( path ) ? ";path=" + path : "") +
	( ( domain ) ? ";domain=" + domain : "" ) +
	";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}


function getExpireDate(){

	var expires = new Date();

	expires.setTime((new Date().getTime() + 1000*60*60*24*365));

	return expires;
}


var quality;
	 
var connectionSpeed = 0;
 // The variable where connection speed information
 // will be stored when it is available.

function drawCSImageTag( fileLocation, fileSize, imgTagProperties ) {
 // This function draws the image tag required to run this process.
 // It needs to be passed:
 // 1. (String) The location of the file to be loaded
 // 2. (Integer) The size of the image file in bytes
 // 3. (String) The tag properties to be included in the <img> tag
 // Place a call to this function inside the <body> of your file
 // in place of a static <img> tag.
 
 	/*
 	 * Ideiglenesen a régi . nélküli cookie-k törléséhez
 	 */
	DeleteCookie("MediaQuality","/");
	if (!checkCookie('MediaQuality')) {
		//alert("nincs süti");
		 start = (new Date()).getTime();
		 // Record Start time of <img> load.
		
		 loc = fileLocation + '?t=' + escape(start);
		 // Append the Start time to the image url
		 // to ensure the image is not in disk cache.
		
		$("#bandwidth").html('<img height=0 src="' + loc + '" ' + imgTagProperties + ' onload="connectionSpeed=computeConnectionSpeed(' + start + ',' + fileSize + ');">');
		 // Write out the <img> tag.
		
		//return;
	//} else {	//nem kell, majd a ChangeQuality felolvassa és értelmezi (pl. yt-nál nincs sml)
		//alert("van süti");
		//quality = getCookie('MediaQuality');
		
	}
}
function connectionType(speed) {
 // This function returns a string describing the connection type
 // being used by the user-agent hitting the page.
 /*SLOW_MODEM = 15;
 FAST_MODEM = 57;
 ISDN_MODEM = 120;*/
 SLOW_ADSL = 256;
 AVG_ADSL = 768;
 FAST_ADSL = 2048;
 // These are constants which define the base speeds
 // for a number of different connections. They are
 // measured in units of kbps.
 var calc_quality;
 if (speed) {
	 if (speed < SLOW_ADSL) {
	 	calc_quality = "sml";
	 } else if (speed < AVG_ADSL) {
	 	calc_quality = "med";
	 } else if (speed < FAST_ADSL) {
	 	calc_quality = "lrg";
	 } else {
	 	calc_quality = "lrg";
	 }
 } else {
 	calc_quality = "undefined";
 }
 setCookie("MediaQuality", calc_quality, getExpireDate());
}

function computeConnectionSpeed( start, fileSize ) {
 // This function returns the speed in kbps of the user's connection,
 // based upon the loading of a single image. It is called via onload
 // by the image drawn by drawCSImageTag() and is not meant to be called
 // in any other way. You shouldn't ever need to call it explicitly.

 end = (new Date()).getTime();
 
 connectSpeed = (Math.floor((((fileSize * 8) / ((end - start) / 1000)) / 1024) * 10) / 10);
 connectionType(connectSpeed);
 //return connectSpeed;
}

/*
 * Ha van extra_link paraméter és az true, akkor megjelenítünk egy popup ablakot,
 * hogy legyen vip tag.
 */

function changeQuality(c_quality, extra_link) {
	//alert('changeQuality_y:'+c_quality+', extra_link:'+extra_link+'.');
	if (extra_link==undefined || extra_link==true) {
		if (c_quality!=null && c_quality!="") {
			setCookie("MediaQuality", c_quality, getExpireDate());
			
			var fullscr;
			if (c_quality=="lrg") {
				fullscr = true;
			} else {
				fullscr = false;
			}
			
			//player.mediaquality = c_quality;
			currentPositionSave = currentPosition;
			
			currentFile = player.getConfig().file;
			
			q_start=currentFile.indexOf(quality);
			 if (q_start==-1)
	   			 { 
					q_start= currentFile.length-7;
	   			 } 
			
			q_end= q_start+3; 
			
			nextFile_1=currentFile.substring(0,q_start);
			nextFile_2=currentFile.substring(q_end,currentFile.length);
			
			NextFile=nextFile_1+c_quality+nextFile_2;
			//alert(NextFile); 
			player.sendEvent('LOAD',NextFile);
			player.sendEvent('PLAY',true);
			player.sendEvent('SEEK', currentPositionSave);
			
		} else {
			c_quality = getCookie("MediaQuality"); 
			if (c_quality =="") {
				c_quality = "med";
			}
		}
		
		quality = c_quality;
		selectQuality(quality);
	} else {
		tb_show(null, '/ajax.php?l=message&message=subscript',false);
	}
}


function changeQuality_y(c_quality, extra_link) {
	//alert('changeQuality_y:'+c_quality+', extra_link:'+extra_link+', quality:'+quality+', player:'+player);
	if(player !== undefined) {
		if (extra_link==undefined || extra_link==true) {
			if (c_quality!=null && c_quality!="" && c_quality!="undefined") {
				setCookie("MediaQuality", c_quality, getExpireDate());
				changeVideo = false;
				currentFile = '' + player.getConfig().file;
				//alert('changeQuality_y currentFile:'+currentFile);
				if (quality!=c_quality) {		 
				 	if (c_quality=="lrg") {
							NextFile=currentFile+'&fmt=18';
							changeVideo = true;
					} else if (c_quality=="med") {
			 			if (currentFile.indexOf('&fmt=18')==-1) {
							NextFile=currentFile;
							changeVideo = true;		//csak amíg nem működik az fmt beállítás
				 		} else {
				 			NextFile=currentFile.substring(0, currentFile.length-7);
				 			changeVideo = true;
				 		}
					}
				}
				  	
				if (changeVideo) {
					quality = c_quality;
					var obj = {file:NextFile,type:"video"};
					player.sendEvent('LOAD',obj);
					player.sendEvent('PLAY',true);
				}
				
			} else {
				c_quality = getCookie("MediaQuality"); 
				if (c_quality =="" || c_quality =="sml") {
					c_quality = "med";
				}
			}
			//alert('changeQuality_y eredmeny:'+c_quality);
			quality = c_quality;
			selectQuality(quality);
		} else {
			tb_show(null, '/ajax.php?l=message&message=subscript',false);
		}
	}
}

var percent;
var counter = 2;
function bufferTracker(obj) { 
	//alert('the buffer percentage is: '+obj.percentage+' id : '+obj.id+' client : '+obj.client+' version : '+obj.version);
	percent = obj.percentage;
	
	if (percent<1) {
		counter= counter-1;
		if (counter == 0) {
			if (!checkCookie('WarningQuality')) {
				setCookie('WarningQuality', '', (8*60*60))
				tb_show(null, '/ajax.php?l=message&message=warningquality',false)
				//alert("Ha szaggatásmentesen szeretnéd megnézni, válassz kissebb méretet.");
			}
		}
	}
};

function loadedTracker(obj) { 
	//alert('the loaded size is: '+obj.loaded+' offset : '+obj.offset+' id : '+obj.id+' client : '+obj.client+' version :'+obj.version); 
};

function errorTracker(obj) { 
	var actplayer = document.getElementById(obj.id);
	//alert("ERROR\n message:"+obj.message+"\n id:"+obj.id+"\n client:"+obj.client+"\n version:"+obj.version+"\n author:"+actplayer.getConfig().author);
	$.ajax({
		   type: "POST",
		   url: "/flashplayer.php",
		   data: "state=ERROR&description="+actplayer.getConfig().description+"&message="+obj.message+"&objid="+obj.id+"&objclient="+obj.client+"&objversion="+obj.version,
		   success: function(msg){
		     if(msg == 'stream_not_found' && actplayer.getConfig().author == 'link/youtube')
			     alert( youtube_error_text );   
			 else if(msg == 'stream_not_found' && actplayer.getConfig().author == 'link/tv2')
			     alert( tv2_error_text ); 
			 else if(msg == 'stream_not_found' && actplayer.getConfig().author == 'link/pornhub')
			     alert( partner_error_text );
			 else if(msg == 'stream_not_found')
			     alert( partner_error_text );
			 else if(msg == 'retry_connection') {
			 			    
			    aborted = setTimeout( function(){broadcast_abort = true; abort_counter=abort_counter+1; actplayer.sendEvent("PLAY","true");   } , 10000);
			    
			    if (abort_counter>120) {
			    	alert( "Gond van az adással, próbáld meg később" );
			    	aborted = clearTimeout(aborted);
			    	broadcast_abort = false;
			     	abort_counter = 0;
			    }
			 }
		   }
	});
};
/**
 * A data részben tudunk átadni paramétereket a php-nak
 * A msg részt a php adja vissza
 */
function stateTracker(obj) {
	var actplayer = document.getElementById(obj.id);
	//alert('the new state is:'+obj.newstate+'\n the old state is:'+obj.oldstate);
	if (obj.newstate=='PLAYING') {
		//alert('the new state is:'+obj.newstate+'\n the old state is:'+obj.oldstate+', client:'+obj.client+', version:'+obj.version+', video author:'+actplayer.getConfig().author+', video description:'+actplayer.getConfig().description+', duration:'+actplayer.getConfig().duration);
		if(actplayer.getConfig().author.substr(0,5) == 'link/') {
			$.ajax({
			   type: "POST",
			   url: "/flashplayer.php",
			   data: "state=PLAYING&description="+actplayer.getConfig().description,
			   success: function(msg){
			     //alert( "PLAYING visszatérési érték: " + msg );
			     aborted = clearTimeout(aborted);
			     broadcast_abort = false;
			     abort_counter = 0;
			   }
			 });
		}
	} else if (obj.newstate=='COMPLETED') {
		//alert('the new state is:'+obj.newstate+'\n the old state is:'+obj.oldstate+', client:'+obj.client+', version:'+obj.version+', video author:'+actplayer.getConfig().author+', video description:'+actplayer.getConfig().description+', duration:'+actplayer.getConfig().duration);
		//alert('COMPLETED state, duration:'+currentPosition);
		if(actplayer.getConfig().duration == 0 && currentPosition > 1) {
			$.ajax({
			   type: "POST",
			   url: "/flashplayer.php",
			   data: "state=COMPLETED&description="+actplayer.getConfig().description+"&duration="+currentPosition,
			   success: function(msg){
			     //alert( "COMPLETED visszatérési érték: " + msg );
			   }
			 });			
		}
	}
};

function playTracker(obj) { 
	alert('PLAY CONTROL');
	if (obj.state) {
		alert('the state is: '+obj.state+' id : '+obj.id+' client : '+obj.client+' version :'+obj.version);
	} 
};

function timeTracker(obj) { 
	//alert('the error message is: '+obj.message+' id : '+obj.id+' client : '+obj.client+' version :'+obj.version);
	currentPosition = obj.position;
};

var playerReadyRun = false;
function playerReady(obj) {
	
	var id = obj['id'];
	var version = obj['version'];
	var client = obj['client'];
	
	playerReadyRun = true;
		
	player = document.getElementById(id);
	//alert('the videoplayer '+id+' has been instantiated\n version : '+version+'\n client : '+client+'\n obj:'+player);
			
	player.addModelListener("BUFFER","bufferTracker");
	player.addModelListener("ERROR","errorTracker");
	player.addModelListener("LOADED","loadedTracker");
	player.addModelListener("TIME", "timeTracker");
	
	/*
	 * Nem tudom melyik lesz jó a nézettségszámláláshoz
	 * elvileg mindkettő
	 */
	player.addModelListener("STATE", "stateTracker");
	//player.addControllerListener("PLAY","playTracker");
	
	//$('#VideoSize ul li').removeClass("selected");
	//$('#VideoSize ul #'+quality).addClass("selected");
	
	//alert('actual playback quality:'+quality);
	//alert('actual swf file:'+player.getConfig().file);

	AdPlayerReady(obj);
	
}

function selectQuality(quality) {
	//alert("selectquality : "+quality);
	$('#VideoSize ul li').removeClass("selected");
	$('#VideoSize ul #'+quality).addClass("selected");
}