jQuery.noConflict();

jQuery(document).ready(function ($) {
    //  MSIE 6 only
    var IE6 = false;
    if ($.browser.msie) {
        if ($.browser.version < 7) {
            IE6 = true;
        }
        // IE stuff
        if (Object.prototype.toString.call(self.JSON) === "[object JSON]") {
            // IE8 stuff
        } else {
            // IE < 8 stuff
            $(".frontpage .cols .col5_5 .image ul li a").each(function () {
                $(this).text("\u00BB\u0020" + $(this).text());
            })
        }
        /*
        $(document).not(":input,a").keydown(function(e){
        if (e.keyCode == 13) {
        $(this).parents('form').submit();
        return false;
        }
        });
        */


    }

    // nav tab animation  
    var navDuration = 150; //time in miliseconds
    var navJumpHeight = "2px";
    $('#level-1 li a').not(".selected")
		.bind("mouseenter focus", function (e) {
		    $(this).stop().animate({ top: "-=" + navJumpHeight }, navDuration);
		})
		.bind("mouseleave blur", function (e) {
		    $(this).stop().animate({ top: "5px" }, navDuration);
		})

    // Tabpanel		
    $("#tabs div.tab").hide(); // Hide all divs
    $("#tabs div.tab:first").show(); // Show the first div
    $("#tabs ul.navi li:first").addClass("active"); // Set the class of the first link to active
    $("#tabs ul.navi li a").click(function () { //When any link is clicked
        $("#tabs ul.navi li").removeClass("active"); // Remove active class from all links
        $(this).parent().addClass("active"); //Set clicked link class to active
        var currentTab = $(this).attr("href"); // Set variable currentTab to value of href attribute of clicked link
        $("#tabs div.tab").hide(); // Hide all divs
        $(currentTab).show(); // Show div with id equal to variable currentTab
        return false;
    });
    //	moreContentMenu
    var moreContentHeight = $("#moreContent > ul").height();
    $("#moreContent > ul").hide();
    var moreContentTimeout = null;
    var showMoreContentMenu = function () {
        clearTimeout(moreContentTimeout);
        if ($("#moreContent > ul").css("display") == "none") {
            $("#moreContent > ul").css({ height: "0" }).show().animate({ height: moreContentHeight }, 300);
        } else {
            $("#moreContent > ul").show();
        }
        if (IE6) {
            $("#page").addClass("hideSelects");
        }
    };
    var hideMoreContentMenu = function () {
        $("#moreContent >ul").fadeOut('fast');
        if (IE6) {
            $("#page").removeClass("hideSelects");
        }
        clearTimeout(moreContentTimeout);
    };
    // Events
    $("#moreContent > a").bind("mouseenter focus", function () {
        showMoreContentMenu();
    });
    $("#moreContent > ul").bind("mouseenter focus", function () {
        clearTimeout(moreContentTimeout);
        $("#moreContent > ul").show();
    });
    $("#moreContent > a, #moreContent > ul").bind("mouseleave blur", function () {
        moreContentTimeout = setTimeout(function () { hideMoreContentMenu() }, 500);
    });

    //  Search box
    if ($("#search input.text").length) {
        $("#search input.text")
			.attr("value", $(".search input.text").attr("title"))
			.focus(function () {
			    if (this.value == this.title) {
			        this.value = "";
			    }
			    $(this).addClass("active");
			})
			.blur(function () {
			    if (this.value == "") {
			        this.value = this.title;
			    }
			    $(this).removeClass("active");
			});
    }

    // Select Box Jumper
    $("select.goto").selectJumper();

    $("#tools_textsize").click(function () {
        document.getElementsByTagName('body')[0].style.fontSize = '100%';
        return false;
    })

    // IE
    if ($.browser.msie) {
        $("body").append("<div id='tooltip'></div>");
        var bLang = navigator.browserLanguage;
        if (bLang != "da") {
            $("#tools_print").tooltip({ text: "<p>Således udskrives siden:</p><ol><li>Klik på browserens udskrifts ikon<br> (<strong>CTRL</strong> + <strong>P</strong>)</li></ol>" });
            $("#tools_textsize").tooltip({ text: "<p>Sådan ændres tekststørrelsen på en webside:</p><ol><li>Åbn menuen 'Vis' øverst i Internet Explorer (<strong>ALT</strong> + <strong>S</strong>)</li><li>Vælg 'Tekststørrelse' (<strong>T</strong>)</li><li>Klik på den ønskede størrelse, f.eks. <em>Mellem</em> eller <em>Større</em>.</li></ol><p>Alternativ genvej  <strong>CTRL</strong> + <strong>PLUS</strong> eller <strong>MINUS</strong>" });
            if (IE6) {
                $("#tools_sendlink").tooltip({ text: "<p>Således sender du et link til denne side via dit email-program.</p><ol><li>Klik på 'Filer' i menubjælken (<strong>ALT</strong>+<strong>F</strong>)</li><li>Vælg 'Send...' (<strong>S</strong>)</li><li>Vælg 'Hyperlink med e-mail...' (<strong>H</strong>)</li></ol>" });
            } else {
                $("#tools_sendlink").tooltip({ text: "<p>Således sender du et link til denne side via dit email-program.</p><ol><li>Klik på 'Side' i menubjælken (<strong>ALT</strong>+<strong>I</strong>)</li><li>Vælg 'Send hyperlink med e-mail...' (<strong>H</strong>)</li></ol>" });
            }
        }

        // Find last child for IE6 + 7
        $(".col_row :last-child").addClass("last-child");

        // IE6
        if (IE6) {
            // Find first child for IE6
            $(".col_row :first-child").addClass("first-child");

            var w = parseInt($("#page").width());
            if ((w > 731) && (w <= 812)) {	// Smaller
                $("#search").css({ top: 26 });
                $("body").prepend("<div id='ie6msg'></div>");
                $("#ie6msg")
					.html("Din tekststørrelse i browseren er sat til '<strong>mindre</strong>', hvilket kan gøre teksten på denne hjemmeside svær at læse. ")
					.animate({ top: 0 }, 1500)
					.animate({ top: 0 }, 10000)
					.animate({ top: -100 }, 1500);
            } else if (w <= 731) {				// Smallest
                $("body").prepend("<div id='ie6msg'></div>");
                $("#ie6msg")
					.html("Din tekststørrelse i browseren er sat til '<strong>mindst</strong>', hvilket desværre bryder layoutet på denne hjemmeside. <br>I menubjælken klik på 'Vis' og 'Tekststørrelse' og derefter vælg en der er større.")
					.animate({ top: 0 }, 1500)
					.animate({ top: 0 }, 10000)
					.animate({ top: -100 }, 1500);
            }
        }
    }
});

(function ($) {


//------------ ENGINE START-----------------------
/*** Engine ***/

	Engine = {
		init: function() {
			$(document).ready(function ($) {
				Engine.onDomLoaded();
			});
		},
		onDomLoaded: function() {
			Engine.ui.popup.init();
            Engine.ui.paging.init();
			Engine.fixes.filmPlayIcon();
		},
		
		tools : {
			query : function( q, url ) {
				var qtype = typeof(q),
					str = null,
					re = "([?&]|^){var}=([^&]*)([&#]|$)";

				if( !url )
				{ url = window.location.href; }

				switch( qtype ) {
					// Manipulate the querystring in the URL and return the new URL
					case "object":
						var newq = "",
							hi = url.indexOf("#");

						if( hi < 0 )
						{ hi = url.length; }

						// Remove the hash value so it doesn't interrupt the manipulation
						var hash = url.substr(hi);

						url = url.substr(0, hi);

						// Loop through all attributes in the object (jSon)
						for( qvarname in q ) {
							var val = q[qvarname],
								qvar = qvarname +"="+ val,
								r = new RegExp(re.replace("{var}", qvarname), "i");

							url = url.replace(r, "$1");

							if( newq !== "" ) { newq += "&" }
							newq += qvar;
						}

						// If any query query variables were set in the loop, add them to the url
						if( newq !== "" ) {
							url = url.replace(/[&]+$/, "");

							if( url.substr(url.length-1) !== "?" ) {
								url += (url.lastIndexOf("?") > 0)? "&" : "?";
							}

							url += newq;
						}

						// Return the url + the removed hash value (if any)
						str = url + hash;

						break;

					// Find the queryvariable in the URL and return the value
					case "string":
						var r = new RegExp(re.replace("{var}", q), "i");
							m = url.match(r);

						if( !!m )
						{ str = m[2]; }

						break;
				}

				return str;
			}
		},
		fixes: {
			context : function( $context  ) {
				$context = $([]).add($context);
				if( $context.length <= 0 )
				{ $context = $("body") }
				
				return $context;
			},
			
			selectorToClass : function( selClass, selector, $context  ) {
				var sel = ":"+ selClass, str = selector.replace(/,/g, sel +",") + sel;
				$(str, this.context($context)).addClass(selClass);
			},
			
			multiClass : function( $context ) {
				if( $.browser.msie && $.browser.version <= 6 ) {
					$context = this.context($context);
					
					$(".more.tiny", $context).addClass("more-tiny");
					$(".more.big", $context).addClass("more-big");
					$(".more.big.tiny", $context).addClass("more-big-tiny");
					$(".down.big", $context).addClass("down-big");
					$(".display-item img + .text", $context).addClass("img-text");
				}
			},

			firstChild : function( selector, $context ) {
				if( $.browser.msie && $.browser.version <= 6 ) {
					this.selectorToClass("first-child", selector, $context);
				}
			},

			lastChild : function( selector, $context ) {
				if( $.browser.msie && $.browser.version <= 7 ) {
					this.selectorToClass("last-child", selector, $context);
				}
			},

			alternateRows : function( $context ) {
				if( $.browser.msie && $.browser.version <= 8 ) {
					$context = this.context($context);
					
					$("table tbody > tr:nth-child(even), table > tr:nth-child(odd)").addClass("alternate");
				}
			},

			filmPlayIcon : function( $context, $items ) {
				if( $("html").hasClass("oldie") ) {
					if( !$items || $items.length <= 0 )
					{ $items = this.context($context).find(".film img, .video img"); }

					$items.after('<b class="play"></b>');
				}
			}
		},
		form: {
			placeholder : function() {
				if( !Modernizr.input.placeholder ) {
					$("input[placeholder]").each(function() {
						var $inp = $(this), ph = $inp.attr("placeholder");

						$inp
						.val(ph).addClass("placeholder")
						.focus(function() {
							if( $inp.hasClass("placeholder") )
							{ $inp.val("").removeClass("placeholder"); }
						})
						.blur(function() {
							if( $inp.val() == "" )
							{ $inp.val(ph).addClass("placeholder"); }
						});
					});
				}
			},

			changeRole : {
				init : function() {
					var self = this,
						$selects = $("#changeRole select"),
						$reset = $("#changeRole .button.reset:first");

						$reset.click(function() {
							if( !$reset.hasClass("btn-inactive") ) {
								$selects.each(function(i, elm) {
									this.selectedIndex = 0;
								});

								$reset.addClass("btn-inactive");
							}
						});

						$selects.change(function(e) {
							self.checkValues($selects, $reset);
						});

						self.checkValues($selects, $reset);
				},

				checkValues : function( $selects, $reset ) {
					var inactive = true,
						selCount = $selects.length;

						for(var i=0; i < selCount && inactive; i++) {
							var sel = $selects[i];
							log(sel, sel.selectedIndex);

							if( sel.selectedIndex > 0 )
							{ inactive = ( sel.selectedIndex <= 0 ); }
						}

						$reset.toggleClass("btn-inactive", inactive);
				}
			}
		},
		ui: {
			slider : function() {
				var sliderEvents = $.plugins.centerSlider.events,
					$disp = $('<div class="slider-display"></div>');

				$("#top-slider")
				.bind(sliderEvents.INIT, function() {
					var $s = $(this);
					Engine.fixes.multiClass($s);
					$disp.appendTo($s);
				})
				.bind(sliderEvents.ITEM_INIT, function(e, $item) {
					var $di = $(".display-item:first", $item).appendTo($disp);
					$item.centerSlider("storage", { width: $item.outerWidth(), display: $di });
				})
				.bind(sliderEvents.BEFORE_SLIDE, function(e, obj) {
					var $s = $(this), s = $s.centerSlider("storage"),
						$fromItem = obj.from, $toItem = obj.to,
						tiS = $toItem.centerSlider("storage"),
						tiDisp = tiS.display, dispShown = tiDisp.is(":visible"),
						cW = s.container.innerWidth(),
						speed = obj.speed, onend = function() {};
					
					if( $fromItem )
					{
						var fiS = $fromItem.centerSlider("storage"),
							fW = fiS.width, fiDisp = fiS.display,
							fiW = $fromItem.outerWidth();
						
						if(obj.fromX > obj.x)
						{ obj.x += (fiW - fW); }

						if( !dispShown ) {
							fiDisp.css({ zIndex: "" });
							onend = function() { fiDisp.css("display", "") };
						}

						$fromItem.animate({width: fW +"px"}, speed, function() { $(this).css("width", "") });
					}

					if( !dispShown ) {
						tiDisp
						.css({ display: "block", opacity: 0, zIndex: 9 })
						.fadeTo(speed, 1);
					}

					$toItem.animate({width: cW +"px"}, speed, onend);
					
				})
				.centerSlider({ classes: { prefix: "slider-" } });
			},

			accordion : function() {
				$(".accordion").each(function(i, elm) {
					$(" > dl > dt", this).each(function() {
						var $dt = $(this),
							$lc = $(" > :last-child", $dt.next());

						$dt.data("accordion", { initH: Math.round($lc.position().top + $lc.outerHeight()) });
					});

					$(this).click(function(e) {
						var $tar = $(e.target);

						if( $tar.is("dt") ) {
							var $dd = $tar.next(), isOpen = $dd.hasClass("open"), acc = $tar.data("accordion");

							if( !!acc ) {
								var h = (isOpen)? 0 : acc.initH;

								if( !Modernizr.csstransitions ) {
									$dd.animate({ height:h }, 400);
								} else {
									$dd.height(h);
								}

								$dd.add($tar).toggleClass("open");
							}
						}
					});
				});
			},

			tabs : {
				init : function() {
					var _this = this;
					$("ul.tabs").each(function() {
						var $ul = $(this).delegate("a", "click", function(e) {
							e.preventDefault();

							var $a = $(this), $list = $a.parent().parent();

							if( $a[0] != $list.data("tabs.storage").currTab[0] )
							{ Engine.ui.tabs.activatepane( $list, $a ); }
						});

						// IE 7 + 6 (IE < 8) - add arrow as a <b> tag
						if( $.browser.msie && $.browser.version < 8 )
						{ $(" > li",  $ul).append('<b class="arrow"></b>'); }

						$ul.data("tabs.storage", { oldTab : null, currTab : null });

						_this.setSizes( $ul );

						Engine.ui.tabs.activatepane( $ul );
					});
				},

				activatepane : function( ul, tab ) {
					var $ul = $(ul), $tab = $(tab),
						s = $ul.data("tabs.storage");

					if( !tab )
					{ 
						$tab = $([]).add(s.currTab);

						if( !s.currTab )
						{
							$(" > li", $ul).each(function(i, elm) {
								var $li = $(this), $a = $li.children("a:first"),
									$area = $($a.attr("href"));

								// Use first child if no other active areas have been found
								if( i === 0 )
								{ $tab = $a; }

								if( $area.hasClass("active") )
								{ $tab = $a; return false; }
							});
						}
					}

					if( $tab.length > 0 ) {
						s.oldTab = s.currTab;
						s.currTab = $tab;

						$ul.data("tabs.storage", s);
						this.switchpanes( $ul );
					}
				},

				switchpanes : function( ul ) {
					var $ul = $(ul), s = $ul.data("tabs.storage"),
						$oldTab = $(s.oldTab), $newTab = $(s.currTab);

					if( $oldTab[0] !== $newTab[0] ) {
						var $ntArea = $( (($newTab.length > 0)? this.getArea($newTab) : []) );

						if( $oldTab.length > 0 && $ntArea.length > 0 ) {
							$ntArea.css("display", "block");

							var	$otArea = this.getArea($oldTab).css("display", "block"),
								otAH = $otArea.outerHeight(), ntAH = $ntArea.outerHeight(),
								onEnd = function() {};

							if( otAH > ntAH )
							{
								$otArea.css({"position": "relative"});
								$ntArea.css({"position": "absolute"});

								onEnd = function() {
									$otArea.add($ntArea).attr("style", "");
								};
							}

							$oldTab.parent().add($otArea).removeClass("active");
							$newTab.parent().add($ntArea).addClass("active");

							if( !Modernizr.csstransitions ) {
								if( $otArea.css("opacity") === "0" )
								{ $otArea.css("opacity", 1); }

								if( $ntArea.css("opacity") === "1" )
								{ $ntArea.css("opacity", 0); }

								$otArea.stop().fadeTo(300, 0, function() { $(this).css("display", "none"); });
								$ntArea.stop().fadeTo(300, 1, onEnd);
							} else {
								$ntArea
								.one("webkitTransitionEnd", onEnd) // Webkit (Chrome/Safari)
								.one("oTransitionEnd", onEnd) // Presto (Opera)
								.one("transitionend", onEnd); // Mozilla (FireFox)
							}
						} else {
							//$ntArea.css("opacity", "1");
							$newTab.parent().add($ntArea).addClass("active");
						}
					}
				},

				setSizes : function( ul ) {
					var _this = this, $ul = $(ul), $container = $ul.parent(),
						$tabs = $(" > li > a", $ul),
						// Test the second tab for any width differences (padding and/or border),
						// so a fixed width is defined and overflow is prevented, as long as it is tested
						$secondTab = $tabs.eq(1).parent().css({"overflow": "hidden", "width": "200px"}),
						tabLen = $tabs.length, ulW = $ul.innerWidth(), maxH = 0,
						wDelta = $secondTab.outerWidth() - 200,
						tabW = (ulW - ((tabLen -1) * wDelta)) / tabLen;
					
					// Remove the testing styles
					$secondTab.css({"overflow": "", "width": ""});

					$tabs.each(function(i, elm) {
						var $a = $(this), $li = $a.parent(), $area = _this.getArea($a),
							setOpac = (Modernizr.opacity || (!Modernizr.opacity && !$area.is(".active")));

						$li.width(tabW);
						$area.css({ display: "block" });

						if( setOpac )
						{ $area.css("opacity", 0); }

						maxH = Math.max(maxH, $area.outerHeight());

						$area.css("display", "");

						if( setOpac )
						{ $area.css("opacity", ""); }
					});

					$container.height(maxH);
				},

				getArea : function( tab ) {
					return $($(tab).attr("href"));
				}
			},

			popup : {
				init : function() {
					//alert('Engine.popup.init() kørt');
                    var self = this;

					$("[data-popup]").live("click", function(e) {
						e.preventDefault();
						var $a = $(this),
							data = $a.attr("data-popup");

						switch( data ) {
							case "confirm":
								var href = $a[0].href,
									yes = function() { window.location = href; };

								self.confirm(yes);

								break;
							case "video":
								var a = '<a href="#" class="close">&times;</a>',
									url = $a.attr("href"); // In IE 7 a link have a href no matter what

								if( !!url ) {
									var id = "video",
										$vid = $("#"+ id);
                                       
                                    $vid.append('<iframe id="'+ id +'" src="'+ url +'" width="565" height="352" frameborder="0" border="0" scrolling="no"></iframe>');
									$vid.append(a)

                                    self.open("#"+ id);

                                    $vid.empty();
									
								} else {
									var sid = "video.iframe",
										id = $a.data(sid);

									if( !id ) {
										id = 'vid'+ Number(new Date());

										var $popups = $("#popups"),
											div = $('<div id="'+ id +'"></div>').append(a).appendTo($popups),
											iframe = $a.next().children().appendTo(div);

										$a.data(sid, id);
									}

									self.open("#"+ id);
								}

								break;
							default:
								Engine.ui.popup.open("#"+ data);
						}
					});
				},

				open : function( item ) {
					var $item = $(item);
					if( $item.length <= 0 ) { return; }

					var $popup = $("#popup"),
						close = function(e) { Engine.ui.popup.close(); };

					// Create popup layer if it doesn't exists
					if( $popup.length <= 0 ) {
						var $bg = $('<div id="popup-bg"></div>'),
							$container = $('<div id="popup-container"><div class="placer"></div></div>'),
							escape = function(e) {
								if( e.which === 27 )
								{ close(); }
							},
							click = function(e) {
								e.preventDefault();
								var $tar = $(e.target);
								if( $tar.is("#popup-bg, #popup, #popup-container, a.close") )
								{ close(this); }
							};

						$popup = $('<div id="popup"></div>')
								.hide()
								.append($bg)
								.append($container)
								.appendTo("body");

						$(document).bind("keyup", escape);
						$popup.bind("click", click);
					}

					$("#popup-container .placer:first", $popup).append($item.clone());

					$popup
					.hide()
					.fadeIn(400);
					
					this.scale($popup, (($item.is("#breaking"))? 455 : null));
				},

				close : function( $popup ) {
					$popup = $($popup);
					if($popup.length <= 0)
					{
						$popup = $("#popup");
						if($popup.length <= 0)
						{ return; }
					}

					$popup.trigger("popup.close").fadeOut(400, function() {
						$("#popup-container .placer", this).html("");
					});
				},

				confirm : function( yes, no ) {
					this.open("#confirm");

					var self = this,
						overlay = $("#popup-container #confirm");
					
					if( !(yes instanceof Function) )
					{ yes = function() {}; }

					if( !(no instanceof Function) )
					{ no = function() {}; }

					$(".button.yes:first", overlay).one("click", function(e) { yes(e); self.close(); });
					$(".button.no:first", overlay).one("click", function(e) { no(e); self.close(); });
				},

				place : function( $popup, fixedTop ) {
					if($popup.length <= 0)
					{
						$popup = $("#popup");
						if($popup.length <= 0)
						{ return; }
					}

					var $c = $("#popup-container", $popup),
						top = fixedTop;

					if( !top ) {
						var $w = $(window),
							cH = $c.outerHeight(),
							wH = $w.height(),
							sT = $w.scrollTop();

						top = (cH > wH)? (wH - cH) : ((wH / 2) - (cH / 2));
						top = Math.max(Math.round(top + sT), 185);
					}

					$c.css("top", top +"px");
					
					this.scrollIntoView($popup);
				},

				scale : function( $popup, fixedTop ) {
					if($popup.length <= 0)
					{
						$popup = $("#popup");
						if($popup.length <= 0)
						{ return; }
					}

					var _root = document.documentElement,
						sW = _root.scrollWidth,
						sH = _root.scrollHeight;

					//$popup.css({"width" : sW +"px", "height" : sH});
					$popup.css({"height" : sH});

					this.place($popup, fixedTop);
				},

				scrollIntoView : function( $popup ) {
					if($popup.length <= 0)
					{
						$popup = $("#popup");
						if($popup.length <= 0)
						{ return; }
					}
					
					var $w = $(window),
						$hb = $("html, body")
						$c = $("#popup-container", $popup),
						t = $c.position().top,
						sT = $w.scrollTop(),
						scr = sT,
						topSpace = 30,
						cH = $c.outerHeight(),
						wH = $w.height();
					
					if( cH < wH ) {
						scr = t - ((wH - cH) /2);
						
						if( scr < topSpace )
						{ scr = topSpace; }
						
						scr = Math.round(scr);
					}

					// Scroll back to previous position, unless the user has scrolled the page, while the popup was open
					$popup
					.data("popup.storage", { scrollTop: sT })
					.one("popup.close", function() {
						var st = $(this).data("popup.storage").scrollTop;
						if( st !== null )
						{ $hb.animate({scrollTop: st}, 300); }
					});

					/*if( (t - topSpace) < scroll )
					{ scroll = (t - topSpace) }*/

					// Scroll pop into center
					if( scr != sT ) {
						$hb.animate({scrollTop: scr}, 300, function() {
							// Eliminate scroll back by setting the scrollTop = null, if the page is scrolled,
							// (timeout is inserted to accommodate the fact that the scroll event on the window
							// is fired after the scroll animation has ended)
							setTimeout(function() {
									$w.one("scroll", function() {
										$popup.data("popup.storage", { scrollTop: null });
									});
								},
								200
							);
						});
					}
				}
			},
            
        // Paging
		paging: {
			nextpage: null,
			pages: null,
			infScroll : null,
			url: window.location.href,
			extraScrollPx: 70,
			isFetching: false,

			config: {
				msgLoad:	"Hent flere videoklip",
				msgLoading:	"Henter flere videoklip...",
				msgNoMore:	""
			},

			init: function () {
                //alert('Engine.ui.paging.init();');
				var $movies = $("#channelmovies"),
					self = this;

				if( $movies.length <= 0 ) { return false; }
				
				/*************************************/

				this.isFetching = false;
				this.pages = parseInt($movies.attr('data-pages'), 10);
				this.nextpage = parseInt($movies.attr("data-nextpage"), 10)+1;
				
				if( this.pages <= 1 ) { return false; }

				/*************************************/

				this.url = this.url.replace(/([&?])page[=]([^&#]*)[&]*/g, "$1").replace(/[&]+$/g, "");
				
				$(".paging").hide();

				$movies.append(
					'<div id="infinite-scroll">' +
						((this.nextpage <= this.pages)? self.config.msgLoad : self.config.msgNoMore) +
					'</div>'
				);
				
				// Desktop with mouse
				$(window).bind("scroll", function() {
					if($(window).scrollTop() >= ($(document).height() - $(window).height() - self.extraScrollPx))
					{ self.fetch(); }
				});
				
				// Click
				this.infScroll = $("#infinite-scroll").click(function(){
					self.fetch();
				});
			},

			fetch: function() {
				var $infiniteScroll = $(this.infScroll),
					self = this;

				if( !!this.isFetching )
				{ return; }

				/*************************************/

				if( this.nextpage <= this.pages ) {
					this.isFetching = true;

					$infiniteScroll.html(self.config.msgLoading);
                    
					$.ajax({
						url: self.url + "?page=" + self.nextpage,
						success: function(html){
							self.isFetching = false;
							var msg = self.config.msgNoMore;

							if( !!html ){
								self.nextpage++;
								var $items = $(html).find("#channelmovies > figure");
								
								Engine.fixes.filmPlayIcon(null, $items.find("img"))

								$infiniteScroll.before($items);

								if( self.nextpage < self.pages )
								{ msg = self.config.msgLoad; }
							}

							$infiniteScroll.html(msg);
						}
					});
				} else {
					$infiniteScroll.html(self.config.msgNoMore);
				}
			}
		
        }

		}
	}
//------------ ENGINE SLUT -----------------------



    $.fn.tooltip = function (option) {
        return this.each(function () {
            //  MSIE 6 only
            var IE6 = false;
            if ($.browser.msie && $.browser.version < 7) {
                IE6 = true;
            }
            var el = $(this);
            var config = {
                title: el.attr("title"),
                text: el.attr("title"),
                xOffset: -100,
                yOffset: -25
            }
            var el = $(this).removeAttr("title").children().removeAttr("alt");
            config = $.extend(config, option);

            if (config.text == "") return;

            var showTooltip = function (e) {

                $("#tooltip")
					.html(config.text)
					.css("top", (e.pageY - config.yOffset) + "px")
					.css("left", (e.pageX + config.xOffset) + "px")
					.show();
                if (IE6) {
                    $("#page").addClass("hideSelects");
                }
            };
            var hideTooltip = function () {
                $("#tooltip").hide();
                if (IE6) {
                    $("#page").removeClass("hideSelects");
                }
            };

            $(this).bind("mouseenter", function (e) {
                showTooltip(e);
            });
            $(this).bind("mouseleave", function () {
                hideTooltip();
            });

            $(this).bind("mousemove", function (e) {
                $("#tooltip")
					.css("top", (e.pageY - config.yOffset) + "px")
					.css("left", (e.pageX + config.xOffset) + "px");
            });

        });
    };
})(jQuery);

(function ($) {
    $.fn.selectJumper = function (option) {
        return this.each(function () {
            var el = $(this);
            el.changed = false;
            el.focus(function () {
                el.initValue = el.val();
            })
            el.change(function () {
                if ((this).selectedIndex == 0) return false;

                if (!el.changed) {
                    return false;
                } else {
                    var targetUrl = el.val();
                    var indexer = targetUrl.indexOf("blank:");
                    if (indexer > -1) {
                        var urlWithoutBlank = targetUrl.substring(indexer + 6, targetUrl.length);
                        window.open(urlWithoutBlank, "jumperwindow")
                        return false;
                    }
                    else {
                        window.location.href = targetUrl;
                    }
                }
            })
            el.keydown(function (event) {
                if (((event.keyCode == 9) || (event.keyCode == 13)) && (el.val() != el.initValue)) {
                    el.changed = true;
                    el.change();
                } else if (event.keyCode == 27) {
                    (this).selectedIndex = 0;
                } else {
                    el.changed = false;
                }
            })
            el.click(function () {
                el.changed = true;
            })
        });
    }
})(jQuery);

(function ($) {
    slideSwitch = function () {
        var $active = $('.slider img.active');

        if ($active.length == 0) $active = $('.slider img:last');

        // use this to pull the images in the order they appear in the markup
        var $next = $active.next().length ? $active.next()
			: $('.slider img:first');

        // uncomment the 3 lines below to pull the images in random order

        // var $sibs  = $active.siblings();
        // var rndNum = Math.floor(Math.random() * $sibs.length );
        // var $next  = $( $sibs[ rndNum ] );

        $active.addClass('last-active');

        $next.css({ opacity: 0.0 })
			.addClass('active')
			.animate({ opacity: 1.0 }, 1000, function () {
			    $active.removeClass('active last-active');
			});
    }

    $(function () {
        var $active = $('.slider');
        if ($active.length) setInterval("slideSwitch()", 5000);
    });
})(jQuery);


