/*
Ursprungligen skriven av Andreas G
Martin A tar sig friheten att skala bort kod som vi inte har behöv av, så att sidan förrhoppningsvis skall parsas igenom snabbare.
Hade varit bra om både informationen, och beskrivningen kunde hämtas i samma ajax- anropp. Detta var svårare att modiefiera än
vad det kunde tyckas, med nuvarande underlag, så detta lades på is...
*/

var protoprod_autoshowstockcode = '';  // Added by Martin A

if (typeof Effect == 'undefined')
    throw ("protoprod.js requires including script.aculo.us' effects.js library!");

var protoprod = Class.create();

protoprod.prototype = {
    showAccordion: null,
    currentAccordion: null,
    duration: null,
    effects: [],
    animating: false,
    AlreadyActivated: [], //Added by Trey
    _options: new Object,

    initialize: function(container, options) {
        this.contain = $(container);
        this.options = Object.extend({
            resizeSpeed: 8,
            resizeDuration: .25, // Default resize duration seconds
            appearDuration: .25, // Default resize duration seconds
            transitions: false, // Toggles transition effects. Transitions are enabled by default
            method: 'get', // Default Ajax request method
            autoFocusing: false,
            params: {},
            infoUrl: '/AjaxPages/ProductInformation.aspx', // Changed by Martin A
            width: 746, // Default width in px
            height: 60, // Default height in px
            loadingString: 'Var god vänta. Laddar...', // Default loading string message
            classNames: {
                toggle: 'storecontain',
                toggleActive: 'accordion_toggle_active',
                content: 'accordion_content'
            },
            defaultSize: {
                height: null,
                width: null
            },
            direction: 'vertical',
            onEvent: 'click',
            stockcode: '', // Added by Martin A
            warehouse: '', // Added by Martin A
            scrollIntoViewElement: null, // Added by Martin A
            onActivate: null, //Added by Trey:  CallBack Function called when Tab is activated, sends elemet.
            RepeatActivate: {} //Added by Trey
        }, options || {});

        Object.extend(this._options, this.options);

        this.isDescFieldOpen = false;

        this.currentCapItem = null;
        this.extraVisible = false;
        this.warehouse = '01';

        this.PPclose = new Element("a", { 'class': 'ppclose', href: "#close" });
        this.PPindex = new Element("div", { id: "ppindex" });
        this.PPnav = new Element("ul", { id: "ppnav" });
        this.PPinfo = new Element("li", { id: "ppinfo" }).update(new Element("a", { href: "#info" }));
        this.PPtillbehor = new Element("li", { id: "pptillbehor", style: "display: none" }).update(new Element("a", { href: "#tillbehor" }));

        this.PTXwindow = new Element("div", { id: "PTX_window", style: "display: block" }).update(
			this.PTXframe = new Element("div", { id: "PTX_frame" })
		);

        this.PTXbottom = new Element("div", { id: "PTX_bottom" });
        this.PTXcontent = new Element("div", { id: "PTX_content" });
        this.PTXloading = new Element("div", { id: "PTX_loading" }).update(this.options.loadingString);


        this.PPnav.insert({ 'bottom': this.PPinfo });
        this.PPnav.insert({ 'bottom': this.PPtillbehor });
        this.PPindex.insert({ 'bottom': this.PPnav });

        this.PTXframe.insert({ 'bottom': this.PTXbottom });
        this.PTXframe.insert({ 'bottom': this.PTXcontent });
        this.PTXframe.insert({ 'top': this.PTXloading });

        this.PTIclose = new Element("a", { 'class': 'ppclose2', href: "#close" });

        Event.observe(this.PTIclose, this.options.onEvent, this.toogleDescField.bind(this), false);
        Event.observe(this.PPclose, this.options.onEvent, this.hide.bind(this), false);
        Event.observe(this.PPinfo, this.options.onEvent, this.showInfo.bind(this), false);
        Event.observe(this.PPtillbehor, this.options.onEvent, this.showTillbehor.bind(this), false);

        //if ($(container)) {
        //var capshopitems = $$('#' + container + ' .' + this.options.classNames.toggle);
        //capshopitems.each(function(capitem) {

        // Binder eventen direkt på knapparna istället...
        //        //var tt = $(capitem.down('a.greeninfo'));
        //        //Event.observe(tt, this.options.onEvent, this.activate.bind(this, capitem), false);

        //        if ($(capitem.down('a.orangeshop'))) {
        //            var adder = $(capitem.down('a.orangeshop'));
        //            Event.observe(adder, this.options.onEvent, this.addShop.bind(this, capitem), false);
        //        }

        // Blir inga mellanrum i IE, om vi gör såhär...
        //($(capitem.down('.storeexpand'))).hide();
        //} .bind(this));
        //}

        if (protoprod_autoshowstockcode != '') {
            this.showExtraProduct(protoprod_autoshowstockcode);
            protoprod_autoshowstockcode = '';
        }
    },

    setOptions: function(options) {
        Object.extend(this.options, options || {});
    },


    hide: function() {

        // Deklarerar variablerna
        var StoreExpandElement = null;
        var StoreItemElement = null;

        // kontrollerar vilket objekt som skall stängas (Extra- infon överst, eller den vanliga beskrivningsrutan)
        if (this.currentCapItem != null) {
            StoreExpandElement = $(this.currentCapItem.down('.storeexpand'));
            StoreItemElement = $(this.currentCapItem.down('.storeitem'));
        }
        if (this.extraVisible) {
            StoreExpandElement = $('ProductExtraExpand');
            if ($('content_top')) $('content_top').scrollIntoView(true);
        }

        // Minimerar beskrivningstexten, om den är öppen
        if (this.isDescFieldOpen) this.toogleDescField();

        // Om man minimerar en vanlig beskrivning, så måste vi också öppna den grundläggande beskrivningsrutan
        if (StoreItemElement != null) StoreItemElement.show();

        // Minimerar beskrivningen, om den finns
        if (StoreExpandElement != null) {
            StoreExpandElement.hide();
            this.PTXcontent.hide().update("");
        }

        this.PPtillbehor.style.display = 'none';

        this.currentCapItem = null;
        this.extraVisible = false;
        this.options.autoFocusing = false;

        if (scroller2 != null) scroller2.updateResize();
    },

    activate: function(capitem, warehouse) {

        this.hide(); // Döljer en eventuell tidigare produktinformation

        if (PageInfoDisplay != null) PageInfoDisplay.close();

        this.stockcode = $(capitem.down('div.storedesc').down('a.blacklink')).href.split("#")[1] ;
        this.warehouse = warehouse;

        ($(capitem.down('.storeitem'))).hide();

        var StoreExpandElement = $(capitem.down('.storeexpand'));
        StoreExpandElement.show();

        StoreExpandElement.insert({ 'top': this.PTXwindow });
        StoreExpandElement.insert({ 'top': this.PPindex });
        StoreExpandElement.insert({ 'top': this.PPclose });

        this.showInfo();

        this.currentCapItem = capitem;

        scrollIntoViewElement = StoreExpandElement;
        if (scroller2 != null) scroller2.updateScrollerFromView();
    },

    showExtraProduct: function(stockcode, warehouse) {

        this.hide(); // Döljer en eventuell tidigare produktinformation

        var StoreExtraExpandElement = $('ProductExtraExpand');
        if (PageInfoDisplay != null) PageInfoDisplay.close();

        StoreExtraExpandElement.show();

        this.stockcode = stockcode;
        this.warehouse = warehouse;

        StoreExtraExpandElement.insert({ 'top': this.PTXwindow });
        StoreExtraExpandElement.insert({ 'top': this.PPindex });
        StoreExtraExpandElement.insert({ 'top': this.PPclose });

        this.showInfo();

        this.extraVisible = true;

        if (scroller2 != null) scroller2.currentValue = 0;

        this.options.autoFocusing = true;

        scrollIntoViewElement = StoreExtraExpandElement;
        if (scroller2 != null) scroller2.updateScrollerFromView();
    },

    showInfo: function() {

        this.PTXframe.setStyle({ backgroundPosition: '-745px 0px' });

        this.PPinfo.addClassName('selected');
        this.PPtillbehor.removeClassName('selected');

        this.show('/AjaxPages/ProductInformation.aspx');

        this.checkAnyAccessories();
    },

    checkAnyAccessories: function() {
        var self = this;
        if (this.stockcode != '') {
            new Ajax.Request('/AjaxPages/ProductAccessories.aspx?id=' + this.stockcode + '&test=1', {
                method: 'post',
                onSuccess: function(transport) {
                    if (transport.responseText.startsWith("yes")) {
                        self.PPtillbehor.style.display = '';
                    } else {
                        self.PPtillbehor.style.display = 'none';
                    }
                }
            });
        }
    },

    showTillbehor: function() {
        $(this.PTXframe).setStyle({ backgroundPosition: '0px 0px' });

        this.PPinfo.removeClassName('selected');
        this.PPtillbehor.addClassName('selected');

        this.show('/AjaxPages/ProductAccessories.aspx');
    },

    show: function(content, options) {
        this.content = content;
        this.setOptions(options);

        this._update();
        this.event("onUpdate"); // Passing onShow callback
    },

    _update: function() {
        this.PTXloading.show().update(this.options.loadingString);
        this.loadContent();
    },

    loadContent: function() {
        var cacheBuster = new Date().getTime();
        var pars = '&cacheBuster=' + cacheBuster + '&id=' + this.stockcode + '&warehouse=' + this.warehouse;

        if (typeof this.content == 'string') {
            this.requester = new Ajax.Request(this.content, { method: this.options.method.toLowerCase(), parameters: pars,
                onSuccess: function(transport) {
                    this._insertContent(transport.responseText.stripScripts(), function() { });
                } .bind(this),
                onException: function(instance, exception) {
                    throw ('ProtoTabX Loading Error: ' + exception);
                }
            });
        } else {
            throw ('ProtoTabX Parameters Error: Please specify correct URL');
        }
    },

    _insertContent: function(content, callback) {
        this.PTXcontent.hide().update("");
        this.PTXcontent.update(content);

        this.PTXcontent.style.display = ''
        this.PTXcontent.down().style.display = ''

        this.PTXcontent.show();
        this.PTXcontent.down().show();

        this.PTXcontent.style.visibility = 'visible'
        this.PTXcontent.down().style.visibility = 'visible'

        this.PTXwindow.setStyle({ width: this.options.width + "px", height: this.options.height + "px" });

        this.resize((this.options.width - this.PTXwindow.getWidth()), this.PTXcontent.getHeight() - this.PTXwindow.getHeight(), {
            afterResize: function() {
                setTimeout(function() { // MSIE fix
                    this._putContent(callback);

                    // Lägger till MAXIMERA/MINIMERA- knapp ovanför Beskrivningsrutan
                    if ($('PTX_holder')) $('PTX_holder').insert({ 'bottom': this.PTIclose });

                    // Kopplar en miniskroller till beskrivningsrutan
                    if ($('PTI_frame')) {
                        this.miniscroller = new ProtoScrollBar($('PTI_frame'), {
                            classNames: {
                                psbcontainer: 'PSB_containermini',
                                psbbuttonup: 'PSB_buttonupmini',
                                psbbuttondown: 'PSB_buttondownmini',
                                psbtrack: 'PSB_trackmini',
                                psbhandle: 'PSB_handlemini'
                            },
                            //containerScroller: scroller2,
                            offseter: 20,
                            debug: false,
                            minifix: 20
                        });

                        if (this.miniscroller) this.miniscroller.updateResize();

                        if (this.PTXcontent.down('#capgallery')) {
                            var galleryItems = $('capgallery').select('.tumbgal');
                            if (galleryItems.length > 0) var gallery = new CaptechGallery(galleryItems, 'popupthumb', this.PTXcontent);
                        }

                        if (scrollIntoViewElement != null) {
                            scrollIntoViewElement.scrollIntoView(false);
                            if (scroller2 != null) scroller2.updateScrollerFromView();
                        }

                        if (this.options.autoFocusing && $('tb' + this.stockcode)) {
                            var numField = $('tb' + this.stockcode);
                            numField.focus();
                            setTimeout(function() { // MSIE fix
                                numField.value = "1";
                                numField.select();
                            }, 100);
                        }

                        if (scroller2 != null) { setTimeout(function() { scroller2.updateScrollerFromView(); }, 1); }

                        // Om "Vi rekomenterar" rutan visas, så blir det grafiskt fel om artikelbenämningen är för lång.
                        // Detta löser problemet att texten flyter ihop med den rutan.
                        var piDataDiv = this.PTXcontent.down(0).down('div.pidata')
                        if ($(piDataDiv.down('div.pi_rekom').down('div.rekrub'))) {
                            piDataDiv.down('div.pi_prodname').style.width = '410px';
                        }
                    }
                } .bind(this), 50);
            } .bind(this)
        });

    },

    _putContent: function(callback) {
        this.PTXloading.hide();

        this.PTXcontent.show();

        if (callback != undefined) callback(); // Executing internal JS from loaded content
        this.event("afterLoad"); // Passing callback
    },

    resize: function(byWidth, byHeight, options) { // Change size of PTX without loading content
        var wHeight = this.PTXwindow.getHeight();
        var wWidth = this.PTXwindow.getWidth();
        var hHeight = 0;
        var cHeight = this.PTXcontent.getHeight();
        //var newHeight = ((wHeight - hHeight + byHeight) < cHeight) ? (cHeight + hHeight) : (wHeight + byHeight);
        var newHeight = wHeight + byHeight;
        var newWidth = wWidth + byWidth;
        if (options) this.setOptions(options); // Passing callbacks
        if (this.options.transitions) {
            new Effect.Morph((this.PTXwindow), {
                style: "width:" + newWidth + "px; height:" + newHeight + "px",
                duration: this.options.resizeDuration,
                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.PTXwindow.setStyle({ width: newWidth + "px", height: newHeight + "px" });
            this.PTXwindow.fire("widget:frob");
            setTimeout(function() {
                this.event("_afterResize"); // Passing internal callback
                this.event("afterResize"); // Passing callback
            } .bind(this), 1);
        }

    },

    toogleDescField: function() {
        if (this.isDescFieldOpen) {
            this.isDescFieldOpen = false;
            $(this.PTIclose).setStyle({ backgroundPosition: '0px 0px' });
            if ($('PTX_holder')) {
                new Effect.Morph($('PTX_holder'),
                {
                    style: 'top: 260px; height: 145px;',
                    afterUpdate: function() { this.miniscroller.updateResize(); if ($('PTI_frame')) { $('PTI_frame').style.height = $('PTX_holder').style.height; } } .bind(this)
                });
            }
        }
        else {
            this.isDescFieldOpen = true;
            $(this.PTIclose).setStyle({ backgroundPosition: '0px -25px' });
            if ($('PTX_holder')) {
                new Effect.Morph($('PTX_holder'),
                {
                    style: 'top: 30px; height: 375px;',
                    afterUpdate: function() { this.miniscroller.updateResize(); if ($('PTI_frame')) { $('PTI_frame').style.height = $('PTX_holder').style.height; } } .bind(this)
                });
            }
        }

    },

    addShop: function(capitem, warehouse) {
        var numitems = $(capitem.down('input'));
        var stockcode = $(capitem.down('a.orangeshop')).href.split("#")[1];
        if (warehouse == null) warehouse = "01";

        ProtoShop.addShopItem(stockcode, numitems.value, warehouse);
    },

    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;
    }

}
