var ISDEV = (document.location.hostname.match("localhost") || document.location.hostname.match("prjm")); 
var FLAG_ATTIVA_REDIRECT_CONSENSO = 'Y'; // flag per redirect consenso al login
var PROD_DOMAIN = 'http://play.mediasetpremium.it';
var LOGGED_COOKIE_NAME = 'pctv_fa_cookie'; /* nome del cookie restituito dal server a login effettuata */
var LOCANDINE_VOD = "/locandineVOD/"; // path locandine vod
var LOCANDINE_EXTRA = "/locandineExtra/"; // path locandine extra
var LOCANDINE_LIVE = "/locandineLive/"; // path locandine live
var PATH_LOGHI = '/loghi/'; // path loghi canali
var JSON_DOMAIN = (ISDEV) ? '/json/' : '/MDSBE/besc?action=';
var URLBASE = ''; // URLBASE per file necessari al player silverlight
var LUMINOSE_PATH = '/luminose/pctv/'; // path luminose;
var _www_url = document.location.protocol+'//'+document.location.host; // url dominio
var _https_url = (!ISDEV) ? 'https://'+document.location.host : ''; // url dominio https
var isQa = (isLogged()) ? $.jStorage.get('isQa', undefined) : undefined;
var loopContents, section;

$.ajaxSetup({
  dataType: 'json',
  data: { channel: 'PCTV' },
  method: 'GET',
  timeout: 15000
});

$(document).ready(function() { 
	//setHeader();
  $('#search input.text').placeholder({label:'Cerca nel sito', customClass:'default'});
  $('#search form').submit(function() {
    if ($('#search input.text').val() == '' || $('#search input.text').val() == 'Cerca nel sito') {
      $('#search input.text').get(0).focus();
      return false;
    }
  });
  $('.colorbox.help').colorbox({ width: 500, height: 270 });
});

/* setta la chiamata stopContent ******************************************************************************************/
function setStopContent() {
  window.onbeforeunload = function() { 
  	updateVolume();
    sendStopEvent();
  };
}

function updateVolume(){
  	//if (content && window.slPlayer && slPlayer.mpPageBridge && slPlayer.mpPageBridge.getVolume)
		try {
			setVolume(slPlayer.mpPageBridge.getVolume());
		} catch(e){
			//errore
		}
}

/* genera le immagini dinamiche *******************************************************************************************/

function getImgMirror() {
  return 'http://x'+Math.round(Math.random()*9)+'.nettv.mediasetpremium.it';
}

var showLogin = function showLogin(event) {
  if (event)
    event.preventDefault();
  if ($(window).scrollTop() >= 50) {
    animateScrollTo(0,500);
  }
}

function checklogged(){
  if(!jQuery.cookie(LOGGED_COOKIE_NAME)){
    document.location.href = '/';
  }
}
function isLogged(){
	return (jQuery.cookie(LOGGED_COOKIE_NAME)) ? true : false;
}


/* messages handling **************************************************************************************************************/
var _message_offset = 28; // number of message's pixel that intersect with top div

var ACCEDI_MESSAGE = '<span style="font-weight: normal;"><span id="ko-accedi" style="display: inline; font-weight: bold;">LA VISIONE &Egrave; RISERVATA AGLI ABBONATI MEDIASET PREMIUM.</span><br/><br/>'+
                     '<span style="text-transform: none;">Se sei già registrato inserisci username e password [accedi]<br/><br/>'+
                     'Se non ricordi la password <a target="_blank" href="https://areaclienti.mediasetpremium.it/invioAiuto.html">clicca qui</a> se invece non sei ancora registrato effettua la<br/> registrazione [registrati]</span></span>';

var desc_buy = '<a class="cont-arrow-open show-purch-text" href="#"></a><label class="normal purch-abstract" style="display: block; padding: 10px 25px 0 0; font-size: 13px;">Il prezzo ti verrà addebitato nella prossima fattura Premium, <a class="show-purch-text" href="#">leggi qui le condizioni d\'acquisto</a>'+
               '<span class="purchase-text"><br/><br/>Il prezzo indicato in alto è I.V.A. inclusa e ti sarà addebitato nella prossima fattura Mediaset Premium.<br/>'+
               'La visione sarà abilitata per 48 ore dal momento dell’acquisto senza limite sul numero di visioni. Nell’arco delle 48 ore potrai fruire dei tuoi acquisti anche <a href="/scopri-il-servizio/sulla-tua-tv/come-si-usa">sulla tua TV attraverso un decoder abilitato al servizio</a>.<br/>'+
               'Potrai trovare gli acquisti ancora fruibili nell’arco delle 48 ore ricercandoli nel Catalogo oppure all’interno della sezione "<a href="/preferiti">Preferiti</a>" alla voce "Ultimi acquisti".<br/><br/>'+
               'Per consultare lo storico dei tuoi acquisti <a target="_blank" href="https://areaclienti.mediasetpremium.it/acquisti_internet.html">clicca qui</a>.<br/><br/></label>';

var ACQUISTA_MESSAGE = 'Prezzo %price%&euro; [acquista]<br/>'+desc_buy;
var buyHTML = '<div class="buy-content">'+
                  '<strong>PREZZO %price%&euro;</strong><br/><span id="buy-pre-input" style="margin: 0;">Per procedere con l\'acquisto inserisci la password</span> &nbsp;'+
                  '<input type="password" class="inputtext" />'+
                  '<a class="buy" href="#"><img src="/img/btn_conferma_acquisto.png" alt="Conferma acqiusto" style="margin-right: 0;" /></a><br/>'+
                  '<label><input type="checkbox" class="checkpwd" /><span>Non chiedermi più la password</span></label><br/>'+desc_buy+
              '</div>';
var setBuyForm = function() {
  $('.top-player #message a:not(#message-close)').remove();
  $('.top-player #message span:first').remove();
  $('.top-player #message-content').html(buyHTML.replace('%price%', price));
  if (rememberpin && rememberpin == 'Y') {
    $('.buy-content input[type="password"]').val('aaaa').attr('disabled', true);
    $('.buy-content input:checkbox').attr('checked',true).click(function() {
      if (!$(this).attr('checked')) {
        $('.buy-content input[type="password"]').val('').attr('disabled', false);
        //$('.buy').stop().fadeTo(400, 0.5).addClass('disabled');            
      } else {
        $('.buy-content input[type="password"]').val('aaaa').attr('disabled', true).get(0).focus();        
        //$('.buy').stop().css({opacity: 1}).removeClass('disabled');
      }
    });
  } else {
    $('.buy').addClass('disabled');//.css({opacity: 0.5});    
  }
  $('.buy-content input[type="password"]').keyup(function(e) {
    if (((e || 0).keyCode || 0) == 13)
      $('.buy').click();
    if ($(this).val().length >= 4)
      $('.buy').stop().removeClass('disabled');//.css({opacity: 1});
    else
      $('.buy').stop().addClass('disabled');//.fadeTo(400, 0.5);
  });
}

$('.show-purch-text').live('click', function() {
  if ($('#message #message-container .cont-arrow-open').size() > 0) {
    $('#message .cont-arrow-open').detach().prependTo($('#message'));
  }
  if ($('#message .purchase-text:visible').size() > 0) {
    $('#message .purchase-text').hide();
    $('#message .cont-arrow-close').removeClass('cont-arrow-close').addClass('cont-arrow-open');
  } else {
    $('#message .purchase-text').show();
    $('#message .cont-arrow-open').removeClass('cont-arrow-open').addClass('cont-arrow-close');
  }
  $('#message').stop().parent().stop();
  showMessage();
  return false;
});

$('#message-close').live('click', function() { closeMessage(); return false; });
$('.accedi').live('click', showLogin);
$('.acquista').live('click', function() {  
  closeMessage(function() {
    setBuyForm();
    showMessage();
  });
  return false;
});

var showMessage = function showMessage() {
  var mh = ($('#message-container').height() > 72 || $('.top-player #message a:not(#message-close)').size() == 0) ? $('#message-container').height() : 72;
  if (!$('#message').data('ih'))
    $('#message').data('ih', $('#message').parent().height());
  $('#message').parent().animate({height: ($('#message').data('ih')+mh-_message_offset)+'px'}, 'swing');
  $('#message').animate({height: mh+'px'}, 'swing');
}

var closeMessage = function closeMessage(cb) {
  $('#message').animate({height: 0});
  $('#message').parent().animate({height: $('#message').data('ih')+'px'}, cb);
}

var isMessageVisible = function isMessageVisible() {
  return $('#message').height() > 0;
}

var setMessage = function setMessage(msg) { 
  if ($('.top-player #message').size () == 0) {
    var stringMsg = '<div id="message">'+
                      '<div id="message-container">'+
                        '<div id="message-content">'+
                          '<span>'+msg+'</span>'+
                        '</div>'+
                      '</div>'+
                    '</div>';
    $('.top-player').prepend(stringMsg);
  }
  $('.top-player #message a:not(#message-close)').remove();
  var btns = msg.match(/\[\w+\]/g);
  $(btns).each(function() {
    var label = this.toLowerCase().replace(/\[/, '').replace(/\]/, '');
    var regexp = eval('/\\['+label+'\\]/i');
    var urls = {'registrati': 'https://areaclienti.mediasetpremium.it/registrati.html?from=PCTV'};
    var target = (urls[label] && !urls[label].match('http://play.')) ? 'target="_blank"': '';
    msg = msg.replace(regexp, '<a class="'+label+'" '+target+' href="'+((urls[label])?urls[label]:'#')+'"><img src="/img/btn_'+label+'.gif" alt="'+label+'" /></a>');
  });
  $('.top-player #message span').html(msg);
}

$('.buy').live('click', function() {
  if (!$(this).hasClass('buying') && !$(this).hasClass('disabled')) {
    $(this).addClass('buying');
    if ($('.buy-content input.inputtext').val() != '') {
      var rememberPwd;
      $('.buy-content').addClass('center-loading');
      var wantToRememberPin = ($('.buy-content input.checkpwd').attr('checked'));
      var pin = ($('.buy-content .inputtext').val()) ? $('.buy-content .inputtext').val() : undefined;
      if (rememberpin == 'N' && wantToRememberPin) {
        rememberPwd = 'Y';
      } else if (rememberpin == 'Y' && !wantToRememberPin) {
        rememberPwd = 'N';
      } else if (rememberpin == 'Y' && wantToRememberPin) {
        pin = undefined;
      }
      contentLive = (isContentLive) ? 'Y' : 'N';
      $.ajax({
        url: _https_url+JSON_DOMAIN+'ContentPurchase', 
        data: { pwd: pin, contentId: content_ID, subscriptionId: content.subscriptionId, channel: 'PCTV', PURCHASE_CC: content.koAccettabileCC, rememberpin: rememberPwd, isLive: contentLive },
        type: 'GET',
        dataType: (ISDEV) ? 'json' : 'jsonp',
        success: function(data) {
          if (data && data.resultCode && (data.resultCode == 'OK' || data.resultCode == 'OK_CC')) {
            // setto il parametro di sessione per il messaggio di ok
            $.jStorage.set('mds_acquisto', true);
            // ricarico la pagina
            if (data.resultCode == 'OK_CC') {
              var form = $('<form action="'+data.resultObj.PageURL+'" method="post"></form>');
              for (var i in data.resultObj) {
                form.append('<input type="hidden" name="'+i+'" value="'+data.resultObj[i]+'" />');
              }
              form.append('<input type="hidden" name="returnURL" value="'+document.location.href+'" />');
              form.append('<input type="hidden" name="purchaseDate" value="'+systemTime+'" />');
              $(document).find('body').append(form);
              form.submit();
            } else {
              document.location.href = document.location.href;
            }
          } else {
            // nascondo il box messaggi
            closeMessage(function() {
            	if (data.resultCode == 'KO_SOGLIA') {
            		$('#message-content').empty().append("<ins style=\"color:#CA162A; text-decoration: none;\">"+data.errorDescription+"</ins>");
            	} else {
            		setBuyForm();
              	$('.top-player #message .buy-content #buy-pre-input').html("<ins style=\"color:#CA162A; text-decoration: none;\">"+data.errorDescription+"</ins>");
            	}
              showMessage();
            });
          }
        },
        error: function() {
          closeMessage(function() {
            $('.top-player #message .buy-content').replaceWith("<span style=\"color:#5F0F1A;\">"+data.errorDescription+"</span>");
            showMessage();
          });
        }
      });
    } else {
      $('#message').addClass('err');
    }    
  }
  return false;
});

/* extending string object *******************************************************************************************************/
String.prototype.slug = function () {
  var accents = "\u00e0\u00e1\u00e4\u00e2\u00e8"
    + "\u00e9\u00eb\u00ea\u00ec\u00ed\u00ef"
    + "\u00ee\u00f2\u00f3\u00f6\u00f4\u00f9"
    + "\u00fa\u00fc\u00fb\u00f1\u00e7";
  var without = "aaaaeeeeiiiioooouuuunc";

  var slugcontent = this.toLowerCase().replace(new RegExp('[' + accents + ']', 'g'), 
    function (c) { 
      return without.charAt(accents.indexOf(c)); 
    });
	var slugcontent_hyphens = slugcontent.replace(/\./g,'-').replace(/[\s\']/g,'-').replace(/[\-]+/g,'-');
  return slugcontent_hyphens.replace(/[^a-zA-Z0-9\-]/g,'').replace(/[\-]+/g,'-');
};
String.prototype.unslug = function () {
  return this.charAt(0).toUpperCase()+(this.substr(1).replace(/\-/g, ' ')/*.replace(" tv", ' TV').replace('animati', 'Animati')*/);
};

/* prende l'ultimo parametro inserito nell'url ************************************************************************************/
var getLastUrlParamAfter = function getLastUrlParamAfter(after) {
  var urlparam = document.location.href.split(after)[1];
  if (!urlparam) return false;
  if (urlparam.match('#')) urlparam = urlparam.split('#')[0];
  if (urlparam.match(/\?/)) urlparam = urlparam.split(/\?/)[0];
  return urlparam;
};

/* animated scroll ****************************************************************************************************************/
var animateScrollTo = function animateScrollTo(y,duration) {
  var reg = /[0-9]+/g;
  y += '';
  if (y.match(reg) && y.match(reg).length > 0)
	  jQuery('html, body').animate({scrollTop:y}, duration);
  else
	  jQuery('html, body').animate({scrollTop:jQuery('#'+y).offset().top}, duration);
}

/* checkContentRights *************************************************************************************************************/

var bookmark, rememberpin, contentRights, isContentLive, price;
function checkContentRights(o) {
	// invio stopContent sincrona con type=LIVE
	if (!o) o = {};
	
	if (!window.blockSCBeforeCCR)
		sendStopEvent(false);
	
  var contentLive = (o.contentType == 'Live') ? 'Y': 'N';
  isContentLive = (o.contentType == 'Live');
  var isAnonymous = (isLogged()) ? undefined : 'Y';
  var KOmessages = ['KO', 'KO_ACCETTABILE_FATTURA', 'KO_ACCETTABILE_CC', 'KO_SUBSCRIPTION', 'KO_COHERENCE_FRUIZIONE', 'GUARD_IN_PANIC'];
  var jsonpCallback = (isLogged()) ? undefined : 'jsonpCCRCallback';
  $.ajax({
    type: 'GET',
    url: _https_url+JSON_DOMAIN+'CheckContentRights',
    data: { contentId: content.contentId, subscriptionId: content.subscriptionId, channel: 'PCTV', isLive: contentLive, isVLC: o.isVLC, isAnonymous: isAnonymous },
    dataType: (ISDEV) ? 'json' : 'jsonp',
    context: this,
    jsonpCallback: jsonpCallback,
    success: function(data) {
      contentRights = data;
      if (data && data.resultObj && data.resultCode) {
        if (data.resultObj.bookmark || data.resultObj.bookmark >=0) bookmark = data.resultObj.bookmark;
        if (data.resultObj.rememberpin) rememberpin = data.resultObj.rememberpin;
        //var ENABLE_PLAYER = data.resultObj.ENABLE_PLAYER;
        var playerContentId = (o.extraId) ? o.extraId : content.contentId;
        var playerConfig = (o.contentType && o.contentType == 'Live') ? 'live' : 'vod';
        
        if (data.resultCode == 'OK' && ENABLE_PLAYER == 'Y') { // avvio contenuto
          if (!o.contentType)
            o.contentType = (playerContentId == content.contentId) ? 'VoD' : 'Extra';
          var isHD = (content.isHD == 'Y') ? '_HD' : '';
          // contenuto per intero extra o vod a seconda dell'id
          playerContentId = (o.idForPlayer) ? o.idForPlayer : playerContentId;
          $('#player').html(initPlayer({
            islive: (playerConfig == 'live'),
            configUri: URLBASE+'/'+o.contentType+'/Player/player_config_'+playerConfig+isHD+'.xml',
            playlist: URLBASE+'/'+o.contentType+'/Player/xml_playlist_'+playerContentId+'.xml'
          }));
        } else if ($.inArray(data.resultCode, KOmessages)  >= 0 && ENABLE_PLAYER == 'Y') { // avvio trailer
          o.contentType = 'Extra';
          var playerConfig = 'vod';
          var isHD = (content.promoHD == 'Y') ? '_HD' : '';
          if (data.message != 'KO_COHERENCE_FRUIZIONE') {
	          playerContentId = (content.promoId) ? content.promoId : false;
          } else {
          	playerContentId = 15070;
          }
          if (playerContentId) { // mostro il promo
            $('#player').html(initPlayer({
              islive: false,
              configUri: URLBASE+'/'+o.contentType+'/Player/player_config_'+playerConfig+isHD+'.xml',
              playlist: URLBASE+'/'+o.contentType+'/Player/xml_playlist_'+playerContentId+'.xml'
            }));
          } else { // non ho id promo e inizializzo il player senza parametri
            $('#player').html(initPlayer({}));
          }
        } else if (ENABLE_PLAYER == 'N') { // avvio player e passo parametro ENABLE_PLAYER
          if (!o.contentType)
            o.contentType = (playerContentId == content.contentId) ? 'VoD' : 'Extra';
          var isHD = (content.isHD == 'Y') ? '_HD' : '';
          // contenuto per intero extra o vod a seconda dell'id
          playerContentId = (o.idForPlayer) ? o.idForPlayer : playerContentId;
          $('#player').html(initPlayer({
            islive: (playerConfig == 'live'),
            configUri: URLBASE+'/'+o.contentType+'/Player/player_config_'+playerConfig+isHD+'.xml',
            playlist: URLBASE+'/'+o.contentType+'/Player/xml_playlist_'+playerContentId+'.xml',
            ENABLE_PLAYER: ENABLE_PLAYER
          }));
        }
        
        // formatto il prezzo
        if ((content.price+'').length >= 3) {
          price = (content.price+'').charAt(0)+','+(content.price+'').substring(1); 
        } else if ((content.price+'').length == 2) {
          price = '0,'+content.price;
        } else {
          price = content.price;
        }
        
        if (!checkUserLogged() && data.resultCode != 'OK') {
          setMessage(ACCEDI_MESSAGE);
          var anonPrice = '';
          if ($.inArray(parseInt(content.subscriptionId), ANONYMOUS_PRICES_PACK_IDS) >= 0)
            anonPrice = '<strong>PREZZO '+price+'&euro;.</strong> ';
          $('#ko-accedi').html(anonPrice+data.errorDescription);
          showMessage();
        } else if($.inArray(data.message, ['KO_ACCETTABILE_FATTURA', 'KO_ACCETTABILE_CC', 'KO_SUBSCRIPTION']) >= 0) {
          content.koAccettabileCC = (data.message == 'KO_ACCETTABILE_CC') ? 'Y' : 'N';         
          if (data.message == 'KO_SUBSCRIPTION') {
          	var anonPrice = '';
          	if ($.inArray(parseInt(content.subscriptionId), ANONYMOUS_PRICES_PACK_IDS) >= 0)
          		anonPrice = '<strong>PREZZO '+price+'&euro;.</strong><br/><br/>';
            setMessage(anonPrice + data.errorDescription);
          } else {
            setMessage(ACQUISTA_MESSAGE.replace('%price%', price));
            // nel caso di acqusti con CC evito di rifar inserire il pin
            if (data.message == 'KO_ACCETTABILE_CC') {
              $('.acquista').die('click').addClass('buy');
            }
          }
          showMessage();
        } else if (data.message == 'KO_COHERENCE_FRUIZIONE') {
        	setMessage('<span class="red">'+data.errorDescription+'</span>');
        	showMessage();
        } else if (data.message == 'KO_NO_PRICE') {
          setMessage(data.errorDescription);
          showMessage();
        } else if (data.message == 'KO_TECNICO') {
        	setMessage('<span class="red">'+data.errorDescription+'</span>');
        	showMessage();
        } else if (data.message == "") {
        	var anonPrice = '';
        	if ($.inArray(parseInt(content.subscriptionId), ANONYMOUS_PRICES_PACK_IDS) >= 0)
        		anonPrice = '<strong>PREZZO '+price+'&euro;.</strong><br/><br/>';
          setMessage(anonPrice + data.errorDescription);
          showMessage();
        } else if (data.errorDescription == "GUARD_IN_PANIC") {
          setMessage(data.message);
          showMessage();
        }
      }
      if (isLogged() && $.jStorage.get('mds_acquisto', false)) {                          
        setMessage('<span style="display: block; line-height: 16px; margin-top: -6px;"><span style="color: #54b258;">Acquisto effettuato correttamente!</span> <span style="text-transform: none;">Il prezzo ti verrà addebitato nella prossima fattura Premium.</span></span>');
        showMessage();
      }
      $.jStorage.deleteKey('mds_acquisto'); 
    }
  });
}

/* player initiliazation **********************************************************************************************************/
var KATimer = 0;
var initPlayer = function initPlayer(params) {
	// gestione luminose
	if (ENABLE_LUMINOSA == 'Y') {
		if (content.lumPos != undefined && content.lumName != undefined && content.lumPos.length > 0 && content.lumName.length > 0) {
			params.lumPos = content.lumPos.join(';');
			$(content.lumName).each(function(i) {content.lumName[i] = LUMINOSE_PATH+content.lumName[i];});
			params.lumUri = content.lumName.join(';');
			params.lumWidth = LUM_WIDTH.join(';');
		}
	}
  var paramString = '';
  for (var key in params)
    paramString += key+'='+params[key]+',';
  paramString = paramString.substring(0, paramString.length-1);
  var player = '<div id="silverlightControlHost">'+
                  '<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" id="SilverlightPlugin" width="640" height="423">'+
                      '<param name="source" value="/PolymediaShow/TXTPolymedia.Show.xap" />'+
                      '<param name="onError" value="onSilverlightError" />'+
                      '<param name="onLoad" value="onSLLoad" />'+
                      '<param name="background" value="white" />'+
                      '<param name="minRuntimeVersion" value="4.0.51204.0" />'+
                      '<param name="autoUpgrade" value="true" />'+
                      '<param name="enableHtmlAccess" value="true" />'+
                      '<param name="enableGPUAcceleration" value="true" />'+
                      '<param name="background" value="transparent" />'+
                      '<param name="windowless" value="true" />'+
                      '<param name="InitParams" value="'+paramString+'" />'+
                      '<a target="_blank" href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.51204.0" style="text-decoration: none">'+
                          '<img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none" />'+
                      '</a>'+
                  '</object>'+
               '</div>';
  // schedulo la chiamata KeepAlive dopo 8 secondi per dare il tempo al player di caricarsi
 	clearTimeout(KATimer);
  KATimer = setTimeout(KeepAlive, 8000);
  
  return player;
}

/* isStringAndNotEmpty ********************************************************************************************************************/
function isStringAndNotEmpty(s) {
  return (s && s != '');
}

/* appendMeta ********************************************************************************************************************/
function appendMeta(c,l,m) {
  if (isStringAndNotEmpty(m)) 
    c.append($('<dt>'+l+':</dt>')).append($('<dd></dd>').text(m));
}

/* gestione della descrizione e metadati *****************************************************************************************/
function manageDesc() {
  var subtitle;
  if (content.contentSubTitle && det.contentSubTitle != '')
    subtitle = ' ( '+det.contentSubTitle+' )';
  $('#desc h2').text(det.contentTitle).append('<span class="details"></span>');
  $('#desc h2 span.details').text(' - '+secToMin(det.duration)+' min');
  $('#desc p:last').empty().siblings('p').remove();
  $('#desc p').html(det.description).show();
  
  // metadati
  var metaList = [
    { l: "Titolo episodio", m: det.episodeTitle, types: [ 'serie-tv', 'serietv', 'serie', 'fiction', 'sitcom', 'cartoni-animati', 'cartoni' ] },
    { l: "Sottotitolo", m: det.contentSubTitle, types: [ 'fiction', 'serie-tv', 'serie', 'serietv', 'intrattenimento', 'cartoni', 'cartoni-animati' ] },
    { l: "Nazione", m: det.country}, 
    { l: 'Anno', m: det.year},
    { l: 'Genere', m: det.genre },
    { l: 'Durata', m: secToMin(det.duration)+'\'' },
    { l: 'Regia', m: det.directors },
    { l: 'Cast', m: det.cast },
    { l: 'Conduttori', m: det.anchors }
  ];
    
  var slugType = det.type.slug();
  var metaContainer = $('<dl></dl>');
  for (var i in metaList) {
    if (metaList[i].types) {
      if ($.inArray(slugType, metaList[i].types) >= 0)
        appendMeta(metaContainer, metaList[i].l, metaList[i].m);
    } else {
      appendMeta(metaContainer, metaList[i].l, metaList[i].m);
    }
  }
  $('#desc p').append(metaContainer);
  
  // expiredate e pacchetti
  var expDate = new Date(det.expirationDate*1000);
  var packDesc = '';
  var packImg = '<img class="pacchetto" src="'+PATH_LOGHI+'pacchetti/'+det.subscriptionId+'_dbl.png" alt="" />';
  var packLink = 'http://www.offerta.mediasetpremium.it/';
  switch(det.subscriptionId) {
  	case "8": 
  		packDesc = ''; 
  		packImg = '<img class="pacchetto" src="'+PATH_LOGHI+'pacchetti/8_dbl.png" alt="" style="float: right;" />'; 
  		break;
  	case "3": 
  		packDesc = 'Incluso per tutti i clienti Mediaset Premium'; 
  		packImg = ''; 
  		break;
  	case "9": 
  		packDesc = 'Gratis per tutti gli utenti Registrati'; 
  		packImg = ''; 
  		break;
  	case "10": 
  		packDesc = ''; 
  		packImg = '<img class="pacchetto" src="'+PATH_LOGHI+'pacchetti/8_dbl.png" alt="" style="float: right;" />'; 
  		break;
  	default: 
  		packDesc = 'Visione inclusa <br /> nei pacchetti:';
  		packImg = '<a href="'+packLink+'" target="_blank">'+packImg+'</a>';
  }
  $('.pacchetti').append('<p><span class="incluso">'+packDesc+'</span>'+packImg+'</p>');
  $('.pacchetti').append('<span class="expire">Disponibile fino al '+dateFormat(expDate, 'dd/mm/yyyy')+'</span>');
  managePackets(content);
  var txtLength = 200; // lunghezza testo abbreviato
  $('#desc p').condense({
    condensedLength: ((det.description.length > txtLength)?txtLength:det.description.trim().length-1),
    delim: '',
    moreText: 'Continua',
    lessText: 'Chiudi',
    ellipsis: '...',
    easing: 'swing',
    minTrail: 10
  });
  if ($('span.condense_control').size() > 0) {
    $('span.condense_control').click(function() {
      $('#desc a.cont-arrow-open, #desc a.cont-arrow-close').toggleClass('cont-arrow-open, cont-arrow-close');
    });
		$('#desc a.cont-arrow-open').remove();
    var contTrigger = $('<a class="cont-arrow-open" href="#"></a>;');
    $('#desc').append(contTrigger);
    contTrigger.click(function() {
      $('#desc span.condense_control:visible').click();
      return false;
    });
  }
  $('#desc a.cont-arrow-open, #desc .condense_control_more').live('click', function() {
    track('descrizione_mostra%26refresh_ce-awe&rnd='+Math.floor(Math.random()*10000001));
  });
}

/* gestione grafica pacchetti e label ********************************************************************************************/
function managePackets(content) {
  var container = $('<div class="labels"></div>');
  var p = 0;
  if (content.isNew && content.isNew == 'Y' && ++p)
    container.append('<img src="/img/new.gif" alt="NEW" />');
  if (content.isLastDays && content.isLastDays == 'Y' && ++p)
    container.append('<img src="/img/ultimi_giorni.gif" alt="ULTIMI GIORNI" />');
  if (content.isHD && content.isHD == 'Y')
    $('.pacchetti').append('<span class="hd">Anche in <img src="/img/hd.gif" alt="HD" /></span>')
  if (p > 0)
    $('.pacchetti .expire').after(container);
}

/* funzione per il check se l'utente è loggato ************************************************************************************/

function checkUserLogged() {
  return (jQuery.cookie(LOGGED_COOKIE_NAME) != null);
}

/* animated scroll ********************************************************************************************************/
var animateScrollTo = function animateScrollTo(y,duration, callback) {
  var reg = /[0-9]+/g;
  y += '';
  if (y.match(reg) && y.match(reg).length > 0)
	  jQuery('html, body').animate({scrollTop:y}, duration, 'swing', callback);
  else
	  jQuery('html, body').animate({scrollTop:jQuery('#'+y).offset().top}, duration, 'swing', callback);
}

/* secToMin *******************************************************************************************************************/
function secToMin(i) {
  return Math.round(parseInt(i)/60);
}

/* KeepAlive ******************************************************************************************************************/

var KeepAlive = function() {
  $.ajax({
    url: JSON_DOMAIN+'KeepAlive',
    data: { checkBlock: ((contentRights && contentRights.resultCode=='OK')?'Y':undefined), contentId: ((window.contentRights && window.contentRights.resultCode=='OK') ? content.contentId : 'extra')},
    success: function(data) {
      if (((data || 0).resultCode || 0) == 'OK' && data.resultObj) {
       	clearTimeout(KATimer);
        KATimer = setTimeout(KeepAlive, data.resultObj.keepAlive*1000);
        if ((data.resultObj.token || data.resultObj.token == "") && slPlayer) {
        	try {
        		slPlayer.mpHeartBeat.setHeartBeatToken(data.resultObj.token);
        	} catch(e) { log('setHeartBeatToken fallito token: '+ data.resultObj.token); }
        }
      } else {
        if (slPlayer && slPlayer.mpHeartBeat && slPlayer.mpHeartBeat.setHeartBeatToken)
          slPlayer.mpHeartBeat.setHeartBeatToken('');
      }
    },
    error: function() {
     	clearTimeout(KATimer);
      KATimer = setTimeout(KeepAlive, 8000); // in caso di errore della keepalive, settato timer ad 8 secondi
    }
  });
}

// Return new array with duplicate values removed
Array.prototype.unique = function() {
  var a = [];
  var l = this.length;
  for(var i=0; i<l; i++) {
    for(var j=i+1; j<l; j++) {
      // If this[i] is found later in the array
      if (this[i] === this[j])
        j = ++i;
    }
    a.push(this[i]);
  }
  return a;
};


/* text truncation by length ********************************************************************************************************/

(function($){
  $.fn.extend({
    truncate: function(o) {
      var defaults = {
        length: 20,
        after: '...',
        mincut: 0
      };
      
      var o = $.extend(defaults, o);
      
      return this.each(function() {
        var text = $(this).text();
        if (text.length > o.length && (text.length - o.length) >= o.mincut)
          $(this).text(text.substr(0,o.length).trim()+o.after);
      });
    }
  });
})(jQuery);

/* Trim strings *******************************************************************************************************************/
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

/* Capitalize the first letter *****************************************************************************************************/
String.prototype.capitalizeFirstChar = function() {
	return this.charAt(0).toUpperCase()+this.substr(1);
}

/* track nielsen */ 
function track(trackUrl) {
  $('#nielsen').remove();
  $('#footercont').append('<img id="nielsen" width="1" height="1" style="float: left;" src="//secure-it.imrworldwide.com/cgi-bin/m?ci=gruppomediaset-it&cg=0&si=http%3A//play.mediasetpremium.it/'+trackUrl+'" alt=""/>');
}

/* clean urls from params */
function cleanUrl(s) {
	return (s.match(/\?/)) ? s.split(/\?/)[0] : s;
}

//usage: log('inside coolFunc',this,arguments);
window.log = function() {
	log.history = log.history || [];   // store logs to an array for reference
	log.history.push(arguments);
	if(this.console){
	 console.log( Array.prototype.slice.call(arguments) );
	}
};

/* Tooltip Mediaset ***************************************************************************************************************/

function init_tooltip(containerLink){
	$(containerLink).bind('mouseenter',function(){
		var linkRef=$(this).attr('href');
		var tempContentId = $(this).attr('id').split('_')[1];
		show_tooltip($(this),linkRef, tempContentId);		
	});
}

function show_tooltip(el, linkRef, tempContentId, offsetSL){
	var y;
	if(offsetSL){
		y=0;
	} else {
		y = (/MSIE (\d+\.\d+);/.test(navigator.userAgent) && new Number(RegExp.$1) <9) ? 6 : 9;
	}
	var stylist='';
	(offsetSL) ? stylist='tooltipSL ' : '';
	(offsetSL && isLogged()) ? stylist+=' noExtra ': '';
	stylist+=(/MSIE (\d+\.\d+);/.test(navigator.userAgent) && new Number(RegExp.$1) <9) ? '' : 'ui-tooltip-shadow ';
	el.qtip({		
		content: {
			text: $('<div class="center-loading" />').css({"height": "145px","width":"100%"}),
			ajax: {
				url: JSON_DOMAIN+'GetContentDetails',
				data: { contentId: tempContentId },
				type: 'POST',
				context:el,
				loading: false,
				success: function(data, status) {
					if(data.resultObj){
						var tt_wrapper = $('<div class="tooltip-wrapper" />');
						var tt_content = $('<div class="tooltip-content" />');
						//Set ToolTip Title
						var tt_content_top = $('<div class="tooltip_content_top" />');
              var tempTitle = data.resultObj.content.contentTitle;
              if(tempTitle.length>36){
                tempTitle= tempTitle.substring(0,36)+'...';
              }
						tt_content_top.append('<a href="'+linkRef+'"><span class="tooltip-contentTitle">'+tempTitle+'</span></a>');
						
						/*//Set ToolTip SubTitle or EpisodeTitle if present
						if((data.resultObj.content.contentSubTitle && data.resultObj.content.contentSubTitle!="") || (data.resultObj.content.episodeTitle && data.resultObj.content.episodeTitle!="")){
							var tempSub = (data.resultObj.content.episodeTitle) ? (data.resultObj.content.episodeTitle) : (data.resultObj.content.contentSubTitle);
							tt_content_top.append('<a href="'+linkRef+'"><span class="tooltip-contentSubTitle">'+tempSub+'</span></a>');
						}*/
						
						//Set ToolTip Favorite if logged
						if(checkUserLogged()){
							var contentId = data.resultObj.content.contentId;
							$.ajax({
								url: JSON_DOMAIN+'GetIsFavoriteContent',
								type: 'POST',
								data: {contentId: contentId},
								success: function(data){
									var isF;
									var aFavorite = '';
									if(data.resultCode == 'KO'){
										aFavorite = $('<a class="tooltip-favorite" href="javascript:void(0);" title="Aggiungi ai Preferiti">Aggiungi ai Preferiti</a>');
										$.data(aFavorite,'isF','Y');
									} else {
										aFavorite = $('<a class="tooltip-favorite active" href="javascript:void(0);" title="Rimuovi dai Preferiti">Rimuovi dai Preferiti</a>');
										$.data(aFavorite,'isF','N');
									}
									$(aFavorite[0]).click(function(){
										$.ajax({
											url: JSON_DOMAIN+'SetFavorite',
											type: 'POST',
											data: { contentId: contentId, isFavorite: $.data(aFavorite,'isF') },
											success: function(data){
												if(data.resultCode == "OK"){
													if($.data(aFavorite,'isF')=='N'){
														$(aFavorite[0]).attr('title','Aggiungi ai Preferiti');
														MDS.user.delFav();
														$.data(aFavorite,'isF','Y');
													} else {
														$(aFavorite[0]).attr('title','Rimuovi dai Preferiti');
														MDS.user.incFav();
														$.data(aFavorite,'isF','N');
													}
													$(aFavorite[0]).toggleClass('active');
												}
											}
										});
									});
									tt_content_top.append(aFavorite[0]);
								}
							});
						}
						tt_content.append(tt_content_top);
						
						//Set ToolTip Directors if present
						if(data.resultObj.content.directors && data.resultObj.content.directors!=""){
							var tempRegia;
							if(data.resultObj.content.directors.length>40){
								tempRegia= (data.resultObj.content.directors).substring(0,40)+'...';
							} else{
								tempRegia= (data.resultObj.content.directors);
							}
							tt_content.append('<div class="tooltip-info_line"><a href="'+linkRef+'"><span class="tooltip-info_title">Regia</span><p>'+tempRegia+'</p></span></a></div>');
						}
						//Set ToolTip Cast or Anchors if present
						if((data.resultObj.content.cast && data.resultObj.content.cast!="") || (data.resultObj.content.anchors && data.resultObj.content.anchors!="")){
							var tempCast = (data.resultObj.content.cast) ? (data.resultObj.content.cast) : (data.resultObj.content.anchors);
							if(tempCast.length>45){
								tempCast= tempCast.substring(0,45)+'...';
							}
							tt_content.append('<div class="tooltip-info_line"><a href="'+linkRef+'"><span class="tooltip-info_title">Con</span><p>'+tempCast+'</p></span></a></div>');
						}
						
						var tt_content_center = $('<div class="tooltip_content_center" />');
						
						//Set ToolTip Duration - Year - Description
						tt_content_center.append("<a href='"+linkRef+"'><p>"+secToMin(data.resultObj.content.duration)+"' - "+data.resultObj.content.country+" "+data.resultObj.content.year+" - "+data.resultObj.content.description+"</p></a>");
						if($(tt_content_center).children().children().text().length > 140){
							$(tt_content_center).children().children().text($(tt_content_center).children().children().text().substring(0,140)+'...');
						};
						tt_content.append(tt_content_center);
						
						var tt_content_bottom = $('<div class="tooltip_content_bottom" />');
						
						//Set ToolTip Facebook Like
						tt_content_bottom.append('<div class="fb" id="fblike'+ ((offsetSL) ? "SL" : "") +'_'+tempContentId+'"><fb:like href="'+PROD_DOMAIN+linkRef+'" send="false" layout="button_count" width="122" show_faces="false" font=""></fb:like></div>');
						//Set ToolTip Pacchetto
						if(data.resultObj.content.subscriptionId!='3' && data.resultObj.content.subscriptionId!='8' && data.resultObj.content.subscriptionId!='9' && data.resultObj.content.subscriptionId!='10' && data.resultObj.content.subscriptionId!='1'){
							tt_content_bottom.append('<span class="tooltip_pacchetto"><a target="_blank" href="http://www.offerta.mediasetpremium.it/"><img class="pacchetto" src="'+PATH_LOGHI+'pacchetti/'+data.resultObj.content.subscriptionId+'_dbl.png" height="30" alt="" /></a></span>');
						} else {
							tt_content_bottom.append('<span class="tooltip_pacchetto"><a href="javascript:void(0);" style="cursor: default !important;"><img class="pacchetto" src="'+PATH_LOGHI+'pacchetti/'+data.resultObj.content.subscriptionId+'_dbl.png" alt="" /></a></span>');
						};
						
						tt_content.append(tt_content_bottom);
						tt_wrapper.append(tt_content);
						
						if (isLogged()) {
							if (MDS.bookmarks.hasCookie()) {
	          		var fruictionPercent = MDS.bookmarks.getContentFruition(tempContentId);
	          		if (fruictionPercent) {
	          			tt_content.append('<span class="bar"><span style="width: '+fruictionPercent+'%"></span></span>');
	          		}
	          	}
						}
											
						//Set ToolTip Bottone ABBONATI se utente non registrato/loggato
						if(!checkUserLogged()){
							var tt_content_extra = $('<div class="tooltip_content_extra" />');
							tt_content_extra.append('<span class="tooltip_abbonati"><a class="btn_login" href="javascript:void(0);">Login</a><p>Se ancora non sei registrato</p><a target="_blank" class="btn_registrati" href="https://areaclienti.mediasetpremium.it/registrati.html?from=PCTV">Registrati</a></span>');
							tt_wrapper.append(tt_content_extra);
						}
											
						//Set ToolTip Banner se utente loggato e indirizzo configurato
						if(checkUserLogged() && TOOLTIP_BANNER_LINK && TOOLTIP_BANNER_LINK!="" && TOOLTIP_BANNER_IMAGE && TOOLTIP_BANNER_IMAGE!=""&& TOOLTIP_BANNER_HEIGHT && TOOLTIP_BANNER_HEIGHT!=""){
							var tt_content_extra = $('<div class="tooltip_content_extra" />');
							var tt_banner = $('<a style="height:'+TOOLTIP_BANNER_HEIGHT+'px;" />').attr({'href':TOOLTIP_BANNER_LINK, 'target':'blank'});
							var tt_banner_image = $('<img/>');
							tt_wrapper.append(tt_content_extra);
							tt_banner.append(tt_banner_image);
							tt_content_extra.html(tt_banner);
							$('#silverlightControlHost').qtip('reposition');
							tt_banner_image.attr({src : TOOLTIP_BANNER_IMAGE, title: '', alt: ''});
						}
						$(this).qtip('option','content.text', tt_wrapper);
						//Run Facebook' script for Like Button
						FB.XFBML.parse(document.getElementById('fblike'+ ((offsetSL) ? "SL" : "") +'_'+tempContentId));
						$('.btn_login').click(showLogin); 
					}
					else{
						$(this).qtip('hide');
					}
			 },
			 error: function(XMLHttpRequest, textStatus, errorThrown) {
			 }
			}
		},
		prerender: (offsetSL) ? true : true,
		position: {
			at: (offsetSL) ? 'top center' : 'right top', 
			my: (offsetSL) ? 'bottom center' : 'left top',
			viewport: $(window),
			target: (offsetSL) ? [parseInt($('#Rullo').offset().left)+offsetSL+100 , parseInt($('#Rullo').offset().top+19)] : el.children().children(),
			adjust: {
				method: 'flip none',
				y: y
			},
			effect: false
		},
		show: {
			delay: (offsetSL) ? 0 : TOOLTIP_OPEN_DELAY, // delay allo show configurata nel config.js
			solo: true, // mostra un toolTip alla volta
			event: 'show-tooltip',
			effect: function(offset) {
				$(this).fadeIn(300, function(){
					if($('.ui-tooltip-tip:visible')){
            if(parseInt($('.ui-tooltip-tip:visible').offset().left) > parseInt($('.ui-tooltip:visible').offset().left)){
              $('.ui-tooltip:visible').removeClass('ui-tooltip-pos-tl').addClass('ui-tooltip-pos-tr');
            }
					}
				}); 
			}
		},
		hide: {
			delay: 300,
			fixed: true,
			event: 'mouseleave',
			effect: function(offset) {
        if(offsetSL){
        	document.getElementById("Rullo").Content.ScriptableObject.RulloPlay();
        }
				$(this).fadeOut(200,function(){
	        if(offsetSL){
				    $('#silverlightControlHost').qtip('destroy');
	        }
				});
			}
		},	
		events: {
			show: function(event, api) {
		        if(offsetSL){
		        	document.getElementById("Rullo").Content.ScriptableObject.RulloStop();
		        }
			}
		},
		style: {
			classes: stylist + 'ui-tooltip-plain ui-tooltip-rounded',
			tip: {
				width: (offsetSL) ? 28 : 13,
				height: (offsetSL) ? 13 : 28,
				mimic: 'center',
				offset: (offsetSL) ? 0 : 10
			}
		}
	}).trigger('show-tooltip');
}

var MDS = function() {	
	function request(o) {
		var defaults = {};
		var options = $.extend({}, defaults, o || {});
		
		jQuery.ajax(options);
	}
	
	return {
		bookmarks: function(data, cookieName) {
			var data = data || {}; 
			var cookieName = cookieName || 'BM';
			
			function setCookie() {
				return $.cookie(cookieName, JSON.stringify(data), {path: '/'});
			}
			function setup() {
				request({
					url: JSON_DOMAIN+'GetBookmarks',
					async: false,
					success: function(response) {
						if (response && response.resultObj && response.resultCode == 'OK' && response.resultObj.bookmarksList) {
							$(response.resultObj.bookmarksList).each(function() {
								data[parseInt(this.contentId)] = this.fruitionPercentage;
							});
							setCookie();
						} else {
							data = {};
							setCookie();
						}
					}
				})
			}
			
			return {
				hasCookie: function() {
					return $.cookie(cookieName, {path: '/'});
				},
				getContentFruition: function(contentId) {
					return parseInt(data[contentId]);
				},
				setContentFruition: function(contentId,percentage) {
					data[contentId] = percentage;
					return setCookie();
				},
				init: function() {
					if(!this.hasCookie()){
						setup();
					} else {
						data = JSON.parse(this.hasCookie()) || {};
					}
				},
				getCookieName: function() {
					return cookieName;
				}
			}
		}(),
		
		user: function() {
			var data = data || {};
			var sessionCookieName = 'pctv_fa_cookie';
			var profileCookieName = 'pctv_profile';
			var mediasetCookieName = 'mds_fa_cookie';
			var prodCookieDomain = (location.hostname.match('mediasetpremium')) ? '.mediasetpremium.it' : location.hostname;
			var profile = ((isLogged()) ? JSON.parse(jQuery.cookie(profileCookieName, {path: '/'})) : {}) || {};
			
			var messages = {
	      user : 'Username obbligatorio',
	      pwd : ' Password obbligatoria'
	    }
			
			var COMessage = '';
			
			function setCookie() {
				var expireDate = new Date();
				expireDate = new Date(expireDate.setHours(expireDate.getHours()+2)); // Da cambiare
				$.cookie(cookieName, JSON.stringify(data), {expires: expireDate, path: '/'}); // Da cambiare
			}
			function buildLoggedHeader() {
			  if (profile) {
					var packageList = '';
					if (profile.commercialOffer) {
			  	$(profile.commercialOffer).each(function(){
			  		COMessage += this.message + '</br>'; // messaggio da mostrare sul tooltip di info da loggato
							$(this.images).each(function(){
								packageList += '<img src="/loghi/offertacommerciale/' + this + '.png" alt="" />';
							});
						});
						packageList += '<span class="info_icon"></span>'; 
					}
			    jQuery('#loginbarcont').html(
              '<div id="loggedinbar" >'
						+   '<span class="bg_sx"></span><span class="bg_dx"></span>'
						+   '<div id="info_container">'
						+     '<div class="welcome_messages">'
						+       '<span class="userid">Ciao, <span id="usernickname">'+ profile.nome +'</span></span>'
						+       '<span class="userTypeMessage">'+ userTypeMap[profile.userType.slug()] +'</span>'
						+     '</div>'
            +     '<div class="packet_container">'
						+       packageList
            +     '</div>'
						+     '<a href="#" class="lbl" title="Esci" id="logout">Esci</a>'
						+   '</div>'
						+ '</div>'
					);
			    if (profile.pref > 0) {
		      	jQuery('#numero_preferiti').text(profile.pref);
			    } else {
			      getFavoriteNumber();
			    }
			    jQuery('#logout').click(MDS.user.logout);
					
					//Regolo la dimensione per una corretta visualizzazione su IE7 e IE8
					if (/MSIE (\d+\.\d+);/.test(navigator.userAgent) && new Number(RegExp.$1) <9){
            $('#info_container').css('width',($('.welcome_messages').width()+$('.packet_container').width()+$('#logout').width())+'px');
						$('#loggedinbar').css('width',($('#loggedinbar .bg_sx').width()+$('#loggedinbar .bg_dx').width()+$('#info_container').width())+'px');
					}
					
					//Gestione tooltip per le info da loggato
					$('#info_container .packet_container').qtip({
            content: {
              text: '<div class="tooltip-content"><p class="info">' + COMessage + '</p></div>'
            },
            position: {
              my: 'top center',
              at: 'bottom center',
              target: $('#info_container .packet_container .info_icon'),
              adjust: {
                x: 0,
                y: 4
              }
            },
            show: {
              event: 'mouseenter',
              effect: function(offset) {
                 $(this).fadeIn(200);
              }
            },
            style: {
              tip: {
                width: 15,
                height: 7,
                offset: 60
              },
              classes: 'qtip_logged ui-tooltip-rounded'
            }
          });
					
					//Attivo la stella dei preferiti sul menu e riporto il numero
					$('#preferiti a').addClass('active').attr('href','/preferiti');
			  }
			}
			function updateProfile() {
				jQuery.cookie(profileCookieName, JSON.stringify(profile), {path: '/'});
			}
			function getFavoriteNumber() {
			  request({
			  	url: JSON_DOMAIN+'GetFavoriteContents', 
			  	data: { channel: 'PCTV' }, 
			  	success: function(data) {
				    if ((((data || 0).resultCode || 0) == 'OK') && data.resultObj) {
				      profile.pref = data.resultObj.contentNumber;
							if(profile.pref > 0)
				        jQuery('#numero_preferiti').text(profile.pref);
				      updateProfile();
				    }
			  	}
			  });
			}
			function isLogged() {
				return (jQuery.cookie(sessionCookieName)) ? true : false;
			}
			
			function showError(error_message){
				var tt_container = ($('#loginform .input_collection').size() > 0) ? '#loginform .input_collection' : '#info_container .welcome_messages';
				// Gestione del tooltip d'errore
	      $(tt_container).qtip({
	        content: {
	          text: '<div class="tooltip-content"><p class="info">' + error_message + '</p></div>'
	        },
	        position: {
	          my: 'top center',
	          at: 'bottom center',
	          target: $(tt_container),
						adjust: {
							y : (!isLogged()) ? 22 : 8
						}
	        },
	        show: {
	          event: 'trigger_error_tt',
	          effect: function(offset) {
	             $(this).fadeIn(200);
	          }
	        },
	        hide: {
	          event: 'click'
	        },
	        style: {
            tip: {
	            width: 15,
	            height: 7
            },
	          classes: 'error ui-tooltip-rounded'
	        }
	      }).trigger('trigger_error_tt');
			}
			
			function setup() { }
			
			
			return {
				inpUser: jQuery('#usercont'),
				inpPwd: jQuery('#pwdcont'),
				validateform: function() {
	        var error_string = '';
	        var error_cnt = 0;
	        
	        if( $('#user').val() == '' || $('#user').hasClass('header_input_holder') ){
	          error_cnt++;
	          error_string += messages.user + '<br />';
	          $('#usercont').addClass('err');
	        }
	        if( $('#pwd').val() == '' || $('#pwd').hasClass('header_input_holder') ){
	          error_cnt++;
	          error_string += messages.pwd + '<br />';
	          $('#pwdcont').addClass('err');
	        }
	        
	        if(error_cnt>0){
	          showError(error_string);
	          return false;
	        } else {
	          jQuery('#usercont').removeClass('err');
	          jQuery('#pwdcont').removeClass('err');
	          return true;
	        }
	      },
				login: function(o) {
					options = o || {};
					if (window.ENABLE_LOGIN && window.ENABLE_LOGIN == 'Y') {
				    jQuery('#submitcont').css('visibility','hidden');
				    jQuery('#loginwait').show();
				    var remember = ($('#rememberme').attr('checked')) ? 'Y' : 'N';
				    var dataObj = (options.silent) ? { remember: 'Y' } : { username: jQuery('#user').val(), password: jQuery('#pwd').val(), remember: remember, forceLogin: 'Y' };
				    request({
				      url: _https_url+JSON_DOMAIN+'Login',
				      data: dataObj,
				      dataType: (ISDEV) ? 'json': 'jsonp',
				      error: function(XMLHttpRequest, textStatus, errorThrown) {
                jQuery('#loginwait').hide();
                jQuery('#submitcont').css('visibility','visible');
				        showError('Errore durante il login');
				        jQuery('#usercont').addClass('err');
				        jQuery('#pwdcont').addClass('err');
				      },
				      success: function(data) {
				        jQuery('#loginwait').fadeOut(250);
				        if (((data || 0).resultCode || 0) == "OK") {
				          if (jQuery.cookie(mediasetCookieName))
				            jQuery.cookie(mediasetCookieName, null, {path: '/', domain: prodCookieDomain}); // consumazione cookie area clienti
				          profile.nome = data.message;
				          profile.pref = -1;
									profile.userType = data.resultObj.userType;
									profile.commercialOffer = data.resultObj.commercialOffers ? data.resultObj.commercialOffers : '' ;
				          updateProfile();
				          if (data.resultObj.isQa)
				            $.jStorage.set('isQa', data.resultObj.isQa);
				          
				          /*if ((data.resultObj || 0).pageUrl) // gestisco redirect
				            document.location.href = data.resultObj.pageUrl;*/
				          
				          if (((data.resultObj || 0).isFirstAccess || 0) == 'Y') {
				            document.location.href = '/coldstart';
				          } else if ($('input[name="cb"]').is(':checked')) {
				          	  var goUrl= "/attiva-promo";
				        	  window.location = goUrl;
				          } else if (options.silent) {
				          	MDS.user.setHeader();
				          } else {
				          	document.location.href = document.location.href;
				          }
				        } else {
				          jQuery('#loginwait').hide();
				          jQuery('#submitcont').css('visibility','visible');
									
				          // cancello eventuale cookie loggato se non sono state accettate le Terms & Condition
				          if (data.resultCode == "KO_TC") {
				            jQuery.cookie(sessionCookieName, null, {path: '/', domain: prodCookieDomain});
				            jQuery.cookie(mediasetCookieName, null, {path: '/', domain: prodCookieDomain});
										showError(data.errorDescription);
				            jQuery('#usercont').addClass('err');
				            jQuery('#pwdcont').addClass('err');
				          }
				          if ((((data.resultObj || 0).pageUrl || 0) != '') && FLAG_ATTIVA_REDIRECT_CONSENSO == 'Y') {
				            document.location.href = data.resultObj.pageUrl;
				          } else if ((((data.resultObj || 0).pageUrl || 0) != '') && data.resultObj.pageUrl && FLAG_ATTIVA_REDIRECT_CONSENSO == 'N') {
				            document.location.href = document.location.href;
				          } else {
				            showError(data.errorDescription);
				            jQuery('#usercont').addClass('err');
				            jQuery('#pwdcont').addClass('err');
					          // controllo se necessario mostrare errore promo
				            if (data.resultObj.msgPromo && data.resultObj.msgPromo != '') {
				            	$.colorbox({html: '<p>'+data.resultObj.msgPromo+'</p>', width: 520, height: 150});
				            }
				          }
				          if (options.silent && ((data.resultCode || 0) == "KO") && ((data.resultObj || 0).pageUrl || 0) != undefined && data.resultObj.pageUrl == '' && data.resultObj.isFirstAccess != undefined && data.resultObj.isFirstAccess == '') {
			              showError(data.errorDescription);
			              showLogin();
			              $('#loginform #subm').click(function() {
			                // cancello il cookie di login
			                jQuery.cookie(sessionCookieName, null, {path: '/', domain: prodCookieDomain});
			              });
			            }
				        } 
				      }
				    });
				  } else {
				  	showLogin();
				    this.displayLoginStop();
				  }
				},
				setHeader: function() {
					if (jQuery.cookie(mediasetCookieName) || (jQuery.cookie(sessionCookieName) && !jQuery.cookie(profileCookieName))) {
						this.login({silent: true});
					} else {
				    if (jQuery.cookie(sessionCookieName) && jQuery.cookie(profileCookieName)){
				      buildLoggedHeader();
				    } else {
				      jQuery.cookie(profileCookieName, null, {path: '/'});
				      jQuery.cookie(sessionCookieName, null, {path: '/'});
							
              $("#user").placeholder({'label':'Username','customClass':'header_input_holder'});
              $('#pwd-default').focus(function(e) {
              	e.preventDefault();
              	$(this).hide();
              	$('#pwd').show().removeClass('header_input_holder').get(0).focus();
              });
              $('#pwd').blur(function() {
              	if ($(this).val() == '') {
              		$(this).hide().addClass('header_input_holder');
              		$('#pwd-default').show();
              	}
              });
              jQuery('#subm').click(function(e) { // assegnazione delle funzioni di validazione dei dati inseriti nei campi
								e.preventDefault();
                $('#subm').attr('disabled', 'true'); //blocca il pulsante di login
                setTimeout(function(){
                  $('#subm').removeAttr('disabled');
                }, 3000);
                if (MDS.user.validateform()) {
                  jQuery('#usercont').removeClass('err');
                  jQuery('#pwdcont').removeClass('err');
                  jQuery('#promoid').removeClass('err');
                  MDS.user.login();
                }
              });
              
              if($('#promocode label').size()){ //Inizializzazione Qtip per label promo
                $('#promocode label').qtip({
                  content: {
                    text: '<div class="tooltip-content"><p class="info"><strong>Inserisci nuovo codice promozionale</strong><br/><br/>Se sei in possesso di un codice promozionale spunta l\'opzione "inserisci nuovo codice promozionale", inserisci le tue username e password e clicca su ENTRA.<br/>Ti verrà successivamente chiesto di inserire il codice promozionale.<br/><br/>Se non sei ancora registrato procedi subito con la registrazione e, successivamente, spunta l\'opzione "inserisci nuovo codice promozionale" e inserisci username e password nella finestrella in alto.</p></div>'
                  },
                  position: {
                    my: 'top center',
                    at: 'bottom center',
                    target: $('#promocode'),
                    adjust: {
                      x: 64,
                      y: -5
                    }
                  },
                  show: {
                    event: 'mouseenter',
                    effect: function(offset) {
                       $(this).fadeIn(200);
                    }
                  },
                  style: {
                    tip: {
                      width: 15,
                      height: 7,
                      offset: 95
                    },
                    classes: 'qtip_header ui-tooltip-rounded'
                  }
                });
              }
				    }
				  }
					jQuery('#loginbarcont').css({'visibility':'visible'});
				},
				logout: function(event, deleteCookies) {
				  if (event) event.preventDefault();
				  deleteCookies = deleteCookies || true;
				  
				  if ($('#player').size() && window.sendStopEvent) // se c'è il player lancio la stopcontent
						sendStopEvent();
				  
					request({
					  type: 'POST',
					  url: JSON_DOMAIN+'Logout',
					  data: { channel: 'PCTV' },
					  dataType: 'json',
					  success: function(data) {
					    if (data.resultCode == 'OK' && deleteCookies) {
							  jQuery.cookie(profileCookieName, null, {path: '/'}); // cookie profilo
							  jQuery.cookie(sessionCookieName, null, {path: '/', domain: prodCookieDomain}); // cookie sessione BE
				        jQuery.cookie(mediasetCookieName, null, {path: '/', domain: prodCookieDomain}); // cookie mediaset
				        jQuery.cookie(MDS.bookmarks.getCookieName(), null, {path: '/'}); // cookie bookmarks utente
				        $.jStorage.flush(); // svuoto la var di sessione
								window.onbeforeunload = null;
								updateVolume();
				        window.location.reload(); // ricarico la pagina
					    }
					    else {
					      showError(data.errorDescription);
					    }
					  },
					  error: function(XMLHttpRequest, textStatus, errorThrown) {
						  showError(textStatus);
					  }
					})
				},
				isLogged: isLogged,
				showStopLogin: function() {
				  this.inpUser.addClass('err');
				  this.inpPwd.addClass('err');
				  showError('Servizio al momento non disponibile. Riprova pi&ugrave; tardi');
				},
				incFav: function() { // incrementa il contatore dei preferiti e aggiorna il profilo
				  if (profile.pref < 30) {
			      profile.pref++;
			      $('#numero_preferiti').text(profile.pref);
			      updateProfile();
				  }   
				},
				delFav: function() { // decrementa il contatore dei preferiti e aggiorna il profilo
				  if (profile.pref > 0) {
				    profile.pref--;
						if(profile.pref > 0)
				      $('#numero_preferiti').text(profile.pref);
						else $('#numero_preferiti').empty();
				    updateProfile();
				  }   
				}, 
				setFav: function(i) { // setta il numero dei preferiti indicato 
				  if (profile) {
				  	profile.pref = i;
						if(profile.pref > 0)
				      $('#numero_preferiti').text(i);
				    updateProfile();
				  }   
				}
			}
		}(),
		
		player: function() {
			return {
				updateVolume: function(){
					try {
						setVolume(slPlayer.mpPageBridge.getVolume());
					} catch(e){
						log('errore su tentativo setVolume');
					}
				}
			}
		}(),
		
		init: function() {
			if (MDS.user.isLogged()) {
				MDS.bookmarks.init();
			}
			$(document).ready(function() {
				MDS.user.setHeader();
			});
		}
	}
}()
MDS.init();
