
(function( $ ){

  $.fn.center = function () {
                    return this.each(function() {
                        var top = (($(window).height() - $(this).outerHeight()) / 2);
                        var left = ($(window).width() - $(this).outerWidth()) / 2;
                        $(this).css({position:'absolute', margin:0, top: (top > 0 ? top : 0)+'px', left: (left > 0 ? left : 0)+'px'});
                    });
                };
})( jQuery );




$(function(){
         //base url
        window.baseUrl = $("#baseUrl").val();
        window.bookingUrl = $("#bookingUrl").val();
		window.lang = $("body").get(0).getAttribute("data-lang");

		//is the user on ipad/iphone?
		window.isiDevice = ((navigator.userAgent.match(/iPad/i)) || (navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)));


        //window.baseUrl = "http://gc/";
//        window.bookingUrl = "http://gc/";


		window.IE7andLower = false;

		if ($.browser.msie){

			var version = parseInt($.browser.version,10);
			 if ( version < 7  ) {
				$('#check_for_ie_6_7').slideDown();
				window.IE7andLower = true;
			}
			if ( version === 7 ) {
				window.IE7andLower = true;
			}
		}



        //progessive enhancement: centre li menus
        $(".menu, #footer").each(function(){

            var $this = $(this);

            var menuitems = $this.children("li");

            menuitems.first().css("border-left", "none");
            menuitems.last().css("border-right", "none");

            var thiswidth = $this.width();
            var extrawidth = Math.floor( ( $this.parent().width() - thiswidth ) / $this.children("li").size() );
            
            if ($(this).attr('id') == 'footer'){
                var total = 0;
                menuitems.each(function(){             
                    total += $(this).width();
                });
                
                if ((total + $this.children("li").size()) > thiswidth) {
                    extrawidth = Math.round( (thiswidth - total)/($this.children("li").size()) ) - Math.round($this.children("li").size()/2.5);
                }
            }
            
            $this.css({
                "width" : thiswidth + "px",
                "display" : "block"
            });

            menuitems.each(function(ind){
                var child = $(this);           
                child.width( child.width() + extrawidth);
                var subchild = child.find("span");
                subchild.css({"padding-left" : "0px", "padding-right" : "0px", "width" : "100%"});
                
            });

            $this.width( $this.parent().width() );
        });


        //ajax load animation
        var loader = $('#loading');

        var ajaxInProgress = false;

        //bind ajax events to display loader
        $("body").bind("ajaxSend", function() {
            ajaxInProgress = true;

            loader.center().fadeIn(10);

        });

        $("body").bind("ajaxComplete", function() {
            ajaxInProgress = false;

            loader.center().fadeOut(200);

        });


        //bind clientside filtering events
        $("body").bind("filterStart", function() {
            if (!ajaxInProgress) {loader.center().fadeIn(10);}
        });

        $("body").bind("filterEnd", function(evt, lengthOfFiltered) {
            if (!ajaxInProgress) {loader.center().fadeOut(10);}
        });

        //progressive enhancement: make form <a> tags with 'surrogate' class submit the form they're in
        $(".surrogate").live("click", function(evt){
            evt.preventDefault();
            $(this).parents("form").trigger("submit");
             $("body").trigger("filterStart");
        });

        $('h4.clickable').bind("click", function(){
            if ($(this).hasClass('small')) {

                var thisPromoCodeType = $(this).attr('data-promo');
                $('#shm_card').val(thisPromoCodeType);
                $('#promocode').val('');

                var big_one = $(this).parent().children('.big');

                big_one.removeClass('big').addClass('small');
                $(this).removeClass('small').addClass('big');
            }
        });

         $(".menu li a").click(function(evt){

            $("body").trigger("filterStart");


            if(  $(this).attr("href").indexOf("bookapi") != -1 && ( $(this).parents('div[id="home_search"]').length !== 0 || $(this).parents('div[id="combined_search"]').length !== 0) ){

                evt.preventDefault();
                $("#search").trigger("submit");
            }


        });

		//slideshow target
        var slideshow = $('#slideshow');

        //slideshow
        var runSlideshow = function(){

            //where image placeholders are
            var moreslides = $("#moreslides div");
            //gets dimensions of initial image to use for others
            var imgwidth = slideshow.width();
            var imgheight = slideshow.height();

            //explore link and holder
            var explorelink = $("#explorelink span");
            var holder = $("#explorelink em");
            var prevwidth = '';
            var newwidth = '';

			$('#slideshow img').css({
				height : slideshow.height(),
				width : slideshow.width()
			});


            //loads each image from image placeholders and inserts into DOM
            moreslides.each(function(ind)
            {

                $('<img />')
                .attr({
                    "id" : "slide_" + ind,
                    "src" : this.getAttribute("data-src"),
                    "alt" : $(this).children("a").html(),
                    "title" : $(this).children("a").html(),
                    "style" : "width:" + imgwidth + "px;height:" + imgheight + "px;display:none",
                    "data-url" : $(this).children("a").attr("href")

                })
                .one("load", function(){

                    slideshow.append( $(this) );

                    //if last element loaded,
                    if( (ind + 1) == moreslides.size()){ //console.log("all images loaded");

                        //initialize slideshow
                        slideshow.cycle({
                            fx : 'fade',
                            timeout:  7500,
							speed: 1500,
                            before : function(){

                                prevwidth = explorelink.width();

                                explorelink
                                .css({
                                    width : prevwidth
                                })
                                .animate({
                                    opacity : 0
                                });


                            },
                            after : function(){

                                holder.html(this.alt);
                                newwidth = holder.width();

                                $("#explorelink a").attr("href", this.getAttribute("data-url"));

                                explorelink
                                .html($(this).attr("alt"))
                                .animate({
                                    width : newwidth + "px"
                                }, 500)
                                .animate({
                                    opacity : 1
                                });

                            }
                        });
                    }

                }).each(function(){

                    //image load workarounds
                    if( this.complete || ( $(window).data("browserGrade") == "C" ) ){

                        $(this).trigger("load");
                    }
                });

            });

        };

        //launch on pageload ( deferred to end of call stack )
        _.defer(function(){runSlideshow();});





        //create kwicks menu (plugin customised to allow callbacks)
        var offersmenu = $('.kwicks');
        var popout = $(".kwick_pop");
        var pop_content = $("#kwick_pop_content");
		offersmenu.data('timeoutId', false);
		var golink = $("#golink");

		var countdown = function(callback){

			var timeoutId = setTimeout(function()
			{
				callback();

			}, 750);

			offersmenu.data('timeoutId', timeoutId); //set the timeoutId, allowing us to clear this trigger if the mouse comes back over

		};


		//mouseout
		var dohidepopout = function(){

			popout.fadeOut(100,function(){
				popout.css({
					"z-index" : 0,
					"display" : "none"
				});
				offersmenu.data('timeoutId', false);
			});

		};


		var hidepopout = function(){

				countdown(dohidepopout);
		};


		var showpopout = function() //mouseover
		{
			if (offersmenu.data('timeoutId')){clearTimeout(offersmenu.data('timeoutId'))}

			var actv = offersmenu.children(".active");
			var e = actv.children(".pop_content").html();
			var elink = $("a", actv);
			var elinkcons = $("<a>").attr({href: elink.attr("href")}).html(golink.html());

			pop_content.html(e).append( $("<div>").attr({"class":"arrlink"}).html(elinkcons) );

			var actpos = offersmenu.children(".active").position();

			popout.css({"z-index" : 2000,
						"left" : actpos.left + "px",
						"top" : "0px",
						"height" : "0px",
						"display" : "block",
						"z-index" : "100"
					 }).animate({
						"top" : "-260px",
						"height" : "275px"
					},200);
		};

		popout.mouseenter(function(){
			if (offersmenu.data('timeoutId')){clearTimeout(offersmenu.data('timeoutId'))}
		}).mouseleave(function(){
			countdown(dohidepopout);
		});


		offersmenu.data("mouseOnKwick", false);
                
             if (offersmenu.children().size() > 0) {     
                  offersmenu.kwicks({
                      max: 300,
                                  event: 'mouseenter',
                                  outevent: 'mouseleave',
                      spacing:  1,
                      duration : 500
                      },
                                  showpopout,
                                  hidepopout
                  );
             }

        //toggleable components
        $(".toggle_head").live("click",function(){

            $(this).next(".toggle_body").slideToggle(200);

        });

        //initialize rss ticker
        //uses BBC news feed as demo
        $('#ticker').rssfeed(window.baseUrl + 'reviews/rss?cb='+Math.floor(Math.random()*100000001)).ajaxStop(function() {
            $('#ticker div.rssBody').vTicker();
        });

//ARRIVAL / DEPARTURE CONTROLS


                  //datefield localization
            $.tools.dateinput.localize("de", {
                   months: 'Januar,Februar,M&auml;rz,April,Mai,Juni,Juli,August,September,Oktober,November,Dezember',
                  shortMonths:  'Jan,Feb,Mar,Apr,Mai,Jun,Jul,Aug,Sep,Okt,Nov,Dec',
                   days:         'Sonntag,Montag,Dienstag,Mittwoch,Donnerstag,Freitag,Samstag',
                   shortDays:    'Son,Mon,Die,Mit,Don,Fre,Sam'
            });

            //build date inputs using jquery tools
                        if ($(".date").length) {

							var dateConfig = {
                                    format: 'dd.mm.yyyy',
                                    lang: (document.getElementsByTagName("body")[0].getAttribute("data-lang")),
                                    min: -1, //set minimum date
                                    max: 332 //set minimum date
                            };

							if (window.IE7andLower) {dateConfig.offset = [-212,0];}

                            $(".date").dateinput(dateConfig);


                            var fromDate = new Date();
                            var toDate = new Date();
                            var today = new Date();
                            var maxInFuture = new Date();
                            maxInFuture.setTime(today.getTime() + 332*86400000);
                            
                            toDate.setTime( today.getTime() + 86400000 );

                            if ($('#datefrom').val() != '' && $('#dateto').val() != '') {
                                var components = $('#datefrom').val().split('.');
                                fromDate = new Date(components[2], components[1]-1, components[0]);
                                components = $('#dateto').val().split('.');
                                toDate = new Date(components[2], components[1]-1, components[0]);
                            }
                            
                            var checkDate_from = checkDate(fromDate.getTime(), today.getTime(), maxInFuture.getTime());
                            var checkDate_to = checkDate(toDate.getTime(), today.getTime(), maxInFuture.getTime());
                            
                            if (checkDate_from < 0 || checkDate_to < 0) {
                                fromDate.setTime(today.getTime());
                                toDate.setTime( today.getTime() + 86400000 );
                                
                            } else if (checkDate_from > 0 || checkDate_to > 0){
                                
                                fromDate.setTime( maxInFuture.getTime() - 86400000 );
                                toDate.setTime(maxInFuture.getTime());
                                
                            }

                            $(".date:first").data("dateinput").setValue(fromDate);
                            $(".date:last").data("dateinput").setValue(toDate);

                            var initialFromDate = fromDate;
                            //damper to prevent double change events (when both fields are altered)
                            var damper = function( evt ){

                                var hot = false;

                                var heat = function(){
                                    hot = true;
                                    setTimeout(function(){
                                        hot = false ;
                                    },50);
                                };

                                this.attempt = function(){
                                    if (hot === false){
                                        evt();
                                        heat();
                                    }
                                };
                            };

                            var dateDamper = new damper(function(){$(window).trigger("datesChanged");});
                            
                            // flag that indicates with input gets the resource on change
                            var dateChanged = 0;
                            

                            // when from date input is changed, update the to date field
                            $(".date:first").data("dateinput").change(function() {
                                    if (dateChanged != 0) {
                                        return;
                                    }
                                    dateChanged = 1;
                                    
                                    fromDate = this.getValue();
                                    
                                    toDate = toDateTmp = $(".date:last").data("dateinput").getValue();
                                    
                                    // $lengthOfStay in ms
                                    var $lengthOfStay = toDate.getTime() - initialFromDate.getTime();
                                    
                                    // overwrite initialFromDate with the new one
                                    initialFromDate = fromDate;
                                    
                                    //if the from value is now >= the to value, make the to value one bigger than the from
                                    //if ( fromDate.getTime() >= toDate.getTime() ){
                                        toDateTmp.setTime( fromDate.getTime() + ($lengthOfStay) );
                                        
                                        var daylightDiff = (Math.abs(toDateTmp.getTimezoneOffset()) - 
                                                Math.abs(fromDate.getTimezoneOffset()));
                                        daylighDiff = -(daylightDiff * 60 * 1000); // min diff * sec * milisec
                                        
                                        toDate.setTime(toDateTmp.getTime() + daylighDiff);
                                        
                                        $(".date:last").data("dateinput").setValue(toDate, true);
                                    //}
                                        
                                    var checkedDate = checkDate(toDate.getTime(), today.getTime(), maxInFuture.getTime());

                                    if (checkedDate < 0){
                                        $(".date:first").data("dateinput").setValue(today);
                                    } else if (checkedDate > 0){
                                        toDate.setTime( maxInFuture.getTime());
                                        $(".date:last").data("dateinput").setValue(toDate, true);
                                    }

                                    $('#datefrom').val(this.getValue('dd.mm.yyyy'));
                                    
                                    dateDamper.attempt();
                                    
                                    dateChanged = 0;
                            });
                            
                            // when to date input is changed, update the from date field
                            $(".date:last").data("dateinput").change(function() {
                                    if (dateChanged != 0) {
                                        return;
                                    }
                                    dateChanged = 1;
                                
                                    fromDate = $(".date:first").data("dateinput").getValue();
                                    toDate = this.getValue();
                                    
                                    $(".date:last").data("dateinput").setValue(toDate, true);
                                    
                                    //if the to value is now <= the from value, make the from value one less than the to
                                    if ( toDate.getTime() <= fromDate.getTime() ) {
                                            fromDate.setTime( toDate.getTime() - 86400000 );
                                            $(".date:first").data("dateinput").setValue(fromDate, true);
                                    }
                                    
                                    var checkedDate = checkDate(fromDate.getTime(), today.getTime(), maxInFuture.getTime());

                                    if (checkedDate < 0){
                                        $(".date:first").data("dateinput").setValue(today);
                                    }else if (checkedDate > 0){
                                        toDate.setTime( maxInFuture.getTime());
                                        $(".date:last").data("dateinput").setValue(toDate, true);
                                    }
                                    
                                    $('#dateto').val(this.getValue('dd.mm.yyyy'));
                                    
                                    dateDamper.attempt();
                                    
                                    dateChanged = 0;
                            });
                        }

//youtube video loader for individual hotel pages

		//loads in iframe - supposed to work for ipad/html5. But always sits on top of everything because wmode isn't controllable.
		var youtubePlayer = function(vidsrc, width, height){
			return '<iframe title="YouTube video player" class="youtube-player" type="text/html" width="'+width+'" height="'+height+'" src="'+vidsrc+'" frameborder="0" allowFullScreen></iframe>';
		};

		//flash-only, but has controllable wmode
		var oldYoutubePlayer = function(vidsrc, width, height){
			return '<object width="'+width+'" height="'+height+'"><param name="movie" value="'+vidsrc+'&rel=0"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><param name="wmode" value="transparent"></param><embed src="'+vidsrc+'&rel=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="'+width+'" height="'+height+'" wmode="transparent"></embed></object>';
		};



		var loadVideo = function(context, target){
			var vidsrc = context.attr("href");
			$(".watchvideoContainer", target).html(youtubePlayer(vidsrc,690,461)).animate({height: 500}, 500);
			$(".watchvideoClose", target).css({display : "block"});
		};

		$(".watchvideo").live("click",function(evt){
		   evt.preventDefault();
		    loadVideo($(this), $('div#watchvideo_'+ $(this).attr("data-src") ) );
	   });

	   $(".watchvideoClose a").live("click",function(evt){
		   evt.preventDefault();
		   $(this).parent().css({display : "none"}).next().html("").animate({height: 0}, 500);
	   });


//youtube video loader for home page

		var vidmaincontainer = $("#vidcontainer");
		var vidinner = $("#vidinner",vidmaincontainer);
		var homebookbox = $(".bookbox");
		var homebookboxfields = $("fieldset", homebookbox);
		var slideshowTexts = $("#slidepromotext, #explorelink");
		var watchmainvideo = $(".watchmainvideo");
		var closemainvideo = $(".closemainvideo");

		var showMainVideo = function(context){

			slideshow.cycle("toggle");
			slideshowTexts.fadeOut(300);
			homebookbox.removeClass("darkshad").animate({top: "0px", left: "0px", height:"445px", width:"263px"},300);
			homebookboxfields.animate({padding: "30px"});
			watchmainvideo.css({display:"none"});
			closemainvideo.css({display:"block"});
			vidinner.html( oldYoutubePlayer( context.attr("href") + "&autoplay=1",672,445 ) );

			vidinner.fadeIn(500);
		};


		var hideMainVideo = function(){

			vidinner.fadeOut(500,function(){
				vidinner.html('');
				homebookbox.addClass("darkshad").animate({top: "25px", left: "25px", height: "325px", width: "230px"},300);
				homebookboxfields.animate({padding: "0px"});
				watchmainvideo.css({display:"block"});
				closemainvideo.css({display:"none"});

				slideshowTexts.fadeIn(300,function(){
					slideshow.cycle("toggle");
				});
			});
		};

		$("a", watchmainvideo).live("click", function(evt){
			if (!window.isiDevice){
				evt.preventDefault();
				showMainVideo( $(this) );
			}

		});

		$("a", closemainvideo).live("click", function(evt){
			evt.preventDefault();
			hideMainVideo();
		});


//promo field selector SCHMETTERLING CARD NUMBER

		$(".promoselect a").live("click",function(evt){

			evt.preventDefault();

			$("#promoFieldTitle").html($(this).html());

			///change code type after choosing a code type field
			var codeType = $(this).attr('data-code');
                        $("#codetype").val(codeType);

			//set name of input to appropriate type
			//$(".promowrite input").attr("name", $(this).attr("href").slice(1));

			$(".promoselectContainer").animate({left : "-184px"}, 500, function(){
                            if (codeType == 3 || codeType == 4 || codeType == 5) {
                                //$('#shm_types input[value="'+codeType+'"]').attr('checked', 'checked');
                                $("#check_schm_div").slideDown(500);
                            }
                        });
		});

		$(".promowrite a").live("click",function(evt){
			evt.preventDefault();

                        $("input#promocode").val('');
                        $("#codetype").val(0);
                        
                        $('#shm_types input[type="radio"]').attr('checked', false);
			$(".promoselectContainer").animate({left : "0px"}, 500, function() {
                            ///hiding the error if visible
                            $('#check_schm_div div.invalid').hide();
                            $("#check_schm_div").hide();
                            $("#shm_types").remove();
                        });
		});
		
                /// firing up the schmetterling events  
                schmEvents();
                optionsEvents();
///////////////////////////////////////////////////////////////////////////////

//Post-load components

        //builds google map. Gets geo information from 'data' attributes of the container div.
        $.fn.buildGoogleMap = function(){

            //only do this if a google map container is found on the page
            if ( $(".googlemap").filter(function(index){

                return !$(this).hasClass('marked');

            }).length !== 0 ){

                    var target = $(".googlemap").filter(function(index){

						return !$(this).hasClass('marked');

					});

                    var randomnumber=Math.floor(Math.random()*1000001);
                    var new_id = 'googlemap_'+randomnumber;
                    var temp = document.createElement('span');
                    temp.id = new_id;
                    target.before(temp);
                    var final_target = document.getElementById(new_id).nextSibling;

                    var latlng = new google.maps.LatLng( Number(final_target.getAttribute("data-lat")), Number(final_target.getAttribute("data-long")));
                    var myOptions = {
                    zoom: Number(final_target.getAttribute("data-zoom")),
                    center: latlng,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                    };

                    var map = new google.maps.Map(final_target, myOptions);

                    //add marker
                    var image = final_target.getAttribute("data-icon");

                    var marker = new google.maps.Marker({
                        position: latlng,
                        map: map,
                        icon: image
                    });

                    target.addClass('marked');
            }

        };


        //build google map on page load if this location page is loaded directly.
        //But normally it is built after the ajax call
        $.fn.buildGoogleMap();

        $.fn.extractSubfooter = function(){
            //subfooter on differen
            if ($('div.nav_subfooter').length > 0) {
               $('div.nav_subfooter div.general_sub').addClass('hidden_section');
               $('div.nav_subfooter .new_sub').html($('#new_temp_subfooter').html());
            }
        }

        $.fn.initializeLightBoxes = function(){

             $('div[id^="gallery"]').each(function(){

                $("a", $(this)).lightBox();
            });
        };

        $.fn.initializeExpandable = function(){

            $('.collapsed').each(function(){
                this.style.display = 'none';
            });


        };
        
        //all things to be fired after html loaded in
        $.fn.revealRooms = function(){

               //reveal hidden rooms
            $(".revealRooms").live("click", function(evt){
    
                var $inst = $(this);
    
                evt.preventDefault();
    
                $inst.parent().parent().prev('.pado2').find(".hiddenRooms").slideDown(300);
    
                //console.trace();
    
                $inst.attr("class", "hideRooms");
    
                $(".moreRoomsText", $inst).css("display","none");
                $(".lessRoomsText", $inst).css("display","block");
    
            });
            
             //hide revealed rooms
            $(".hideRooms").live("click",function(evt){
    
                var $inst = $(this);
    
                evt.preventDefault();
    
                $inst.parent().parent().prev('.pado2').find(".hiddenRooms").slideUp(300);
    
                $inst.attr("class", "revealRooms");
    
                $(".moreRoomsText", $inst).css("display","block");
               $(".lessRoomsText", $inst).css("display","none");
    
            });
        };
       

        //call on pageload
        $.fn.initializeLightBoxes();
        $.fn.initializeExpandable();
        $.fn.revealRooms();


        window.enableEditor = function(){
            if (typeof(displayedLabels) !== 'undefined') {
                if ($('.newLabels').length >= 1) {
                    $('.newLabels').each(function(){
                       var newLabels = $(this).val().split(',');
                       displayedLabels = $.merge(displayedLabels, newLabels);
                    });
                }
                $(stInitInlineEditing);
            }
        };

        //all things to be fired after html loaded in
        $.fn.loadUIComponents = function(){

                $.fn.extractSubfooter();
                enableEditor();
                $.fn.buildGoogleMap();
                $.fn.initializeLightBoxes();
                $.fn.initializeExpandable();


                // image gallery
                // if ($('#gallery a').length > 0) $('#gallery a').lightBox();
        };

//HOME PAGE SEARCH FORM - does normal GET

        $("#home_search #booknow").live("click",function(evt){evt.preventDefault();

            $(this).parents("form").trigger("submit");

            $("body").trigger("ajaxSend");
        });

    $(".viewPrices a.big").live("click",function(evt){
  
                    var $inst = $(this);
                    var parent = $inst.parents(".roomset");
                    evt.preventDefault();

                    
                    changeOverlay = function(newHtml, appendContent){

                        var container = $(".baseRooms, .extraRoomToggle", parent);
                        
                        container.html(newHtml);
                        container.slideDown(500,function(){			
                        $("html, body").animate({
                                          scrollTop : $(".baseRooms", parent).offset().top - 200
                        }, 500);			
                        });
                        
                        var newLabel = $inst.get(0).getAttribute("data-alt");			
                        $inst.get(0).setAttribute("data-alt", $inst.html());			
                        $inst.html(newLabel).parent().attr("class", "hidePrices");
                        $inst.attr('class', 'small');
                        
                        $("body").trigger("ajaxComplete");
                        
                        intializePopupContent();
                        $.fn.revealRooms();
    
                    };
                    
                    
                    getPageContent = function(thishref, getParams, callback){
                        if (currentRequest != null) {
                            currentRequest.abort();
                        }
                      
                        //get html and continue
                        var currentRequest = $.get( thishref, getParams, function(data){
                            hotline = $('#reservationHotline', data).val();
                            
                            if ($(data).attr('id') == 'redirUrl') {
                                window.location = $(data).text();
                                return false;
                            }
            
                            if (data) {
                                /// loads a sertain parts of the newly generated html into the layout
                                partialContentLoader(data);
                                data = $("#rooms_additional_options", data);
                            }
            
                            callback(data);
            
                        },"html");                
                    
                    };
                  
                  
                  /// make a hotel availability request ////////////////
                  var getParams = {
                        datefrom : $("#datefrom").data("dateinput").getValue("dd.mm.yyyy"),
                        dateto : $("#dateto").data("dateinput").getValue("dd.mm.yyyy"),
                        promocode : $("#promocode").val(),
                        codetype : $("#codetype").val()
                    }
                    
                  getPageContent($(this).attr('href'), getParams, changeOverlay);
                  
                  /////////////////////////////////////////////////////////
                  
  });


  $(".hidePrices a.small").live("click",function(evt){
  
                    var $inst = $(this);
                    var parent = $inst.parents(".roomset");
                    evt.preventDefault();
                          
                    $(".baseRooms, .extraRoomToggle", parent).slideUp(500);
                    
                    var newHtml = $inst.get(0).getAttribute("data-alt");			
                    $inst.get(0).setAttribute("data-alt", $inst.html());			
                    $inst.html(newHtml).parent().attr("class", "viewPrices");
                    $inst.attr('class', 'big');
  });


$(window).bind("datesChanged", function() {
            clearBasket();
        });

        
        
        
  
        


}); //end jq closure

function urlencode (str) {
    str = (str+'').toString();
    return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
}

function getYOffset() {
    var pageY;
    if(typeof(window.pageYOffset)=='number') {
       pageY=window.pageYOffset;
    }
    else {
       pageY=document.documentElement.scrollTop;
    }
    return pageY;
}

function expandDefaultCollapsed(elem){
    var parent = $(elem).parent();
    parent.slideUp(300, function(){
        parent.next('li').slideDown(300);
    });
}

function changeOccupancy(elem, direction) {
    var window_size = 2;
    var parent = $(elem).parents('table.tallcell_table');
    var next_length = 0;
    if (direction > 0){

       if ((next_length = parent.find('.window_present_'+window_size ).eq(0).nextAll('.window_notpresent').length) > 0) {
           //right edge
           parent.find('.window_present_'+window_size ).each(function () {
               $(this).removeClass('window_present_'+window_size);
               $(this).next('.window_notpresent').addClass('window_present_'+window_size).removeClass('window_notpresent');
           });

           //left edge
           parent.find('.window_present_1' ).each(function () {
               $(this).next().addClass('window_present_1');
               $(this).removeClass('window_present_1').addClass('window_notpresent');
           });

           if (next_length == 1) {
                parent.find('.right_arrow').addClass('hidden');
                parent.find('.left_arrow').removeClass('hidden');
           }else {
                parent.find('.left_arrow').removeClass('hidden');
           }
       }

    }else {
        if ((prev_length = parent.find('.window_present_1').eq(0).prevAll('.window_notpresent').length) > 0) {
           //left edge
           parent.find('.window_present_1' ).each(function () {
               $(this).prev('.window_notpresent').addClass('window_present_1').removeClass('window_notpresent');
               $(this).removeClass('window_present_1');
           });

           //right edge
           parent.find('.window_present_'+window_size ).each(function () {
               $(this).removeClass('window_present_'+window_size).addClass('window_notpresent');
               $(this).prev().addClass('window_present_'+window_size);
           });

           if (prev_length == 1) {
                parent.find('.left_arrow').addClass('hidden');
                parent.find('.right_arrow').removeClass('hidden');
           }else {
               parent.find('.right_arrow').removeClass('hidden');
           }
        }
    }
}

//checks date to be in limits
function checkDate(date, min, max){
    if (date < min) { // this is impossible case
        return 0;
    }else if(date >= min && date <= max){
        return 0;
    }else {
        return 1;
    }
}


function optionsEvents(){
    
    $('#shm_types input[type="radio"]').click(function (){
        $("#codetype").val($(this).val());
    });
    
}

function schmEvents(){

    
    $('#check_schm').click(function (){
        var button = $(this);
        button.attr('disabled', true);
        ///hiding the error if visible
        $('#check_schm_div div.invalid').slideUp(300);
        
        var promo = $('#promocode').val();
        var url = window.baseUrl + 'schmetterling';
        $.post(url, {'c': promo}, function(data){
            if (data.success == 1){
                $('#check_schm_div').slideUp(400, function(){
                    $(this).addClass('hidden_section');
                    $('#check_schm_div').parent().append($(data.data));
                    optionsEvents();
                });
                
            }else if (data.success == 0){
                $('#check_schm_div div.invalid').slideDown(300);
            }
            button.attr('disabled', false);
            
        }, 'json');
    });
        
    
}

//force click on addthis
var addthis_config = {
   ui_click: true
};
