﻿/*jslint laxbreak: true */
/*global $ Class DR Events Options Request Swiff Uplayer document initPlaylist1 initPlaylist2 initPlaylist3 initSlideVars initSpotPlayer window alert location*/

/*jslint laxbreak: true, eqeqeq: true, browser: true, undef: true */
/*extern $, $$, $H, $A, $splat, $defined, $type, Hash, Request, Class, Event, Events, Elements, Options, JSON, Element, __doPostBack */
/*global DR, AjaxManager */


/*** AJAX MANAGER START ***/

if (!window.DR) {
    DR = {};
}

/*
Class: DR.AjaxManager
Client side implementation of the DR.AjaxManager framework for asynchrous postback to asp.net. Use the <DR.AjaxManager.Postback> function to do postback to the server, instead of the asp.net __doPostBack. This class hooks __doPostBack and replaces it with <DR.AjaxManager.postback>.

Event: updatePending
Fired from an update panel just before it is updated. Use this event to create transistions between the old and new data in the update panel, or to cancel updateting. The updatepanel can be extracted from the event through e.target

Paramters:
e - custom event, cancel this (e.stop() or e.preventDefault()) to prevent that the update panel is updated by the DR.AjaxManager.
elements - a MooTools Elements collection containing the elements of the incoming data for the panel. Be aware that root level textnodes are not in this collection.
html - the HTML in clear text.

Event: updateComplete
Fired from an update panel when it has been updated. Use to reattach events.

Parameters:
panel - the updatepanel that has been updated.
*/

DR.AjaxManager = new Class({
    Implements: [Options, Events]
	, AJAXTriggers: []
	, stack: []
	, __oldCmsPostBackFunction: undefined
    /*
    Method: initialize
    Initializes a new DR.AjaxManager. Call on document ready.
    */
	, initialize: function() {
	    this.form = $$('form')[0];
	    this.request = new Request({
	        url: __CMS_CurrentUrl ? __CMS_CurrentUrl : this.form.getProperty('action')
			, onSuccess: this.success_handler.bind(this)
			, onFailure: this.failure_handler.bind(this)
			, headers: {
			    'X-DRAJAX': '1'
				, 'Content-Type': 'application/x-www-form-urlencoded'
			}
			, autoCancel: true
	    });

	    // bind functions
	    ['postback', 'submitButtonHandler', 'send']
			.each(function(f) { this[f].bound = this[f].bind(this); }, this);

	    if (typeof __cmsResetFormCachedPostBack != "undefined") {
	        __oldCmsPostBackFunction = __cmsResetFormCachedPostBack;
	        __cmsResetFormCachedPostBack = this.postback.bound;
	    }
	    else {
	        __doPostBack = this.postback.bound;
	    }

	    if (!$('__EVENTTARGET')) {
	        var eventtarget = new Element('input', { type: 'hidden', id: '__EVENTTARGET', name: '__EVENTTARGET', value: '' });
	        eventtarget.inject($('__VIEWSTATE'), 'after');
	    }
	    if (!$('__EVENTARGUMENT')) {
	        var eventargument = new Element('input', { type: 'hidden', id: '__EVENTARGUMENT', name: '__EVENTARGUMENT', value: '' });
	        eventargument.inject($('__VIEWSTATE'), 'after');
	    }

	    this.import_triggers();
	    this.attach_triggers();
	}

    /*
    Method: attach_triggers
    Initialize / attach events to form submitbuttons. Required to handle async postback for regular submit buttons.
    This function is called automatically from <DR.AjaxManager.initialize>, and after a panel has been updated.
    Parameters:
    root - optional, a dom element to limit the function; defaults to document
    */
	, attach_triggers: function(root) {
	    if (!root) { root = this.form; }

	    root.getElements('input[type=submit], input[type=image]')
			.removeEvent('click', this.submitButtonHandler.bound)
			.addEvent('click', this.submitButtonHandler.bound);
	}
    /*
    Method: import_triggers
    Import trigger information from page by reading and parsing the DR_AJAX_TRIGGERS hidden field. This function disables the DR_AJAX_TRIGGERS hidden field after processing it.
    This function is called automatically from <DR.AjaxManager.initialize>.
    */
	, import_triggers: function() {
	    var triggers = $('DR_AJAX_TRIGGERS');
	    if (triggers) {
	        this.AJAXTriggers = JSON.decode(this.base64_decode(triggers.value)).map(function(arr) {
	            arr = $splat(arr);
	            return {
	                TriggerControlUniqueID: arr[0].replace(/:/g, '$')
					, TriggerControlClientID: arr[0].replace(/\$/g, '_')
					, EventName: arr.length > 1 ? arr[1] : ''
	            };
	        });
	        triggers.setProperty('disabled', true);
	    } else {
	        this.AJAXTriggers = [];
	    }
	}
    /*
    Method: base64_decode
    Decodes a base64 string
    Parameters:
    s - string to decode
    Returns: 
    base64 decoded copy of s
    */
	, base64_decode: function(s) {
	    var base64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split("");
	    var base64inv = {}; for (var i = 0; i < base64chars.length; i++) { base64inv[base64chars[i]] = i; }
	    var p = (s.charAt(s.length - 1) === '=' ? (s.charAt(s.length - 2) === '='
			? 'AA' : 'A') : ""); var r = ""; s = s.substr(0, s.length - p.length) + p;
	    s = s.replace(new RegExp('[^' + base64chars.join("") + ']', 'g'), "");
	    for (var c = 0; c < s.length; c += 4) {
	        var n = (base64inv[s.charAt(c)] << 18) + base64inv[s.charAt(c + 3)] +
				(base64inv[s.charAt(c + 1)] << 12) + (base64inv[s.charAt(c + 2)] << 6);
	        r += String.fromCharCode((n >>> 16) & 255, (n >>> 8) & 255, n & 255);
	    }
	    return r.substring(0, r.length - p.length);
	}
    /*
    Method: postback
    Setup a postback to server. Checks the list of triggers managed by the AjaxManager object, and creates an async postback if the event target is registered as an async trigger. Otherwise a synchronous postback is sent.
    Parameters:
    target - Event target of the asp.net postback.
    event_args - optional, Event arguments for the asp.net postback; defaults to an empty string.
    always_async - optional, forces the postback to be async if true; defaults to false.
    */
	, postback: function(target, event_args, always_async) {

	    // if marked as async postback or in triggerlist, push on stack and send
	    if (always_async || this.AJAXTriggers.map(function(o) { return o.TriggerControlUniqueID; }).contains(String(target))) {
	        this.stack.push({
	            target: target
				, event_args: event_args
	        });

	        var ActivatedControl = String(target);

	        var progressPanels = $$(".DR_AJAX_Extensions_ProgressPanel");
	        progressPanels.each(function(panel) {
	            var TriggerPanelsString = String(panel.get("dr_StartTriggers"));
	            if (TriggerPanelsString != null && TriggerPanelsString.length > 0) {
	                var TriggerPanels = TriggerPanelsString.split(",");
	                TriggerPanels.each(function(trigger) {
	                    if (trigger.lastIndexOf("*") >= 0) {
	                        //Ends on *, meaning we need to regex test
	                        var newTrigger = trigger.replace("*", "");
	                        if (ActivatedControl.indexOf(newTrigger) == 0) {
	                            panel.setStyle("display", "block");
	                        }
	                    }
	                    else {
	                        //Normal match
	                        if (trigger == ActivatedControl) {
	                            panel.setStyle("display", "block");
	                        }
	                    }
	                });
	            }
	        });

	        this.send();
	        return;
	    }

	    if (typeof __oldCmsPostBackFunction != "undefined") {
	        __oldCmsPostBackFunction(String(target), event_args);
	    }
	    else {
	        // else do synchronous postback (regular form submit)
	        $('__EVENTTARGET').set('value', String(target));
	        $('__EVENTARGUMENT').set('value', event_args);
	        this.form.submit();
	    }
	}
    /*
    Method: send
    Send a postback set up by <DR.AjaxManager.postback>
    */
	, send: function() {

	    if (this.request.running || !this.stack.length) { return; }

	    var args = this.stack.shift();

	    var data = new Hash();
	    this.form.getElements('input, select, textarea').each(function(el) {
	        var name = el.name, type = el.type, value = Element.get(el, 'value');
	        if (value === false || !name || el.disabled || type === 'submit') { return; }
	        if (type === 'radio' && !el.get('checked')) { return; }
	        if (data.get(name)) {
	            data.set(name, $splat(data.get(name)).extend(value));
	        } else {
	            data.set(name, value);
	        }
	    });
	    data.set('__EVENTTARGET', String(args.target));
	    data.set('__EVENTARGUMENT', args.event_args);

	    this.request.send({
	        data: data.toQueryString()
	    });
	}
    /*
    Method: failure_handler
    Dummy method to silently handle failures in postback queue.
    */
	, failure_handler: function() {
	    this.send.bound.delay(50);
	}
    /*
    Method: success_handler
    Called on successfull completion of postback, and updates required fields and panels on the page. Also fires events on updatePanels, resetting progress display. 
    */
	, success_handler: function(json) {
	    // Temporary work-around for custom HTML appended to AJAX outputs
	    var jsonString = json.trim();
	    if (jsonString.charAt(0) != "{" || jsonString.charAt(jsonString.length - 1) != "}")
	        return;

	    json = JSON.decode(json);

	    // redirect to location, if specified
	    if (json.Location) {
	        window.location = json.Location;
	        return;
	    }

	    $H(json.fields).each(function(value, field_id) {
	        $$('#' + field_id).set('value', value);
	    });

	    this.import_triggers();

	    $H(json.updatePanels).each(function(html, id) {
	        var panel = $(id);
	        if (!panel) { return; }


	        var progressPanels = $$(".DR_AJAX_Extensions_ProgressPanel");
	        progressPanels.each(function(panel) {
	            var TriggerPanelsString = String(panel.get("dr_StopTriggers"));
	            if (TriggerPanelsString != null && TriggerPanelsString.length > 0) {
	                var TriggerPanels = TriggerPanelsString.split(",");
	                TriggerPanels.each(function(trigger) {
	                    if (trigger.lastIndexOf("*") >= 0) {
	                        //Ends on *, meaning we need to regex test
	                        var newTrigger = trigger.replace("*", "");
	                        if (id.indexOf(newTrigger) == 0) {
	                            panel.setStyle("display", "none");
	                        }
	                    }
	                    else {
	                        //Normal match
	                        if (trigger == id) {
	                            panel.setStyle("display", "none");
	                        }
	                    }
	                });
	            }
	        });

	        var tmp = new Element('div').set('html', html);
	        var elements = tmp.getFirst().getChildren();
	        html = tmp.getFirst().get('html');

	        var pending = new DR.AjaxManager.UpdatePendingEvent();
	        pending.target = panel;
	        panel.fireEvent('updatePending', [pending, elements, html]);

	        if (pending.perform_default) {
	            panel.empty().adopt(elements);

	            var attributes = {};
	            $A(tmp.getFirst().attributes).each(function(o) {
	                if ($type(o.nodeValue) === "string") {
	                    attributes[o.nodeName] = o.nodeValue;
	                }
	            });
	            panel.set(attributes);
	        }

	        this.attach_triggers(panel);
	        panel.fireEvent('updateComplete', panel);

	    }, this);

	    this.send.bound.delay(50);
	}
    /*
    Function: submitButtonHandler
    Cancels click events from submit buttons and maps them to postbacks, so they can be handled like all other calls to postback().
    Handles events registered by <DR.AjaxManager.attach_triggers>.
    */
	, submitButtonHandler: function(e) {
	    var trig = this.AJAXTriggers.filter(function(o) { return o.TriggerControlClientID === e.target.id; });
	    if (trig.length) {
	        e.stop();
	        this.postback(trig[0].TriggerControlUniqueID, '');
	    }
	}
});

DR.AjaxManager.UpdatePendingEvent = new Class({
    perform_default: true
	, preventDefault: function() { this.perform_default = false; }
	, stop: function() { return this.preventDefault(); }
});

window.addEvent('domready', function() {
    AjaxManager = new DR.AjaxManager();
});

/*** AJAX MANAGER END ***/

var Update;
var UPlayerInstance;


// Player class
var UPlayerWrapper = new Class({
    Implements: [Events, Options]

	, firstClipPlay: true

	, PlayerInstance: undefined

	, initialize: function() {
	    var playerD = $('player_d');

	    // Listener (listens to the framework if a new file is going to play)
	    Update.RegisterStartClipEvent(this, function(options) {
	        // Check if a media link is set
	        if (typeof (options.Media) !== 'undefined') {
	            // Check what file type it is trying to play
	            if (options.MediaType == "Flash" || options.MediaType == "MPEG4" || options.MediaType == "RTMP" || options.MediaType == "liveStream") {
	                var GUID = "";

	                var MediaUrl = options.Media;
	                if (options.MediaType != "liveStream" && options.MediaType != "RTMP") { MediaUrl = MediaUrl + '&OnlyPath=true'; }

	                if (options.MediaType == "RTMP" && MediaUrl.search(/^http:\/\//i) != -1) {
	                    var req = new Request({
	                        async: false,
	                        url: MediaUrl,
	                        onComplete: function(response) { MediaUrl = response; }
	                    }).send();
	                    //alert("Fetched rtmp url");
	                }


	                //alert("Type:" + options.MediaType + "\t Url:" + MediaUrl);

	                if (this.PlayerInstance === null || typeof (this.PlayerInstance) === "undefined") {
	                    //** FLV (Flash) **
	                    GUID = options.GUID;
	                    //{className:"StationID", parameters:{file:'/Design/www/update/img/player/ident.png', align:'tl', marginLeft:82, marginTop:22}},
	                    var player_options = {
	                        wmode: "transparent",
	                        width: "550",
	                        height: "310",
	                        version: "9",
	                        smoothing: true,
	                        autoplay: true,
	                        swf: '/Design/www/update/swf/Uplayer.swf',
	                        playlist: [{
	                            mediaFile: MediaUrl,
	                            scaleMode: "box",
	                            overscan: 0.02,
	                            gemius_live: (options.MediaType == "liveStream"),
	                            gemius_materialId: "019_" + GUID + "&" + options.Name,
	                            gemius_customPackage: [
													{ name: "CHANNEL", value: "Update" },
													{ name: "AUTOSTART", value: "Yes" }
											]}],
	                            modules: [
											{ className: 'JavaScript' },
											{ className: "Gemius", parameters: {
											    encoding: "utf-8",
											    identifier: "p9AwR.N.S86s_NjaJKdww7b.fdp8ky90ZnrKpgLHOUn.s7",
											    hitCollector: "http://sdk.hit.gemius.pl",
											    playerId: "UPlayer"
											}
											},
											{ className: 'Persistent', parameters: { pause: true, volume: true, index: 2} },
											{ className: 'Skin', parameters: { swf: '/Design/www/update/swf/skin.swf?guid=' + GUID, index: 1} }
											]
	                        };

	                        // Clear any WMP html
	                        playerD.innerHTML = "";

	                        this.PlayerInstance = new Uplayer(playerD, player_options);

	                        this.PlayerInstance.addEvent('complete', function(s) {
	                            Update.FireClipCompletedEvent();
	                        } .bind(this));

	                        this.PlayerInstance.addEvent('stateChange', function(s) {
	                            // Check which state the player is broadcasting
	                            //alert(s);

	                            switch (s) {
	                                case "play":
	                                    Update.FireClipStartedEvent();
	                                    break;
	                                case "pause":
	                                    Update.FireClipPausedEvent();
	                                    break;
	                                case "stop":
	                                    Update.FireClipStoppedEvent();
	                                    break;
	                            }
	                        } .bind(this));

	                        // Also let flash know that we forced the checkbox to true
	                        //Swiff.remote(this.PlayerInstance.swiff.object, 'setAutoplay', true);

	                    } else {
	                        GUID = options.GUID;
	                        this.PlayerInstance.setPlaylist([{
	                            mediaFile: MediaUrl,
	                            scaleMode: "box",
	                            overscan: 0.02,
	                            gemius_live: (options.MediaType == "liveStream"),
	                            gemius_materialId: "019_" + GUID + "&" + options.Name,
	                            gemius_customPackage: [
															{ name: "CHANNEL", value: "Update" },
															{ name: "AUTOSTART", value: "Yes" }
														]
}]);
	                            // Push GUID
	                            Swiff.remote(this.PlayerInstance.swiff.object, 'getGuid', GUID);
	                        }
	                    }
	                    else {
	                        //** WMP (Microsoft Media Player) **
	                        var viewportID = "player_d";
	                        var oViewport = playerD;

	                        // Clear any UPlayer html
	                        oViewport.innerHTML = "";

	                        var embedPlayerID = viewportID + "Player";
	                        var strClipUrl = options.Media; // + "&bitrate=low";

	                        var playerHeight = 310;
	                        var playerWidth = parseInt(oViewport.offsetWidth, 10);
	                        var sWMVPlayerHTML = "";

	                        var allSupported = window.ActiveXObject ? true : false;
	                        if (allSupported) {
	                            sWMVPlayerHTML += '<object ID="' + embedPlayerID + '"';
	                            sWMVPlayerHTML += 'CLASSID="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6" width="' + playerWidth + '" height="' + playerHeight + '">';
	                            sWMVPlayerHTML += '<param name="URL" value="' + strClipUrl + '">';
	                            sWMVPlayerHTML += '<param name="AutoStart" value="' + true + '">';
	                            sWMVPlayerHTML += '<param value="True" name="ShowControls">';
	                            sWMVPlayerHTML += '<param value="True" name="ShowAudioControls">';
	                            sWMVPlayerHTML += '<param value="True" name="ShowPositionControls">';
	                            sWMVPlayerHTML += '<param value="True" name="ShowDisplay">';
	                            sWMVPlayerHTML += '<param value="True" name="ShowCaptioning">';
	                            sWMVPlayerHTML += '<param value="True" name="ShowGotoBar">';
	                            sWMVPlayerHTML += '<param value="True" name="ShowStatusBar">';
	                            sWMVPlayerHTML += '<param value="full" name="UIMode">';
	                            sWMVPlayerHTML += '</object>';
	                        }
	                        else {
	                            sWMVPlayerHTML += '<embed  ';
	                            sWMVPlayerHTML += ' id="' + embedPlayerID + '" ';
	                            sWMVPlayerHTML += ' name="' + embedPlayerID + '" ';
	                            sWMVPlayerHTML += ' type="application/x-mplayer2" '; // video/x-ms-wmv
	                            sWMVPlayerHTML += ' width="' + playerWidth + '" ';
	                            sWMVPlayerHTML += ' height="' + playerHeight + '" ';
	                            sWMVPlayerHTML += ' src="' + strClipUrl + '" ';
	                            sWMVPlayerHTML += ' fullScreen="0"';
	                            sWMVPlayerHTML += ' currentPosition="0"';
	                            sWMVPlayerHTML += ' autostart="' + true + '"';
	                            sWMVPlayerHTML += ' stretchtofit="0"';
	                            sWMVPlayerHTML += ' showcontrols="1"';
	                            sWMVPlayerHTML += ' autorewind="1" ';
	                            sWMVPlayerHTML += ' showaudiocontrols="1"';
	                            sWMVPlayerHTML += ' showpositioncontrols="1"';
	                            sWMVPlayerHTML += ' showcaptioning="0"';
	                            sWMVPlayerHTML += ' showgotobar="0"';
	                            sWMVPlayerHTML += ' showstatusbar="1"';
	                            sWMVPlayerHTML += ' uimode="full"';
	                            sWMVPlayerHTML += ' ></embed>';
	                        }

	                        oViewport.innerHTML = sWMVPlayerHTML;
	                        this.PlayerInstance = null;
	                    }
	                } else {
	                    alert("Der er sket en fejl. Linket til video filen er ufuldstændigt, så vi kan ikke vise videoen. Kontakt venligst DR for at udbedre fejlen.");
	                }
	            } .bind(this));
	        }

    // Scroll the browser window aligning the top with the news ticker top
	, scrollToPlayer: function() {
	    var playerElement = $('player_d');
	    if (playerElement === null) {
	        return;
	    }

	    // Prevent the window from auto-scrolling when the page first loads
	    if (this.firstClipPlay) {
	        this.firstClipPlay = false;
	        return;
	    }

	    var playerPosition = playerElement.getPosition();
	    window.scrollTo(playerPosition.x, playerPosition.y - 32);
	}
});

// Framework class
var UpdateFramework = new Class({
    Implements: [Events, Options]

	, StartClipListeners: []
	, ClipPausedListeners: []
	, ClipClearListeners: []
	, ClipStartedListeners: []
    , ClipStoppedListeners: []
    , ClipCompletedListeners: []
	, InfoHeader: undefined
	, InfoDate: undefined
	, InfoDescription: undefined
	, InfoAuthor: undefined
	, InfoLink: undefined
	, InfoRelatedAmount: undefined
	, InfoRelatedContainer: undefined

	, initialize: function() {
	    this.InfoHeader = $('updatePlayerTitle');
	    this.InfoDate = $('updatePlayerDate');
	    this.InfoDescription = $('updatePlayerDescription');
	    this.InfoAuthor = $('updatePlayerAuthor');
	    this.InfoRelatedAmount = document.getElement('.updatePlayerRelatedArticelsNo');
	    this.InfoRelatedContainer = document.getElement('.updatePlayerRelatedArticelsUl');
	    this.InfoLink = document.getElement('.updatePlayerCopyLinkPopupBoxInput');
	}

	, RegisterStartClipEvent: function(obj, callback) {
	    if (!this.StartClipListeners.contains(obj)) {
	        obj.addEvent('UPlayerStartClip', callback);

	        this.StartClipListeners.include(obj);
	    }
	}

	, RegisterClipStartedEvent: function(obj, callback) {
	    if (!this.ClipStartedListeners.contains(obj)) {
	        this.ClipStartedListeners.length = 0;

	        obj.addEvent('UPlayerClipStarted', callback);

	        this.ClipStartedListeners.include(obj);
	    }
	}

	, RegisterClipPausedEvent: function(obj, callback) {
	    if (!this.ClipPausedListeners.contains(obj)) {
	        this.ClipPausedListeners.length = 0;

	        obj.addEvent('UPlayerClipPaused', callback);

	        this.ClipPausedListeners.include(obj);
	    }
	}

    , RegisterClipStoppedEvent: function(obj, callback) {
        if (!this.ClipStoppedListeners.contains(obj)) {
            //this.ClipStoppedListeners.length = 0;

            obj.addEvent('UPlayerClipStopped', callback);

            this.ClipStoppedListeners.include(obj);
        }
    }

    , RegisterClipCompletedEvent: function(obj, callback) {
        if (!this.ClipCompletedListeners.contains(obj)) {
            //this.ClipStoppedListeners.length = 0;

            obj.addEvent('UPlayerClipCompleted', callback);

            this.ClipCompletedListeners.include(obj);
        }
    }

	, RegisterClipClearedEvent: function(obj, callback) {
	    if (!this.ClipClearListeners.contains(obj)) {

	        obj.addEvent('UPlayerClipClear', callback);

	        this.ClipClearListeners.include(obj);
	    }
	}

	, FireStartClipEvent: function(media, mediatype, guid, name) {
	    Update.StartClipListeners.each(function(obj) {
	        obj.fireEvent('UPlayerStartClip', { "Media": media, "MediaType": mediatype, "GUID": guid, "Name": name, "Autostart": true });
	    });
	}

	, FireClipStartedEvent: function() {
	    Update.ClipStartedListeners.each(function(obj) {
	        obj.fireEvent('UPlayerClipStarted');
	    });
	}

	, FireClipPausedEvent: function() {
	    Update.ClipPausedListeners.each(function(obj) {
	        obj.fireEvent('UPlayerClipPaused');
	    });
	}

    , FireClipStoppedEvent: function() {
        Update.ClipStoppedListeners.each(function(obj) {
            obj.fireEvent('UPlayerClipStopped');
        });
    }

    , FireClipCompletedEvent: function() {
        Update.ClipCompletedListeners.each(function(obj) {
            obj.fireEvent('UPlayerClipCompleted');
        });
    }

    , FireClipClearEvent: function() {
        Update.ClipClearListeners.each(function(obj) {
            obj.fireEvent('UPlayerClipClear');
        });
    }

	, LoadClip: function(clip, callback) {
	    this.UpdateInfoboxContents(clip);

	    // Clear marked playing clip
	    this.FireClipClearEvent();

	    // Call the callback function after clearing, marking the new clip to be marked
	    if (typeof (callback) === "function") {
	        callback();
	    }

	    this.FireStartClipEvent(clip.Media, clip.MediaType, clip.GUID, clip.Name);

	    this.ChangeShareboxContents(clip.GUID);

	    this.RegisterClipViewed(clip.GUID);

	    UPlayerInstance.scrollToPlayer();
	}

	, CheckAutoplay: function() {
	    // Flash calls this function to know what to do

	    // Check if playlist is compelete or we are in another playlist
	    if (!objUpdatePlaylist1.isAutoPlayValid()) {
	        document.getElement('.updatePlaylist1AutoplayBox').checked = false;
	    }
	    // Return state of autoplay
	    return document.getElement('.updatePlaylist1AutoplayBox').checked;
	}

	, UpdateInfoboxContents: function(clip) {
	    this.InfoHeader.innerHTML = clip.Name;
	    this.InfoDate.innerHTML = clip.PublishedTime;
	    this.InfoDescription.innerHTML = clip.Description;
	    this.InfoLink.value = this.GetDeeplink(clip.GUID);
	    this.InfoAuthor.innerHTML = this.GetAuthorText(clip.Author);
	    this.InfoAuthor.href = "mailto:" + clip.AuthorMail;
	    this.InfoRelatedAmount.innerHTML = clip.InternalLinks.length + clip.ExternalLinks.length;
	    this.InfoRelatedContainer.innerHTML = this.GetRelatedLinks(clip);

	    // Reset the vars for sliding in the related script
	    initSlideVars(clip.InternalLinks.length);
	}

    /**
    * Initiate loading of AJAX cliplists, handling automatic retry and time-out
    **/
	, LoadCliplistContents: function(ajaxPanel, callbackFunction, ajaxLink) {
	    // Start on Ajax contents
	    ajaxPanel.removeEvent('updateComplete', callbackFunction);

	    if (ajaxPanel.getElement('.ajaxLoading').getStyle('display') == 'none') {
	        callbackFunction();
	        ajaxPanel.addEvent('updateComplete', callbackFunction); // even if there's no loading screen, we still need to add events to the clips if the contents should change
	    }
	    else {
	        ajaxPanel.addEvent('updateComplete', callbackFunction);

	        var ajaxLoop;
	        var count = 1;
	        var delay = 3000;
	        var numberOfRetries = 5;

	        var getCliplistData = function() {
	            if (ajaxPanel.getElement('.ajaxLoading').getStyle('display') == 'none') {
	                ajaxLoop = $clear(ajaxLoop);
	                return;
	            }

	            if (count > numberOfRetries) {
	                ajaxLoop = $clear(ajaxLoop);

	                ajaxPanel.getelement('.ajaxLoading .ajaxLoadingImageGreen').set('class', 'ajaxLoadingImageGreenError');
	                ajaxPanel.getelement('.ajaxLoading .ajaxLoadingTextGreen').set('html', 'Fejl ved indlæsning');

	                return;
	            } else {
	                eval(ajaxLink);
	            }

	            count++;
	            delay *= 2;
	        };

	        getCliplistData();
	        ajaxLoop = getCliplistData.periodical(delay);
	    }
	}

    /**
    * Update the contents of the sharebox each time we load a new clip.
    * Since all the functionality in the sharebox relies on the browser URL,
    * we have to manipulate their links.
    **/
	, ChangeShareboxContents: function(clipGuid) {
	    this.ChangeAddThisLink(clipGuid);

	    this.ChangeMailButtonLink(clipGuid);

	    this.ChangeFacebookLink(clipGuid);
	}

    /**
    * Updated the AddThis link to point to the current playing clip
    * Since the AddThis script relies on the browser URL to create
    * a deeplink, we must manipulate it's contents with regular expressions
    **/
	, ChangeAddThisLink: function(clipGuid) {
	    var sharebox = document.getElement('.sharboxFooter p');
	    if (sharebox === null) {
	        return;
	    }
	    sharebox.setAttribute('url', this.GetDeeplink(clipGuid));

	    var shareboxLink = sharebox.getElement("a");
	    shareboxLink.addEvent("mouseover", function() { return addthis_open(this, '', this.parentNode.getAttribute('url'), '[TITLE]'); });

	    if (shareboxLink.getAttribute("onmouseover") !== null) {
	        shareboxLink.removeAttribute("onmouseover");
	    }
	}

    /**
    * Update the mail link to the current playing clip.
    * Since the mail link is generated when the page is first loaded,
    * we must update it every time a new clip is loaded.
    **/
	, ChangeMailButtonLink: function(clipGuid) {
	    var mailLink = document.getElement('#articleShare .icMail a');

	    // IE6 and maybe newer does not support removeAttribute on the onclick attribute, as per http://msdn.microsoft.com/en-us/library/ms536696(VS.85).aspx
	    if (Browser.Engine.trident) {
	        mailLink.onclick = null;
	    } else {
	        mailLink.removeAttribute("onclick");
	    }

	    mailLink.removeEvents("click");
	    mailLink.addEvent("click", function() {
	        new DR.Window('/Forms/Published/Tipglobal.aspx?postingGuid=' + clipGuid + "&linksrc=" + this.GetDeeplink(clipGuid), { title: 'SendTilVen', height: 560, width: 450 });
	    } .bind(this));
	}

    /**
    * Update the Facebook link to the current playing clip.
    * Since the Facebook link is generated when the page is first loaded,
    * we must update it every time a new clip is loaded.
    **/
	, ChangeFacebookLink: function(clipGuid) {
	    document.getElement('#articleShare .icFacebook a').set('href', clipGuid);
	}

    /**
    * Report to the CMS system that this clip is being played
    **/
	, RegisterClipViewed: function(clipGuid) {
	    var hitcountRequest = new Request({ url: '/Forms/Published/HitCounter.aspx?GUID=' + clipGuid, autoCancel: true });
	    hitcountRequest.send();
	}

    /**
    * Generate an absolute url pointing to the current playing clip
    **/
	, GetDeeplink: function(clipGuid) {
	    var url = window.location.href;

	    // Remove trailing hash sign from the url
	    if (url.match("#$")) {
	        url = url.substring(0, url.length - 1);
	    }

	    var intIndexOfQ = url.indexOf('?');
	    if (intIndexOfQ != -1) {
	        url = url.slice(0, intIndexOfQ);
	    }

	    return url + "?video=" + clipGuid;
	}

    /**
    * Generate the contents for the related links container
    **/
	, GetRelatedLinks: function(clip) {
	    var relatedContents = "";

	    if (clip.InternalLinks !== null) {
	        clip.InternalLinks.each(function(obj) {
	            relatedContents += '<li class="updatePlayerRelatedArticelsList"><a title="' + obj.Name + '" href="' + obj.Path + '">' + obj.Name + '</a></li>';
	        });
	    }

	    if (clip.ExternalLinks !== null) {
	        clip.ExternalLinks.each(function(obj) {
	            relatedContents += '<li class="updatePlayerRelatedArticelsList"><a title="' + obj.Name + '" href="' + obj.Url + '">' + obj.Name + '</a></li>';
	        });
	    }

	    return relatedContents;
	}

    /**
    * Generate the author text for the infobox
    */
	, GetAuthorText: function(authorName) {
	    return (authorName !== "" ? "Af: " + authorName : "");
	}
});

window.addEvent('domready', function() {
    // FIXME: Temporary hack to prevent browser from executing this code several times
    if (typeof Update !== "undefined") {
        return;
    }

    Update = new UpdateFramework();
    UPlayerInstance = new UPlayerWrapper();

    // Initiate classes
    if (typeof initPlaylist1 === "function") {
        initPlaylist1();
    }
    if (typeof initPlaylist2 === "function") {
        initPlaylist2();
    }
    if (typeof initPlaylist3 === "function") {
        initPlaylist3();
    }
    if (typeof initSpotPlayer === "function") {
        initSpotPlayer();
    }

    // Modify the LIVE button to start the TV signal feed
    var liveButton = document.getElement('.theme9');
    if (liveButton !== null) {
        liveButton.addEvent('click', function(event) {
            //var LiveFeedMedia = this.getElement('a').getProperty('href');
            var LiveFeedMedia = "rtmp://rtmplive.dr.dk/live/livedr03astream2";
            var liveFeedPostingGUID = "{6B171E62-99D7-440A-8FD0-4E3B9A8132BC}";
            var liveFeedName = "Direkte TV Signal";
            var liveFeedBroadcastTime = "Live";
            var liveFeedDescription = "Du ser nu det direkte TV Signal fra DR Update.";
            var liveFeedMediaType = "liveStream";

            var arrJSonDataForLive = JSON.decode('{"GUID":"' + liveFeedPostingGUID + '","Name":"' + liveFeedName + '","BroadcastTime":"","Author":"","Description":"' + liveFeedDescription + '","Media":"' + LiveFeedMedia + '","MediaType":"' + liveFeedMediaType + '","InternalLinks":[],"ExternalLinks":[],"Image":""}');

            Update.LoadClip(arrJSonDataForLive, null, false);
            return false;
        });
    }

    // Modify the "Dagens vejr" (weather) button in the top/site navigation to display weather data
    // obtained from a drxml file.
    //var weatherButton = document.getElement('.theme12');
    //var weatherTestData = "<p><a href='#'><img src='http://dr.dk/Design/www/update/img/vejrikoner/1.gif' /><span class='text'>Dagens vejr</span><span id='degrees' class='degrees'>16<sup>o</sup></span></a></p>";
    /*
    if (Browser.Engine.trident) { //let's leave it off for FF for now..
    var weatherRequest = new Request({
    url: 'http://webudv01.net.dr.dk/tjenester/update/update2/vejr.drxml',
    method: 'get',
    onComplete: function(response) {
    weatherButton.set('html', response);
    }
    }) 
    weatherRequest.send();
    } 
    */


    // Add ...'s to Playlist teasertexts
    $$('div.updatePlaylist2DimmerPadding').each(function(item) {
        var dateText = item.getElement(".updatePlaylist2InfoDate").get("text").trim();
        var itemTxt = item.get("html").replace(/\n/g, "").replace(/<div.+div>/mi, "").trim();
        if (itemTxt.length > 80) {
            item.innerHTML = '<div class="updatePlaylist2InfoDate">' + dateText + '</div>' + itemTxt.substring(0, 80) + "...";
        }
    });

    // Watermarked search box functionality
    var searchBox = document.getElement('.updateSearchBox');
    if (searchBox !== null) {
        var orgSearchContent = searchBox.get('value');
        searchBox.addEvent('focus', function(event) {
            if (searchBox.get('value') == orgSearchContent) {
                searchBox.set('value', '');
            }
        });

        searchBox.addEvent('blur', function(event) {
            if (searchBox.get('value').length < 1) {
                searchBox.set('value', orgSearchContent);
            }
        });

        // a keydown event for tracking if the user presses enter in the searchfield
        // also clears the field of the user clicks escape
        searchBox.addEvent('keydown', function(event) {
            if (event.key == "enter") {
                eval(document.getElement('.updateSearchButton a').getProperty('href'));
                return false;
            }
            if (event.key == "escape") {
                searchBox.fireEvent('blur');
            }

        });



    }

    var addthisJavascript = document.createElement("script");
    addthisJavascript.setAttribute("type", "text/javascript");
    addthisJavascript.setAttribute("src", "http://s7.addthis.com/js/152/addthis_widget.js");

    document.getElementsByTagName("head")[0].appendChild(addthisJavascript);

    // TIKKER
    var sTikkerXML = document.getElement("#updatePlayerTicker") === null ? "" : document.getElement("#updatePlayerTicker").get('html');

    var tickerSwiff = new DR.Swiff(
		"/Design/www/update/swf/tikker.swf?tikkerXML=" + sTikkerXML,
		{
		    id: "updateTikker_fs",
		    width: 550,
		    height: 30,
		    version: 9,
		    container: "updateTikker",
		    params: {
		        wmode: 'transparent'
		    },
		    vars: {}
		}
	);
});
