/*
PageInfo Class handles the pageinfo / pageAds that is displayed when user clicks
on the menus heads or visiting mina sidor
*/


if (typeof Effect == 'undefined')
    throw ("pageinfo.js requires including script.aculo.us' effects.js library!");

var PageInfo = Class.create();
PageInfo.prototype = {

    _options: new Object,

    initialize: function(options) {
        this.options = Object.extend({
            resizeDuration: .25, // Default resize duration seconds
            width: 745, // Default width in px
            height: 90, // Default height in px
            loadingString: 'Var god vänta. Laddar...', // Default loading string message
            resizeDuration: .25, // Default resize duration seconds
            appearDuration: .25, // Default resize duration seconds
            transitions: true, // Toggles transition effects. Transitions are enabled by default // INte längre, eftersom det skapar uppdateringsproblem...
            method: 'get', // Default Ajax request method
            autoFocusing: true,
            params: {}
        }, options || {});

        Object.extend(this._options, this.options);
        this.lastUrl = ""; // Added by Martin A
        this.firstTimeOpen = true;
        this.animating = false;
        this.isAdsOpen = false;
        this.PageInfoHolder = new Element("div", { id: "PageInfo_holder" });
        this.PageInfoHeader = new Element("div", { id: "PageInfo_header" }).update(new Element("p", { 'class': 'small' }).update("CAPTECH REKOMMENDERAR"));
        this.PageInfoResize = new Element("div", { id: "PageInfo_resize" }).update("Minimera [-]");

        this.PageInfoHolder.insert({ 'bottom': this.PageInfoHeader });
        this.PageInfoHolder.insert({ 'bottom': this.PageInfoResize });

        this.PageInfoWindow = new Element("div", { id: "PageInfo_window", style: "display: block" }).update(
			this.PageInfoFrame = new Element("div", { id: "PageInfo_frame" })
		);

        this.PageInfoContent = new Element("div", { id: "PageInfo_content" });
        this.PageInfoLoading = new Element("div", { id: "PageInfo_loading" }).update(this.options.loadingString);


        this.PageInfoFrame.insert({ 'top': this.PageInfoContent });
        this.PageInfoFrame.insert({ 'top': this.PageInfoLoading });


        this.bindClick = this.tooglePageInfo.bindAsEventListener(this);
        Event.observe(this.PageInfoHolder, 'click', this.bindClick);

    },

    open: function(url) {
        if (url == this.lastUrl) {
            if (!this.isAdsOpen) this.tooglePageInfo();
        } else {
            this.show(url);
        }
        this.lastUrl = url;
    },

    close: function() {

        if (this.isAdsOpen) {
            this.isAdsOpen = false;
            this.PageInfoResize.update("Maximera [+]");

            var resizeOption = {
                style: {
                    height: 0 + 'px'
                },
                afterUpdate: function() {
                    this.PageInfoWindow.fire("widget:frob");
                } .bind(this)

            };

            new Effect.Morph(this.PageInfoWindow, resizeOption);

        }
    },

    tooglePageInfo: function(e) {
        if (this.animating) {
            return false;
        }
        var theHeight = 0;

        if (!this.isAdsOpen) {
            this.isAdsOpen = true;
            theHeight = this.realSize;
            this.PageInfoResize.update("Minimera [-]");
        }
        else {
            this.isAdsOpen = false;
            this.PageInfoResize.update("Maximera [+]");
        }


        var resizeOption = {
            style: {
                height: theHeight + 'px'
            },
            afterUpdate: function() {
                this.PageInfoWindow.fire("widget:frob");
            } .bind(this)

        };

        new Effect.Morph(this.PageInfoWindow, resizeOption);

    },

    setOptions: function(options) {
        Object.extend(this.options, options || {});
    },
    _setWidth: function() { //Set size
        $(this.PageInfoWindow).setStyle({ width: this.options.width + "px", height: this.options.height + "px" });
    },

    show: function(content, options) {
        this.isAdsOpen = true;
        this.content = content;
        this.setOptions(options);
        this._update();
        this.event("onUpdate"); // Passing onShow callback
    },

    _update: function() { // Updating PTX in case of wizards
        this.PageInfoLoading.show().update(this.options.loadingString);
        this.loadContent();
    },
    _insertContent: function(content, callback) {

        var injectToEl = $('pageinfo');
        if (content.length > 0) {
            if ($('content_top')) $('content_top').scrollIntoView(true);
            if (!injectToEl.down()) {
                // Om pageinfo inte innehåller några element, lägg till placeholdern.
                injectToEl.insert({ 'top': this.PageInfoWindow });
                injectToEl.insert({ 'top': this.PageInfoHolder });
                this._setWidth();
            }
        }

        $(this.PageInfoContent).hide().update("");
        this.PageInfoContent.update(new Element("div", { style: "display: none" }).update(content)).down().show();

        var self = this;

        // Prepare and resize modal box for content
        if (this.options.height == this._options.height) {

            self.resize((this.options.width - $(this.PageInfoWindow).getWidth()), $(this.PageInfoContent).getHeight() - $(this.PageInfoWindow).getHeight(), {
                afterResize: function() {
                    setTimeout(function() { // MSIE fix
                        this._putContent(callback);
                    } .bind(this), 1);
                } .bind(this)
            });

        } else { // Height is defined. Creating a scrollable window
            this._setWidth();

            this.PageInfoContent.setStyle({ overflow: 'auto', height: $(this.PageInfoWindow).getHeight() - 13 + 'px' });
            setTimeout(function() { // MSIE fix
                this._putContent(callback);
            } .bind(this), 1);
        }
    },

    resize: function(byWidth, byHeight, options) { // Change size of PTX without loading content

        var wHeight = $(this.PageInfoWindow).getHeight();
        var wWidth = $(this.PageInfoWindow).getWidth();
        var hHeight = 0;
        var cHeight = $(this.PageInfoContent).getHeight();
        var newHeight = ((wHeight - hHeight + byHeight) < cHeight) ? (cHeight + hHeight) : (wHeight + byHeight);
        var newWidth = wWidth + byWidth;
        this.realSize = newHeight;
        if (options) this.setOptions(options); // Passing callbacks
        if (this.options.transitions) {
            new Effect.Morph(this.PageInfoWindow, {
                style: "width:" + newWidth + "px; height:" + newHeight + "px",
                duration: this.options.resizeDuration,
                fps: 30,
                beforeStart: function(fx) {
                    fx.element.setStyle({ overflow: "hidden" }); // Fix for MSIE 6 to resize correctly
                },
                afterUpdate: function(fx) {
                    fx.element.fire("widget:frob");
                } .bind(this),
                afterFinish: function(fx) {
                    fx.element.setStyle({ overflow: "visible" });
                    this.event("_afterResize"); // Passing internal callback
                    this.event("afterResize"); // Passing callback
                } .bind(this)
            });
        } else {
            this.PageInfoWindow.setStyle({ width: newWidth + "px", height: newHeight + "px" });
            this.PageInfoWindow.fire("widget:frob");
            setTimeout(function() {
                this.event("_afterResize"); // Passing internal callback
                this.event("afterResize"); // Passing callback
            } .bind(this), 1);
        }

    },
    _putContent: function(callback) {

        this.PageInfoLoading.hide();

        this.PageInfoContent.appear({
            duration: +this.options.appearDuration,
            afterFinish: function(fx) {
                fx.element.show();
            } .bind(this)
        });

        //this.focusableElements = this._findFocusableElements();
        //this._setFocus(); // Setting focus on first 'focusable' element in content (input, select, textarea, link or button)
        if (callback != undefined)
            callback(); // Executing internal JS from loaded content
        this.event("afterLoad"); // Passing callback

    },


    loadContent: function() {

        var cacheBuster = new Date().getTime();

        var pars = 'cacheBuster=' + cacheBuster;

        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(), 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
                    this.requester = new Ajax.Request(this.content, { method: this.options.method.toLowerCase(), parameters: pars,
                        onSuccess: function(transport) {

                            var response = new String(transport.responseText);
                            this._insertContent(transport.responseText.stripScripts(), function() {
                                response.extractScripts().map(function(script) {
                                    return eval(script.replace("<!--", "").replace("// -->", ""));
                                } .bind(window));
                            });

                        } .bind(this),
                        onException: function(instance, exception) {
                            throw ('ProtoTabX Loading Error: ' + exception);
                        }
                    });

            } else if (typeof this.content == 'object') {// HTML Object is given
                this._insertContent(this.content);
            } else {
                throw ('ProtoTabX Parameters Error: Please specify correct URL or HTML element (plain HTML or object)');
            }
        }
    },


    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;
    }

}