/** 
 * @projectDescription	Die XHR- und Animations-Teile des iTravel-Hochzeitstisches.
 *
 * @author  Sascha Quasthoff s.quasthoff@assenmacher.net
 * @version 0.1
 * @date    04.04.2008
 */



/**
 * Create a new instance of Shape.
 *
 * @classDescription    Die Klasse baut alle Links in XHR-Aufrufe inkl. der Animation um.
 * @return {Shape}	Returns a new Shape.
 * @type {Object}
 * @constructor	
 */
XHR = Class.create (
{



    /**
    * Start der ganzen Verarbeitung
    * @constructor
    */
    initialize : function()
    {

        this.rebuild.initialize();

    },



    /**
     * 
     */    
    rebuild : {


        // Array mit den umgebauten Links
        _REBUILT : {},



        initialize : function()
        {

            this.add_gift();
            this.edit_link();
            this.move_up();
            this.move_down();
            this.delete_gift();
            this.donate();

        },



        /**
         * Alle Edit-Links (HTML-Klasse = 'edit_link')
         */
        edit_link : function()
        {

            $$('.edit_link').each((function (n) {
                if ( !n.hasClassName('rebuilt') && !n.hasClassName('edit_image') && !n.hasClassName('edit_orga') ) {
                    this._REBUILT[n.id] = new XHR_Layer(n);
                }
            }).bind(this));

        },



        /**
         * Alle "Verschenken"-Links im Frontend
         */
        donate : function()
        {

            $$('.donation_link a').each((function (n) {
                if ( !n.hasClassName('rebuilt') ) {
                    this._REBUILT[n.id] = new XHR_Layer(n);
                }
            }).bind(this));

        },



        /**
         * Alle Links zum Bewegen eines Geschenkpaketes um eine Position nach OBEN
         */
        move_up : function()
        {

            $$('a.move_gift_up').each((function (n) {
                var url = n.readAttribute('href');
                if ( typeof url == 'object' ) return;
                n.observe('click', (function (event) {
                    new Ajax.Request ( url, {
                        onSuccess: (function (t) {
                            if ( t.responseText.startsWith('success:') ) {
                                var ids = t.responseText.replace(/\r\n/, '').split(':');
                                new Effect.Parallel(
                                    [
                                        new Effect.Move( $('gift_'+ids[1]), { sync: true, x: 0, y: -215, mode: 'relative' }), 
                                        new Effect.Move( $('gift_'+ids[2]), { sync: true, x: 0, y: 215, mode: 'relative' })
                                    ],
                                    {
                                        duration: 1.0,
                                        afterFinish : (function () {
                                            new Ajax.Updater('content', iTravel.base_dir+'/verwaltung/'+iTravel.user_dir, {
                                                onComplete: (function () {
                                                    if ( !! _XHR ) _XHR.initialize();
                                                    if ( !!_UI ) _UI.initialize();
                                                }).bind(this)
                                            });
                                        }).bind(this)
                                    }
                                );
                            }
                        }).bind(this)
                    });
                    Event.stop(event);
                }).bind(this));
            }).bind(this));

        },



        /**
         * Alle Links zum Bewegen eines Geschenkpaketes um eine Position nach UNTEN werden umgebaut.
         */
        move_down : function()
        {

            $$('.move_gift_down').each((function (n) {
                var url = n.readAttribute('href');
                if ( typeof url == 'object' ) return;
                n.observe('click', (function (event) {
                    new Ajax.Request ( url, {
                        onSuccess: (function (t) {
                            if ( t.responseText.startsWith('success:') ) {
                                var ids = t.responseText.replace(/\r\n/, '').split(':');
                                new Effect.Parallel(
                                    [
                                        new Effect.Move( $('gift_'+ids[1]), { sync: true, x: 0, y: 215, mode: 'relative' }), 
                                        new Effect.Move( $('gift_'+ids[2]), { sync: true, x: 0, y: -215, mode: 'relative' })
                                    ],
                                    {
                                        duration: 1.0,
                                        afterFinish : (function () {
                                            new Ajax.Updater('content', iTravel.base_dir+'/verwaltung/'+iTravel.user_dir, {
                                                onComplete: (function () {
                                                    if ( !! _XHR ) _XHR.initialize();
                                                    if ( !!_UI ) _UI.initialize();
                                                }).bind(this)
                                            });
                                        }).bind(this)
                                    }
                                );
                            }
                        }).bind(this)
                    });
                    Event.stop(event);
                }).bind(this));
            }).bind(this));

        },



        /**
         * Die Links zum Löschen eines Geschenkpaketes werden umgebaut.
         */
        delete_gift : function()
        {

            $$('.delete_gift').each((function (n) {
                var url = n.readAttribute('href');
                n.observe('click', (function () {
                    new Ajax.Request ( url, {
                        onSuccess: (function (t) {
                            if ( t.responseText.startsWith('success:') ) {
                                new Effect.BlindUp ( n.up('ul').up('li'), {
                                    duration: 1,
                                    afterFinish: (function (transport) {
                                        new Ajax.Updater('content', iTravel.base_dir+'/verwaltung/'+iTravel.user_dir, {
                                            onComplete: (function () {
                                                this.initialize();
                                                if ( typeof _UI == 'object' ) _UI.initialize();
                                            }).bind(this)
                                        });
                                    }).bind(this)
                                });
                            }
                        }).bind(this)
                    });
                }).bind(this)).removeAttribute('href');
            }).bind(this));

        },



        /**
         * Die DropDown-Liste für neue Geschenkpakete wird umgebaut
         */
        add_gift : function()
        {

            var form = $$('form#add_gift')[0];
            if ( !!form ) {

                var link = form.down('*[type=submit]');
                if ( !!link ) {

                    var list = form.down('select.giftlist');
                    if ( !!list ) {

                        // Den Link umbauen
                        link.replace('<a id="show_giftlist" class="button">'+form.down('*[type=submit]').innerHTML+'</a>');
                        link = $('show_giftlist');

                        // Die DropDown-Liste in eine ungeordnete Liste umbauen und erst mal ausblenden
                        html = '';
                        list.childElements().each( function (o, i) {
                            html += '<li class="'+o.className+(i == 0 ? ' first' : '')+'"><a id="gift_'+o.readAttribute('value')+'">&raquo; '+o.innerHTML+'</a></li>';
                        });
                        list.replace('<ul class="giftlist">'+html+'</ul>');
                        list = $$('.giftlist')[0].hide();


                        // Beim Klick auf den Link wird (je nach aktuellem Zustand)
                        // - entweder die ungeordnete Liste eingeblendet und das Hintergrundbild des Links geändert
                        // - oder die Liste wird wieder ausgeblendet
                        link.observe('click', (function () {
                            if ( link.up('span.button').hasClassName('opened') ) {
                                new Effect.SlideUp( list, {
                                    duration: 0.2,
                                    beforeStart: function () {
                                        if ( !!$$('#add_gift #close_button')[0] ) {
                                            new Effect.Fade($$('#add_gift #close_button')[0], { duration: 0.4 });
                                        }
                                    },
                                    afterFinish: function () {
                                        link.up('span.button').removeClassName('opened');
                                    }
                                });
                            } else {
                                new Effect.SlideDown( list, {
                                    duration: 0.2,
                                    beforeStart: (function () {
                                        link.up('span.button').addClassName('opened');
                                        link.insert('<img src="'+iTravel.base_dir+'/assets/themes/'+iTravel.theme_name+'/images/button-schliessen.gif" id="close_button" style="position:absolute;right:4px;top:4px;display:none;" width="10" height="11" />');
                                        new Effect.Appear($$('#add_gift #close_button')[0], { duration: 0.4});
                                    }).bind(this)
                                });
                            }
                        }).bind(this));


                        // Korrigiere einige CSS-Eigenschaften und tausche die Reihenfolge des Links und der Liste
                        link.up('form').insert(list.up('fieldset'));
                        $$('#add_gift fieldset')[0].setStyle({ background: 'white', zIndex: 100, position: 'absolute', width: '240px' });


                        // Beim Klick in die Links in der DropDown-Liste wird das entsprechende Geschenkpaket in die Auswahl-Liste aufgenommen.
                        $$('#add_gift .giftlist a').each( (function (n) {
                            n.observe('click', (function () {
                                $('add_gift').request({
                                    parameters: 'g_id='+n.id.substr(5),
                                    onComplete: (function (transport) {
                                        new Ajax.Updater('content', iTravel.base_dir+'/verwaltung/'+iTravel.user_dir, {
                                            onComplete: (function () {
                                                this.initialize();
                                                if ( typeof _UI == 'object' ) _UI.initialize();
                                            }).bind(this)
                                        });
                                    }).bind(this)
                                });
                            }).bind(this)).removeAttribute('href');
                        }).bind(this));

                    }

                }

            }

        }

    },



    /**
     * Tauscht die beiden Elemente el_1 und el_2 im DOM aus.
     */
    replacePackets : function( el_1, el_2 )
    {

        // Elemente zwischenspeichern
        temp1 = el_1.cloneNode(true);
        temp2 = el_2.cloneNode(true);

        // Elemente tauschen
        Element.replace( el_1, temp2 );
        temp_id = el_2.id;
        el_2.id = el_2.id+'_temp';
        temp_el = Element.replace( el_2, temp1 );
        temp_el.id = temp_id;

    }


}

);





/**
 * Kleines Unterobjekt für die Inhalts-Layer
 */
XHR_Layer = Class.create (
{


    /**
     * @param (Integer) id
     * @constructor
     */
    initialize : function( id )
    {

        if ( !$(id) || $(id).nodeName != 'A' ) return;
        this.url = $(id).readAttribute('href');
        if ( typeof this.url == 'object' ) return;
        $(id).observe('click', (function () {
            new Ajax.Request ( this.url, {
                requestHeaders: {
                    'X-Requested_-With' : 'XMLHttpRequest'
                },
                onSuccess: (function (t) {
                    if (t.status == '200') this.create( t.responseText );
                    else if (t.status == '202' && t.statusText == 'Accepted') this.refresh();
                }).bind(this)
            });
        }).bind(this));
        $(id).removeAttribute('href')
        $(id).addClassName('rebuilt');

    },



    /**
     * Erzeugt einen Content-DIV mit dem erhaltenen Code als Inhalt.
     * @param (String) html : der HTML-Code
     */
    create : function( html )
    {

        // Erzeuge die HTML-Elemente und baue sie in den <body> ein
        html = '<div class="header"><a href="#" id="close">Schlie&szlig;en <img src="'+iTravel.base_dir+'/assets/themes/default/images/button-schliessen.gif" alt="Schlie&szlig;en" width="10" height="11" /></a></div>'+html;
        var inhalt = new Element('div', { 'id' : 'ajax_layer' }).update(html);

        var container = new Element('div',{ 'id' : 'ajax_container' }).update(inhalt);
        var overlay = new Element('div',{ 'id' : 'overlay' });
        var objBody = $$('body')[0];

        objBody.appendChild( container );
        objBody.appendChild( overlay );

        if ( $$('#ajax_container #layer_form')[0].hasClassName('wide') ) {
            $('ajax_layer').addClassName('wide');
        }


        // setze die Styles
        var arrayPageSize = this.getPageSize();
        $('ajax_container').setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' });
        $('overlay').setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px', opacity: 0.8 });


        // Einige Elemente explizit ausblenden
        $$('select', 'object', 'embed').each(function(n){ n.style.visibility = 'hidden'; });
        $$('#ajax_container select', '#ajax_container object', '#ajax_container embed' ).each(function (n) { n.style.visibility = 'visible'; });

        // Beim Klick auf den 'Schliessen'-, den 'Abbrechen'-Button und ausserhalb des Formulars, schliesse das Formular
        $('ajax_container').observe('click', (function(event) {
            var id = event.element().id;
            if (id == 'ajax_container' || id == 'close' || id == 'cancel' || event.element().descendantOf('close') || event.element().descendantOf('cancel') )
                this.destroy();
        }).bind(this));
        $('cancel').setAttribute('href', '#');


        // Einblenden des Containers
        $('overlay').setStyle({'opacity': '0'});
        new Effect.Appear($('overlay'), { duration: .4, from: 0.0, to: 0.8 });
        $('ajax_container').hide();
        new Effect.Appear($('ajax_container'), { duration: .3 });



        if ( !!$$('#layer_form *[type=submit]')[0] ) {

            var el = $$('#layer_form *[type=submit]')[0];
            // Abfangen des submit-Events


            Event.observe( 'layer_form', 'submit', (function (evt) {
                var valid = true;
                var reqs = $$('#layer_form strong.req');
                if ( reqs.length > 0 ) {
                    reqs.each( (function (r) {
                        if ( typeof r.up('label').readAttribute('for') != 'string' ) return; // nur wenn <label> existiert
                        if ( $(r.up('label').readAttribute('for')).value == '' ) valid = false; // wenn Feld leer
                    }).bind(this));
                }
                if ( valid == true ) { // wenn alle erforderl. Felder ausgefüllt sind => Absenden und aktualisieren
                    $('layer_form').request({
                        onComplete: (function () {
                            this.destroy();
                            this.refresh();
                        }).bind(this)
                    });
                } else { // wenn nicht => Fehlermeldung
                    $$('#layer_form .buttons')[0].insert({ before: '<p class="errormessage">Sie müssen alle erforderlichen Felder ausfüllen!</p>' });
                }
                Event.stop(evt);
            }).bind(this) );


        } else if ( typeof $$('a.select_photo')[0] == 'object' ) {

            // Abfangen der Links und Umbau in AJAX-Aufrufe
            $$('a.select_photo').each( function (a) {
                url = a.readAttribute('href');
                a.observe('click', (function () {
                    new Ajax.Request ( url, {
                    onSuccess: (function (t) {
                        if (t.status == '200') this.create( t.responseText );
                        else if (t.status == '202' && t.statusText == 'Accepted') this.refresh();
                    }).bind(this)
                    });
                }).bind(this)).removeAttribute('href');
            } );

        }

    },



    /**
     * Ausblenden des Containers
     * ausgeliehen von lightbox
     */
    destroy : function()
    {

        new Effect.Fade($('ajax_container'), { duration: .4, afterFinish: function () { $('ajax_container').remove(); } });
        new Effect.Fade($('overlay'), { duration: .3, from: 0.8, to: 0.0, afterFinish: function () { $('overlay').remove(); } });
        $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' });

    },



    /**
     * Lädt den Inhaltsblock per AJAX neu und baut die Links in Javascript um
     */
    refresh : function()
    {

        if ( location.href.include('verwaltung') ) {
            new Ajax.Updater('content', iTravel.base_dir+'/verwaltung/'+iTravel.user_dir, {
                onComplete: (function () {
                    if ( !! _XHR ) _XHR.initialize();
                    if ( !!_UI ) _UI.initialize();
                }).bind(this)
            });
        } else {
            new Ajax.Updater('content', iTravel.base_dir+'/'+iTravel.user_dir, {
                onComplete: (function () {
                    if ( !! _XHR ) _XHR.initialize();
                    if ( !!_UI ) _UI.initialize();
                }).bind(this)
            });
        }

    },



    /**
     * getPageSize()
     * ausgeliehen von lightbox
     */
    getPageSize : 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;
        }

        return [pageWidth,pageHeight];
    }

}

);




document.observe('dom:loaded', function () {
    _XHR = new XHR();
});

