/*
 * Itravel Core Library
 * @author joerg
 * @version 0.2
 */

/**
 * JSWidget supports core widget functionality.
 */
 
 
 function fadeContainer() {			/* Paging des ProductlistContents */
	new Effect.Opacity('opacityEffectBusinessCards' , {duration:0.2, from:1.0, to:0.2} );
	document.getElementById('opacityEffectBusinessCards').style.filter = 'alpha(opacity=20)';
	document.getElementById('doorpageLoader').style.display = 'block';
 	ratingDetailWidget.close();
 }
 
 function showWidgetLoader() {
    document.getElementById('widgetLoadingAnimation').style.display = 'block';	  	
 }
 

	var ajaxHandler = { 

    	onComplete : function() {
 	
    	document.getElementById('mouseLoadingAnimation').style.display = 'none';
    	
    	document.getElementById('widgetLoadingAnimation').style.display = 'none';	 
    	
    	document.getElementById('loadingGif').style.display = 'none';	
    	
    	document.getElementById('opacityEffectBusinessCards').style.filter = 'alpha(opacity=100)'; 
    	
		document.getElementById('opacityEffectBusinessCards').style.opacity = '1';    	
        	
    	document.getElementById('doorpageLoader').style.display = 'none';
		
		document.getElementById('loadingGif').style.display = 'none';
	 
    	}
	};

		Ajax.Responders.register(ajaxHandler);	





 
 
 
 
var widgetContainerId = "WidgetContainer";
var blackOutId = "Blackout";

var widgetAvailable = false; 
var galleryWidgetContainerId = "GalleryWidget";
/* Flag, ob bei zum Anzeigen bzw. bei Aufruf der prepareAppearMethode das innerHTML des $(widgetContainerId)-Elementes gelöscht werden soll oder nicht */
var dontRemoveContentOnPrepareAppear = false;
var JSWidget = Class.create({
    initialize : function(inRequestUrl, inWidth) {
        this.bodyTag = document.getElementsByTagName("body")[0];
		if(widgetAvailable) {
        	this.coreAnimation = new JSCoreAnimation();
		}
        this.CSSId = widgetContainerId;
        this.requestUrl = inRequestUrl;
        this.wdth = (inWidth!=null) ? inWidth : 400;
    },
    setCursorWait : function() {
        this.bodyTag.style.cursor = "wait";
    },
    setCursorDefault : function() {
        this.bodyTag.style.cursor = "default";
    },
    fade: function() {
        new Effect.Fade(this.CSSId,{
            duration:1.0,
            from: 1.0, to: 0.0,
            fps:80,
            beforeStart: showSelects
        });
    },
    close: function(){
        this.beforeClose();
        this.fade();
        this.coreAnimation.fadeIn();
    },
    appear : function() {
        new Effect.Appear(this.CSSId,{
            duration:1.0,
            from: 0.1, to: 1.0,
            fps:80,
            beforeStart: prepareAppear,
            afterFinish: this.afterAppear
        });
		
    },
    display : function(){
        this.setCursorDefault();
		this.coreAnimation.blackoutPage();
        $(this.CSSId).style.width = this.wdth +'px';
        $(this.CSSId).style.backgroundColor = "white"; //Warum dies? Muss beim GalleryWidget transparent bleiben, zerstoert sonst dessen Zweiteilung!
		this.coreAnimation.centerElement(this);
        this.appear();
    },
    show : function(){
        Element.show( this.CSSId );
    },
    getHtml : function(inUrl, inWidth, inRemoveWidgetContentOnAppear){
        this.wdth = inWidth == null ? this.wdth : inWidth;
        /* Schalter, der verhindert, dass der Inhalt des WidgetContainers entfernt wird. */
        dontRemoveContentOnPrepareAppear = inRemoveWidgetContentOnAppear != null && inRemoveWidgetContentOnAppear;
        this.setCursorWait();
        var url = inUrl == null ? this.requestUrl : inUrl;
        new Ajax.Updater(this.CSSId, url, {
            method: 'post',
            evalScripts: true,
            onComplete: this.display()
        });
    },
    submit : function(inFormId) {
        var response = $(inFormId).request({
            onSuccess: function(transport){
                $(widgetContainerId).update(transport.responseText);
            }
        });
    },
/** callback, der nach Abschluss des Appear-Effekts ausgeführt wird;
 * obj ist das Effekt-Objekt, das unter obj.element eine Referenz auf
 * das eingeblendete Element (den Widgetcontainer) enthält
 */
    afterAppear : function(obj){
        //put your setup code here
    },
/** callback, der vor beim Aufruf der Schliessen-Methode vor dem Fade-Effekts
 * ausgeführt wird;
 */
    beforeClose : function(){
        //put your cleanup code here
    }
});

/**
 * viewport, black out the Page used when presenting widgets
 * JSCoreAnimation. Takes care of basic things like getting Dimensions of the clients
 *
 */



var JSCoreAnimation = Class.create();
JSCoreAnimation.prototype = {
    initialize : function(){
        this.absoluteWidth = this.getAbsoluteBodyWidth();
        this.absoluteHeight = this.getAbsoluteBodyHeight();
        this.blackOutId  = "Blackout";
        this.scrollTopBefore = 0;
        this.defaultTop = 100;
    },
    blackoutPage : function(){
        try {
            $(this.blackOutId).setStyle({
            //height:    this.absoluteHeight  + 'px',
                height: getPageDimensions().Ht + 'px',
                width: getPageDimensions().Wd + 'px',
				bottom: 0
            });
            new Effect.Appear(this.blackOutId,{
                duration: 1.0,
                from: 0.0, to: 0.5,
                fps:80
            });
        } catch (e){}
    },
    fadeIn : function(){
        $(this.blackOutId).hide();
        window.scrollTo(0, this.scrollTopBefore);
    },
    isBlackoutPageVisible : function() {
        return Element.visible($(this.blackOutId));
    },
    getAbsoluteBodyWidth : function(){
        //return document.body.offsetWidth;
        return getPageDimensions().Wd;
        //return document.viewport.getDimensions()["width"];
    },
    getAbsoluteBodyHeight : function(){
        return getPageDimensions().Ht;
        //return document.viewport.getDimensions()["height"];
    },
    centerElement: function(inWidgetObject, absolute){
        // alert('widget: '+ inWidgetObject.wdth);
        var width = getPageDimensions().Wd; //document.viewport.getDimensions()["width"];
        // var elementWidth = Element.getWidth(elId) == 0 ? inWidth : Element.getWidth(elId);
        var elementWidth = inWidgetObject.wdth;
        // alert( 'elementWidth: '+ elementWidth );
        var leftPosition = absolute ? (width - 940)/2 : (width - elementWidth)/2;
        this.scrollTopBefore = Position.realOffset(document.getElementsByTagName('body')[0])[1];
        $(inWidgetObject.CSSId).setStyle({left: leftPosition +'px', top: this.defaultTop + 'px'});
        window.scrollTo(0, 0);
    }
    /*
    centerElement: function(elId, absolute, inWidth){
        alert('widget: '+ $(elId).style.display);
        inWidth =  $(elId).wdth;//!Object.isUndefined(inWidth) ? inWidth : 400; 
        var width = document.viewport.getDimensions()["width"];
        var elementWidth = inWidth; //Element.getWidth(elId) == 0 ? inWidth : Element.getWidth(elId);
        alert( 'elementWidth: '+ elementWidth );
        var leftPosition = absolute ? (width - 940)/2 : (width - elementWidth)/2;
        this.scrollTopBefore = Position.realOffset(document.getElementsByTagName('body')[0])[1];
        $(elId).setStyle({left: leftPosition +'px', top: this.defaultTop + 'px'});
        window.scrollTo(0, 0);
    }
    */
}

window.onresize = function () {
    var blackoutDiv = document.getElementById(blackOutId);
    if (blackoutDiv) {
        with (blackoutDiv.style) {
            height = getPageDimensions().Ht + 'px';
            width = getPageDimensions().Wd + 'px';
            right = 0;
        }
    }
}

/*
window.onscroll = function () {
    alert(document.body.scrollLeft + 'px');
    document.getElementById('Blackout').style.left = document.body.scrollLeft + 'px';
}
*/


/**
 * RatingWidget, takes care of RatingWiget handling
 * <ul>
 * <li>registers Button or opening</li>
 * <li>registers Button for closing</li>
 * <li>registers Eventhandlers for headlines to open and close siblings</li>
 * </ul>
 */
var JSRatingWidget = Class.create(JSWidget,{
    initialize : function($super, inRequestUrl){
        $super(inRequestUrl);
        this.CSSId = "RatingWidget";
        this.dragObject;
    },
    close : function(){
        new Effect.Fade(this.CSSId);
        //this.dragObject.destroy();
    },
    getHtml : function( $super, inUrl, inXPos, inYPos, inElementId  ) {
        
        if ( !Object.isUndefined(inXPos) && !Object.isUndefined(inYPos) )  {
            if ( !Object.isUndefined(inElementId) ) {
                /* TODO ITR-709: positionieren des Widgets an der richtigen Stelle */
            } 
            $( this.CSSId ).style.top = inXPos+'px';
            $( this.CSSId ).style.left = inXPos+'px';
        }
        $super( inUrl );
    },
    display : function(){
        this.dragObject = new Draggable('RatingWidget', {handle:'header'});
        new Effect.Appear(this.CSSId,{duration: 1.0});
        this.setCursorDefault();
    },
    openFirst : function(){
        if (this.tables != null && this.tables[0] != null)
            this.tables[0].style.display = "block";
    },
    setFunctions : function() {
        this.headlines = $$('#RatingWidget h4');
        this.tables = $$('#RatingWidget table');
        this.headlines.each(function(el){
            Event.observe(el,'click',function(){
                $$('#RatingWidget table').invoke('hide');

                var mySibs = $(el).parentNode.parentNode.getElementsByTagName('H4');
                for (i=0; i<mySibs.length; i++) {
                    if($(el)==mySibs[i]) {
                        $(el).className = 'active';
                    } else {
                        mySibs[i].className = 'inactive';
                    }
                }
                $(el.next()).show();
                $(el.next()).style.marginBottom = "10px";

            });
        });
        this.openFirst();
    }
});

var JSToggleableWidget = Class.create(JSWidget,{
    initialize : function($super, inRequestUrl){
        $super(inRequestUrl);
    },
    setFunctions : function() {
        var headlines = $$('#WidgetContainer h4');
        var tables = $$('#WidgetContainer table');
        headlines.each(function(el){
            Event.observe(el,'click',function(){
                $$('#WidgetContainer table').invoke('hide');

                var mySibs = $(el).parentNode.parentNode.getElementsByTagName('H4');
                for (i=0; i<mySibs.length; i++) {
                    if($(el)==mySibs[i]) {
                        $(el).className = 'active';
                    } else {
                        mySibs[i].className = 'inactive';
                    }
                }
                $(el.next()).show();
                //              $(el.next()).style.marginBottom = "0px";

            });
        });
        if (tables != null && tables[0] != null)
            tables[0].style.display = "block";
    },
    updateLayer : function(inUrl) {
        url = inUrl == null ? this.requestUrl : inUrl;
        new Ajax.Updater(this.CSSId, url, {
            method: 'post',
            evalScripts: true
        });      
    }
});

/**
 * Takes care of photogallery functions
 * <ul>
 * <li>centers element and brings it up front</li>
 * <li>exchanges content</li>
 * </ul>
 */
var JSGalleryWidget = Class.create(JSWidget,{
    initialize : function($super, inRequestUrl, inWidth ){
        $super(inRequestUrl);
        this.CSSId = "GalleryWidget";
        this.wdth = (inWidth!=null) ? inWidth : 441;
        /* TODO ITR-713: this.wdth = (inWidth!=null) ? inWidth : 651; */
    },
    display : function($super){
        this.setCursorDefault();
        this.coreAnimation.blackoutPage();
        $(this.CSSId).style.width = this.wdth+'px';
        $(this.CSSId).style.backgroundColor = "";
		this.coreAnimation.centerElement(this);
        //this.appear(); funktioniert im IE6/7 nicht einwandfrei, da manchmal bis meistens der Effect.appear nicht terminiert.
        $(this.CSSId).style.display = 'block';
    },
    close: function($super){
        // Wird überschrieben damit der Fadein-Effekt nicht ausgeführt wird.
        $(this.CSSId).style.display = 'none';
        this.coreAnimation.fadeIn();
    }
})

/**
 * simple Login Form that appears beneath servicenavigation
 * CSS ID = LoginFormWidget
 *
 * @base JSWidget
 */
var JSLoginFormWidget = Class.create(JSWidget,{
    initialize : function($super, inLoginUrl, inSuccessUrl, inErrorUrl, inAlternativeUrl){
        $super();
        this.CSSId = "LoginFormWidget";
        this.isOpen = false;
        this.coreAnimation = new JSCoreAnimation();
        this.loginUrl = inLoginUrl; // Request Login
        this.successUrl = inSuccessUrl; // Forward after Login
        this.errorUrl = inErrorUrl; // Forward after Failure
        this.alternativeUrl = inAlternativeUrl; // alternative Forward after Success
    },
    appear : function() {
        new Effect.Appear(this.CSSId,{
            duration:0.3, from: 0.1, to: 1.0
        });

    },
    close: function(){
        this.isOpen = false;
        this.fade();
    },
    submit: function(){

    },
    display : function(){
        this.isOpen = true;
        this.appear();
    },
    toggle: function(){
        (this.isOpen) ? this.close() : this.display();

    },
    hidePwd: function(){
        Element.show($('Login_PasswordDummy'));
        Element.hide($('Login_Password'));
    },
    showPwd: function(){
        Element.hide($('Login_PasswordDummy'));
        Element.show($('Login_Password'));
        $('Login_Password').focus();
    },
    login: function() {
        new Ajax.Request(this.loginUrl, {
            method: 'post',
            parameters: {username: $('Login_Username').value, password: $('Login_Password').value},
            onSuccess: function(transport) {
                var response = transport.responseText.evalJSON();
                if(response.success.startsWith("true")){
                    // Login success
                    if(loginFormWidget.successUrl.indexOf('welcome.action') != -1 || loginFormWidget.successUrl == '') {
                       window.top.location.href = loginFormWidget.alternativeUrl;
                    }
                    else {
                        window.top.location.href = loginFormWidget.successUrl;
                    } 
                } else {
                    // Login failt. Display error message
                    $('LoginWidgetError').style.visibility = 'visible';
                    loginFormWidget.setCursorDefault();
                }
            },
            onCreate: function() {
                loginFormWidget.setCursorWait();
            },
            onFailure: function() {
                loginFormWidget.setCursorDefault();
            }
        });
    },
    loginHelp: function() {
        new Ajax.Request(this.loginUrl, {
            method: 'post',
            parameters: {username: $('LoginHelp_Username').value, password: $('LoginHelp_Password').value},
            onSuccess: function(transport) {
                var response = transport.responseText.evalJSON();
                if(response.success.startsWith("true")){
                    // Login success
                    if(loginFormWidget.successUrl.indexOf('welcome.action') != -1 || loginFormWidget.successUrl == '') {
                       window.top.location.href = loginFormWidget.alternativeUrl;
                    }
                    else {
                        window.top.location.href = loginFormWidget.successUrl;
                    } 
                } else {
                    // Login failt. Display error message
                    $('LoginHelpWidgetError').style.visibility = 'visible';
                    loginFormWidget.setCursorDefault();
                }
            },
            onCreate: function() {
                loginFormWidget.setCursorWait();
            },
            onFailure: function() {
                loginFormWidget.setCursorDefault();
            }
        });
    }    
});


/**
 * Basis-Widget für alle Widgets, die Eingabefelder für Datumszeiträume enthalten;
 * enthält zusätzliche Callback-Methoden (afterAppear und beforeClose) zum
 * Initialisieren und Schliessen der Datepicker (Sub-) Widgets
 * Anmerkung vs: Das afterAppear funktioniert nur, wenn das Widget gerade geöffnet wird, da nur dann der
 * Callback ausgelöst wird. Bewegt man sich jedoch dann innerhalb des geöffneten Widgets von Seite zu Seite,
 * wird überhaupt kein Callback mehr ausgelöst. Folge: Die DatePicker werden nicht initialisiert und bei Klick auf die
 * Icons passiert nichts. Eine automatische Initialisierung beim Laden der Seite ist ebenfalls unsicher, da nicht
 * sichergestellt werden kann, dass das HTML-Element, an das die datepicker.js den onClick-Event bindet, zu diesem
 * Zeitpunkt schon vorhanden ist. Konsequenz aus all dem: Der DatePicker kann erst dann initialisiert werden, wenn
 * der Benutzer zum ersten Mal auf das Icon klickt. Man muss also auf das gewünschte HTML-Element einen
 * onclick-Handler legen und in diesem widget.showDateFrom() bzw. widget.showDateTo() aufrufen.
 */
var JSDateRangeWidget = Class.create(JSWidget, {
    beforeClose: function(){
	    var dateFrom = $(this.CSSId).dateFrom;
	    var dateTo = $(this.CSSId).dateTo;
	    if (!Object.isUndefined(dateFrom) && $(dateFrom._id_datepicker) != null && dateFrom.visible())
	        dateFrom.close();
	    if (!Object.isUndefined(dateTo) && $(dateTo._id_datepicker) != null && dateTo.visible())
	        dateTo.close();
    },
    initDateFrom: function() {
        if ( $('datepicker-date-from') != null ) {
            $('datepicker-date-from').parentNode.removeChild( document.getElementById('datepicker-date-from') );
        } 
        if ( ($('date-from') != null && $(this.CSSId).dateFrom == null)){
            $(this.CSSId).dateFrom = this.createDatePicker('date-from');
        }
    },
    initDateTo: function() {
        if ( $('datepicker-date-to') != null ) {
            $('datepicker-date-to').parentNode.removeChild( document.getElementById('datepicker-date-to') );
        }
        if ($('date-to') != null && $(this.CSSId).dateTo == null){
            $(this.CSSId).dateTo = this.createDatePicker('date-to');
        }
    },
    createDatePicker: function(inDateName) {
        return new DatePicker({
            relative    : inDateName,
            zindex: 1001,
            enableShowEffect: false,
            keepFieldEmpty: true,
            bodyAppend: true,
            /*enableCloseOnBlur: true,*/
            externalControl: inDateName + '-ctrl'
        });
    },
    showDateFrom: function() {
        this.initDateFrom();
         $(this.CSSId).dateFrom.click();
    },
    showDateTo: function() {
        this.initDateTo();
        $(this.CSSId).dateTo.click()
    }
});

var JSRatingFormWidget = Class.create(JSDateRangeWidget, {
    initialize : function($super, inRequestUrl){
        $super(inRequestUrl, 562);
    },
    getHtmlRated : function(inOverallRating){
        this.setCursorWait();
        new Ajax.Updater(this.CSSId, this.requestUrl, {
            parameters: {overallRating: inOverallRating},
            method: 'get',
            evalScripts: true,
            onComplete: this.display()
        });
    }
});


var JSRatingDetailWidget = Class.create(JSWidget, {
    initialize : function($super, inRequestUrl){
        $super(inRequestUrl);
        this.CSSId = "RatingDetailWidget";
    },
    close : function(){
        document.getElementById('RatingDetailWidget').style.display = 'none';
        document.getElementById('ratingDetailWidgetContainer').style.display = 'none';
  //      document.getElementById('whiteLayerRatingDetailWidget').style.zIndex = '1000';
  //      document.getElementById('whiteLayerRatingDetailWidget').style.display = 'block';       
        //this.dragObject.destroy();
    },
    getHtml : function( $super, inUrl, inElementId  ) {
 //       if ( !Object.isUndefined(inXPos) && !Object.isUndefined(inYPos) )  {
 //           if ( !Object.isUndefined(inElementId) ) {
 //               /* TODO ITR-709: positionieren des Widgets an der richtigen Stelle */
 //           } 
 //           $( this.CSSId ).style.top = inXPos+'px';
 //           $( this.CSSId ).style.left = inXPos+'px';
 //       }
        $super( inUrl );
	},
    display : function(){
        this.dragObject = new Draggable('RatingDetailWidget', {handle:'header'});
	//	new Effect.Appear(this.CSSId);
        this.setCursorDefault();
    },
    openFirst : function(){
        if (this.tables != null && this.tables[0] != null)
            this.tables[0].style.display = "block";
    },
    setFunctions : function() {
		//	setzt das RatingWidget + ratingWidgetContainer auf 'display:block' //
        document.getElementById('RatingDetailWidget').style.display = 'block';
		document.getElementById('ratingDetailWidgetContainer').style.display = 'block';
		    
        this.headlines = $$('#RatingDetailWidget h4');
        this.tables = $$('#RatingDetailWidget table');
        this.headlines.each(function(el){
            Event.observe(el,'click',function(){
                $$('#RatingDetailWidget table').invoke('hide');

                var mySibs = $(el).parentNode.parentNode.getElementsByTagName('H4');
                for (i=0; i<mySibs.length; i++) {
                    if($(el)==mySibs[i]) {
                        $(el).className = 'active';
                    } else {
                        mySibs[i].className = 'inactive';
                    }
                }
                $(el.next()).show();
                $(el.next()).style.marginBottom = "10px";

            });
        });
        this.openFirst();
    }    
});


var JSInfoWidget = Class.create(JSWidget, {
    initialize : function($super, inRequestUrl){
        $super(inRequestUrl);
        this.CSSId = "InfoWidget";
        this.dragObject;
    },
    display : function(){
        this.setCursorDefault();
        this.coreAnimation.centerElement(this);
        this.appear();

    },
    afterAppear: function(){
        this.dragObject = new Draggable('InfoWidget', {handle :'heading' });
    }
});

var JSUploadWidget = Class.create(JSWidget, {
    initialize : function($super, inRequestUrl){
        $super(inRequestUrl);
        this.CSSId = "UploadWidget";
    }
});


/**
 * handles update of modules with XHR
 *
 */
var JSContentHandler = Class.create();
JSContentHandler.prototype = {
    initialize : function(){
    },
    update : function(inId, inUrl) {
        new Ajax.Updater(inId, inUrl, {
            method: 'post',
            evalScripts: true
        });
    }
}

var contentHandler = new JSContentHandler();

function updateLayer(inUrl, inContainerId) {
    contentHandler.update(inContainerId == null ? widgetContainerId : inContainerId, inUrl);
}

function openWidget(inUrl, inWidth) {
    // alert('openWidget(...,inWidth='+ inWidth +'); widgetContainerId='+ widgetContainerId);
    setCursorWait();
    new Ajax.Updater(widgetContainerId, inUrl, {
        method: 'post',
        evalScripts: true,
        onComplete: displayWidget(inWidth == null ? 400 : inWidth)
    });
}

function displayWidget(inWidth) {
    setCursorDefault();
    blackoutPage();
    var width = inWidth == null ? 400 : inWidth; 
    $(widgetContainerId).style.width = width + "px";
    centerElement(widgetContainerId, width);
    new Effect.Appear(widgetContainerId, { duration:1.0, from: 0.1, to: 1.0, fps:80,
        beforeStart: prepareAppear
    });
}



function closeWidget() {
    new Effect.Fade(widgetContainerId, { duration:1.0, from: 1.0, to: 0.0, fps:80,
        beforeStart: showSelects
    });
    new JSCoreAnimation().fadeIn();
}

function submitForm(inFormId, noupdate) {
    
    var response = $(inFormId).request({
        onSuccess: function(transport){
            if(noupdate != 'true') {
            $(widgetContainerId).update(transport.responseText);
            } else {
            document.getElementById("messagediv").style.visibility = 'visible';
            }
        },
        onFailure: function(transport){
            alert('FAILURE: ' + transport)
        },
        on500: function(transport){
            alert('500: ' + transport)
        }
    });
}


function submitTheForm(inFormId, updateId) {
// $(updateId).innerHTML = "Wird geladen....";
 
    var response = $(inFormId).request({
        onSuccess: function(transport){
            if(updateId == '') {
             $(widgetContainerId).update(transport.responseText);
            } else {
             $(updateId).innerHTML = "Wird geladen....";
             $(updateId).innerHTML = transport.responseText;
             sIFRcontentBoxHeaderText();
            }
        },
        onFailure: function(transport){
            alert('FAILURE: ' + transport)
        },
        on500: function(transport){
            alert('500: ' + transport)
        }
    });
}


function submitFormWishmap(inFormId, noupdate) {
    
    var response = $(inFormId).request({
        onSuccess: function(transport){
            if(noupdate != 'true') {
            $(widgetContainerId).update(transport.responseText);
            } else {
            document.getElementById("messagediv").style.visibility = 'visible';
            }
            window.location.href='/portal/myITravel.action';
        },
        onFailure: function(transport){
            alert('FAILURE: ' + transport)
        },
        on500: function(transport){
            alert('500: ' + transport)
        }
    });
}

function centerElement(elId, inWidth) {
    var width = document.viewport.getDimensions()["width"];
    var elementWidth = inWidth == null ? 400 : inWidth;
    //alert( 'elementWidth: '+ elementWidth );
    var leftPosition = (width - elementWidth)/2;
    this.scrollTopBefore = Position.realOffset(document.getElementsByTagName('body')[0])[1];
    $(elId).setStyle({left: leftPosition +'px', top: '100px'});
    window.scrollTo(0, 0);
}

function blackoutPage(){
    try {
        $(blackOutId).setStyle({
            height: getPageDimensions().Ht + 'px',
            width: getPageDimensions().Wd + 'px'
        });
        new Effect.Appear($(blackOutId),{
            duration: 1.0,
            from: 0.0, to: 0.5,
            fps:80
        });
    } catch (e){}
}

function setCursorWait() {
    document.getElementsByTagName("body")[0].style.cursor = "wait";
}

function setCursorDefault() {
    document.getElementsByTagName("body")[0].style.cursor = "default";
}

function showSelects () {
    var mySelects = $('Main').getElementsByTagName('SELECT');
    for(i=0; i<mySelects.length; i++) {
        mySelects[i].style.visibility = "";
    }
}

function hideSelects () {
    var mySelects = $('Main').getElementsByTagName('SELECT');
    for(i=0; i<mySelects.length; i++) {
        mySelects[i].style.visibility = "hidden";
    }
}

function prepareAppear() {
    if ( dontRemoveContentOnPrepareAppear == null || !dontRemoveContentOnPrepareAppear ) {
        $(widgetContainerId).innerHTML = '';
    }
    $(galleryWidgetContainerId).innerHTML = '';
    dontRemoveContentOnPrepareAppear=false;
    hideSelects();
}

function expand(idCollapsed, idExpanded){
    Element.hide(idCollapsed);
    Element.show(idExpanded);
    myContent = findMyContent(idCollapsed);
    myContent.parentNode.style.height = 'auto';
    return false;
}

function collapse(idCollapsed, idExpanded){
    Element.hide(idExpanded);
    Element.show(idCollapsed);
    myContent = findMyContent(idCollapsed);
    myContent.parentNode.style.height = '';
    return false;
}

function findMyContent(myId) {
    myParent = document.getElementById(myId).parentNode;
//    while(myParent.className.indexOf('content')<0) {
//        myParent = myParent.parentNode;
//    }
    return myParent;
}


function getPageDimensions () {
    var pg = new Object;
	
    if (window.innerHeight) {
        pg.Ht = (window.innerHeight > document.body.scrollHeight) ? window.innerHeight : document.body.scrollHeight;
    } else if(document.documentElement && document.documentElement.offsetHeight && document.documentElement.scrollHeight > 0) {
        pg.Ht = (document.documentElement.offsetHeight > document.body.scrollHeight) ? document.documentElement.offsetHeight : document.body.scrollHeight;
    } else if(document.body && document.body.offsetHeight && document.body.offsetHeight > 0) {
        pg.Ht = (document.body.offsetHeight > document.body.scrollHeight) ? document.body.offsetHeight : document.body.scrollHeight;
    } 
    pg.Wd = document.body.clientWidth;
    return pg;
}

function login(inFormId) {
    var response = $(inFormId).request({
        onSuccess: function(transport){
            var responseText = transport.responseText;
            if (responseText.startsWith('http')) {
                window.top.location.href = responseText;
            } else {
                $(widgetContainerId).innerHTML = responseText;
            }
        }
    });
}


//--------------- FORMULAR REISEMANAGER -------------------------------------------------




function getAdultHTML(){
    //   return     '\n<div class="adult">'
    //               + '\n<div class="number">${newCount}.&nbsp;</div>'
    //               + '\n<div class="adultName">'
    //                  + '\n<label for="adult${newCount}FirstName">Vorname</label>'
    //                  + '\n<input type="text" id="adult${newCount}FirstName" name="adults[${newIndex}].firstName"/>'
    //               + '\n</div>'
    //               + '\n<div class="adultName">'
    //                  + '\n<label for="adult${newCount}LastName">Nachname</label>'
    //                  + '\n<input type="text" id="adult${newCount}LastName" name="adults[${newIndex}].lastName"/>'
    //               + '\n</div>'
    //            + '\n</div>';
    return     '\n<li class="adultItem">'
            + '\n<input type="text" id="adult${newCount}FirstName" name="adults[${newIndex}].firstName" maxlength="50" />'
            + '\n<input type="text" id="adult${newCount}LastName" name="adults[${newIndex}].lastName" maxlength="50" />'
            + '\n</li>';
}
function removeAdult(){
    removeLastElement('AdultList', 'adultItem', 1);
    synchronizeElements('Adults', 'adultItem', 'AdultsCount', 1);
}
function addAdult(){
    addElement('AdultList', 'adultItem', null, getAdultHTML(), 10);
    synchronizeElements('Adults', 'adultItem', 'AdultsCount', 1);

}
function updateAdults(requestedCount){
    updateElements('AdultList', 'adultItem', getAdultHTML(), requestedCount, 1, 10);
    synchronizeElements('Adults', 'adultItem', 'AdultsCount', 1);
}

function getTravellerHTML(){
    //   return     '\n<div class="adult">'
    //               + '\n<div class="number">${newCount}.&nbsp;</div>'
    //               + '\n<div class="adultName">'
    //                  + '\n<label for="adult${newCount}FirstName">Vorname</label>'
    //                  + '\n<input type="text" id="adult${newCount}FirstName" name="adults[${newIndex}].firstName"/>'
    //               + '\n</div>'
    //               + '\n<div class="adultName">'
    //                  + '\n<label for="adult${newCount}LastName">Nachname</label>'
    //                  + '\n<input type="text" id="adult${newCount}LastName" name="adults[${newIndex}].lastName"/>'
    //               + '\n</div>'
    //            + '\n</div>';
    return    '\n<li class="adultItem">'
            + '\n<input type="text" id="adult${newCount}FirstName" name="adults[${newIndex}].firstName" maxlength="50" />'
            + '\n<input type="text" id="adult${newCount}LastName" name="adults[${newIndex}].lastName" maxlength="50" />'
            + '\n<input type="text" id="adult${newCount}age" name="adults[${newIndex}].age" maxlength="50" />'
            + '\n</li>';
}
function removeTraveller(){
    removeLastElement('AdultList', 'adultItem', 1);
    synchronizeElements('Adults', 'adultItem', 'AdultsCount', 1);
}
function addTraveller(){
    addElement('AdultList', 'adultItem', null, getTravellerHTML(), 10);
    synchronizeElements('Adults', 'adultItem', 'AdultsCount', 1);

}
function updateTraveller(requestedCount){
    updateElements('AdultList', 'adultItem', getTravellerHTML(), requestedCount, 1, 10);
    synchronizeElements('Adults', 'adultItem', 'AdultsCount', 1);
}

function getKidHTML(){
    return '\n<li class="childItem">'
            + '\n<input type="text" name="children[${newIndex}].firstName" id="children${newCount}FirstName" maxlength="50" />'
            + '\n<input type="text" name="children[${newIndex}].lastName" id="children${newCount}LastName" maxlength="50" />'
            + '\n<select id="childSelect${newIndex}" class="text" name="children[${newIndex}].age" style="display:inline">'
            + '\n<option value="-1">bitte w&auml;hlen</option>'
            + '\n<option value="0-2">unter 1</option>'
            + '\n<option value="1">1</option>'
            + '\n<option value="2">2</option>'
            + '\n<option value="3">3</option>'
            + '\n<option value="4">4</option>'
            + '\n<option value="5">5</option>'
            + '\n<option value="6">6</option>'
            + '\n<option value="7">7</option>'
            + '\n<option value="8">8</option>'
            + '\n<option value="9">9</option>'
            + '\n<option value="10">10</option>'
            + '\n<option value="11">11</option>'
            + '\n<option value="12">12</option>'
            + '\n<option value="13">13</option>'
            + '\n<option value="14">14</option>'
            + '\n<option value="15">15</option>'
            + '\n<option value="16">16</option>'
            + '\n<option value="16-18">&Uuml;ber 16</option>'
            + '\n</select>'
            + '\n</li>';
    //   return '\n<div class="child">'
    //               + '\n<div class="number">${newCount}.&nbsp;</div>'
    //               + '\n<div class="childName">'
    //                  + '\n<label for="child${newCount}FirstName">Vorname</label>'
    //                  + '\n<input type="text" id="child${newCount}FirstName" name="children[${newIndex}].firstName"/>'
    //               + '\n</div>'
    //               + '\n<div class="childName">'
    //                  + '\n<label for="child${newCount}LastName">Nachname </label>'
    //                  + '\n<input type="text" id="child${newCount}LastName" name="children[${newIndex}].lastName"/>'
    //               + '\n</div>'
    //               + '\n<div class="childAge">'
    //                  + '\n<label for="childAge${newCount}">Alter&sup1;</label>'
    //                  + '\n<select class="text" id="childAge${newCount}" name="childAge${newCount}" style="display:inline">'
    //                  + '\n<option value="0">--</option>'
    //                  + '\n<option value="0.5">&lt;1</option>'
    //                  + '\n<option value="1">1</option>'
    //                  + '\n<option value="2">2</option>'
    //                  + '\n<option value="3">3</option>'
    //                  + '\n<option value="4">4</option>'
    //                  + '\n<option value="5">5</option>'
    //                  + '\n<option value="6">6</option>'
    //                  + '\n<option value="7">7</option>'
    //                  + '\n<option value="8">8</option>'
    //                  + '\n<option value="9">9</option>'
    //                  + '\n<option value="10">10</option>'
    //                  + '\n<option value="11">11</option>'
    //                  + '\n<option value="12">12</option>'
    //                  + '\n<option value="13">13</option>'
    //                  + '\n<option value="14">14</option>'
    //                  + '\n<option value="15">15</option>'
    //                  + '\n<option value="16">16</option>'
    //                  + '\n<option value="17">17</option>'
    //                  + '\n</select>'
    //               + '\n</div>'
    //            + '\n</div>';
}

function removeKid(){
    removeLastElement('ChildList', 'childItem', 0);
    synchronizeElements('Children', 'childItem', 'ChildrenCount', 0, 'ChildListLabels');
}
function addKid(){
    addElement('ChildList', 'childItem', null, getKidHTML(), 10);
    synchronizeElements('Children', 'childItem', 'ChildrenCount', 0, 'ChildListLabels');
}
function updateChildren(requestedCount){
    updateElements('ChildList', 'childItem', getKidHTML(), requestedCount, 0, 10);
    synchronizeElements('Children', 'childItem', 'ChildrenCount', 0, 'ChildListLabels');
}

function updateElements(containerId, className, html, requestedCount, minCount, maxCount){
    if (requestedCount >= minCount && requestedCount <= maxCount){
        var currentCount = $(containerId).getElementsByClassName(className).length;
        var changeCount = requestedCount - currentCount;
        for (var i = changeCount; i < 0; i++){
            removeLastElement(containerId, className, minCount);
        }
        for (var i = 0; i < changeCount; i++){
            addElement(containerId, className, null, html, maxCount);
        }
    }
}
function removeLastElement(containerId, className, minCount){
    var items = $(containerId).getElementsByClassName(className);
    var aCount = items.length;
    if (aCount > 0 && aCount > minCount){
        var lastItem = items[items.length - 1];
        lastItem.parentNode.removeChild(lastItem);
    }
}
function addElement(containerId, className, elementToInsertBefore, html, maxCount){
    var aNewCount = $(containerId).getElementsByClassName(className).length + 1;
    var aNewIndex = $(containerId).getElementsByClassName(className).length;
    if (aNewCount <= maxCount){
        var theHTML = html.replace(/\$\{newCount\}/g, aNewCount);
        theHTML     = theHTML.replace(/\$\{newIndex\}/g, aNewIndex);
        var newContent  = document.createElement('span');
        $(newContent).update(theHTML);
        $(containerId).insertBefore(getFirstChildElement(newContent), $(elementToInsertBefore));
    }
}

function getFirstChildElement(inElement){
    if (inElement.nodeType != 1)
        return null;
    var aChild = inElement.firstChild;
    while(aChild != null && aChild.nodeType != 1){
        aChild = aChild.nextSibling;
    }
    return aChild;
}
function synchronizeElements(containerId, className, counterId, increment, labelId){
    var currentCount = $(containerId).getElementsByClassName(className).length;
    var currentSelect = $(counterId).selectedIndex + increment;

    if (currentCount != currentSelect && currentCount > -1){
        $(counterId).selectedIndex = currentCount - increment;
    }
    if (currentCount == 0 && labelId != null){
        $(labelId).hide();
    }
    else if(currentCount > 0 && labelId != null){
        $(labelId).show();
    }
}
//------- /FORMULAR REISEMANAGER -----------------------------------------------

function addUpload(containerId, uploadPrefix, descriptionPrefix){
    var newCount = $(containerId).getElementsByClassName('file').length + 1;

    var label = 'Foto ' + newCount;
    var uploadId =  uploadPrefix  + newCount;
    var descriptionId =  descriptionPrefix  + newCount;

    var html = '<label>Foto ' + newCount +'</label>'
            + '\n<input class="file" type="file" size="60" name="' + uploadId +'"/>'
            + '\n<input class="description" type="text"  name="' + descriptionId +'" value="Bildbeschreibung angeben"/>';

    var newContent = document.createElement('div');
    $(containerId).appendChild(newContent);
    $(newContent).update(html);
}


var maxImageIndex = 4; 
function submitTravelogueFileUploadForm(isUploadFinished) {
    // Prüfen, ob Dateien zum Hochladen eingestellt wurden
    var hasImages = false;
    for (i = 0; i < 5; i++) {
        if ($("foto" + i).value.length > 0) {
            hasImages = true;
            break;
        }
    }
    // Falls auf "Hochladen" geklickt wurde, sollten auch Dateien ausgewählt sein
    if (isUploadFinished == 'false' && !hasImages) {
        $('noImagesSelectedMessage').style.display = 'block';
        return false
    }
    // Falls Dateien hochgeladen wurden, prüfen, ob das Copyright-Häkchen gesetzt wurde
    if (hasImages && ! $('NoCopyRightViolation').checked) {
        $('noImagesSelectedMessage').style.display = 'none';
        $('copyrightViolationMessage').style.display = 'block';
        return false;
    } else {
        $('noImagesSelectedMessage').style.display = 'none';
        $('copyrightViolationMessage').style.display = 'none';
        $('uploadFinished').value = isUploadFinished;
        $('travelogueForm').submit();
        return true;
    }
}

function initDateRangePicker(){
    if ( document.dateFrom == null ) {
        document.dateFrom = new DatePicker({
            relative    : 'date-from',
            zindex: 1001,
            enableShowEffect: false,
            keepFieldEmpty: true,
            bodyAppend: true,
            disableFutureDate: false,
            externalControl: 'date-from-ctrl'

        });
        document.dateFrom.load();
    }
    if ( document.dateTo == null ) {
        document.dateTo = new DatePicker({
            relative    : 'date-to',
            zindex: 1001,
            enableShowEffect: false,
            keepFieldEmpty: true,
            bodyAppend: true,
            disableFutureDate: false,
            externalControl: 'date-to-ctrl'

        });
        document.dateTo.load();
    }
}

function setVisibility(inValue, inId) {
    document.getElementById(inId).style.visibility = inValue.blank() ? "hidden" : "";
}


function initContingentDatePicker() {
	var datepicker    = new DatePicker({
	    relative    : 'date-from2',
	    language    : 'de',
	    disableFutureDate: false,
	    disablePastDate: false,
	    zindex: 100,
        keepFieldEmpty: true,
        externalControl: 'date-from-ctrl2'
	    });
	
	var datepicker2    = new DatePicker({
	    relative    : 'date-to2',
	    language    : 'de',
	    disableFutureDate: false,
	    disablePastDate: true,
	    zindex: 100,
        keepFieldEmpty: true,
        externalControl: 'date-to-ctrl2'
	    });
}
