$(document).ready(function(){
  externalLinks();
  if ( $('#moment').length ) Moment();
  if ( $('#newsletterCompleteForm').length ) CompleteNewsletterSubscription();
  if ( $('.article').length ) ImageSlideshow();
  // Audio and Video Downloadlinks in richText
  if ( $('#facebooklike').length ) $.getScript('http://static.ak.fbcdn.net/connect.php/js/FB.Share');
  // Orderlist Progressive Disclosure in B2B
  if ( $('#orderlist') ) orderlist();
  HeaderClaim();
  HeaderInfo();
  StatusCookies();
  Contest();
  Newsletter();
  Quickbook();
  eventAdaptions();
  if( $('#hrs-hotel-search').length > 0 ) {initHRSPage();}
  if( $('#hotel').length > 0 ) {initHRSQuickbook();}
  $('#faq').faq();
  $('#b2b-body').b2b();
});

function externalLinks () {
  $('a[rel="extern"]').removeAttr('rel').attr('target', '_blank');
  $('a.relextern').removeClass('relextern').attr('target', '_blank');
}

function HeaderClaim () {
  var claimImage  = $('#headerMain').find('.headline-replace').find('img:hidden');
  if (! claimImage.length ) return;
  
  var logo = claimImage.prev('img').hide(),
      link = claimImage.parent()
  ;
  
  link
  .bind('mouseenter.HeaderClaim focus.HeaderClaim', function(event) {
    logo.hide();
    claimImage.show();
  })
  .bind('mouseleave.HeaderClaim blur.HeaderClaim', function(event) {
    logo.show();
    if ( event.type == 'blur' ) {
      setTimeout(function() {claimImage.hide();}, 500);
    } else {
      claimImage.hide();
    }
  })
  ;
      
  var inititalTimeout = setTimeout(function() {
    claimImage.fadeIn(500, function() {
      var claimTimeout = setTimeout(function() {
        claimImage.fadeOut(800, function() {
          logo.fadeIn(500);
        });
      }, 4000);
    });
  }, 200);
}

// Orderlist Progressive Disclosure in B2B
function orderlist () {
  var orderlist = $('#orderlist'),
      catHeadings = orderlist.find('h2')
  ;
  if ( catHeadings.length < 2 || orderlist.hasClass('error') ) return;
  // close all lists
  orderlist.find('ul').hide();
  
  // go through all headings
  catHeadings.each(function() {
    var heading = $(this),
        link = heading.wrapInner('<a href="#"></a>').children('a'),
        list = heading.next('ul'),
        listitemCount = list.children('li').length
    ;
    
    // add count to heading
    link.prepend('<span>'+listitemCount+' '+lang['pieces']+'</span>');
    
    // add clickhandler
    link.click(function() {
      list.slideToggle(300, function() {
        heading.toggleClass('open');
      });
      return false;
    });
    
  });
}

function Moment () {
  var moment  = $('#moment').parent(),
      overlay = $('#momentOverlay'),
      playPause = $('<a href="#" id="playPause">'+lang['pause']+'</a>').insertBefore(overlay)
  ;
  
  play();
  playPause.click(function() {
    if ( $(this).hasClass('paused') ) {
      play();
      $(this).removeClass('paused').text(lang['pause']);
    } else {
      pause();
      $(this).addClass('paused').text(lang['play']);
    }
    return false;
  });
  moment.click(function(event) {
    if ( $(event.target).is('a') ) return true;
    window.location = overlay.find('a').attr('href');
  });
  
  overlay.find('a')
  .focus(overlayShow)
  .blur(overlayHide)
  ;
  
  function overlayShow () {
    if ( overlay.hasClass('gone') ) {
      if ( $.browser.msie ) {
        overlay.show().removeClass('gone');
      } else {
        overlay.fadeTo(0,0).removeClass('gone').fadeTo(150,1);
      }
    }
  }
  
  function overlayHide () {
    if ( $.browser.msie ) {
      overlay.hide().addClass('gone');
    } else {
      overlay.fadeTo(150,0).addClass('gone');
    }
  }
  
  function pause () {
    overlayShow();
    moment.unbind('mouseenter mouseleave');
    overlay.find('a').unbind('focus blur');
  }
  
  function play () {
    overlayHide();
    
    moment
    .mouseenter(overlayShow)
    .mouseleave(overlayHide)
    ;
    
    overlay.find('a')
    .focus(overlayShow)
    .blur(overlayHide)
    ;
  }
}

function HeaderInfo() {
	if (! $('#headerCopyright').length ) return;
	
	var img       = $('#headerMain').children('img'),
	    copyright = $('#headerCopyright'),
	    info      = $('#headerInfo'),
	    infoLink  = info.find('a'),
	    hideTimeout;
	
	img.attr('aria-describedby', 'headerInfoInner');	
	copyright.bind('mouseenter focus', showInfo);
	info.mouseenter(stopHide).add(copyright).mouseleave(hideInfo);
	
	if ( infoLink.length ) {
	  infoLink.blur(hideInfo);
	} else {
	  copyright.blur(hideInfo);
	}
	
	function showInfo () {
	  clearTimeout(hideTimeout);
	  if ( info.hasClass('hidden') ) info.hide().removeClass('hidden').fadeIn(300);
	}
	
	function hideInfo() {
	  hideTimeout = setTimeout(function() {
	    info.fadeOut(500, function() {
  			info.addClass('hidden').show();
  		});
	  }, 100);
	}	  
	
	function stopHide () {
	  clearTimeout(hideTimeout);
	}
}

function StatusCookies (where) {
  var parent = where || '#mainContent';
  
  var statusMsg = readCookie('statusmsg');
  if (! statusMsg ) return;
  statusMsg = decodeURIComponent(statusMsg);
  
  // strip ""
  if ( statusMsg.charAt(0) == '"' &&  statusMsg.charAt(statusMsg.length-1) == '"' ) {
	statusMsg = statusMsg.substring(1, statusMsg.length-1);
  }
  
  // add or update message
  if (! $('#statusmsg').length ) {
    $(parent).prepend('<div id="statusmsg" class="archived"><p>'+statusMsg+'</p></div>');
  }
  else {
	  $(parent).find('#statusmsg p').html(statusMsg);
  }
  
  eraseCookie('statusmsg');
}

function Contest () {
  if (! $('#field_get_newsletter_0').length ) return;
  
  var getNewsletter = $('#field_get_newsletter_0');
  var newsletterLang = $('#newsletterLang');
  
  if (! $('#field_get_newsletter_0:checked').length ) newsletterLang.hide();
  
  getNewsletter.click(function() {
    newsletterLang.toggle();
  });
}

function Newsletter () {
  if (! $('.newsletterReg')[0] ) return;
  
  var fieldsToCheck = $('#email, #country, #german, #accept_privacy_statement');
  var valid = true;
  var errors = [];
  
  $('#newsletterForm').submit(function() {
    removeErrMsgs();
    validateEmpty(fieldsToCheck);
    validateEmail($('#email'));    
    
    if ( errors.length ) insertErrSummary();
      
    return valid;
  });
  
  // Validates if given fields are not empty
  function validateEmpty (fields) {
    fields.each(function() {
      if (! isFilled(this) ) {
        valid = false;
        addError(this);
        insertErrMsg(this);
      }
    });
  }
  
  // Validates if given fields are email address
  function validateEmail (fields) {
    fields.each(function() {
      if (! isEmail(this) ) {
        valid = false;
        addError(this, 'email');
        insertErrMsg(this, lang['error']+lang['errorEmail']);
      }
    });
  }
  
  // Is the field not empty?
  function isFilled (field) {
    if ( isOption (field) ) {
      return (fieldPlusOptions(field).filter(':checked').length);
    } else {
      return ($(field).val() == '' ? false : true);
    }
  }
  
  // Is the string in the field a valid email address?
  function isEmail (field) {
    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    return (filter.test($(field).val()));
  }
  
  // Add the error to the Errors Array so that we can use it in the Error Summary Box
  function addError (field, type) {
    var type = type || 'filled';
    
    if ( isOption(field) ) {
      errors.push($(field).attr('id')+','+getLabelText($(field).parents('fieldset').find('legend'))+': '+lang['errorOneOption']);
    } else {
      var message = lang['errorRequired'];

      if ( type == 'email' ) {
        message = lang['errorEmail'];
      }
      
      errors.push($(field).attr('id')+','+getLabelText($(field).prev('label'))+': '+message);
    }
  }
  
  // Insert the error message into the field's label
  function insertErrMsg (field, msg) {
    var msg = msg || lang['error']+lang['errorRequired'];
    
    if ( isOption (field) ) {
      msg =  lang['error']+lang['errorOneOption'];
    }
    
    fieldPlusOptions(field).prev('label').append(' <em>'+msg+'</em>').parent().addClass('error');
  }
  
  // Insert the Error Summary Box at the top
  function insertErrSummary () {
    $('p.margin').after('<div class="errors"><h2>'+lang['error']+'('+errors.length+')</h2><ul></ul></div>');
    $.each(errors, function() {
      var errorDetails = this.split(',');
      $('.errors ul').append('<li><a href="#'+errorDetails[0]+'">'+errorDetails[1]+'</a></li>');
    });
  }
  
  // Remove everything Error related so we have a clean form again
  function removeErrMsgs () {
    valid = true;
    errors = [];
    $('.errors').remove();
    fieldsToCheck.each(function() {
      fieldPlusOptions(this).parent().removeClass('error').find('label em').remove();
    });
  }
  
  // Is the field of type checkbox or Radio?
  function isOption (field) {
    return ($(field).attr('type') == 'radio' || $(field).attr('type') == 'checkbox');
  }
  
  /* If isOption(field): Returns all fields with the same name
     If ! isOption(field): Returns the field */
  function fieldPlusOptions (field) {
    if ( isOption(field) ) {
      var fieldName = $(field).attr('name');
      return $('input[name="'+fieldName+'"]');
    } else {
      return $(field);
    }
  }
  
  // Returns only the text of the label without any added <em> or <span>
  function getLabelText (field) {
    var fieldCopy = field.clone();
    fieldCopy.find('em, span').remove();
    
    return (fieldCopy.text());
  }
}

function CompleteNewsletterSubscription() {
  var nlcForm = $('#newsletterCompleteForm');
  nlcForm.hide();
  if ( nlcForm.length ) {
	var action = nlcForm.attr('action');
	var formdata = nlcForm.serialize();
	$.ajax({
	  type: 'GET',
	  url: action,
	  data: formdata,
	  dataType: 'html',
	  success: function(data, textStatus) {}
	});
	nlcForm.remove();
  }
}

function ImageSlideshow() {
	if (! $('#galleryShow')[0] ) return;
	
	var gallery = $('#galleryShow .imageGallery'),
	    slideshow = $('#galleryShow .imageSlideshow'),
	
	    list = new LinkedList(),
	    slides = slideshow.find('.image'),
	    thumbs = gallery.find('.galleryImage'),
	    slideNav = $('#slideNav'),
	    prevLink = $('#slideNavBack'),
	    nextLink = $('#slideNavForward'),
	    galleryLink = $('#slideNavUp'),
	    currentPage,
	    pages,
	    current = new Object(),
	    gallerySize
	;	
	initialize();
	
	function initialize(gallerySize, slideIndex) {
	  currentPage = 1;
	  gallerySize = gallerySize || 9;
	  pages = Math.ceil(thumbs.length / gallerySize);
	  
	  var slideIndex = slideIndex || 0,
	      topMargin = parseInt(slides.eq(0).css('margin-top'), 10),
	      slideNavHeight = slideNav.height()
	  ;
	  if ( slideshow.is(':hidden') ) {
	    slideshow.show();
	    slideNavHeight = slideNav.height();
	    slideshow.hide();
	  } 
	  var galleryShowWidth = $('#galleryShow').width(),
	      slidePage = 1
	  ;
  	// add some properties to each slide object
  	slides.each(function(i){
  	  el = $(this);
  		this.image = el.children('img');
  		
  		// save all styles for the link
  		el.add(slideshow).addClass('hidden').show();
  		this.prevLinkStyle = {'width': this.image.attr('width')/2+'px',
  				      'height': this.image.attr('height')+'px',
  				      'top': slideNavHeight+topMargin+'px'
  												};
  		this.prevLinkStyle[lang['left']] = (galleryShowWidth - this.image.attr('width'))/2+'px';
  		
  		this.nextLinkStyle = {'width': this.image.attr('width')/2,
  				      'height': this.image.attr('height'),
  				      'top': slideNavHeight+topMargin
  				     };
  		this.nextLinkStyle[lang['left']] = galleryShowWidth/2;
      el.add(slideshow).hide().removeClass('hidden');
      
  		this.page = slidePage;
  		if ( ((i+1) % gallerySize) == 0 ) slidePage+=1;
  		
  		// add this slide to the linked list
  		list.append(this);
  	});
	
  	var thumbsPage = 1;
  	thumbs.each(function(i){
  	  $(this)
  	    .addClass('page'+thumbsPage)
  		  .children('a').click(function(){
    			showSlideshow(i);
    			return false;
    		})
    	;
  		if ( ((i+1) % gallerySize) == 0 ) thumbsPage+=1;
  	});
  	
  	nextLink.children('span').addClass('hidden');
  	nextLink.click(function(){
  		nextSlide();
  		return false;
  	});
  	
  	prevLink.children('span').addClass('hidden');
  	prevLink.click(function(){
  		prevSlide();
  		return false;
  	});
  	
  	galleryLink.click(function(){
  		showGallery(currentPage);
  		return false;
  	});
  	
  	insertPagination();
  	current = list.first;
	
	  if (gallery.css('display') == 'block') {
      showGallery(currentPage, 0);
    } else {
      showSlideshow(slideIndex, 0);
    }
	}
	
	function insertPagination() {
	  if ( pages==1 ) return;
	  
	  var content = '<p class="hidden">'+lang['gotoPage']+'</p><ul id="galleryPagination" class="clearfix">';
	  for ( i=0; i<pages; i++ ) {
	    var page = i+1;
	    if ( page == currentPage) {
	      content += '<li><span>'+page+'</span></li>';
	    } else {
	      content += '<li><a href="#">'+page+'</a></li>';
	    }
	  }
	  content += '</ul>';
	  gallery.append(content);
	  updatePagination();
	}
	
	function updatePagination() {
	  var pagination = $('#galleryPagination');
	  
	  $('li', pagination).each(function(i) {
	    var page = i+1;
	    if ( page == currentPage) {
	      $(this).html('<span>'+page+'</span>');
	    } else {
	      $(this).html('<a href="#">'+page+'</a>');
	      $('a', this).click(function() {
	        showGallery(page);
	        return false;
	      });
	    }
	  });
	}
	
	function setLinks() {
		prevLink.css(current.prevLinkStyle);
		nextLink.css(current.nextLinkStyle);
		nextLink.next = current.next;
		prevLink.prev = current.prev;
	}
	
	function nextSlide() {
		current = current.next;
		currentPage = current.page;
		changeSlide(current.prev, nextLink);
	}
	
	function prevSlide() {
		current = current.prev;
		currentPage = current.page;
		changeSlide(current.next, prevLink);
	}
	
	function changeSlide(oldSlide,link) {
	  link.hide();
	  $(oldSlide).fadeTo(500, 0, function(){
			$(current).fadeIn(500, function(){
				link.show();
			});
			if ( list.length > 1 ) {
			  $(oldSlide).hide().fadeTo(0,1);
			} else {
			  $(current).fadeTo(500, 1);
			}
		});
		setLinks();
	}
	
	function showSlideshow(i, time) {
	  var time = time ? time : 500;
	  
		current = list.at(i);
		$(slides).hide();
		$(current).show();
		gallery.fadeTo(time, 0, function(){
			slideshow.fadeIn(time);
			gallery.hide().fadeTo(0,1);
		});
		setLinks();
	}
	
	function showGallery(page, time) {
	  var time = time ? time : 500;
	  var page = page ? page : currentPage;
	  var toHide = gallery.is(':hidden') ? slideshow : gallery;
	  currentPage = page;
	  
		toHide.fadeOut(time, function() {
		  updatePagination();
		  $('.galleryImage', gallery).hide();
	    $('.page' + page, gallery).show();
			gallery.fadeIn(time);
		});
		setLinks();
	}
}

function Quickbook() {
  if (! $('#quickbook').length ) return;
  
	// Tabs
	$('#quickbook > ul').show();
	$('#hotel > h3, #event > h3').addClass('hidden');
	var default_view = $('#quickbook').attr('class');
	if (default_view == 'hotel') {
	  $('#hotelListitem').addClass('state-active');
	  $('#event').addClass('tabs-hide');
	}
	else {
	  $('#eventListitem').addClass('state-active');
	  $('#hotel').addClass('tabs-hide');
	}
        
        $('#hrs-quickbook').attr('target', '_blank');
	
	$('#hotelListitem a, #eventListitem a').click(function() {
		$('#hotel, #event').toggleClass('tabs-hide');
		$('#hotelListitem, #eventListitem').toggleClass('state-active');
		return false;
	});
	
	// update hidden field for hrs
	$('#quickbook-hrs-dateformat').val( getHRSDateFormat() );
	
	var endDateOptionsHotel = datepickerOptions({
				      beforeShow: customRange,
				      dateFormat: getHRSDateFormat()
				  });
	
	var startDateOptionsEvent = datepickerOptions({
					minDate: 0,
					setDate: new Date(),
					onSelect: function( dateText, inst ) {
					  var date2 = $("#from").datepicker('getDate', '+3d'); 
					      date2.setDate( date2.getDate() + 3 );
					  $('#to').datepicker('setDate', date2 );
				        }
				    });
	
	var	endDateOptionsEvent 	= datepickerOptions({
					    beforeShow: customRange
					  });
        
	// Give Common options to all Datepickers
	var startDateOptionsHotel = datepickerOptions({
	  minDate: 0,
          dateFormat: getHRSDateFormat(),
	  onSelect: function(dateText, inst) {
		var date2 = $("#arrival").datepicker('getDate', '+1d'); 
		    date2.setDate( date2.getDate() + 1 ); 
                $('#departure').datepicker('setDate', date2 );
          }
        });

	// Datepicker Hotel	
	$("#arrival")
	  .attr('title', getHRSDateFormat())
	  .datepicker(startDateOptionsHotel)
	  .datepicker('setDate', new Date());
	  
        $('#departure')
	  .attr('title', getHRSDateFormat())
	  .datepicker(endDateOptionsHotel)
	  .datepicker('setDate', +1);

        $('#ui-datepicker-div').hide();

	// Datepicker Event
	$("#from").datepicker(startDateOptionsEvent).datepicker('setDate', new Date());
        $('#to').datepicker(endDateOptionsEvent).datepicker('setDate', +3);
}

function eventAdaptions () {
  var host = window.location.hostname;
  // if we arent on events.wien.info => return
  if ( host != 'events.wien.info' ) return;
  
  // Repair the toplink here
  $('.toplink a').click(function() {
    window.location = window.location + '#skiplinks';
    return false;
  });
  
  // if the user is not logged in => return
  if (! readCookie('user') ) return;
    
  // Remove Login Links to myVienna because they don't work anyway
  $('#serviceNav .loginLogout').remove();
  $('#myviennaLoginRegister').remove();
  TopNavigation.positionLanguageMenu();
}

/* --- Datepicker Helperfunctions --- */

// Set Datepicker Options
function datepickerOptions(options) {
  var domain = '';
  if (window.location.hostname.match(/events|hotels/) != null) {
	domain = 'http://www.wien.info';
  }
  var generalOptions = {
		duration: 'fast',
		constrainInput: true,
		showOn: 'both',
		buttonText: lang['chooseDate'],
		buttonImage: domain + '/++resource++wir/img/iconCalendar.png',
		buttonImageOnly: true
	};
	
	return $.extend(generalOptions, options);
}

// Intitialize Dates on Datepickers if the input fields are empty
function initDates (start, end, difference) {
  // 3 days is the default difference between start and end dates
  difference = difference || 3;
  
  if (start.val() == '') {
    start.datepicker('setDate', new Date());
  }
  if ( end.val() == '' ) {
    end.datepicker('setDate', +difference);
  }
}

function resetEnd() {
  // Hotel Quickbook
  if ( this.id == "arrival") {
    if ($(this).datepicker('getDate') >= $('#departure').datepicker('getDate')) {
	    $('#departure').datepicker('setDate', 0);
	  }
	// Event Quickbook
  } else if ( this.id == "from" ) {
    if ($(this).datepicker('getDate') > $('#to').datepicker('getDate')) {
	    $('#to').datepicker('setDate', 0);
	  }
	// Hotelsearch
  } else if ( this.id == "hotelArrival" ) {
    if ($(this).datepicker('getDate') >= $('#hotelDeparture').datepicker('getDate')) {
	    $('#hotelDeparture').datepicker('setDate', 0);
	  }
  // Eventsearch
  } else if ( this.id == "eventFrom" ) {
    if ($(this).datepicker('getDate') > $('#eventTo').datepicker('getDate')) {
	    $('#eventTo').datepicker('setDate', 0);
	  }
	// Hotelbooking
  } else if ( this.id == "bookingArrival" ) {
    if ($(this).datepicker('getDate') >= $('#bookingDeparture').datepicker('getDate')) {
	    $('#bookingDeparture').datepicker('setDate', 0);
	  }
  }
}

function customRange() {
	var myDate = new Date();
	
	if (this.id == 'departure') {
		myDate = $('#arrival').datepicker('getDate');
		if (myDate == null) myDate = new Date();
		myDate.setDate(myDate.getDate()+1);
	} else if (this.id == 'to') {
		myDate = $('#from').datepicker('getDate');
		if (myDate == null) myDate = new Date();
	} else if (this.id == 'hotelDeparture') {
		myDate = $('#hotelArrival').datepicker('getDate');
		if (myDate == null) myDate = new Date();
		myDate.setDate(myDate.getDate()+1);
	} else if (this.id == 'eventTo') {
		myDate = $('#eventFrom').datepicker('getDate');
		if (myDate == null) myDate = new Date();
	}
	else if (this.id == 'bookingDeparture') {
		myDate = $('#bookingArrival').datepicker('getDate');
		if (myDate == null) myDate = new Date();
		myDate.setDate(myDate.getDate()+1);
	}
	
  return {minDate: myDate};
}

/* --- A Linked List --- */

function LinkedList() {}
LinkedList.prototype = {
  length: 0,
  first: null,
  last: null
};

LinkedList.prototype.append = function(node) {
  if (this.first === null) {
    node.prev = node;
    node.next = node;
    this.first = node;
    this.last = node;
  } else {
    node.prev = this.last;
    node.next = this.first;
    this.first.prev = node;
    this.last.next = node;
    this.last = node;
  }
  this.length++;
};

LinkedList.prototype.at = function(i) {
  if (!(i >= 0 && i < this.length)) {return null;}
  var node = this.first;
  while (i--) {node = node.next;}
  return node;
};

LinkedList.prototype.each = function(fn) {
  var node = this.first, n = this.length;
  for (var i = 0; i < n; i++) {
    fn(node, i);
    node = node.next;
  }
};

/* --- Delete Value on Focus --- */

function deleteContent (field, content) {
  if ( field.val() == content ) {
    field.removeClass('hint').val('');
  }
}

function restoreContent (field, content) {
  if ( field.val() == '') {
    field.addClass('hint').val(content);
  }
}

/* --- Cookie Helpers --- */

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/; domain="+getCookieDomain();
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function getCookieDomain() {
  var domain = window.location.hostname;
  var parts = domain.split('.');
  var num = parts.length;
  
  if ( num > 1 ) {
    if ( num == 4 ) {
      if ( domain.match(/\d+.\d+.\d+.\d+/) ) {
        return domain;
      }
    }
    for (var i=0; i<num-2; i++) {
      parts.shift();
    }
    domain = '.' + parts.join('.');
  }
  return domain;
}



            
function addJumper() {
  $('#hrs-hotel-search').find('#starjump').bind('click', function( event ) {
    $('#stars').addClass('highlight');
  });
            
}
function initHRSPage() {
    
    initHRSTabs();
    initDatepicker();
    addAria();
    addJumper();
    
    // Open Results in new window
    $('#hrs-hotel-search').attr('target', '_blank');
    
    // On Submit - perform Check
    $('#hrs-hotel-search .submit').bind('click', function(event) {
        var submit = validateHRSForm();        
        if(!submit) {event.preventDefault();} else {return true;}
    });
    
    // HRS-VALIDATION FOLLOWING
    // Function to valdidate the HRWS-Form
    function validateHRSForm() {
        var $form = $('#hrs-hotel-search'),
        $f_from = $form.find('#hrs-date-from'),
        $f_to = $form.find('#hrs-date-to'),
        $f_room_s = $form.find('#hotels_room_s'),
        $f_room_d = $form.find('#hotels_room_d'),
        $f_adults = $form.find('#adults'),
        $f_children_count = $form.find('#select-children-count'),
        $submit = $form.find('.submit');                
                
        var val_adults = parseInt($f_adults.val()),
        val_room_s = parseInt($f_room_s.val()),
        val_room_d = parseInt($f_room_d.val()),
        val_children = parseInt($f_children_count.val()),
        errorcount = 0;
        
        if(!val_room_d) {val_room_d = 0;$f_room_d.val('0');}
        if(!val_room_s) {val_room_s = 0;$f_room_s.val('0');}
        if(!val_adults) {val_adults = 0;$f_adults.val('0');}
        
        removeAllErrors();
                
        var ERROR_LAYER = lang['hrs_error_layer'],
        ERROR_AGE       = lang['hrs_error_age'],
        ERROR_ADULTS    = lang['hrs_error_adults'],
        ERROR_ROOMS2    = lang['hrs_error_rooms2'],
        ERROR_ROOMS     = lang['hrs_error_rooms'];        
       
        var $bs_error = $('<div id="errlist" class="errors"><ul></ul></div>');
                
        // Validations                 
        if( val_adults == 0 || !val_adults )    
            {addErrorToField($f_adults, ERROR_ADULTS);}
                
        if(!val_room_s && !val_room_d) 
            {addErrorToField($f_room_s, ERROR_ROOMS2);addErrorToField($f_room_d, ERROR_ROOMS2, true);}            
        
        if(val_adults > val_room_s + val_room_d * 2) 
            {addErrorToField($f_adults, ERROR_ROOMS);}  
            
            if(val_children > val_room_d * 2) 
            {addErrorToField($submit, ERROR_LAYER);}    
            
        if(val_adults > 6) 
            {addErrorToField($submit, ERROR_LAYER);}
        
        // Children Validation
        var $children_age_obj = $('.hrs-children-age-select');    
        
        $children_age_obj.change(function() {
            var $parent = $(this).parent().parent();
            if( $(this).val() != 0 )   {$parent.removeClass('children_error');$(this).parent().removeClass('error');}
            else {$parent.addClass('children_error');}
        });
        
        $.each($children_age_obj, function() {               
            if( $(this).val() == 0 || !$(this).val() ) {
                $(this).parent().parent().addClass('children_error');
                addErrorToField( $(this) , ERROR_AGE);                
                errorcount++;
            }
        });                
        
        
        // Helper Functions                
        function addErrorToField($field, message, hide) {  
            errorcount++;
            $submit_wrapper = $('#submit-wrapper');
        
            if( $field.attr('type') != 'submit' ) {
                                
                $('<li>').attr('id', 'errorid_' + $field.attr('name')).html( '<label for="'+$field.attr('id')+'">' +  $('label[for='+$field.attr('id')+']').text() + '</label>: ' + message ).appendTo( $bs_error.find('ul') );
                $field.attr('aria-labelledby', 'errorid_' + $field.attr('name')).attr('aria-invalid', 'true').parent('div').addClass('error');
                $bs_error.insertBefore($submit_wrapper);
                $bs_error.find('label:first').focus();
                
            } else {
                
                removeAllErrors();
                
                var $image = $('<img>').attr('src', '/++resource++wir/img/hrs-dialog-corner.png').addClass('corner');
                var $close = $('<a>').attr('href', '#').addClass('closelink').text('x').bind('click', function(event) {
                    $('.hrs-dialog').remove();
                    event.preventDefault();                
                });
            
                var $submit_wrapper = $('#submit-wrapper');

                var $error = $('<div>').addClass('hrs-error hrs-dialog')
                .html(message);                                   
                                       
                $close.prependTo($error);                        
                $image.appendTo($error);                    
                $error.appendTo($submit_wrapper);
            
                $error.css( {
                    'bottom' : parseInt($submit_wrapper.find('button.submit').outerHeight() + 35 ) + 'px',
                    'right' : parseInt($submit_wrapper.find('button.submit').outerWidth() / 2 - 60 ) + 'px'
                });
                
                $('.hrs-dialog').find('a.closelink').focus();
            }  
        }
        
        if( errorcount > 0 ) {
            return false;
        } else {
            return true;
        }
    }
    
    function removeAllErrors(settings) {
        $('#errlist').remove();
        $('.error').removeClass('error');
        
        $('.children_error').removeClass('children_error');
        $('input').removeAttr('aria-labelledby').removeAttr('aria-invalid');
    }    
            
    function handleHRSChildren($element) {
        $('#hrs-children-wrap').remove();
                    
        var $element = $(this),
        child_count = $element.val(),                    
        $wrapper = $('<div class="subfield clearfix"><div class="subfield_prefix"><span></span></div>'),                    
        $children_age = $('<div class="subfield_age"><label for="hrs_cs">'+lang['hrs_age']+'</label><select class="hrs-children-age-select" id="hrs_cs" name="childAccomodations[0].age"></select></div>'),
        $children_bed = $('<div class="subfield_bed"><label for="hrs_cbe">'+lang['hrs_beds']+'</label>'+
                          '<select class="hrs-children-bed-select" id="hrs_cbe" name="childAccomodations[0].accomodation">'+
                          '<option value="1">'+lang['hrs_parent_bed']+'</option>'+
                          '<option value="0">'+lang['hrs_add_bed']+'</option>'+
                          '<option value="2">'+lang['hrs_ownroom']+'</option>'+
                          '</select></div>');
                    
        for(i=0;i<=17;i++) {
            $('<option value="'+i+'">'+i+'</option>').appendTo($children_age.find('select'));
        }
                     
        $children_age.appendTo($wrapper);
        $children_bed.appendTo($wrapper);
        $('#hrs-room-settings').after('<div id="hrs-children-wrap">');                     
                     
        for(i=1; i<=child_count; i++) {
            
            $wrapper.find('.subfield_bed').find('label').attr('for', 'select-children-count_bed_' + i);
            $wrapper.find('.subfield_age').find('label').attr('for', 'select-children-count_age_' + i);
            
            $wrapper.find('.subfield_bed').find('select').attr('id', 'select-children-count_bed_' + i);
            $wrapper.find('.subfield_age').find('select').attr('id', 'select-children-count_age_' + i);
            
            $wrapper.find('.subfield_bed').find('label').attr('for', 'select-children-count_bed_' + i);
            $wrapper.find('.subfield_age').find('label').attr('for', 'select-children-count_age_' + i);
            
            $wrapper.find('div.subfield_prefix span').html('<img src="/++resource++wir/img/hrs_children.png" alt="" />');
            
            $wrapper.find('#hrs_cs').attr('name', 'childAccomodations['+parseInt(i-1)+'].age');
            $wrapper.find('#hrs_cbe').attr('name', 'childAccomodations['+parseInt(i-1)+'].accomodation');
            
            $wrapper.find('select').eq(0).attr('name', 'childAccomodations['+parseInt(i-1)+'].age');
            $wrapper.find('select').eq(1).attr('name', 'childAccomodations['+parseInt(i-1)+'].accomodation');
            
            $wrapper.clone().appendTo('#hrs-children-wrap');            
        }
        
        $('#hrs-children-wrap').find('select:first').focus();
    }


    // Do not count adults any more, if there is a changed value
    var adults_buff = 0;
    $('#adults').focus(function() {
        adults_buff = $(this).val();
    }).bind('blur', function() {
       if(adults_buff != $(this).val() ) {$(this).addClass('changed');}
    }).bind('keyup', function() {
        if( val_s > 0 && val_d > 0 && $(this).val > 0 ) {removeAllErrors();}
    });

    // Count up the adults automatic
    $('#hotels_room_d, #hotels_room_s').bind('keyup', function() {
        if( !$('#adults').hasClass('changed') ) {
            var $room_s = $('#hotels_room_s'),
            $room_d = $('#hotels_room_d'),
            adults;
        
            if( $(this).length > 0 ) {
                removeAllErrors();
            }            
            var val_s = $room_s.val() == false ? 0 : parseInt($room_s.val());
            var val_d = $room_d.val() == false ? 0 : parseInt($room_d.val()) * 2; 
        
            adults =  val_s + val_d;
            if(adults && adults > 0) {            
                $('#adults').val(adults);
            } 
        }      
    });    
            

    
    // Default - Hide all Tabs
    function initHRSTabs() {
        $('.hrs-hotel-list').addClass('hrs-hidelist');
        $('.hrs-hotel-list:first').addClass('hrs-showlist').removeClass('hrs-hidelist');

        // Handle the HRS-Tabs    
        $('#hrs-tabs a').bind('click', function(event) {
            var $all = $('#hrs-tabs a'),
            index = $all.index($(this)) + 1;

            $('#hrs-tabs').find('.active').removeClass('active');
            $(this).parent().addClass('active');
            $('.hrs-showlist').removeClass('hrs-showlist').addClass('hrs-hidelist');
            $('#hrs-hotel-list-'+index).removeClass('hrs-hidelist').addClass('hrs-showlist');

            event.preventDefault();
        });
    } 

    // Helper
    function addAria() {
        $('#hrs-date-from, #hrs-date-to, #adults').attr('aria-required', 'true');
    }

    function initDatepicker() {
        $('#select-children-count').bind('change', handleHRSChildren );
        
        $('#hrs-date-from')
	  .val( new Date() )
	  .attr('title', getHRSDateFormat())
	  .datepicker({
            minDate: new Date(),
            dateFormat: getHRSDateFormat(),
            onSelect: function(dateText, inst) {
                var d = $.datepicker.parseDate(getHRSDateFormat(), dateText );
                $('#hrs-date-to').datepicker( "option", "minDate", new Date(d) );

                // Add 1 Day and reinit 2nd Datepicker
                var nd =  new Date(d.getFullYear(), d.getMonth(),  d.getDate() + 1);
                var nd_p = $.datepicker.formatDate(getHRSDateFormat(), nd);
                $('#hrs-date-to').val(nd_p);
            }
	  })
	  .datepicker('setDate', new Date());

        $('#hrs-date-to')
	  .attr('title', getHRSDateFormat())
	  .datepicker({
	      minDate: new Date(),
	      dateFormat: getHRSDateFormat(),
	      onSelect: function(dateText, inst) {
		  $('#hrs-date-from').datepicker( "option", "maxDate", new Date( $.datepicker.parseDate(getHRSDateFormat(), dateText ) ) );
	      }
	  })
	  .datepicker('setDate' , +1);

        // Enable Click for Icons
        $('#date-from-icon').click(function(event) {
            $('#hrs-date-from').focus();
            event.preventDefault();
        });         

        $('#date-to-icon').click(function(event) {
            $('#hrs-date-to').focus();
            event.preventDefault();
        });
        }
}


function initHRSQuickbook() {        
    $('#hrs-qb-select').change(function() {          
        switch($(this).val()) {
            case '1':$('#hrs-qb-sr').val('1').removeClass('hidden');$('#hrs-qb-dr').addClass('hidden').val('0');break;
            case '2':$('#hrs-qb-dr').val('1').removeClass('hidden');$('#hrs-qb-sr').addClass('hidden').val('0');break;
        }   
    });
    
    $('#hrs-qb-hotelsubmit').click(function() {
        var adults = $('#hrs-qb-dr').val()*2 + $('#hrs-qb-sr').val();
        $('#hrs-qb-adults').val(adults);
    });
    
}

$.fn.faq = function() {
/*
    this plugins adds event-handlers to given headlines,
    wraps all following elements to a container and
    toggles this container
*/

    if( !this.length ) return this;
    
    var o = {
        heading : 'h2',
        slidespeed : 300,
        getSource: function( $trigger ) {
            return $trigger.find('.richText')
        }
    }
    
    return this.each(function() {
        var $trigger = $(this),
            $children = o.getSource( $trigger ).children(),
            $headings = $children.filter( o.heading );
            
            $headings
            .wrapInner( '<a href="#"></a>' )
            .each(function() {
               var $this = $(this),
                   $ch = $this;
                   
               if(  $ch.is( o.heading ) ) {
		
		    // check if jquery supports the nextUntil function - else use the fallback
		    if( $.fn.hasOwnProperty('nextUntil') ) {
		      $('<div class="faq-container"></div>').wrapInner( $ch.nextUntil( o.heading ) ).insertAfter( $ch );
		    } else {
		      var $container = $('<div class="faq-container"></div>'),
			  $nextAll = $ch.nextAll();
                        
                      $nextAll.each(function() {
                           var $this = $(this);                           
                           if( !$this.is( o.heading ) )                                 
                                $container.append($this);
                           else
                                return false;
                      });
		      $container.insertAfter( $ch );
		    }

                    $ch
                    .bind('toggle.faq', function( ev ) {                                    
                        var $this = $(this),
                            $next = $this.next('div');
                            
                            if( $next.hasClass('open') )
                                $this.trigger('close', $next).removeClass('open');
                            else
                                $this.trigger('open', $next).addClass('open');
                    })
                    .bind('click.faq', function( ev ) {
                        $(this).trigger('toggle');
                        ev.preventDefault();    
                    })
                    .bind('open.faq', function( ev, $next ) {
                        $next = $($next);
                        $next.stop(true, true).slideDown(o.slidespeed, function() { $(this).addClass('open') })
                    })
                    .bind('close.faq', function( ev, $next ) {
                        $next = $($next);
                        $next.stop(true, true).slideUp(o.slidespeed, function() { $(this).removeClass('open') })
                    })                                
               }
            });
    });            
}

// Wrapper for b2b page
$.fn.b2b = function() {
  if( !this.length ) return this
  
  return this.each(function() {
    var $body = $(this),    
	$article = $body.find('.article'),
	$b2bnews = $article.filter('.b2b_news');
    
    /* Create dialog from content */    
    // create button
    var $button = $('<div id="b2bnews-link-wrap"><a href="#">'+lang['copytext']+'</a></div>');
    $button.find('a').elementToDialog({ 'base': $article,
			      'dialog': { 'dialogClass': 'article',
					  'width': 655
					}
			   })
           .end()
	   .prependTo( $b2bnews.find('h1').parent() );
  });
}

/* b2b article to dialog */
$.fn.elementToDialog = function( options ) {
  if( !this.length ) return this
  
  var o = $.extend({
      base: false,
      // function to get the content
      getContent: false,
      getTitle: function() {
	return $('h1').clone().find('span').remove().end().text();
      },
      // some processing functions for content
      processContent: function( $content ) {
	var $wrap = $('<div id="mainContent"></div>'),
	    $newcontent = $content;
	    
	$('<div class="article"></div>').appendTo($wrap);
	$newcontent.clone(true).appendTo( $wrap.find('div') );	
	$newcontent = $wrap;
	
	$newcontent.find('#b2b-copy-button, #serviceBar, .verticalImagebar, img, .htmlBlock, #audioCast, #videoCast, .imageBlock, .imageSlideshow, #galleryShow')
		    .remove()
	          .end()
		  .find('.richText')
		    .removeClass('slim');
	
	return $newcontent
      },
      dialog: false
    }, options);
  
  return this.each(function() {
    var $trigger = $(this),
	$content = o.base || o.getContent(),
	title = o.getTitle();
    
    if( $.isFunction( o.processContent ) ) { $content = o.processContent( $content ); }
    
    $trigger.bind('click.elementToDialog', function( ev ) {
      $content.clone(true).dialog( $.extend(o.dialog,
					    {'title': title,
					     'close': function() { $('.ui-dialog').remove() }
					    })
				 );
      ev.preventDefault();
    });
    
  })
}

function getHRSDateFormat() {
  switch( $('html').attr('lang') ) {
    case 'de': df = 'dd.mm.y';
      break;
    case 'ru': df = 'dd.mm.y';
      break;
    case 'hu': df = 'yy.mm.dd.';
      break;
    case 'pl': df = 'yy-mm-dd';
      break;
    case 'cs': df = 'd.m.y';
      break;
    case 'ja': df = 'd/m/y';
      break;
    default: df = 'dd/mm/y';
  }
  return df;
}

