var ie6Below = $.browser.msie && parseFloat($.browser.version) <= 6;

$( function() {
	if ($('.specialOffersHeader p.image').length) {
		$('.specialOffersHeader p.image').css('cursor', 'pointer').click(function() {
		window.open('/freepass', '', 'menubar=no, left=340, top=282, width=400, height=200, toolbar=no, scrollbars=yes');
		});
	}

    // setup newsletter signup
    if( $(".newsletterSignUp :text").length )
    {
        setEmailSignText();
    }
    
    // setup dynamic loading of google maps for search pages
    if ($(".bookingResults .parc[coords]").length) {
        googleSearchResultsSetup();
    }
    
    // setup floorplan popup
    $(".accommodation .floorplan a").click( openFloorplanPopup );
    
	//Jscript for the FAQ's Page
    if ( $(".freqAskedQ").length) {  
	$(".showHide").wrapInner("<a></a>");
    $(".freqAskedQ .questionList,.questionList .question .answer")
        .hide();
    
    $(".freqAskedQ .showHide").each( function() {
        $(this).html('<a href="#">' + $(this).text() + '</a>');
    });
 
    $(".questionList .question span").each( function() {
        $(this).html('<a href="#">' + $(this).text() + '</a>');
    });    
       
    $(".freqAskedQ .showHide a,.questionList .question span a").click(function (){
        if( $(this).parent(".showHide").length )
            $(this).parent(".showHide").toggleClass("showHide_expand");
        
        $(this).parent().next().slideToggle();
		$(this).toggleClass("expand");
        return false;
      });
    }
			
	$(".alternativeDates").hide();
	 $(".tableSlide").click(function(){
									 
	 $(this).parent().next().slideToggle("slow");
	 $(this).toggleClass("active"); return false;
	 });
		
	 $(".additionalInformation").hide();
	 $("a.info").click(function(){
	 $(this).parent().next().slideToggle("slow");
	 $(this).toggleClass("active"); return false;
	 });
	 $(".fullArticle").hide();
	 $("a.article").click(function(){
	 $(this).parent().prev().slideToggle("slow");
	 $(this).toggleClass("active"); return false;
	 });
	 

	// Join the team show/hide
	if ($(".jobInfoContainer").length) {
			$(".jobInfoHeader").click(function() {
				$(this).toggleClass("open").next().slideToggle();
			}).filter(":first").click();		
		}
	
	
    $(".parcCountries .country")
	    .append('<p><a href="#nogo">View all regions</a></p>')
	    .find("p a")	 
        .click(function(){
            
            var anchor = this;
            var regions = $(anchor).parents(".parcCountries").find(".regions");
            
            if( anchor.className.match(/active/i) ) {
                $(anchor).removeClass("active");
                regions.slideUp();
            }
            else {
                $(anchor).addClass("active");
                regions.slideDown();
            }
            
            return false;
	     });
	 
 
	 $(".specialOffers p.terms,.specialOffersHeader p.terms").hide();
	 $("a.viewTerms").toggle(function(){
	        $(this).parent().next().slideToggle("slow");
	        $(this).toggleClass("active").text("Close terms and conditions"); return false;
	        },
	        function(){
	        $(this).parent().next().slideToggle("slow");
	        $(this).toggleClass("active").text("View terms and conditions"); return false;
	        }
	        );	 
	        
	  $(".specialOffers .offerTerms").hide();
	 $(".specialOffers .termsLink a").toggle(function(){
	        $(this).parent().parent().next().slideToggle("slow");
	        $(this).toggleClass("active").text("Close terms and conditions"); return false;
	        },
	        function(){
	        $(this).parent().parent().next().slideToggle("slow");
	        $(this).toggleClass("active").text("View terms and conditions"); return false;
	        }
	        );	
	 
	 
	 $(".accommodation .mobileHomes .types .accomInfo div").hide();
	 $("a.homeInfo").toggle(function(){
	        $(this).parent().prev().slideToggle("slow");
	        $(this).parents(".accomInfo").parent().animate({backgroundColor: "blue"}, "slow");
	        $(this).toggleClass("active").text("Close"); return false;
	        },
	        function(){
	        $(this).parent().prev().slideToggle("slow");
	        $(this).parents(".accomInfo").parent().animate( { backgroundColor: 'white' }, "slow");
	        $(this).toggleClass("active").text("Find out more"); return false;
	        }
	        );
  
    //Jscript for toggling Accessory Description
    var accessoryHold = $(".purProcess .accessories .accessoryHold");
    $(".accessory .desc")
        .hide()
        .after('<p><a href="#nogo">Show details</a></p>')
        .next().find("a").click(function (){
            $(this).parent().prev().toggle();
            if ($(this).text()=="Show details"){
                $(this).text("Hide details")
            }
            else{$(this).text("Show details")} 
        });
   
   
    //Jscript to generate Optional Accessories Links (open & close)
    accessoryHold
    .hide()
    .before('<p class="viewAccessories"><a href="#purchase">View and purchase additional accessories with your plan.</a></p>')
    
    .prev().find("a").click(function (){
        accessoryHold.slideDown();
        $(this).parent().hide();
        $("#closeAccessories").show();
    })
    
    $(".accessories")
        .after('<p id="closeAccessories" class="closeAccessories"><a href="#nogo">Close accessories panel</a></p>')
        .next()
        .hide()
        .find("a")
        .click(function (){
            accessoryHold
                .hide()
                .prev()
                .show();
            $(this).parent().hide();
        })

		// setup driving information
		if( $(".drivingDirections .info").length )
		{
			initDirections();
		}
		
		// setup  image gallery
		if( $(".gallery").length )
		{
			initGallery();
		}
		
		
		if( $(".offerRadio").length )
		{
		    setupOfferOverlay();
		}
		
		// setup home image show
		if( window.homeSlideShow )
		{
		    imageSlideShow();
		}

    });


function imageSlideShow()
{
    var images = window.homeSlideShow;
    var container = null;

    if( !$(".homepage h1 a").length )
    {
        for( var x in images)
        {
            if( images[x].href )
            {
                $(".homepage h1 img").wrap("<a/>");
                break;
            }
        }
    }

    if( $(".homepage h1 a").length )
    {
        container = $(".homepage h1 a");
    }
    else
    {
        container = $(".homepage h1");
    }

    var timer = images.timer || 4000;
    var index = 0;
    
    function runShow()
    {
		index = (index + 1) % images.length;
        
        var img = new Image();

	    function imageLoaded()
	    {
	        $("img",container).fadeOut("slow" ,function() { $(this).remove(); } );
			$(img).hide().appendTo(container).fadeIn("slow" , function() {setTimeout(runShow,timer)});
	    }

        function imageFail()
        {
            runShow();
        }

        img.onload = imageLoaded;
        img.onerror = imageFail;

        img.src = images[index].src;
        img.alt = img.title = images[index].alt;
        container.attr("title",img.alt);
        if( images[index].href )
        {
            container.attr("href" , images[index].href );
        }
        else
        {
            container.removeAttr("href");
        }
        
    }

    setTimeout( runShow , timer );
}

function setupOfferOverlay()
{
    $(".offerRadio")
        .click( function() {

            /*  setup any hidden input values here.
                Don't put them inside the checkAvailability
                box at the bottom of the page */
            // $("input" ,this).attr("checked","checked");
			/********************************/

			var accomid = $(this).children("#accom").attr("value");
			var Pdate = $(this).children("#Pdate").attr("value");
			var Pnight = $(this).children("#Pnight").attr("value");

            if( $("#checkAvailability").length )
            {
                showOverlay( $('<div class="bookingFrame" />').append( $("#checkAvailability").show() ) , true );
            }
            else
            {
                showOverlay( null , true );
            }
            
			$("#checkAvailability").find("#selctedaccom").val(accomid);
			$("#checkAvailability").find("#selectdate").val(Pdate);
			$("#checkAvailability").find("#selectnight").val(Pnight);

			$("#checkAvailability").find('#PSTAYN').val(Pnight);
			DrawYears(3,"+","PSTYYYY","N",startDate);
			if (isDate(Pdate, 'dd-MMM-yyyy')) {
				var defaultDate=0;
				defaultDate =getDateFromFormat(Pdate,'dd-MMM-yyyy',true);  
				var month = (defaultDate.getMonth() + 1)+'';
				var day = ''+defaultDate.getDate();
				$("#checkAvailability").find('#PSTDD').val(LZ(day)); 
				$("#checkAvailability").find('#PSTMM').val(LZ(month)); 
				$("#checkAvailability").find('#PSTYYYY').val(defaultDate.getFullYear());
			}
			PsetEndDate();

			return false;
		});
}

function initGallery()
{
	var script = document.createElement("script");
	script.type = "text/javascript";
	script.src = "NewCSS/eqtr_image_gallery.js";
	document.body.appendChild(script);
}
	
function initDirections()
{
	var container = $(".drivingDirections .info");
	var setup = false;

	$(":submit" , container ).one( "click" , function() {
		$(this).after('<span class="googleLoading">Loading directions</span>');
		container.append( '<div class="googleControls hideOnload"><div class="googleMap"/></div>' );
	    var script = document.createElement("script");
	    script.type = "text/javascript";
	    script.src = googleApi + "&callback=loadGoogleMaps";
	    document.body.appendChild(script);
		return false;
	});
}

function loadGoogleMaps()
{
		var script = document.createElement("script");
	    script.type = "text/javascript";
	    script.src = "NewCSS/eqtr_google_directions.js";
	    document.body.appendChild(script);
}
    
// floorplan popup

function openFloorplanPopup()
{
    var el = this;
    
    var img = new Image();
    
    img.onload = function() {
        
        var winHeight = $(window).height();
        var winWidth = $(window).width();
        var imgHeight = img.height;
        var imgWidth = img.width;
        
        if( imgWidth > winWidth )
        {
            img.width = winWidth - 40;//abitrary height.
            img.height = img.width*imgHeight/imgWidth;

            imgHeight = img.height;
            imgWidth = img.width;
        }
        
        if( imgHeight > winHeight )
        {
            img.height = winHeight - 40;//abitrary height.
            img.width = img.height*imgWidth/imgHeight;
        }
        
        showOverlay( $('<div class="imageFrame"/>').append(img) );
    };
    
    img.onerror = function() {
           
    };  
    
    img.src = el.href;
    return false; 
    
}

//Jscript to generate window height (this is used with Monitor Solutions Popup)
function getWindowSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return [ myWidth , myHeight ];
}

function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}
	
/* common functions */

function playMovie(url, thumb) {
    var myFlashMovie = thisMovie("flashVideo");
    myFlashMovie.playFlashVideo(url, thumb);
}

function thisMovie(movieName) {
    return ($.browser.msie) ? window[movieName] : document[movieName];
}	

function getWMV( src )
{
    var str = [];
    str.push( '<object id="player" data="' + src + '" class="flash" width="393" height="271">' );
    str.push( '<param name="filename" value="' + src + '"/>' );
    str.push( '<param name="stretchToFit" value="true" /><param name="Showcontrols" value="true"/>' );
    str.push( '<param name="autoStart" value="False"/><param name="ShowStatusBar" value="True" />' );
    str.push('<p>This video requires the Windows Media Player plugin.</p>');
    if( $.browser.msie )
    {
        str.push('<p>Download load the Windows Media Player Core add-on (click on the yellow bar alert bar) or update to the latest version of Windows Media Player</p>');
    }
    else
    {
        str.push('<p>Update to the latest version of Windows Media Player</p>');
    }
    str.push( '</object>' );
    return str.join("");
}

/* lightbox overlay for content */

function showOverlay( html , keepContentWhenRemove ) {

    var popup = null;

    if( keepContentWhenRemove && showOverlay.html )
    {
        html = showOverlay.html;
    }
  
	displayPanel(html);

    function removePopup() {
        popup.fadeOut("slow", function() { $(this).add(".popFrame").remove(); });
        $(window).unbind("scroll");
        return false;
    }

    function displayPanel(html) {
        popup = $('<div id="overlayPopup" class="popup"></div><div class="overlay"><a class="popupClose" title="Close window" href="#"><span>Close window</span></a><div class="popupContent" /></div>').hide().css("display", "none");
        popup.filter(".popup").css("opacity", "0.5").click( removePopup );
        var popupContent = popup.find(".popupContent").append(html);
        
        showOverlay.html = popupContent.html();

        $("body").append(popup);

        popup.eq(1).width( popup.eq(1).width() );

        popup.eq(1)
            .css("margin-left" , -popup.eq(1).width()/2 )
            .find(".popupClose")
            .css("float","right")
            .click( removePopup );

        popup.fadeIn();

        var offsetTop = ($(window).height() - popup.eq(1).height())/2;
        
        if (ie6Below) {

            popup.css("position","absolute").eq(1).css({ top: (getScrollXY()[1] + offsetTop)}).end().eq(0).height(document.body.scrollHeight);
            $(window).bind("scroll", function() {
                popup.eq(1).stop().animate({ top: getScrollXY()[1] + offsetTop }, 500);
            });

            $("body").append('<iframe class="popFrame" style="position:absolute;top:0;left:0;width:100%;height:' + document.body.scrollHeight + 'px" frameborder="0" src="javascript:false;"></iframe>').find(":last").css("opacity",0);
        }
        else {
            popup.get(1).style.top = offsetTop + "px";
        }
    }

    return false;
}

$(window).load( function() {

var maxheight = 0;
$(".aboutAlFresco,.alfUpdates").each( function() {
	var h = this.offsetHeight;
	if( h > maxheight ) maxheight = h;
}).each( function() {
	var pb = $(this).css("padding-bottom").replace("px","");
	var pt = $(this).css("padding-top").replace("px","");
	$(this).css("height" , maxheight - pb - pt );
});

});


function setEmailSignText()
{
	
	// Default text. Required field notification text, in this example. 
	var signup = $(".newsletterSignUp");
	var label = $("label" ,signup ).hide();
	var input = $("input" , signup);
	var reqVal = label.text();
	
	// Initial addition of text
	input.each(function(){
		createText(reqVal, $(this));
	});
}

// Create default text for text field on page load
function createText(defVal, thisObj){
	if( thisObj.is(":text") )
	{
		thisObj.addClass("empty").val( defVal );
		thisObj.data("text" , defVal );

    	thisObj
    	    .focus( removeText )	// Removal of text on user-focus
	        .blur( restoreText );	// Restoration of default text on input blur, if no user input.
	}
}

// Remove default text on focus. Ignore user-inserted text
function removeText() {
	var el = $(this);
	
	var text = el.data("text");
	if( text )
	{
		if( el.val() == text ){ 
			el.removeClass("empty").val(""); 
		}
	}
}

// Restore default text on focus. Ignore user-inserted text
function restoreText (defVal, thisObj) {
	var el = $(this);
	var text = el.data("text");
	if( text )
	{
		var currVal = $.trim(el.val());
		if(currVal == "") { 
			el.addClass("empty").val(text);	 
		}
	}
}

	
