var $j = jQuery.noConflict();

var _effects = { "fade": 2000 };
var _pagelocked = false;
var _tooltip_timer = null;
var _tooltip_video = null;

var jsonVideoCorrelati = null;

var SCROLL_MODE_REL = 0;
var SCROLL_MODE_ABS = 1;
var IMAGE_UNAVAIL = "/res/img/138_nothumb.jpg";
var TOOLTIP_DELAY = 1000; //1000; //ritardo per la comparsa del tooltip (ms.)

//to set last slide position
var _cur_typ, _cur_ses, _cur_cat, _cur_ord, _cur_pos;

function _dbg(key, args, msg) {
  try {
    if ( console && console.log ) {
      console.log(key + ': ("' + args.join('","') + '")' + ( msg ? " [" + msg + ']' : ' []' ) );
    }
  } catch (exception) {
    //install firebug
  }
}

function idModulo(_id) {
  _id = _id % 1000;
  if (_id < 10)
    return "00" + _id;
  else if (_id < 100)
    return "0" + _id;
  else
    return _id;
}

function idPadded(_id) {
  if (_id < 10)
    return "00" + _id;
  else if (_id < 100)
    return "0" + _id;
  else
    return _id;
}

function gotoPage(keyword_search,page,scope,sort) {
  var searchpage = '/ricerca/ricerca.shtml'; 
  var src = searchpage + '?q=' + keyword_search + '&scope=' + scope;

  if(sort!='' && sort!='undefined')
    src += '&sort='+sort;

  src += '&numPage='+page;

  document.location.href = src;
}

function socialnetworkURL(socialnetwork){
  var snURL = '';
  //alert('sn:'+socialnetwork)
  switch (socialnetwork){
    case 'oknotizie':
       return bmkURL('http://oknotizie.alice.it/post.html.php?','url',document.location.href, 'title', document.title);
       break;
    case 'microsoftlive':
       return bmkURL('https://favorites.live.com/quickadd.aspx?marklet=1&','url', document.location.href , 'title', document.title);
       break;
    case 'delicious':
       return bmkURL('http://del.icio.us/save?','url', document.location.href, 'title', document.title);
       break;
    case 'digg':
       return bmkURL('http://digg.com/submit?','url', document.location.href, 'title', document.title);
       break;
    case 'twitter':
       var twitterUrl =  'http://twitter.com/home?status='+document.title+': '+document.location.href;
       return twitterUrl;
       break;
    case 'facebook':
       return bmkURL('http://www.facebook.com/sharer.php?', 'u', document.location.href);
       break;
    case 'google':
       return bmkURL('http://www.google.com/bookmarks/mark?op=edit&','bkmk', document.location.href,'title', document.title);
       break;
    case 'badzu':
       if(navigator.userAgent.indexOf('Safari') >=0){
          Q=getSelection();
       }
       else{
          Q=document.selection?document.selection.createRange().text:document.getSelection();
       }
       var badzuUrl = 'http://www.badzu.net/submit?action=it&segnalazione='+encodeURIComponent(Q)+'&link='+encodeURIComponent(location.href)+'&title='+encodeURIComponent(document.title);
       return badzuUrl
    break;
    case 'reddit':
       return bmkURL('http://reddit.com/submit?','url', document.location.href, document.title);
       break;
    case 'technorati':
       return bmkURL('http://technorati.com/faves?','add', document.location.href, document.title);
       break;
    case 'yahoo':
       return bmkURL('http://bookmarks.yahoo.com/toolbar/savebm?','u', document.location.href, document.title);
       break;
  }
}

/*function sharingMailTo() {
  var tit = document.title;
  var domaininvia='www.video.mediaset.it';
  var urlinvia=document.location.href;
  var subjPrefix="Video su "+domaininvia+": ";
  var bodyPrefix="\n\n Puoi trovare questo video all'indirizzo:\n";
  var subj=escape(subjPrefix+tit);
  var body=escape('Video su www.video.mediaset.it: "'+tit+'"'+bodyPrefix+urlinvia);
  var mail =  'mailto:?subject='+subj+'&body='+body;
  return mail;
}*/

function sharingMailTo() {
  var tit = document.title;
  var domaininvia='www.video.mediaset.it';
  var urlinvia=document.location.href;
  var subjPrefix="Video su "+domaininvia+": ";
  var bodyPrefix="VIDEO MEDIASET  -  La tv del giorno dopo\n\nUn amico ti invia questo video da Video Mediaset:\n";
  var bodyPostfix="\nPer vedere il video clicca sul link oppure copialo nel tuo browser internet\nBuona visione!\n\n\n----------------------------------------------\nTutti gli altri video su http://"+domaininvia+"\nPuoi rivedere tutti i giorni i migliori video dei tuoi programmi preferiti: Grande Fratello, Iene, Chiambretti, Amici, Uomini e Donne, Beautiful e molti altri.\n----------------------------------------------";
  var subj=escape(subjPrefix+tit);
  var body=escape(bodyPrefix+urlinvia+bodyPostfix);
  var mail =  'mailto:?subject='+subj+'&body='+body;
  return mail;
}

function lockPage(pagelocked) {
  _pagelocked = pagelocked;
  _dbg("lockPage()", [pagelocked], "");
}

function lockItem(_obj) {
  $j('a', _obj).each(function(i) {
    $j(this).unbind('click').bind('click', function() {
      if (_pagelocked == true) {
        //alert('Guarda la pubblicità prima di cambiare canale!');
        return false;
      } else {
        return true;
      }
    });
  });
}

function bmkURL(bookmark, paramUrl, valueUrl, paramTitle, valueTitle) {
  var snURL = bookmark +  paramUrl +'=' + encodeURIComponent(valueUrl) + '&'+ paramTitle +'=' + encodeURIComponent(valueTitle);
  return snURL;
}

function shareURL(socialnetwork) {
  var snURL = socialnetworkURL(socialnetwork)
  window.open(snURL);
}

function getRelatedVideos(id) {
  //jsonVideoCorrelati = {"message":"guid(00000000030000500001000000000000): no document found","errorCode":61};
  var idPadded = "" + id;
  while (idPadded.length < 12) idPadded = "0" + idPadded;
  var urlCorrelati = "http://91.211.156.138/Mediaset/related?guid=00000000040000200001" + idPadded + "&order=iev&maxitems=i:0;e:0;v:5&callback=?";
  $j.ajaxSetup({ scriptCharset: "iso-8859-1" }); //forced default because page is utf-8 but expert systems returns iso-8851-1
  $j.getJSON(urlCorrelati, function(data) {
    jsonVideoCorrelati = data;
  });
}

$j.fn.removeTextOnFocus = function(txt) {
  return this
      .data('defaultText', txt)
      .bind('focus blur', function(e) {
        var v = $j(this).val();
        if ( v == $j(this).data('defaultText') && e.type == 'focus' ) {
          $j(this).val('');
        } else if ( v == '' && e.type == 'blur' ) {
          $j(this).val( $j(this).data('defaultText') );
        }
      });
};

//begin initTooltips()
function initTooltips() {
  _dbg("initTooltips()", [], "init tooltips: " + $j(".cont-video").length);
  $j(".cont-video").each(function(i) {
    initTooltip($j(this));
  });
}
//end initTooltips()

//begin initTooltip()
function initTooltip(_obj) {
  $j(_obj).hover(function() {
    _tooltip_video = $j(this);
    clearTimeout(_tooltip_timer);
    _tooltip_timer = setTimeout("showTooltip()", TOOLTIP_DELAY);
  },function() {
    hideTooltip();
  });
}
//end initTooltip()

//begin hideTooltip()
function hideTooltip() {
  _dbg("hideTooltip()", [], "tooltip active # " + $j('#tooltip').length);
  _tooltip_video = null;
  clearTimeout(_tooltip_timer);
  _tooltip_timer = null;
  var _tt = $j('#tooltip').each(function(i) {
    $j(this).hide().remove();
  });
}
//end hideTooltip()

//begin showTooltip()
function showTooltip() {
  if (_tooltip_video == null) hideTooltip();

  var _obj = $j(_tooltip_video);
  var _tmp = _obj.attr('id').split('|');
  var _url = '/videos/' + _tmp[1] + '/' + idModulo(_tmp[2]) + '/' + idPadded(_tmp[2]) + '/metainfo.sxml?view=true';

  _dbg("showTooltip()", [_obj.attr('id'), _url], "");

  $j.ajax({
    type: "GET",
    url: _url,
    cache: false,
    dataType: "xml",
    success: function(data) {
      //alert(data);
      if (_tooltip_video != null) {
        var videoType = $j("video > type", data).text();
        var videoTypeLabel = "Video Clip";
        if(videoType != 'clip'){
          videoTypeLabel = "Full episode";
        }
        var expireDateValue = $j("video > expire-date", data).text();
        var expireDateTag = "";
        if(expireDateValue != null && expireDateValue != "" && expireDateValue != "31/12/9999"){
          expireDateTag = '<p class="infoextra">Expire date: <strong>' + expireDateValue + '</strong></p>';
        }
        var _of = $j(_obj).offset();
        var _tt = $j('<div id="tooltip">' +
          '<div id="infotooltip">' +
          '<h4>' + $j("video > title", data).text() + '</h4>' +
          '<p>' + $j("video > short-description", data).text() + '</p>' +
          '<p class="brand">' + $j("video > brand-info > brand-description", data).text() + '</p>' +
          '<p class="infoextra">Video: <strong>' + videoTypeLabel + '</strong></p>' +
          '<p class="infoextra">In Tv: <strong>' + $j("video > production-date", data).text() + '</strong></p>' +
          '<p class="infoextra">Durata: <strong>' + $j("video > duration", data).text() + '</strong></p>' +
          '<p class="infoextra">Visto: <strong>' + ($j("video > visto", data).text() || " 0 ") + ' volte</strong></p>' +
          expireDateTag +
          '<div class="mediavoti"><p>Media voti:</p><img src="/res/img/mediavoti_' + ($j("video > rating", data).attr("stars") || '0') + '.png"/></div>' +
          '</div>' +
          '</div>')
        .hide()
        .appendTo('#body2')
        .css({ left: (_of.left + 118) + 'px', top: (_of.top + 0) + 'px' })
        .fadeIn(50);
      }
    }
  });
}
//end showTooltip()

$j(function() {

  //begin onload()
  _dbg("onload()", [], "");

  //inizializzazioni generali
  initPageMenu();
  initPageSearch();
  initTooltips();

  //inizializzazioni specifiche secondo il contenuto della pagina
  if ($j('div.videoNavigation').length > 0) {
    //
     _dbg("onload()", [], "video page");
    initTabs();
    lockItem($j('#spalla'));
    initVideoNavigation();
    initEmail();
    initVideoCorrelati();
  }
  if ($j('div.direttewebNavigation').length > 0) {
     _dbg("onload()", [], "live page");
    initTabs();
  }
  if ($j('div.pageNavigation').length > 0) {
     _dbg("onload()", [], "archive page navigation");
    initPageNavigation();
  }
  if ($j('div.pageNavigationFep').length > 0) {
     _dbg("onload()", [], "archive page navigation Fep");
    initPageNavigationFep();
  }
  //end onload()

  //begin initTabs()
  function initTabs() {
    _dbg("initTabs()", [], "");

    $j("#tabs > ul > li > a").each(function(i) {
      $j(this).click(function() {
        if ($j(this).parent().hasClass('current')) return false;
        var curChildIndex = $j(this).parent().prevAll().length + 1;
        $j(this).parent().parent().children('.current').removeClass('current');
        $j(this).parent().addClass('current');
        $j(this).parent().parent().parent().parent().next('.tabs-cont').children('.current').fadeOut(100,function() {
          $j(this).removeClass('current');
          $j(this).parent().children('div:nth-child('+curChildIndex+')').fadeIn(100,function() {
            $j(this).addClass('current');
          });
        });
        return false;
      });
    });
    if ($j('div#commenti').length > 0) {
      $j('div#tabs > ul > li#tabber-fragment2').css({ display: "block" });
    }
  }
  //end initTabs()

  //begin initVideoCorrelati()
  function initVideoCorrelati() {
    _dbg("initVideoCorrelati", [], "init related videos: " + $j('#box-correlati').length);
    if ((jsonVideoCorrelati != undefined) && (jsonVideoCorrelati != null) && ($j('div.box-correlati').length > 0)) {
      renderVideoCorrelati();
    }
  }
  //end initVideoCorrelati()

  //begin initPageNavigation()
  function initPageNavigation() {
    _dbg("initPageNavigation()", [], "");
    
    $j(".etichetta-sub").each(function(i) {
      var objInput = $j(this).children().children().children().children('#pageNum');
      var maxPage  = $j(this).attr('maxpage');
      var numPage  = eval(objInput.attr('value'))
      var prevPage = numPage - 1;
      var nextPage = numPage + 1;
      var namePage = objInput.attr('section');

      $j(this).children().children().children('.current').children().attr('href', namePage + '-' + maxPage + '.html');
      if (prevPage > 0) {
        $j(this).children().children().children('.prev').children().attr('href', namePage + '-' + prevPage + '.html');
      } else {
        $j(this).children().children().children('.prev').children().hide();
      }

      if (nextPage <= maxPage) {
        $j(this).children().children().children('.next').children().attr('href', namePage + '-' + nextPage + '.html');
      } else {
        $j(this).children().children().children('.next').children().hide();
      }

      $j(this).children().submit(function() {
        var customPage = eval(objInput.attr('value'));
        if ((customPage > 0) && (customPage <= maxPage)) {
          document.location.href = namePage + '-' + customPage + '.html';
        } else {
          //alert('Numero di pagina non valido')
        }
      });
    });
  }
  //end initPageNavigation()

  //begin initPageMenu()
  function initPageMenu() {
    _dbg("initPageMenu()", [], "");

    var contentmenu = $j('#main').attr('class');
    var divsubmenu = '#fascia-menu > ul > li#menu-' + contentmenu;
    var submenuclass = $j(divsubmenu).attr('class') + ' active';
    $j(divsubmenu).attr('class', submenuclass);

    _dbg("initPageMenu()", [contentmenu], "");
    if (contentmenu == '') return;

    if(contentmenu == 'episodi-interi') {
      var submenuclass = $j('#fascia-menu > ul > li > a.menu-episodi-interi').attr('class') + ' active';
      $j('#fascia-menu > ul > li > a.menu-episodi-interi').attr('class', submenuclass);
    } else if (contentmenu == 'novita') {
      var submenuclass = $j('#fascia-menu > ul > li > a.menu-novita').attr('class') + ' active';
      $j('#fascia-menu > ul > li > a.menu-sub-novita').attr('class', submenuclass);
    } else if (contentmenu == 'piu-visti') {
      var submenuclass = $j('#fascia-menu > ul > li > a.menu-piu-visti').attr('class') + ' active';
      $j('#fascia-menu > ul > li > a.menu-piu-visti').attr('class', submenuclass);
    } else if (contentmenu == 'programmi') {
      var submenuclass = $j('#fascia-menu > ul > li > a.menu-programmi').attr('class') + ' active';
      $j('#fascia-menu > ul > li > a.menu-programmi').attr('class', submenuclass);
    } else if (contentmenu == 'videonews') {
      var submenuclass = $j('#fascia-menu > ul > li > a.menu-videonews').attr('class') + ' active';
      $j('#fascia-menu > ul > li > a.menu-videonews').attr('class', submenuclass);
    } else if(contentmenu == 'dirette-web') {
      var submenuclass = $j('#fascia-menu > ul > li > a.menu-dirette-web').attr('class') + ' active';
      $j('#fascia-menu > ul > li > a.menu-dirette-web').attr('class', submenuclass);
    }
  }
  //end initPageMenu()

  //begin initPageSearch()
  function initPageSearch() {
    _dbg("initPageSearch()", [], "");

    $j('.query').removeTextOnFocus('cerca video');
    
    $j('.query:first').focus();

    $j('.query').keydown(function(event) {
      if (event.keyCode == 13) {
        $j(this).blur();
        $j('.goSearchTop').click();
        return false;
      }
    });

    $j('.goSearchTop').click(function() {
      // Preform an ajax search
      var query = escape($j('.query').val());
      var scope = 'www.videomediaset.it';
      var sort = 'date';
      var from = $j('#from').val();
      var to = $j('#to').val();

      if (from!='' || to!='')
        query += '&dtrange=';
      if (from!='')
        query += from;
      if (from!=to)
        query += '-';
      if (to > from)
        query += to;

      gotoPage(query,1,scope,sort);
    });
  }
  //end initPageSearch()

  //begin initEmail()
  function initEmail() {
    if ($j('div#email').length > 0) {
      var mail = sharingMailTo();
      $j('div#email > a').attr('href', mail);
    }
  }
  //end initEmail()

 //begin initPageNavigationFep()
  function initPageNavigationFep() {
  	_dbg("initPageNavigationFep()", [], "");
   	
   	$j("div.boxvideo").each(function(i) {
   		var _box = $j("div.box-contenuti-video-quattro > div.box-contenuti-video", $j(this))
      		showFasciaVideoBacini($j(this), _box, 1, SCROLL_MODE_ABS)
   	});

  }
  //end initPageNavigationFep()

  //begin initVideoNavigation()
  function initVideoNavigation() {

    try {
      var _href = document.location.href;
      _cur_typ = new RegExp("#t([efc])-").exec(_href)[1];
      _cur_ses = parseInt(new RegExp("-s([0-9]+)-").exec(_href)[1]);
      _cur_cat = parseInt(new RegExp("-c([0-9]+)-").exec(_href)[1]);
      _cur_ord = parseInt(new RegExp("-o([0-9]+)-").exec(_href)[1]);
      _cur_pos = parseInt(new RegExp("-p([0-9]+)").exec(_href)[1]);
      //alert("typ: " + _cur_typ + ", ses: " + _cur_ses + ", cat: " + _cur_cat + ", ord: " + _cur_ord + ", pos: " + _cur_pos);
    } catch (exception) {
      //alert(exception.message);
    }
    

    //init box editoriali
    var _eti_bed = $j("#edit-etichetta");
    var _box_bed = $j("#edit-container");
    if (_box_bed.length > 0) {
      _box_bed.data("max", $j(".cont-video-big", _box_bed).length);
      _box_bed.data("pos", 1);
      _box_bed.data("typ", "e");

      _dbg("initVideoNavigation()", [], "init box editoriali");

      $j("ul.pagg-sub > li.prev > a", _box_bed).click(function(e) {
        _own = $j(this).parent().parent().parent().parent();
        editScroll(_eti_bed, _box_bed, -1, SCROLL_MODE_REL);
        return false;
      });
      $j("ul.pagg-sub > li.next > a", _box_bed).click(function(e) {
        _own = $j(this).parent().parent().parent().parent();
        editScroll(_eti_bed, _box_bed, +1, SCROLL_MODE_REL);
        return false;
      });
      $j('ul.pagg-sub > li.curr > input', _box_bed).change(function() {
        editScroll(_eti_bed, _box_bed, $j(this).val(), SCROLL_MODE_ABS);
        return false;
      });
      
      editScroll(_eti_bed, _box_bed, 0, SCROLL_MODE_REL);
    }

    //init box full episode
    var _eti_fep = $j("#fep-etichetta");
    var _box_fep = $j("#fep-container");
    if (_box_fep.length > 0) {
      var _max_fep = $j("div.box-container", _box_fep).length;
      var _pos_fep = (_cur_typ == "f" && _cur_ses > 0) ? _cur_ses : 1; //da leggere dall'url

      _dbg("initVideoNavigation()", [], "init box full episode");

      _box_fep.data("max", _max_fep);
      _box_fep.data("pos", _pos_fep);
      _box_fep.data("typ", "f");

      //
      var _sel_fep = $j("div.season-container:hidden", _eti_fep);
      if (_sel_fep.length > 0 && _max_fep > 1) {
        $j("ul.pagg > li.prev > a", _sel_fep).click(function(e) {
          seasonScroll(_eti_fep, _box_fep, -1, 0);
          return false;
        });
        $j("ul.pagg > li.next > a", _sel_fep).click(function(e) {
          seasonScroll(_eti_fep, _box_fep, +1, 0);
          return false;
        });
        $j("ul.pagg > li.season-selector > a", _sel_fep).each(function(i) {
          $j(this).click(function(e) {
            seasonScroll(_eti_fep, _box_fep, i + 1, 1);
            return false;
          });
        });
        _sel_fep.show();
      }
      seasonScroll(_eti_fep, _box_fep, _pos_fep, 1);
    }

    //init box clip arrow and aperture
    if ($j('body').hasClass('video-fep')) {
      $j('#clip-etichetta > a').addClass('open').html('Apri').attr('title', 'Apri');
      $j('#clip-etichetta').addClass('close');
    } else {
      $j('#clip-etichetta > a').addClass('close').html('Chiudi').attr('title', 'Chiudi');
      $j('#clip-etichetta').addClass('open');
    }

    $j('#clip-etichetta > a').bind('click', function() {
      _hdl = $j(this);
      if (_hdl.hasClass('close')) {
        _hdl.removeClass('close').addClass('open').html('Apri').attr('title', 'Apri');
        $j('#clip-etichetta').removeClass('open').addClass('close');
        $j('#clip-container').hide();
      } else {
        _hdl.removeClass('open').addClass('close').html('Chiudi').attr('title', 'Chiudi');
        $j('#clip-etichetta').removeClass('close').addClass('open');
        $j('#clip-container').show();
      }
      return false;
    });

    //init box clip
    var _eti_clip = $j("#clip-etichetta");
    var _box_clip = $j("#clip-container");
    if (_box_clip.length > 0) {
      var _max_clip = $j("div.box-container", _box_clip).length;
      var _pos_clip = (_cur_typ == "c" && _cur_ses > 0) ? _cur_ses : 1; //da leggere dall'url

      _dbg("initVideoNavigation()", [], "int box clip");

      _box_clip.data("max", _max_clip);
      _box_clip.data("pos", _pos_clip);
      _box_clip.data("typ", "c");

      //
      var _sel_clip = $j("div.season-container:hidden", _eti_clip);
      if (_sel_clip.length > 0 && _max_clip > 1) {
        $j("ul.pagg > li.prev > a", _sel_clip).click(function(e) {
          seasonScroll(_eti_clip, _box_clip, -1, 0);
          return false;
        });
        $j("ul.pagg > li.next > a", _sel_clip).click(function(e) {
          seasonScroll(_eti_clip, _box_clip, +1, 0);
          return false;
        });
        $j("ul.pagg > li.season-selector > a", _sel_clip).each(function(i) {
          $j(this).click(function(e) {
            seasonScroll(_eti_clip, _box_clip, i + 1, 1);
            return false;
          });
        });
        _sel_clip.show();
      }
      seasonScroll(_eti_clip, _box_clip, _pos_clip, 1);
    }
  }
  //end initVideoNavigation()

  //begin editScroll()
  //_obj1: container etichetta
  //_obj2: container season
  //_inc : incremento o valore assoluto
  //_mode: incremento = 0; valore assoluto = 1;
  function editScroll(_obj1, _obj2, _inc, _mode) {
    var _eti = $j(_obj1);
    var _box = $j(_obj2);
    var _pos = _box.data("pos");
    var _max = _box.data("max");
    var _typ = _box.data("typ");
    var _new = (_mode == 0) ? (_pos + _inc) : (_inc);
    if (_new < 1) _new = 1;
    if (_new > _max) _new = _max;
    _pos = _new;
    _box.data("pos", _pos);
    if(_inc==0)
    	_pos = (_cur_typ == _typ && _cur_pos > 0) ? _cur_pos : _new;  //da leggere dall'url
   
    _dbg("editScroll()", [_box.attr('id'), _inc, _pos, _max], "");

    $j("div.box-contenuti-video > div.scroll", _box).animate({ left: ((1 - _pos) * 688) + 'px'});
    _nav = $j("div.etichetta-sub > ul.pagg-sub", _box);
    if (_pos == 1) {
      $j("li.prev > a", _nav).hide();
    } else {
      $j("li.prev > a", _nav).show();
    }
    if (_pos == _max) {
      $j("li.next > a", _nav).hide()
    } else {
      $j("li.next > a", _nav).show()
    }
    $j("li.curr", _nav).html('<input type="text" name="textfield" id="textfield" value="' + _pos + '"> di ' + _max);
    $j('input', _nav).keydown(function(event) {
      if (event.keyCode == 13) {
        $j(this).blur();
        var _val = _pos;
        try {
          _val = parseInt($j(this).val());
        } catch (exception) {
          //invalid number
        }
        if (_val > _max) _val = _max; //the order of this two lines is important
        if (_val < 1) _val = 1; //the order of this two lines is important
        editScroll(_eti, _box, _val, SCROLL_MODE_ABS);
        return false; //required
      }
    });
  }
  //end editScroll()

  //begin seasonScroll()
  //_obj1: container etichetta
  //_obj2: container season
  //_inc : incremento o valore assoluto
  //_mode: incremento = 0; valore assoluto = 1;
  function seasonScroll(_obj1, _obj2, _inc, _mode) {
    var _eti = $j(_obj1);
    var _box = $j(_obj2);
    var _max = _box.data("max");
    var _pos = _box.data("pos");
    var _typ = _box.data("typ");
    var _new = (_mode == 0) ? (_pos + _inc) : (_inc);

    _dbg("seasonScroll()", [_eti.attr('id'), _box.attr('id'), _new, _max], "typ: " + _typ);

    if ((_new > 0) && (_new <= _max)) {
      _box.data("pos", _new);
      // pannello box
      var _tohide = $j("> div:eq(" + (_pos - 1) + ")", _box).hide();
      var _toshow = $j("> div:eq(" + (_new - 1) + ")", _box).show();
			//store data
      _toshow.data("typ", _typ);
      _toshow.data("ses", _new);
      //season selector
      var _nav = $j("div.season-container > ul.pagg", _eti);
      $j("> li.season-selector", _nav).each(function(i) {
        var j = i + 1;
        var k = Math.abs(_new - j);
        if (((_new == 1 || _new == _max) && (k > 2)) || ((_new > 1 && _new < _max) && (k > 1))) {
          $j(this).hide();
        } else {
          $j(this).show();
        }
      });
      $j("> li:eq(" + _pos + ") > a", _nav).removeClass("active");
      $j("> li:eq(" + _new + ") > a", _nav).addClass("active");
      if (_new == 1) {
        $j("li.prev > a", _nav).hide();
      } else {
        $j("li.prev > a", _nav).show();
      }
      if (_new == _max) {
        $j("li.next > a", _nav).hide()
      } else {
        $j("li.next > a", _nav).show()
      }
      //show season panel
      showSeason(_toshow);
    }
  }
  //end seasonScroll()

  //begin showSeason()
  function showSeason(_obj) {
    var _box = $j(_obj);
    var _typ = _box.data("typ");
    var _ses = _box.data("ses");
    var _box_id = _box.attr('id').split("|");
    _dbg("showSeason()", _box_id, "typ: " + _typ + ", ses: " + _ses);
    $j("> div", _box).each(function(i) {
    	var _sub = $j(this);
			//store data
    	_sub.data("typ", _typ);
    	_sub.data("ses", _ses);
    	_sub.data("cat", i + 1);

	//show showbrand
      showSubBrand(_sub);
    });
  }
  //end showSeason()

  //begin showSubBrand()
  function showSubBrand(_obj) {
    var _box = $j(_obj);
    //read data
    var _typ = _box.data("typ");
    var _ses = _box.data("ses");
    var _cat = _box.data("cat");
    var _ord = _box.data("ord");
    //get strip to show
    var _tmp = _box.attr('id').split("|");
    var _box_id = _tmp[1] + "|" + _tmp[2] + "|" + _tmp[3];
    var _box_ord = "";
      /*alert('_cur_typ:'+_cur_typ+' _typ:'+_typ)
	alert('_cur_ses:'+_cur_ses+' _ses:'+_ses)
	alert('_cur_cat:'+_cur_cat+' _cat:'+_cat)
	alert('_cur_ord:'+_cur_ord+' _ord:'+_ord)*/
	
    _ord = (_cur_typ == _typ && _cur_ses == _ses && _cur_cat == _cat && _cur_ord>0) ? _cur_ord : 1;  //da leggere dall'url
    
    switch (_ord) {
      case 1: _box_ord = "novita"; break;
      case 2: _box_ord = "visti"; break;
      case 3: _box_ord = "votati"; break;
      default: _ord = 1; _box_ord = "novita";
    }

    var _sub_id = "fascia-video|" + _box_id + "|" + _box_ord;

    _dbg("showSubBrand()", [], "typ: " + _typ + ", ses: " + _ses + ", cat: " + _cat + ", ord: " + _ord + ", id: " + _sub_id);

    $j("div.box-contenuti-video-quattro > div.box-contenuti-video", _box).each(function(i) {
	var _con = $j(this);
        //store data
    	_con.data("typ", _typ);
    	_con.data("ses", _ses);
    	_con.data("cat", _cat);
        _con.data("ord", _ord);
      if (_con.attr("id") == _sub_id) {
        _con.show();
        showFasciaVideo($j(_box), $j(_con), 0, SCROLL_MODE_REL)
      } else {
        _con.hide();
      }
    });

    //setup order selector
    var _nav = $j('div.etichetta-sub > ul.link-ipiu', _box);
    var _sel = $j('li', _nav).each(function (i) {
    	//the first <li> is not a selector
      if (i > 0) {
        var _sel = $j(this);
        var _id_sel = _sel.attr('id');
        var _id_cur = "selettore-ordine|" + _box_id + "|" + _box_ord;
        //bind click action
        $j("a", _sel).unbind('click').bind('click', function() {
			    _dbg("showSubBrand()", [_sub_id], "click order selector: " + i);
		      //store new data
    		  _box.data("ord", i);
    		  _cur_typ = _box.data("typ");
    		  _cur_ses = _box.data("ses");
    		  _cur_cat = _box.data("cat");
    		  _cur_ord = _box.data("ord");
    		  _cur_pos = 1;
          showSubBrand(_box);
          return false;
        });
        //activate current selector
        if (_id_cur == _id_sel) {
        	//this selector is the active one
          $j("a", _sel).addClass('active');
        } else {
        	//this selector is non active
          $j("a", _sel).removeClass('active');
        }
      }
    });
  }
  //end showSubBrand()

  //begin fasciaVideoScroll()
  //_obj1: container etichetta
  //_obj2: container season
  //_inc : incremento o valore assoluto
  //_mode: incremento = 0; valore assoluto = 1;
  function fasciaVideoScroll(_obj1, _obj2, _inc, _mode) {
    var _eti = $j(_obj1);
    var _box = $j(_obj2);
    var _max = parseInt(_box.data("max"));
    var _pos = parseInt(_box.data("pos"));
    var _new = (_mode == SCROLL_MODE_REL) ? (_inc + _pos) : (_inc);

    var _own = $j("div.scroll", _box);
    var _nav = $j("div.etichetta-sub > div.page-container", _eti);

    _dbg("fasciaVideoScroll()", [], "pos: " + _pos + ", max: " + _max + ", new: " + _new);

    if ((_new > 0) && (_new <= _max)) {
      var _cont_new = $j("div.cont-video-scroll:eq(" + (_new - 1) + ")", _own);
      _cont_new.html('<img class="loader" src="/res/img/video_loader.gif">');
      _own.animate({ left: ((1 - _new) * 688) + 'px'}, function() {
        if (_pos != _new) {
          var _cont_pos = $j("div.cont-video-scroll:eq(" + (_pos - 1) + ")", _own);
          _cont_pos.empty();
        }
        showFasciaVideo(_obj1, _obj2, _new, SCROLL_MODE_ABS);
      });
    }
  }
  //end fasciaVideoScroll()

  //begin showFasciaVideo()
  //_obj1: container etichetta
  //_obj2: container season
  //_inc : incremento o valore assoluto
  //_mode: incremento = 0; valore assoluto = 1;
  function showFasciaVideo(_obj1, _obj2, _inc, _mode) {

    _dbg("showFasciaVideo", [], "inc: " + _inc + ", mode: " + _mode);

    var _eti = $j(_obj1);
    var _box = $j(_obj2);

    var _id = _box.attr('id');
    var _tmp = _id.split("|");
    var _url = "/brand-info/" + _tmp[1] + "/" + _tmp[2] + "/" + _tmp[3] + "/" + _tmp[4] + ".sxml";
    var _own = $j("div.scroll", _box);
    var _nav = $j("div.etichetta-sub > div.page-container", _eti);
    var _cont = null;
    var _html = "";

    var _max = _box.data("max");
    var _pos = _box.data("pos");
    var _typ = _box.data("typ");
    var _ses = _box.data("ses");
    var _cat = _box.data("cat");
    var _ord = _box.data("ord");

    _dbg("showFasciaVideo", [_id, _inc, _mode], "max: " + _max + ", pos: " + _pos);

		//init slide if necessary
    if (_max == "" || _max == undefined) {
      _max = 0;
      //_pos = 0;
      _pos = (_cur_typ == _typ && _cur_ses == _ses && _cur_cat == _cat && _cur_ord == _ord && _cur_pos > 0) ? _cur_pos : 0; //da leggere dall'url
      _url_pos = _url + "?page=" + _pos;

      _dbg("showFasciaVideo", [_id, _url_pos], "init slide");
      _own.html('<div class="cont-video-scroll"><img class="loader" src="/res/img/video_loader.gif"></img></div>');

      $j.ajax({
        type: "GET",
        url: _url_pos,
        dataType: "xml",
        async: false,
        success: function(result) {
          _pages = $j(result).find("result").attr("totPage");
          if (_pages == 0) {
            _nav.hide();
            _own.html('<div class="cont-video-scroll"><p class="novideo">Nessun video nella categoria</p></div>');
            return;
          } else {
            _html = "";
            for (i = 1; i <= _pages; i++) _html += '<div class="cont-video-scroll"></div>';
            _own.html(_html);
            _max = _pages;
          }
        },
        error: function() {
          _dbg("showFasciaVideo", [_id, _url_pos], "error loading xml file");
          _nav.hide();
          _own.html('<div class="cont-video-scroll"><p class="novideo">Nessun video nella categoria</p></div>');
        }
      });
    }

		//load videos in page
    var _new = (_mode == SCROLL_MODE_REL) ? (_pos + _inc) : (_inc);
    if (_new > _max) _new = _max; //the order of this two lines is important
    if (_new < 1) _new = 1; //the order of this two lines is important
    _pos = _new;
    _box.data("pos", _pos);
    _box.data("max", _max);
    _url_pos = _url + "?page=" + _pos;

    _dbg("showFasciaVideo", [_id, _url_pos], "load slide: " + _pos + " of " + _max);

    _cont = $j("div.cont-video-scroll:eq(" + (_pos - 1) + ")", _own); //get container to fill
    _cont.html('<img class="loader" src="/res/img/video_loader.gif">'); //draw loading image
    _own.css({ left: ((1 - _pos) * 688) + 'px'}); //scroll

    //load xml file and draw result
    $j.ajax({
      type: "GET",
      url: _url_pos,
      dataType: "xml",
      async: false,
      success: function(result) {
        _pages = $j(result).find("result").attr("totPage");
        //alert(result);

        _dbg("showFasciaVideo", [_id, _url_pos], "this slide: typ: " + _typ + ", ses: " + _ses + ", cat: " + _cat + ", ord: " + _ord + ", pos:" + _pos);

        if (_pages == 0) {
          _nav.hide();
          _own.html('<div class="cont-video-scroll"><p class="novideo">Nessun video nella categoria</p></div>');
          return;
        } else if (_pages != _max) {
          _html = "";
          for (i = 1; i <= _pages; i++) _html += '<div class="cont-video-scroll"></div>';
          _own.html(_html);
          _max = _pages;
          _box.data("max", _max);
        }

        _cont.empty();
        $j("record", result).each(function(i) {
          var _video_id = $j("ID", this).text();
          var _video_name_brand = $j("NAME_BRAND", this).text();
          var _video_type = $j("TIPO", this).text();
          var _video_thumbnail = $j("THUMBNAIL", this).text();
          var _video_url = $j("URL", this).text() + ".html";
          var _video_title = $j("TITOLO", this).text();
          var _video_duration = $j("DURATA", this).text().substring(0, 8);
          var _video_date = $j("DATA", this).text();

          if (_video_thumbnail == "") {
            _video_thumbnail = "/res/img/138_nothumb.jpg";
          } else {
            _video_thumbnail = "/images/138" + _video_thumbnail;
          }

          if (_video_url == ".html") {
            _video_url = "#";
          } else {
          	_video_url += "#t" + _typ + "-s" + _ses + "-c" + _cat + "-o" + _ord + "-p" + _pos;
          }

          _html = '<div id="cont-video|' + _video_name_brand + '|' + _video_id + '" class="cont-video">' +
            '<div class="cont-img"><a href="' + _video_url + '"><img id="img-video|' + _video_name_brand + '|' + _video_id + '" title="" alt="" src="' + _video_thumbnail + '"/></a></div>' +
            '<h2><a href="' + _video_url + '">' + _video_title + '</a></h2>' +
            ((_video_type == '0') ? '<p>Durata: ' + _video_duration + '</p>' : '<p class="full-ep">Puntata intera</p>') +
            '<p>Data: ' + _video_date + '</p>' +
            //'<p class="add-plist"><a href="#">Aggiungi alla playlist</a></p>' +
            '</div>';
          var _item = $j(_html);

          initTooltip(_item);
          lockItem(_item);

          $j('img', _item).bind('load', function () {
            $j(this).unbind('load').fadeIn();
          }).bind('error', function () {
            $j(this).unbind('error').attr('src', IMAGE_UNAVAIL).show();
          }).hide();

          _item.appendTo(_cont);
        });

        //page selector
        if (_pos == 1) {
          $j("ul.pagg-sub > li.prev > a", _nav).hide();
        } else {
          $j("ul.pagg-sub > li.prev > a", _nav).show().unbind('click').bind('click', function(e) {
			      _dbg("showFasciaVideo()", [_id], "click prev page selector");
            fasciaVideoScroll(_eti, _box, -1, SCROLL_MODE_REL);
            return false; //required
          });
        }
        if (_pos == _max) {
          $j("ul.pagg-sub > li.next > a", _nav).hide()
        } else {
          $j("ul.pagg-sub > li.next > a", _nav).show().unbind('click').bind('click', function(e) {
			      _dbg("showFasciaVideo()", [_id], "click next page selector");
            fasciaVideoScroll(_eti, _box, +1, SCROLL_MODE_REL);
            return false; //required
          });
        }
        ////set page number
        $j('ul.pagg-sub > li.curr', _nav).html('<input type="text" name="textfield" id="textfield|' + _id + '" value="' + _pos + '"> di <a href="#">' + _max + '</a>');
        ////add click event to right arrow
        $j('ul.pagg-sub > li.curr > a', _nav).unbind('click').bind('click', function(e) {
			    _dbg("showFasciaVideo()", [_id], "click last page selector");
          fasciaVideoScroll(_eti, _box, _max, SCROLL_MODE_ABS);
          return false; //required
        });
				////add change event to page input
        $j('input', _nav).keydown(function(event) {
          if (event.keyCode == 13) {
            $j(this).blur();
            var _val = _pos;
            try {
              _val = parseInt($j(this).val());
            } catch (exception) {
              //invalid number
            }
            if (_val > _max) _val = _max; //the order of this two lines is important
            if (_val < 1) _val = 1; //the order of this two lines is important
   			    _dbg("showFasciaVideo()", [_id], "entered page number: " + _val);
            fasciaVideoScroll(_eti, _box, _val, SCROLL_MODE_ABS);
            return false; //required
          }
        });
        _nav.show();
      },
      error: function() {
        _dbg("showFasciaVideo", [_id, _url_pos], "error loading xml file");
        _nav.hide();
        _own.html('<div class="cont-video-scroll"><p class="novideo">Nessun video nella categoria</p></div>');
      }
    });
  }


  //begin scrollFasciaVideoBacini()
  //_obj1: container bacino
  //_obj2: container videoBacini
  //_inc : incremento o valore assoluto
  //_mode: incremento = 0; valore assoluto = 1;
  function scrollFasciaVideoBacini(_obj1, _obj2, _inc, _mode) {
    var _eti = $j(_obj1);
    var _box = $j(_obj2);
    var _max = _box.data("max");
    var _pos = _box.data("pos");
    var _new = (_mode == 0) ? (_pos + _inc) : (_inc);

    var _own = $j("div.scroll", _box);
    var _nav = $j("div.etichetta-sub > div.page-container", _eti);

    if ((_new > 0) && (_new <= _max)) {
      var _cont_new = $j("div.cont-video-scroll:eq(" + (_new - 1) + ")", _own);
      _cont_new.html('<img class="loader" src="/res/img/video_loader.gif">');
      _own.animate({ left: ((1 - _new) * 688) + 'px'}, function() {
        if (_pos != _new) {
          var _cont_pos = $j("div.cont-video-scroll:eq(" + (_pos - 1) + ")", _own);
          _cont_pos.empty();
        }
        showFasciaVideoBacini(_obj1, _obj2, _new, SCROLL_MODE_ABS);
      });
    }
  }
  //end scrollFasciaVideoBacini()
    
  //begin showFasciaVideoBacini()
  //_obj1: container etichetta
  //_obj2: container season
  //_inc : incremento o valore assoluto
  //_mode: incremento = 0; valore assoluto = 1;
  function showFasciaVideoBacini(_obj1, _obj2, _inc, _mode) {
    var _eti = $j(_obj1);
    var _box = $j(_obj2);

    var _id = _box.attr('id');
    var _tmp = _id.split("|");
    var _url = "/bacino/"+_tmp[0]+"/" + _tmp[3] + "/" + _tmp[2] + "/" + _tmp[1] + "/fep.sxml";

    var _own = $j("div.scroll", _box);
    var _nav = $j("div.etichetta-sub > div.page-container", _eti);
    var _cont = null;
    var _html = "";

    var _max = _box.data("max");
    var _pos = _box.data("pos");

    if (_max == "" || _max == undefined) {
      _max = 0;
      _pos = 0;
      _url_pos = _url + "?page=" + _pos;

      _dbg("showFasciaVideo", [_id, _url_pos], "init");
      _own.html('<div class="cont-video-scroll"><img class="loader" src="/res/img/video_loader.gif"></img></div>');

      $j.ajax({
        type: "GET",
        url: _url_pos,
        dataType: "xml",
        async: false,
        success: function(result) {
          _pages = $j(result).find("result").attr("totPage");
          if (_pages == 0) {
            _nav.hide();
            _own.html('<div class="cont-video-scroll"><p class="novideo">Nessun video nella categoria</p></div>');
            return;
          } else {
            _html = "";
            for (i = 1; i <= _pages; i++) _html += '<div class="cont-video-scroll"></div>';
            _own.html(_html);
            _max = _pages;
          }
        },
        error: function() {
          _dbg("showFasciaVideo", [_id, _url_pos], "error loading xml file");
          _nav.hide();
          _own.html('<div class="cont-video-scroll"><p class="novideo">Nessun video nella categoria</p></div>');
        }
      });
    }

    var _new = (_mode == SCROLL_MODE_REL) ? (_pos + _inc) : (_inc);
    if (_new > _max) _new = _max; //the order of this two lines is important
    if (_new < 1) _new = 1; //the order of this two lines is important
    _pos = _new;
    _box.data("pos", _pos);
    _box.data("max", _max);
    _url_pos = _url + "?page=" + _pos;

    _dbg("showFasciaVideoBacini", [_id, _url_pos], "load page: " + _pos + " of " + _max);

    _cont = $j("div.cont-video-scroll:eq(" + (_pos - 1) + ")", _own); //get container to fill
    _cont.html('<img class="loader" src="/res/img/video_loader.gif">'); //draw loading image
    _own.css({ left: ((1 - _pos) * 688) + 'px'}); //scroll

    //load xml file ad draw result
    $j.ajax({
      type: "GET",
      url: _url_pos,
      dataType: "xml",
      async: false,
      success: function(result) {
        _pages = $j(result).find("result").attr("totPage");
        //alert(result);

        if (_pages == 0) {
          _nav.hide();
          _own.html('<div class="cont-video-scroll"><p class="novideo">Nessun video nella categoria</p></div>');
          return;
        } else if (_pages != _max) {
          _html = "";
          for (i = 1; i <= _pages; i++) _html += '<div class="cont-video-scroll"></div>';
          _own.html(_html);
          _max = _pages;
          _box.data("max", _max);
        }

        _cont.empty();
        $j("record", result).each(function(i) {
          var _video_id = $j("ID", this).text();
          var _video_name_brand = $j("NAME_BRAND", this).text();
          var _video_desc_brand = $j("DESC_BRAND", this).text();
          var _video_type = $j("TIPO", this).text();
          var _video_thumbnail = $j("THUMBNAIL", this).text();
          var _video_url = $j("URL", this).text() + ".html";
          var _video_title = $j("TITOLO", this).text();
          var _video_duration = $j("DURATA", this).text().substring(0, 8);
          var _video_date = $j("DATA", this).text();

          if (_video_thumbnail == "") {
             _video_thumbnail = "/res/img/138_nothumb.jpg";
          } else {
             _video_thumbnail = "/images/138" + _video_thumbnail;
          }

          if (_video_url == ".html") {
             _video_url = "#";
          }

          /*_html = '<div id="cont-video|' + _video_name_brand + '|' + _video_id + '" class="cont-video">' +
            '<div class="cont-img"><a href="' + _video_url + '"><img id="img-video|' + _video_name_brand + '|' + _video_id + '" title="" alt="" src="' + _video_thumbnail + '"/></a></div>' +
            '<h2><a href="' + _video_url + '">' + _video_title + '</a></h2>' +
            ((_video_type == '0') ? '<p>Durata: ' + _video_duration + '</p>' : '<p class="full-ep">Puntata intera</p>') +
            '<p>Data: ' + _video_date + '</p>' +
            '<p class="brand"><a href="/programma/'+_video_name_brand+'/'+_video_desc_brand.replace(' ', '-').toLowerCase()+'.html" rel="nofollow">'+_video_desc_brand+'</a></p>'+
            '</div>';*/
            
            _html = '<div id="cont-video|' + _video_name_brand + '|' + _video_id + '" class="cont-video">' +
            '<div class="cont-img"><a href="' + _video_url + '"><img id="img-video|' + _video_name_brand + '|' + _video_id + '" title="" alt="" src="' + _video_thumbnail + '"/></a></div>' +
            '<p class="brandfull"><a href="/programma/'+_video_name_brand+'/'+_video_desc_brand.replace(' ', '-').toLowerCase()+'.html" rel="nofollow">'+_video_desc_brand+'</a></p>'+
            '<h2><a href="' + _video_url + '">' + _video_title + '</a></h2>' +
             ((_video_type == '0') ? '<p>Durata: ' + _video_duration + '</p>' : '<p class="full-ep">Puntata intera</p>') +
            ((_video_type == '1') ? '<p>Durata: ' + _video_duration + '</p>' : '') +
            '</div>';
            
            
          var _item = $j(_html);

          initTooltip(_item);

          $j('img', _item).bind('load', function () {
            $j(this).unbind('load').fadeIn();
          }).bind('error', function () {
            $j(this).unbind('error').attr('src', IMAGE_UNAVAIL).show();
          }).hide();

          _item.appendTo(_cont);
        });

        //page selector
        ////add click event to left arrow
        $j("ul.pagg-sub > li.prev > a", _nav).unbind('click').bind('click', function(e) {
          scrollFasciaVideoBacini(_eti, _box, -1, SCROLL_MODE_REL);
          return false; //required
        });
        if (_pos == 1) {
          $j("ul.pagg-sub > li.prev > a", _nav).hide();
        } else {
          $j("ul.pagg-sub > li.prev > a", _nav).show();
        }
        ////add click event to right arrow
        $j("ul.pagg-sub > li.next > a", _nav).unbind('click').bind('click', function(e) {
          scrollFasciaVideoBacini(_eti, _box, +1, SCROLL_MODE_REL);
          return false; //required
        });
        if (_pos == _max) {
          $j("ul.pagg-sub > li.next > a", _nav).hide()
        } else {
          $j("ul.pagg-sub > li.next > a", _nav).show()
        }
        ////set page number
        $j('ul.pagg-sub > li.curr', _nav).html('<input type="text" name="textfield" id="textfield|' + _id + '" value="' + _pos + '"> di ' + _max);
        $j('input', _nav).keydown(function(event) {
          if (event.keyCode == 13) {
            $j(this).blur();
            var _val = _pos;
            try {
              _val = parseInt($j(this).val());
            } catch (exception) {
              //invalid number
            }
            if (_val > _max) _val = _max; //the order of this two lines is important
            if (_val < 1) _val = 1; //the order of this two lines is important
            scrollFasciaVideoBacini(_eti, _box, _val, SCROLL_MODE_ABS);
            return false; //required
          }
        });
        _nav.show();
      },
      error: function() {
        _dbg("showFasciaVideoBacini", [_id, _url_pos], "error loading xml file");
        _nav.hide();
        _own.html('<div class="cont-video-scroll"><p class="novideo">Nessun video nella categoria</p></div>');
      }
    });
  }

});

(function init() {
  //alert('init');
})();
