				/**
 *  README:
 *  Funktionsweise: 
 *  
 *  Im HTML-Quelltext wird ein leerer Containerbehaelter fuer die 
 *  Objekte zur Verfuegung gestestellt. Der Container verfuegt ueber eine eindeutige ID.
 *  Der Name der ID muss nicht mit dem Namen des Objektes uebereinstimmen. 
 *  In diesem Container befinden sich andere HTML-Element, die die Eigenschaften 
 *  des Objektes aufnehmen, z.B. Objekt ist "offers", Eigenschaften sind "hotelName", "city".
 *  Diese Elemente werden mit css-Klassennamen versehen, die den Namen der Eigenschaften
 *  entsprechen.
 *   
 *  JSON-Objekt:
 *   
 *  {"offers":[
 *      {"hotelName":"Holiday Inn","city":"Barcelona"},
 *      {"hotelName":"Best Western","city":"Athen"}
 *      ]
 *   }     
 *  
 * HTML-Container:
 *    
 *  <div id="hotel">
 *    <div class="hotelName"></div>
 *    <div class="city"></div>
 *  </div>   
 * url, item, containerClass, wrapperID, parentElementID
 *  Die Funktion printJsonPResults benoetigt 
 *  - url = die URL, die das JSON-Objekt zurueckliefert,
 *  - item = der Namen des JSON-Objektes 
 *  - containerClass = Klasse des Containerbehaelters
 *  - wrapperID = ID des wrappers im Template
 *  - parentElementID = ID des Containerbehaelters
 *  
 *  Funktionsaufruf:
 *     
 *  printResults('http://eineURL','offers','hotel');
 *  
 *  Die Funktion iteriert ueber die Elemente des JSON-Objektes und gibt sie in Kopien
 *  des Container-Elementes auf der Seite aus. Diese Kopien erhalten wiederum 
 *  eindeutige IDs.
 *     
 *  generiertes HTML:
 *   
 *  <div id="hotel0">
 *    <div class="hotelName">
 *      Holiday Inn  
 *  </div>
 *    <div class="city">
 *      Barcelona
 *    </div>
 *  </div>   
 *    
 *  <div id="hotel1">
 *    <div class="hotelName">
 *      Best Western
 *    </div>
 *    <div class="city">
 *      Athen  
 *    </div>
 *  </div>    
 *             
 */ 

/**
 * Remove old result list from the DOM and hide error container if neccessary
 */   
function cleanJsonPResults(containerClass, wrapperID, firstElementID){
	//console.log(jQuery('#' + wrapperID + ' .' + containerClass + ':first').attr('id'));
	
		jQuery('#' + wrapperID + ' .' + containerClass + ':first').siblings().remove();
		jQuery('.' + containerClass).hide();
		
		jQuery('#errorContainer').hide();
}
/**
 * Main function for processing Json objects and spitting them out as html on the page.
 */

function printJsonPResults(url, item, containerClass, wrapperID, parentElementID,theOffer) {
	//alert(url);
    cleanJsonPResults(containerClass, wrapperID, parentElementID);
    displayWaitAnimation();
    
	jQuery.ajax({
    dataType: "jsonp",
    jsonp: 'jsonp_callback',
    url: url,
    cache: false,
    error:function (xhr, status, error){
                    alert('Das Veranstaltersystem ist kurzfristig nicht erreichbar.\n Bitte probieren Sie es gleich noch einmal.');
                    hideWaitAnimation();
                    ///alert(thrownError);
        },
    success: function(data){
    //alert("success");
	  //  fetch data
	      var obj = data;
	      var theItems = obj[item];
	      var container = parentElementID; 
	      var newParentElementID = "";
	      var numItems = 0;
	      
	      //  iterate through Json   
              
        jQuery.each(theItems, function(i, val) {
         //console.log(i);
        	numItems++;
           newParentElementID = container + i;

           // clone html container that displays the the data and give it a new ID.
           jQuery('#' + parentElementID).clone(true).attr('id', newParentElementID).insertAfter(jQuery('#' + parentElementID));
           
           var text = ""; 
        // sort out items in the object
           jQuery.each(theItems[i], function(key, thisItem){
        	   if(isNaN(key))
        	   key = key.toLowerCase();
        	   //console.log(key);
            // check if item is an object  
              if(thisItem != null && typeof(thisItem) == 'object'){
            // check if item is a simple Array 
                if(thisItem.constructor == Array){
                //console.log('Array');
                  for(var i = 0; i < thisItem.length; i++){
// TODO: separating by comma is not enough!                  
                    text += thisItem[i] + ", ";
                // fill Array items into the container, separated by comma
                    jQuery('#'+ newParentElementID + ' .' + key).text(text);
                     jQuery('#'+ newParentElementID).show();
                  }
                }
            // or an embedded object
                else {
                // console.log('embedded object');
                  jQuery.each(thisItem, function(k, subItem){
                	  if(isNaN(k))
                	  k = k.toLowerCase();
                	  // check if it is an img and set src of container img to src provided by Json	
                    if(jQuery('#'+ newParentElementID + ' .' + k).is('img')){
                    	jQuery('#'+ newParentElementID + ' .' + k).attr('src', 'http://cluster1.loc1.ffm.synaix.de' + subItem);
                    }
	                else {
	                	// set the text of the html element with the css-class provided by the key to the value
	                    jQuery('#'+ newParentElementID + ' .' + k).text(subItem);
	                    jQuery('#'+ newParentElementID).show();
	                  }
                  });
                }   
              } 
          //  or a simple key/value pair
              else {
            	// check if it is an img and set src of container img to src provided by Json	
                if(jQuery('#'+ newParentElementID + ' .' + key).is('img')){
                  jQuery('#'+ newParentElementID + ' .' + key).attr('src', 'http://cluster1.loc1.ffm.synaix.de' + thisItem);
                 //console.log('img');
                }
                else {
                	// set the text of the html element with the css-class provided by the key to the value
                  jQuery('#'+ newParentElementID + ' .' + key).text(thisItem);
                  jQuery('#'+ newParentElementID).show();
                  //alert('key/value');
                }
              }
           });
            parentElementID = newParentElementID;
	      });
        
	      if(numItems == 0){
          // no items were returned - show error
	    	  jQuery('#errorContainer').show();
	    	  jQuery('#' + container).parent().parent().hide(); 
        }
	      jQuery('#' + container).parent().parent().show();
      	
// set the href of each link in the resultslists to an unique anchor
// not sure we need this	      
	 /*
	      jQuery('.resultContainer').each(function(i){
	    	  //console.log(jQuery(this).attr('id'));
	    	  var num = Math.random();
	    	  num = num * 10;
	    	  jQuery(this).find('.priceContainer').attr('href', '#'+jQuery(this).attr('id') + num);
	    	  jQuery(this).find('.priceContainer').attr('name', '#'+jQuery(this).attr('id') + num);
	      });
	   */   
	    // hide parent container used to clone the others  
	       jQuery('#' + container).hide();
	       hideWaitAnimation();
	    // do all kinds of stuff that is unique to this special IBE
		      prettifyThis(item, theOffer);
	      }
	  });
}  

function setUrl(serviceName, formContainerID){
//	var url = "http://192.168.1.213:8787/ibeservice/ibe/"
	var url = jQuery('base').attr('href');
//	var url = "http://www.spartours.de/";
	url += "ibeservice/ibe/"
	url += serviceName + ".json?";
	url += jQuery('#' + formContainerID + ' form').serialize();
	  //console.log(url);
	url += "&format=jsonp&jsonp_callback=?";
	  //alert(url);
	  return url;
}
function setUrlHttps(serviceName, formContainerID){
	var url = jQuery('base').attr('href');
 
//	var url = "https://www.spartours.de/";
	url += "ibeservice/ibe/";
	url += serviceName + ".json?";
	url += jQuery('#' + formContainerID + ' form').serialize();
	url += "&format=jsonp&jsonp_callback=?";
	return url;
}
function fetchResults(serviceName, objectName, formContainerID, storageFormName, setStorageForm,url,wrapperID,containerID){
  
  if(url == '')
	  url = setUrl(serviceName,formContainerID);
  
  //alert(jQuery('#ibeRegion').get(0).value);
  if(setStorageForm){
    setStorageValues(formContainerID, storageFormName);
  }
  if(wrapperID == undefined && containerID == undefined) {
	  if(document.forms[storageFormName].elements['region'].value == ''){
		  //console.log(document.forms[storageFormName].elements['region'].value + " is region value")
		  wrapperID = 'regionResults';
	    containerID = 'regionResultContainer';
	    document.forms[storageFormName].elements['iff-code'].value = '';
	  }
	  else {
	    wrapperID = 'hotelResults';
	    containerID = 'hotelResultContainer';
	  }
	  if(document.forms[storageFormName].elements['iff-code'].value != ''){
	    wrapperID = 'datePriceResults';
	    containerID = 'datePriceResultContainer';
	  }
  }
  if(wrapperID == 'regionResults' || wrapperID == 'hotelResults'){
	  jQuery('#shoppingCartWrapper').hide();
	  jQuery('#shoppingCartBottom').hide();
  }
  printJsonPResults(url, objectName, 'resultContainer', wrapperID, containerID);
  //alert(url + '---- ' + containerID);   
  jQuery('.resultWrapper').hide();
  if(wrapperID == 'datePriceResults'){
	  jQuery('#shoppingCartWrapper').children().show();
	  jQuery('#shoppingCartBottom').children().show();
  }
  jQuery('#results').show(); 
  jQuery('#' + wrapperID + "Wrapper").show();
  //console.log(jQuery('#storage-anzahl-treffer-pro-seite').attr('value'));
  getHistory();
}

/**
 * Copies the values of the searchForm to a storage form
 */
function setStorageForm(formContainerID, storageFormName){
	
	if(!document.forms[storageFormName]) return;
	
	jQuery('#' + formContainerID + ' input').each(function(i){
		var theName = jQuery(this).attr('name');
		if(document.forms[storageFormName].elements[theName] != undefined){
			if(jQuery(this).attr('type') == 'checkbox'){
				if(jQuery(this).attr('checked') == true){
					document.forms[storageFormName].elements[theName].value = jQuery(this).get(0).value;
						
	    		} else {
	    			document.forms[storageFormName].elements[theName].value = '';
	    		}
	    	}
	    	else{
			if(theName != "reiseart"){
		    		document.forms[storageFormName].elements[theName].value = jQuery(this).get(0).value;
			}
	    	}
	    }
  });
  jQuery('#' + formContainerID + ' select').each(function(i){
	    var theName = jQuery(this).attr('name');
//alert(theName);	    
	    if(jQuery(this).attr('value') == '') {
	    	jQuery('#' + storageFormName + ' input[name="'+theName+'"]').val('');
//	    	jQuery('#' + storageFormName + ' input[name="'+theName+'"]').attr('value', '');
	    } else {
	    	jQuery('#' + storageFormName + ' input[name="'+theName+'"]').attr('value', jQuery(this).find('option:selected').val());//get(0).value);
	    }
//	    if(document.forms[storageFormName].elements[theName] != undefined) 
	    	//document.forms[storageFormName].elements[theName].value = jQuery(this).val();//get(0).value; 
  });
  jQuery('#numChildren').attr('value', getNumChildren()); 
  jQuery('#selectedPageNumber').attr('value', 1);
}

function prettifyThis(item, theOffer){
	//alert('prettifyThis ' + jQuery('#datePriceResultsWrapper').get(0).style.display);
	checkBookingStatus();
	fillBookingParams();
	  // Change hotelInfoUrl 
	  var oldHref = jQuery('#id_hotelname').attr('href');
	  jQuery('#id_hotelname').attr('href',oldHref + '&VA='+jQuery('#veranstaltercode').val()); 
	  
	  
	  if(item == "gz-antwort"){
			 // alert('gz');
		  if(jQuery('#gz-antwort-switch').attr('value') == 1) {
			 // jQuery('#flightDetailsResultsWrapper').insertAfter('.wrapper h2');
			 // jQuery('#flightDetailsResultsWrapper').show();
			 // jQuery('#GrayOut').show();
			 // jQuery('#InnerDimensions').show();
			 // jQuery('.close').css('right','20px');
			 // jQuery('#Popup').height(490);
			 // jQuery('#Popup').css('overflow-y','scroll');
			 displayWaitAnimation();
			  setFlightDetailsFields();
		  }
		  else {
			  jQuery('#flightDetailsResultsWrapper').insertAfter('.wrapper h2');
			  jQuery('#flightDetailsResultsWrapper').show();
			  jQuery('#GrayOut').show();
			  jQuery('#InnerDimensions').show();
		  }	
	  }
//	  if(item == "gz-antwort-summary"){
//		 // alert('gz');
//		  jQuery('#flightDetailsResultsWrapper').appendTo('.wrapper');
//		  setFlightDetailsFields();
//	  }
	  if(item == "ba-antwort"){
		  setTotalPrice();
		  var thisTotalPrice = jQuery('#storageForm .buchungspreis').val();
      	thisTotalPrice = thisTotalPrice.split(';');
      	var last = thisTotalPrice.length - 1;
      	jQuery('#' + theOffer + ' .thisTotalPriceLabel').show();
      	thisTotalPrice = thisTotalPrice[last] + ' &euro;';
      	jQuery('#' + theOffer + ' .thisTotalPrice').html(thisTotalPrice);
      	jQuery('#' + theOffer + ' .thisTotalPrice').show();
      	jQuery('#' + theOffer + ' .priceContainer').hide();
      	jQuery('#' + theOffer + ' .submitThis').show();
      	jQuery('#' + theOffer + ' .submitThis').css('display','block');
      	jQuery('#' + theOffer + ' .checkAvailability').remove();
		  var url = setUrl('flugzeiten-anfrage','storageFormContainer')
		  jQuery('#myUrl').text(url);
		  var theFormdata = jQuery('#storageForm').serialize(); 
	  	  jQuery('#' + theOffer + ' .thisFormdata').text(theFormdata);
  	  	
	  }
	/*if(jQuery('#hotelResultsWrapper').get(0).style.display == 'block') {
	  printStars();
	  printHotelRatings();
	  updatePageNumbers('hotel');
	 // toggleDisplayAlternatives();
	}
	if(jQuery('#regionResultsWrapper').get(0).style.display == 'block'){  
	 toggleDisplayTopRegion ();
	// updatePageNumbers('region'); 
	 setRegionInfoLink();
	 }
	if(jQuery('#datePriceResultsWrapper').get(0).style.display == 'block'){
		printStars();
		printHotelRatings();
		toggleDaysFormat();
		updatePageNumbers('datePrice');
		prettifyDate('datum');
		checkBookingStatus();
		fillBookingParams();
	}
	*/
}


/**
 * functions for region list
 * 
 */

function toggleDisplayTopRegion (){
  var text = "";
  jQuery('#regionResults .regionRow').each(function(i){
    jQuery(this).show();
    jQuery(this).prev('.headerRow').show();
    if(jQuery(this).children().children().children('.preistermin').text() == '0'){
      jQuery(this).hide();
    }
    else {
      jQuery(this).prev('.headerRow').hide();
    }
  });
}

/**
 * sets the link to the region info popup
 */
function setRegionInfoLink(){
  jQuery('.laenderefid').each(function(){
    jQuery(this).siblings('.infoLink').attr('href', 'http://cp.traveltainment.de/content_page/index.php3?KID=622000&Laender_Ref_ID=' + jQuery(this).text());
  });
}
/**
 * get all hotels from a specific region and display hotel list
 */
function fetchHotelList(thisLink){
  document.storageForm.region.value = jQuery(thisLink).prev('.topregion').text();
  jQuery('#ibeRegion').val(jQuery(thisLink).prev('.topregion').text());
  jQuery('#storage-anzahl-treffer-pro-seite').attr('value', 20);
  jQuery('#numResultsHotel').attr('value', 20);
  var url = setUrl('hotel-angebote','storageFormContainer');
  jQuery('#clickpathHotel').attr("href", "javascript:fetchResults('hotel-angebote','hotels','storageFormContainer','storageForm',false,'" + url + "','hotelResults','hotelResultContainer');resetIff();");  resetSortBy();
  resetPageNumbers();
  fetchResults('hotel-angebote','hotels','storageFormContainer','storageForm', false,'');
  
}


/**
 * handling of alternative offers - not yet in use
 */
function toggleDisplayAlternatives(){
  var isAlternative = "";
  jQuery('.alternativ').each(function(i){
     
    //console.log(i + ". " + isAlternative );
    isAlternative = this.get(i).text();
  });
}

/**
 * functions for hotel list
 * 
 */

/**
 * display category stars in hotel list
 */
function printStars(){
  jQuery('.sterne').each(function(){
  jQuery(this).next().removeClass();
  var categoryStars = jQuery(this).text().replace(/\./, "");
    jQuery(this).next('div').addClass('sterneContainer');
    jQuery(this).next('div').addClass('sterne' + categoryStars);
  });
}
/**
 * display hotel ratings in hotel list
 */
function printHotelRatings() {
  jQuery('.hotelRating').each(function(i){
    var rating = jQuery(this).parent().prev('.hotelbewertunggesamt').text();
    
    rating = rating * 10;
    if(rating > 0){
      jQuery(this).parents('.ratingsContainer').show();
      jQuery(this).parents('.ratingsContainer').prev('.noRatings').hide();
      jQuery(this).css('width', rating);
    }
      else {
        jQuery(this).parents('.ratingsContainer').hide();
        jQuery(this).parents('.ratingsContainer').prev('.noRatings').show();
      }
  });
}
function fetchDatePriceList(thisLink, inputName){
  document.storageForm.elements[inputName].value = jQuery(thisLink).siblings('.iff').text();
  resetSortBy();
  resetPageNumbers();
  fetchResults('termine-und-preise','angebote','storageFormContainer','storageForm', false,'');
  var url = setUrl('hotel-angebote','storageFormContainer');
  jQuery('#clickpathDatePrice').attr("href", "javascript:fetchResults('termine-und-preise','angebote','storageFormContainer','storageForm',false,'" + url + "','datePriceResults','datePriceResultContainer');");  
  resetSortBy();
  jQuery('#shoppingCartWrapper').children().text('');
  var cartId = jQuery(thisLink).parents('.resultContainer').get(0).id + 'Cart'; 
  jQuery(thisLink)
  	.parents('.resultContainer')
  	.clone(true)
  	.attr('id', cartId)
  	.appendTo('#shoppingCartWrapper');
  jQuery('#' + cartId).find('.priceContainer').remove();
  jQuery('#' + cartId).find('.fetchDatePriceButton').remove();
  	displayShoppingCart();
  jQuery('#numResultsDatePrice').attr('value', jQuery('#storage-anzahl-treffer-pro-seite').attr('value'));
  
}
/**
 * functions for datePrice list
 * 
 */
/**
 * singular/plural days
 */
function toggleDaysFormat(){
  jQuery('.dauer').each(function(){
    var numDays = parseInt(jQuery(this).text(), 10);
    if(numDays == 1)
      jQuery(this).next('.formatDay').html('Tag');
    else
      jQuery(this).next('.formatDay').html('Tage');
  });
}
function getNumChildren(){
	var numChildren = 0;
	jQuery('.childrenInput').each(function(){
		if(parseInt(jQuery(this).attr('value'), 10))
			numChildren++;
	});
	return numChildren;
}
/**
 * set source for tour operator logo - does not work yet
 * @param className
 * @param thisItem
 * @return
 */
function setTourOperatorLogo(className, thisItem){
  if(className == "veranstalterCode"){
    jQuery('#'+ newParentElementID + ' .' + key).attr('src', 'http://cluster1.loc1.ffm.synaix.de' + thisItem);
  }
}

/**
 *  set number of results to display
 * 
 */

function setNumResults(thisSelect, serviceName, objectName){
	document.forms['storageForm'].elements['anzahl-treffer-pro-seite'].value = jQuery('#' + thisSelect).get(0).value;
	document.forms['searchForm'].elements['anzahl-treffer-pro-seite'].value = jQuery('#' + thisSelect).get(0).value;
	resetPageNumbers();
    fetchResults(serviceName, objectName,'storageFormContainer','storageForm', false,'');
    if(jQuery('#datePriceResultsWrapper').get(0).style.display == 'block')
    	displayShoppingCart();
}

function resetSortBy(){
	jQuery('#storageForm #sortierung').attr('value','preis');
	jQuery('#hotelSortBy').attr('value','preis');
	jQuery('#datePriceSortBy').attr('value','preis');
}
function resetIff(){
	jQuery('#storageIffCode').attr('value','');
}
/**
 * Paging
 * 
 */

function updatePageNumbers(resultList){
	jQuery('.rem').remove();
	var totalResults = jQuery('#' + resultList + 'ResultContainer1 .headerErgebnis').text();
	var resultsPerPage = jQuery('#storage-anzahl-treffer-pro-seite').get(0).value;
	var numPages = Math.ceil(totalResults/resultsPerPage);
	for(var i = 1; i < numPages; i++){
		jQuery('#' + resultList + 'Pager .page' + i)
			.clone()
			.insertAfter('#' + resultList + 'Pager .page' + i)
			.removeClass()
			.addClass('page' + (i + 1))
			.addClass('rem')
			.attr('id', 'pageNum' + (i + 1))
			.text(i + 1);
	}
	var selectedPage = jQuery('#selectedPageNumber').attr('value');
	jQuery('#' + resultList + 'Pager .page' + selectedPage).addClass('highLighter');
	//console.log('#' + resultList + 'Pager #pageNum' + selectedPage + ' totalResults'+totalResults + ' -- ' + resultsPerPage + ' numPages:' + numPages + ' selectedPage: ' + selectedPage);
}

function resetPageNumbers(){
	jQuery('#startposition').attr('value', 0);
	jQuery('.page1').addClass('highLighter');
	jQuery('#selectedPageNumber').attr('value', 1);
}

function fetchNewPage(thisPage, resultList){
	jQuery('.pageNumbers li').removeClass('highLighter');
	
	thisPage = jQuery('#' + thisPage).text();
	jQuery('#selectedPageNumber').attr('value', thisPage);
	var offset = jQuery('#storage-anzahl-treffer-pro-seite').attr('value') * (thisPage - 1) + 1;
	jQuery('#startposition').attr('value', offset);
	if(resultList == 'hotel')
		fetchResults('hotel-angebote','hotels','storageFormContainer','storageForm', false,'');
	if (resultList == 'datePrice') {
		fetchResults('termine-und-preise','angebote','storageFormContainer','storageForm', false,'');
		displayShoppingCart();
	}
	if(resultList == 'region'){
		fetchResults('regions-liste','regions','searchFormContainer', 'storageForm', false,'');
	}
}

function setBookingStatus(url, item, thisOffer) {
	
	jQuery.ajax({
    dataType: "jsonp",
    jsonp: 'jsonp_callback',
    url: url,
    cache: false,
    error:function (xhr, status, error){
                    alert('Das Veranstaltersystem ist kurzfristig nicht erreichbar.\nBitte probieren Sie es gleich nochmal.');
                    hideWaitAnimation();
                    ///alert(thrownError);
        },
    success: function(data){
    //alert("success");
	  //  fetch data
	      var obj = data;
	      var theItems = obj[item];
	      var bookingStatusOk = true;
	       
	      //  iterate through Json   
      // alert('success');       
        jQuery.each(theItems, function(i, val) {
           jQuery.each(theItems[i], function(key, thisItem){
        	   if(isNaN(key))
        	   key = key.toLowerCase();
        	   if(key == "ergebnis"){
        		//   alert('Item ' + key + ' value ' + thisItem + ' bookingStatus ' + bookingStatusOk);
        		   jQuery('.ergebnis').text(thisItem);  
	        	  if(thisItem < 0){
	            		  bookingStatusOk = false;
	            		  //alert('booking status is sooo' + bookingStatusOk);
	              }
        	   }
        	   if(key == "buchungsaction"){
        		   if(thisItem == ''){
        			   bookingStatusOk = false;
        			  // alert('Leeres BA-Ergebnis');
        		   }
        	   }
           });
	      });
        	if(bookingStatusOk){
        		  //console.log('STAAAAARRRRRTTTTIIIINNNNNGGGG!!!!!');
        		jQuery.each(theItems, function(i, val) {
                   jQuery.each(theItems[i], function(key, thisItem){
                	//   alert('storageField ' + key + ' ' + jQuery('#storageForm .' + key).attr('value') +  ', new value ' + thisItem);
                	   if(isNaN(key))
                	   key = key.toLowerCase();
                	  // alert('storageField old value ' + key + ' -- ' + jQuery('#storageForm').find('.' + key).attr('value')); 
                	 jQuery('#storageForm').find('.' + key).attr('value',thisItem);
                	
                	 
                   });
        	      });
        	}
	        
        	if(bookingStatusOk){
        		var theOffer = jQuery('#offerID').text();
        //		printJsonPResults(url,'ba-antwort','baContainer','baResultsWrapper','baResultContainer', theOffer);
/*****/
        		cleanJsonPResults('baContainer', 'baResultsWrapper', 'baResultContainer');
        		var container = 'baResultContainer'; 
        		var parentElementID = 'baResultContainer';
      	      var newParentElementID = "";
      	      var numItems = 0;
      	      
      	      //  iterate through Json   
                    
              jQuery.each(theItems, function(i, val) {
               //console.log(i);
              	numItems++;
                 newParentElementID = container + i;

                 // clone html container that displays the the data and give it a new ID.
                 jQuery('#' + parentElementID).clone(true).attr('id', newParentElementID).insertAfter(jQuery('#' + parentElementID));
                 
                 var text = ""; 
              // sort out items in the object
                 jQuery.each(theItems[i], function(key, thisItem){
              	   if(isNaN(key))
              	   key = key.toLowerCase();
              	   //console.log(key);
                  // check if item is an object  
                    if(thisItem != null && typeof(thisItem) == 'object'){
                  // check if item is a simple Array 
                      if(thisItem.constructor == Array){
                      //console.log('Array');
                        for(var i = 0; i < thisItem.length; i++){
      // TODO: separating by comma is not enough!                  
                          text += thisItem[i] + ", ";
                      // fill Array items into the container, separated by comma
                          jQuery('#'+ newParentElementID + ' .' + key).text(text);
                           jQuery('#'+ newParentElementID).show();
                        }
                      }
                  // or an embedded object
                      else {
                      // console.log('embedded object');
                        jQuery.each(thisItem, function(k, subItem){
                      	  if(isNaN(k))
                      	  k = k.toLowerCase();
                      	  // check if it is an img and set src of container img to src provided by Json	
                          if(jQuery('#'+ newParentElementID + ' .' + k).is('img')){
                          	jQuery('#'+ newParentElementID + ' .' + k).attr('src', 'http://cluster1.loc1.ffm.synaix.de' + subItem);
                          }
      	                else {
      	                	// set the text of the html element with the css-class provided by the key to the value
      	                    jQuery('#'+ newParentElementID + ' .' + k).text(subItem);
      	                    jQuery('#'+ newParentElementID).show();
      	                  }
                        });
                      }   
                    } 
                //  or a simple key/value pair
                    else {
                  	// check if it is an img and set src of container img to src provided by Json	
                      if(jQuery('#'+ newParentElementID + ' .' + key).is('img')){
                        jQuery('#'+ newParentElementID + ' .' + key).attr('src', 'http://cluster1.loc1.ffm.synaix.de' + thisItem);
                       //console.log('img');
                      }
                      else {
                      	// set the text of the html element with the css-class provided by the key to the value
                        jQuery('#'+ newParentElementID + ' .' + key).text(thisItem);
                        jQuery('#'+ newParentElementID).show();
                        //alert('key/value');
                      }
                    }
                 });
                  parentElementID = newParentElementID;
      	      });
              
      	      if(numItems == 0){
                // no items were returned - show error
      	    	  jQuery('#errorContainer').show();
      	    	  jQuery('#' + container).parent().parent().hide(); 
              }
      	      jQuery('#' + container).parent().parent().show();
            	
      // set the href of each link in the resultslists to an unique anchor
      // not sure we need this	      
      	 /*
      	      jQuery('.resultContainer').each(function(i){
      	    	  //console.log(jQuery(this).attr('id'));
      	    	  var num = Math.random();
      	    	  num = num * 10;
      	    	  jQuery(this).find('.priceContainer').attr('href', '#'+jQuery(this).attr('id') + num);
      	    	  jQuery(this).find('.priceContainer').attr('name', '#'+jQuery(this).attr('id') + num);
      	      });
      	   */   
      	    // hide parent container used to clone the others  
      	       jQuery('#' + container).hide();
      	       hideWaitAnimation();
      	    // do all kinds of stuff that is unique to this special IBE
      		      prettifyThis(item, theOffer);
      	     
      	 

/****/        		
        		//alert('setting flight dates ' + jQuery('#offerID').text());
	        	
	        	
	        	//console.log('removed checkAvailability');
	        	
	        	
	        	var theFormdata = jQuery('#storageForm').serialize(); 
	        	jQuery('#' + theOffer + ' .thisFormdata').text(theFormdata);
	        
	        	
	        	
	        } else {
	        	displayWaitAnimation();
	        	checkBookingStatus();
	        }
        }
        
	  });
}  

function doBA(thisOffer){
	displayWaitAnimation();
	jQuery('#storageForm #veranstaltercode').attr('value', jQuery(thisOffer).siblings('.veranstaltercode').text());
	jQuery('#myOperatorCode').text(jQuery(thisOffer).siblings('.veranstaltercode').text());
	//console.log(jQuery(thisOffer).siblings('.buchungsid').text());
	jQuery('#storageForm #buchungs-id').attr('value', jQuery(thisOffer).siblings('.buchungsid').text());
	var url = setUrl('buchungs-anfrage','storageFormContainer');
	//alert('doBA ' + url);
	//jQuery('#offerID').text('');
	url = trimUrlParams(url);
	jQuery('#offerID').text(jQuery(thisOffer).parents('.resultContainer').attr('id'));
	//console.log(jQuery('#offerID').text() + " -- " + jQuery(thisOffer).siblings('.buchungsid').text());
	setBookingStatus(url, 'ba-antwort',thisOffer);
	displayShoppingCart();
	//jQuery('#shoppingCartInput').attr('value', jQuery('#shoppingCartWrapper').html());
	
	
	
}
function trimUrlParams (url){
	var urlArray = url.split('&');
	url = urlArray[0] + '&';
	for(var i = 0; i < urlArray.length; i++){
		var theKey = urlArray[i].split('=');
		switch(theKey[0]){
			case 'alter-kind-1':
				url += urlArray[i] + '&';
				break;
			case 'alter-kind-2':
				url += urlArray[i] + '&';
				break;
			case 'alter-kind-3':
				url += urlArray[i] + '&';
				break;
			case 'anzahl-erwachsene':
				url += urlArray[i] + '&';
				break;
			case 'buchungs-id':
				url += urlArray[i] + '&';
				break;
			case 'iff-code':
				url += urlArray[i] + '&';
				break;
			case 'reiseart':
				url += urlArray[i] + '&';
				break;
			case 'start-datum':
				url += urlArray[i] + '&';
				break;
			case 'veranstaltercode':
				url += urlArray[i] + '&';
			break;
			case 'abflughafen':
				url += urlArray[i] + '&';
			break;
			case 'zielflughafen':
				url += urlArray[i] + '&';
				break;
		}
//    		
	}
	url += "format=jsonp&jsonp_callback=?";
	
	return url;

}
/**
 * shopping cart functions
 */
/**
 * assemble the data needed for display of shopping cart 
 * @return
 */
function populateShoppingCart(thisOffer){
	var cartId = jQuery('#shoppingCartWrapper').children('.resultContainer').attr('id');
	jQuery('#shoppingCartWrapper').find('.ratingsContainer').remove();
	jQuery('#shoppingCartWrapper').find('.noRatings').remove();
	var shoppingCartClone = jQuery('#shoppingCart').clone();
	jQuery('#' + cartId + ' .hotelNameContainer').siblings('#shoppingCart').remove();
	jQuery('#' + cartId + ' .hotelNameContainer').after(jQuery(shoppingCartClone));
	
	thisOffer = jQuery(thisOffer).find('.resultRow');
	var veranstalterName = jQuery(thisOffer).find('.veranstaltername').text();
	
	
	//console.log(jQuery('#storageForm #anzahl-erwachsene').attr('value'));
	jQuery("#shoppingCartTourOperator").text(veranstalterName);
	jQuery("#shoppingCartDuration").text(jQuery(thisOffer).find('.dauer').text() + " " + jQuery(thisOffer).find('.formatDay').text());
	var numAdults = jQuery('#storageForm #anzahl-erwachsene').attr('value');
	jQuery("#shoppingCartNumAdults").text(numAdults);
	if(numAdults == 1)
		jQuery("#shoppingCartAdults").text('Erwachsener');
	else
		jQuery("#shoppingCartAdults").text('Erwachsene');
	var numChildren = parseInt(getNumChildren(),10);
	jQuery("#shoppingCartNumChildren").text(', ' + numChildren); 
	if(numChildren == 0) {
		jQuery("#shoppingCartChildren").text('');
		jQuery("#shoppingCartNumChildren").text('');
	}
	if(numChildren == 1)
		jQuery("#shoppingCartChildren").text('Kind');
	if(numChildren > 1)
		jQuery("#shoppingCartChildren").text('Kinder');
	jQuery("#shoppingCartCatering").text(jQuery(thisOffer).find('.verpflegunglang').text());
	jQuery("#shoppingCartFlightInfo").text();
	jQuery("#shoppingCartDepartureAirport").text(); 
	jQuery("#shoppingCartDepartureDate").text();
	jQuery("#shoppingCartArrivalAirport").text(); 
	jQuery("#shoppingCartArrivalDate").text();
	
}
function fillBookingParams(){
	jQuery('#hotelResultContainer').css('min-height','180px');
	jQuery('#hotelResults *').each(function(){
		var theValue = "";
		var theClass = jQuery(this).attr('class');
		theClass = theClass.replace(/ valueStorage/, '');
		if(jQuery(this).attr('class').match(/thumbnail/)){
			theValue = jQuery(this).attr('src');
			
		}
		else
			theValue = jQuery(this).text();
		//console.log(theClass + " -- " + theValue);
		if(jQuery(this).attr('class').match(/flg/)){
			theValue = theValue.replace(/&gt\;/, '>');
			theValue = theValue.replace(/&lt\;/, '<');
			jQuery(this).html(theValue);
		}
		if(theValue != '' && theValue != undefined){
		theClass="." + theClass + ":first";
		//console.log(theClass + ' -- ' + theValue);
		
		jQuery('#storageForm').find(theClass).attr('value', theValue);
			
		}
	});
	
		
	
	jQuery('#storageForm *').each(function(){
		//console.log('name= ' + jQuery(this).attr('name') + ', value= ' + jQuery(this).attr('value') + ', class= ' + jQuery(this).attr('class'));
		//jQuery('#shoppingCartWrapper').hide();
	});
	//jQuery('#tpl_subheader').attr('value', jQuery('#shoppingCartWrapper .land').text() + "," + jQuery('#shoppingCartWrapper .region').text() + "," + jQuery('#shoppingCartWrapper .region').text() jQuery('#shoppingCartWrapper .ort').text());
}

var bookedOutOffersStorage = new Array();
function checkBookingStatus(){
	//console.log(jQuery('.ergebnis:eq(0)').text() + " - " + jQuery('#success').text());
	var thisOffer = '#' + jQuery('#offerID').text();
	var thisResult = jQuery('.ergebnis:eq(0)').text();
	//console.log('thisOffer ' + thisOffer);
	if(thisOffer.length > 1){
		//console.log('thisResult is ' + thisResult);
		if(parseInt(thisResult, 10) < 0){
			
			//bookedOutOffer = '.resultContainer #' + bookedOutOffer + ' .price'; 
			jQuery(thisOffer + ' .price').html('Leider ausgebucht');
			jQuery(thisOffer + ' .checkAvailability').remove();
			//alert('Ausgebucht - ' + thisOffer);
			hideWaitAnimation();
		} else {
			populateShoppingCart(thisOffer);
			
		}
		jQuery('.ergebnis:eq(0)').text('');
		setSubmitButton();
		prettifyDate('abflugDatum');
		prettifyDate('rueckflugDatum');
	}
}
function setTotalPrice(){
	var price = jQuery('#datePriceResultsWrapper #hotelResults .buchungspreis').text();
	var anzErw = jQuery('#anzahl-erwachsene').val();
	var anzKinder = getNumChildren();
	var einzelpreise = '';
	
	price = price.split(';');
	var last = price.length - 1;
	jQuery('.totalPrice').each(function(i){
		jQuery(this).html(price[last] + ' EUR');
	});
	
	if(price[0]!='') {
		var erw = 1;
		for (var r = 0;r < anzErw; r++) {
			einzelpreise += erw + '. Erwachsene: ' + price[r] + ' EUR<br/>';
			erw++;
		}
		if (anzKinder>0) {
			var kin= 1;
			for (var r = anzErw;r < (parseInt(anzErw)+parseInt(anzKinder)); r++)
{
				var aktPreis = '';
				aktPreis = (price[r] != '' ? price[r] : '0');
				einzelpreise += kin + '. Kind: ' + aktPreis + ' EUR<br/>';
				kin++;
			}
		}	
	}
	jQuery('.sepPrice').html(einzelpreise);
}

function fetchFlightDetails(){
	removeFlightDetailsFields();
	var url = jQuery('#myUrl').text();
	  
	  url = trimUrlParams(url);
	  //alert(url);
	//var url = setUrl('flugzeiten-anfrage','storageFormContainer');
	//jQuery(thisLink).attr('href', 'javascript:')
	//alert(url);
	printJsonPResults(url, 'gz-antwort', 'flightDetailsContainer', 'flightDetailsResultsWrapper', 'flightDetailsResultContainer') ;
}
  
function setFlightDetailsFields(){
	var addAfterMe = 'id_id';
	var theIndex = 0;
	var output = "";
	jQuery('#flightDetailsResultsWrapper .flightDetailsContainer').each(function(i){
		var thisID = jQuery(this).attr('id');
		
		jQuery('#' + thisID + ' td').each(function(){
			theIndex++;
			var theName = jQuery(this).attr('class');
			var theValue = jQuery(this).text();
			var theID = 'gz-field-id' + theIndex; 
			if(i > 0){
				jQuery('#' + addAfterMe)
				.after('<input type="hidden" name="gz_' 
						+ i + '_' 
						+ theName 
						+'" value="' + theValue 
						+'" class="gz-field" id="'
						+ theID + '" \/>');
				output += theName + i + ' = ' + theValue + ' und die ID ist ' + theID + ' \n ';
				addAfterMe = theID;
			}
		});
		//jQuery(this).after('<br class="clearBoth" \/>')	
	});
	//alert(output);
}
function removeFlightDetailsFields(){
	jQuery('.gz-field').remove();
}
function setSubmitButton(){
	jQuery('.storeBookingIDs').each(function(){
		var storedBookingID = jQuery(this).text();
		jQuery('.buchungsid').each(function(){
			//console.log(jQuery(this).text() + " -- " + storedBookingID);
			if(jQuery(this).text() != '' && jQuery(this).text() == storedBookingID){
				//console.log('setting submit button ' + jQuery(this).parents('.resultContainer').attr('id'));
				
				if(!jQuery(this).hasClass('submitThis')){
					jQuery(this).siblings('.checkAvailability').remove();
					jQuery(this).siblings('.submitThis').css('display','block');
				}
			}
		})
	});
}
function submitStorageForm(thisOffer){
	// Clickpfad setzen
	var str = jQuery(thisOffer).siblings('.thisFormdata').text();
	jQuery("#storageForm").deserialize(str);
	jQuery('#storageForm input').each(function(){
		if(jQuery(this).val() == 'false')
			jQuery(this).val('');
	});
	jQuery('#storageForm [name="link_cp1"]').val(jQuery('#clickpath #search a').attr("href"));
	jQuery('#storageForm [name="link_cp2"]').val(jQuery('#clickpath #regions a').attr("href"));
	jQuery('#storageForm [name="link_cp3"]').val(jQuery('#clickpath #hotel a').attr("href"));
	jQuery('#storageForm [name="link_cp4"]').val(window.location.href);
	
	document.storageForm.submit();
}
function prettifyDate(dateClass){
	jQuery('.' + dateClass).each(function(){
	var theDate = jQuery(this).text();
	if(theDate.length == 10 ){
		var dayName = new Date(theDate.replace(/\./g, '/'));
		dayName = dayName.getDayName(true);
		jQuery(this).text(dayName + '. ' + theDate);
	}
	});
}
function displayShoppingCart(){
	
	jQuery('#shoppingCartWrapper').show();
	jQuery('#shoppingCartWrapper').children().show();
	jQuery('#shoppingCartBottom').show();
}


function submitAjaxSearchForm(){
	if(jQuery('#ibeRegion').get(0).selectedIndex == 0) {
		document.forms['storageForm'].elements['anzahl-treffer-pro-seite'].value = 1000;
		document.forms['searchForm'].elements['anzahl-treffer-pro-seite'].value = 1000;
		jQuery('.clickpath').attr('href', '');
	//	jQuery('regionPager').show();
		//jQuery('#clickpathRegions').text(storeValuesForClickpath());
		fetchResults('regions-liste','regions','searchFormContainer', 'storageForm', true,'');
		var url = setUrl('regions-liste','storageFormContainer');
		jQuery('#clickpathRegions').attr("href", "javascript:fetchResults('regions-liste','regions','storageFormContainer','storageForm',false,'" + url + "','regionResults','regionResultContainer');resetIff();");
		jQuery('#clickpathRegions').css('cursor', 'pointer');
		jQuery('#storage-anzahl-treffer-pro-seite').attr('value', 20);
		//jQuery('#region').attr('href', 'fetchResults('regions-liste','regions','searchFormContainer', 'storageForm', true);')
	} else { 
		//console.log( jQuery('#numResultsHotel').get(0).value);
		if(jQuery('#storage-anzahl-treffer-pro-seite').attr('value') > 50){
			jQuery('#storage-anzahl-treffer-pro-seite').attr('value', 20);
		}
		jQuery('#storageForm #sortierung').attr('value','preis');
		//jQuery('#clickpathHotel').text(storeValuesForClickpath());
		
		fetchResults('hotel-angebote','hotels','searchFormContainer', 'storageForm', true,'');
		var url = setUrl('hotel-angebote','storageFormContainer');
		jQuery('#clickpathHotel').attr("href", "javascript:fetchResults('hotel-angebote','hotels','storageFormContainer','storageForm',false,'" + url + "','hotelResults','hotelResultContainer');resetIff();");
		jQuery('#clickpathHotel').css('cursor', 'pointer');
		
		jQuery('#numResultsHotel').attr('value', jQuery('#storage-anzahl-treffer-pro-seite').attr('value'));
	}
}
/*
 * Wait animation
 * 
 */

function displayWaitAnimation(){
	jQuery('#GrayOut').show();
    jQuery('#Popup').css('height','auto');
	  jQuery('#Popup').css('overflow-y','auto');
    jQuery('#InnerDimensions').show();
    jQuery('.close').css('right','4px');
    jQuery('#flightDetailsResultsWrapper').css('display','none');
    jQuery('.wrapper').addClass('waitAnimation');
    jQuery('.wrapper h2').show();
	//jQuery('body *').css('cursor', 'wait');
}
function hideWaitAnimation(){
    jQuery('#GrayOut').css('display','none');
    jQuery('#InnerDimensions').css('display','none');
    jQuery('.wrapper').removeClass('waitAnimation');
    jQuery('.wrapper h2').css('display','none');
    //jQuery('body *').css('cursor', '');
}


/**
 * clickpath functions - does not work yet
 * 
 */
function storeValuesForClickpath(){
	jQuery('#storageForm input').each(function(i){
		storedValuesForClickpath.push(jQuery(this).attr('value'));
	});
	for (var i = 0; i < storedValuesForClickpath.length; i++){
		//console.log(storedValuesForClickpath[i]);
	}
	return storedValuesForClickpath;
}

jQuery(document).ready(function($){
//$('#hotelResultsWrapper').load('fileadmin/templates/html/hotelResult.html');
//$('#regionResultsWrapper').load('fileadmin/templates/html/regionResult.html');
//$('#datePriceResultsWrapper').load('fileadmin/templates/html/datePrice.html');
//$('#shoppingCartInfoWrapper').load('fileadmin/templates/html/shoppingCart.html #shoppingCart');
$('#flightDetailsResultsWrapper').load('fileadmin/templates/html/flightDetails.html #flightDetailsResultContainer');
//$('#searchFormWrapper').load('hotelSearchForm.html');


$('#clickme').click(function(){
	printJsonPResults('http://192.168.1.213:8787/ibeservice/ibe/hotel-angebote.json?anzahl-treffer-pro-seite=10&region=350&reiseziel=10010&start-datum=16.03.2010&end-datum=05.04.2010&reise-dauer=1&anzahl-erwachsene=2&anzahl-kinder=0&alter-kind-1=&alter-kind-2=&alter-kind-3=&format=jsonp&jsonp_callback=?', 'offers', 'resultContainer', 'hotelResultContainer');
});

// History setzen
$.history.init(pageload);

//$("#ibe a.buttonSearch [@rel='history']").click(function(){
$("#ibe .buttonSearch").click(function(){
	submitSearchForm();
//	this.href = '#'+$('#searchForm').serialize();
//	$.history.load(this.href.replace(/^.*#/, ''));
	return false;
});
$("#ibe-search #searchButton").click(function(){
	$('#searchForm').submit();
	return false;
});
$("#ibe-search #searchButtonFilter").click(function(){
	$('#searchForm').submit();
	return false;
});
$('#search-form #searchButton').click(function(){
	$('#searchForm').submit();
	return false;
});
$('#search-form #searchButtonFilter').click(function(){
	$('#searchForm').submit();
	return false;
});



$('#clickpathRegions').click(function(){
		$('#clickpathHotel').attr('href', '');
		$('#clickpathHotel').css('cursor', 'text');
		$('#clickpathDatePrice').attr('href', '');
		$('#clickpathDatePrice').css('cursor', 'text');
	});
	$('#clickpathHotel').click(function(){
		$('#clickpathDatePrice').attr('href', '');
		$('#clickpathDatePrice').css('cursor', 'text');
		$('#shopingCartWrapper .priceContainer').hide();
	});
	
	
	
});
/**
* jQuery Deserialize Plugin 0.1
*
* Deserializes a string of data into a set of input elements. This plugin is the
* the antithesis of Ajax/serialize.
*
* Currently, a few form elements are not supported. They can/will be added as
* needed. Better yet, add support for them and I'll pull from and credit you!
*
*
* Usage
*
* $("form").deserialize(str);
*
* Copyright (c) Drew Yeaton (drew@sentineldesign.net)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*
* Contributors: sentineldesign
*
**/
jQuery.fn.deserialize = function(str) {
data = str.split("&");

for(i = 0; i < data.length; i++) {
pairs = data[i].split("=");
jQuery(this).find("[name='" + pairs[0] + "']").attr("value", jQuery.urlDecode(pairs[1]));
}
};

jQuery.urlDecode = function(str) {
if(!str) return false;

    var histogram = {}, histogram_r = {}, code = 0, str_tmp = [], search = "";
    var ret = str.toString();
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    histogram['!'] = '%21';
    histogram['%20'] = '+';
    
    for (replace in histogram) {
        search = histogram[replace]; // Switch order when decoding
        ret = replacer(search, replace, ret) // Custom replace. No regexing
    }
    
    ret = decodeURIComponent(ret);
 
    return ret;
};
