Powered.Util = Class.create();

Powered.Util.noenter = function (event) {
    return !(event && event.which == 13);
};

Powered.Util.log = function(s) {
    var logElem = document.getElementById('pageLog');
    if (logElem) {
        logElem.innerHTML += "<div>" + s + "</div>";
    }
};

Powered.Util.stopEvent = function(e) {
    if (!e) var e = window.event;
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
};

Powered.Util.isIE = function() {
    var browser = navigator.appName;
    var regexp = new RegExp('explorer', 'i');
    return browser.match(regexp);
};

Powered.Util.getElementsByClass = function(searchClass) {
    var classElements = new Array();
    var els = document.getElementsByTagName("div");
    var elsLen = els.length;
    var pattern = new RegExp("(^|\\s)" + searchClass + "(\\s|$)");
    for (var i = 0, j = 0; i < elsLen; i++) {
        if (pattern.test(els[i].className)) {
            classElements[j] = els[i];
            j++;
        }
    }
    return classElements;
};

Powered.Util.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;
};

Powered.Util.isFunction = function(a) {
    return typeof a == 'function';
};

Powered.Util.addOptionalParams = function(param) {
    if (Powered.optionalParams) {
        param += "&" + Powered.optionalParams;
    }
    return param;
};

Powered.Util.setOptionalParams = function(param) {
    Powered.optionalParams = param;
};

Powered.Util.getCheckedValue = function (radioObj) {
    if (!radioObj)
        return "";
    var radioLength = radioObj.length;
    if (radioLength == undefined)
        if (radioObj.checked)
            return radioObj.value;
        else
            return "";
    for (var i = 0; i < radioLength; i++) {
        if (radioObj[i].checked) {
            return radioObj[i].value;
        }
    }
    return "";
};

Powered.Util.submitAjax = function(action, url, formObject, targetId) {
    if (formObject.command) {
        formObject.command.value = action;
    }
    var params = Form.serialize(formObject);
    document.getElementById(targetId).innerHTML = "  <div class='spinner'><img src='" + Powered.contextPath + "/resources/images/spinner.gif' height='16' /> Loading...</div>";
    new Ajax.Updater(targetId, Powered.contextPath + url,
    {
        asynchronous:true,
        parameters:params,
        evalScripts:true
    }
            );
    formObject.reset();
    return false;
};

Powered.Util.submitAjax = function(action, url, formObject, targetId, onSuccess, onComplete) {
    if (formObject.command) {
        formObject.command.value = action;
    }
    var params = Form.serialize(formObject);
    document.getElementById(targetId).innerHTML = "  <div class='spinner'><img src='" + Powered.contextPath + "/resources/images/spinner.gif' height='16' /> Loading...</div>";
    new Ajax.Updater(targetId, Powered.contextPath + url,
    {
        asynchronous:true,
        parameters:params,
        evalScripts:true,
        onSuccess: onSuccess,
        onComplete: onComplete
    }
            );
    formObject.reset();
    return false;
};

Powered.Util.arrayToString = function(array) {
    var s = '';
    for (var i = 0; i < array.length; i++) {
        if (i > 0) s += ',';
        s += array[i];
    }
    return s;
};

Powered.Util.userFavorite= function(objTypeId, objId, imageOnly) {
    var param = "objectTypeId=" + objTypeId + "&objectId=" + objId +"&imageOnly="+imageOnly;
    param = Powered.Util.addOptionalParams(param);
    var request = new Ajax.Request(
            Powered.contextPath + "/widget/submitUserFavorite.jsp",
    {
        parameters:param,
        onSuccess:  function(req) {
            var els = Powered.Util.getElementsByClass('userFavorite_'+objTypeId+'_'+objId);
            for (i = 0; i < els.length; i++) {
                els[i].innerHTML = req.responseText;
            }
        }
    });
};


Powered.Util.onFBLogin = function (title) {
    Powered.pageModal = Powered.Modal.show(Powered.contextPath + '/social/facebook/connect.jsp',
    {params: "target="+escape(window.location.href), id: 'FBLogin', title: "Connect to "+ title});
    return false;
}

Powered.Util.onFBLink = function (title) {
    Powered.pageModal = Powered.Modal.show(Powered.contextPath + '/social/facebook/link.jsp',
    {params: "target="+escape(window.location.href), id: 'FBLogin', title: "Connect to "+title});
    return false;
}

//Graphics library code
Powered.Graphics = Class.create();
Powered.Graphics.findPosition = function (oLink) {
    if (oLink.offsetParent) {
        for (var iPosX = 0, iPosY = 0; oLink.offsetParent; oLink = oLink.offsetParent) {
            iPosX += oLink.offsetLeft;
            iPosY += oLink.offsetTop;
        }
        return [iPosX, iPosY];
    } else {
        return [oLink.x, oLink.y];
    }
};

Powered.Graphics.getScrollXY = function() {
    var scrOfX = 0, scrOfY = 0;
    if (typeof( window.pageYOffset ) == 'number') {
        //Netscape compliant
        scrOfY = window.pageYOffset;
        scrOfX = window.pageXOffset;
    } else if (document.body && ( document.body.scrollLeft || document.body.scrollTop )) {
        //DOM compliant
        scrOfY = document.body.scrollTop;
        scrOfX = document.body.scrollLeft;
    } else if (document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop )) {
        //IE6 standards compliant mode
        scrOfY = document.documentElement.scrollTop;
        scrOfX = document.documentElement.scrollLeft;
    }
    return [ scrOfX, scrOfY ];
};

Powered.Graphics.getScreenSize = function () {
    var xScroll, yScroll;
    if (window.innerHeight && window.scrollMaxY) {
        xScroll = window.innerWidth + window.scrollMaxX;
        yScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
        xScroll = document.body.scrollWidth;
        yScroll = document.body.scrollHeight;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
        xScroll = document.body.offsetWidth;
        yScroll = document.body.offsetHeight;
    }
    var windowWidth, windowHeight;
    if (self.innerHeight) {    // all except Explorer
        if (document.documentElement.clientWidth) {
            windowWidth = document.documentElement.clientWidth;
        } else {
            windowWidth = self.innerWidth;
        }
        windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
    }

    // for small pages with total height less then height of the viewport
    if (yScroll < windowHeight) {
        pageHeight = windowHeight;
    } else {
        pageHeight = yScroll;
    }

    // for small pages with total width less then width of the viewport
    if (xScroll < windowWidth) {
        pageWidth = xScroll;
    } else {
        pageWidth = windowWidth;
    }
    arrayPageSize = new Array(pageWidth, pageHeight, windowWidth, windowHeight)
    return arrayPageSize;
};

Powered.Graphics.showOverlay = function() {
    if (!$('Overlay')) {
        var divElem = document.createElement('div');
        divElem.id = 'Overlay';
        document.body.appendChild(divElem);
    }
    var arrayPageSize = Powered.Graphics.getScreenSize();
    $('Overlay').style.width = arrayPageSize[0] + "px";
    $('Overlay').style.height = arrayPageSize[1] + "px";
    new Effect.Appear('Overlay', { duration: 0.5 , from: 0.0, to:0.5})

};

Powered.Graphics.hideOverlay = function() {
    if ($('Overlay')) {
        $('Overlay').hide();
    }
};

Powered.Graphics.loadImageOnReady = function(elemId, imgSrc) {
    $(elemId).src = imgSrc;
};

//Ratings Widgets use these methods

Powered.Rating = Class.create();


Powered.Rating.singleVote = function(ratingSystemId, ratingSystem, objTypeId, objId, rating) {
    var param = "ratingSystemId=" + ratingSystemId + "&objectTypeId=" + objTypeId + "&objectId=" + objId + "&rating=" + rating;
    param = Powered.Util.addOptionalParams(param);
    var url = Powered.contextPath + "/rating/submit_single_rating.jsp";
    var request = new Ajax.Request(
            url,
    {
        parameters:param,
        onSuccess:  function(req) {
            var els = Powered.Util.getElementsByClass(ratingSystem + "_" + objTypeId + "_" + objId);
            for (var i = 0; i < els.length; i++) {
                els[i].innerHTML = req.responseText;
            }
        }
    });
};

Powered.Rating.dualVote = function(objTypeId, objId, rating) {
    var param = "objectTypeId=" + objTypeId + "&objectId=" + objId + "&rating=" + rating;
    param = Powered.Util.addOptionalParams(param);
    var request = new Ajax.Request(
            Powered.contextPath + "/rating/submit_dual_rating.jsp",
    {
        parameters:param,
        onSuccess:  function(req) {
            var els = Powered.Util.getElementsByClass("dualRating_" + objTypeId + "_" + objId);
            for (i = 0; i < els.length; i++) {
                els[i].innerHTML = req.responseText;
            }
        }
    });
};

Powered.Rating.fiveStarRating = function(objTypeId, objId, rating, starWidth, objName, contentType) {
    var param = "objectTypeId=" + objTypeId + "&objectId=" + objId + "&rating=" + rating + "&starWidth=" + starWidth;
    param = Powered.Util.addOptionalParams(param);
    var request = new Ajax.Request(
            Powered.contextPath + "/rating/submit_5star_rating.jsp",
    {
        parameters:param,
        onSuccess:  function(req) {
            var els = Powered.Util.getElementsByClass("fiveStarRating_" + objTypeId + "_" + objId);
            for (i = 0; i < els.length; i++) {
                els[i].innerHTML = req.responseText;
            }
        }
    });
};

Powered.Rating.setRatingText = function(className, message) {
    var parentEls = Powered.Util.getElementsByClass(className);
    for (i = 0; i < parentEls.length; i++) {
        var parentEl = parentEls[i];
        for (j = 0; j < parentEl.childNodes.length; j++) {
            var childNode = parentEl.childNodes[j];
            if (childNode.className == "ratingText") {
                childNode.innerHTML = message;
            }
        }
    }
};

Powered.Rating.fiveStarUserRating = function(objTypeId, objId, rating, objName, contentType) {
    var param = "objectTypeId=" + objTypeId + "&objectId=" + objId + "&rating=" + rating;
    param = Powered.Util.addOptionalParams(param);
    var request = new Ajax.Request(
            Powered.contextPath + "/rating/submit_5star_userOnly_rating.jsp",
    {
        parameters:param,
        onSuccess:  function(req) {
            var els = Powered.Util.getElementsByClass("fiveStarUserRating_" + objTypeId + "_" + objId);
            for (i = 0; i < els.length; i++) {
                els[i].innerHTML = req.responseText;
            }
        }
    });
};

Powered.Button = Class.create({
    state:null,
    href:null,
    onclick:null,
    id: null,
    cssClass:'Button',

    initialize:function(id, state, cssClass) {
        this.id = id;
        if (cssClass) this.cssClass = cssClass;
        this.state = state;
        if (state == 'disabled') {
            var aElem = $(this.id).down();
            this.href = aElem.href;
            this.onclick = aElem.onclick;
            aElem.href = "javascript://";
            aElem.onclick = "javascript://";
        }
    },

    disable:function() {
        if (this.state == 'enabled') {
            var aElem = $(this.id).down();
            this.href = aElem.href;
            this.onclick = aElem.onclick;
            aElem.href = "javascript://";
            aElem.onclick = "javascript://";
            this.cssClass = $(this.id).className;
            Element.addClassName(this.id, "Disabled");
            this.state = 'disabled';
        }
    },

    enable:function() {
        if (this.state == 'disabled') {
            var aElem = $(this.id).down();
            aElem.href = this.href;
            aElem.onclick = this.onclick;
            this.state = 'enabled';
            Element.removeClassName(this.id, "Disabled");
        }
    }
});

Powered.NavigationBar = Class.create({
    id: null,
    url: null,
    options: {
        targetId: null,
        preFunction:null,
        postFunction:null
    },

    initialize:function(id, url, options) {
        this.url = url;
        this.id = id;
        this.options = Object.extend(this.options, options || {});
        this.links = $(id).select("a");
        for (var i = 0; i < this.links.length; i++) {
            if (this.links[i].rel) {
                Event.observe(this.links[i].id, 'click', this.goto.bindAsEventListener(this, this.links[i].rel, this.options.targetId));
            }
        }
    },

    goto:function(elem) {
        var data = $A(arguments);
        var page = data[1];
        var targetId = data[2];
        if (Powered.Util.isFunction(this.options.preFunction)) this.options.preFunction(page);
        new Ajax.Updater(targetId, Powered.contextPath + this.url,
        {
            asynchronous:true,
            parameters:"page=" + page,
            evalScripts:true
        });
        if (Powered.Util.isFunction(this.options.postFunction)) this.options.postFunction(page);
    }
});

//Confirmation javascript class
Powered.Confirm = Class.create({
    elem: null,
    options: {
        // display message
        id: 'ConfirmBox',
        msg: "Are you sure you want to proceed?",
        x_offset: -150,
        y_offset: 30,
        onSuccess:null,
        onFailure:null,
        cssClass: "Confirmation",
        okButtonClass: "Button",
        cancelButtonClass: "Button",
        //text of the ok button
        okButtonText: "Ok",
        //text of the cancel button
        cancelButtonText: "Cancel"
    },

    initialize: function(elem, options) {
        this.elem = elem;
        this.options = Object.extend(this.options, options || {});
        this.invoke();
    },

    invoke: function() {
        if (!$(this.options.id)) {
            var confirm = document.createElement('div');
            confirm.id = this.options.id;
            document.body.appendChild(confirm);
            $(this.options.id).addClassName(this.options.cssClass);
        }
        new Effect.Appear(this.options.id, { duration: 0.0});
        aPosition = Powered.Graphics.findPosition(this.elem);
        placeX = eval(aPosition[0]) + this.options.x_offset;
        placeY = eval(aPosition[1]) + this.options.y_offset;
        $(this.options.id).style.left = placeX + "px";
        $(this.options.id).style.top = placeY + "px";
        $(this.options.id).innerHTML = "<h3>" + this.options.msg + "</h3>";
        $(this.options.id).innerHTML += "<div class='" + this.options.okButtonClass + "'>" +
                                        "<a id='ConfirmBoxOkLink' href='javascript:void(0);'>" + this.options.okButtonText + "</a></div>";
        $(this.options.id).innerHTML += "<span class='Cancel'>" +
                                        "<a id='ConfirmBoxOkCancel'>" + this.options.cancelButtonText + "</a></span>";
        Event.observe('ConfirmBoxOkLink', 'click', this.success.bindAsEventListener(this));
        Event.observe('ConfirmBoxOkCancel', 'click', this.failed.bindAsEventListener(this));
    },

    success:function() {
        if (Powered.Util.isFunction(this.options.onSuccess)) this.options.onSuccess();
        Effect.Fade(this.options.id, { duration:0.0});
    },

    failed:function(elem) {
        if (Powered.Util.isFunction(this.options.onFailure)) this.options.onFailure();
        Effect.Fade(this.options.id, { duration:0.0});
    }
});

Powered.ReportAbuse = Class.create({
    elem: null,
    objectId: null,
    objectTypeId: null,
    options: {
        // display message
        id: 'ReportAbuseForm',
        loginTargetUrl: '',
        callback:null
    },

    initialize: function(elem, objectTypeId, objectId, options) {
        this.elem = elem;
        this.objectId = objectId;
        this.objectTypeId = objectTypeId;
        this.options = Object.extend(this.options, options || {});
    },

    load: function() {
        var params = Powered.Util.addOptionalParams("objectId=" + this.objectId + "&objectTypeId=" + this.objectTypeId + "&targetUrl=" + this.options.loginTargetUrl);
        Powered.pageModal = Powered.Modal.show(Powered.contextPath + "/ugc/fragments/reportAbuse.jsp",
        {id: this.options.id, title: 'Flag As Inappropriate', params: params, width: 435});

    },

    submit:function(control, typeElem, commentText) {
        var params = "objectId=" + this.objectId + "&objectTypeId=" + this.objectTypeId;
        params += "&comment=" + encodeURIComponent(commentText) + "&abuseStateId=" + Powered.Util.getCheckedValue(typeElem) + "&command=reportAbuse";
        new Ajax.Updater('reportAbuseUpdate', Powered.contextPath + '/ugc/fragments/reportAbuse.jsp',
        {
            asynchronous: true,
            parameters: params,
            evalScripts: true,
            onSuccess : function() {
                Powered.pageModal.hide();
                if (Powered.Util.isFunction(control.options.callback)) control.options.callback();
            }
        });
    },

    validateAndSave: function(control, typeElem, commentText) {
        new Ajax.Updater('abuseErrors', Powered.contextPath + '/ugc/fragments/validateReportAbuse.jsp',
        {
            asynchronous: true,
            parameters: params,
            evalScripts: true,
            onSuccess :function(response) {
                if(!response.responseText) {
                    Powered.pageModal.hide();
                    if (Powered.Util.isFunction(control.options.callback)) control.options.callback();
                }
            }
        });
    },

    callback:function() {
        if (Powered.Util.isFunction(this.options.callback)) this.options.callback();
    },

    hide:function() {
        //        $(this.options.id).hide();
        Powered.pageModal.hide();
    }
});

Powered.Util.addLoadEvent = function (func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            oldonload();
            func();
        };
    }
};
Powered.Util.printWindow = function() {
    window.print();
    return false;
};

Powered.Util.addBookmark = function (title, url) {
    if (window.sidebar) {
        window.sidebar.addPanel(title, url, "");
    }
    else if (document.all) {
        window.external.AddFavorite(url, title);
    }
    else if (window.opera && window.print) {
        return true;
    }
};

Powered.Util.winOpen = function (w, h, t, p) {
    if (!w) w = 600;
    if (!h) h = 400;
    if (!t) t = '_win';
    if (!p) p = ',resizable=1,scrollbars=1,menubar=1,status=1,toolbar=1,location=0';
    var newWin = window.open('', t, 'width=' + w + ',height=' + h + p);
    newWin.focus();
    return true;
};

Powered.HTTPUtils = Class.create();

/**
 * Returns a map of the request parameters
 */
Powered.HTTPUtils.getRequestParametersMap = function() {
    var paramsHash = {};
    if (!window.location.search) {
        return paramsHash;
    }
    var keyValuePairs = window.location.search.substring(1).split(/&/);
    for (var i = keyValuePairs.length - 1; i >= 0; i--) {
        keyValuePairs[i] = keyValuePairs[i].split(/=/);
        paramsHash[decodeURIComponent(keyValuePairs[i][0])] = decodeURIComponent(keyValuePairs[i][1]);
    }
    return paramsHash;
};

Powered.HTTPUtils.parseParameterString = function(queryString) {
    var paramsHash = {};
    var keyValuePairs = queryString.split(/&/);
    for (var i = keyValuePairs.length - 1; i >= 0; i--) {
        keyValuePairs[i] = keyValuePairs[i].split(/=/);
        paramsHash[decodeURIComponent(keyValuePairs[i][0])] = decodeURIComponent(keyValuePairs[i][1]);
    }
    return paramsHash;
};

/**
 * Removes a parameter from the given url
 */
Powered.HTTPUtils.removeParameter = function(url, parameterName) {
    var encodedParamName = encodeURIComponent(parameterName);
    var regex = new RegExp("&?" + encodedParamName + "=([^&]*)");
    url = url.replace(regex, "");
    url = url.replace(/\?&/, "?");
    if (url.charAt(url.length - 1) == "?") {
        url = url.substring(0, url.length - 1);
    }
    return url;
};

/**
 * Adds a paremter to the given url
 */
Powered.HTTPUtils.addParameter = function(url, parameterName, parameterValue) {
    return url + (url.indexOf('?') == -1 ? '?' : '&') + encodeURIComponent(parameterName) + "=" + encodeURIComponent(parameterValue);
};

Ajax.getOriginalTransport = function() {
    return Try.these(
            function() {
                return new XMLHttpRequest();
            },
            function() {
                return new ActiveXObject('Msxml2.XMLHTTP');
            },
            function() {
                return new ActiveXObject('Microsoft.XMLHTTP');
            }
            ) || false;
};

Ajax.getTransport = function() {
    if (!Powered.contextPath.startsWith('http://') || Powered.contextPath.replace(/http:\/\//, '').startsWith(document.domain)) {
        return Ajax.getOriginalTransport();
    }
    else {
        return new XMLHTTP();
    }
};


Powered.WebAnalytics = Class.create();

Powered.WebAnalytics.recordMediaView = function(url, eventType, mediaId) {
    new Ajax.Request(url,
    {
        method:'get',
        parameters:"eventType=" + eventType + "&mediaId=" + mediaId,
        onSuccess:  function(req) {
        }
    });
};

Powered.WebAnalytics.recordPageView = function(catId) {
    Powered.WebAnalytics.recordView( window.location.href, catId);
};

Powered.WebAnalytics.recordClick = function(anchorTag, params) {
    var sessionId = Powered.Util.readCookie(Powered.sessionKeyPrefix + Powered.contextPath.replace("/", "."));
    new Ajax.Request(Powered.contextPath + '/lc.gif?' + params,
    {
        method:'get',
        parameters:"s=" + sessionId + "&u=" + escape(anchorTag.href) + "&nocache=" + new Date().getTime()
    });
};

/**
 * Adds missing onmousedown="PoweredWebAnalytics.recordClick(this,'')" handlers
 * for external links
 */
Powered.WebAnalytics.addLinkClickHandlers = function() {
    var anchors = document.getElementsByTagName("A");
    var docLocation = document.location.protocol + "//" + document.location.hostname;
    for (var i = 0; i < anchors.length; i++) {
        try {
            var a = anchors[i];
            if (a.href.startsWith('/') ||
                a.href.startsWith('javascript:') ||
                a.href.contains('mailto:') ||
                a.href.startsWith('#')) {
                continue;
            }
            if (a.href.startsWith('http') && a.href.startsWith(docLocation)) {
                continue;
            }
            if (typeof (a.onmousedown) == 'undefined' || a.onmousedown == null || !a.onmousedown.toString().contains("Powered.WebAnalytics.recordClick")) {
                Event.observe(a, "mousedown", function() { Powered.WebAnalytics.recordClick(this,''); });
            }
        }
        catch (e) {
            // suppress
        }
    }
};

Powered.WebAnalytics.recordView = function(url, catId) {
    var sessionId = Powered.Util.readCookie(Powered.sessionKeyPrefix + Powered.contextPath.replace("/", "."));
    new Ajax.Request(Powered.contextPath + '/pv.gif',
    {
        method:'get',
        parameters:"s=" + sessionId + "&cid=" + catId + "&u=" + escape(url) + "&nocache=" + new Date().getTime()
    });
};

var poweredFlashRecord = null;

Powered.WebAnalytics.initFlash = function(courseId, courseSessionId) {
    poweredFlashRecord = {};
    poweredFlashRecord.courseId = courseId;
    poweredFlashRecord.courseSessionId = courseSessionId;
};

Powered.WebAnalytics.startVideo = function(mediaId) {
    if (poweredFlashRecord == null) {
        poweredFlashRecord = {};
    }
    poweredFlashRecord.mediaId = mediaId;
    poweredFlashRecord.videoTime = 0;
    poweredFlashRecord.playheadTime = 0;
};

Powered.WebAnalytics.updateVideo = function(playheadTime, videoTime) {
    if (poweredFlashRecord != null && playheadTime > poweredFlashRecord.playheadTime) {
        poweredFlashRecord.videoTime = videoTime;
        poweredFlashRecord.playheadTime = playheadTime;
    }
};

Powered.WebAnalytics.recordVideoEvent = function() {
    if (poweredFlashRecord != null && poweredFlashRecord.mediaId !=null ) {
        new Ajax.Request(Powered.contextPath + '/webAnalytics/videoEvent.jsp',
        {
            method:'get',
            asynchronous:false,
            parameters:"action=submit&flashId=" + poweredFlashRecord.mediaId + "&videoTime=" + poweredFlashRecord.videoTime + "&playheadTime=" + poweredFlashRecord.playheadTime + "&courseId=" + poweredFlashRecord.courseId + "&courseSessionId=" + poweredFlashRecord.courseSessionId + "&nocache=" + new Date().getTime()
        });
        poweredFlashRecord = null;
    }
};

Powered.WebAnalytics.createFlashRecord = function(mediaId) {
    if (poweredFlashRecord == null) {
        poweredFlashRecord = {};
    }
    poweredFlashRecord.mediaId = mediaId;
};

 Powered.WebAnalytics.recordFlashEvent = function() {
    if (poweredFlashRecord != null) {
        new Ajax.Request(Powered.contextPath + '/webAnalytics/flashEvent.jsp',
        {
            asynchronous:false,
            method:'get',
            parameters:"action=submit&flashId=" + poweredFlashRecord.mediaId + "&courseId=" + poweredFlashRecord.courseId + "&courseSessionId=" + poweredFlashRecord.courseSessionId + "&nocache=" + new Date().getTime()
        });
        poweredFlashRecord = null;
    }
};

/*
 *  utility methods for making ajax calls
 */
function doNothing() {
}

Powered.callUpdater = function(elementId, params, requestUrl, onSuccessCall, onFailureCall) {
    Powered.callUpdaterWithMethod(elementId, params, requestUrl, onSuccessCall, onFailureCall, 'post');
};

Powered.callUpdaterWithMethod = function(elementId, params, requestUrl, onSuccessCall, onFailureCall, methodType) {
    if (onSuccessCall == null) {
        onSuccessCall = doNothing;
    }
    if (onFailureCall == null) {
        onFailureCall = doNothing;
    }
    params += "&nocache=" + new Date().getTime();
    var request = new Ajax.Updater(
    {success : elementId},
            requestUrl,
    {
        method: methodType,
        parameters : params,
        onFailure : onFailureCall,
        onSuccess : onSuccessCall,
        evalScripts: true
    }
            );
};

Powered.callRequest = function(params, requestUrl, onSuccessCall, onFailureCall) {
    Powered.callRequestWithMethod(params, requestUrl, onSuccessCall, onFailureCall, 'post');
};

Powered.callRequestWithMethod = function(params, requestUrl, onSuccessCall, onFailureCall, methodType) {
    if (onSuccessCall == null) {
        onSuccessCall = doNothing;
    }
    if (onFailureCall == null) {
        onFailureCall = doNothing;
    }
    params += "&nocache=" + new Date().getTime();
    var request = new Ajax.Request(
            requestUrl,
    {
        method: methodType,
        parameters : params,
        onFailure : onFailureCall,
        onSuccess : onSuccessCall,
        evalScripts: true
    }
            );
};

Powered.fireEvent = function (element, event) {
    var evt = null;
    if (document.createEventObject) {
        // dispatch for IE
        evt = document.createEventObject();
        return element.fireEvent('on' + event, evt);
    }
    else {
        // dispatch for firefox + others
        evt = document.createEvent("HTMLEvents");
        evt.initEvent(event, true, true); // event type,bubbling,cancelable
        return !element.dispatchEvent(evt);
    }
};

Powered.backgroundLabel = function(element, text, color) {
    var originalColor = element.style.color;
    if (!color) {
        color = "#aaa";
    }
    if (element.value == '') {
        element.value = text;
        element.style.color = color;
    }
    element.onfocus = function() {
        if (element.value == text) {
            element.value = '';
        }
        element.style.color = originalColor;
    };
    element.onblur = function() {
        if (element.value == '') {
            element.value = text;
            element.style.color = color;
        }
    };
};


//Modal dialog class : hacked together from simpleModal and window
Powered.pageModal = new Object();

if (!Powered.Modal)
    Powered.Modal = new Object();

Powered.Modal.Methods = {
	overrideAlert: false, // Override standard browser alert?
	focusableElements: new Array,
	currFocused: 0,
	initialized: false,
	active: true,
    resizeInterval: null,
    options: {
        id : "ModalWindow",
        className : "modal",
        title: "", // Title of the Modal window
        overlayClose: true, // Close modal box by clicking on overlay
        width: 500, // Default width in px
        height: 90, // Default height in px
        overlayOpacity: .65, // Default overlay opacity
        overlayDuration: .25, // Default overlay fade in/out duration in seconds
        slideDownDuration: .5, // Default Modal appear slide down effect in seconds
        slideUpDuration: .5, // Default Modal hiding slide up effect in seconds
        resizeDuration: .25, // Default resize duration seconds
        inactiveFade: true, // Fades Modal window on inactive state
        transitions: true, // Toggles transition effects. Transitions are enabled by default
        loadingString: "Please wait. Loading...", // Default loading string message
        closeString: "Close window", // Default title attribute for close window link
        closeValue: "&times;", // Default string for close link in the header
        params: {},
        method: 'get', // Default Ajax request method
        autoFocusing: true, // Toggles auto-focusing for form elements. Disable for long text pages.
        fixedLocation: true  // Toggles whether the Modal appears fixed in the window or scrolls with the page
    },
    _options: new Object,

    setOptions: function(options) {
        Object.extend(this.options, options || {});
    },

    _init: function(options) {
        // Setting up original options with default options
        Object.extend(this._options, this.options);
        this.setOptions(options);

        //Create the overlay
        this.Modaloverlay = new Element("div", { id: "Overlay", opacity: "0" });

        //Create DOm for the window
        this.Modalwindow = new Element("div", {id: this.options.id, 'class': this.options.className, style: "display: none"}).update(
                this.Modalframe = new Element("div", {id: "Modal_frame"}).update(
                        this.Modalheader = new Element("div", {id: "Modal_header"}).update(
                                this.Modalcaption = new Element("div", {id: "Modal_caption"})
                                )
                        )
                );
        this.Modalclose = new Element("a", {id: "Modal_close", title: this.options.closeString, href: "#"}).update("<span>" + this.options.closeValue + "</span>");
        this.Modalheader.insert({'bottom':this.Modalclose});

        this.Modalcontent = new Element("div", {id: "Modal_content"}).update(
                this.Modalloading = new Element("div", {id: "Modal_loading"}).update(this.options.loadingString)
                );
        this.Modalframe.insert({'bottom':this.Modalcontent});

        // Inserting into DOM. Will inject into body as topmost element.
        // Be sure to set padding and marging to null via CSS for both body.
        var injectToEl = $(document.body);
        injectToEl.insert({'top':this.Modalwindow});
        injectToEl.insert({'top':this.Modaloverlay});

        // Initial scrolling position of the window. To be used for remove scrolling effect during Modal appearing
        this.initScrollX = window.pageXOffset || document.body.scrollLeft || document.documentElement.scrollLeft;
        this.initScrollY = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;

        //Adding event observers
        this.hideObserver = this._hide.bindAsEventListener(this);
        this.kbdObserver = this._kbdHandler.bindAsEventListener(this);
        this._initObservers();

        this.initialized = true; // Mark as initialized
    },

    show: function(content, options) {
        if (!this.initialized) this._init(options); // Check for is already initialized

        this.content = content;
        this.setOptions(options);

        if (this.options.title) // Updating title of the Modal
            $(this.Modalcaption).update(this.options.title);
        else { // If title isn't given, the header will not displayed
            $(this.Modalheader).hide();
            $(this.Modalcaption).hide();
        }

        if (this.Modalwindow.style.display == "none") { // First modal box appearing
            this._appear();
            this.event("onShow"); // Passing onShow callback
        }
        else { // If Modal already on the screen, update it
            this._update();
            this.event("onUpdate"); // Passing onUpdate callback
        }
        return this;
    },

    hide: function(options) { // External hide method to use from external HTML and JS
        if (this.initialized) {
            window.clearInterval(this.resizeInterval);
            // Reading for options/callbacks except if event given as a pararmeter
            if (options && typeof options.element != 'function') Object.extend(this.options, options);
            // Passing beforeHide callback
            this.event("beforeHide");
            if (this.options.transitions)
                Effect.SlideUp(this.Modalwindow, { duration: this.options.slideUpDuration, transition: Effect.Transitions.sinoidal, afterFinish: this._deinit.bind(this) });
            else {
                $(this.Modalwindow).hide();
                this._deinit();
            }
        } else throw("Modal is not initialized.");
    },

    _hide: function(event) { // Internal hide method to use with overlay and close link
        event.stop(); // Stop event propaganation for link elements
        /* Then clicked on overlay we'll check the option and in case of overlayClose == false we'll break hiding execution [Fix for #139] */
        if (event.element().id == 'Modal_overlay' && !this.options.overlayClose) return false;
        this.hide();
    },

    alert: function(message) {
        var html = '<div class="Modal_alert"><p>' + message + '</p><input type="button" onclick="Powered.Modal.hide()" value="OK" /></div>';
        Powered.Modal.show(html, {title: 'Alert: ' + document.title, width: 300});
    },

    _appear: function() { // First appearing of Modal
        if (Prototype.Browser.IE && !navigator.appVersion.match(/\b7.0\b/)) { // Preparing IE 6 for showing Modal
            window.scrollTo(0, 0);
            this._prepareIE("100%", "hidden");
        }
        this._setWidth();
        this._setPosition();
        if (this.options.transitions) {
            $(this.Modaloverlay).setStyle({opacity: 0});
            new Effect.Fade(this.Modaloverlay, {
                from: 0,
                to: this.options.overlayOpacity,
                duration: this.options.overlayDuration,
                afterFinish: function() {
                    new Effect.SlideDown(this.Modalwindow, {
                        duration: this.options.slideDownDuration,
                        transition: Effect.Transitions.sinoidal,
                        afterFinish: function() {
                            this._setPosition();
                            this.loadContent();
                        }.bind(this)
                    });
                }.bind(this)
            });
        } else {
            $(this.Modaloverlay).setStyle({opacity: this.options.overlayOpacity});
            $(this.Modalwindow).show();
            this._setPosition();
            this.loadContent();
        }
        this._setWidthAndPosition = this._setWidthAndPosition.bindAsEventListener(this);
        Event.observe(window, "resize", this._setWidthAndPosition);
        if (this.options.fixedLocation) {
            Event.observe(window, "scroll", this._setWidthAndPosition);
        }
    },

    resize: function(byWidth, byHeight, options) { // Change size of Modal without loading content
        var wHeight = $(this.Modalwindow).getHeight();
        var wWidth = $(this.Modalwindow).getWidth();
        var hHeight = $(this.Modalheader).getHeight();
        var cHeight = $(this.Modalcontent).getHeight();
        var newHeight = ((wHeight - hHeight + byHeight) < cHeight) ? (cHeight + hHeight - wHeight) : byHeight;
        if (options) this.setOptions(options); // Passing callbacks
        if (this.options.transitions) {
            new Effect.ScaleBy(this.Modalwindow, byWidth, newHeight, {
                duration: this.options.resizeDuration,
                afterFinish: function() {
                    this.event("_afterResize"); // Passing internal callback
                    this.event("afterResize"); // Passing callback
                }.bind(this)
            });
        } else {
            this.Modalwindow.setStyle({width: wWidth + byWidth + "px", height: wHeight + newHeight + "px"});
            setTimeout(function() {
                this.event("_afterResize"); // Passing internal callback
                this.event("afterResize"); // Passing callback
            }.bind(this), 1);

        }

    },

    resizeToContent: function(options) {

        // Resizes the Modal window to the actual content height.
        // This might be useful to resize Modal after some content modifications which were changed ccontent height.

        var byHeight = this.options.height - this.Modalwindow.offsetHeight;
        if (byHeight != 0) {
            if (options) this.setOptions(options); // Passing callbacks
            Powered.Modal.resize(0, byHeight);
        }
    },

    resizeToInclude: function(element, options) {

        // Resizes the Modal window to the camulative height of element. Calculations are using CSS properties for margins and border.
        // This method might be useful to resize Modal before including or updating content.

        var el = $(element);
        var elHeight = el.getHeight() + parseInt(el.getStyle('margin-top')) + parseInt(el.getStyle('margin-bottom')) + parseInt(el.getStyle('border-top-width')) + parseInt(el.getStyle('border-bottom-width'));
        if (elHeight > 0) {
            if (options) this.setOptions(options); // Passing callbacks
            Powered.Modal.resize(0, elHeight);
        }
    },

    _update: function() { // Updating Modal in case of wizards
        $(this.Modalcontent).update("");
        this.Modalcontent.appendChild(this.Modalloading);
        $(this.Modalloading).update(this.options.loadingString);
        this.currentDims = [this.Modalwindow.offsetWidth, this.Modalwindow.offsetHeight];
        Powered.Modal.resize((this.options.width - this.currentDims[0]), (this.options.height - this.currentDims[1]), {_afterResize: this._loadAfterResize.bind(this) });
    },

    loadContent: function () {
        if (this.event("beforeLoad") != false) { // If callback passed false, skip loading of the content
            if (typeof this.content == 'string') {
                var htmlRegExp = new RegExp(/<\/?[^>]+>/gi);
                if (htmlRegExp.test(this.content)) { // Plain HTML given as a parameter
                    this._insertContent(this.content.stripScripts());
                    this._putContent(function() {
                        this.content.extractScripts().map(function(script) {
                            return eval(script.replace("<!--", "").replace("// -->", ""));
                        }.bind(window));
                    }.bind(this));
                } else // URL given as a parameter. We'll request it via Ajax
                    new Ajax.Request(this.content, { method: this.options.method.toLowerCase(), parameters: this.options.params,
                        onSuccess: function(transport) {
                            var response = new String(transport.responseText);
                            this._insertContent(transport.responseText.stripScripts());
                            this._putContent(function() {
                                response.extractScripts().map(function(script) {
                                    return eval(script.replace("<!--", "").replace("// -->", ""));
                                }.bind(window));
                            });
                        }.bind(this),
                        onException: function(instance, exception) {
                            Powered.Modal.hide();
                            throw('Modal Loading Error: ' + exception);
                        }
                    });

            } else if (typeof this.content == 'object') {// HTML Object is given
                this._insertContent(this.content);
                this._putContent();
            } else {
                Powered.Modal.hide();
                throw('Modal Parameters Error: Please specify correct URL or HTML element (plain HTML or object)');
            }
        }
    },

    _insertContent: function(content) {
        $(this.Modalcontent).hide().update("");
        if (typeof content == 'string') {
            setTimeout(function() { // Hack to disable content flickering in Firefox
                this.Modalcontent.update(content);
            }.bind(this), 1);
        } else if (typeof content == 'object') { // HTML Object is given
            var _htmlObj = content.cloneNode(true); // If node already a part of DOM we'll clone it
            // If clonable element has ID attribute defined, modifying it to prevent duplicates
            if (content.id) content.id = "Modal_" + content.id;
            /* Add prefix for IDs on all elements inside the DOM node */
            $(content).select('*[id]').each(function(el) {
                el.id = "Modal_" + el.id;
            });
            this.Modalcontent.appendChild(_htmlObj);
            this.Modalcontent.down().show(); // Toggle visibility for hidden nodes
            if (Prototype.Browser.IE) // Toggling back visibility for hidden selects in IE
                $$("#Modal_content select").invoke('setStyle', {'visibility': ''});
        }
    },

    _putContent: function(callback) {
        // Prepare and resize modal box for content
        if (this.options.height == this._options.height) {
            setTimeout(function() { // MSIE sometimes doesn't display content correctly
                Powered.Modal.resize(0, $(this.Modalcontent).getHeight() - $(this.Modalwindow).getHeight() + $(this.Modalheader).getHeight(), {
                    afterResize: function() {
                        this.Modalcontent.show().makePositioned();
                        this.focusableElements = this._findFocusableElements();
                        this._setFocus(); // Setting focus on first 'focusable' element in content (input, select, textarea, link or button)
                        setTimeout(function() { // MSIE fix
                            if (callback != undefined)
                                callback(); // Executing internal JS from loaded content
                            this.event("afterLoad"); // Passing callback
                        }.bind(this), 1);
                    }.bind(this)
                });
            }.bind(this), 1);
        } else { // Height is defined. Creating a scrollable window
            this._setWidth();
            this.Modalcontent.setStyle({overflow: 'auto', height: $(this.Modalwindow).getHeight() - $(this.Modalheader).getHeight() - 13 + 'px'});
            this.Modalcontent.show();
            this.focusableElements = this._findFocusableElements();
            this._setFocus(); // Setting focus on first 'focusable' element in content (input, select, textarea, link or button)
            setTimeout(function() { // MSIE fix
                if (callback != undefined)
                    callback(); // Executing internal JS from loaded content
                this.event("afterLoad"); // Passing callback
            }.bind(this), 1);
        }
    },

    activate: function(options) {
        this.setOptions(options);
        this.active = true;
        $(this.Modalclose).observe("click", this.hideObserver);
        if (this.options.overlayClose)
            $(this.Modaloverlay).observe("click", this.hideObserver);
        $(this.Modalclose).show();
        if (this.options.transitions && this.options.inactiveFade)
            new Effect.Appear(this.Modalwindow, {duration: this.options.slideUpDuration});
    },

    deactivate: function(options) {
        this.setOptions(options);
        this.active = false;
        $(this.Modalclose).stopObserving("click", this.hideObserver);
        if (this.options.overlayClose)
            $(this.Modaloverlay).stopObserving("click", this.hideObserver);
        $(this.Modalclose).hide();
        if (this.options.transitions && this.options.inactiveFade)
            new Effect.Fade(this.Modalwindow, {duration: this.options.slideUpDuration, to: .75});
    },

    _initObservers: function() {
        $(this.Modalclose).observe("click", this.hideObserver);
        if (this.options.overlayClose)
            $(this.Modaloverlay).observe("click", this.hideObserver);
        if (Prototype.Browser.IE)
            Event.observe(document, "keydown", this.kbdObserver);
        else
            Event.observe(document, "keypress", this.kbdObserver);
    },

    _removeObservers: function() {
        $(this.Modalclose).stopObserving("click", this.hideObserver);
        if (this.options.overlayClose)
            $(this.Modaloverlay).stopObserving("click", this.hideObserver);
        if (Prototype.Browser.IE)
            Event.stopObserving(document, "keydown", this.kbdObserver);
        else
            Event.stopObserving(document, "keypress", this.kbdObserver);
    },

    _loadAfterResize: function() {
        this._setWidth();
        this._setPosition();
        this.loadContent();
    },

    _setFocus: function() {
        /* Setting focus to the first 'focusable' element which is one with tabindex = 1 or the first in the form loaded. */
        if (this.focusableElements.length > 0 && this.options.autoFocusing == true) {
            var firstEl = this.focusableElements.find(function (el) {
                return el.tabIndex == 1;
            }) || this.focusableElements.first();
            this.currFocused = this.focusableElements.toArray().indexOf(firstEl);
            firstEl.focus(); // Focus on first focusable element except close button
        } else if ($(this.Modalclose).visible()) {
            try {
                $(this.Modalclose).focus(); // If no focusable elements exist focus on close button
            } catch(e) {
              //suppress IE focus error
            }
        }
    },

    _findFocusableElements: function() { // Collect form elements or links from Modal content
        this.Modalcontent.select('input:not([type~=hidden]), select, textarea, button, a[href]').invoke('addClassName', 'Modal_focusable');
        return this.Modalcontent.select('.Modal_focusable');
    },

    _kbdHandler: function(event) {
        var node = event.element();
        switch (event.keyCode) {
            case Event.KEY_TAB:
                event.stop();

            /* Switching currFocused to the element which was focused by mouse instead of TAB-key. Fix for #134 */
                if (node != this.focusableElements[this.currFocused])
                    this.currFocused = this.focusableElements.toArray().indexOf(node);

                if (!event.shiftKey) { //Focusing in direct order
                    if (this.currFocused == this.focusableElements.length - 1) {
                        this.focusableElements.first().focus();
                        this.currFocused = 0;
                    } else {
                        this.currFocused++;
                        this.focusableElements[this.currFocused].focus();
                    }
                } else { // Shift key is pressed. Focusing in reverse order
                    if (this.currFocused == 0) {
                        this.focusableElements.last().focus();
                        this.currFocused = this.focusableElements.length - 1;
                    } else {
                        this.currFocused--;
                        this.focusableElements[this.currFocused].focus();
                    }
                }
                break;
            case Event.KEY_ESC:
                if (this.active) this._hide(event);
                break;
            case 32:
                this._preventScroll(event);
                break;
            case 0: // For Gecko browsers compatibility
                if (event.which == 32) this._preventScroll(event);
                break;
            case Event.KEY_UP:
            case Event.KEY_DOWN:
            case Event.KEY_PAGEDOWN:
            case Event.KEY_PAGEUP:
            case Event.KEY_HOME:
            case Event.KEY_END:
            // Safari operates in slightly different way. This realization is still buggy in Safari.
                if (Prototype.Browser.WebKit && !["textarea", "select"].include(node.tagName.toLowerCase()))
                    event.stop();
                else if ((node.tagName.toLowerCase() == "input" && ["submit", "button"].include(node.type)) || (node.tagName.toLowerCase() == "a"))
                    event.stop();
                break;
        }
    },

    _preventScroll: function(event) { // Disabling scrolling by "space" key
        if (!["input", "textarea", "select", "button"].include(event.element().tagName.toLowerCase()))
            event.stop();
    },

    _deinit: function()
    {
        this._removeObservers();
        Event.stopObserving(window, "resize", this._setWidthAndPosition);
        if (this.options.transitions) {
            Effect.toggle(this.Modaloverlay, 'appear', {duration: this.options.overlayDuration, afterFinish: this._removeElements.bind(this) });
        } else {
            this.Modaloverlay.hide();
            this._removeElements();
        }
        $(this.Modalcontent).setStyle({overflow: '', height: ''});
    },

    _removeElements: function () {
        $(this.Modaloverlay).remove();
        $(this.Modalwindow).remove();
        if (Prototype.Browser.IE && !navigator.appVersion.match(/\b7.0\b/)) {
            this._prepareIE("", ""); // If set to auto MSIE will show horizontal scrolling
            window.scrollTo(this.initScrollX, this.initScrollY);
        }

        /* Replacing prefixes 'Modal_' in IDs for the original content */
        if (typeof this.content == 'object') {
            if (this.content.id && this.content.id.match(/Modal_/)) {
                this.content.id = this.content.id.replace(/Modal_/, "");
            }
            this.content.select('*[id]').each(function(el) {
                el.id = el.id.replace(/Modal_/, "");
            });
        }
        /* Initialized will be set to false */
        this.initialized = false;
        this.event("afterHide"); // Passing afterHide callback
        this.setOptions(this._options); //Settings options object into intial state
    },

    _setWidth: function () { //Set size
        $(this.Modalwindow).setStyle({width: this.options.width + "px", height: this.options.height + "px"});
    },

    _setPosition: function () {
        $(this.Modalwindow).setStyle({left: Math.round((Element.getWidth(document.body) - Element.getWidth(this.Modalwindow)) / 2) + "px"});
        $(this.Modalwindow).setStyle({top: Powered.Graphics.getScrollXY()[1] + 100 + "px"});
    },

    _setWidthAndPosition: function () {
        $(this.Modalwindow).setStyle({width: this.options.width + "px"});
        this._setPosition();
    },

    _getScrollTop: function () { //From: http://www.quirksmode.org/js/doctypes.html
        var theTop;
        if (document.documentElement && document.documentElement.scrollTop)
            theTop = document.documentElement.scrollTop;
        else if (document.body)
            theTop = document.body.scrollTop;
        return theTop;
    },
    _prepareIE: function(height, overflow) {
        $$('html, body').invoke('setStyle', {width: height, height: height, overflow: overflow}); // IE requires width and height set to 100% and overflow hidden
        $$("select").invoke('setStyle', {'visibility': overflow}); // Toggle visibility for all selects in the common document
    },
    event: function(eventName) {
        if (this.options[eventName]) {
            var returnValue = this.options[eventName](); // Executing callback
            this.options[eventName] = null; // Removing callback after execution
            if (returnValue != undefined)
                return returnValue;
            else
                return true;
        }
        return true;
    }
};

Object.extend(Powered.Modal, Powered.Modal.Methods);

if (Powered.Modal.overrideAlert) window.alert = Powered.Modal.alert;

Effect.ScaleBy = Class.create();
Object.extend(Object.extend(Effect.ScaleBy.prototype, Effect.Base.prototype), {
    initialize: function(element, byWidth, byHeight, options) {
        this.element = $(element)
        var options = Object.extend({
            scaleFromTop: true,
            scaleMode: 'box',        // 'box' or 'contents' or {} with provided values
            scaleByWidth: byWidth,
            scaleByHeight: byHeight
        }, arguments[3] || {});
        this.start(options);
    },
    setup: function() {
        this.elementPositioning = this.element.getStyle('position');

        this.originalTop = this.element.offsetTop;
        this.originalLeft = this.element.offsetLeft;

        this.dims = null;
        if (this.options.scaleMode == 'box')
            this.dims = [this.element.offsetHeight, this.element.offsetWidth];
        if (/^content/.test(this.options.scaleMode))
            this.dims = [this.element.scrollHeight, this.element.scrollWidth];
        if (!this.dims)
            this.dims = [this.options.scaleMode.originalHeight,
                this.options.scaleMode.originalWidth];

        this.deltaY = this.options.scaleByHeight;
        this.deltaX = this.options.scaleByWidth;
    },
    update: function(position) {
        var currentHeight = this.dims[0] + (this.deltaY * position);
        var currentWidth = this.dims[1] + (this.deltaX * position);

        currentHeight = (currentHeight > 0) ? currentHeight : 0;
        currentWidth = (currentWidth > 0) ? currentWidth : 0;

        this.setDimensions(currentHeight, currentWidth);
    },

    setDimensions: function(height, width) {
        var d = {};
        d.width = width + 'px';
        d.height = height + 'px';

        var topd = Math.round((height - this.dims[0]) / 2);
        var leftd = Math.round((width - this.dims[1]) / 2);
        if (this.elementPositioning == 'absolute' || this.elementPositioning == 'fixed') {
            if (!this.options.scaleFromTop) d.top = this.originalTop - topd + 'px';
            d.left = this.originalLeft - leftd + 'px';
        } else {
            if (!this.options.scaleFromTop) d.top = -topd + 'px';
            d.left = -leftd + 'px';
        }
        this.element.setStyle(d);
    }
});