function widthInIeEight()
{
    var xScroll, yScroll;
    if (window.innerHeight && window.scrollMaxY) {
        xScroll = document.body.scrollWidth;
        yScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
        xScroll = document.body.scrollWidth;
        yScroll = document.body.scrollHeight;
    } else if (document.documentElement && document.documentElement.scrollHeight > document.documentElement.offsetHeight){ // Explorer 6 strict mode
        xScroll = document.documentElement.scrollWidth;
        yScroll = document.documentElement.scrollHeight;
    } else { // Explorer Mac...would also work in Mozilla and Safari
        xScroll = document.body.offsetWidth;
        yScroll = document.body.offsetHeight;
    }

    if (self.innerHeight) { // all except Explorer
        windowWidth = self.innerWidth;
        windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
    }

    // for small pages with total height less then height of the viewport
    if(yScroll < windowHeight){
        pageHeight = windowHeight;
    } else {
        pageHeight = yScroll;
    }

    // for small pages with total width less then width of the viewport 
    if(xScroll < windowWidth){
        pageWidth = windowWidth;
    } else {
        pageWidth = xScroll;
    }

    var scrollTop = ($(document).scrollTop());
    var scrollLeft = ($(document).scrollLeft());
    var scrollBottom = pageHeight-scrollTop-windowHeight;

    if ( (scrollTop>0) || (scrollBottom>0) )
    {
        var jPageWidth = pageWidth;
    }
    else
    {
        var jPageWidth = pageWidth-21;
    }
    return jPageWidth;
}

function fixPNG(element)
{
    if (/MSIE (5\.5|6).+Win/.test(navigator.userAgent))
    {
        var src;
        if (element.tagName=='IMG')
        {
            if (/\.png$/.test(element.src))
            {
                src = element.src;
                element.src = "../images/blank.gif";
            }
        }
        else
        {
            src = element.currentStyle.backgroundImage.match(/url\("(.+\.png)"\)/i);
            if (src)
            {
                src = src[1];
                element.runtimeStyle.backgroundImage="none";
            }
        }
        if (src)
            element.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='scale')";
    }
}

function clearinputvalue(id)
{
    var currentInput = document.getElementById(id);
    var additionalInput = document.getElementById(id+'_comp');
    if( currentInput.value ==  additionalInput.innerHTML )
    {
        currentInput.value = '';
    }
}

function setinputvalue(id)
{
    var currentInput = document.getElementById(id);
    var additionalInput = document.getElementById(id+'_comp');
    if( currentInput.value ==  '' )
    {
        currentInput.value = additionalInput.innerHTML;
    }
}

function changeSlide(currentIndex, tempIndex)
{
    var gallaryItems = $('div.images-container').find('div.hotel_image');
    var pagePositionOfHidden = currentIndex+1;
    var pagePositionOfVisible = tempIndex+1;
    var hideimageidarray =$('.imageposition_'+pagePositionOfHidden).attr('id').split('_');
    var showimageidarray =$('.imageposition_'+pagePositionOfVisible).attr('id').split('_');

    if( hideimageidarray[1] != showimageidarray[1] )
    {
        $('.hotel_'+hideimageidarray[1]).removeClass('selected-hotel');
        $('.hotel_'+showimageidarray[1]).addClass('selected-hotel');
    }

    if(hideimageidarray[2] != showimageidarray[2])
    {
        $('#gallerypart_'+hideimageidarray[1]+'_'+hideimageidarray[2]).removeClass('selected-part');
        $('#gallerypart_'+showimageidarray[1]+'_'+showimageidarray[2]).addClass('selected-part');
    }

    var imageSource = $(gallaryItems[currentIndex]).find('img').attr('src');
    $('div.images-container').css({'backgroundImage':'url("'+imageSource+'")', 'backgroundPosition':'left top' });
    $(gallaryItems[currentIndex]).hide();
    $(gallaryItems[tempIndex]).fadeIn(2500);
    $('.image_caption').text($(gallaryItems[tempIndex]).find('.current_image_caption').text());

}

$(document).ready(function(){
    $('.pageloading').remove();

    $('.choose_area').change(function(){
      //** Arrays on arrea
      var allhotels = new Array ('Tilal Liwa Hotel','Danat Jebel Dhanna Resort','Al Raha Beach Hotel','Dhafra Beach Hotel', 'Sands Hotel')
      var jebel_dhanna = new Array('Danat Jebel Dhanna Resort', 'Dhafra Beach Hotel');
      var abu_dhabi = new Array('Al Raha Beach Hotel', 'Sands Hotel');
      var al_gharbia = new Array('Tilal Liwa Hotel');
      var selectedlist = new Array();

      $('.choose_hotel').empty();

      if( $(this).attr('value') == '' )
      {
        $('.choose_hotel').append('<option value=""></option>');
        $('.choose_hotel').append('<option value="AUHTIL">Tilal Liwa Hotel</option>');
        $('.choose_hotel').append('<option value="AUHDR">Danat Jebel Dhanna Resort</option>');
        $('.choose_hotel').append('<option value="AUHAR">Al Raha Beach Hotel</option>');
        $('.choose_hotel').append('<option value="AUHBEA">Dhafra Beach Hotel</option>');
        $('.choose_hotel').append('<option value="15911">Sands Hotel</option>');
      }
      else if( $(this).attr('value') == 'Jebel Dhanna')
      {
        $('.choose_hotel').append('<option value=""></option>');
        $('.choose_hotel').append('<option value="AUHDR">Danat Jebel Dhanna Resort</option>');
        $('.choose_hotel').append('<option value="AUHBEA">Dhafra Beach Hotel</option>');
      }
      else if($(this).attr('value') == 'Abu Dhabi')
      {
        $('.choose_hotel').append('<option value=""></option>');
        $('.choose_hotel').append('<option value="AUHAR">Al Raha Beach Hotel</option>');
        $('.choose_hotel').append('<option value="15911">Sands Hotel</option>');
      }
      else if($(this).attr('value') == 'Al Gharbia')
      {
        $('.choose_hotel').append('<option value=""></option>');
        $('.choose_hotel').append('<option value="AUHTIL">Tilal Liwa Hotel</option>');
      }

    });

    $('.choose_hotel').change(function(){
      //**Arrays on hotelname
      var danat_jebel_dhanna = 'Jebel Dhanna';
      var dhafra_beach_hotel = 'Jebel Dhanna';
      var al_raha_beach_hotel = 'Abu Dhabi';
      var sands_hotel = 'Abu Dhabi';
      var tilal_liwa_hotel = 'Al Gharbia';
      var selectedlist = new Array();

      if( $(this).attr('value') == '' )
      {
        selectedlist = '';
      }
      else if( $(this).attr('value') == 'AUHTIL')
      {
        selectedlist = tilal_liwa_hotel;
      }
      else if( $(this).attr('value') == 'AUHDR')
      {
        selectedlist = danat_jebel_dhanna;
      }
      else if($(this).attr('value') == 'AUHAR')
      {
        selectedlist = al_raha_beach_hotel;
      }
      else if($(this).attr('value') == '15911')
      {
        selectedlist = sands_hotel;
      }
      else if($(this).attr('value') == 'AUHBEA')
      {
        selectedlist = dhafra_beach_hotel;
      }

      $('.choose_area option').each(function(){
          if( $(this).attr('value')==selectedlist )
          {
              $(this).attr('selected', 'selected');
          }
      });
    });

    //****** Promoblocks code
    $('.promoitem_title').hover(
        function(){
            var currentOnhoverPromo = $(this).parent().parent().parent().parent().parent();
            var parentId = currentOnhoverPromo.attr('id');
            var promoContainer = currentOnhoverPromo.parent();
            promoContainer.stopTime('promoslide');
            promoContainer.oneTime(250, 'promoslide',function(){
                promoContainer.find('.promoitem').each(function(){
                    if($(this).attr('id') == parentId)
                    {
                        $(this).find('.promoitem_title').addClass('opened_promo');
                        $(this).find('.promoheight').animate({'height': 128}, 500);
                    }
                    else
                    {
                        if( $(this).find('.promoitem_title').hasClass('opened_promo') )
                        {
                            $(this).find('.promoheight').animate({'height': 29}, 500,function(){
                                $(this).find('.promoitem_title').removeClass('opened_promo');
                            });
                        }
                    }
                });
            });
        },
        function(){
            var currentOnhoverPromo = $(this).parent().parent().parent().parent().parent();
            var parentId = currentOnhoverPromo.attr('id');
            var promoContainer = currentOnhoverPromo.parent();
            promoContainer.stopTime('promoslide');
        }
    );

    //****** Photo gallary code
    $('.gallery-hotel-title').click(function(){
        $(this).parent().find('.parts_block').slideToggle();
    });

    //****** Quick reservation code
    $('.hotel_checkin, .hotel_checkout').focus(function(){
        $('.choose_hights').focus();
        $('#quick_reservation_form table.selections').hide(); //for IE 6
        $('#block_with_calendars').show();
    });

    $('.close_date_selection').click(function(){
      $('#block_with_calendars').hide();
      $('#quick_reservation_form table.selections').show();//for IE 6
   });

   $('#quick_reservation_form .input_button_lb').click(function(){
       if( ($('.choose_hotel').attr('value') == 'AUHDR') ||
           ($('.choose_hotel').attr('value') == 'AUHAR')  )
       {
           $('#quick_reservation_form').attr('action', 'https://www.phgsecure.com/IBE/bookingRedirect.ashx');
           $('#quick_reservation_form').attr('method', 'GET');
           $('#quick_reservation_form').attr('target', '_blank');
           $('.choose_hotel').attr('name', 'propertyCode');
           $('.hotel_checkin').attr('name', 'arrivalDate');
           $('.hotel_checkout').attr('name', 'departureDate');
           $('.choose_hights').attr('name', 'numberOfNights');
           $('.choose_rooms').attr('name', 'numberOfRooms');
           $('.choose_adults').attr('name', 'numberOfAdults');
           $('.choose_children').attr('name', 'numberOfChildren');
           if( ( $('.choose_hotel').attr('value') == '' )||( $('.hotel_checkin').attr('value') == 'MM/DD/YY' )||( $('.hotel_checkout').attr('value') == 'MM/DD/YY' )||( $('.choose_area').attr('value') == '' ) )
           {
               alert('All fields are required!')
           }
           else
           {
             var s=s_gi('thaydanathotels');
             var selected_hotel_name = '';
             $(".choose_hotel option:selected").each(function (i, selected) {
                selected_hotel_name = $(selected).text();
             });

             s.linkTrackVars='prop1,eVar1,events';
             s.events='event1';
             s.prop1= '' + selected_hotel_name + ' Reservation Widget';
             s.eVar1= '' + selected_hotel_name + ' Reservation Widget';
             s.tl(this, 'o', '' + selected_hotel_name + ' Reservation Widget');
             $("#quick_reservation_form").submit();
           }
       }
       else if ($('.choose_hotel').attr('value') == '15911')
       {
            if( ( $('.choose_hotel').attr('value') == '' )||( $('.hotel_checkin').attr('value') == 'MM/DD/YY' )||( $('.hotel_checkout').attr('value') == 'MM/DD/YY' )||( $('.choose_area').attr('value') == '' ) )
            {
                alert('All fields are required!');
            }	    
            else
            {
               var ad = $('.choose_adults').attr('value');
	       var nr = $('.choose_rooms').attr('value');
               var nc = $('.choose_children').attr('value');
	       
               var checkinArray = $('.hotel_checkin').attr('value').split('/');
               var ciy = checkinArray[2];
	       var cim = parseInt(checkinArray[0],10);
	       var cid = checkinArray[1];
	       var arrive=ciy+'-'+cim+'-'+cid;
	       
               var checkoutArray = $('.hotel_checkout').attr('value').split('/');
               var coy = checkoutArray[2];
	       var com = parseInt(checkoutArray[0],10);
	       var cod = checkoutArray[1];
	       
	       var depart=coy+'-'+com+'-'+cod;
	       var linkSandsHotel = 'https://gc.synxis.com/rez.aspx?Hotel=28981&Chain=11893&locale=en-US&area=Abu%20Dhabi'+
	                         '&adult='+ad+
				 '&child='+nc+
				 '&numberOfRooms='+nr+
				 '&arrive='+arrive+
				 '&depart='+depart ;

                var s=s_gi('thaydanathotels');
                var selected_hotel_name = '';
                $(".choose_hotel option:selected").each(function (i, selected) {
                    selected_hotel_name = $(selected).text();
                });

                s.linkTrackVars='prop1,eVar1,events';
                s.events='event1';
                s.prop1='' + selected_hotel_name + ' Reservation Widget';
                s.eVar1='' + selected_hotel_name + ' Reservation Widget';
                s.tl(this,'o','' + selected_hotel_name + ' Reservation Widget');

                var newwindow = window.open(linkSandsHotel);
                newwindow.focus();
            }
	   
       }
       else if( ($('.choose_hotel').attr('value') == 'AUHBEA')||($('.choose_hotel').attr('value') == 'AUHTIL') )
       {
            if( $('.choose_hotel').attr('value') == 'AUHBEA' )
            {
             var linkDhafraTilal = 'http://www.snrhotels.com/hotels/AUHBEA/gb/displayall.asp?hc=AUHBEA&';
            }
            else if($('.choose_hotel').attr('value') == 'AUHTIL')
            {
             var linkDhafraTilal = 'http://www.snrhotels.com/hotels/AUHTIL/gb/displayall.asp?hc=AUHTIL&';
            }
            var checkinArray = $('.hotel_checkin').attr('value').split('/');
            var ciy = checkinArray[2];
            var cim = checkinArray[0];
            var cid = checkinArray[1];
            linkDhafraTilal = linkDhafraTilal+'ciy='+checkinArray[2]+'&cim='+checkinArray[0]+'&cid='+checkinArray[1]+'&';
            //var checkOutArray = $('.hotel_checkout').attr('value').split('/');
            var nn = $('.choose_hights').attr('value');
            var nr = $('.choose_rooms').attr('value');
            var ad = $('.choose_adults').attr('value');
            var nc = $('.choose_children').attr('value');
            linkDhafraTilal = linkDhafraTilal+'ad='+ad+'&nn='+nn+'&nc='+nc+'&nr='+nr+'&cc=SX&txtID=';

            if( ( $('.choose_hotel').attr('value') == '' )||( $('.hotel_checkin').attr('value') == 'MM/DD/YY' )||( $('.hotel_checkout').attr('value') == 'MM/DD/YY' )||( $('.choose_area').attr('value') == '' ) )
            {
                alert('All fields are required!');
            }
            else
            {
                var s=s_gi('thaydanathotels');
                var selected_hotel_name = '';
                $(".choose_hotel option:selected").each(function (i, selected) {
                    selected_hotel_name = $(selected).text();
                });

                s.linkTrackVars='prop1,eVar1,events';
                s.events='event1';
                s.prop1='' + selected_hotel_name + ' Reservation Widget';
                s.eVar1='' + selected_hotel_name + ' Reservation Widget';
                s.tl(this,'o','' + selected_hotel_name + ' Reservation Widget');

                var newwindow = window.open(linkDhafraTilal);
                newwindow.focus();
            }
       }
   });

    var dates = $('#fromdate, #todate').datepicker({'dateFormat': 'mm/dd/yy',
                                        'minDate':'-1',
                                        'onSelect':function(dateText, inst) {
                                                      var fieldlimit = this.id == "fromdate" ? "hotel_checkin" : "hotel_checkout";
                                                      var option = this.id == "fromdate" ? "minDate" : "maxDate";
                                                      $('.'+fieldlimit).attr('value', dateText);
                                                      var date = $.datepicker.parseDate(inst.settings.dateFormat || $.datepicker._defaults.dateFormat, dateText, inst.settings);
                                                      dates.not(this).datepicker("option", option, date);
                                                      var fromdate = $('.hotel_checkin').val();
                                                      var todate = $('.hotel_checkout').val();
                                                      if((fromdate!='MM/DD/YY')&&(todate!='MM/DD/YY')){
                                                        var perHours = 24*60*60*1000;
                                                        var d = new Date();
                                                        var fromdate1 = Date.parse(fromdate);
                                                        var todate1 = Date.parse(todate);
                                                        fromdate1 = new Date(fromdate1);
                                                        todate1 = new Date(todate1);
                                                        var nights = new Date(todate1 - fromdate1);
                                                        nights = Math.round(nights/perHours);
                                                        $('.choose_hights').val(nights);
                                                        $('#block_with_calendars').hide();
                                                        $('#quick_reservation_form table.selections').show();
                                                      }
                                                    }
                                      });



    // ***** Navigation for slideshow page *****
    var gallaryItems = $('div.images-container').find('div.hotel_image');
    var gallaryItemsLength = gallaryItems.length;

    $('.gallery-part-item').click(function(){
        var currentPartIdArray = $(this).attr('id').split('_');
        var newindex = 0;
        $('div.images-container').find('div.hotel_image').each(function(index){
            var imageitemIdArray = $(this).attr('id').split('_');
            if( imageitemIdArray[2] == currentPartIdArray[2] )
            {
                changeSlide(currentIndex, index);
                currentIndex = index;
                $('.current_position').text(index+1);
                $('div.images-container').stopTime('slideshow');
                $('div.images-container').everyTime(5000, 'slideshow',function(){
                    var tempIndex = currentIndex;
                    tempIndex += 1;
                    if( tempIndex == gallaryItemsLength )
                    {
                        tempIndex = 0;
                    }
                    changeSlide(currentIndex, tempIndex);
                    currentIndex = tempIndex;
                    $('.current_position').text(tempIndex+1);
                });
                return false;
            }
        });
    });

    if ( gallaryItemsLength > 1 )
    {
        $('div.images-container').oneTime(5000, function(){
            $('div.images-container').everyTime(5000, 'slideshow',function(){
                var tempIndex = currentIndex;
                tempIndex += 1;
                if( tempIndex == gallaryItemsLength )
                {
                    tempIndex = 0;
                }
                changeSlide(currentIndex, tempIndex);
                currentIndex = tempIndex;
                $('.current_position').text(tempIndex+1);
            });
        });

        $('span.gallery_pause').click(function(){
            $('div.images-container').stopTime('slideshow');
        });

        $('span.gallery_back').click(function(){
            var tempIndex = currentIndex;
            tempIndex -= 1;
            if( tempIndex == -1 )
            {
                tempIndex = gallaryItemsLength-1;
            }
            changeSlide(currentIndex, tempIndex);
            currentIndex = tempIndex;
            $('.current_position').text(tempIndex+1);
            $('div.images-container').stopTime('slideshow');
            $('div.images-container').everyTime(5000, 'slideshow',function(){
                var tempIndex = currentIndex;
                tempIndex += 1;
                if( tempIndex == gallaryItemsLength )
                {
                    tempIndex = 0;
                }
                changeSlide(currentIndex, tempIndex);
                currentIndex = tempIndex;
                $('.current_position').text(tempIndex+1);
            });
        });

        $('span.gallery_forward').click(function(){
            var tempIndex = currentIndex;
            tempIndex += 1;
            if( tempIndex == gallaryItemsLength )
            {
                tempIndex = 0;
            }
            changeSlide(currentIndex, tempIndex);
            currentIndex = tempIndex;
            $('.current_position').text(tempIndex+1);
            $('div.images-container').stopTime('slideshow');
            $('div.images-container').everyTime(5000, 'slideshow',function(){
                var tempIndex = currentIndex;
                tempIndex += 1;
                if( tempIndex == gallaryItemsLength )
                {
                    tempIndex = 0;
                }
                changeSlide(currentIndex, tempIndex);
                currentIndex = tempIndex;
                $('.current_position').text(tempIndex+1);
            });
        });
    }

    // ***** End of the slideshow navigation ******


    //***** Top menu navigation

    $('.qr_link').parent().parent().hover(
        function(){
          $(this).oneTime(300, 'quickresshow' ,function(){
              $(this).parent().addClass('selected-res');
              $(this).parent().css('position','relative');
              $(this).find('.topmenu_dropdown').fadeIn(700);
              $('.open_quick_reservation').addClass('close_quick_reservation');
          });
          return false;
        },
        function(){
            $(this).stopTime('quickresshow');
        }
    );
    $('.qr_link').click(function(){
        $('#block_with_calendars').hide();
        $(this).parent().parent().parent().removeClass('selected-res');
        $(this).parent().parent().parent().find('div.topmenu_dropdown').fadeOut('400');
        $('.open_quick_reservation').removeClass('close_quick_reservation');
    });

    $('.plus-minus-overlay').click(function(){
        if( $(this).parent().parent().hasClass('selected-res') )
        {
            $('#block_with_calendars').hide();
            $(this).parent().parent().removeClass('selected-res');
            $(this).parent().find('div.topmenu_dropdown').fadeOut('400');
            $('.open_quick_reservation').removeClass('close_quick_reservation');
        }
        else
        {
            $(this).parent().parent().addClass('selected-res');
            $(this).parent().parent().css('position','relative');
            $(this).parent().find('.topmenu_dropdown').fadeIn(700);
            $('.open_quick_reservation').addClass('close_quick_reservation');
        }
    });

    $('.topmenulink_subitems').hover(
      function(){
        $(this).addClass('hovered');
        $(this).find('div.topmenu_dropdawn').stop(true, true);
        $(this).stopTime('stoplink');
        $(this).parent().parent().find('div.topmenu_dropdown').hide();
        $(this).parent().parent().find('li').css('position', 'static');
        var firstliid = $('#topmenu-firstlevel li:first-child').attr('id');
        var lastliid = $('#topmenu-firstlevel li:last-child').attr('id');
        if($(this).parent().hasClass('destination_li'))
        {
            $(this).find('.topmenulink').css('position', 'relative');
        }
        else
        {
            $(this).parent().css('position', 'relative');
        }
        if( $(this).parent().attr('id') != lastliid )
        {
            $(this).find('.menuitem_hover_lb_black').show();
        }
        if( $(this).parent().attr('id') != firstliid )
        {
            $(this).find('.menuitem_hover_rb_black').show();
        }
        $(this).oneTime(300, 'stopcurrentshow' ,function() {
          var topmenudivwidth = parseInt($(this).width());
          var dropdownwidth = $(this).find('div.topmenu_dropdown').width();
          var leftposition = (topmenudivwidth - dropdownwidth)/2;
          $(this).find('div.topmenu_dropdown').css('left', Math.round( leftposition));
          $(this).find('div.topmenu_dropdown').fadeIn(700);
        });
      },
      function(){
        $(this).removeClass('hovered');
        $(this).stopTime('stopcurrentshow');
         if($(this).parent().hasClass('destination_li'))
         {
             $(this).find('.topmenulink').css('position', 'static');
         }
        $(this).find('.menuitem_hover_lb_black').hide();
        $(this).find('.menuitem_hover_rb_black').hide();
        $(this).oneTime(300, 'stoplink' ,function() {
          $(this).find('div.topmenu_dropdown').fadeOut('fast');
        });
      }
    );

    //***** Our destination
    $('.ourdestination_link, .opengooglemap').click(function(){
        if (/MSIE (8).+Win/.test(navigator.userAgent))
        {
            docWidth = widthInIeEight();
        }
        else
        {
            var docWidth = $(document).width();
        }
        $("#shadow").css("height", $(document).height());
        $("#shadow").css("width", docWidth);
        $('.destination_googlemap').css("width", docWidth);
        $("#shadow").show();

        $('.destination_googlemap').slideDown('slow');
        $('.destination_googlemap_short').slideDown('slow');
        window.scrollTo(0,0);
        return false;
    });

    $('.close_destination_map').click(function(){
        $('.destination_googlemap').slideUp('slow');
        $('.destination_googlemap_short').slideUp('slow');
        $("#shadow").hide();
    });

    $('.promoitem .input_button_lb').hover(
        function(){
            $(this).addClass('hovered_button');
        },
        function(){
            $(this).removeClass('hovered_button');
        }
    );

});