// JavaScript Document
var check_ad = false;

function cookieManager(){
if(check_ad == false){
	if(!$.cookie("tioTV")){
		 setTvCookie(1);
	}else{
		old_cookie=$.cookie("tioTV");
		param_array = old_cookie.split("&");
		var old_cv = "";

		for(izy=0;izy<param_array.length;izy++){			

			if(param_array[izy].indexOf("cv=") != -1){
				old_cv = param_array[izy].replace("cv=","");
			}
		}
	
		if(isNaN(old_cv) || old_cv<=0){
			setTvCookie(1);
		}else{
			old_cv++;	
			setTvCookie(old_cv);
		}
	}
}
}

function setTvCookieAd(){
			$.ajax({
					   type: "GET",
					   url: "http://www.tio.ch/aa_new_tiotv/ajax_video_ads.asp",
					   data: "type=ad",
					   success: function(msg){
						   /*temp_ad_video = $f().getClip().url;
						   temp_video_array = new Array();
						   temp_video_array = temp_ad_video.split('/');*/
						   check_ad = "sigla";
		   				   $f().getControls().widgets({scrubber: false,playlist: false,play: false}); 
						   $f().play({url: msg, provider: 'tiotv'}); 					   
						   $f().onBeforeFinish(function(){
														if(check_ad=="sigla"){
														 check_ad = false;
		   												 	 //alert(temp_video_array[1]);
															 if(temp_video_array_video == "undefined"){
																playlistPlayNext();
		 												 	 }else{
																  this.play({url: document.getElementById("temp_video").value+".mp4", provider: 'tiotv'}); 
															 }
															 this.getControls().widgets({scrubber: true,play: true}); 
														 }
							})
						   }
					 });	
}

function setTvCookie(cv){
			//modificato omar
			//alert(cv);
			if(cv%5==1){	

			$.ajax({
					   type: "GET",
					   url: "http://www.tio.ch/aa_new_tiotv/ajax_video_ads.asp",
					   data: "type=ad",
					   success: function(msg){
						  // alert(document.getElementById("temp_video").value);
						   temp_msg_array = new Array();
						   temp_msg_array = msg.split(";");
						  // alert(temp_msg_array[0]);
						   count_view_ad(temp_msg_array[2].replace("[RandomNumber]",random_number()));
						   check_ad = true;						   
		   				   $f().getControls().widgets({scrubber: false,play: false}); 
						   $f().play({url: temp_msg_array[0], provider: 'tiotv'}); 
						   document.getElementById('temp_ad_link').value = temp_msg_array[1].replace("[RandomNumber]",random_number())+"";
						   $f().getPlugin("adLayer").show();
						   $f().onBeforeFinish(function(){
														if(check_ad==true){
														 check_ad = false;		   					
														  $f().getPlugin("adLayer").hide();
														 //alert(document.getElementById("temp_video").value);
															 if(document.getElementById("temp_video").value == ""){
																playlistPlayNext();
		 												 	 }else{
															 	 this.play({url: document.getElementById("temp_video").value+".mp4", provider: 'tiotv'}); 
															 }
															 this.getControls().widgets({scrubber: true,play: true}); 
														 }
							})
						   }
					 });
			}		
		var end_date = new Date();
  		end_date.setHours(23,59,59,999)
		var options = { path: '/', expires: end_date };
	    $.cookie("tioTV", 'cv='+cv, options);		
}


function startTvCookie(){			
	/*	 $.ajax({
					   type: "GET",
					   url: "http://www.tio.ch/aa_new_tiotv/ajax_video_ads.asp",
					   data: "type=sigla",
					   success: function(msg){
						   temp_ad_video = $f().getClip().url;
						   temp_video_array = new Array();
						   temp_video_array = temp_ad_video.split('/');	
						   document.getElementById("temp_video").value = temp_video_array[1];				   
						   check_ad = true;
		   				   $f().getControls().widgets({scrubber: false,play: false}); 					   
						   $f().play({url: msg, provider: 'tiotv'}); 					   
						   $f().onBeforeFinish(function(){
														if(check_ad==true){	
															check_ad = "sigla";
															//omar disattivato
															//setTvCookieAd();
														}
														
							})						   

				 		  }
					 });

		*/
														/*if(check_ad==true){
														 check_ad = false;
		   												 this.getControls().widgets({scrubber: true, play: true}); 																 														 this.play({url: temp_video_array[1]+".mp4", provider: 'tiotv'}); 	
								 					     $("#playlist").show();														 
														 }*/
		var end_date = new Date();
  		end_date.setHours(23,59,59,999)
		var options = { path: '/', expires: end_date };
	    $.cookie("tioTV", 'cv=1', options);	
}

function random_number(){
	var today = new Date();
	return Math.round(today.getTime()/1000.0)+Math.floor(Math.random()*1000);
}

function count_stats(id){
	$("#stats_counter").html("<img SRC=\"/aa_pagine_comuni/articolo_stat.asp?idarticolo="+id+"&idtipo=4&rand="+random_number()+"\" border=0 width=0 height=0 />");
}

function count_view_ad(viewpixel){
	$("#stats_counter").html("<img SRC='"+viewpixel+"' border=0 width=0 height=0 />");
}

function openplayer(video_name,id){
		document.getElementById("temp_video").value = video_name;
		if(video_name != ""){
			$("#fms :first").css({display: "block"});		
		if(check_ad == false){
			$f().play({url: video_name+".mp4", provider: 'tiotv'}); 
		}else{
		   				      $f().getControls().widgets({scrubber: false,play: false}); 		
						  	  $f().onBeforeFinish(function(){
												  if(check_ad==true){
														 check_ad = false;
		   												 this.getControls().widgets({scrubber: true, play: true});												
														 this.play({url: document.getElementById("temp_video").value+".mp4", provider: 'tiotv'}); 													 
														 }
							})
		}
	
			$("div.overlay").overlay({effect: 'apple'}).load(); 
			$("#stats_counter").html("<img SRC=\"/aa_pagine_comuni/articolo_stat.asp?idarticolo="+id+"&idtipo=4&rand="+random_number()+"\" border=0 width=0 height=0>");
			$f().hide().stop();

	}else{
		alert("Video Non ancora convertito")	;
	}	

}

function openplaylist(video_name,id){
	if(video_name != ""){	
		if(check_ad == false){
			$f().play({url: video_name+".mp4", provider: 'tiotv'}); 
			$("#stats_counter").html("<img SRC=\"/aa_pagine_comuni/articolo_stat.asp?idarticolo="+id+"&idtipo=4&rand="+random_number()+"\" border=0 width=0 height=0>");
		    cookieManager();
		}	
	}else{
		alert("Video Non ancora convertito")	;
	}
}


function playlistPlayNext(){

	  if(check_ad == false){
	  $f().stop();
	  if(current_video_id > 0){
		  if(current_video_id < 4){
			  current_video_id = current_video_id+1;
				  $("#bg_play_button_1000"+current_video_id).click();
		  }else if(current_video_id == 4){
			  if(currentPlaylist < (video_total-4)){
				  current_video_id = 1;
			  if(currentPlaylist > 15){
				  currentPlaylist = 0;				
				  paginaPlaylist = paginaPlaylist+1;
			  }else{
				  currentPlaylist = Math.floor((currentPlaylist+4)/4)*4;
			  }				
				  $("#video_box_container_move").animate({marginLeft: "-800"}, "slow",function(){$("#playlist").load("/aa_new_tiotv/_ajax_playlist.asp?video="+escape(current_video)+"&lista="+current_lista+"&pag="+paginaPlaylist+"&cpl="+currentPlaylist+"&pos=right", {}, function(){$("#video_box_container_move").animate({marginLeft: "0"}, "slow",function(){$("#bg_play_button_1000"+current_video_id).click();});});});
				  
			  }
		  }
	  }
	}
}

var current_video = "";
var current_video_id = -1;
function getPlayList(){

	if(check_ad == false){
				   temp_ad_video = $f().getClip().url;
				   var temp_video_array = new Array();
				   temp_video_array = temp_ad_video.split('/');
				   current_video = temp_video_array[1];
				   if(paginaPlaylist == -1){
						   paginaPlaylist = current_pagina;
				   }
				   $("#playlist").load("/aa_new_tiotv/_ajax_playlist.asp?video="+escape(current_video)+"&lista="+current_lista+"&pag="+paginaPlaylist, {}, function(){	});
	}
}


var currentPlaylist = 0;
var paginaPlaylist = 1;

function clearPlaylist(){
	paginaPlaylist = 1;	
}

function movePlayList_next(){

	if(currentPlaylist < (video_total-4)){
		if(currentPlaylist > 15){
			currentPlaylist = 0;
			paginaPlaylist = paginaPlaylist+1;
		}else{
			currentPlaylist = Math.floor((currentPlaylist+4)/4)*4;
		}
		$("#video_box_container_move").animate({marginLeft: "-800"}, "slow",function(){changePlaylist("right");});
	}
	
}

function changePlaylist(position){
		$("#playlist").load("/aa_new_tiotv/_ajax_playlist.asp?video="+escape(current_video)+"&lista="+current_lista+"&pag="+paginaPlaylist+"&cpl="+currentPlaylist+"&pos="+position, {}, function(){	$("#video_box_container_move").animate({marginLeft: "0"}, "slow"); });	
		
}

function movePlayList_prev(){
	if(paginaPlaylist == 1 && currentPlaylist < 4){
	}else{
		if(currentPlaylist<4){
			currentPlaylist = 16,
			paginaPlaylist = paginaPlaylist--;
		}else{				
			currentPlaylist = Math.floor((currentPlaylist-4)/4)*4;		
		}
		$("#video_box_container_move").animate({marginLeft: "800"}, "slow",function(){changePlaylist("left");})
	}
}


$f("fms", "/aa_new_tiotv/flowplayer/flowplayer.commercial-3.1.5.swf", { 	
	key:  "#@651f5c18b7664ad40ce",
	logo: {
		  url: '/aa_new_tiotv/img/watermark.png',
		  fullscreenOnly: false,
		  bottom: 50,
		  right: 140,
		  opacity: 0.5, 
		  displayTime: 0,
		  linkUrl: "http://www.tiotv.ch"
	},
   	clip: { 
	       url: '', 
   	   	   scaling: 'fit',
        // configure clip to use influxis as our provider, it uses our rtmp plugin 
		   provider: 'tiotv',
		   wmode: 'transparent',
		   autoPlay: true
	 }, 
	onLoad: function() {  
		this.hide();
	},
	onFinish: function(){
		playlistPlayNext();
	},	
	play: {  
		replayLabel: 'Guarda di nuovo'
	},
	canvas: { 
        backgroundColor:'#000000', 
        backgroundGradient: 'none' 
    },onStart: function(){	
				   getPlayList();
			
	},
    // streaming plugins are configured under the plugins node 
    plugins: {  
        // here is our rtpm plugin configuration 
        tiotv: { 
            url: '/aa_new_tiotv/flowplayer/flowplayer.rtmp-3.1.3.swf',  
			wmode: 'transparent',
			backgroundColor: "#FFFFFF",
            // netConnectionUrl defines where the streams are found 
            netConnectionUrl: 'rtmpt://91.208.130.109:80/tiotv/' ,
     	    urlResolvers: 'bwcheck'

        },
		controls:{
		    url: '/aa_new_tiotv/flowplayer/flowplayer.controls-3.1.5.swf'
		},
		bwcheck: { 
            url: '/aa_new_tiotv/flowplayer/flowplayer.bwcheck-3.1.3.swf', 
			
            serverType: 'wowza',  
            // Use this connection for bandwidth detection 
            netConnectionUrl: 'rtmpt://91.208.130.109:80/bwcheck/', 
			connectTimeout: 5000,			
			defaultBitrate: 450,
            // available bitrates for file names 
			bitrates: [300,450,750], 
            // use a customized urlPattern for file names 
            urlPattern: 'mp4:{1}/{0}', 		
			dynamic: true
 			/*,onConnect: function(host){
				 var el = document.getElementById("rtmpInfo"); 
				el.innerHTML = "Your Host is connecting: " +host+ ""; 
			}, 		
			onConnectFailed: function(host){
				 var el = document.getElementById("rtmpInfo"); 
				el.innerHTML = "Your Host is failed: " +host+ ""; 
			},
            // this method is called when the bandwidth check is done 
            onBwDone: function(url, chosenBitrate, bitrate) { 
                var el = document.getElementById("rtmpInfo"); 
                el.innerHTML = "Your speed is: " +bitrate+ "<br />Video file served: " +url; 
            } ,
			onStreamSwitch: function(bitrate, newUrl, oldUrl) { 
                var el = document.getElementById("rtmpInfo"); 
                el.innerHTML = "Switched to stream: " + newUrl + "<br />current bitrate: " + bitrate; 
          }  */
        },	 
		adLayer: { 
          	  // the only required property 
	            url: '/aa_new_tiotv/flowplayer/flowplayer.content-3.1.0.swf',
				width: '100%',
				height: '90%',
				backgroundColor: 'none', 
				opacity: 0, 
				onClick: function() { 
		            window.open(document.getElementById('temp_ad_link').value+"",'_new','');
					
    		    }  
    	    } 
    } 
});
mac_check = 0;
$("div.overlay").overlay({  
    // use the Apple effect for overlay 
    effect: 'apple',          
    // 1. start expose effect when overlaying begins 
    expose: '#000000',  
    // 2. when overlay is loaded, we reposition and resize the player on top of it 
    onLoad: function() {  
        // get handle to the embed element 
        var embed = $("#fms :first");  
        /* and reposition / resize it. you will propably have to tweak 
            these when placing this on your site */ 
			
        var el = this.getContent(); 
        var height = el.height();  
		if($.browser.msie){
			if($.browser.version == "8.0"){
				embed.css({ 
					// size 
					width:parseInt(el.width()) -22, 
					height:parseInt(height) -22,  
					// position 
					left: parseInt(el.css("left")) + 3, 
					top: parseInt(el.css("top")) + 1012
					
				});   			
			}else{
				embed.css({ 
					// size 
					width:parseInt(el.width()) -22, 
					height:parseInt(height) -22,  
					// position 
					left: parseInt(el.css("left")) - 321, 
					top: parseInt(el.css("top")) + 1012
					
				});   			
				
			}
		}else if($.browser.opera){
		  embed.css({ 
			  visibility: "visible",
			  // size 
			  width:parseInt(el.width()) -22, 
			  height:parseInt(height) -22,  
			  // position 
			  left: parseInt(el.css("left")) + 3, 
			  top: parseInt(el.css("top")) +4
			  
		  });   
			
	 	}else{
		  embed.css({ 
			  visibility: "visible",
			  // size 
			  width:parseInt(el.width()) -22, 
			  height:parseInt(height) -22,  
			  // position 
			  left: parseInt(el.css("left")) + 3, 
			  top: parseInt(el.css("top")) - 48
			  
		  });   
		}

		//var el_playlist = $("#playlist");  
		//el_playlist.css({
	   //        top: parseInt(el.css("top")) + 400 
		//});
	    $f().getPlugin("adLayer").hide();
		$f().play(); 
		overley_status = "open";
		cookieManager();	
		
		//OLD MAC CHECK
		/*if(mac_check == 0 && $.client.os == "Mac"){
			//setTimeout(check_mac_adobe(this),2000);
		}else if(mac_check == 1){
			$f().stop(); 
			mac_check = 2
		}*/
    }, 
    onClose: function() { 
    	    // 1. return our player to its original size/position 
	        $("#fms :first").css({top: null, left: null, width: null, height: null}); 
			$f().stop().hide(); 
			clearPlaylist();
			overley_status = "closed";

    } 
});
	overley_status = "closed";

function check_mac_adobe(overlay){
	if(mac_check == 0 && $.client.os == "Mac"){

		overlay.close();

		mac_check = 1;
		setTimeout("$('div.overlay').overlay({effect: 'apple'}).load(); ",2000)
	}	
	
}