/* @group global functions */

  window.choice = window.choice || {};

  choice.is_ie6 = navigator.userAgent.toLowerCase().indexOf('msie 6') != -1;

/* @end */

/* @group global functions */

  function startLoginStatus(id){
    jQuery(id).append('<div class="loading-overlay" style="margin-left: -9999em;"><p><img src="/images/europe/shared/loader-big.gif" alt="" /></p></div>');
      jQuery('.loading-overlay').width(jQuery(id).width()+1);
      jQuery('.loading-overlay').css({top:jQuery(id).position().top-22});
      jQuery('.loading-overlay').height(jQuery(id).height()-10).css({ marginLeft: 0, left: 0, opacity: 0.01 }).fadeTo(500,0.8);
      jQuery('.loading-overlay p').css({ marginTop: (jQuery(window).scrollTop()-jQuery(id).position().top)+50 });
  }


  function startStatus(id, top){
    jQuery(id).append('<div class="loading-overlay" style="margin-left: -9999em;"><p><img src="/images/europe/shared/loader-big.gif" alt="" /></p></div>');
      jQuery('.loading-overlay').width(jQuery(id).width()+20);
      jQuery('.loading-overlay').css({top: (!top) ? jQuery(id).position().top : top });
      jQuery('.loading-overlay').height(jQuery(id).height()).css({ marginLeft: 0, opacity: 0.01 }).fadeTo(500,0.8);
      jQuery('.loading-overlay p').css({ marginTop: (jQuery(window).scrollTop()-jQuery(id).position().top)+50 });
  }
  function stopStatus(){
    jQuery('.loading-overlay').fadeOut(200, function(){
      jQuery(this).remove();
    });
  }

/* @end */

/* @group this.methods */

  this.attachShowMoreRooms = function() {
    //show more room types
    jQuery('.view-room-types').click(function() {
      if (navigator.appVersion.indexOf("MSIE 8.") != -1){
        jQuery(this).prev().find('tr.hidden').show();
      }else{
        jQuery(this).prev().find('tr.hidden').fadeIn();
      }
      jQuery(this).toggleClass('open');
      if (jQuery(this).hasClass('open')) {
              jQuery(this).html(msgHideMoreRooms);
      } else {
        jQuery(this).prev().find('tr.hidden').hide();
              jQuery(this).html(msgSeeMoreRooms);
      }
      return false; 
    });
  }

  this.attachEditDates = function() {
    jQuery(".edit-dates").click(function(){
      if(jQuery(this).parents(".room-dates").parent().hasClass("selected-room-dates")) {
        jQuery(this).parents(".room-dates").parent().removeClass("selected-room-dates").addClass("selected-cancel-dates");
      }return false;
    });
    jQuery(".cancel-dates").click(function(){
      if(jQuery(this).parents(".room-edit-dates").parent().hasClass("selected-cancel-dates")) {
        jQuery(this).parents(".room-edit-dates").parent().removeClass("selected-cancel-dates").addClass("selected-room-dates");
      }return false;
    });
  }

  this.tooltip = function(){	
    /* CONFIG */		
      xOffset = 40;
      yOffset = -20;		
      // these 2 variable determine popup's distance from the cursor
      // you might want to adjust to get the right result		
    /* END CONFIG */		
    jQuery("a.amenity").hover(function(e){											  
      this.t = this.title;
      this.title = "";									  
      jQuery("body").append("<p class='tooltip'><span></span>"+ this.t +"</p>");
      jQuery(".tooltip")
        .css("top",(e.pageY - xOffset) + "px")
        .css("left",(e.pageX + yOffset) + "px")
        .fadeIn("fast");		
      },
    function(){
      this.title = this.t;		
      jQuery(".tooltip").remove();
      });	
    jQuery("a.amenity").mousemove(function(e){
      jQuery(".tooltip")
        .css("top",(e.pageY - xOffset) + "px")
        .css("left",(e.pageX + yOffset) + "px");
    });			
  };

/* @end */

/* @group document.ready */

  jQuery(document).ready(function initializeChoiceHotels(){
    
    /* @group language dropdown */

      jQuery('.lang-select').click(function() {
        jQuery(this).next().toggle();
        jQuery(this).toggleClass('lang-open');
        return false;
      });
      
    /* @end */

    /* @group amenities tooltip */
      
      tooltip();
      
      jQuery('.resv-number-tooltip-children, .resv-number-tooltip-adults').hover(
        function () {
            jQuery(this).next().show();
            
          
            // new start
            jQuery(this).parent('.stack').css({'zIndex':'100','position':'relative'});
            //new end

            
        }, 
        function () {
          jQuery('.resv-number-info').hide();
          
          
          // new start
           jQuery(this).parent('.stack').attr('style','');
          //new end
           
          
        }
      );
      
      jQuery('#green_icon, #green_text').hover(
          function () {
              jQuery('.green-description').show();
              jQuery(this).parent('.stack').css({'zIndex':'100','position':'relative'});
          }, 
          function () {
            jQuery('.green-description').hide();
             jQuery(this).parent('.stack').attr('style','');
          }
        );
    
    /* @end */
        
    /* @group login dropdown */

      jQuery('.login-btn').click(function() {
        jQuery(this).next().toggle();
        jQuery(this).toggleClass('login-open');
        return false;
      });
    
    /* @end */

    /* @group input focus and blur */
    
      function switchText()
      {
        if (jQuery(this).val() == jQuery(this).attr('title')){
          jQuery(this).val('').removeClass('blur');
        }
        else if (jQuery.trim(jQuery(this).val()) == ''){
          jQuery(this).addClass('blur').val(jQuery(this).attr('title'));
          if (jQuery(this).attr('value') == 'dd/mm/yyyy'){
            jQuery(this).removeClass('blur');
          }
        }
      }

      /* 
        NEW CODE FROM VIGET, 2011-01-10
        Previous code had bad attribute selector
        jQuery('input[@type=text][title!=""]').each(function() {
      */
      jQuery('input[type=text][title!=""]').each(function() {
      /* END NEW CODE */

        if (jQuery.trim(jQuery(this).val()) == '') jQuery(this).val(jQuery(this).attr('title'));
        if (jQuery(this).val() == jQuery(this).attr('title')) jQuery(this).addClass('blur');
      }).focus(switchText).blur(switchText);
      
      //Questions/Input toggle
      jQuery("a.showInput").click(function(){
        jQuery(this).toggleClass("hide").next().toggleClass("hide");		
        return false; 
      });
      jQuery("a.hideInput").click(function(){
        jQuery(this).parent().parent().toggleClass("hide").prev().toggleClass("hide");
        return false; 
      });
      
    /* @end */

    /* @group reservation tabs */

      jQuery(".resv-tabs a.book-room-tab").click(function(){
        if (jQuery(this).parents(".aside-wrapper").hasClass("selected-view-resv")) {
          jQuery(this).parents(".aside-wrapper").removeClass("selected-view-resv").addClass("selected-book-room");
        }
      });
      
      jQuery(".resv-tabs a.view-resv-tab").click(function(){
        if (jQuery(this).parents(".aside-wrapper").hasClass("selected-book-room")) {
          jQuery(this).parents(".aside-wrapper").removeClass("selected-book-room").addClass("selected-view-resv");
        }
      });
      
      attachShowMoreRooms();
      attachEditDates();

    /* @end */

    /* @group toolbox */
    
      jQuery('.toolbox-close').click(function() {
          jQuery(this).parent().hide();
          return false;
        });

    /* @end */

    /* @group hide selects when an error overlaps on the checkout page */

	    if ( choice.is_ie6 ){

        jQuery('.second-field select').each(function(){

          var $select = jQuery(this),
            $previous_field = $select.parents('.second-field').prev(),
            $previous_close_link = $previous_field.find('.error-close'),
            error_exists_on_previous_field = $previous_close_link.length === 1;

          if ( error_exists_on_previous_field ) {
            $select.hide();
            $previous_close_link.bind('click', function(){
              $select.show();
            });
          }

        });  

      }

    /* @end */

  });

/* @end */

/* @group calendar */

  CHICalendar=Class.create();
  Object.extend(CHICalendar.prototype,{initialize:function(id, fid, forinput, frominput, isCheckout){
    this.id=id;
    this.fid=fid.slice(0, fid.length-4);
    this.forinput=forinput;
    this.frominput=frominput;
    this.isCheckout=isCheckout=='true'?true:false;
    this.date = null;
    this.firststart = true;
    this.isVisible = false;
    if($(this.forinput).value!=''){
      $(this.fid+'calendar1').component.selectDate($(this.forinput).value, true);
      $(this.fid+'calendar2').component.selectDate($(this.forinput).value, true);
      this.date = $(this.fid+'calendar1').component.getSelectedDate();
      $(this.fid+'calendar1').component.currentDate = this.date;
      $(this.fid+'calendar2').component.currentDate = this.date;
      $(this.fid+'calendar1').component.nextMonth();
      $(this.fid+'calendar1').component.prevMonth();
      $(this.fid+'calendar2').component.nextMonth();
    }
    $(this.fid+'calendar1').component.params.isDayEnabled = isCalendarDayEnabled;
    $(this.fid+'calendar2').component.params.isDayEnabled = isCalendarDayEnabled;
    $(this.fid+'calendar1').component.params.frominput = frominput;
    $(this.fid+'calendar2').component.params.frominput = frominput;
    $(this.fid+'calendar1').component.render();
    $(this.fid+'calendar2').component.render();
    this.shouldSendEvent=true;
    this.checkDate();
    this.collapse = this.doCollapseCalendar.bindAsEventListener(this);
    this.show = this.show.bindAsEventListener(this);
    Event.observe($(this.forinput),'focus', this.show, false);
    Event.observe($(this.fid+'ico'),'click', this.show, false);
  //	Event.observe($(this.forinput),'change', function(){alert(0)}, false);
    if(this.isCheckout){
      this.checkinDateSelected = this.checkinDateSelected.bindAsEventListener(this);
      Event.observe(document,'checkin:date:selected', this.checkinDateSelected, false);
    }
  },

  checkinDateSelected:function(e){
    if (!e) var e = window.event;
    var dt = new Date(e.memo.date);
    dt.setDate(dt.getDate()+1);
    if(dt>=this.date && eval(this.frominput+".forinput")==e.memo.forinput){
      $(this.fid+'calendar1').component.selectDate(dt, true);
    }else{
      $(this.fid+'calendar1').component.render();
    }
  },

  checkDate:function(){
    if(this.frominput && this.frominput!=null && this.frominput!=''){
      var fromdate = eval(this.frominput+".date");
      if(fromdate>=this.date){
        var dt = new Date(fromdate);
        dt.setDate(dt.getDate()+1);
        $(this.fid+'calendar1').component.selectDate(dt, true);
      }else{
        if(this.isCheckout){
          $(this.fid+'calendar1').component.render();
        }
      }
    }
  },

  move:function(){
    Richfaces.Calendar.clonePosition($(this.fid+'group'), $(this.forinput));
    $(this.fid+'group').style.top = parseInt($(this.fid+'group').style.top)+$(this.forinput).getDimensions().height+'px';
  },

  cumulativeOffset:function() {
    element = $(this.forinput);
      var valueT = 0, valueL = 0;
      do {
          valueT += element.scrollTop  || 0;
          valueL += element.scrollLeft || 0;
        element = element.parentNode;
      } while (element && element != document.body);
      return Element._returnOffset(valueL, valueT);
  },

  doCollapseCalendar:function(e){
    if (!e) var e = window.event;
    var tg = (window.event) ? e.srcElement : e.target;
    if(tg.id == this.forinput || tg.id == (this.fid+'ico')){
      return;
    }

    /* Uncomment me to watch the different values in different browsers!
    This bug is mentioned here:
    https://prototype.lighthouseapp.com/projects/8886/tickets/857-cumulativeoffset-inconsistent-in-ie
    
    alert( Position.cumulativeOffset( $(this.fid+'grid') )[0] + ' ' +
           Position.cumulativeOffset( $(this.fid+'grid') )[1] + ' ' +
           Element.getDimensions( $(this.fid+'grid') ).width + ' ' +
           Element.getDimensions( $(this.fid+'grid') ).height
        );
    */ 
    
    // we use a DOM method to get the element, because jQuery doesn't like the name:name:name ID treatment
    var $elem      = jQuery( document.getElementById( this.fid+'grid' ) ),
    
        // use jQuery's offset to get the correct offset
        offset     = $elem.offset(),
        leftEdge   = offset.left,
        rightEdge  = leftEdge + $elem.width(),
        topEdge    = offset.top,
        bottomEdge = topEdge + $elem.height(),
        
        // check the event position against our edges
        within     = ( ( Event.pointerX(e) > leftEdge   ) &&
                       ( Event.pointerX(e) < rightEdge  ) &&      
                       ( Event.pointerY(e) > topEdge    ) &&      
                       ( Event.pointerY(e) < bottomEdge ) );      
      
    if ( !within ){
     this.hide();
    }
  },

  /* original code
  doCollapseCalendar:function(e){
    if (!e) var e = window.event;
    var tg = (window.event) ? e.srcElement : e.target;
    if(tg.id == this.forinput || tg.id == (this.fid+'ico')){
      return;
    }
    if (!Position.within($(this.fid+'grid'), Event.pointerX ( e), Event.pointerY(e))){
      this.hide();
    }
  },
  */

  hide:function(){
    $(this.fid+'group').style.display = 'none';
    this.isVisible = false;
    Event.stopObserving(window.document,'click', this.collapse, false);
    
  },

  show:function(){
    if(this.firststart){
      this.move();
  //		$(this.fid+'calendar2').component.nextMonth();
    }
  //	this.checkDate();
  //	$(this.fid+'calendar1').component.showSelectedDate();
  //	$(this.fid+'calendar2').component.showSelectedDate();
  //	$(this.fid+'calendar2').component.nextMonth();
    $(this.fid+'header1').innerHTML=$(this.fid+'calendar1').component.getCurrentMonth(true)+" "+$(this.fid+'calendar1').component.getCurrentYear();
    $(this.fid+'header2').innerHTML=$(this.fid+'calendar2').component.getCurrentMonth(true)+" "+$(this.fid+'calendar2').component.getCurrentYear();

    // CHSSEAM-516 fix. Grow function Overloaded
      Effect.Grow = function(C) {
          C = $(C);
          var B = Object.extend({direction:"center",moveTransition:Effect.Transitions.sinoidal,scaleTransition:Effect.Transitions.sinoidal,opacityTransition:Effect.Transitions.full}, arguments[1] || {});

          var A = {top:C.style.top,left:C.style.left,height:C.style.height,width:C.style.width,opacity:C.style.opacity};
          var G = C.getDimensions();
          var H,F;
          var E,D;
          switch (B.direction) {case"top-left":H = F = E = D = 0;
              break;
              case"top-right":H = G.width;
                  F = D = 0;
                  E = -G.width;
                  break;
              case"bottom-left":H = E = 0;
                  F = G.height;
                  D = -G.height;
                  break;
              case"bottom-right":H = G.width;
                  F = G.height;
                  E = -G.width;
                  D = -G.height;
                  break;
              case"center":H = G.width / 2;
                  F = G.height / 2;
                  E = -G.width / 2;
                  D = -G.height / 2;
                  break
          }
          return new Effect.Move(C, {x:H,y:F,duration:0.01,beforeSetup:function(I) {
              I.element.hide().makeClipping().makePositioned()
          },afterFinishInternal:function(I) {
              new Effect.Parallel([new Effect.Opacity(I.element, {sync:true,to:1,from:0,transition:B.opacityTransition}),new Effect.Move(I.element, {x:E,y:D,sync:true,transition:B.moveTransition}),new Effect.Scale(I.element, 100, {scaleMode:{originalHeight:G.height,originalWidth:G.width},sync:true,scaleFrom:window.opera ? 1 : 0,transition:B.scaleTransition,restoreAfterFinish:true})], Object.extend({beforeSetup:function(J) {
                  J.effects[0].element.setStyle({height:"0px"}).show()
              },afterFinishInternal:function(J) {
                  J.effects[0].element.undoClipping().undoPositioned().setStyle(A)
              }}, B))
          }})
      };
    Effect.Grow(this.fid+'group',{direction: 'top-left', duration: 0.8});
    if(this.firststart){
      this.firststart = false;
    }
    this.isVisible = true;
    Event.observe(window.document,'click', this.collapse, false);

  },

  toggle:function(){
    if(this.isVisible){
      this.hide();
    }else{
      this.show();
    }
  },

  selectdate:function(e){
    if (!e) var e = window.event;
    $(this.forinput).value=Richfaces.Calendar.formatDate(e.rich.date, e.rich.component.params.datePattern);
    this.hide();
    this.date = e.rich.date;
    if(e.rich.component.id==this.fid+'calendar1'){

      if(!this.isCheckout){
        document.fire("checkin:date:selected", { date: e.rich.date, forinput: this.forinput });
      }
      $(this.fid+'calendar2').component.selectDate($(this.forinput).value, false);
      $(this.fid+'calendar2').component.render();
      $(this.fid+'calendar2').component.nextMonth();
    }else{
      $(this.fid+'calendar1').component.selectDate($(this.forinput).value, false);
      $(this.fid+'calendar1').component.render();
    }
    
    this.hide();
  },

  switchmonth:function(np){
    if(np){
      $(this.fid+'calendar1').component.nextMonth();
      $(this.fid+'calendar2').component.nextMonth();
    }else{
      $(this.fid+'calendar1').component.prevMonth();
      $(this.fid+'calendar2').component.prevMonth();
    }
    $(this.fid+'header1').innerHTML=$(this.fid+'calendar1').component.getCurrentMonth(true)+" "+$(this.fid+'calendar1').component.getCurrentYear();
    $(this.fid+'header2').innerHTML=$(this.fid+'calendar2').component.getCurrentMonth(true)+" "+$(this.fid+'calendar2').component.getCurrentYear();
  }
  });

  function isCalendarDayEnabled(dataobj){
    var today = new Date();
    today.setDate(today.getDate()-1);
    if(this.frominput && this.frominput!=null && this.frominput!=''){
      var fromdate = eval(this.frominput+".date");
      if(fromdate>today){
        today=new Date(fromdate);
        today.setDate(today.getDate()+1);
      }
    }
    
    if(dataobj.date < today){
      return false;
    }else{
      return true;
    }
  }

  function getCalendarStyle(dataobj){
    var today = new Date();
    today.setDate(today.getDate()-1);

    if(this.frominput && this.frominput!=null && this.frominput!=''){
      var fromdate = eval(this.frominput+".date");
      
      if(fromdate>today){
        today=new Date(fromdate);
        today.setDate(today.getDate()+1);
      }
    }
    if(dataobj.date < today){
      return "rich-calendar-cell-disabled";
    }else{
      return "rich-calendar-cell";
    }
  }

/* @end */

/* @group theme info */

  function onNoneThemeSelect(evt) {
    if (evt.checked == false && getCheckedThemesCount() == 0) {
      evt.checked = true;
    }
    var ch = $('themesList').getElementsByTagName('input');
    for (var i in ch) {
      if (ch[i].className != 'noneTheme') 
      ch[i].checked = false;
    }
  }

  function getCheckedThemesCount() {
    var ch = $('themesList').getElementsByTagName('input');
    var c=0;
    for (var i in ch) {
      if (ch[i].className != 'noneTheme' && ch[i].checked == true)
        c++;
    }	
    return c;
  }

  function onThemeSelect (evt) {
    if (evt.checked == true) {
      jQuery("input.noneTheme").attr('checked',false);
    }else if(getCheckedThemesCount() == 0) {
      jQuery("input.noneTheme").attr('checked',true);
    }
  }

/* @end */

/* @group popups and awards */

  function popUpWindow(url,name) {
    newWindow = window.open(url,name,'toolbar=0,location=0,directories=0,status=0,menubar=1,scrollbars=yes,resizable=yes,width=640,height=480');
  }

  function showAward(level, hasAward) {
    if (hasAward == null || hasAward != "true"){
      return;
    }
    if (level == "GOLD"){
      popUpAwardWindow('/goldaward','Award');
    } else if (level == "PLAT"){
      popUpAwardWindow('/platinumaward','Award');
    }
  }	
  function popUpAwardWindow(url,name){
    window.name = "main";
    var awardWin=window.open(url,name,'toolbar=no,location=0,directories=0,status=0,scrollbars=no,resizable=no,width=550,height=400,top=300,left=400');
    awardWin.focus(); 
  }
  function closeAwardWindow(url){
    window.open (url,"main");
    self.close();
  }

/* @end */


