var bl = false;
var tl = false;
var wmpId = -1;

function onToolboxLoad() 
{
    tl = true;
    if (tl&&bl) initPortal();
}

                                                          
function bodyLoad()
{
    bl = true;
    if (tl&&bl) initPortal();                                                                                    
}





var client;
var contentId; // value picked from eventual parameter in url. Is set in port
var contentFormat;// value picked from eventual parameter in url. Is set in port
var encrChannelName;// value picked from eventual parameter in url. Is set in port
var defaultView;

var rightAreaBanners;
function setViewState(viewState){
    
   if(viewState == "default"){
        if(defaultView == "portal"){
            if(oMiniChannelHandler.isActive)
                return;
            $("bottom2").style.display = "block";
        }        
    }
}

function initPortal() {
    defaultView = "portal";
    if ($("serviceDown").innerHTML != "") {
        $("window").style.display = "none";
        return;
    }
    client = new Client();
    browserWindow.positionDoc();
    window.onresize = browserWindow.positionDoc;
    if (contentId != null) {
        oPlayer.view = "portal";
        oMiniChannelHandler.openAndPlay(contentId);
    }
    initRatings();
}

// Some Function to test if Cookies are allowed
function writeCookie(name,value,minutes)
{
	var expires = '';
	if (minutes)
	{
		var date = new Date();
		date.setTime(date.getTime()+(minutes*60*1000));
		expires = '; expires='+date.toGMTString();
	}
	document.cookie = name+'='+value+expires+'; path=/';
}

function readCookie(name)
{
	var nameEQ = name + '=';
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

var oCategoryViewState;
var channelAlphaDivIndex;

function initCategories(){
    defaultView = "categories";
    client = new Client();
    setPortalBranding();
    oCategoryViewState = new CategoryViewState();
    setCategoryViewState();
    historyPath.onUpdate();
    reportContentSize();
    setIndexForChannelAlphaDiv();
}

function initLogin(){
    defaultView = "login";
    client = new Client();
    setPortalBranding();
}

function initSubscriber(){
    defaultView = "subscriber";
    client = new Client();
    setPortalBranding();
}
function initPurchase(){
    defaultView = "purchase";
    client = new Client();
    setPortalBranding();
}

function forgotpw()
{
    //$("formLogin").hide(),
    //$("formForgottenPwd").show();
}

function changedetails()
{
    $("showUserDetails").hide(),
    $("changeDetails").show();
}

var encrChannelName;

function initChannel(){
    defaultView = "channel";
    if($("serviceDown").innerHTML != "")
    {
        $("window").style.display = "none";
        return;
    }
    client = new Client();
    if(contentId != null){
        $("clipInfoArea").style.display = "block";
        oPlayer.view = "channel";
        createClickEvent(contentId);
    }
    openCategory(contentId);
    browserWindow.positionDoc();
    window.onresize = browserWindow.positionDoc;
    window.onscroll = browserWindow.positionBanners;
    
    initRatings();
}

function initGeneric(){
    if($("serviceDown").innerHTML != "")
    {
        $("window").style.display = "none";
        return;
    }
    client = new Client();
    browserWindow.positionDoc();
    window.onresize = browserWindow.positionDoc;
}

function createClickEvent(contentId){   
    if(!documentUpdater.isActive){
        ajaxEngine.registerRequest("getUpdate", "../UIController.aspx");
        ajaxEngine.sendRequest("getUpdate", "contentId="+contentId);
    }
}

function prepareToPlayMedia(URI){  
        startPlayback(URI);       
}

/* Event handler functions ********************************************************************/
function onClickHandler(obj, actionParam){
    if(obj.className == "selectableContainer" && obj.parentNode.parentNode.id == "clipList"){
        try{
            parent.oPlayer.close();
        }
        catch(e){}
		
		var arrArgs = actionParam.split("_");
        var contentId = arrArgs[0];
        var channelName = arrArgs[1];;
        var format = arrArgs[2];
		
        var params = (location.href.indexOf("?")>-1)? "&"+location.href.substr(location.href.indexOf("?")+1):"";
        var href = "portal.aspx?contentId="+contentId+"&channelName="+channelName+"&format="+format+params;
        parent.window.location.href = href; 
    }
    else if(obj.className == "selectableContainer" && obj.parentNode.className == "clipList"){
        try{
            oPlayer.close();
        }
        catch(e){}
		var arrArgs = actionParam.split("_");
        var contentId = arrArgs[0];
        var format = arrArgs[1];
        //var contentId = actionParam; 
        var href = "channel.aspx?contentId="+contentId+"&channelName="+encrChannelName+"&format="+format;
        parent.window.location.href = href; 
    }
    else if(obj.className == "button" && obj.parentNode.parentNode.id == "clipListArea"){
        var clipList = (obj.nextSibling.nodeType == 1)? obj.nextSibling : obj.nextSibling.nextSibling;
        if(openClipList != null)openClipList.style.display = "none";
        clipList.style.display = "block";
        openClipList = clipList;
        browserWindow.setTheEnd(); 
        browserWindow.positionBanners(); 
    }
}

var hoverObj;

function onMouseOverHandler(obj,e){
    if (!e) var e = window.event;
    e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
	var relTarg = e.relatedTarget || e.toElement;
	try{
        if(obj.className == "imagebutton" && obj.parentNode.parentNode.id == "clipList"){
            if(hoverObj != obj){
                try{if(hoverObj.childNodes[channelAlphaDivIndex].style.display == "block")hoverObj.childNodes[channelAlphaDivIndex].style.display = "none";}catch(e){}
                hoverObj = obj;
                obj.childNodes[channelAlphaDivIndex].style.display = "block";
            }
        }
        if(obj.className == "hover" && obj.parentNode.className == "selectableContainer"){
            obj.style.backgroundImage = "url(img/clipHover.gif)";
        }
    }
    catch(e){}    
}

function onMouseOutHandler(obj,e){
    if (!e) var e = window.event;
    e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
	var relTarg = e.relatedTarget || e.toElement;
	
    if(obj.className == "imagebutton" && obj.parentNode.parentNode.id == "clipList"){
        try{
        if(relTarg != hoverObj && relTarg.parentNode != hoverObj && relTarg.parentNode.parentNode != hoverObj){
            try{if(hoverObj.childNodes[channelAlphaDivIndex].style.display == "block")hoverObj.childNodes[channelAlphaDivIndex].style.display = "none";}catch(e){}
            
            obj.childNodes[channelAlphaDivIndex].style.display = "none";
            hoverObj = null;
        }
        }catch(e){}
    }
    if(obj.className == "hover" && obj.parentNode.className == "selectableContainer"){
        obj.style.backgroundImage = "url(img/blank.gif)";
    }
}

function onKeyPressHandler(e,obj){
    var code;
	if (!e) var e = window.event;
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;
	if(code == 13)search();
}
/****************************************************************************************************/




//*** Class BrowserWindow *****************************************************************
// Handles positioning of banners and portal in the browser window
var BrowserWindow = Class.create();
BrowserWindow.prototype = {
    initialize: function() {
        this.theEnd;
        this.height;
        this.width;
        this.scrollY = 0;
    },
    setScrollY: function() { // calculates how much the page is scrolled
        if (typeof (window.pageYOffset) == 'number') {
            //Netscape compliant
            this.scrollY = window.pageYOffset;
        }
        else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
            //DOM compliant
            this.scrollY = document.body.scrollTop;
        }
        else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
            //IE6 standards compliant mode
            this.scrollY = document.documentElement.scrollTop;
        }

    },
    setSize: function() { // calculates the size of the browser window
        if (typeof (window.innerWidth) == 'number') {
            //Non-IE
            this.width = window.innerWidth;
            this.height = window.innerHeight;
        }
        else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
            //IE 6+ in 'standards compliant mode'
            this.width = document.documentElement.clientWidth;
            this.height = document.documentElement.clientHeight;
        }
        else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
            //IE 4 compatible
            this.width = document.body.clientWidth;
            this.height = document.body.clientHeight;
        }
    },
    positionDoc: function() { // Positiones mainContainer & bannerAreaRight at the right x position
        browserWindow.setSize();
        var bredd = 1000;
        if (defaultView == "channel" && document.body.className == "wideBanners") {
            bredd = 1110
        }
        $('mainContainer').style.left = (browserWindow.width) - (bredd + 100) >= 0 ? 100 + "px" : browserWindow.width - bredd > 0 ? browserWindow.width - bredd + "px" : "0px";
        if (defaultView != "portal") {
            $("bannerAreaRight").style.left = (browserWindow.width) - (bredd + 100) >= 0 ? 960 + "px" : browserWindow.width - bredd > 0 ? browserWindow.width - (bredd - 860) + "px" : 860 + "px";
        }
        if (defaultView == "channel") {
            browserWindow.setTheEnd();
            browserWindow.positionBanners();

        }
    },

    positionBanners: function() { // Positiones "bannerAreaRight" at the right y position 
        browserWindow.setScrollY();
        if (browserWindow.scrollY > 123) {
            if (browserWindow.height > 705) {
                if (browserWindow.scrollY > browserWindow.theEnd - 705) {
                    $("bannerAreaRight").style.top = (browserWindow.theEnd - 705) + "px";
                }
                else {
                    $("bannerAreaRight").style.top = browserWindow.scrollY + "px";
                }
            }
            else {
                if (browserWindow.height + browserWindow.scrollY > 828) { //826 = 705 + 121
                    if (browserWindow.height + browserWindow.scrollY > browserWindow.theEnd) {
                        $("bannerAreaRight").style.top = (browserWindow.theEnd - 705) + "px";
                    }
                    else {
                        $("bannerAreaRight").style.top = (browserWindow.height + browserWindow.scrollY - 705) + "px";
                    }
                }
            }
        }
        else {
            $("bannerAreaRight").style.top = "123px";
        }
    },
    setTheEnd: function() { //Gets the position of div "theEnd" which decides how long the page is
        var obj = $("theEnd");
        var curtop = 0;
        if (obj.offsetParent) {
            curtop = obj.offsetTop
            while (obj = obj.offsetParent) {
                curtop += obj.offsetTop
            }
        }
        this.theEnd = (curtop <= 806 || oPlayer.isFullScreen) ? 826 : curtop + 20;
    }
}
var browserWindow = new BrowserWindow();
//*********************************************************************************************

var oMiniPopup = 
{       
    initialize: function(){
	    this.checkDefaultColors();
    },
    hide: function(e){
      if($("miniPopup") && $("miniPopup").style.display == "block")
        $("miniPopup").style.display = "none"; 
    },
    show: function(htmlStr,obj,e){
        if (!e) var e = window.event;
        e.cancelBubble = true;
	    if (e.stopPropagation) e.stopPropagation();
	    $("miniPopup_content").innerHTML = htmlStr;
	    oMiniPopup.positionMe(obj);
	    $("miniPopup").style.display = "block"; 
    },
    showOnLoad: function(htmlStr,obj){
	    $("miniPopup_content").innerHTML = htmlStr;
	    oMiniPopup.positionMe(obj);
	    $("miniPopup").style.display = "block"; 
    },
    positionMe: function(obj){
        
        var x_link = this.getXForClickedObj(obj);
        
        var width_popup = 300;
                
        if((x_link + width_popup) > browserWindow.width)
        {
            var width_link = obj.offsetWidth;
            var width_endPosition = x_link + width_link;
            $("miniPopup").style.left = (width_endPosition - width_popup) + "px";
        }
        else
        {
            $("miniPopup").style.left = this.getXForClickedObj(obj) + "px";
        }
        
        $("miniPopup").style.top = (this.getYForClickedObj(obj) + obj.offsetHeight + 3) + "px";

    },// Todo: Låt dessa vara globala funktioner
    getXForClickedObj:function(obj){
        var x = 0;
	    if (obj.offsetParent) {
		    x = obj.offsetLeft
		    while (obj = obj.offsetParent) {
			    x += obj.offsetLeft
		    }
	    }
	    return x;
    },
    getYForClickedObj:function(obj){
        var y = 0;
	    if (obj.offsetParent) {
		    y = obj.offsetTop
		    while (obj = obj.offsetParent) {
			    y += obj.offsetTop
		    }
	    }
	    return y;
    }
}

Event.observe(document, 'click', oMiniPopup.hide);


var FAQ = Class.create();
FAQ.prototype = {       
    initialize: function(){
        this.activeQ;
    },
    onClick: function(obj){
        Element.extend(obj);
        if(oFAQ.activeQ != null){
            oFAQ.activeQ.removeClassName('active');
            $(oFAQ.activeQ.id + "a").style.display = "none";
        }
        obj.addClassName('active');
        $(obj.id + "a").style.display = "block";
        oFAQ.activeQ = obj;
    }
}
var oFAQ = new FAQ();


function clearText(thefield){
    if (thefield.defaultValue==thefield.value)
        thefield.value = ""
}

function clearTextPW(){
    $("fakePassWord").hide();
    $("passWord").show();
    $("passWord").focus();
}

function initRatings()
{
    if($("ratingbg"))
    {
        var contentIddiv = $("contentId"); 
        var cid = contentIddiv.innerHTML;
        
        var storedrating = parseInt(readCookie("rating_" + cid));
        if (isNaN(storedrating)) storedrating = 0;
        
        if (storedrating == 0)
        {
        //:visible;
            $("yourrating").setStyle({"visibility":"hidden"});
        }
        else
        {
            $("yourrating").innerHTML = $("yourrating").innerHTML.split("[rating]").join(storedrating);
        }
        
        if (storedrating == 0)
        {
            $("ratingbg").observe('mouseout', 
            function (event)
            {
                $("ratinguser").setStyle({"width":"1px"});
            });
            $("ratingbg").observe('mousemove', 
            function (event) 
            {
                var mouse_x = Event.pointerX(event);
                var container_x = Position.page($("ratingbg"))[0]; 
                var size = mouse_x-container_x;
                
                if (size < 16) 
                {
                    size = 16;
                } 
                else if (size < 29)
                {
                    size = 29;
                } 
                else if (size < 42)
                {
                    size = 42;
                }
                else if (size < 55)
                {
                    size = 55;
                }
                else
                {
                    size = 68;
                }
                $("ratinguser").setStyle({"width":size+"px"});
            });
            $("ratingbg").observe('click', 
            function (event) 
            {
                var mouse_x = Event.pointerX(event);
                var container_x = Position.page($("ratingbg"))[0]; 
                var size = mouse_x-container_x;
                var rating = 0;
                if (size < 16) 
                {
                    rating = 1;
                } 
                else if (size < 29)
                {
                    rating = 2;
                } 
                else if (size < 42)
                {
                    rating = 3;
                }
                else if (size < 55)
                {
                    rating = 4;
                }
                else
                {
                    rating = 5;
                }
                
                var cnftext = $("rate").innerHTML;
                cnftext = cnftext.split("[rating]").join(rating);
                
                if (top.confirm(cnftext))
                {
                    var contentId = $("contentId").innerHTML;
                    
                    new Ajax.Request("rating_ajax.aspx?cmd=rate&contentId=" + contentId + "&rating=" + rating, 
                    {
                        method: 'post',
                        onSuccess: function(transport) 
                        {
                            $("yourrating").setStyle({"visibility":"visible"});
                            $("yourrating").innerHTML = $("yourrating").innerHTML.split("[rating]").join(rating);
                            
                            writeCookie("rating_" + contentId, rating);
                            
                            alert($("rated").innerHTML);
                            
                            $("ratingbg").stopObserving('mouseout');
                            $("ratingbg").stopObserving('mousemove');
                            $("ratingbg").stopObserving('click');
                            $("ratinguser").setStyle({"width":"1px"});
                        }
                    });            
                }
            });
        }
    }
}

function showrefer()
{
    $("referer_button").setStyle({"display":"none"});
    $("refer").setStyle({"display":"block"});
}
function sendrefer()
{
    var yourname = ($("txt_yourname") == null) ? "" : $("txt_yourname").value;
    var youremail = ($("txt_youremail") == null) ? "" : $("txt_youremail").value;
    var friendsname = ($("txt_friendsname") == null) ? "" : $("txt_friendsname").value;
    var friendsemail = ($("txt_friendsemail") == null) ? "" : $("txt_friendsemail").value;
    var yourmessage = ($("txt_yourmessage") == null) ? "" : $("txt_yourmessage").value;
    
    new Ajax.Request("rating_ajax.aspx?cmd=refer&yourname="+yourname+"&youremail="+youremail+"&friendsname="+friendsname+"&friendsemail="+friendsemail+"&yourmessage=" + yourmessage,
    {
        method: 'post',
        onSuccess: function(transport) 
        {
            alert($("referer_confirmation").innerHTML);
        }
    });
    
    $("refer").setStyle({"display":"none"});
    $("referer_button").setStyle({"display":"block"});
}

