var _debug = false;
var gup = function(name) {
    var results = (new RegExp("[\\?&]" + name + "=([^&#]*)")).exec(window.location.href);
    if (results == null) { return "" }
    else { return results[1] }
};
function initDebug() {
    $("body").prepend("<div id='debug'></div>");

    $("#debug").css({
        'position': 'fixed',
        'width': '300px',
        'height': ($(document).height() - 40) + "px",
        'background': '#111',
        'color': 'Lime',
        'border': '3px solid #666',
        'padding': '4px',
        'font-family': 'Monaco, Courier New',
        'right': '10px',
        'top': '10px',
        'text-align': 'left',
        'font-size': '10px',
        'display': 'block',
        'overflow': 'auto',
        'z-index': '1000'
    });
    _debug = true;
}
var _debug_counter = 0;
function debug(msg) {
    if (!_debug)
        resizeBy;
    var d = new Date();
    var _d = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + "|" + d.getMilliseconds();
    $("#debug").prepend("<p>" + "[" + _d + "]> " + msg + "</p>");
}

function recordOutboundLink(link, category, action) {
  try {
    var pageTracker=_gat._getTracker("UA-1721300-48");
    pageTracker._trackEvent(category, action);
    setTimeout('document.location = "' + link.href + '"', 100)
  }catch(err){}
}

var Visor = function() {
    var $_launches;
    var _startedup = false;
    var _intvl;
    var _duration;
    var _switching;
    var _itemSelector;
    var _activeItemSelector;
    var _thumbnailListSelector;
    var _thumbnailClasses;
    var _fadeValue;
    var _visorContent;
    var _linkVisor;
    var _thumbnailWidth;
    var _scrollingThumbnails;
    var _visibleThumbnails;
    var _hiddenThumbnailOnRightSide;
    var _hiddenThumbnailOnLeftSide;
    var _fadeInDuration;
    var _fadeOutDuration;
    var _prevButtonSelector;
    var _nextButtonSelector;
    var _currentItem;
    var $_thumbnailContainer;
    //    var $_visorContainer;

    function _listClick(e) {
        $li = $(e.currentTarget).parent();
        debug("_listClick");
        if (_switching) {
            debug("is switching !");
            return;
        }
        debug("_listClick : clearing _intvl " + _intvl);
        //clearInterval(_intvl);
        Visor.Stop();
        var i = $(_thumbnailListSelector + " li").index($li);
        var $wanted = $_launches.children().eq(i);
        //        _intvl = setInterval(Visor.NextVisor, _duration);
        Visor.Start();
        debug("_listClick interval set: item " + i + " (_intvl " + _intvl + ")");

        _loadVisor($wanted);
    }

    function _bindActiveVisorClick() {
			var to = $(_itemSelector).eq(_currentItem).find('a[name=link]').attr('rel');
			         $(_linkVisor).attr('href', to);
					debug("bind content click to "+to);
			        $(_visorContent).unbind("click").click(function() { 
							location.href = to; 
							debug("click to "+to)
					});
		}
		
    function _loadVisor($e) {
        _switching = true;
        var i = $_launches.children(_itemSelector).index($e);
		
		$.each($("input[name=css-class]", $e), function(i, e) {
			$("#header-big").attr("class", "header-"+$(e).val());
		});
		
        _currentItem = i;
        debug("_loadVisor " + i + " (_intvl " + _intvl + ")");
        $(_thumbnailListSelector + " li a.selected").removeClass("selected").css('opacity', _fadeValue);
        $(_thumbnailListSelector + " li a").eq(i).css('opacity', 1).addClass("selected");
        _decorateSelectedThumbnail();

        var thumbCount = $(_thumbnailListSelector + " li").size();
        if (_scrollingThumbnails && i > thumbCount / 2 && _hiddenThumbnailOnRightSide > 0) {
            $_thumbnailContainer.animate({ left: '-=' + _thumbnailWidth });
            _hiddenThumbnailOnRightSide--;
            _hiddenThumbnailOnLeftSide++;
            debug("scrolling thumbnails (still hidden on right " + _hiddenThumbnailOnRightSide + ")");
        }
        if (_scrollingThumbnails && i < thumbCount / 2 && _hiddenThumbnailOnLeftSide > 0) {
            $_thumbnailContainer.animate({ left: '+=' + _thumbnailWidth });
            _hiddenThumbnailOnRightSide++;
            _hiddenThumbnailOnLeftSide--;
            debug("scrolling thumbnails (still hidden on left " + _hiddenThumbnailOnRightSide + ")");
        }
        if (_scrollingThumbnails && i == 0) {
            $_thumbnailContainer.animate({ left: 0 });
            var thumbCount = $("li", $_thumbnailContainer).size();
            _hiddenThumbnailOnRightSide = thumbCount - _visibleThumbnails;
            _hiddenThumbnailOnLeftSide = 0;
        }
        if (_scrollingThumbnails && i == thumbCount - 1) {
            $_thumbnailContainer.animate({ left: _thumbnailWidth * (thumbCount - _visibleThumbnails) * -1 });
            var thumbCount = $("li", $_thumbnailContainer).size();
            _hiddenThumbnailOnRightSide = 0;
            _hiddenThumbnailOnLeftSide = thumbCount - _visibleThumbnails; ;
        }

        var $active = $_launches.children(_itemSelector + _activeItemSelector);

        if ($.browser.msie) {
            $active.hide().removeClass("active");
            $e.show().addClass("active");
            _switching = false;
            _bindActiveVisorClick();
        } else {
            $active.fadeOut(_fadeOutDuration, function() {
                $(this).removeClass("active");
            });

            $e.fadeIn(_fadeInDuration, function() {
                $(this).addClass("active");
                _bindActiveVisorClick();
                _switching = false;
            });
        }
    }

    function _bindButtons() {
        $(_nextButtonSelector).click(function() {
            debug("Next button clicked");
            Visor.Stop();
            Visor.NextVisor();
            Visor.Start();
            return false;
        });
        $(_prevButtonSelector).click(function() {
            debug("Prev button clicked");
            Visor.Stop();
            Visor.PrevVisor();
            Visor.Start();
            return false;
        });
    }

    function _decorateSelectedThumbnail() {
        $("li a span", $_thumbnailContainer).remove();
        $("li a.selected", $_thumbnailContainer).append("<span></span>");
    }
    function _loadThumbnails() {
        $_thumbnailContainer = $(_thumbnailListSelector);
        $_thumbnailContainer.empty();
        $_launches.children(_itemSelector).each(function(i, v) {
            var $thumb = $(v).find("a[name=thumbnail]");
            var thumb_src = $thumb.attr("rel");
            $thumb.remove();
            var $li = $("<li class='" + _thumbnailClasses + "'></li>");
            var $a = $("<a></a>");
            $a.attr("href", "#")
                .click(function(e) { _listClick(e); return false; })
                .hover(
                    function() {
                        if ($(this).hasClass("selected"))
                            return;
                        $(this).css("opacity", 1);
                    },
                    function() {
                        if ($(this).hasClass("selected"))
                            return;
                        $(this).fadeTo("slow", _fadeValue);
                    }
                )
                .append("<img src='" + thumb_src + "' />");
            $li.append($a);
            $_thumbnailContainer.append($li);
            $a.fadeTo(200, _fadeValue);
        });

        _thumbnailWidth = $("li", $_thumbnailContainer).width() +
                          parseInt($("li", $_thumbnailContainer).css("margin-right").replace("px", "")) +
                          parseInt($("li", $_thumbnailContainer).css("margin-left").replace("px", ""));
        var thumbCount = $("li", $_thumbnailContainer).size();
        _scrollingThumbnails = thumbCount > _visibleThumbnails;
        _hiddenThumbnailOnRightSide = thumbCount - _visibleThumbnails;
        _hiddenThumbnailOnLeftSide = 0;
        debug("hidden thumbnails " + _hiddenThumbnailOnRightSide);
        $("li a", $_thumbnailContainer)
            .eq(0)
            .addClass("selected")
            .fadeTo(200, 1);
        _decorateSelectedThumbnail();
				$_thumbnailContainer.find("a").eq(0).trigger("click");
    }
    return {
        Startup: function(conf) {
            $_launches = $(conf.visorContent);
            if ($_launches.size() == 0)
                return;
            _itemSelector = conf.item;
            _activeItemSelector = conf.activeItem;
            _thumbnailListSelector = conf.thumbnailList;
            _thumbnailClasses = conf.thumbnailClasses;
            _fadeValue = conf.fadeValue;
            _visorContent = conf.visorContent;
            _duration = conf.duration;
            _linkVisor = conf.linkVisor;
            _visibleThumbnails = conf.visibleThumbnails;
            _fadeInDuration = conf.fadeInDuration;
            _fadeOutDuration = conf.fadeOutDuration;
            _nextButtonSelector = conf.nextButton;
            _prevButtonSelector = conf.prevButton;
            //            $_visorContainer = $(conf.visorContainer);


            _switching = false;
            _loadThumbnails();
            _bindButtons();
            _currentItem = 0;

            var $active = $_launches.children(_itemSelector + _activeItemSelector);

            if ($active.size() == 0) { //nessuno attivo? Attivo il primo
                $active = $_launches.children(_itemSelector).eq(0).addClass(_activeItemSelector.replace(".", ""));
            }
            _bindActiveVisorClick();

            $("img", $_launches).ready(function() {
                _startedup = true;
                Visor.Start();
                debug("Startup");
            });
        },
        NextVisor: function() {
            var $active = $_launches.children(_itemSelector + _activeItemSelector);
            var $next = $active.next(_itemSelector);

            if ($next.size() == 0) {
                debug("NextVisor : no next item");
                $next = $_launches.children().eq(0);
            }

            debug("NextVisor : _intvl " + _intvl);
            _loadVisor($next);
        },
        PrevVisor: function() {
            var $active = $_launches.children(_itemSelector + _activeItemSelector);
            var $prev = $active.prev(_itemSelector);
            if ($prev.size() == 0)
                $prev = $_launches.find(_itemSelector + ":last");

            debug("PrevVisor : _intvl " + _intvl);
            _loadVisor($prev);
        },
        Stop: function() {
            debug("Stop : clearing intvl " + _intvl);
            clearInterval(_intvl);
        },
        Start: function() {
            if (_startedup) {
                if (_intvl != undefined) {
                    debug("Start clearing _intvl " + _intvl);
                    clearInterval(_intvl);
                }
                _intvl = setInterval(Visor.NextVisor, _duration);
                debug("Start (_intvl) " + _intvl);
            }
        },
        IsRunning: function() {
            return _startedup;
        }
    }
} ();

var SimpleItemScroller = function() {
    var _strip;
    var _items;
    var _itemW;
    var _duration;
    var _jump;
    var _pages;
    var _page;
    var _lock;
    var _mainImage;
    var _prevButton;
    var _nextButton;
    var _currentItem;
    var _itemSelector;
    var _selectedClass;
    var _click;

    function _move(dir) {
        if (_lock)
            return;
        _lock = true;

        var delta_x = (_itemW * _jump);
        if (_page == _pages - 1 && dir == "-") {
            var d = _items.size() - (_pages * _jump);
            debug("d : " + d);
            delta_x += (d * _itemW);
        }
        if (_page == 2 && dir == "+") {
            if (parseInt(_strip.css("left").replace("px", "")) + delta_x > 0)
                delta_x = parseInt(_strip.css("left").replace("px", "")) * -1;
        }

        _strip.animate({ left: (dir + "=") + delta_x }, _duration, function() {
            _lock = false;
            if (dir == "+")
                _page--;
            else
                _page++;
        });
    }
    function _next() {
        debug("_next()");
        if (_items.filter("." + _selectedClass).next().size() == 0) {
            _items.removeClass(_selectedClass).eq(0).addClass(_selectedClass);
        } else {
            var n = _items.filter("." + _selectedClass).next();
            _items.removeClass(_selectedClass);
            n.addClass(_selectedClass);
        }
        //console.log(_items.filter("." + _selectedClass));
        _items.filter("." + _selectedClass).find("a").trigger("click");
        _currentItem = ++_currentItem % _items.size();
        debug("_currentItem " + _currentItem);
        if (_currentItem % _jump == 0)
            SimpleItemScroller.forward();
    }
    function _prev() {
        if (_items.filter("." + _selectedClass).prev().size() == 0) {
            _items.removeClass(_selectedClass).eq(_items.size() - 1).addClass(_selectedClass);
        } else {
            var n = _items.filter("." + _selectedClass).prev();
            _items.removeClass(_selectedClass);
            n.addClass(_selectedClass);
        }
        _items.filter("." + _selectedClass).find("a").trigger("click");
        if (--_currentItem < 0)
            _currentItem = 0;
        if (_currentItem % _jump == 0)
            SimpleItemScroller.backward();
    }

    function _bindClick() {
        _items.find("a").click(function() {
            if ($(this).hasClass("go")) {
                location.href = $(this).attr("href");
            }

            var img = $(this).attr("rel");
            _mainImage.attr("src", img);
            _items.removeClass(_selectedClass);
            $(this).parents(".scrollingItem").addClass(_selectedClass);
            if (_click != undefined)
                _click.call(window, this);
            return false;
        });
        _nextButton.click(function() { _next(); return false; });
        _prevButton.click(function() { _prev(); return false; });
    }
	function _setItemWidth() {
		_items = $(_itemSelector, _strip);
        _itemW = _items.width();
		var mr = parseInt(_items.css("margin-right").replace(/\s/g, ''));
		var ml = parseInt(_items.css("margin-left").replace(/\s/g, ''));
		_itemW += (mr + ml);
	}
    return {
        init: function(options) {
            _strip = $(options.strip);
            _itemSelector = options.item != undefined ? ".scrollingItem" : options.item;
            _click = options.click;
            _selectedClass = options.selectedClass != undefined ? options.selectedClass : "selected";
            _duration = options.duration != undefined ? options.duration : 1000;
            _jump = options.jump != undefined ? options.jump : 1;
            _mainImage = $(options.mainImage);
            _prevButton = $(options.prevButton);
            _nextButton = $(options.nextButton);
			
			_setItemWidth();
			
            _pages = Math.ceil(_items.size() / _jump);
            _page = 1;
            _currentItem = 0;
            _lock = false;

            if (__fox_debug) {
                _items.each(function(i, e) {
                    $(".relative", e).append("<span style='position:absolute;color:#fff'>" + (i + 1) + "</span>");
                });
            }

            var selected = $(_items).filter("." + _selectedClass);
            if (selected.size() == 0)
                _items.eq(0).addClass(_selectedClass);
            
            debug("_currentItem " + _currentItem);
            _bindClick();

            debug("items :" + _items.size());
            debug("pages : " + _pages);


        },
        backward: function() {
            debug("page : " + _page);
            if (_page == 1)
                return;
            _move("+");
        },
        forward: function() {
            debug("page : " + _page);
            if (_page == _pages)
                return;
            _move("-");
        }
    }
} ();

var MyShare = function() {
		var _uri;
    var _title;
		function _myspace() {
			return 'http://www.myspace.com/Modules/PostTo/Pages/?u='+encodeURIComponent(_uri);
		}
		function _facebook() {
			return 'http://www.facebook.com/sharer.php?u='+encodeURIComponent(_uri)+'&t='+encodeURIComponent(_title);
		}
		return {
			init: function(options) {
				_uri = options.uri;
				_title = options.title;
				$('#share_myspace').attr("href", _myspace());
				$('#share_facebook').attr("href", _facebook());
			}
		}
} ();

var __fox_debug = false;
$(function() {

    if (gup("debug") != "") {
        __fox_debug = true;
        initDebug();
    }

    Visor.Startup({
        visorContent: "#visor-content",
        item: ".item",
        activeItem: ".active",
        thumbnailList: "#menu-serie ul",
        thumbnailClasses: "left widgetBoxScroll",
        fadeValue: .6,
        duration: 5000,
        linkVisor: "#link-visor",
        visibleThumbnails: 5,
        fadeIdDuration: 500,
        fadeOutDuration: 500,
        nextButton: "#btnNext",
        prevButton: "#btnPre"
    });

    var _tentState, _dealingWithTent = false;


    /* BEGIN bindings */
    $("#main-menu a.serietv").click(function() {
        if (_tentState || _dealingWithTent)
            return;
        _dealingWithTent = true;
        $("#tendina .menu-top").fadeIn();
        $("#tendina").slideDown(function() {
            _tentState = true;
            _dealingWithTent = false;
        });
        return false;
    });
    $(".btn-chiudi-tendina").click(function() {
        if (_dealingWithTent)
            return;
        _dealingWithTent = true;
        $("#tendina .menu-top").fadeOut();
        $("#tendina").slideUp(function() {
            _tentState = false;
            _dealingWithTent = false;
            $("#tendina .menu-all").hide();
        });
    });
    $(".btn-switch-tendina").click(function() {
        $("#tendina .menu-all").toggle();
        $("#tendina .menu-top").toggle();
    });
    $(".btn-switch-on-air-panel").click(function() {
        if($("#now-on-air-panel").length == 0) {
					$.get("/guidatv/ora", '',
					  function(html){
							$('#menu-tonight').append(html);
							Cufon.refresh();
							$("#tonight-on-air-panel").toggle();
			        $("#now-on-air-panel").toggle();
			        $(".title-on-air").toggle();
							
							$("#btn-switch-tonight").click(function() {
								$("#tonight-on-air-panel").toggle();
				        $("#now-on-air-panel").toggle();
				        $(".title-on-air").toggle();
							});
							
						});
				} else {
					$("#tonight-on-air-panel").toggle();
	        $("#now-on-air-panel").toggle();
	        $(".title-on-air").toggle();
				}
    });

    $(".btn-calendar-switch").hover(
        function() { $("#calendar", this).show(); },
        function() { $("#calendar", this).hide(); }
    );

    try {
        $("#scroll>div").jScrollPane();
    } catch (e) { }
    $("#btn-commento").click(function() {
        $("#form-commento").show();
        __refresh_bd_height();
        return false;
    });


    $("#btn-mostra-commento").click(function() {
        $(".comment.invisible").show();
        __refresh_bd_height();
        return false;
    });

    $(".btn-read-all").click(function() {
        var ab = $(this).parents(".actor-box");
        ab.find(".preview").toggle();
        ab.find(".complete").toggle();
        $(this).text($.trim($(this).text().toLowerCase()) == "leggi tutto" ? "CHIUDI" : "LEGGI TUTTO");
        return false;
    });
    $(".btn-scheda-attore").click(function() {        
        var c = $(this).parents(".contents");
        $.get($(this).attr("href"), function(html) {
			$(".actor-box.index400").removeClass("index400");
            $("#scheda-attore").hide().find(".contents").html(html);
            c.parent().addClass("index400");
            c.append($("#scheda-attore"));
            Cufon.refresh();
            $("#scheda-attore").show();
        });
        return false;
    });
    $("#btn-chiudi-finestra").live("click", function() {
        $("#scheda-attore").hide();
        $("#form-commento").hide();
        __refresh_bd_height();
        return false;
    });
    /* END bindings */

   
       
    $("#btn-scroll .avanti").click(function() {
        SimpleItemScroller.forward();
        return false;
    });
    $("#btn-scroll .indietro").click(function() {
        SimpleItemScroller.backward();
        return false;
    });



    /* BEGIN tool voti versione 2 (differente dalla versione di fox life) */
    var _fox_voting_tool = $("#voti");
    var _fox_voting_tool_update = function() {
        var rating = parseInt(_fox_voting_tool.data("rating"));
        $("a", _fox_voting_tool).removeClass("on");
    }
    function _fox_voting_tool_show(e) {
        var rating = $(e).parents(".scrollingItem").data("rating");
        $("#votes-counter").text($(e).parents(".scrollingItem").data("votes"));

        var _bar = $(".pallini", _fox_voting_tool);
        var w = _bar.width();
        var _w = Math.round(rating * w / 5);
        $(".mask", _fox_voting_tool).css("width", _w + "px");
        return false;
    }
    $("a", _fox_voting_tool).hover(
        function() {
            var a = $("a", _fox_voting_tool);
            var index = $(this).index("#voti a");
            a.each(function(i, e) {
                if (i <= index) {
                    $(e).addClass("on");
                }
                else
                    $(e).removeClass("on");
            });
        },
        function() { }
    );

    function _init_voting() {
        if (_fox_voting_tool.size() == 0)
            return;
        /* voti su thumbnails */
        var items = $("#cont-thumbnail .scrollingItem");
        items.each(function(i, e) {
            try {
                var d = $(e).attr("title").split("/");
                $(e).data("rating", parseFloat(d[0]));
                $(e).data("votes", d[1]);
            } catch (e) { }
        });
        var _bar = $(".pallini", _fox_voting_tool);
        var w = _bar.width();

        if (_fox_voting_tool.attr("title") != "") {
            _fox_voting_tool.data("rating", parseFloat(_fox_voting_tool.attr("title")));
            _fox_voting_tool.removeAttr("title");
            var _w = Math.round(_fox_voting_tool.data("rating") * w / 5);
            $(".mask", _fox_voting_tool).css("width", _w + "px");
        }
    }
    $(".pallini, .mask", _fox_voting_tool).hover(
		function() {
		    $(".mask", _fox_voting_tool).hide();
		},
		function() {
		    $(".mask", _fox_voting_tool).show();
		    $("a", _fox_voting_tool).removeClass("on");
		}
	);
    _init_voting();
    /* END tool voti */
});

var __refresh_bd_height = function(fade) {
	return;
    var ft = $("#shop");
    ft.css("margin-top", $("#bd").height() + "px");
    if (fade != undefined && fade)
        ft.fadeIn();
}

$(function() {
    __refresh_bd_height(true);
});
