﻿

// JavaScript Document

var content_markup = {
    init: function() {
        var ie6 = (parseFloat(navigator.appVersion.split('MSIE')[1]) < 7);

        //Rezbox
        if ($('searchwrapper')) { $('searchwrapper').addClassName('rezbox'); }
        if ($('pageMenu') && $('pageMenu').style.display != "none") { $('pageMenu').addClassName('rezbox'); }
        if ($('mainContentList')) { $('mainContentList').addClassName('rezbox rzbg_label'); }
        if ($('mainContentInfo')) { $$('#mainContentInfo .shortInfo, #mainContentInfo .buttons, #mainContentInfo .links, #mainContentInfo .rating, #mainContentInfo .tipafriend').invoke('addClassName', 'rezbox'); }
        $$('#middlecolumn .contentListWrapper').invoke('addClassName', 'carousel rezbox rzbg_label');
        $$('#rightcolumn .contentListWrapper').invoke('addClassName', 'rezbox');
        $$('#leftcolumn .contentListWrapper').invoke('addClassName', 'rezbox');
        if ($('curContentInfo')) $('curContentInfo').addClassName('rezbox');

        rezbox.init();

        //initiera eventuella karuseller(horisontella listor) dvs contentlistor med class="carousel"
        initCarousel_html_carousel();

        //Cover image Reflections
        $$('.coverimage img').invoke('addClassName', 'reflect rheight25 ropacity50');
        $$('.listdisplay .reflect').invoke('removeClassName', 'reflect').invoke('addClassName', 'noreflect');
        if (window.chrome) { setTimeout("addReflections()", 10); }
        else { addReflections(); }

        // "Utfällningseffekten" på kategorilistorna
        $$('#rightcolumn ul.contentlist>li:first-child', '#leftcolumn ul.contentlist>li:first-child').invoke('addClassName', 'selected');
        $$('#rightcolumn ul.contentlist>li', '#leftcolumn ul.contentlist>li').each(function(element) {
            element.observe('mousemove', Action.select.bindAsEventListener(element));
        });

        //klick på hela contentlistraden
        $$('.contentrow').each(function(element) {
            element.observe('click', Action.contentRowLink.bindAsEventListener(element));
            element.setStyle({ cursor: 'pointer' });
        });


        //Events för sökformuläret	
        if ($('search')) {
            $('search').onfocus = function() {
                if (this._cleared) return
                this.clear()
                this._cleared = true;
            }

            Event.observe('submitsearch', 'click', function(e) {
                Event.stop(e);
                Action.doSearch();
            });
            Event.observe('search', 'keyup', function(e) {
                if (e.keyCode == Event.KEY_RETURN) {
                    Event.stop(e);
                    Action.doSearch();
                }
            });
            Event.observe('search_form', 'submit', function(e) {
                Event.stop(e);
                Action.doSearch();
            });
        }
        content_markup.centreButtons();
        // IE6 workarounds
        if (ie6) {
            //fake :hoover on unsupported tags
            $$('.contentrow', '.carousel-prev', '.carousel-next').each(function(element) {
                element.observe('mousemove', Action.setHover.bindAsEventListener(element));
                element.observe('mouseout', Action.removeHover.bindAsEventListener(element));
            });
            //rezbox fix
            $$('.rezbox_wrapper').each(function(element) {
                rezbox.setFixedDimensions(element);
            });
        }

    },
    // addEvent function from http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html
    centreButtons: function() {
        //wrapper för att centrera flerradig knapptext på köpknappar vertikalt
        $$('#mainContentInfo .buttons .buy a').each(function(btn) {
            btn.innerHTML = '<div class="vert1"><div class="vert2"><div class="vert3">' + btn.innerHTML + '</div></div></div>';
        });
    }
};

Event.observe(window, 'load', content_markup.init);

/*
fredrik edgren, mps
based on cbb function by Roger Johansson, http://www.456bereastreet.com/
*/
var rezbox = {
	init : function() {
	// Check that the browser supports the DOM methods used
		if (!document.getElementById || !document.createElement || !document.appendChild) return false;
		var oElement, oOuter, tempId;
	// Find all elements with a class name of rezbox
		var arrElements = document.getElementsByTagName('*');
		var oRegExp = new RegExp("(^|\\s)rezbox(\\s|$)");
		for (var i=0; i<arrElements.length; i++) {
	// Save the original outer element for later
			oElement = arrElements[i];
			if (oRegExp.test(oElement.className)) {
	// 	Create a new element and give it the original element's class name(s)
				oOuter = document.createElement('div');
				oOuter.className = oElement.className.replace(oRegExp, '$1rezbox_wrapper$2');
	// Give the new div the original element's id if it has one
				if (oElement.getAttribute("id")) {
					tempId = oElement.id;
					oElement.removeAttribute('id');
					oOuter.setAttribute('id', '');
					oOuter.id = tempId;
				}
				
	// check if alternative background image class needs to be added
				var altBgClass = " default_rzbg";
				var classes = oOuter.className.split(' ');
					for (j=0;j<classes.length;j++) {
						if (classes[j].indexOf("rzbg_") == 0) {
							//save classname and remove from outer div
							altBgClass = ' ' + classes.splice(j,1) + '_rzbg';
						}
					}
				oOuter.className = classes.join(' ');
				
	// Change the original element's class name and replace it with the new div
				oElement.className = 'rezbox_content';
				oElement.parentNode.replaceChild(oOuter, oElement);
	// Create four new div elements and insert them into the outermost div
				var oTempDiv;
				oTempDiv = document.createElement('div');
				oTempDiv.className = 'rezbox_topleft' + altBgClass;
				oOuter.appendChild(oTempDiv);
				oTempDiv = document.createElement('div');
				oTempDiv.className = 'rezbox_topright' + altBgClass;
				oOuter.appendChild(oTempDiv);
				oTempDiv = document.createElement('div');
				oTempDiv.className = 'rezbox_bottomleft' + altBgClass;
				oOuter.appendChild(oTempDiv);
				oTempDiv = document.createElement('div');
				oTempDiv.className = 'rezbox_bottomright' + altBgClass;
				oOuter.appendChild(oTempDiv);
				
				// Insert the original element
				oOuter.appendChild(oElement);
			}
		}
	},
	// addEvent function from http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html
	addEvent : function(obj, type, fn) {
		if (obj.addEventListener)
			obj.addEventListener(type, fn, false);
		else if (obj.attachEvent) {
			obj["e"+type+fn] = fn;
			obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
			obj.attachEvent("on"+type, obj[type+fn]);
		}
	},
	
	setFixedDimensions : function(element, reset){ //use with ie6 only
			if(reset) element.setStyle({height:'auto'});
			element.down('.rezbox_topleft').setStyle({height:'auto', width:'auto'});
			element.down('.rezbox_topright').setStyle({height:'auto', width:'auto'});
			element.down('.rezbox_bottomleft').setStyle({height:'auto', width:'auto'});
			element.down('.rezbox_bottomright').setStyle({height:'auto', width:'auto'});
			var d = element.getDimensions();
			var h = d.height;
			var w = d.width;
			var pt = Number(element.getStyle('padding-top').gsub('px',''));
			var pb = Number(element.getStyle('padding-bottom').gsub('px',''));
			var pl = Number(element.getStyle('padding-left').gsub('px',''));
			var pr = Number(element.getStyle('padding-right').gsub('px',''));
			var boxh = h-pt-pb;
			var boxw = w-pl-pr;
			var parth = h/2;
			var partw = w/2;
			var parto = 0.2;
			//custom opacity
			var classes = element.className.split(' ');
			for (j=0;j<classes.length;j++) {
				if (classes[j].indexOf("ie6opacity") == 0) {
					parto = classes[j].substring(10)/100;
				} 
			}
			element.setStyle({height:boxh+'px', width:boxw+'px'});
			element.down('.rezbox_topleft').setStyle({height:parth+'px', width:partw +'px', opacity:parto});
			element.down('.rezbox_topright').setStyle({height:parth+'px', width:partw +'px', opacity:parto});
			element.down('.rezbox_bottomleft').setStyle({height:parth+'px', width:partw +'px', opacity:parto});
			element.down('.rezbox_bottomright').setStyle({height:parth+'px', width:partw +'px', opacity:parto});
		
	},
	ie6fix : function() {
		$$('.rezbox_wrapper').each(function(element){
			rezbox.setFixedDimensions(element);
		});	
	}
};

//Event.observe(window, 'load', rezbox.init);



AjaxUpdater = Class.create();
AjaxUpdater.prototype = {
    initialize: function() {
        this.requestUrl = "ajax_controller.aspx";
        var miscObj = getLoadObject('misc');
        if (miscObj) {
            this.requestUrl = miscObj.ajaxtarget || this.requestUrl;
        }
    },
    getContentDataForNewChallenge: function(obj) {
        // Get content data to call function MediaObject.newChallenge
        this.params = {};
        this.params.cmd = "content";
        this.params.contentid = obj.contentid;

        this.newAjaxRequest();
    },
    getContentAsset: function(obj) {
        var miscObj = getLoadObject('misc');
        this.params = {};
        this.params.cmd = "play";
        this.params.level = miscObj.level;
        this.params.deliverymethod = obj.deliverymethod;
        this.params.contentid = obj.contentid;
        this.params.istrailer = obj.istrailer;
        this.params.priceid = obj.priceid;
        this.params.machineid = obj.machineid;
        this.params.bitrate = obj.bitrate;
        this.params.deliverdrm = obj.deliverdrm;
        this.params.silent = obj.silent;
        this.params.format = MediaObject.properties.format;
        this.params.subscriberObjectIdForRegisterPlaybackAction = obj.subscriberObjectIdForRegisterPlaybackAction;

        this.newAjaxRequest();
    },
    login: function(loginform) {
        this.params = $(loginform).serialize();
        this.newAjaxRequest();
    },
    logout: function() {
        this.params = {};
        this.params.cmd = "logout";
        this.newAjaxRequest();
    },
    purchase: function(params) {
        this.params = params;
        this.params.cmd = "purchase";
        this.newAjaxRequest(Purchase.onAjaxFailure);
    },
    getDiscountInfo: function(params) {
        this.params = params;
        this.params.cmd = "discountcode";
        this.newAjaxRequest(Purchase.onAjaxFailure);
    },
    checkPaymentStatus: function(params) {
        this.params = params;
        this.params.cmd = "checkspaymentstatus";
        this.newAjaxRequest(Purchase.onAjaxFailure);
    },
    checkInitRedirectStatus: function(params) {
        this.params = params;
        this.params.cmd = "checksinitredirectstatus";
        this.newAjaxRequest(Purchase.onAjaxFailure);
    },
    pollLiveEvent: function() {
        this.params = {};
        this.params.cmd = "pollliveevent";
        this.params.silent = true;

        var myObj = getLoadObject("liveevent");
        if (myObj != null) {
            this.params.contentObjectId = myObj.objectid;
        }
        this.newAjaxRequest();
    },
    sendTipEmail: function(receiversEmail, sendersName, address) {
        this.params = {};
        this.params.receiversEmail = receiversEmail;
        this.params.sendersName = sendersName;
        this.params.address = address;
        this.params.cmd = "tipafriend";
        this.newAjaxRequest();
    },
    commentsChangePage: function(pageNumber) {
        this.params = {};

        var myT = getLoadObject("misc");
        var myO = getLoadObject("contentobjectid");

        if (myT != null) {
            if (myT.contentobjectid != 0)
                this.params.contentObjectId = myT.contentobjectid;
        }
        else if (myO != null) {
            if (myO.contentobjectid != 0)
                this.params.contentObjectId = myO.contentobjectid;
        }

        this.params.pageNumber = pageNumber;
        this.params.cmd = "commentschangepage";
        this.newAjaxRequest();
    },
    sendComment: function(commentTitle, commentText) {
        this.params = {};

        this.params.commentTitle = commentTitle;
        this.params.commentText = commentText;

        var myT = getLoadObject("misc");
        var myO = getLoadObject("contentobjectid");

        if (myT != null) {
            if (myT.contentobjectid != 0)
                this.params.contentObjectId = myT.contentobjectid;
        }
        else if (myO != null) {
            if (myO.contentobjectid != 0)
                this.params.contentObjectId = myO.contentobjectid;
        }

        this.params.cmd = "sendcomment";
        this.newAjaxRequest();
    },
    sendAbuse: function(commentID, abuseReason) {
        this.params = {};
        this.params.commentID = commentID;
        this.params.abuseReason = abuseReason;
        this.params.cmd = "abuse";
        this.newAjaxRequest();
    },
    saveRating: function(params) {
        this.params = params;
        this.params.cmd = "rating";
        this.newAjaxRequest();
    },
    newAjaxRequest: function(failureCallback) {
        var req = new Ajax.Request(this.requestUrl,
            {
            method: "get",
            parameters: this.params,
            onSuccess: function(transport) {
                var response = transport.responseText || "no response text";
                ajaxUpdater.onAjaxResponse(response);
            },
            onFailure: function(failure) {
                if (ajaxUpdater.params.silent) {
                    return;
                }
                if (failureCallback) {
                    failureCallback(failure);
                } else {
                    Action.showError("AjaxUpdater.newAjaxRequest :onFailure " + failure.status + ":" + failure.statusText, "Ajax error");
                }
            }
        });
    },
    onAjaxResponse: function(response) {
        var objarr = response.evalJSON();
        if (objarr.type == 'error' && !ajaxUpdater.params.silent) {
            var msg = objarr.message || "Bad response: \r" + response;
            Action.showError(msg, "Error (AjaxUpdater.onAjaxResponse)");
            return;
        }
        if (objarr.size() == 0 && !ajaxUpdater.params.silent) {
            Action.showError("Empty response: \r" + response, "Error (AjaxUpdater.onAjaxResponse)");
        }
        //		alert(objarr);
        objarr.each(function(obj) {
            if (obj.type == 'play') {//play
                MediaObject.onAjaxPlayResponse(obj);
            } else if (obj.type == 'login') {//login
                if (obj.value == 'new') {
                    Action.showLogin(obj.prelogin);
                } else {
                    Action.onAjaxLoginResponse(obj);
                }
            } else if (obj.type == 'redirect') {
                ajaxUpdater.createAndSubmitRedirectForm(obj);
            } else if (obj.type == 'purchase') {//login
                Purchase.onAjaxPurchaseResponse(obj);
            }
            else if (obj.type == 'smscode') {
                Purchase.onAjaxSmsCodeResponse(obj);
            }
            else if (obj.type == 'discountcode') {
                Purchase.onAjaxDiscountCodeResponse(obj);
            }
            else if (obj.type == 'initredirectpaymentresponse') {
                Purchase.onAjaxInitRedirectPaymentResponse(obj);
            }
            else if (obj.type == 'completeredirectpaymentresponse') {
                Purchase.onAjaxCompleteRedirectPaymentResponse(obj);
            }
            else if (obj.type == 'redirectmsg') {
                Purchase.onAjaxShowRedirectMsg(obj);
            }
            else if (obj.type == 'rating') {
                Action.onSaveRatingResponse(obj);
            }
            else if (obj.type == 'liveevent') {
                Action.onPollLiveEvent(obj);
            }
            else if (obj.type == 'tipafriend') {
                Action.onSendTipEmailResponse(obj);
            }
            else if (obj.type == 'sendcomment') {
                Action.onSendCommentResponse(obj);
            }
            else if (obj.type == 'abuse') {
                Action.onSendAbuseResponse(obj);
            }
            else if (obj.type == 'commentschangepage') {
                Action.onCommentsChangePageResponse(obj);
            }
            else if (obj.type == 'playonload') {
                MediaObject.newChallenge(obj);
            }
            else if (obj.type == 'contentpresentation') {
                var cciObj = $("curContentInfo");
                if (cciObj) {
                    if (cciObj.down('.rezbox_content'))
                        cciObj.down('.rezbox_content').update(obj.html);
                    else
                        cciObj.update(obj.html);
                    cciObj.style.display = "block";
                }
            }
            else if (!ajaxUpdater.params.silent) {
                Action.showError("Unrecognized response:<br>" + Object.toJSON(obj), "Error (AjaxUpdater.onAjaxResponse)");
            }

        });
    },
    createAndSubmitRedirectForm: function(obj) {
        var formstr = '<form id="redirectForm" method="' + obj.method + '" action="' + obj.target + '" >';
        for (prop in obj.params) {
            formstr += '<input type="hidden" id="' + prop + '" name="' + prop + '" value="' + obj.params[prop] + '"/>'
        }
        formstr += '</form>';
        var elt = document.createElement("div");
        elt.innerHTML = formstr;
        document.body.appendChild(elt);
        document.forms["redirectForm"].submit();
    }
};



Ajax.Responders.register({
	
    onCreate: function() { 
			if (!ajaxUpdater.params.silent) {
				var statusTest = globalLangObj.WC_AjaxLoaderText || "Loading data...";
				$('ajaxloaderstatus').update(statusTest);
				$('ajaxloader').setStyle('display:block');
				$(document.body).setStyle({
					cursor: 'progress'
				});
			}
		},
    onComplete: function() {
        if (0 == Ajax.activeRequestCount){
			$('ajaxloaderstatus').update("");
	        $('ajaxloader').setStyle('display:none'); 
			$(document.body).setStyle({cursor:'default'});
		}
    }
});

var ajaxUpdater;
Event.observe(window, 'load', function(){
	ajaxUpdater = new AjaxUpdater();
});




/**
 * @author mkfred
 */

var MediaObject = {
    init: function() {
        this.BWTestText = globalLangObj.WC_BWTestText || "Testing bandwidth";
        this.BWTestCurrent = globalLangObj.WC_BWTestCurrent || "Current:";
        this.BWTestAverage = globalLangObj.WC_BWTestAverage || "Average:";
        this.BWLowHeader = globalLangObj.WC_BWLowHeader || "Bandwidth to low";
        this.BWLowMsg = globalLangObj.WC_BWLowMsg || "Measured bitrate (#{measured} Kbit/s) is lower than the requested medias minimum bitrate(#{minimum} Kbit/s)";
        this.SystemTest = globalLangObj.WC_SystemTest || "Testing system";
        this.ClientTestErrorHeader = globalLangObj.WC_ClientTestErrorHeader || "Uppspelningsproblem på grund av";
        this.DownloadFileLinkText = globalLangObj.WC_DownloadFile || "Problems viewing the file? Click on this link to open in a new window.";
        this.WmvPlugin = getLoadObject('misc').wmvplugin || "wmp";
        this.FlvPlayer = getLoadObject('misc').flvplayer || "";

        this.mediaOverlayObj = $('teaser');
        MediaObject.checkPlayOnLoad();

    },
    newChallenge: function(obj) {
        this.properties = {};
        this.properties.type = obj.type || "";
        this.properties.contentid = obj.contentid || "";
        this.properties.aguid = obj.aguid || "";
        this.properties.format = obj.format.toLowerCase() || "";
        this.properties.deliverymethod = obj.deliverymethod || "";
        this.properties.minbitrate = obj.minbitrate || "0";
        this.properties.testurl = obj.testurl || "";
        this.properties.istrailer = obj.istrailer || "";
        this.properties.priceid = obj.priceid || "";
        this.properties.deliverdrm = obj.deliverdrm || "";
        //this.properties.bitrate = obj.bitrate || "";
        this.properties.bitrate = (this.properties.testurl == "") ? -1 : obj.bitrate || ""; // bitrate must be set to -1 when no bitrate testing.
        this.properties.machineid = obj.machineid || "";
        this.properties.mediaurl = obj.url || "";
        this.properties.samiurl = obj.samiurl || "";
        this.properties.container = obj.container || "trailer";
        this.properties.contenttitle = obj.contenttitle || "Video playing";
        this.properties.silent = obj.silent || false;
        this.properties.subscriberObjectIdForRegisterPlaybackAction = obj.subscriberid || 0;
        this.properties.mediaIsPostSpot = obj.mediaIsPostSpot || false;
        this.properties.amsintegrationurl = obj.amsintegrationurl || "";

        if (this.properties.mediaurl.indexOf(";") != -1) //Fulkod, until CF handles secure ticketing.
        {
            var ar = this.properties.mediaurl.split(";");
            this.properties.mediaurl = ar[0];
            this.properties.hashcode = ar[1];
        }
        if (this.properties.format.indexOf(";") != -1) //Fulkod, until CF handles secure ticketing.
        {
            var ar = this.properties.format.split(";");
            this.properties.format = ar[0];
        }

        this.clientTest(this.properties.format);

        //		this.deliveryTest();
        //		this.onCheckBandWidthDone(3000);

    },
    checkPlayOnLoad: function() {
        if (toolbox != undefined) {
            if (toolbox.loaded) {
                /*
                loginState value is based on enum LoginState:
                LoginSuccess = 0,
                LoginFailed = 1,
                RecoverSuccess = 2,
                RecoverFailed = 3,
                Undefined = 4   
                */
                if (loginState != 1 && loginState != 3 && loginState != 2) {
                    var playObj = getLoadObject('playonload');
                    if (playObj) {
                        playObj.silent = true;
                        MediaObject.newChallenge(playObj);
                    }
                    var playUrlObj = getLoadObject('playurlonload');
                    if (playUrlObj) {
                        MediaObject.newChallenge(playUrlObj);
                        MediaObject.getMedia(playUrlObj)
                    }
                }
            } else {
                window.setTimeout(MediaObject.checkPlayOnLoad, 1000);
            }
        }
    },
    showClientTestProgress: function(show) {
        if (MediaObject.properties.silent) {
            return;
        }
        if (show) {
            $('ajaxloaderstatus').update(SystemTest);
            $('ajaxloader').setStyle('display:block');
            $(document.body).setStyle({ cursor: 'progress' });
            var ie6 = (parseFloat(navigator.appVersion.split('MSIE')[1]) < 7);
            if (ie6) {
                rezbox.setFixedDimensions($('ajaxloader'), true);
            }

        } else {
            if (0 == Ajax.activeRequestCount) {
                $('ajaxloaderstatus').update("");
                $('ajaxloader').setStyle('display:none');
                $(document.body).setStyle({ cursor: 'default' });
            }
        }
    },
    clientTest: function(format) {
        this.showClientTestProgress(true);
        switch (format) {
            case "flv":
            case "flvlive":
            case "mp4":
            case "mp3":
                verify.setupTest("flash", "false");
                verify.checkSystem(this.onClientTestDone);
                break;
            case "fil":
            case "pdf":
                this.getMedia();
                break;
            case "peertv":
                verify.setupTest("silverlight-peertv");
                verify.checkSystem(this.onClientTestDone);
                break;
            default: //wmv
                if ((WmvPlugin == "silverlight" || WmvPlugin == "smoothstreaming") && this.properties.deliverymethod == "stream") {
                    verify.setupTest("silverlight", "false");
                    verify.checkSystem(this.onClientTestDone);
                } else {//windows media player
                    client.checkWMP();
                    verify.setupTest(this.properties.deliverymethod, this.properties.deliverdrm);
                    verify.checkSystem(this.onClientTestDone);
                }

                break;
        }
    },
    onClientTestDone: function(actions, verified) {
        MediaObject.showClientTestProgress(false);
        if (verified) {
            MediaObject.deliveryTest();
        } else if (!MediaObject.properties.silent) {
            if (0 == Ajax.activeRequestCount) {
                $('ajaxloader').hide();
                document.body.setStyle({ cursor: 'default' });
            }
            var res = "";
            var errCount = 0;
            var titlepref;
            var textpref;
            var srclink;
            var srclinkLabel;
            var header = ClientTestErrorHeader;
            actions.each(function(action) {
                if (action.result == 0) {
                    errCount++;
                    titlepref = (errCount == 1) ? ': ' : ', ';
                    textpref = (errCount == 1) ? '<br>' : '<br><br>';
                    srclinkLabel = action.sourcename || "Link";
                    if (action.type == "software") {
                        srclink = '<br><a href="' + action.source + '" target="_blank">' + srclinkLabel + '</a>';
                    }
                    else
                        if (action.type == "script") {
                        srclink = '<br><a href="javascript:' + action.source + '();">' + srclinkLabel + '</a>';
                    } else {
                        srclink = '';
                    }
                    header += titlepref + action.text.title;
                    res += textpref + '<span class="title">' + action.text.title + ':</span><br>' + action.text.text + srclink;
                    //res += '<br><a href="javascript:MediaObject.deliveryTest();">continue anyway (development purposes)</a>';
                }
            });
            Action.showError(res + '<br><br>', header);
        }
    },
    deliveryTest: function() {
        this.showClientTestProgress(true);
        if ((this.properties.format == "wmv" || this.properties.format == "flv" || this.properties.format == "flvlive" || this.properties.format == "mp4") && this.properties.testurl != "") {
            if (this.properties.deliverymethod == "stream" && (WmvPlugin != "silverlight" && WmvPlugin != "smoothstreaming")) {
                verify.checkBandWidth(this.properties.testurl, this.onCheckBandWidthDone, false, this.properties.minbitrate, this.onCheckBandWidthProgress);
            }
            else if (this.properties.deliverymethod == "stream" && (WmvPlugin == "silverlight" || WmvPlugin == "smoothstreaming")) {
                verify.checkBandWidth(toolbox_settings.SilverlightFlashTestURI, this.onCheckBandWidthDone, false, this.properties.minbitrate, this.onCheckBandWidthProgress);
            }
            else
                if (this.properties.deliverymethod == "download") {
                this.properties.machineid = client.getMachineId();
                this.getMedia();
            }
            else {
                MediaObject.getMedia();
            }
        }
        else {
            MediaObject.getMedia();
        }

    },
    onCheckBandWidthProgress: function(caBW, cBW, percent) {
        var bwstr = '<div style="text-align:left">' +
					this.BWTestText +
					'<div style="margin:10px 1px;padding:2px;background:#CCC;width:' + percent + '%">' + percent + '%</div>' +
					'<table style="width:100%";border:0;>' +
						'<thead>' +
							'<tr>' +
							'<td>' + this.BWTestCurrent + '</td>' +
							'<td>' + this.BWTestAverage + '</td>' +
							'</tr>' +
						'</thead>' +
						'<tbody>' +
							'<tr>' +
								'<td>' + cBW + ' Kbit/s</td>' +
								'<td>' + caBW + ' Kbit/s</td>' +
							'</tr>' +
						'</tbody>' +
					'</table>' +
					'</div>';
        if ($('ajaxloaderstatus')) {
            $('ajaxloaderstatus').update(bwstr);
        }
        var ie6 = (parseFloat(navigator.appVersion.split('MSIE')[1]) < 7);
        if (ie6) {
            rezbox.setFixedDimensions($('ajaxloader'), true);
        }
    },
    onCheckBandWidthDone: function(measuredBitrate) {
        //alert("onCheckBandWidthDone " + measuredBitrate);
        MediaObject.showClientTestProgress(false);
        MediaObject.properties.bitrate = measuredBitrate;
        if (MediaObject.properties.bitrate >= MediaObject.properties.minbitrate) {
            MediaObject.getMedia();
        } else if (!MediaObject.properties.silent) {
            var errTemplate = new Template(BWLowMsg);
            var bitrates = { measured: measuredBitrate, minimum: MediaObject.properties.minbitrate };
            var msg = errTemplate.evaluate(bitrates);
            Action.showError(msg, BWLowHeader);
        }
    },
    getMedia: function() {
        MediaObject.showClientTestProgress(false);
        if (MediaObject.properties.mediaurl != "") {
            MediaObject.playMedia();
        }
        else {
            if (ajaxUpdater != null) {
                ajaxUpdater.getContentAsset(MediaObject.properties); // --> onAjaxPlayResponse              
            }
            else {
                setTimeout("MediaObject.getMedia()", 500);
            }
        }
    },
    onAjaxPlayResponse: function(obj) {
        if (obj.value == "failed") {
            var msg = obj.msg || "ajaxresponse value: failed";
            Action.showError(msg + "<br>(MediaObject.onAjaxPlayResponse)", "Play Response Error ");
            return;
        }


        MediaObject.properties.mediaurl = obj.asseturl || "";
        MediaObject.properties.contenttitle = obj.contenttitle || "";
        MediaObject.properties.samiurl = obj.samiurl || "";
        MediaObject.properties.aguid = obj.aguid || "";
        MediaObject.properties.cpprespoturl = obj.prespoturl || "";
        MediaObject.properties.cppostspoturl = obj.postspoturl || "";
        MediaObject.properties.hascpspots = obj.hascpspots || false;
        MediaObject.properties.amsintegrationurl = obj.amsintegrationurl || "";
        MediaObject.properties.player = obj.player || "";
        MediaObject.properties.contentid = obj.contentid || "";

        if (MediaObject.properties.mediaurl.indexOf(";") != -1) //Fulkod, until CF handles secure ticketing.
        {
            var ar = MediaObject.properties.mediaurl.split(";");
            MediaObject.properties.mediaurl = ar[0];
            MediaObject.properties.hashcode = ar[1];
        }


        if (obj.showinfo) {
            var label = obj.showinfolabel || "";
            Action.showError(obj.showinfo, label);
        }
        var WmvPlugin = getLoadObject('misc').wmvplugin || toolbox_settings.WmvPlugin || "wmp";

        if (((WmvPlugin != "silverlight" && WmvPlugin != "smoothstreaming") || MediaObject.properties.deliverymethod == "download") && MediaObject.properties.deliverdrm && obj.licenseserver) {    //alert("deliverDRMLicense" + obj.licenseserver + "," + obj.cguid + "," + obj.aguid + "," + obj.sguid + MediaObject.onDRMLicense);
            wmpobject.deliverDRMLicense(obj.licenseserver, obj.cguid, obj.aguid, obj.sguid, MediaObject.onDRMLicense);
        } else {
            MediaObject.playMedia();
        }

    },
    onDRMLicense: function(licOk, errCode, errMessage) {
        //alert("MediaObject.onDRMLicense licOk:" + licOk);
        if (licOk) {
            MediaObject.playMedia();
        } else {
            Action.showError(errMessage + "<br>errorcode:" + errCode + "<br>(MediaObject.onDRMLicence)", "DRM delivery Error ");
        }
    },
    playMedia: function() {
        if (this.properties.hashcode == "LLN" || this.properties.hashcode == "IPO" || this.properties.hashcode == "QKN" || this.properties.hashcode == "QWM") //Fulkod, until CF handles secure ticketing.
        {
            var req = new Ajax.Request
            (getLoadObject("misc").hasheruri,
                {
                    method: "POST",
                    postBody: "<hash><uri>" + MediaObject.properties.mediaurl + ";" + MediaObject.properties.hashcode + "</uri></hash>",
                    onSuccess: function(transport) {
                        delete MediaObject.properties.hashcode;
                        MediaObject.properties.mediaurl = transport.responseText;
                        MediaObject.playMedia();
                    },
                    onFailure: function(failure) {
                        alert("Error while hashing uri!");
                    }
                }
            );
            return;
        }

        this.showClientTestProgress(false);

        if (this.properties.format == "fil") {
            this.openFile();
        }
        else if (this.properties.format == "pdf") {
            this.openPdf();
        }
        else if (this.properties.deliverymethod != "download") {//windows media
            this.preparePlayInToolbox();
        } // download, do nothing
    },
    preparePlayInToolbox: function() {
        if (this.wmpId == undefined) {
            this.createToolboxPlayer();
        }
        spotInjection.resetSpotUrls(); //sets prespoturl & postspoturl to ""

        //Verify boolean for isTrailer
        var isTrailer = Boolean(this.properties.istrailer && this.properties.istrailer != "false");

        if (!isTrailer)
            spotInjection.setSpotUrls();
        else
            this.playInToolbox();
    },
	useSmoothing: false,
	spotControls: "disabled",
    playInToolbox: function() {

        if (this.properties.mediaurl) {
            if (FlvPlayer == "MultiPlayer") {
                toolbox_settings.FLAPlayerUri = toolBoxURI + "resources/MultiPlayer.swf";
                MediaObject.showMedia();

                wmpobject.resetURIs(this.wmpId);
                if (!this.properties.mediaIsPostSpot) {

                    if (spotInjection.preContentSpotUrl) {
                        var extraParamsPre = new Object();
                        extraParamsPre["src"] = spotInjection.preContentSpotUrl;
                        extraParamsPre["mode"] = "overlay";
                        extraParamsPre["frameColor"] = "000000";
                        extraParamsPre["eventlistener"] = "MediaObject.multiPlayerEventListener";
                        extraParamsPre["controls"] = this.spotControls;
						if(this.useSmoothing){
							extraParamsPre["smoothing"] = "true";
						}
                        wmpobject.adduri(this.wmpId, spotInjection.preContentSpotUrl, "", true, true, true, null, null, extraParamsPre);
                    }

                    var extraParamsMain = new Object();
                    extraParamsMain["src"] = this.properties.mediaurl;
                    extraParamsMain["mode"] = "overlay";
                    extraParamsMain["frameColor"] = "000000";
                    extraParamsMain["eventlistener"] = "MediaObject.multiPlayerEventListener";
					if(this.useSmoothing){
						extraParamsMain["smoothing"] = "true";
					}
                    wmpobject.adduri(this.wmpId, this.properties.mediaurl, this.properties.samiurl, true, true, true, null, null, extraParamsMain);

                }

                if (spotInjection.postContentSpotUrl) {
                    var extraParamsPost = new Object();
                    extraParamsPost["src"] = spotInjection.postContentSpotUrl;
                    extraParamsPost["mode"] = "overlay";
                    extraParamsPost["frameColor"] = "000000";
                    extraParamsPost["eventlistener"] = "MediaObject.multiPlayerEventListener";
					extraParamsPost["controls"] = this.spotControls;
					if(this.useSmoothing){
						extraParamsPost["smoothing"] = "true";
					}
                    wmpobject.adduri(this.wmpId, spotInjection.postContentSpotUrl, "", true, true, true, null, null, extraParamsPost);
                }

                wmpobject.play(this.wmpId);
            }
            else {
                MediaObject.showMedia();

                wmpobject.resetURIs(this.wmpId);

                if (!this.properties.mediaIsPostSpot) {

                    if (spotInjection.preContentSpotUrl) {
                        var extraParamsPre = new Object();
                        extraParamsPre["highlightColor"] = this.highlightColor; //TODO: FREDDAN!
                        extraParamsPre["contentName"] = this.properties.contenttitle;
                        extraParamsPre["contentUrl"] = spotInjection.preContentSpotUrl;
                        extraParamsPre["captionUrl"] = "";
                        wmpobject.adduri(this.wmpId, spotInjection.preContentSpotUrl, "", true, true, true, null, null, extraParamsPre);
                    }


                    var miscObj = getLoadObject('misc');
                    var extraParamsMain = new Object();
                    extraParamsMain["highlightColor"] = this.highlightColor; //TODO: FREDDAN!
                    extraParamsMain["contentName"] = this.properties.contenttitle;
                    extraParamsMain["contentUrl"] = this.properties.mediaurl;
                    extraParamsMain["captionUrl"] = this.properties.samiurl;
                    if (miscObj) {
                        extraParamsMain["sessionContext"] = miscObj.sessioncontext || "0";
                        extraParamsMain["subscriberObjectId"] = miscObj.subscriberobjectid || 0;
                        extraParamsMain["serviceObjectId"] = miscObj.serviceobjectid || 0;
                    }
                    if (this.properties.format == "flvlive") {
                        extraParamsMain["isLive"] = "true";
                    }
                    extraParamsMain["contentObjectId"] = this.properties.contentid || 0;
                    extraParamsMain["aguid"] = this.properties.aguid || 0;
                    wmpobject.adduri(this.wmpId, this.properties.mediaurl, this.properties.samiurl, true, true, true, null, null, extraParamsMain);

                }

                if (spotInjection.postContentSpotUrl) {
                    var extraParamsPost = new Object();
                    extraParamsPost["highlightColor"] = this.highlightColor; //TODO: FREDDAN!
                    extraParamsPost["contentName"] = this.properties.contenttitle;
                    extraParamsPost["contentUrl"] = spotInjection.postContentSpotUrl;
                    extraParamsPost["captionUrl"] = "";
                    wmpobject.adduri(this.wmpId, spotInjection.postContentSpotUrl, "", true, true, true, null, null, extraParamsPost);
                }
                wmpobject.play(this.wmpId);
            }



        } else {
            var desc = (wmpObj ? "" : "wmpObj missing <br>") + (this.properties.mediaurl ? "" : "mediaUrl missing <br>") + (wmpObj.msg ? wmpObj.msg : "");
            Action.showError(desc, "Error in mediaObject.playWmp");
        }
    },
    createToolboxPlayer: function() {
        var mediaContainer = MediaObject.properties.container;

        toolbox_settings.MP3PlayerUri = "soundplayer.swf";
        toolbox_settings.FLAPlayerUri = "flvplayer.swf";
        toolbox_settings.FLAControllerFullUri = "flvplayerskin.swf";
        toolbox_settings.FLAControllerNoneUri = "nothing.swf";

        toolbox_settings.WmvPlugin = WmvPlugin;

        this.wmpId = wmpobject.create(mediaContainer, "100%", "100%");

        /* Set properties */
        if (WmvPlugin == "silverlight") {

            var miscObj = getLoadObject('misc');
            wmpobject.addParam(this.wmpId, "subscriberobjectid", miscObj.subscriberobjectid);
            wmpobject.addParam(this.wmpId, "contentobjectid", miscObj.contentobjectid);
            wmpobject.addParam(this.wmpId, "serviceobjectid", miscObj.serviceobjectid);
            wmpobject.addParam(this.wmpId, "subscribercontext", miscObj.sessioncontext);

            toolbox_settings.SilverlightTheme = miscObj.silverlighttheme || toolbox_settings.SilverlightTheme;
            toolbox_settings.PlayReadyServerURL = miscObj.playreadyserverurl || toolbox_settings.PlayReadyServerURL;

        }
        else if (WmvPlugin == "smoothstreaming") {

            var miscObj = getLoadObject('misc');
            wmpobject.addParam(this.wmpId, "licenseuri", miscObj.licenseuri);

        }
        else {
            wmpobject.addParam(this.wmpId, "allowFullScreen", "true");
            wmpobject.addParam(this.wmpId, "autostart", "true");
            wmpobject.addParam(this.wmpId, "mute", "false");
            wmpobject.addParam(this.wmpId, "enableContextMenu", "false");
            wmpobject.addParam(this.wmpId, "uiMode", "full");
            wmpobject.addParam(this.wmpId, "volume", "50");
            wmpobject.addParam(this.wmpId, "windowlessVideo", "false");
            wmpobject.addParam(this.wmpId, "stretchToFit", "true");
        }
        /* add Listeners*/
        wmpobject.addListener(this.wmpId, "all", MediaObject.wmpEvents);

        wmpobject.setFullscreenUrl("fullscreen_wmp.aspx");
    },
    stopMedia: function() {
        this.stopWmp();
        this.stopFvp();
        this.hideMedia(true);
    },
    stopWmp: function() {
        try {
            if (this.wmpId > -1) {
                var wmpObj = this.getWmpObj();
                if (wmpObj.controls.isAvailable('Stop')) {
                    wmpObj.controls.stop();
                }
            }
        }
        catch (e) { }
    },
    getWmpObj: function() {
        try {
            return wmpobject.getWmp(this.wmpId);
        }
        catch (e) {
            return false;
        }
    },
    wmpEvents: function(id, wmpObj, eventName, args) {
        switch (eventName.toLowerCase()) {
            case "click":
                if (args[0] == 1) {
                    /* Go Fullscreen on Click*/
                    wmpobject.setFullscreen(id);
                }
                break;

            case "playstatechange":
                /* When playing, switch to pause */

                if (wmpObj.playState == 3) {
                    MediaObject.showMedia();
                    MediaObject.playstatus = "playing";
                    //					 alert("SAMIFileName:" + MediaObject.getWmpObj().closedCaption.SAMIFileName)
                    //if (document.getElementById("tooglePlay").value != "Pause") document.getElementById("tooglePlay").value = "Pause";
                }
                else if (wmpObj.playState == 1) //Stopped
                {
                    MediaObject.hideMedia();
                }
                else if (wmpObj.playState == 8) //media ended
                {
                    //playlists is handled in toolbox
                }
                else {

                    //if (document.getElementById("tooglePlay").value != "Play") document.getElementById("tooglePlay").value = "Play";
                }
                break;

            case "statuschange":
                /* Show MediaPlayer Status */
                //document.getElementById("MediaStatus").innerHTML = wmpObj.status;
                break;
            case "error":
                var errItem = wmpObj.error.item(wmpObj.error.errorCount - 1);
                if (errItem.errorCode == -1072879433) {//A problem has occurred in the Digital Rights Management component. Contact Microsoft product support.
                    if (confirm("Windows Media Player cannot play the protected file because a security upgrade is required. Do you want to download the security upgrade?")) {
                        window.open("http://drmlicense.one.microsoft.com/crlupdate/en/crlupdate.html");
                    };
                }
                break;
        }
    },
    multiPlayerEventListenerTimer: 0,
    multiPlayerEventListener: function(type, data) {
        if (type == "metadata") {
            if (data.height && data.width) {
                var dimObj = {};
                dimObj.width = data.width;
                dimObj.height = data.height;
                MediaObject.showMedia(dimObj);
            }
        } else
            if (type == "start") {
            clearTimeout(MediaObject.multiPlayerEventListenerTimer);
        } else
            if (type == "end") {
            MediaObject.multiPlayerEventListenerTimer = setTimeout(function() {
                if (!wmpobject.playNext(MediaObject.wmpId)) MediaObject.hideMedia();
            }, 2000);
        }
    },
    refreshWmp: function() {
        if (!Prototype.Browser.IE && MediaObject.getCurrentPlayingFormat().indexOf("wmv") == 0 && WmvPlugin != "silverlight" && WmvPlugin != "smoothstreaming") {
            var mediacontainer = MediaObject.properties.container;
            $(mediacontainer).innerHTML = $(mediacontainer).innerHTML;
        }
    },
    setWmpUiMode: function(newMode) {
        if (this.wmpId > -1 && this.getWmpObj()) {
            this.getWmpObj().uiMode = newMode;
        }
    },
    stopFvp: function() {
        try {
            var fvp = this.getFvpObj();
            if (fvp) {
                fvp.FVPStop();
            }
        }
        catch (e) { }
    },
    getFvpObj: function() {
        if (navigator.appName.indexOf("Microsoft") != -1) {
            return window.flashPlayerObj;
        }
        else {
            return document.flashPlayerObj;
        }
    },
    onFvpNsStatus: function(nsStatus) {
        switch (nsStatus) {
            case "NetStream.Play.Start":

                break;

            case "NetStream.Play.Stop":
            case "Stop":
                if (!wmpobject.playNext(this.wmpId)) MediaObject.hideMedia();
                break;
        }

    },
    fvpDisconnectDuplicateSubscriber: function(ip) {
        var label = globalLangObj.WC_FmsDuplicateSubscriberError_label || "Multiple users";
        var msg = globalLangObj.WC_FmsDuplicateSubscriberError || "You have been disconnected from the server since another user (#{userip}) has connected with the same subscriber id.";
        var errTemplate = new Template(msg);
        var translations = { userip: ip };
        var desc = errTemplate.evaluate(translations);
        Action.showError(desc, label);
    },
    getMediaDimensions: function() {
        var dimObj = {};
        try {
            if (this.properties.format == 'flv' || this.properties.format == 'flvlive' || this.properties.format == 'mp4') {
                var fvp = this.getFvpObj();
                if (fvp) {
                    var dim = fvp.getMediaDimensions();
                    //alert("flashdim:" + dim.width + "/" + dim.height);
                }
                if (dim) {
                    dimObj.width = dim.width || 14;
                    dimObj.height = dim.height || 9;
                }
                else {
                    dimObj.width = 14;
                    dimObj.height = 9;
                }
            } else if (this.properties.format == 'mp3') {
                dimObj.width = 580;
                dimObj.height = 31;
            } else {
                dimObj.width = this.getWmpObj().currentMedia.imageSourceWidth || 14;
                dimObj.height = this.getWmpObj().currentMedia.imageSourceHeight || 9;
                //alert("dimObj.width:" + dimObj.width + ", dimObj.height:" + dimObj.height);
            }
        }
        catch (e) {
            dimObj.width = 14;
            dimObj.height = 9;
        }
        finally {
            return dimObj;
        }
    },

    showMedia: function(dimObj) {
        var mediacontainer = MediaObject.properties.container;
        if (mediaOverlayObj) {
            if (mediaOverlayObj.visible()) {
                var teaserHeight = mediaOverlayObj.getHeight();
                mediaOverlayObj.hide();
                $(mediacontainer).setStyle({
                    height: teaserHeight + 'px'
                }, true);
            }
        }
        $(mediacontainer).removeClassName('hidden');
        var mediaDim = dimObj || MediaObject.getMediaDimensions();
        var h = Math.round(mediaDim.height * $(mediacontainer).getWidth() / mediaDim.width);

        if (this.wmpId > -1 && MediaObject.getWmpObj()) {
            if (MediaObject.getWmpObj().uiMode == 'full' || MediaObject.getWmpObj().uiMode == 'mini') h += 65;
        }

        if (h != $(mediacontainer).getHeight()) {

            MediaObject.setWmpUiMode("invisible");
            $(mediacontainer).morph('height:' + h + 'px', {
                afterFinish: function() {
                    MediaObject.setWmpUiMode("full");
                    MediaObject.refreshWmp();
                }
            });
        }

    },
    hideMedia: function(ignoreAds) {
        if (!ignoreAds && !MediaObject.properties.istrailer) { // if hideMedia is not called from MediaObject.stopMedia
            if (!MediaObject.properties.mediaIsPostSpot && MediaObject.properties.amsintegrationurl != "") {
                spotInjection.getSpotUrlFromAdManagementSystem("post");
                return;
            }
            else if (MediaObject.properties.mediaIsPostSpot)
                MediaObject.properties.mediaIsPostSpot = false;
        }

        // If service uses DirectPlayback (no content pages) #curContentInfo contains contentInfo.
        // When mediaplayer is hidden #curContentInfo is also hidden.
        if ($("curContentInfo").style.display == "block")
            $("curContentInfo").style.display = "none";

        var mediacontainer = MediaObject.properties.container;
        if ($(mediacontainer).getHeight() != 0) {
            if (Prototype.Browser.IE) {
                MediaObject.setWmpUiMode("invisible"); //hänger firefox!
            }
            var teaserHeight = 0;
            if (mediaOverlayObj) {
                teaserHeight = mediaOverlayObj.getHeight();
            }
            $(mediacontainer).update('');
            $(mediacontainer).morph('height:' + teaserHeight + 'px', {
                afterFinish: function() {
                    $(mediacontainer).addClassName('hidden');
                    $(mediacontainer).setStyle({ height: 0 }, true);
                    if (mediaOverlayObj) {
                        mediaOverlayObj.show();
                    }
                }
            });
        }
    },
    openFile: function() {
        $(this.properties.container).removeClassName('hidden');
        $(this.properties.container).morph('height:15px');
        $(this.properties.container).innerHTML = '<a title="Download" target="download" href="' + this.properties.mediaurl + '">' + DownloadFileLinkText + '</a>'
        window.open(this.properties.mediaurl, this.properties.contenttitle);
    },
    openPdf: function() {
        if (mediaOverlayObj) {
            mediaOverlayObj.hide();
        }
        $(this.properties.container).removeClassName('hidden');
        $(this.properties.container).setStyle('height:520px');
        $(this.properties.container).innerHTML = '<iframe src="' + this.properties.mediaurl + '#navpanes=0&statusbar=0&toolbar=0&view=Fit" href="' + this.properties.mediaurl + '" width="100%" style="position:relative;height:500px;" ></iframe><a title="Download" style="text-decoration: underline;margin-left:0.5em;" target="download" href="' + this.properties.mediaurl + '">' + DownloadFileLinkText + '</a>';
    },
    getCurrentPlayingUrl: function() {
        return wmpobject.getURL(MediaObject.wmpId) || "";
    },
    getCurrentPlayingFormat: function() {
        var arr = this.getCurrentPlayingUrl().split(".");
        return arr[arr.length - 1].toLowerCase();
    },
    test: function() {

    }
};

Event.observe(window, 'load', MediaObject.init);



/**
 * @author mkfred
 */
var Action = {
    setContentDisplay: function(displaytype) {
        var displayclass = displaytype || 'gallerydisplay';
        $('mainContentList').removeClassName('gallerydisplay').removeClassName('listdisplay');
        $('mainContentList').addClassName(displayclass);
        this.createCookie("mainContentListDisplayType", displayclass);
        if (displayclass == 'gallerydisplay') {
            $$('.gallerydisplay .noreflect').invoke('removeClassName', 'noreflect').invoke('addClassName', 'reflect');
            if (window.chrome) { setTimeout("addReflections()", 10); }
            else { addReflections(); }
        }
        var ie6 = (parseFloat(navigator.appVersion.split('MSIE')[1]) < 7);
        if (ie6) {
            rezbox.setFixedDimensions($('mainContentList'), true);
        }
    },

    setBodyClass: function(style) {
        $$('body').first().className = style;
    },

    select: function(event) {
        if (!this.hasClassName('selected')) {
            this.siblings().invoke('removeClassName', 'selected');
            this.addClassName('selected');
        }
    },
    contentRowLink: function(e) {
        var target = $(e.target);
        var tag = target.tagName;
        var link;
        if (tag != "A") {
            if (target.down("a.moreinfo")) {
                link = target.down("a.moreinfo");
            }
            else
                if (target.up(".contentrow").down("a.moreinfo")) {
                link = target.up(".contentrow").down("a.moreinfo");
            }
        }
        if (link) {
            if (link.protocol == "javascript:")
                eval(link.href.substr(11));
            else {
                if (link.target == "")
                    location.href = link;
                else {
                    var newWindow = window.open(link.href, '_blank');
                    newWindow.focus();
                }
            }
        }
    },
    setHover: function(event) {
        this.addClassName('hover');
    },
    removeHover: function(event) {
        this.removeClassName('hover');
    },
    showError: function(description, label) {
        var l = label || "&nbsp;";
        var d = description || "undefined error";
        var errorClose = globalLangObj.WC_Close || "CLOSE";
        var errorStr = '<div class="error">' +
		                    '<h3 class="label">' + l + '</h3>' +
		                    '<div class="description">' + d + '</div>' +
		                    '<a href="#" class="lbAction closebtn" rel="deactivate">' + errorClose + '</a>' +
		               '</div>';
        try {
            MediaObject.stopMedia();
        } catch (e) { }
        try {
            Lightbox.showMessage(errorStr);
        } catch (e) {
            window.setTimeout('Action.showError("' + d + '", "' + l + '")', 1000);
        }
    },
    pollLiveEvent: function() {
        ajaxUpdater.pollLiveEvent();
    },
    onPollLiveEvent: function(obj) {
        if (obj.stillwaiting == "True") {
            var myObj = getLoadObject("liveevent");
            if (myObj != null) {
                setTimeout("Action.pollLiveEvent()", 30000);
                $("playlivebuttontext").innerHTML = myObj.buttontext + obj.message;
            }
        }
        else {
            location.href = location.href;
        }
    },
    commentsChangePage: function(pageNumber) {
        ajaxUpdater.commentsChangePage(pageNumber);
    },
    onCommentsChangePageResponse: function(obj) {
        $("comments").innerHTML = obj.html;
    },
    sendTipEmail: function() {

        var friendsEmail = $F('friendsemail');
        var sendersName = $F('yourname');
        var address = location.href;

        ajaxUpdater.sendTipEmail(friendsEmail, sendersName, address);
    },
    onSendTipEmailResponse: function(obj) {
        if (obj.success == "True") {
            Lightbox.deactivate();
        }
        else {
            var infoDiv = $("info");
            infoDiv.innerHTML = globalLangObj.WC_TipAFriendBoxErrorMessage;
        }
    },
    sendAbuse: function() {
        var commentID = $F('commentID');
        var reason = $F('abuseReason');

        ajaxUpdater.sendAbuse(commentID, reason);
    },
    onSendAbuseResponse: function(obj) {
        if (obj.success == "True") {
            Lightbox.deactivate();
        }
        else {
            var infoDiv = $("info");
            infoDiv.innerHTML = globalLangObj.WC_GeneralError;
        }
    },
    sendComment: function() {

        var commentTitle = $F('commenttitle');
        var commentText = $F('commenttext');

        ajaxUpdater.sendComment(commentTitle, commentText);
    },
    onSendCommentResponse: function(obj) {
        if (obj.success == "True") {
            $("comments").innerHTML = obj.html;
            Lightbox.deactivate();
        }
        else {
            var infoDiv = $("info");
            infoDiv.innerHTML = globalLangObj.WC_CommentBoxErrorMessage;
        }
    },
    showComments: function() {
        var arr = $$('div.synopsis h2 a');
        for (var i = 0; i < arr.length; i++) {
            if (arr[i].href.toLowerCase().indexOf("showcomments") > -1)
                Element.removeClassName(arr[i], "inactive");
            else
                Element.addClassName(arr[i], "inactive");
        }
        $("synopsis").hide();
        $("comments").show();
    },
    showSynopsis: function() {
        var arr = $$('div.synopsis h2 a');
        for (var i = 0; i < arr.length; i++) {
            if (arr[i].href.toLowerCase().indexOf("showsynopsis") > -1)
                Element.removeClassName(arr[i], "inactive");
            else
                Element.addClassName(arr[i], "inactive");
        }
        $("synopsis").show();
        $("comments").hide();
    },
    showAbuseBox: function(commentID) {
        var errorClose = globalLangObj.WC_Close || "CLOSE";
        var header = globalLangObj.WC_AbuseBoxHeader || "Report Abuse";
        header = header.toUpperCase();
        var info = globalLangObj.WC_AbuseBoxInfo || "";
        var button = globalLangObj.WC_AbuseBoxButton || "Report";

        var loginStr = '<div id="abuseBox">' +
                                '<h1>' + header + '</h1>' +
								'<div id="info">' + info + '</div>' +
                                '<div id="fields">' +
                                '<input type="hidden" id="commentID" name="commentID" value="' + commentID + '" />' +
                                '<textarea id="abuseReason" name="abuseReason"></textarea>' +
	                            '</div>' +
								'<div id="buttons">' +
                                '<input id="submit" class="submit" onClick="Action.sendAbuse();" type="button" value="' + button + '" />' +
	                            '</div>' +
                       '</div>' +
					   '<a href="#" class="lbAction closebtn" rel="deactivate">' + errorClose + '</a>';

        try {
            MediaObject.stopMedia();
        } catch (e) { }
        try {
            Lightbox.showMessage(loginStr);
        } catch (e) {
            //window.setTimeout('Action.showError("'+d+'", "'+l+'")', 1000);
        }
    },
    showCommentBox: function() {
        var errorClose = globalLangObj.WC_Close || "CLOSE";
        var text = globalLangObj.WC_CommentBoxText || "Text";
        var title = globalLangObj.WC_CommentBoxTitle || "Title";
        var info = globalLangObj.WC_CommentBoxInfoMessage || "";
        var header = globalLangObj.WC_CommentBoxHeader || "Write a comment";
        header = header.toUpperCase();
        var button = globalLangObj.WC_CommentBoxButton || "Send comment";


        var loginStr = '<div id="commentBox">' +
                                '<h1>' + header + '</h1>' +
								'<div id="info">' + info + '</div>' +
                                '<div id="fields">' +
                                '<label id="lblcommenttitle" for="commenttitle" accesskey="N" >' + title + '</label>' +
                                '<input type="text" id="commenttitle" name="title" />' +
                                '<label id="lblcommenttext" for="commenttext" accesskey="P" >' + text + '</label>' +
                                '<textarea id="commenttext" name="comment"></textarea>' +
	                            '</div>' +
								'<div id="buttons">' +
                                '<input id="submit" class="submit" onClick="Action.sendComment();" type="button" value="' + button + '" />' +
	                            '</div>' +
                       '</div>' +
					   '<a href="#" class="lbAction closebtn" rel="deactivate">' + errorClose + '</a>';

        try {
            MediaObject.stopMedia();
        } catch (e) { }
        try {
            Lightbox.showMessage(loginStr);
        } catch (e) {
            //window.setTimeout('Action.showError("'+d+'", "'+l+'")', 1000);
        }
    },
    showTipAFriend: function() {
        var errorClose = globalLangObj.WC_Close || "CLOSE";
        var emailLabel = globalLangObj.WC_TipAFriendBoxEmailLabel || "Your friends email address";
        var nameLabel = globalLangObj.WC_TipAFriendBoxNameLabel || "Your name";
        var header = globalLangObj.WC_TipAFriendBoxHeader || "Tip a friend";
        header = header.toUpperCase();
        var button = globalLangObj.WC_TipAFriendBoxSendButton || "Send Tip";

        var loginStr = '<div id="tipAFriend">' +
                                '<h1>' + header + '</h1>' +
                                '<div id="info"> </div>' +
                                '<div id="fields">' +
                                '<label id="lblemail" for="friendsemail" accesskey="N" >' + emailLabel + '</label>' +
                                '<input type="text" id="friendsemail" name="friendsemail" /><br>' +
                                '<label id="lblname"for="yourname" accesskey="P" >' + nameLabel + '</label>' +
                                '<input type="text" id="yourname" name="yourname" />' +
	                            '</div>' +
								'<div id="buttons">' +
                                '<input id="submit" class="submit" onClick="Action.sendTipEmail();" type="button" value="' + button + '" />' +
	                            '</div>' +
                       '</div>' +
					   '<a href="#" class="lbAction closebtn" rel="deactivate">' + errorClose + '</a>';

        try {
            MediaObject.stopMedia();
        } catch (e) { }
        try {
            Lightbox.showMessage(loginStr);
        } catch (e) {
            //window.setTimeout('Action.showError("'+d+'", "'+l+'")', 1000);
        }
    },
    showLogin: function(prelogin) {
        var secureLoginRoot;
        var miscObj = getLoadObject('misc');
        if (miscObj)
            secureLoginRoot = miscObj.secureloginroot || "";
        else
            secureLoginRoot = "";

        if (secureLoginRoot != "" && location.href.indexOf("login_secure.aspx") < 0) // when login should be handled on separate page.
        {
            if (prelogin == 'play') {
                prelogin = "&prelogin=play";
                // Creates a cookie containing MediaObject.properties, so when user returns to main.aspx
                // from login page, playback can be resumed by reading cookie
                var cookieValue = Object.toJSON(MediaObject.properties);
                this.createCookie("mediaobject.properties", Object.toJSON(MediaObject.properties));
            }
            else
                prelogin = "";

            // remove possible encrSubscriberObjId from location.search
            var qsArr = location.search.substr(1).split("&");
            var sKeyValues = new Array();
            for (var i = 0; i < qsArr.length; i++) {
                // remove paramters s & logout from querystring
                if (qsArr[i].indexOf("s=") == 0 || qsArr[i].indexOf("logout=") == 0) {
                    if (qsArr.length > 1) {
                        // om sista parametern
                        if (i == qsArr.length - 1)
                            sKeyValues.push("&" + qsArr[i]);
                        else
                            sKeyValues.push(qsArr[i] + "&");
                    }
                    else {
                        sKeyValues.push("?" + qsArr[i]);
                    }
                }
            }
            var currentUrl = location.href;
            if (sKeyValues.length > 0) {
                for (var i = 0; i < sKeyValues.length; i++) {
                    currentUrl = currentUrl.split(sKeyValues[i]).join("");
                }
            }
            // Redirects to separate login page. 
            // Returnpath = which page to return to from login page. 
            // Prelogin = Reason for login and the action resume on return to the returnpath page
            // overideParamsForLoginPage = operatorOverride, referrer, languageOverride, regionOverride - if these are stated in web.config or HostandRegionOverrides.xml
            location.href = secureLoginRoot + "login_secure.aspx?returnPath=" + Base64.encode(currentUrl) + prelogin + this.overideParamsForLoginPage(miscObj);
            return;
        }
        else if (location.href.indexOf("subscriber_secure.aspx") > -1)
            location.href = "login_secure.aspx" + location.search;
        //		Lightbox.deactivate();

        var paramstr = '<input type="hidden" id="cmd" name="cmd" value="login"/>';
        var loginHeader = globalLangObj.WC_Login || "LOG IN";
        loginHeader = loginHeader.toUpperCase();
        var loginMsg = globalLangObj.WC_LoginText || "Enter your Username and Password to log in.";
        var loginUsername = globalLangObj.WC_Username || "Name:";
        var loginPassword = globalLangObj.WC_Password || "Password:";
        var loginSubmit = globalLangObj.WC_Login || "Log In";
        var loginCancel = globalLangObj.WC_Cancel || "Cancel";
        var loginClose = globalLangObj.WC_Close || "Cancel";
        var signupText = globalLangObj.WC_Register || "Click here to sign up!";

        var forgotPWText = globalLangObj.WC_ForgotPassword || "Forgotten Password?";
        var recoverPWLabel = globalLangObj.WC_RecoverPassword_Label || "Email or Username";

        var msgClass = "";

        var loginFieldsStyle = '';
        var recoverPasswordStyle = 'style="display:none"';

        if (prelogin == 'play') {
            paramstr += '<input type="hidden" id="prelogin" name="prelogin" value="play"/>';
            for (prop in MediaObject.properties) {
                if (MediaObject.properties[prop]) {
                    paramstr += '<input type="hidden" id="' + prop + '" name="' + prop + '" value="' + MediaObject.properties[prop] + '"/>'
                }
            }
        } else if (prelogin == 'failed') {
            loginMsg = globalLangObj.WC_LoginText_Failed || "Wrong username or password";
            msgClass = ' class="error" ';
            var playObj = getLoadObject('playonload');
            if (playObj) {
                paramstr += '<input type="hidden" id="prelogin" name="prelogin" value="play"/>';
                for (prop in playObj) {
                    if (playObj[prop]) {
                        paramstr += '<input type="hidden" id="' + prop + '" name="' + prop + '" value="' + playObj[prop] + '"/>'
                    }
                }
            }
        }
        else if (prelogin == 'recoversuccess') {
            loginMsg = globalLangObj.WC_RecoverPassword_Success || "Your password has been sent!";
        }
        else if (prelogin == 'recoverfailed') {
            loginMsg = globalLangObj.WC_RecoverPassword_Failed || "User doesn't exist.";
            msgClass = ' class="error" ';
        }
        else if (prelogin == 'recoverbademail') {
            loginMsg = globalLangObj.WC_RecoverPassword_BadEmail || "E-mail address missing or incomplete. Please contact support.";
            msgClass = ' class="error" ';
        }

        var registerUrl = 'subscriber.aspx' + window.location.search;
        if (location.href.indexOf("login_secure.aspx") > -1)
            registerUrl = 'subscriber_secure.aspx' + window.location.search;

        var loginStr = '<div id="loginForm">' +
                                '<h1>' + loginHeader + '</h1>' +
								'<div id="loginMsg"' + msgClass + '>' + loginMsg + '</div>' +
								'<div id="loginSignup"><a href="' + registerUrl + '">' + signupText + '</a><a href="#" id="loginForgotPW" onClick="Action.ShowRecoverPassword();">' + forgotPWText + '</a></div>' +
                                '<div id="loginFields">' +
                                '<label id="lblusername" for="username" accesskey="N" >' + loginUsername + '</label>' +
                                '<input type="text" id="username" name="username" /><br>' +
                                '<label id="lblpassword"for="password" accesskey="P" >' + loginPassword + '</label>' +
                                '<input type="password" id="password" name="password" />' +
								paramstr +
	                            '</div>' +
                                '<div id="recoverPassword" style="display:none">' +
                                '<label id="lblrecoverPasswordMail" for="recoverPasswordMail" accesskey="O" >' + recoverPWLabel + '</label>' +
                                '<input type="text" id="recoverPasswordMail" name="recoverPasswordMail" /><br>' +
	                            '</div>' +
								'<div id="loginButtons">' +
                                '<input id="loginSubmit" class="submit" type="submit" value="' + loginSubmit + '" />' + //<input class="reset" type="reset" value="' + loginCancel + '" />' +
	                            '</div>' +
        //'</form>' +
                       '</div>' +
					   '<a href="#" class="lbAction closebtn" rel="deactivate">' + loginClose + '</a>';
        try {
            MediaObject.stopMedia();
        } catch (e) { }
        Lightbox.showMessage(loginStr);

        Event.observe('form1', 'reset', function(e) {
            Event.stop(e);
            Lightbox.deactivate();
        });

        $("username").focus();
        if (Prototype.Browser.IE) {// split up login fix
            rezbox.setFixedDimensions($('lightbox'), true);
        }

        if (prelogin == 'recoverfailed') Action.ShowRecoverPassword();
    },
    overideParamsForLoginPage: function(miscObj) {
        var queryString = location.search.toLowerCase();
        var arr = [];
        var ret = "";

        if (miscObj.serviceobjectid != "")
            arr.push("serviceobjid=" + miscObj.serviceobjectid);

        if (miscObj.operatoroverride != "")
            arr.push("operatoroverride=" + miscObj.operatoroverride);

        if (miscObj.regionoverride != "")
            arr.push("regionoverride=" + miscObj.regionoverride);

        if (miscObj.referrer != "")
            arr.push("referrer=" + miscObj.referrer);

        if (miscObj.languageoverride != "")
            arr.push("languageoverride=" + miscObj.languageoverride);

        if (arr.length > 0) {
            for (var i = 0; i < arr.length; i++)
                ret += "&" + arr[i];

        }

        return ret;
    },
    overideParamsForSubscriberPage: function(queryString) {
        //        queryString = queryString.substr(1);
        //        var cop = {"serviceobjectid","operatoroverride","regionoverride","referrer","languageoverride"}
        //        var params = queryString.split("&");
        //        var hash = new Hash(); 
        //        
        //        // för varje key-value string i querystringen (key=value)
        //        for(var i=1; i<params.length; i++)
        //        {
        //            var keyValue = params[i].split("=");
        //            if(keyValue.length > 1)
        //            {
        //                for(var j=0; j<cop.length; j++)
        //                {
        //                    if(keyValue[0] == cop[j])
        //                        hash.set(keyValue[0], params[i].substring(0,params[i].indexOf("=")); 
        //                }
        //            }
        //            hash.set('name', 'Bob'); 
        //        }
        //        var ret = "";
        //    
        //        if(queryString.indexOf(miscObj.serviceobjectid != "")
        //            arr.push("serviceobjectid=" + miscObj.serviceobjectid);
        //        
        //        if(miscObj.operatoroverride != "")
        //            arr.push("operatoroverride=" + miscObj.operatoroverride);
        //    
        //        if(miscObj.regionoverride != "")
        //            arr.push("regionoverride=" + miscObj.regionoverride);
        //    
        //        if(miscObj.referrer != "")
        //            arr.push("referrer=" + miscObj.referrer);
        //    
        //        if(miscObj.languageoverride != "")
        //            arr.push("languageoverride=" + miscObj.languageoverride);
        //    
        //        if(arr.length > 0)
        //        {
        //            for(var i=0; i<arr.length; i++)
        //                ret += "&" + arr[i];
        //            
        //        }
        //    
        //        return ret; 
    },
    ShowRecoverPassword: function() {
        var recoverPWText = globalLangObj.WC_RecoverPassword || "Send password";
        $("loginFields").style.display = 'none';
        $("recoverPassword").style.display = 'inline';
        $("loginSubmit").value = recoverPWText;
        $("cmd").value = "recoverPassword";
    },
    logOut: function() {
        //ajaxUpdater.logout();
        var formstr = '<input type="hidden" id="logout" name="logout" value="true"/>';
        var elt = document.createElement("div");
        elt.innerHTML = formstr;
        //document.body.appendChild(elt);
        var form1 = $('form1');
        form1.appendChild(elt);
        document.forms[0].submit();
    },
    onAjaxLoginResponse: function(response) {
        //Action.showError(response, "Action.onLogin");
        var value = response.value;
        if (value == "failed") {
            var errMsg = response.msg || "Wrong username or password";
            $("loginMsg").update(errMsg);
            $("loginMsg").addClassName("error");
            $("username").focus();
        } else if (value == "success") {
            Lightbox.deactivate();
            var statusStr = response.msg || 'Welcome <strong>[username]</strong>! <a href="javascript:Action.logOut();" title="Log out">Log out</a>';
            var usrStr = response.username || 'Friend';
            statusStr = statusStr.split("[username]").join(usrStr);
            new Effect.Fade("loginstatus", { duration: 0.5, afterFinish: function() {
                $('loginstatus').update(statusStr);
                new Effect.Appear("loginstatus", { duration: 0.5 });
            }
            });
        } else if (value == "loggedout") {
            var statusStr = response.msg || '<a href="javascript:;" title="Sign up">Sign up</a> or <a href="javascript:Action.showLogin();" title="Login">Log in</a>';
            new Effect.Fade("loginstatus", { duration: 0.5, afterFinish: function() {
                $('loginstatus').update(statusStr);
                new Effect.Appear("loginstatus", { duration: 0.5 });
            }
            });
        }
    },
    doSearch: function() {
        if (!this.searchTarget) {
            var miscObj = getLoadObject('misc');
            if (miscObj) {
                this.searchTarget = miscObj.mainpage || "main.aspx";
            } else {
                this.searchTarget = "main.aspx";
            }
        }
        var value = $("search").value;
        var value_s = $("search").serialize();
        var searchstr = (this.searchTarget.include("?") ? "&" : "?") + "cmd=search&" + value_s;
        if (value != "") {
            location.href = this.searchTarget + searchstr;
        }
    },
    rateContent: function(rating, contentid, anonymous) {
        var contentid, rating, anonymous;

        if (arguments.length == 3 && Object.isNumber(arguments[0]) && Object.isNumber(arguments[1])) {
            rating = arguments[0];
            contentid = arguments[1];
            anonymous = arguments[2];

            var obj = {}
            obj.contentid = contentid;
            obj.rating = rating;
            obj.anonymous = anonymous;

            if (anonymous) {
                var hasSavedRating = false;
                var currentratings = this.readCookie("rating") || "";
                var ra = currentratings.split("|");
                for (var i = 0; i < ra.length; i++) {
                    var r = ra[i];
                    if (r == contentid) {
                        hasSavedRating = true;
                        break;
                    }
                }
                var ratingObj = $("rating-" + obj.contentid);
                var userObj = ratingObj.down(".user-rating");
                var infoObj = ratingObj.down(".rating-info");

                if (userObj == null) {
                    infoObj.insert({ after: "<div class=\"user-rating\"></div>" })
                    userObj = ratingObj.down(".user-rating");

                }

                if (hasSavedRating) {
                    userObj.update(globalLangObj.WC_AlreadyVoted || "You voted already.");
                    this.removeRating(contentid);
                    return;
                } else {
                    this.createCookie("rating", currentratings + contentid + "|", 365);
                    this.removeRating(contentid);
                }
            }

            ajaxUpdater.saveRating(obj); //svar till onSaveRatingResponse
            //this.onSaveRatingResponse({'percent':'70','contentid':'363549112','userinfo':'new user info','ratinginfo':'new rating info'});
        }
    },
    onSaveRatingResponse: function(obj) {
        var ratingObj = $("rating-" + obj.contentid);
        var infoObj = ratingObj.down(".rating-info");
        var userObj = ratingObj.down(".user-rating");

        if (userObj == null) {
            infoObj.insert({ after: "<div class=\"user-rating\"></div>" })
            //ratingObj.innerHTML = ratingObj.innerHTML + "<div class=\"user-rating\"></div>";
            userObj = ratingObj.down(".user-rating");
        }


        ratingObj.down(".current-rating").setStyle({ width: obj.percent + "%" });
        userObj.update(obj.userinfo);
        infoObj.update(obj.ratinginfo);

    },
    removeRating: function(contentid) {
        var ratingObj = $("rating-" + contentid);
        ratingObj.down("ul").update(ratingObj.down("li"));
    },
    createCookie: function(name, value, days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            var expires = "; expires=" + date.toGMTString();
        }
        else var expires = "";
        document.cookie = name + "=" + value + expires + "; path=/";
    },
    readCookie: function(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;
    },
    eraseCookie: function(name) {
        createCookie(name, "", -1);
    }
};





var Slideshow = Class.create();

var SLIDESHOW_INTERVAL = 5000;
var SLIDESHOW_FADEOBJECT = {fps:15, duration:0.7, transition: Effect.Transitions.linear};
var SLIDESHOW_APPEAROBJECT = {fps:15, duration:0.7, transition: Effect.Transitions.linear};

Slideshow.prototype = {
  initialize: function(slideShowWrapperElement, interval) {
  	this.interval = interval;
	this.slides = $(slideShowWrapperElement).childElements().findAll(function(elt) {
		return elt.hasClassName('slide');
	});
	this.lastIndex = this.slides.length - 1;
	this.currIndex = 0;
	//All but the first slide is hidden backend
	if(this.lastIndex > 0){
		setTimeout(this.swap.bind(this),this.interval);
	}
  },
  swap: function() {
  	var s = this;
	var oldIndex = s.currIndex;
	if (s.currIndex == s.lastIndex) { s.currIndex = 0; } else { s.currIndex++; }
	var oldSlide = s.slides[oldIndex];
	var newSlide = s.slides[s.currIndex];
  	oldSlide.visualEffect('fade',SLIDESHOW_FADEOBJECT);
	newSlide.visualEffect('appear',SLIDESHOW_APPEAROBJECT);
	setTimeout(s.swap.bind(this),s.interval);
  }
};

Event.observe(window, 'load', function() {
	$$(".slideshow").each(function(element){
		new Slideshow(element, SLIDESHOW_INTERVAL);
	});
});


var spotInjection =  // TODO: Kolla om spotInjection.preContentSpotUrl kan bytas ut till  MediaObject.properties.preContentSpotUrl överallt (och såklart samma för postspoturl)
{
resetSpotUrls: function() {
    this.preContentSpotUrl = "";
    this.postContentSpotUrl = "";
},
setSpotUrls: function() {

    if (MediaObject.properties.amsintegrationurl != "") { // Get prespot from ad management system
        this.getSpotUrlFromAdManagementSystem("pre");

    }
    else {
        if (MediaObject.properties.hascpspots) { // set spots from content profile
            this.preContentSpotUrl = MediaObject.properties.cpprespoturl;
            this.postContentSpotUrl = MediaObject.properties.cppostspoturl;
        }
        else { // set spots from menu builder
            var obj = getLoadObject('spotinjection');
            if (obj != null) {
                if (obj.prespoturl && this.isMediaUrl(obj.prespoturl))
                    this.preContentSpotUrl = obj.prespoturl;

                if (obj.postspoturl && this.isMediaUrl(obj.postspoturl))
                    this.postContentSpotUrl = obj.postspoturl;
            }
        }

        MediaObject.playInToolbox();
    }
},
getSpotUrlFromAdManagementSystem: function(toDisplayWhen) // toDisplayWhen: "pre" if prespot. "post" if postspot 
{
    if (toDisplayWhen == null || toDisplayWhen.toLowerCase() != "pre")
        toDisplayWhen == "post";

    this.fallback = toDisplayWhen == "post" ? MediaObject.hideMedia : MediaObject.playInToolbox;

    var miscObj = getLoadObject('misc');
    var params = {};
    params.todisplaywhen = toDisplayWhen;
    params.level = miscObj.level;
    params.serviceviewobjectid = miscObj.serviceviewobjectid;
    params.serviceobjectid = miscObj.serviceobjectid;
    params.contentid = MediaObject.properties.contentid;
    params.uri = MediaObject.properties.amsintegrationurl;
    // Reset MediaObject.properties.contentid
    MediaObject.properties.contentid = null;

    var req = new Ajax.Request("proxy.aspx",
            {
                method: "get",
                parameters: params,
                onSuccess: function(transport) {
                    var response = transport.responseText || "no response text";
                    var responseObj = response.evalJSON();
                    if (responseObj != null) {
                        if (responseObj.prespoturl != null) {
                            if (responseObj.prespoturl != "")
                                spotInjection.preContentSpotUrl = responseObj.prespoturl;

                            MediaObject.playInToolbox();
                        }
                        else if (responseObj.postspoturl != null) {
                            if (responseObj.postspoturl != "") {
                                spotInjection.postContentSpotUrl = responseObj.postspoturl;
                                MediaObject.properties.mediaIsPostSpot = true;
                                MediaObject.playInToolbox();
                            }
                            else {
                                MediaObject.hideMedia(true);
                            }
                        }
                        else
                            spotInjection.fallback();
                    }
                },
                onFailure: function(failure) {
                    spotInjection.fallback.call(MediaObject,true);
                }
            });
},
isMediaUrl: function(str) {
    if (str.indexOf(".flv") > -1 || str.indexOf(".wmv") > -1)
        return true;
    else
        return false;
},
verify: function() {
    if (spotInjection.preContentSpotUrl != null && spotInjection.postContentSpotUrl != null) {

    }
    else
        setTimeout(function() { spotInjection.verify() }, 100);
}
}


function navigateBySelectbox(obj)
{
    if(obj.selectedIndex > -1)
    {
        window.location.href = obj.options[obj.selectedIndex].value;
    } 
}

function sortMainContentList(name, url)
{
	toggleSortOptions();
	$("sortOptionsTitle").innerHTML = name; 
	window.location.href = url;
}

function toggleSortOptions()
{
	if($("sortOptions").style.display == "block")
	{
		$("sortOptions").style.display = "none"; 
		$("sortOptionsArrow").removeClassName('active');
	}
	else
	{
		var pos = $("sortOptionsTitle").cumulativeOffset();
		$("sortOptions").style.top = (pos.top + $("sortOptionsTitle").offsetHeight + 3)+"px";
		$("sortOptions").style.left = pos.left + "px";
		$("sortOptionsArrow").addClassName('active');
		$("sortOptions").style.display = "block";
	}
	
}

Event.observe(window, 'load', function() {	
	if($("sortOptions"))
	{
		var obj = $("sortOptions").remove();
		var body = document.getElementsByTagName("body")[0];
		Element.extend(body)
		body.insert(obj);
	}
});


Event.observe(window, 'load', function() {
	var myObj = getLoadObject("liveevent");
	if(myObj != null)
	{
	    setTimeout("Action.pollLiveEvent()", 30000);
	}
});


/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/

var Base64 = {

    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = Base64._utf8_decode(output);

        return output;

    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}


var parentalLock = {
    ready: false,
    setReady: function(str) {
        parentalLock.ready = true;
    },
    flashExceptionMsg: function(str)
    { },
    flashVersionOk: function(str) {
        checkFlash();
        if (!client.is_flash10up)
            return false;
        else
            return true;
    },
    settings: null,
    locked: false,
    init: function() {
        if (toolbox.loaded) {
            if (parentalLock.flashVersionOk()) {
                if (parentalLock.ready) {
                    parentalLock.getSettingsFromSharedObj();
                    if (parentalLock.settings != null) {
                        if (editSettings) {
                            parentalLock.showDialogue_editSettings();
                        }
                        else {
                            if (parentalLock.settings.hasLock) {
                                parentalLock.showDialogue_login();
                            }
                            else {
                                parentalLock.returnToService();
                            }
                        }
                    }
                    else { // no settings in shared object
                        parentalLock.showDialogue_offerLock();
                    }
                }
                else { // flash obj not loaded
                    setTimeout(parentalLock.init, 200);
                }
            }
            else { // flash version not ok
                parentalLock.showDialogue_getFlash();
            }
        }
        else { // toolbox not loaded
            setTimeout(parentalLock.init, 200);
        }
    },
    getFlashMovie: function(movieName) {
        var isIE = navigator.appName.indexOf("Microsoft") != -1; return (isIE) ? window[movieName] : document[movieName];
    },
    getSettingsFromSharedObj: function() {
        var sharedObjStr = parentalLock.getFlashMovie("sharedobject").getSharedObj("parentalLockPsw");
        if (sharedObjStr != null && sharedObjStr != "") {
            parentalLock.settings = sharedObjStr.evalJSON();
        }
    },
    saveSettingsToSharedObj: function(sharedObjStr) {
        parentalLock.getFlashMovie("sharedobject").setSharedObj("parentalLockPsw", sharedObjStr);
    },
    saveSettings: function(obj) {
        if (obj != null) {
            parentalLock.settings = obj;
            parentalLock.saveSettingsToSharedObj(Object.toJSON(obj));
        }
        parentalLock.returnToService();
    },
    LockOrNot: function() {     
        if ($("radio_lock").checked) {
            parentalLock.showDialogue_setPsw();
        }
        else {
            parentalLock.saveSettings({ hasLock: false, psw: 0 });
        }
    },
    showDialogue_getFlash: function() 
    {
        var str = '<div id="parentalLockDialogue">' +
                                '<h1>' + globalLangObj.WC_ParentalLock_InstallFlashHeader + '</h1>' +

                                '<p>' + globalLangObj.WC_ParentalLock_InstallFlashInfo + '</p>' +

                                '<a class="link" href="http://get.adobe.com/flashplayer/">' + globalLangObj.WC_ParentalLock_InstallFlashLink + '</a>' +
                    '</div>';

        Lightbox.showMessage(str);
    },
    showDialogue_offerLock: function() {
        var str = '<div id="parentalLockDialogue">' +
                                '<h1>' + globalLangObj.WC_ParentaLock_DialogueHeader + '</h1>' +

                                '<p>' + globalLangObj.WC_ParentalLock_OfferLockInfo + '</p>' +
                                '<table>' +
                                '<tr>' +
                                '<td><input class="radio" type="radio" name="radio_lockOptions" checked="checked" value="" id="radio_lock"></td>' +
                                '<td><label class="radio" id="" for="radio_lock" accesskey="" >' + globalLangObj.WC_ParentalLock_LockService + '</label></td>' +
                                '</tr>' +
                                '<tr>' +
                                '<td><input class="radio" type="radio" name="radio_lockOptions" value="" id="radio_nolock"></td>' +
                                '<td><label class="radio" id="" for="radio_nolock" accesskey="" >' + globalLangObj.WC_ParentalLock_KeepServiceOpen + '</label></td>' +
                                '</tr>' +
                                '</table>'+
                                '<a class="button" href="javascript:parentalLock.LockOrNot()">' + globalLangObj.WC_Apply + '</a>' +
                       '</div>';

        Lightbox.showMessage(str);
    },
    showDialogue_setPsw: function(errorMsg) {

        if (errorMsg == null) errorMsg = "";
        if (errorMsg != "") errorMsg = "<p class=\"error\">" + errorMsg + "</p>";

        var str = '<div id="parentalLockDialogue">' +
                                '<h1>' + globalLangObj.WC_ParentaLock_DialogueHeader + '</h1>' +

                                errorMsg +

                                '<label id="" for="txt_psw1" accesskey="" >' + globalLangObj.WC_ParentalLock_WritePsw + '</label>' +
                                '<input type="password" name="txt_psw1" value="" id="txt_psw1">' +

                                '<label id="" for="txt_psw2" accesskey="" >' + globalLangObj.WC_ParentalLock_RepeatPsw + '</label>' +
                                '<input type="password" name="txt_psw2" value="" id="txt_psw2">' +

                                '<p>' + globalLangObj.WC_ParentalLock_SetPswInfo + '</p>' +

                                '<a class="button" href="javascript:parentalLock.setPsw()">' + globalLangObj.WC_Apply + '</a>' +
                       '</div>' +
        '<a href="javascript:parentalLock.returnToService()" class="closebtn">' + (globalLangObj.WC_Close || "CLOSE") + '</a>';

        Lightbox.showMessage(str);
        $("txt_psw1").focus();
    },
    setPsw: function() {
        if ($("txt_psw1").value == "" || $("txt_psw2").value == "") {
            parentalLock.showDialogue_setPsw(globalLangObj.WC_ParentalLock_Error_EmptyFields);
        }
        else if ($("txt_psw1").value != $("txt_psw2").value) {
            parentalLock.showDialogue_setPsw(globalLangObj.WC_ParentalLock_Error_UnidenticalPsw);
        }
        else {
            parentalLock.saveSettings({ hasLock: true, psw: $("txt_psw1").value });
        }
    },
    showDialogue_editSettings: function() {

        var str;

        if (parentalLock.settings.hasLock) {
            str = '<p>' + globalLangObj.WC_ParentalLock_ServiceIsLocked + '<p>' +
                   '<a class="link" href="javascript:parentalLock.showDialogue_editPsw()">' + globalLangObj.WC_ParentalLock_ChangePsw + '</a>' +
                   '<a class="link" href="javascript:parentalLock.saveSettings({ hasLock:false, psw:0})">' + globalLangObj.WC_ParentalLock_RemoveLock + '</a>' +
                   '<a class="link" href="javascript:parentalLock.returnToService()">' + globalLangObj.WC_ParentalLock_KeepSettings + '</a>';
        }
        else {
            str = '<p>' + globalLangObj.WC_ParentalLock_ServiceIsUnlocked + '<p>' +
                   '<a class="link" href="javascript:parentalLock.showDialogue_setPsw()">' + globalLangObj.WC_ParentalLock_ActivateLock + '</a>' +
                   '<a class="link" href="javascript:parentalLock.returnToService()">' + globalLangObj.WC_ParentalLock_KeepSettings + '</a>';
        }
        var str = '<div id="parentalLockDialogue">' +

                                '<h1>' + globalLangObj.WC_ParentaLock_DialogueHeader + '</h1>' +
                                str +
                   '</div>' +
                   '<a href="javascript:parentalLock.returnToService()" class="closebtn">' + (globalLangObj.WC_Close || "CLOSE") + '</a>';

        Lightbox.showMessage(str);
    },
    showDialogue_editPsw: function(errorMsg) {

        if (errorMsg == null) errorMsg = "";
        if (errorMsg != "") errorMsg = "<p class=\"error\">" + errorMsg + "</p>";

        var str = '<div id="parentalLockDialogue">' +
                                '<h1>' + globalLangObj.WC_ParentaLock_DialogueHeader + '</h1>' +

                                errorMsg +

                                '<label id="" for="txt_psw" accesskey="" >' + globalLangObj.WC_ParentalLock_WriteCurrentPsw + '</label>' +
                                '<input type="password" name="txt_psw" value="" id="txt_psw">' +

                                '<label id="" for="txt_psw1" accesskey="" >' + globalLangObj.WC_ParentalLock_WriteNewPsw + '</label>' +
                                '<input type="password" name="txt_psw1" value="" id="txt_psw1">' +

                                '<label id="" for="txt_psw2" accesskey="" >' + globalLangObj.WC_ParentalLock_RepeatNewPsw + '</label>' +
                                '<input type="password" name="txt_psw2" value="" id="txt_psw2">' +

                                '<p>' + globalLangObj.WC_ParentalLock_SetPswInfo + '</p>' +

                                '<a class="button" href="javascript:parentalLock.editPsw()">' + globalLangObj.WC_Apply + '</a>' +
                       '</div>';

        Lightbox.showMessage(str);
        $("txt_psw").focus();
    },
    editPsw: function() {
        if ($("txt_psw").value != parentalLock.settings.psw) {
            parentalLock.showDialogue_editPsw(globalLangObj.WC_ParentalLock_Error_WrongPsw);
        }
        else if ($("txt_psw1").value == "" || $("txt_psw2").value == "") {
            parentalLock.showDialogue_editPsw(globalLangObj.WC_ParentalLock_Error_EmptyFields);
        }
        else if ($("txt_psw1").value != $("txt_psw2").value) {
            parentalLock.showDialogue_editPsw(globalLangObj.WC_ParentalLock_Error_UnidenticalPsw);
        }
        else {
            parentalLock.saveSettings({ hasLock: true, psw: $("txt_psw1").value });
        }
    },
    showDialogue_login: function(errorMsg) {

        if (errorMsg == null) errorMsg = "";
        if (errorMsg != "") errorMsg = "<p class=\"error\">" + errorMsg + "</p>";

        var str = '<div id="parentalLockDialogue">' +
                                '<h1>' + globalLangObj.WC_Login + '</h1>' +

                                errorMsg +

                                '<p>' + globalLangObj.WC_ParentalLock_LockedServiceinfo + '</p>' +

                                '<label id="" for="txt_psw" accesskey="" >' + globalLangObj.WC_ParentalLock_WritePsw + '</label>' +
                                '<input type="password" name="txt_psw" value="" id="txt_psw">' +

                                '<p>' + globalLangObj.WC_ParentalLock_HowToUnlock + '</p>' +

                                '<a class="button" href="javascript:parentalLock.login()">' + globalLangObj.WC_Apply + '</a>' +
                       '</div>';

        Lightbox.showMessage(str);
        $("txt_psw").focus();
    },
    login: function() {
        if ($("txt_psw").value == parentalLock.settings.psw) {
            parentalLock.returnToService();
        }
        else {
            var errorMsg = globalLangObj.WC_ParentalLock_Error_WrongPsw;
            parentalLock.showDialogue_login(errorMsg);
        }
    },
    returnToService: function() {
        if (parentalLock.settings.hasLock)
            $("txt_hasLock").value = "true";
        else
            $("txt_hasLock").value = "false";

        $("frm_parentallock").submit();
        //submit form + set sessionsvariable +return to url-referrer
        // sessionsvariabeln måste veta om tjänsten har lås eller ej.
    },
    callButtonAction: function() {
        try {
            eval($('parentalLockDialogue').down('a.button').href.substr(11));
        } catch (exp) { }
    }
}



function trace(str) {
    document.getElementById("debug").innerHTML = document.getElementById("debug").innerHTML + "<br>" + str;
}