var SLRegistry = new Object();
var nzOCOpenedImage = 'images/pfeil.gif';
var nzOCClosedImage = 'images/pfeilOpen.gif';

/**
 *global Datevars
 */
Date.monthNames = ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September','Oktober', 'November', 'Dezember'];
Date.dayNames =['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'];
 
 
window.DEBUG_MODE=false;   





/**
 *TabRegistry
 */
window.TabRegistry = {};
/**
 *registers a tab object
 */
TabRegistry.add =function(tab, name) {
        if (!tab.headlines || !tab.image) return;
        this[name]=tab;
}
/**
 *changes the css Class from an element with given id to the new class
 */
function changeCssClassTo(elementId,newClass) {
        if (!elementId) return;
        var element = document.getElementById(elementId);
        if ((!element)) return;
        element.className=newClass;
}
/**
 *closes one or more registered objects
 */
function closeContainer(objects) {
        var i=0;
        for (i=0;i<objects.length;i++) {
                closeMe(objects[i]);
        }        
}
/**
 *closes an Element via visibilty and changes the class
 *opens and 
 */ 
function closeMe(objectName) {
        var oElement = document.getElementById(objectName);
        if (!oElement) return; 
        oElement.style.display = 'none';
        if(!window.TabRegistry[objectName]) return;
        var buttonImage = document.getElementById(window.TabRegistry[objectName].image);
        buttonImage.src = nzOCClosedImage;
        window.TabRegistry[objectName].openStatus = false;
        //change headline classes
        var i;
        for (i=0;i<window.TabRegistry[objectName].headlines.length;i++) {
                changeCssClassTo(window.TabRegistry[objectName].headlines[i],'');
        }       
}



/**
 *displays an element via it's visibility
 *@see
 */
function openMe(objectName){

                var oElement = document.getElementById(objectName);
        if (!oElement) return; 
        oElement.style.display = 'block';
        var buttonImage = document.getElementById(window.TabRegistry[objectName].image);
        buttonImage.src = nzOCOpenedImage;
        window.TabRegistry[objectName].openStatus = true;
        //change headline classes
        var i;
        for (i=0;i<window.TabRegistry[objectName].headlines.length;i++) {
                changeCssClassTo(window.TabRegistry[objectName].headlines[i],'activeInformations');
        }         
}

//Toggles an elements visibility in gui  (visibility and space) between closed / open 
function OpenCloseMe(objectName) {
			try {
        if(TabRegistry[objectName].openStatus == false) {
                openMe(objectName);
        }else{
                closeMe(objectName);
        }//end if display
     } catch (e) {
    	if(window.DEBUG_MODE) {
      	alert(e+'\n'+e.description );
      }
    }   
       
}//end of OpenCloseMe

/**
 * switches the open/closed image of a tab
 * nzContentObjectName is the contentContainer
 * nzButtonObjectName is the id of the Image
 *@todo needed?
 */
function toggleImage(nzContenObjectName,nzButtonObjectName) {
        var image = document.getElementById(nzButtonObjectName);        
        if (SLRegistry[nzContenObjectName]) {
                image.src = nzOCOpenedImage;
        } else {
                image.src = nzOCClosedImage;
        }
}

/**
 * ensures that only one of the passed content object is displayed
 * object must be registered in the TabRegistry
 */

function mutualExcluder(objectName1,objectName2) {
        //name of the elements to exclude
               this.objectName1=objectName1;
        this.objectName2=objectName2;
        
        /**
         *@param objectName the object To open
         */
        this.toggle = function(objectName) {
                if (objectName==this.objectName1) {
                        OpenCloseMe(objectName);
                        if (window.TabRegistry[this.objectName1].openStatus)  { //this content object is open, close the other one
                                closeMe( this.objectName2);
                        }                        
                } else {
                        OpenCloseMe(objectName);
                        if (window.TabRegistry[this.objectName2].openStatus)  { //this content object is open, close the other one
                                closeMe(this.objectName1);
                        }                          
                }                
        }            
}
/**
 *shows an element with a given id-string
 */
function show(nzContenObjectName) {
        var oElement = document.getElementById(nzContenObjectName);
        if (!oElement) return; 
        oElement.style.display = '';        
} 
/**
 *hides an element with  a given id-string
 */
function hide(nzContenObjectName) {
        var oElement = document.getElementById(nzContenObjectName);
        if (!oElement) return;
        oElement.style.display = 'none';
}

function loadReiseziel() {
        document.cookie = 'reiseziel';
        location.href='reiseziel.htm';
}

function updateHotellist() {
        hide('updateHotelsButton');
        hide('updateHotelsButtonMore');
        hide('updateHotelsButtonFlughafen');
}

function handleTravelDateChange() {
        show('updateHotelsButton');
}

function handleTravelMoreChange() {
        show('updateHotelsButtonMore');
}

function handleTravelFlughafenChange() {
        show('updateHotelsButtonFlughafen');
}

function handleOnAllinclusiveClick() {
        document.cookie = 'reisekategorie'; 
        loadDetailseite();
}
function loadDetailseite() {
        //document.cookie = 'reiseziel'; 
        location.href='detailseite.htm';
}
/**
 *@todo add comments
 */
function outwardReturnFlight() {
         hide('returnAirport');
         show('destinationAirport');
         show('startAirport');
         show('travelDateReturn');
         show('inboundPicker');
         openMe('airportContent');
}
/**
 *@todo add comments
 */
function outwardFlight() {
         hide('returnAirport');
         show('destinationAirport');
         show('startAirport');
         hide('travelDateReturn');
         hide('inboundPicker');
         openMe('airportContent');
}
/**
 *@todo add comments
 */
function openJawFlight() {
         show('returnAirport');
         show('destinationAirport');
         show('startAirport');
         show('travelDateReturn');
         show('inboundPicker');
         openMe('airportContent');
}

/**
 *funicton which will be called if a bis-date is selected
 */
function handleBisDateChange(vonPickerId, bisPickerId,timeDifference) {
        //if vonDate set, update dauer
        if ((!window.vonPicker || !window.bisPicker) && (!vonPickerId || !bisPickerId)) return;
        if (vonPickerId) {
        	 try {
        	 	var vonDate = window.datePickers[vonPickerId].getValue();
        	 } catch (e) {
        	 		if(window.DEBUG_MODE) {
                		alert('handleBisDateChange:\n'+e+'\n'+e.description);
              }
        			return;
        	 } 
        } else {
      		 var vonDate = window.vonPicker.getValue();
        }
        var vonDateInMs=vonDate.format('U');
       
        if (bisPickerId) {
	        	try {		
	        		var bisDate = window.datePickers[bisPickerId].getValue();
       			 } catch (e) {
       			 			if(window.DEBUG_MODE) {
                		alert('handleBisDateChange:\n'+e+'\n'+e.description);
                	}
        			return;
        	 	 } 
       		} else {
       		 var bisDate = window.bisPicker.getValue();
        }        
        
        var bisDateInMs = bisDate.format('U');
        
        	
        
       	if  (bisDate<vonDate) {
       		if (timeDifference!=undefined) { //get time difference
       			var timeDifferenceInDays=timeDifference;
       		} else { //standard solution
	       		//var travelDauerSelect = document.getElementById('travelDauer');
	        	var timeDifferenceInDays = parseInt(DauerList.getValue()+1);
	        }
	        
	        if (bisPickerId) {
	        	try {	
	        		
       			 	window.datePickers[bisPickerId].setValue(vonDate.add(Date.DAY, timeDifferenceInDays)); 
       			 } catch (e) {
       			 	if(window.DEBUG_MODE) {
                		alert('handleBisDateChange:\n'+e+'\n'+e.description);
                	}
        			return;
        	 	 } 
       		} else {
       				window.bisPicker.setValue(vonDate.add(Date.DAY, timeDifferenceInDays)); 
       		}
       		return;
       	}
        
}
/**
 *@see handleBisDateChange()
 */
function handleVonDateChange(vonPickerId, bisPickerId,timeDifference) {
        if ((!window.vonPicker || !window.bisPicker) && (!vonPickerId || !bisPickerId)) return;
        
        if (vonPickerId) {
        	 try{
        	 var vonDate = window.datePickers[vonPickerId].getValue();
        	 } catch (e) {
        	 		if(window.DEBUG_MODE) {
                		alert('handleVonDateChange:\n'+e+'\n'+e.description);
                	}
        			return;
        	 } 
        } else {
      		 var vonDate = window.vonPicker.getValue();
        }
       
        var vonDateInMs=vonDate.format('U');
        
        //alert(vonDateInMs);
        
        if (bisPickerId) {
	        	try {		
	        		var bisDate = window.datePickers[bisPickerId].getValue();
       			 } catch (e) {
       			 			if(window.DEBUG_MODE) {
                		alert('handleBisDateChange:\n'+e+'\n'+e.description);
                	}
        			return;
        	 	 } 
       		} else {
       		 var bisDate = window.bisPicker.getValue();
        }
        //alert(bisDate);       
        var bisDateInMs = bisDate.format('U');

        if  (bisDate<vonDate) {
       		if (timeDifference!=undefined) { //get time difference
       			var timeDifferenceInDays=timeDifference;
       		} else { //standard solution
	       		//var travelDauerSelect = document.getElementById('travelDauer');
	        	var timeDifferenceInDays = parseInt(DauerList.getValue())+1;
	        }
       		if (bisPickerId) {
       			try{
       			 	window.datePickers[bisPickerId].setValue(vonDate.add(Date.DAY, timeDifferenceInDays)); 
       			 	} catch (e) {
       			 		if(window.DEBUG_MODE) {
                		alert('handleVonDateChange:\n'+e+'\n'+e.description);
                	}
        			return;
        	 } 
       		} else {
       				/* TEST by Phillip ---- Datum: 6.11.08  16:00 */
       				var dateNow = new Date();
		            var newBisValue = '';
		            var dayNow =  (dateNow.getDate() < 10)  ? "0"+dateNow.getDate()  : dateNow.getDate(); 
		            
		            //var vonDateValue = window.bisPicker.getValue();
		            
		            
		            
		                   
		            //newBisValue = vonDate.add( bisDateRawValue.day/*'17.12.2008'*/, timeDifferenceInDays);
	       			window.bisPicker.setValue(vonDate.add(Date.DAY,timeDifferenceInDays));
       		}
       		return;
       }
}

/**
 * function will be called if the travelDauer changes
 * if the travelduration is longer then the difference between von and bis, the bis date will be adjusted
 */
function handleDauerChange() {
				if (!window.vonPicker || !window.bisPicker) return;
				//alert('inside');
        var vonDate = window.vonPicker.getValue(); 
        var bisDate = window.bisPicker.getValue();
        //var travelDauerSelect = DauerList('travelDauer');
        var timeDifferenceInDays = DauerList.getValue()+1;
        
        if (vonDate && bisDate) { //check, if the selected duration is smaller than the time difference
        	 var timeDifference = vonDate.getElapsed(bisDate) / 1000 / 60 /60 /24;
        	 if (timeDifference<timeDifferenceInDays) {
        	 		bisDate = vonDate.add(Date.DAY, timeDifferenceInDays);                
              window.bisPicker.setValue(bisDate);   
        	 } 
        } else if (vonDate) { //if only a vonDate, automatically set the bisDate
        	 bisDate = vonDate.add(Date.DAY, timeDifferenceInDays);                
           window.bisPicker.setValue(bisDate); 
        }     
}




/**
 *ldt den von DatePicker
 */
function initVonPicker(startDate,onSelectHandler) {
        window.vonPicker = new Ext.form.DateField({
                //fieldLabel: 'Testdatum',
                name: 'startDate',
                width: 133,
                allowBlank: true,
                showWeekNumber: true,
                triggerClass:'kalender',
                monthNames:['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September','Oktober', 'November', 'Dezember'],
                //fieldClass:'fieldClass',
                //focusClass:'focusClass',
                //ctCls:'ctClass',
                //style: 'font-size:21px;',
                //cls:'cls',
                invalidClass:'invalidClass',
                //width:100px,
                //height:17px,
                format: 'd.m.Y'
        });
        var inputField=document.getElementsByName('startDate'); inputField = inputField[0];
      
    
        if (onSelectHandler) {
                window.vonPicker.on('change',onSelectHandler);
                window.vonPicker.on('valid',onSelectHandler);
        }
         window.vonPicker.render('vonPicker');
        if (startDate) {
                try {
                   window.vonPicker.setValue(startDate);
                } catch (e) {
                	if(window.DEBUG_MODE) {
                		alert('initVonPicker:\n'+e+'\n'+e.description);
                	}
                }
        }
        if (window.vonPicker.triggerClass) {//if a specific trigger class is set, override the other ones
                window.vonPicker.trigger.dom.className=window.vonPicker.triggerClass; //delete other kalender class
        }
        
        //Ext.apply(window.vonPicker.trigger,{triggerClass:'x-form-kalender-trigger'});
        //window.picker.trigger.dom.style.backgroundImage="../images/kalender.gif";
}
/**
 *ldt den bis DatePicker
 */
function initBisPicker(startDate, onSelectHandler) {
        window.bisPicker = new Ext.form.DateField({
                //fieldLabel: 'Testdatum',
                name: 'returnDate',
                width: 133,
                allowBlank: true,
                showWeekNumber: true,
                triggerClass:'kalender',
                
                                  //fieldClass:'fieldClass',
                //focusClass:'focusClass',
                //ctCls:'ctClass',
                //style: 'style',
                //cls:'cls',
                //invalidClass:'invalidClass',
                //width:100px,
                //height:17px,
                format: 'd.m.Y'
        });

        if (onSelectHandler) {
                window.bisPicker.on('change',onSelectHandler);
                window.bisPicker.on('valid',onSelectHandler);
        }
        
        window.bisPicker.render('bisPicker');
        if (startDate) {
                try {
                        window.bisPicker.setValue(startDate);
                } catch (e) {
                	if(window.DEBUG_MODE) {
                		alert(e+'\n'+e.description);
                	}
                }
        }
        if (window.bisPicker.triggerClass) {//if a specific trigger class is set, override the other ones
                window.bisPicker.trigger.dom.className=window.bisPicker.triggerClass;
        }
}

/**
 *ldt den bis DatePicker 
 *@param id die id es datepickers und des div-tags,
                 in das der date picker gerendert werden soll. ebenfalls der name, den das ding im form hat
 *@param Date startDate wenn angegeben, wird das bergebene Date Object als startdatum verwendet
 *@param Object config alternative config fr den Datepicker
 *@param function onSelectHandler Funktion, die aufgerufen wird wenn ein Datum ausgewhlt wird.
 */
function initDatePicker(id,startDate,config, onSelectHandler) {
                    if (!window.datePickers) window.datePickers = [];
                    var standardConfig = {
                //fieldLabel: 'Testdatum',
                name: id,
                width: 133,
                allowBlank: true,
                id:id+'Id',
                showWeekNumber: true,
                 triggerClass:'kalender',
                 emptyText: 'TT.MM.JJJJ',
                format: 'd.m.Y'
        };
              standardConfig  = config || standardConfig ;
        window.datePickers[id] = new Ext.form.DateField(standardConfig);
       

        if (onSelectHandler) {
                //alert(onSelectHandler);
                window.datePickers[id].on('change',onSelectHandler);
                window.datePickers[id].on('valid',onSelectHandler);
        }
        
        window.datePickers[id].render(id);
        if (startDate) {
                try {
                        window.datePickers[id].setValue(startDate);
                } catch (e) {
                	if(window.DEBUG_MODE) {
                		alert(e+'\n'+e.description);
                	}
                }
        }
        if (window.datePickers[id].triggerClass) {//if a specific trigger class is set, override the other ones
                window.datePickers[id].trigger.dom.className=window.datePickers[id].triggerClass;
        }
}


/*
        //oObject.setAttribute("onclick", 'CloseMe(this,'+nzContenObjectName+')');
        //SlideTo(oObject,nStartWidth, nStartHeight, nEndWidth, nEndHeight);

function SlideTo(oObject,nStartWidth, nStartHeight, nEndWidth, nEndHeight) {

        if(nStartWidth != nEndWidth) {
        
                 oObject.style.width = nEndWidth;
        
        }//end if nStartWidth != nEndWidth
        if(nStartHeight != nEndHeight) {
        
                //alert('YES');
                oObject.style.border = "solid red 10px";
                oObject.style.height = nEndHeight+'px';
                
        }//end if nStartWidth != nEndWidth


}//end of SlideUp

*/

/**
 *creates a new,Global load mask
 */
function initLoadMask(containerId) {
        //var loadMaskContainer = Ext.DomHelper.append(Ext.getBody(), {id: 'loadMask', tag: 'div'});
        var loadMaskContainer = Ext.getDom(containerId);
        if (!loadMaskContainer) return; 
        window.loadMask =  new Ext.LoadMask(loadMaskContainer,{msg:'Ldt Daten...',removeMask:false});
        /**
         *changes the status message of the loading mask
         *@param refresh: if true, the status message will be updated even if the load mask is active
         */
        window.loadMask.setMessage = function(message, refresh) {
                if (message) {
                        this.msg=message;
                        if (refresh) {
                                this.hide();
                                this.show();                                
                        }
                }
        }

        window.loadMask.enable();
        //window.loadMask.show();
        //window.loadMask.hide();
}

/**
 *function, which is called when a travel target has been selected

function handleTravelTargetChange() {
        var pauschhalreiseSearchForm = document.getElementById('pauschalreise_search');
        try {
                DoBeforeSubmit(pauschhalreiseSearchForm);
        } catch (e) {
        		if(window.DEBUG_MODE) {
                		alert(e+'\n'+e.description);
            }                
        }
}
 */

                               

/**
 *handles a click on the tagCloud
 
function handleTravelTargetLinkClick(value) {
                var regionSelect = document.getElementById('region');
                var i=0,madeSelection=false;

                for (i=0;i<regionSelect.options.length;i++) {
                        if (regionSelect.options[i].value==value) {
                                regionSelect.options[i].selected = true;
                                madeSelection=true;
                                break;
                        } 
                }
                if (madeSelection) {
                        handleTravelTargetChange();
                } else {
                        return;
                }
}
 */
/**
 *hides the travelagency data div and displays the search form again
 */
function hideAgencyDataDisplayAgencyForm(scope) {
        if (!scope) scope = window;
        var tadc = scope.document.getElementById("travelAgencyDataContainer");
        var tafc = scope.document.getElementById("travelAgencyFormContainer");
        tadc.style.display="none";
        tafc.style.display="";
}

/**
 *Function splits the ExtJs DatePicker Format into the double Date input from Denkwerk
 */
function SplitDate(nzExtDateFielId, nzDayFieldId, nzMonthYearFieldId) {
        
        //30.07.2008
        
        var nzExtValue = window.datePickers[nzExtDateFielId].getRawValue();
        
        var Day                = nzExtValue.substr(0,1);
        
        if(Day == '0' || Day == 0) {
           Day = nzExtValue.substr(1,1);
        }else{
           Day = nzExtValue.substr(0,2);
        }//end if Day
        
        var Month        = nzExtValue.substr(3,2);
        var Year         = nzExtValue.substr(6,4);
        //alert(nzExtValue);
        //alert('Day: '+Day+' Month: '+Month +' Year: '+ Year);        
        document.getElementById(nzDayFieldId).value = Day;
        document.getElementById(nzMonthYearFieldId).value = Month + Year;
        
        //alert(Day + ' ' + Month + Year);

}//end of SplitDate

/**
 *Function combines the double Date input from Denkwerk into the ExtJs DatePicker Format
 */
function CombineDate(nzExtDateFielId, nzDayFieldId, nzMonthYearFieldId) {
        

        var Day		= document.getElementById(nzDayFieldId).value;
        var Month	= document.getElementById(nzMonthYearFieldId).value.substr(0,2);
        var Year	= document.getElementById(nzMonthYearFieldId).value.substr(2,6);
        
        window.datePickers[nzExtDateFielId].setRawValue(Day + '.' + Month  + '.' + Year);
        

}//end of CombineDate


/**
 *loads an image into the image cache
 */
function preLoad(imageUrl, containerId) {
	
	var imageToBeCached = new Image();
	//imageToBeCached.src = imageUrl;
	//imageToBeCached.style.backgroundImage=imageUrl;
	//imageToBeCached.style.display = 'none';
	container = document.getElementById(containerId);
	container.innerHTML="<div style='background:url("+imageUrl+");'></div>";
	
}
/**
 *object that represents a cookie
 */
function cookieHelper (cookieString) {
		if (!cookieString) return;
		this.items = [];
		var i=0,name='',value='';		
		var nameStart=0,equalPosition=0;
		for (i=0;i<cookieString.length;i++) {
			  name='';value='';
			  //alert(cookieString[i]);
			  if(cookieString.charAt(i)=='=') equalPosition=i;
			  if(cookieString.charAt(i)==';') {
			  	name = cookieString.substring(nameStart,equalPosition);
			  	value = cookieString.substring(equalPosition+1,i);
			  	this.items[name]=value;
			  	name='';
			  	value='';
			  	nameStart=i+1;
			  } 
		}
		
}

/**
 *function to clear an input field
 */
function clearThis(domElement, startValue) {
	try {
		if (startValue) { //if there is a startValue to compare
			if (domElement.value==startValue) { //only clear, if it is the start value
				domElement.value='';				
			}	else {
				return;
			}
		} else {//with no start value, just clear
			domElement.value='';
		} 
	} catch (e) {
		if(window.DEBUG_MODE) {
    	alert(e+'\n'+e.description);
    }
	}
}