var tv4Player = {
    /* public */
    playOnLoad: null,
    adBeforeTag: null,
    adAfterTag: null,

    /* private */
    videoId: null,
    player: null,
    scriptRegExp: new RegExp("<[\\s\\/]*script\\b[^>]*>([^>]*)<\\/script>"),

	prepare: function() {
		tv4.playerInstalled = true;
		tv4.addClickEventToClass("menu-main", this.menu.handleSubmenu, true);
        tv4.addClickEventToClass("menu-path", this.menu.handleSubmenuPath, true);
        tv4.addClickEventToClass("menu-sub", this.menu.openSubmenuAtContentNode, true);
        tv4.addClickEventToClass("video-list", this.selectAndPlay, true);
        tv4.addClickEventToClass("video", this.handlePageVideos, true);
        tv4.addClickEventToClass("paging", this.loadVideoListPage, true);
        tv4.runOnDOMLoad("tv4Player.init()");
	},

    init: function() {
        if (DOMAssistant.$$("rotator")) {
            this.rotator.init();
            this.rotator.startRotator();
        }
        if (navigator.userAgent.indexOf("MSIE") >= 0 && navigator.userAgent.indexOf("Opera") < 0 && navigator.userAgent.indexOf("Mac") < 0) {
           this.populateWmpObject(0);
        }
        this.player = new VideoPlayer(0, false, false, {onVideoEnd: tv4Player.selectAndPlayNext});
        if (this.playOnLoad != null) {
            this.playOnLoad.call();
        }

        // capturing
        window.enableWaitForFlash = tv4Player.player.enableAdWait;
        window.onFlashEnd = tv4Player.player.adEnded;
        window.reloadAd = tv4Player.player.updatePageAd;
    },

    populateWmpObject: function(index) {
        var obj = DOMAssistant.$$("video" + index);
        var newCode = '<object id="video' + index + '" class="' + obj.className + '" classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6">';
        newCode += '<param name="stretchToFit" value="true"><param name="uiMode" value="none"><param name="url" value=""><param name="autoStart" value="false">';
        newCode += '<param name="enableContextMenu" value="true"><param name="volume" value="85"><param name="windowlessVideo" value="false">';
        newCode += '</object>';
        obj.outerHTML = newCode;
    },

    play: function(progId, itemId, live, title, categoryId, videoId, adCategory, duration, bufferFlash) {
		if (this.player != null) {
	        this.addLogging("video0", escape(title), duration);
	        if (title != null) {
	            DOMAssistant.$$("videoTitle0").innerHTML = title;
	        }
	        if (!adCategory) {
	            adCategory = "";
	        }
	        if (videoId != null) {
	            this.videoId = videoId;
	        }
	        var videoUrl = "http://anytime.tv4.se/webtv/metafile.asx?p=" + progId;
	        if (itemId != null) {
	            videoUrl += "&i=" + itemId;
	        }
	        videoUrl += "&bw=600";
			if (bufferFlash == null) {
				bufferFlash = "/tv4se/flash/programmetladdas.swf";
			}
	        var rotator = DOMAssistant.$$("rotator");
	        if (rotator) {
	            rotator.style.display = "none";
	        }
			this.player.start({
	                "metaUrl": videoUrl,
	                "progId": progId,
	                "hostProgId": 0,
	                "live": live,
	                "bufferFlash": bufferFlash,
	                "adCategory": adCategory,
	                "startAdPos": this.adBeforeTag,
	                "endAdPos": this.adAfterTag,
	                "programTitle": title
	            }
	        );
	        this.player.show();
	        DOMAssistant.$$("player").style.display = "block"
			if (categoryId != null) {
	            tv4Player.menu.openSubmenuAtContentNode(categoryId);
	        }
	        var synchedAd = DOMAssistant.$$("synched-ad");
			if (synchedAd) {
				synchedAd.src = synchedAd.src;
			}
		}
    },

    isPlaying: function() {
        return this.player != null && this.player.isPlaying();
    },

    selectAndPlayNext: function() {
        var active = DOMAssistant.$("#video-list .video-list .active")[0];
        if (active) {
			active = DOMAssistant.$(active);
            active.removeClass("active");
            var h3 = active.getElementsByTagName("h3")[0];
            var sibling = active.nextSibling;
            if (sibling != null) {
                sibling = sibling.nodeType && sibling.nodeType == 1 ? DOMAssistant.$(sibling) : DOMAssistant.$(sibling.nextSibling);
                if (sibling != null) {
                    sibling.addClass("active");
                    sibling.insertBefore(h3, sibling.childNodes[0]);
                    var anchor = DOMAssistant.$("#video-list .video-list .active A")[0];
                    tv4Player.loadVideo.call(anchor);
                }
            } else {
                active.removeChild(h3);
            }
        }
    },

    selectAndPlay: function() {
        var anchor = this;
        while (anchor.tagName != "A") {
			if (anchor.parentNode) {
	            anchor = anchor.parentNode;			
			} else {
				return false;
			}
        }
        var listItem = anchor.parentNode;
        while (listItem.tagName != "LI") {
            listItem = listItem.parentNode;
        }
        var active = null;
        var actives = DOMAssistant.$("#video-list .video-list .active");
        if (actives != null && actives.length > 0) {
            active = DOMAssistant.$(actives[0]);
        }
        var h3;
        if (active != null) {
            active.removeClass("active");
            h3 = active.getElementsByTagName("h3")[0];
        } else {
            h3 = document.createElement("h3");
            h3.appendChild(document.createTextNode("Nu spelas:"));
        }

        DOMAssistant.$(listItem).addClass("active");
        listItem.insertBefore(h3, listItem.childNodes[0]);
        tv4Player.loadVideo.call(anchor);
    },

    loadVideo: function() {
        if (tv4.context != null) {
            var hrefContext = this.href.replace(/.*(?:\\?|&|&amp;)renderingdepartment=(.*?)(?:&|$).*/, "$1");
            if (hrefContext != tv4.context) {
                window.location.href = this.href;
                return;
            }
        }
        var rotator = DOMAssistant.$$("rotator");
        if (rotator) {
            rotator.style.display = "none";
        }
        var player = DOMAssistant.$$("player");
        player.style.display = "block";
		DOMAssistant.$$("video-info").get(this.href + "&mode=video&popup=true", tv4Player.injectAndDisplay);
        tv4Player.scrollTo(player);
        tv4.logger.log();
    },

    handlePageVideos: function() {
        for (var parent = this; parent != null; parent = parent.parentNode) {
            if (parent.id == "video") {
                return false;
            }
        }
		var el = this;
		while (el.tagName != "A") {
			el = el.parentNode;
		}
        tv4Player.loadVideo.call(el);
    },

    loadVideoList: function() {
        var category = DOMAssistant.$$(this.className.replace(/.*category-(.*).*/, "$1"));
        var videoList = DOMAssistant.$$("video-list");
        var url = category.href + "&mode=list&popup=true";
        if (tv4Player.videoId != null) {
            url += "&videoId=" + tv4Player.videoId;
        }
        videoList.innerHTML = "";
        videoList.get(url, function(data) { this.innerHTML = data; this.style.display = "block"; tv4Player.scrollTo(this); });
        tv4Player.menu.openSubmenuAtContentNode(category.id);
    },

    loadVideoListPage: function() {
        if (this.href) {
            var url = this.href + "&mode=list&popup=true";
            if (tv4Player.videoId != null) {
                url += "&videoId=" + tv4Player.videoId;
            }
            DOMAssistant.$$("video-list").load(url);
        }
    },

    injectAndDisplay: function(data) {
        if (data != null && data.length > 0) {
            this.innerHTML = data;
            var scriptMatch = data.match(tv4Player.scriptRegExp);
            if (scriptMatch) {
                try {
                    var script = RegExp.$1;
                    if (script.length > 0) {
                        if (window.execScript) {
                            window.execScript(script);
                        } else {
                            window.setTimeout(script, 0);
                        }
                    }
                } catch (e) {}
            }
            this.style.display = "block";
        }
    },

    scrollTo: function(elm) {
        var position = Position.cumulativeOffset(this);
        window.scrollTo(position[0], position[1]);
    },

    addLogging: function(playerId, logString, duration) {
        var player = DOMAssistant.$$(playerId);
        var script1 = document.createElement("script");
        script1.language = "JScript";
        script1.htmlFor = playerId;
        script1.event = "OpenStateChange(new_state)";
        var contents1 = "davPlayerOpenStateChange(new_state);";
        var script2 = document.createElement("script");
        script2.language = "JScript";
        script2.htmlFor = playerId;
        script2.event = "PlayStateChange(new_state)";
        var contents2 = "davPlayerStateChange(new_state);";
        if (null == script1.canHaveChildren || script1.canHaveChildren) {
            script1.appendChild(document.createTextNode(contents1));
            script2.appendChild(document.createTextNode(contents2));
        } else {
            script1.text = contents1;
            script2.text = contents2;
        }
        player.parentNode.appendChild(script1);
        player.parentNode.appendChild(script2);
        var frequency = 2 * 60; // every second minute
        if (duration < 2 * 60) {
            frequency = 15; // every 15 seconds
        } else if (duration < 5 * 60) {
            frequency = 30; // every half minute
        }
        davInitStream(player, "http://secure-dk.imrworldwide.com/cgi-bin/m", "tv4stream", logString, frequency, "tv4se", window.location.href, new Array());
    },

    /* MENU */
    menu: {
        handleSubmenu: function() {
            var menuLi = this.parentNode;
            if (menuLi.hasClass("active")) {
                var submenu = DOMAssistant.$$(this.href.replace(/.*#(.*)/, "$1"));
                if (submenu.hasClass("menu-open") && ! submenu.hasClass("menu-show-content")) {
                    tv4Player.menu.openSubmenuAtContentNode(submenu.id);
                } else {
                    tv4Player.menu.closeSubmenu();
                }
            } else {
                tv4Player.menu.openSubmenu.call(this);
            }
        },

        resetSubmenu: function() {
            tv4.removeClasses(DOMAssistant.$$("submenu"), "active");
        },

        openSubmenu: function() {
            tv4Player.menu.resetSubmenu();
            this.parentNode.addClass("active");
            tv4Player.menu.openSubmenuAtContentNode(this.href.replace(/.*#(.*)/, "$1"));
        },

        closeSubmenu: function() {
            tv4Player.menu.resetSubmenu();
            tv4Player.menu.resetSubmenuPath();
            tv4Player.menu.resetSubmenuContent();
			DOMAssistant.$$("submenu-wrapper").removeClass("menu-open");
        },

        handleSubmenuPath: function() {
            tv4Player.menu.openSubmenuAtContentNode(this.href.replace(/.*#(.*)/, "$1"));
        },

        resetSubmenuPath: function() {
            DOMAssistant.$$("submenu-path").innerHTML = "";
        },

        resetSubmenuContent: function() {
            var submenuContent = DOMAssistant.$$("submenu-content");
            tv4.removeClasses(submenuContent, "menu-open");
            tv4.removeClasses(submenuContent, "menu-show-content");
        },

        openSubmenuAtContentNode: function(nodeId) {
            if (!nodeId && this.tagName != "A") {
                return;
            }
            var node = nodeId ? DOMAssistant.$$(nodeId) : this;
            if (node) {
				DOMAssistant.$$("submenu-wrapper").addClass("menu-open");
				// @todo don't fold out an already folded out menu
                if (node.href != null && node.href.length > 0 && node.href != window.location.href && node.href != window.location.href.replace(/(.*\/).*/, "$1")) {
                    // is this a leaf node - then don't fold out further but load content
                    var isLeaf = node.nextSibling == null || (node.nextSibling.nodeType == 3 && node.nextSibling.nextSibling == null);
                    if (isLeaf) {
                        var videoList = DOMAssistant.$$("video-list");
                        if (!videoList.hasClass("content-from-" + node.id)) {
                            DOMAssistant.$$("video-selections").style.display = "none";
							var url = node.href + "&mode=list&popup=true";
                            if (tv4Player.videoId != null) {
                                url += "&videoId=" + tv4Player.videoId;
                            }
                            videoList.get(url, tv4Player.injectAndDisplay);
                            tv4.logger.log();
                            videoList.className = "content-from-" + node.id;
                        }
                    } else {
                        var videoSelection = DOMAssistant.$$("video-selections");
                        if (!videoSelection.hasClass("content-from-" + node.id)) {
                            var url = node.href + "&mode=selection&popup=true";
                            if (tv4Player.videoId != null) {
                                url += "&videoId=" + tv4Player.videoId;
                            }
                            videoSelection.get(url, tv4Player.injectAndDisplay);
                            tv4.logger.log();
                            videoSelection.className = "content-from-" + node.id;
                        }
                    }
                }

                // getting submenu content
                var submenuContent = DOMAssistant.$$("submenu-content");

                // clearing submenu
                tv4Player.menu.resetSubmenuContent();

                // activating parent nodes and building path
                var nodeContainer;
                if (node.parentNode.id == "submenu-content") {
                    nodeContainer = node;
                } else {
                    nodeContainer = DOMAssistant.$(node.parentNode)
                }
                nodeContainer.addClass("menu-show-content");
                var path = new Array();
                while (nodeContainer.id != "submenu-content") {
                    if (nodeContainer.tagName == "DIV") {
                        topNodeId = nodeContainer.id;
                    }
                    var headerNode = nodeContainer.firstChild.nodeType == 3 ? nodeContainer.childNodes[1] : nodeContainer.firstChild;
                    if (headerNode.tagName == "A") {
                        var li = document.createElement("LI");
                        var a = document.createElement("A");
                        a.innerHTML = headerNode.innerHTML;
                        a.href = "#" + headerNode.id;
                        li.appendChild(a);
                        if (path.length == 0) {
                            li.className = "menu-selected";
                        }
                        path.push(li)
                    }
                    nodeContainer.addClass("menu-open");
                    nodeContainer = DOMAssistant.$(nodeContainer.parentNode);
                }
                var menuPath = DOMAssistant.$$("submenu-path");
                tv4Player.menu.resetSubmenuPath();
                if (path.length > 0) {
                    var ul = document.createElement("ul");
                    for (var i = path.length - 1; i >= 0; i--) {
                        ul.appendChild(path[i]);
                    }
                    menuPath.appendChild(ul);
                }

                // activating submenu
                var actives = DOMAssistant.$("#submenu a");
                for (var i = 0; i < actives.length; i++) {
                    var parent = DOMAssistant.$(actives[i].parentNode);
                    if (actives[i].href.match("#" + topNodeId)) {
                        parent.addClass("active");
                    } else {
                        parent.removeClass("active");
                    }
                }
            }
        }
    },

    /* ROTATOR */
    rotator: {
        rotatorPE: null,
        rotatorId: 0,
        rotatorTimeout: 5,
        delayId: null,
        rotatorPaused: false,
        rotatorDelayed: false,
        rotatorHasList: false,
        rotatorListLength: 5,

        init: function() {
            var rotator = DOMAssistant.$$("rotator");
            var hasSIFR = (typeof sIFR == "function");
            var rotatorTexts = rotator.elmsByClass("rotatorText");
                for (var i = 0; i < rotatorTexts.length; i++) {
                    rotatorTexts[i].id = "rotatorText" + i;
                    if (hasSIFR) {
                        var spanH2 = document.createElement("span");
                        spanH2.className = "sIFR-cover cover-h2";
                        rotatorTexts[i].appendChild(spanH2);
                        var spanP = document.createElement("span");
                        spanP.className = "sIFR-cover cover-p";
                        rotatorTexts[i].appendChild(spanP);
                    }
                }
            if (hasSIFR) {
                sIFR.replaceElement(".rotatorText H2", named({sFlashSrc: "/tv4se/flash/avantgardebook.swf", sColor: "#FFFFFF", sWmode: "transparent"}));
                sIFR.replaceElement(".rotatorText P", named({sFlashSrc: "/tv4se/flash/avantgardebook.swf", sColor: "#FFFFFF", sWmode: "transparent"}));
            }
            var rotatorItems = rotator.elmsByClass("rotatorItem", "a");
            for (var i = 0; i < rotatorItems.length; i++) {
                rotatorItems[i].id = "rotatorItem" + i;
                if (i > 0) {
                    Element.hide(rotatorItems[i]);
                }
            }
            tv4.addClickEventToClass("rotatorButton", this.rotateToElement);
            tv4.addClickEventToClass("rotatorItem", tv4Player.loadVideo);
        },

        startRotator: function(hasList) {
            this.stopRotator();
            this.rotatorHasList = hasList;
            this.rotatorId = 0;
            if ($("rotatorItem" + this.rotatorId) != null &&
                $("rotatorItem" + (this.rotatorId + 1))) {
                rotatorPE = new PeriodicalExecuter(this.doRotate, this.rotatorTimeout);
            }
        },

        stopRotator: function() {
            if (this.rotatorPE && this.rotatorPE.stop) {
                this.rotatorPE.stop();
            }
            this.rotatorPE = null;
            this.rotatorId = 0;
        },

        pauseRotator: function(delay) {
            if (delay) {
                window.clearTimeout(this.delayId);
                this.delayId = window.setTimeout(function() { tv4Player.rotator.resumeRotator(true); }, this.delay * 1000);
                this.rotatorDelayed = true;
            }
            this.rotatorPaused = true;
        },

        resumeRotator: function(delayFinished) {
            if (!this.rotatorDelayed || delayFinished) {
                this.rotatorDelayed = false;
                this.rotatorPaused = false;
            }
        },

        rotateToElement: function() {
            tv4Player.rotator.rotateTo(this.id.replace(/rotatorButton(.*)/, "$1"));
        },

        rotateTo: function(newId) {
            this.pauseRotator();
            var oldId = this.rotatorId;
            this.rotatorId = newId;

            if (newId == oldId) {
                this.pauseRotator(20);
                return;
            }
            // clean up last selected button
            Element.removeClassName("rotatorButton" + oldId, "selected");

            if (this.rotatorHasList) {
                Element.removeClassName("rotatorList" + oldId, "selected");
                Element.addClassName("rotatorList" + (oldId), "separated");
                if ($("rotatorList" + (oldId - 1))) {
                    Element.addClassName("rotatorList" + (oldId - 1), "separated");
                }
            }

            if ($("rotatorButton" + (oldId - 1))) {
                Element.addClassName("rotatorButton" + (oldId - 1), "separated");
            }
            var old = $("rotatorButton" + oldId);
            if (old != null && old.className.indexOf("lastButton") < 0) {
                Element.addClassName("rotatorButton" + (oldId), "separated");
            }
            // switch item text, if any
            if ($("rotatorText" + this.rotatorId)) {
                Element.hide("rotatorText" + (oldId));
                Element.show("rotatorText" + this.rotatorId);
            }

            // show new button
            Element.removeClassName("rotatorButton" + this.rotatorId, "separated");
            if ($("rotatorButton" + (this.rotatorId - 1))) {
                Element.removeClassName("rotatorButton" + (this.rotatorId - 1), "separated");
            }
            Element.addClassName("rotatorButton" + this.rotatorId, "selected");

            if (this.rotatorHasList) {
                Element.removeClassName("rotatorList" + this.rotatorId, "separated");
                if ($("rotatorList" + (this.rotatorId - 1))) {
                    Element.removeClassName("rotatorList" + (this.rotatorId-1), "separated");
                }
                Element.addClassName("rotatorList" + this.rotatorId, "selected");
            }
            // show item image
            if (oldId < newId) {
                Effect.Appear("rotatorItem"+ (this.rotatorId), {
                        duration: 0.5,
                        from: 0.0,
                        to: 1.0,
                        afterFinish: function(e) {
                            Element.hide("rotatorItem" + (oldId));
                        }
                    });
            } else {
                Effect.Appear("rotatorItem" + (this.rotatorId), {
                        duration: 0.1,
                        from: 0.0,
                        to: 1.0
                    });
                Effect.Appear("rotatorItem" + (oldId), {
                        duration: 0.5,
                        from: 1.0,
                        to: 0.0,
                        afterFinish: function(e) {
                            Element.hide("rotatorItem" + (oldId));
                        }
                    });
            }
            if (this.rotatorHasList) {
                var oldListStart = Math.floor(oldId / this.rotatorListLength) * this.rotatorListLength;
                var newListStart = Math.floor(newId / this.rotatorListLength) * this.rotatorListLength;

                for (var i = oldListStart; i < oldListStart + this.rotatorListLength; i++) {
                    if ($("rotatorList" + i)) {
                        Element.hide("rotatorList" + i);
                    }
                }
                for (var j = newListStart; j < newListStart + this.rotatorListLength; j++) {
                    if ($("rotatorList" + j)) {
                        Element.show("rotatorList" + j);
                    }
                }
            }
            this.pauseRotator();
        },

        doRotate: function() {
            tv4Player.rotator.rotate.call(tv4Player.rotator);
        },

        rotate: function() {
            try {
                if (!(this.rotatorPaused || tv4Player.isPlaying())) {
                    if($("rotatorItem" + this.rotatorId) == null) {
                        this.stopRotator();
                    } else {
                        this.rotatorId = this.rotatorId + 1;
                        if($("rotatorItem" + this.rotatorId) == null) {
                            Element.hide("rotatorItem" + (this.rotatorId - 1));
                            Element.removeClassName("rotatorButton" + (this.rotatorId - 1), "selected");
                            if ($("rotatorButton" + (this.rotatorId - 2))) {
                                Element.addClassName("rotatorButton" + (this.rotatorId - 2), "separated");
                            }
                            if (this.rotatorHasList) {
                                Element.removeClassName("rotatorList" + (this.rotatorId - 1), "selected");
                                if ($("rotatorList" + (this.rotatorId - 2))) {
                                    Element.addClassName("rotatorList" + (this.rotatorId - 2), "separated");
                                }
                            }
                            this.rotatorId = 0;
                        }
                        if (this.rotatorId > 0) {
                            if ($("rotatorText" + (this.rotatorId - 1)))
                                Element.hide("rotatorText" + (this.rotatorId - 1));
                            Element.removeClassName("rotatorButton" + (this.rotatorId - 1), "selected");
                            Element.removeClassName("rotatorButton" + (this.rotatorId - 1), "separated");
                            if (this.rotatorHasList) {
                                Element.removeClassName("rotatorList" + (this.rotatorId - 1), "selected");
                                Element.removeClassName("rotatorList" + (this.rotatorId - 1), "separated");
                            }
                        }
                        if (this.rotatorId > 1) {
                            Element.addClassName("rotatorButton" + (this.rotatorId - 2), "separated");
                            if (this.rotatorHasList) {
                                Element.addClassName("rotatorList" + (this.rotatorId - 2), "separated");
                            }
                        }
                        if ($("rotatorText" + this.rotatorId)) {
                            Element.show("rotatorText" + this.rotatorId);
                        }
                        Element.removeClassName("rotatorButton" + this.rotatorId, "separated");
                        Element.addClassName("rotatorButton" + this.rotatorId, "selected");

                        Effect.Appear("rotatorItem" + (this.rotatorId), {
                                duration: 0.5,
                                from: 0.0,
                                to: 1.0,
                                afterFinish: function(e) {
                                    if (tv4Player.rotator.rotatorId > 0) Element.hide("rotatorItem" + (tv4Player.rotator.rotatorId - 1));
                                }
                            });

                        if (this.rotatorHasList) {
                            if ((this.rotatorId) % this.rotatorListLength == 0) {
                                for (var i = this.rotatorId - this.rotatorListLength; i < this.rotatorId; i++) {
                                    if ($("rotatorList" + i)) {
                                        Element.hide("rotatorList" + i);
                                    }
                                }
                                for (var j = this.rotatorId; j < this.rotatorId + this.rotatorListLength; j++) {
                                    if ($("rotatorList" + j)) {
                                        Element.show("rotatorList" + j);
                                    }
                                }
                                Element.removeClassName("rotatorList-1", "separated");
                            } else {
                                Element.addClassName("rotatorList-1", "separated");
                            }
                            Element.removeClassName("rotatorList" + this.rotatorId, "separated");
                            Element.addClassName("rotatorList" + this.rotatorId, "selected");
                        }
                    }
                }
            } catch(e) {}
        }
    }
}
tv4Player.prepare();