var $j = jQuery;

var videomediasetBaseUrl = 'http://www.video.mediaset.it';
var customerBaseUrl = 'http://servizi.mediaset.it';
var _registrationPageUrl = customerBaseUrl + '/Customer/Servizi/front-end/portal_videomediaset/portalHome.jsp?portal=videomediaset&page=registration&srvc=105';
var loginPageUrl = customerBaseUrl + '/Customer/Servizi/front-end/portal_videomediaset/portalHome.jsp?portal=videomediaset&target=' + escape(document.location.href);

var divstrip = "quattro";
var _video = null;

function getVideoProperties(id, brand, _box, _state){
     var tipo = $j('p.full-ep', _box).html() == null ? 'clip' : 'fep';
	 var state = _state != undefined ? _state : $j('h2 > a', _box).attr('state');
	 var durata = $j('p.durata', _box).html();
	 if(durata == null){
		$j('p', _box).each(function(_p) {	
          var _phtml = 	$j(this).html();	
		  if(_phtml != null && _phtml.indexOf('Durata: ') > 0){
			durata = _phtml.substring(_phtml.indexOf('Durata: ')+8);
		  }
		});
	 } else {
		durata = durata.substring(8);
	 }
	 var url = ($j('h2 > a', _box).attr('href') == undefined || $j('h2 > a', _box).attr('href') == '') ?  $j('h2 > a', _box).attr('url') : $j('h2 > a', _box).attr('href');	
	 if(url.indexOf("?")>0){
		url = url.substring(0,url.indexOf("?"));
	 } else if (url.indexOf("#")>0){
		url = url.substring(0,url.indexOf("#"));	
	 }
	 var img = $j('div.cont-img > a > img', _box).attr('src');	 
	 if(img.indexOf("http")>=0){	 
		img = img.substring(img.indexOf("/images"));
	 }		
	 
	 var videoObj = new Object();
		 videoObj.GUID = id;
		 videoObj.SECTION = brand;		 
		 videoObj.Documentname = url;
		 videoObj.TITOLO = $j('h2 > a', _box).html();
		 videoObj.THUMBNAIL = img;	 
		 videoObj.DURATA =durata;
		 videoObj.TIPO = tipo;
		 videoObj.PROGRAM = ($j('p.brandfull > a', _box).html() == null || $j('p.brandfull > a', _box).html() == '') ? $j('p.brand > a', _box).html() : $j('p.brandfull > a', _box).html();
		 videoObj.STATE = state;	    
	return videoObj;
}

function closeBoxPlaylist(){
	if($j('#boxPlaylist').length > 0){
		$j('#fascia-playlist').stop(true);
		$j('#boxPlaylist').remove();
	}
}

//begin showTooltipLogin()
function showTooltipLogin(left, top) {
_dbg("showTooltipLogin", [left, top], "init");

	if((left == null && top == null) || ( $j('myPlaylistBox').length > 0)){
		document.location.href="/playlist";
	} else{
		 var _tt = $j('<div id="tooltip" class="tooltip">' +
			 '<div id="logintooltip">' +
			 '<p><a href="' + loginPageUrl + '">Accedi</a> per aggiungerlo a una playlist</p>' +								  
			 '</div>' +
			 '<div class="arrow"></div></div>')
			.hide()
			.appendTo('#body2')
			.mouseleave(function() {
				hideTooltip('showTooltipLogin mouseleave')
			})
			.css({ left: (left + 108) + 'px', top: (top) + 'px' })
			.fadeIn(50);
	}
							
}
//end showTooltipLogin()

//begin showMyTooltipAdd()
function showMyTooltipAdd(_obj) {
 _dbg("showMyTooltipAdd", [], "init");
 
    var _box = $j(_obj);	 
	var _of = $j(_obj).offset();
	
	$j.getJSON(customerBaseUrl + '/Customer/checkLoggedExtended.jsp?callback=?', function(data) {
		if(data.user) {
			try {
				$j.each(data.user, function(j, uservalue) {
					var username = uservalue.username;
					var email = uservalue.email;
					var myplaylistpath = uservalue.id;	
					var myplaylistArray = uservalue.playlists;					
					
					if(username=='') {
					   // utente non loggato					   		
					   showTooltipLogin(_of.left, _of.top);
					} else {
						// utente loggato
						 _video = _box;						 
						var _ttdiv = ('<div id="tooltip" class="tooltip">' +
									  '<div id="addtooltip">' +
									  '<h4 class="crea"><a href="#" onClick="createMyPlaylist(\''+myplaylistpath+'\');return false;" id ="create-playlist" >Crea nuova playlist</a></h4>' +	
									  '<input type="text" id="input-playlist" value="" style="display:none;"/>');
						if(myplaylistArray.length > 0){
							_ttdiv += ('<h4 class="aggiungi">Aggiungi a </h4><div id="myplaylist-container">'); 	
							$j.each(myplaylistArray, function(i, mp) {							
								var myplaylistid = mp.id;
								var myplaylisttitle = mp.title;	
								_ttdiv +=  ('<p><a href="#" onClick="addVideoMyPlaylist(\''+myplaylistpath+'\',\''+myplaylistid+'\',\''+myplaylisttitle+'\');return false;">'+ myplaylisttitle+'</a></p>');					  
							});  
							_ttdiv +=	( '</div>');
						}
						 _ttdiv +=	( '</div><div class="arrow"></div></div>');
									  
						var _tt = $j(_ttdiv)
							.hide()							
							.mouseleave(function() {
								hideTooltip('showMyTooltipAdd mouseleave')
							 })
							.appendTo('#body2')
							.css({ left: (_of.left + 108) + 'px', top: (_of.top + 0) + 'px' })
							.fadeIn(50);	
						
					}

				});
			} catch(er) {			    
				alert('[showMyTooltipAdd] error : '+er);
			}
		} else
			alert('[showMyTooltipAdd] no data found');
	});
}
//end showMyTooltipAdd()

//begin addBoxMyPlaylist()
function addBoxMyPlaylist(myplaylistpath, myplaylistid, myplaylisttitle, lastitem) {
 _dbg("addBoxMyPlaylist", [myplaylistpath, myplaylistid, myplaylisttitle, lastitem], "init");
   if($j('#myPlaylistBox div.box-container').length > 0){
    var myplaylisttitleSEO = titleSEO(myplaylisttitle);
	var _url = videomediasetBaseUrl +'/myplaylist/'+myplaylistpath+"/"+myplaylistid+'/'+myplaylisttitleSEO+'.html'
	var body=escape('Ciao, guarda questa playlist! \n\n');
	body += escape(_url);
	body += escape('\n\nPuoi rivedere tutti i video e le dirette dei programmi e TG Mediaset su http://www.video.mediaset.it !');
	var mail = 'mailto:?subject='+myplaylisttitle+'&body='+body;
	var _boxplaylist = $j("<div id=\"box-playlist|"+myplaylistpath+"|"+myplaylistid+"\" class=\"boxplaylist\">"+
	"<div id=\"div-rename-playlist"+myplaylistid+"\" style=\"display:none\" class=\"renameplaylist\"><input type=\"text\" id=\"input-rename-playlist\" value=\"\"/><a id=\"ok-rename-playlist\" href=\"#\">ok</a></div>"+
	"<div class=\"etichetta-sub\"><h4>" +myplaylisttitle + " </h4>"+	
	'<div id="toolbarshare"><div class="addthis_toolbox addthis_default_style " id="toolbox-'+myplaylistpath+"-"+myplaylistid+'" addthis:url="'+_url+'" addthis:title="'+myplaylisttitle +'"><a href="'+ mail +'"><span class="at300bs at15nc at15t_email"></span></a><a class="addthis_button_facebook"></a><a class="addthis_button_twitter"></a><a class="addthis_button_compact"></a><a class="addthis_button_google_plusone" g:plusone:count="false"></a></div></div>'+
	"<div class=\"page-container-option\"><a class=\"delete-myplaylist\" href=\"#\">Elimina</a>" +
	"<a class=\"rename-myplaylist\" href=\"#\">Rinomina</a>"+
	"<a class=\"modify-myplaylist\" href=\"#\">Modifica</a>"+
	"</div></div><div class=\"box-contenuti-video-" + divstrip + "\"><div id=\"myplaylist|"+myplaylistpath+"|"+myplaylistid+"\" class=\"box-contenuti-video\"><div  class=\"scroll\">&nbsp;</div></div></div>" + 	
	"<div class=\"etichetta-sub  noline\"><div class=\"page-container\"><p>Pagina</p><ul  class=\"pagg-sub\"><li class=\"prev\"><a href=\"#\">&laquo;</a></li><li class=\"curr\"><input type=\"text\" name=\"textfield\" id=\"textfield\"> di <a href=\"#\"></a></li><li  class=\"next\"><a href=\"#\">&raquo;</a></li></ul></div></div></div>");
	
	_boxplaylist.appendTo('#myPlaylistBox div.box-container');
		
	
	var _box = $j("div.box-contenuti-video-" + divstrip + " > div.box-contenuti-video", _boxplaylist);
	showFasciaVideoPlaylist(_boxplaylist, _box, 1, SCROLL_MODE_ABS, false);
	if(lastitem){
		//chiamo funzione per inizializzare bottoni addthis
		loadAddthis();
	}
  }
}
//end addBoxMyPlaylist()

//begin reloadBoxMyPlaylist()
function reloadBoxMyPlaylist(myplaylistpath, myplaylistid, mode) {
 _dbg("reloadBoxMyPlaylist", [myplaylistpath, myplaylistid], "init");
	var _boxplaylist = $j('#box-playlist\\|'+myplaylistpath+'\\|'+myplaylistid);
	var _box = null;
	if(_boxplaylist.length > 0){
		if($j("div.box-contenuti-video-" + divstrip + " > div.box-contenuti-video", _boxplaylist).length > 0 ){
			_box = $j("div.box-contenuti-video-" + divstrip + " > div.box-contenuti-video", _boxplaylist);
			showFasciaVideoPlaylist(_boxplaylist, _box, 1, SCROLL_MODE_ABS, false);
		}else{
			_box = $j("div.box-contenuti-video-all > div.box-contenuti-video", _boxplaylist);
			if(mode == 'modify'){
				_box.parent().attr('class', 'box-contenuti-video-'+ divstrip );
				_box.parent().css({ height: '210px'});
				showFasciaVideoPlaylist(_boxplaylist, _box, 1, SCROLL_MODE_ABS, false);
			}else{
				modifyMyPlaylist(_box);
			}

		}   
	}

}
//end reloadBoxMyPlaylist()

//begin showFasciaMyPlaylist()
function showFasciaMyPlaylist() {
 _dbg("showFasciaMyPlaylist", [], "init");  
	$j.getJSON(customerBaseUrl + '/Customer/checkLoggedExtended.jsp?callback=?', function(data) {
		if(data.user) {
			try {
				$j.each(data.user, function(j, uservalue) {
					var username = uservalue.username;
					var email = uservalue.email;
					var myplaylistpath = uservalue.id;	
                    var myplaylistArray = uservalue.playlists;																				
					
					//gestione menu mediaset
					if(username=='') {
						$j('#myPlaylistBox').append('<div id="boxNoReg"><h2>Puoi creare le tue playlist personali solo se sei registrato.</h2><h4 id="registrati"><a href="' + _registrationPageUrl + '" target="_blank" title="Registrati">REGISTRATI</a></h4><h4 id="login"><a href="' + loginPageUrl + '" title="Login">LOGIN</a></h4></div>');						
					} else {
						
						if(myplaylistpath == '' || myplaylistArray.length == 0){
							$j('#myPlaylistBox').append("<div class=\"etichetta\"><h3>Le mie playlist</h3></div><div class=\"box-container\">"+
							 '<div class="box-contenuti-video" id="myplaylist||"><div class="scroll" style="left: 0px;"><div class="cont-video-scroll"><p class="novideo">Nessuna playlist personale</p></div></div></div>'+
							 "</div>");
						}else{												
							$j("<div class=\"etichetta\"><h3>Le mie playlist</h3></div><div class=\"box-container\"></div>").appendTo('#myPlaylistBox');
							myplaylistArray.each(function(mp, i) {									
								addBoxMyPlaylist(myplaylistpath, mp.id, mp.title, (i == (myplaylistArray.length-1)) );										
						    });
						}
					}
				});					
			} catch(er) {			    
				alert('[showFasciaMyPlaylist] error : '+er);
			}
		} else
			alert('[showFasciaMyPlaylist] no data found');
	});
}
//end showFasciaMyPlaylist()

//begin showFasciaMyPlaylistShared()
function showFasciaMyPlaylistShared() {
 _dbg("showFasciaMyPlaylistShared", [mpuser, mpid ], "init");
    if(mpuser != '' &&  mpid != ''){	
		$j("<div class=\"etichetta\"><h3>Le mie playlist</h3></div><div class=\"box-container\"></div>").appendTo('#myPlaylistSharedBox');			
		if($j('#myPlaylistSharedBox div.box-container').length > 0){
			var _boxplaylist = $j("<div id=\"box-playlist|"+mpuser+"|"+mpid+"\" class=\"boxplaylist\">"+
			
			"<div class=\"etichetta-sub\"><h4></h4><div class=\"page-container-option\">"+	
			"</div></div><div class=\"box-contenuti-video-all\"><div id=\"myplaylist|"+mpuser+"|"+mpid+"\" class=\"box-contenuti-video\"><div  class=\"scroll\"><div class=\"cont-video-scroll\"></div></div></div></div></div>");
			
			_boxplaylist.appendTo('#myPlaylistSharedBox div.box-container');
			
			var _box = $j("div.box-contenuti-video-all > div.box-contenuti-video", _boxplaylist);
			showMyPlaylistShared(_box);
		  }
	}
}
//end showFasciaMyPlaylistShared()

//begin showMyPlaylistShared()
 //_obj: container videoPlaylist
 function showMyPlaylistShared(_obj, retry) {  
    closeBoxPlaylist();
    var _box = $j(_obj);
	
	if(!(_box.parent().hasClass('box-contenuti-video-all'))){		
		_box.parent().attr('class', 'box-contenuti-video-all');
	}

    var _id = _box.attr('id');
    var _tmp = _id.split("|");
	var _url ="";
	 
	if(_tmp.length == 3){
		// playlist es /playlist/bacino/6.sjson
		 var _t = new Date().getTime();
		_url = "/"+_tmp[0]+"/" + _tmp[1] + "/" + _tmp[2] + ".sxml?" + _t;
	} 	
	
	_dbg("showMyPlaylistShared", [_id, _url, retry], "init");

    var _own = $j("div.scroll", _box);
    var _cont = null;
    var _html = "";
	var _playlistName = "";
	
	
	//nascondo div con paginazione
	$j("div.etichetta-sub > div.page-container", _box.parent().parent()).hide();

    _cont = $j("div.cont-video-scroll:eq(0)", _own); //get container to fill --> the first
	_cont.parent().css('left', '0px');
    _cont.html('<img class="loader" src="/res/img/video_loader.gif">'); //draw loading image    	

    //load xml file ad draw result
    $j.ajax({
      type: "GET",
      url: _url,
      dataType: "xml", 
      async: false,
      success: function(result) {
		 //alert(result);	
		 _pages = $j(result).find("result").attr("totPage");
		 _playlistName = $j(result).find("title").text();
		 _dbg("showMyPlaylistShared", [_id, _url, _playlistName], "success loading xml file pages: "+_pages);
 		  if(_pages == undefined) {
		   if(retry != 1){
				showMyPlaylistShared(_obj, 1);
				return;
			} else {
				_pages = 0;
			}
		  }    
		  
        $j('div.etichetta-sub > h4', _box.parent().parent()).html(_playlistName);
		
        if (_pages == 0) {         
          _own.html('<div class="cont-video-scroll"><p class="novideo">Nessun video nella playlist</p></div>');
          return;
        } 

        _cont.empty();	
        _cont.css({height: (_pages * 210) + 'px'});	
        		
		_box.css({ height: ((_pages * 210) +20) + 'px'}); // setto altezza _box	

		$j("record", result).each(function(i) {
          var _video_id = $j("GUID", this).text();
          var _video_name_brand = $j("SECTION", this).text();
          var _video_desc_brand = $j("PROGRAM", this).text();
          var _video_type = $j("TIPO", this).text();
          var _video_thumbnail = $j("THUMBNAIL", this).text();
          var _video_url = $j("URL", this).text();
          var _video_title = $j("TITOLO", this).text().replace(/\\/g, "");
          var _video_duration = $j("DURATA", this).text().substring(0, 8);
          var _video_date = $j("DATA", this).text();
		  var _video_state = $j("STATE", this).text();		      

          if (_video_thumbnail == "") {
             _video_thumbnail = "/res/img/138_nothumb.jpg";
          } else if (_video_thumbnail.indexOf("/images/138") != 0){
             _video_thumbnail = "/images/138" + _video_thumbnail;
          }
		  
		  if(_video_state != '' && _video_state == 'unpublish'){  // controllo se video ha stato non più disponibile
				_video_thumbnail = "/res/img/138_unpublish.jpg";
		  }

          if (_video_url == ".html" || _video_url == "" ) {
             _video_url = "#";
          }

					
		  var sbrandLower = _video_desc_brand.toLowerCase();
		  var sbrandEscape = escape(sbrandLower);
		  var strbrand="\'"+"LINK=vid-"+sbrandEscape+"\'";
          
          if(_tmp.length == 3){
            _html = '<div id="cont-video|' + _video_name_brand + '|' + _video_id + '" class="cont-video">' +
            '<div class="cont-img"><a><img id="img-video|' + _video_name_brand + '|' + _video_id + '" title="" alt="" src="' + _video_thumbnail + '"/></a></div>' +
            '<p class="brandfull" onclick="javascript:ssxl('+ strbrand +')"><a href="/programma/'+_video_name_brand+'/'+_video_desc_brand.replace(' ', '-').toLowerCase()+'.html" rel="nofollow">'+_video_desc_brand+'</a></p>'+
            '<h2><a url="' + _video_url + '">' + _video_title + '</a></h2>' +
             ((_video_type == 'clip') ? '<p class="durata">Durata: ' + _video_duration + '</p>' : '<p class="full-ep">Puntata intera</p>') +
            ((_video_type == 'fep') ? '<p class="durata">Durata: ' + _video_duration + '</p>' : '') +
            '</div>';
            } 
            
          var _item = $j(_html);
          var param = '';
		  var _vt = _video_type; /*(_video_type == '0') ? 'clip' : 'fep';*/		
		  
		  initTooltip(_item);
		  
		   _item.click(function() {   
			      _curpos =  i;
			      initPlaylist(_tmp[0],_tmp[1],_tmp[2],_playlistName,_video_id,_video_name_brand,_video_desc_brand,_video_url,_vt,(_curpos +1));
          })

          $j('img', _item).bind('load', function () {
            $j(this).unbind('load').fadeIn();
          }).bind('error', function () {
            $j(this).unbind('error').attr('src', IMAGE_UNAVAIL).show();
          }).hide();
          		       									 
		  // aggiungo video
          _item.appendTo(_cont);
		 
        });		
      },
      error: function() {
        _dbg("showMyPlaylistShared", [_id, _url_pos], "error loading xml file");
        _own.html('<div class="cont-video-scroll"><p class="novideo">Nessun video nella Playlist</p></div>');
      }
    }); 
 }
 //end showMyPlaylistShared()

//begin reloadFasciaPlaylist()
function reloadFasciaPlaylist(myplaylistpath, myplaylistid, myplaylisttitle){
	_dbg("reloadFasciaPlaylist", [myplaylistpath, myplaylistid, myplaylisttitle], "init");
	 var _t = new Date().getTime();
	var _url = "/myplaylist/" + myplaylistpath + "/" + myplaylistid + ".sxml?"+_t;	
	var _data = createPlaylistData('myplaylist',myplaylistpath,myplaylistid,myplaylisttitle,'','','','','p1','');	
	var _dataArrayreload = _data.split(",");	
    var nameMyPlaylist = "myplaylist-" + myplaylistpath + "-" + myplaylistid;		
	// nel caso l'utente ha la customertoolbar chiusa ... la apro	
	if($j.cookie("BOTTOMBARSTATUS") != null && $j.cookie("BOTTOMBARSTATUS") == "CLOSE"){	
		$j('#boxPlaylist').show();
		$j('#customerToolbar, #boxPlaylist').animate({width: '100%'}, 1500);
		$j('#barButton').removeClass('close');
		$j('#barButton').addClass('open');
		$j.cookie('BOTTOMBARSTATUS', 'OPEN', {expires: null, path: '/'});
	}
	drawFasciaPlaylist(_url, '', _dataArrayreload, nameMyPlaylist);	
}
//end reloadFasciaPlaylist()

//begin drawMenuMyPlaylist()
function drawMenuMyPlaylist(_playlisttype){
	_dbg("drawMenuMyPlaylist", [_playlisttype], "init");
	  $j.getJSON(customerBaseUrl + '/Customer/checkLoggedExtended.jsp?callback=?', function(data) {
		if(data.user) {
			try {
				$j.each(data.user, function(j, uservalue) {
					var username = uservalue.username;
					var email = uservalue.email;
					var myplaylistpath = uservalue.id;	
                    var myplaylistArray = uservalue.playlists;																				
					//gestione playlistTitle
					if(username!='' && myplaylistpath != '' && myplaylistArray.length > 0) {								
						var _html = $j('#playlistTitle').html();	
						var _myplaylist = '<li class="title"><h4>Le mie playlist</h4></li>';
                        if(_html.toLowerCase().indexOf('<h4>Le mie playlist</h4>'.toLowerCase())<0){													
							myplaylistArray.each(function(mp) {								
								var _li = '';							
								var _actualpArray = (new RegExp("\\$p=([A-Za-z0-9!\_\-]+)($|&|\\$)").exec(_href)[1]).split('-');
								if(_playlisttype == 'personale' && _actualpArray.size() == 3 && mp.id == _actualpArray[2]){
									_li = '<li class="active">'+namePlaylistEdit+'</li>';
								} else {
									_li = '<li><a onclick="initMyPlaylist(\''+myplaylistpath+'\',\''+mp.id+'\',\''+mp.title+'\');">' + mp.title +'</a></li>'
								}						
								_myplaylist += _li;
							});
							_myplaylist += '<li>&#160;</li>';
							$j('#playlistTitle').html(_myplaylist + _html);
					    }
						$j('#playlistTitle').show();
					}

					});
				} catch(er) {			    
					alert('Error checkLogged : '+er);
				}
			} /*else
				alert('Impossibile caricare la barra');
				*/
		});
}
//end drawMenuMyPlaylist()		  
		  
//begin createMyPlaylist()
function createMyPlaylist(myplaylistpath) {
	closeBoxPlaylist();
	 if (_video != null) { 
		_dbg("createMyPlaylist", [myplaylistpath], "init");
		
		var _box = $j(_video);
		var _id = _box.attr('id');
		var _tmp = _id.split('|');
		var newplaylistid = ''; //valore restituito dal server.
	
		//$j('#create-playlist').hide();		
		      
		$j('#input-playlist').bind('keypress', function(e) {
			if(e.keyCode==13){
				  //chiamata serverside per crate playlist				  
				  var v = getVideoProperties(_tmp[2], _tmp[1], _box, 'publish');
				  var t = $j(this).val();				  
				  //title, description, videoId, videoInfo					  
				  $j.getJSON(customerBaseUrl+"/Customer/videoMediaset/playlist/newPlaylist.jsp?callback=?", { title: t , videoId: _tmp[2], videoInfo: v  },				  
					 function(data) {					  
						if(data.playlist) {
							try {
								$j.each(data.playlist, function(j, playlistvalue) {
									if(playlistvalue.error == '0'){										
										newplaylistid = playlistvalue.id;
										// disegno fascia playlist solo se non sono già in playlist
										_p = new RegExp("\\$p=([A-Za-z0-9!\_\-]+)($|&|\\$)").exec(_href);
										_notplaylist = (_p == null || (_p[1]).indexOf('playlist-') == -1);	
										if(($j('#boxPlaylist').length == 0 || _notplaylist) && newplaylistid != ''){											 
											reloadFasciaPlaylist(myplaylistpath, newplaylistid, t);												
										} 
										// ricarico div le mie playlist se sono in pagina playlist
										if($j('#myPlaylistBox').length > 0){											
										    $j('#myPlaylistBox').empty();
											showFasciaMyPlaylist();												
										}
									} else if(playlistvalue.error == '-400'){
										//utente non loggato
										 showTooltipLogin(_box.offset().left, _box.offset().top);
									} else{
									    alert('Si è verificato un errore ' + playlistvalue.errordescription);
									}
								});																

								} catch(er) {			    
								alert('[createMyPlaylist] error : '+er);
							}
						} else
							alert('[createMyPlaylist] no data found');					   					  
					 }
				   );
				hideTooltip('createMyPlaylist');   				  				  
			}
	    });
		$j('#input-playlist').show().focus();		
	}
}

//begin addVideoMyPlaylist()
function addVideoMyPlaylist(myplaylistpath, myplaylistid, myplaylisttitle) {
  closeBoxPlaylist();
  if (_video != null) { 
	_dbg("addVideoMyPlaylist", [myplaylistpath, myplaylistid, myplaylisttitle], "init");
	
	var _box = $j(_video);
	var _id = _box.attr('id');
	var _tmp = _id.split('|');
		
	 //chiamata serverside per append video
	  var v = getVideoProperties(_tmp[2], _tmp[1], _box, 'publish');					  
	  //title, description, videoId, videoInfo					  
	  $j.getJSON(customerBaseUrl+"/Customer/videoMediaset/playlist/addVideo.jsp?callback=?", { playlistId: myplaylistid, videoId: _tmp[2], videoInfo: v  },				  
		 function(data) {					  
			if(data.playlist) {
				try {
					$j.each(data.playlist, function(j, playlistvalue) {
						if(playlistvalue.error == '0'){				
                            // disegno fascia playlist solo se non sono già in playlist						
							_p = new RegExp("\\$p=([A-Za-z0-9!\_\-]+)($|&|\\$)").exec(_href);
							_notplaylist = (_p == null || (_p[1]).indexOf('playlist-') == -1);	
							if(($j('#boxPlaylist').length == 0 || _notplaylist) && myplaylistid != ''){	
								var _time = setTimeout(
									function() { reloadFasciaPlaylist(myplaylistpath,myplaylistid,myplaylisttitle); }, 
									50);														
							} 							
							// ricarico div della mia playlist se sono in pagina playlist
							if($j('#myPlaylistBox').length > 0){
								reloadBoxMyPlaylist(myplaylistpath, myplaylistid, 'add');
							}							
							// ricarico div le mie playlist, sono in pagina playlist
							/*	if($j('#myPlaylistBox').length > 0){
									$j('#myPlaylistBox').empty();
									showFasciaMyPlaylist();
								}*/
						} else if(playlistvalue.error == '-400'){
							//utente non loggato
							 showTooltipLogin(_box.offset().left, _box.offset().top);
						} else {
							alert('Si è verificato un errore ' + playlistvalue.errordescription);
						}
					});
					} catch(er) {			    
					alert('[addVideoMyPlaylist] error : '+er);
				}
			} else{
				alert('[addVideoMyPlaylist] no data found');
			}
			hideTooltip('addVideoMyPlaylist');
		 });
 
  } 
}  
//end addVideoMyPlaylist()

//begin delVideoMyPlaylist()
function delVideoMyPlaylist(_obj) {
	closeBoxPlaylist();
 _dbg("delVideoMyPlaylist", [], "init");
 
    var _box = $j(_obj);	
	var _of = $j(_obj).offset();
	var _id = _box.attr('id');
	var _tmp = _id.split("|");
	
	var _mpobj = _obj.parent().parent().parent();
	var _mpid = _mpobj.attr('id');
	var _mptmp = _mpid.split("|");
	
	// calcolo index del video cancellato
	var _index = -1;
	if(_mpobj.parent().hasClass('box-contenuti-video-all')){
	 // caso save --> indice è reale
	 _index = _box.index();
	}else{
	 // caso paginazione --> indice relatico alla pagina
		_pg = $j('#textfield\\|myplaylist\\|'+_mptmp[1]+'\\|'+_mptmp[2]).val();
		if(_pg != undefined){
			_index = ((Number(_pg) -1) * 4) + _box.index();
		}
	}
	
	_dbg("delVideoMyPlaylist", [_index], "remove");
	
	if(_index > -1){
	    var vArray = [];
	    var _t = new Date().getTime();
		_url = "/"+_mptmp[0]+"/" + _mptmp[1] + "/" + _mptmp[2] + ".sxml?"+_t;
		 $j.ajax({
		  type: "GET",
		  url: _url,
		  dataType: "xml",
		  async: false,
			  success: function(result) {				
				$j("record", result).each(function(i, itemVideo) {
					if(i != _index){
					   var _video_id = $j("GUID", itemVideo).text();
					    vArray.push(_video_id);
					}
				});

			  },
			  error: function() {
				_dbg("delVideoMyPlaylist", [_id, _url], "error loading xml file");			
			  }
		 }); 
	}
	
	//salvo modifica
	saveMyPlaylist(_mpobj, 'delvideo', vArray);
}  
//end delVideoMyPlaylist()

 //begin modifyMyPlaylist()
 //_obj: container videoPlaylist
 function modifyMyPlaylist(_obj, retry) {  
    closeBoxPlaylist();
    var _box = $j(_obj);	

    var _id = _box.attr('id');
    var _tmp = _id.split("|");
	var _url ="";
	 
	if(_tmp.length == 3){		
		 var _t = new Date().getTime();
		_url = "/"+_tmp[0]+"/" + _tmp[1] + "/" + _tmp[2] + ".sxml?" + _t;
	} 	
	
	_dbg("modifyMyPlaylist", [_id, _url, retry], "init");

    var _own = $j("div.scroll", _box);
    var _cont = null;
    var _html = "";
	var _playlistName = $j('div.etichetta-sub > h4', _box.parent().parent()).html();
	
	
	//nascondo div con paginazione
	$j("div.etichetta-sub > div.page-container", _box.parent().parent()).hide();

    _cont = $j("div.cont-video-scroll:eq(0)", _own); //get container to fill --> the first
	_cont.parent().css('left', '0px');
    _cont.html('<img class="loader" src="/res/img/video_loader.gif">'); //draw loading image    	

    //load xml file ad draw result
    $j.ajax({
      type: "GET",
      url: _url,
      dataType: "xml",
      async: false,
      success: function(result) {
		 //alert(result);	
		 _pages = $j(result).find("result").attr("totPage");
		 _dbg("modifyMyPlaylist", [_id, _url_pos], "success loading xml file pages: "+_pages);
 		  if(_pages == undefined) {
		   if(retry != 1){
				modifyMyPlaylist(_obj, 1);
				return;
			} else {
				_pages = 0;
			}
		  }    

        if (_pages == 0) {         
          _own.html('<div class="cont-video-scroll"><p class="novideo">Nessun video nella playlist</p></div>');
          return;
        } 

        _cont.empty();	
        _cont.css({height: (_pages * 210) + 'px'});	
        _cont.sortable({
			cursor: 'move',
			opacity: 0.4
		});
		_cont.disableSelection();
		        
		
		
		if(!(_box.parent().hasClass('box-contenuti-video-all'))){		
			_box.parent().attr('class', 'box-contenuti-video-all');
			_box.parent().css({ height: (_pages * 210) + 'px'});
		}
		
		_box.css({ height: (_pages * 210) + 'px'}); // setto altezza _box	

		$j("record", result).each(function(i) {
          var _video_id = $j("GUID", this).text();
          var _video_name_brand = $j("SECTION", this).text();
          var _video_desc_brand = $j("PROGRAM", this).text();
          var _video_type = $j("TIPO", this).text();
          var _video_thumbnail = $j("THUMBNAIL", this).text();
          var _video_url = $j("URL", this).text();
          var _video_title = $j("TITOLO", this).text().replace(/\\/g, "");
          var _video_duration = $j("DURATA", this).text().substring(0, 8);
          var _video_date = $j("DATA", this).text();
		  var _video_state = $j("STATE", this).text();		      

          if (_video_thumbnail == "") {
             _video_thumbnail = "/res/img/138_nothumb.jpg";
          } else if (_video_thumbnail.indexOf("/images/138") != 0){
             _video_thumbnail = "/images/138" + _video_thumbnail;
          }
		  
		  if(_video_state != '' && _video_state == 'unpublish'){  // controllo se video ha stato non più disponibile
				_video_thumbnail = "/res/img/138_unpublish.jpg";
		  }

          if (_video_url == ".html" || _video_url == "" ) {
             _video_url = "#";
          }

					
		  var sbrandLower = _video_desc_brand.toLowerCase();
		  var sbrandEscape = escape(sbrandLower);
		  var strbrand="\'"+"LINK=vid-"+sbrandEscape+"\'";
          
          if(_tmp.length == 3){
            _html = '<style>.cont-video * {cursor:move}</style><div id="cont-video|' + _video_name_brand + '|' + _video_id + '" class="cont-video">' +
            '<div class="cont-img"><a><img id="img-video|' + _video_name_brand + '|' + _video_id + '" title="" alt="" src="' + _video_thumbnail + '"/></a></div>' +
            '<p class="brandfull" onclick="javascript:ssxl('+ strbrand +')"><a href="/programma/'+_video_name_brand+'/'+_video_desc_brand.replace(' ', '-').toLowerCase()+'.html" rel="nofollow">'+_video_desc_brand+'</a></p>'+
            '<h2><a url="' + _video_url + '">' + _video_title + '</a></h2>' +
             ((_video_type == 'clip') ? '<p class="durata">Durata: ' + _video_duration + '</p>' : '<p class="full-ep">Puntata intera</p>') +
            ((_video_type == 'fep') ? '<p class="durata">Durata: ' + _video_duration + '</p>' : '') +
            '</div>';
            } 
            
          var _item = $j(_html);
          var param = '';
		  var _vt = _video_type; /*(_video_type == '0') ? 'clip' : 'fep';*/		
		  
		  initTooltip2(_item);
		  		   
		 /*  _item.click(function() {   
			      _curpos =  i;
			      initPlaylist(_tmp[0],_tmp[1],_tmp[2],_playlistName,_video_id,_video_name_brand,_video_desc_brand,_video_url,_vt,(_curpos +1));
          })*/

          $j('img', _item).bind('load', function () {
            $j(this).unbind('load').fadeIn();
          }).bind('error', function () {
            $j(this).unbind('error').attr('src', IMAGE_UNAVAIL).show();
          }).hide();
          		       									 
		  // aggiungo video
          _item.appendTo(_cont);
		 
        });		
		
		var _save = $j("<div class=\"save\"><a href=\"#\">save</a></div>").unbind('click').bind('click', function(e) {          
		  saveMyPlaylist(_box, 'modify', []);		  
          return false; //required
        });
	    _save.appendTo(_cont);
        
      },
      error: function() {
        _dbg("modifyMyPlaylist", [_id, _url_pos], "error loading xml file");
        _own.html('<div class="cont-video-scroll"><p class="novideo">Nessun video nella Playlist</p></div>');
      }
    }); 
 }
 //end modifyMyPlaylist()
 
 //begin saveMyPlaylist()
//_obj: container videoPlaylist
 function saveMyPlaylist(_obj, mode, vArray) {  
 
    var _box = $j(_obj);
		
    var _id = _box.attr('id');   
    var _tmp = _id.split("|");
	var myplaylistpath =  _tmp[1]
	var myplaylistid = _tmp[2];
	var myplaylisttitle = $j('div.etichetta-sub > h4', _box.parent().parent()).html();
		
	if(mode == 'modify'){
		$j('div.cont-video', _box).each(function(i) {	
			var itemid = $j(this).attr('id');
			var itemtmp = itemid.split("|");			
			vArray.push(itemtmp[2]);
		  }
		);
	}
	
	_dbg("saveMyPlaylist", [_id, vArray.join(',')], "init");
    //chiamata serverside per modify playlist
	$j.getJSON(customerBaseUrl+"/Customer/videoMediaset/playlist/modifyPlaylist.jsp?callback=?", { playlistId: myplaylistid, videoIds: vArray.join(',')},				  
		 function(data) {					  
			if(data.playlist) {
				try {
					$j.each(data.playlist, function(j, playlistvalue) {
						if(playlistvalue.error == '0'){		
							//ridisegno fascia playlist solo se è aperta
							if(($j('#boxPlaylist').length > 0) && myplaylistid != ''){		
								/*var _time = setTimeout(
									function() { */ reloadFasciaPlaylist(myplaylistpath,myplaylistid,myplaylisttitle); /* }, 
									5);	*/							
							} 
							// ricarico div della mia playlist  visto che sono in pagina playlist
								/*var _time = setTimeout(
									function() {*/ reloadBoxMyPlaylist(myplaylistpath, myplaylistid, mode); /*}, 
									5);	*/														
						} else if(playlistvalue.error == '-400'){
							//utente non loggato
							 showTooltipLogin();
						} else {
							alert('Si è verificato un errore ' + playlistvalue.errordescription);
						}
					});
					} catch(er) {			    
					alert('[addVideoMyPlaylist] error : '+er);
				}
			} else
				alert('[addVideoMyPlaylist] no data found');
			
		});			
		
 }
 //end saveMyPlaylist()
 
 
//begin renameMyPlaylist()
//_obj1: container videoPlaylist
 function renameMyPlaylist(_obj1) {  
    closeBoxPlaylist();
	
    var _box = $j(_obj1);
			
    var _id = _box.attr('id');   
    var _tmp = _id.split("|");
	
	_dbg("renameMyPlaylist", [_id], "init");
     //chiamata serverside per rename playlist  
	 var myplaylistid = _tmp[2];
	 
	 var _renamebox = $j('#div-rename-playlist'+myplaylistid);
    	
    $j('#input-rename-playlist', _renamebox).val('');	
	$j('#ok-rename-playlist', _renamebox).unbind('click').bind('click', function(e) {
		 renameBox(_renamebox,myplaylistid);
	});	
	 $j('#input-rename-playlist', _renamebox).bind('keypress', function(e) {
		if(e.keyCode==13){		
			 renameBox(_renamebox,myplaylistid);
		}
	});
	_renamebox.show();
	return false;  
 }
 //end renameMyPlaylist()
  
 //begin renameMyPlaylist()
 function renameBox(_renamebox,myplaylistid){
	 //chiamata serverside per rename playlist		  		 
	  var t = $j('#input-rename-playlist', _renamebox).val();				  
		$j.getJSON(customerBaseUrl+"/Customer/videoMediaset/playlist/renamePlaylist.jsp?callback=?", { title: t, playlistId: myplaylistid},				  
				 function(data) {					  
					if(data.playlist) {
						try {
							$j.each(data.playlist, function(j, playlistvalue) {
								if(playlistvalue.error == '0'){
									// modifico titolo playlist
									//$j('div.etichetta-sub > h4',_box.parent().parent()).html(t);	
									$j('#myPlaylistBox').empty();
									showFasciaMyPlaylist();	
								} else if(playlistvalue.error == '-400'){
									//utente non loggato
									 showTooltipLogin();
								} else {
									alert('Si è verificato un errore ' + playlistvalue.errordescription);
								}
							});
							} catch(er) {			    
							alert('[renameMyPlaylist] error : '+er);
						}
					} else
						alert('[renameMyPlaylist] no data found');					   					  
				 }
		);	
	_renamebox.hide();	
	return false;  
 }
 //end renameMyPlaylist()
  
 //begin deleteMyPlaylist()
//_obj1: container videoPlaylist
 function deleteMyPlaylist(_obj1) {  
 
    var _box = $j(_obj1);
		
    var _id = _box.attr('id');  
	var _tmp = _id.split("|");	
	
	_dbg("deleteMyPlaylist", [_id], "init");   
	
	var answer = confirm("Sei sicuro di voler eliminare questa playlist ?");
    if (answer){
	     //chiamata serverside per delete playlist        
		$j.getJSON(customerBaseUrl+"/Customer/videoMediaset/playlist/deletePlaylist.jsp?callback=?", { playlistId: _tmp[2]},				  
			 function(data) {					  
				if(data.playlist) {
					try {
						$j.each(data.playlist, function(j, playlistvalue) {
							if(playlistvalue.error == '0'){
								// rimuovo div
								_box.parent().parent().remove();
								//cancello fascia playlist solo se è aperta								
								if($j('#boxPlaylist').length > 0){
									$j('#boxPlaylist').remove();
								}								
							} else if(playlistvalue.error == '-400'){
								//utente non loggato
								 showTooltipLogin();
							} else {
								alert('Si è verificato un errore ' + playlistvalue.errordescription);
							}
						});
						} catch(er) {			    
						alert('[deleteMyPlaylist] error : '+er);
					}
				} else
					alert('[deleteMyPlaylist] no data found');					   					  
			 }
		);
    }
    
    return false;  
 }
 //end deleteMyPlaylist()
 
function titleSEO(str) {

	var url = 	str.replace(/^\s+|\s+$/g, "");
		
	var preserveNormalForm = /[,_`;\':-]+/gi
    url = url.replace(preserveNormalForm, ' ');

    // strip accents
    url = stripVowelAccent(url);

    //remove all special chars
    url = url.toLowerCase().replace(/[^a-z|^0-9|^-|\s]/gi, '');

    //replace spaces with a -
    url = url.replace(/\s+/gi, '-');

 return url;

 }
 
 function stripVowelAccent(str) {
    var rExps = [{ re: /[\xC0-\xC6]/g, ch: 'A' },
                 { re: /[\xE0-\xE6]/g, ch: 'a' },
                 { re: /[\xC8-\xCB]/g, ch: 'E' },
                 { re: /[\xE8-\xEB]/g, ch: 'e' },
                 { re: /[\xCC-\xCF]/g, ch: 'I' },
                 { re: /[\xEC-\xEF]/g, ch: 'i' },
                 { re: /[\xD2-\xD6]/g, ch: 'O' },
                 { re: /[\xF2-\xF6]/g, ch: 'o' },
                 { re: /[\xD9-\xDC]/g, ch: 'U' },
                 { re: /[\xF9-\xFC]/g, ch: 'u' },
                 { re: /[\xD1]/g, ch: 'N' },
                 { re: /[\xF1]/g, ch: 'n'}];

    for (var i = 0, len = rExps.length; i < len; i++)
        str = str.replace(rExps[i].re, rExps[i].ch);

    return str;
}


function loadAddthis(){
	try {
		_dbg("loadAddthis", [], "init");  			
		if (window.addthis){
			 window.addthis.ost = 0;
			 window.addthis.ready();
		}
		// prevent jQuery from appending cache busting string to the end of the URL
		var cache = $j.ajaxSettings.cache;
		$j.ajaxSettings.cache = true; 
		$j.getScript("http://s7.addthis.com/js/250/addthis_widget.js#pubid=ra-4e2e8a6f6006758e");
		   
		// Restore jQuery caching setting
		$j.ajaxSettings.cache = cache;
	} catch(er) {			    
		alert('[loadAddthis] error : '+er);
	}
}

