jQuery.expr[':'].regex = function(elem, index, match) {
    var matchParams = match[3].split(','),
    validLabels = /^(data|css):/,
    attr = {
        method: matchParams[0].match(validLabels) ?
        matchParams[0].split(':')[0] : 'attr',
        property: matchParams.shift().replace(validLabels,'')
    },
    regexFlags = 'ig',
    regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
    return regex.test(jQuery(elem)[attr.method](attr.property));
}

$(document).ready(function(){

    configResortMenu();

    checkGoogleEarthArrows();

    $('#selLanguage').change(function() {
	    window.location.href = $('#language-url').val();
        //window.location = "/language-picker/pick/language/" + $(this).val();
    });
    $("#mainContent h2").append("<span class='wave'></span>");
    $("label.required").append("<span style=\"color:red\">*</span>");

    var r = $("#recaptcha_widget_div");
    r.remove();
    var b = $("#App_Form_JobApplicant input#apply");
    b.remove();

    $("#App_Form_JobApplicant").append(r);
    $("#App_Form_JobApplicant").append(b);

    $("dt:has(label.required[for='captcha'])").addClass("spam-note");
    $("dt:has(label.optional[for='alert'])").addClass("long-field");
    $("dd input#alert").parent().addClass("short-field");
    $("span.removable").remove();
    var subHeight = $("#subNav.topNav").height();
    var navItem = $("#subNav.topNav a.selected");
    if (subHeight > 35 && navItem.height() < 25 )
        navItem.addClass("bigger");


    $("div.scrollable").scrollable({
        size:8
    }).circular();
    
    $("ul.items li a").click( function(e) {
        e.preventDefault();
    });

    // Replace select boxes by fancy drop downs
    $(':input[type=select-one]').each(function(el) {
        (title = $(this).find(':selected').text()) || ((!title.length) && (title = $(this).find(':first-child').text()));

        $(this).imgdropdown({
            title: title,
            optionElements: 'option',
            isFormElement: true
        });

    });

    // google maps
    $('#googleEarth li a').fancybox({
        frameWidth: 600,
        frameHeight: 500
    });
    
    $('a:regex(href,(jpg|gif|png)$)').fancybox({
        frameWidth: 600,
        frameHeight: 500
    });
    
    $('a.signupJobAlerts').fancybox({
        frameWidth: 680,
        frameHeight: 430
    });
    
    $('a.signupNewsletter').fancybox({
        frameWidth: 680,
        frameHeight: 300
    });

    //Fixates virtual tours screen size on IE7
    var p = document.getElementById("pano");
    if(p)
    {
        $('#pano').css('height', '200px');
    }
	
	
    // Transitions the main page Special Offers list
    var o = document.getElementById("experience-transition"); //if this ID does not exist, do not initialise the code
    if(o)
    {
        $('ul#experience-transition').innerfade({
            speed: 1000,
            timeout: 5000,
            type: 'sequence',
            containerheight: '160px'
        });
    }
    
    //Sets the return date to the departure date when the departure date is selected
    $('#sDepDate').change(function() {
    	$('#sRetDate').datepicker("setDate", $('#sDepDate').datepicker('getDate'));
    });
    
    $('#sDepDate').change(function() {
    	$('#sRetDate').datepicker2("setDate", $('#sDepDate').datepicker2('getDate'));
    });
    
    $('#fromdate').change(function() {
    	$('#todate').datepicker("setDate", $('#fromdate').datepicker('getDate'));
		
		$('#indate').val($('#fromdate').val());
		$('#outdate').val($('#todate').val());
    });

    $('#todate').change(function() {
		$('#outdate').val($('#todate').val());
	});
	
	$('#package_wiz').hide();
});

$(window).load(function(){
	if ($.browser.msie) {
		$('#frmAvail div.dropdownPanel').show().hide();
	}
});

// Takes an array of DOM elements and sets all their heights to be equal
// to the highest element.
function evenHeight(elements) {
    var highest = 0;

    jQuery.each( elements, function(){
        if (this.height() > highest)
            highest = this.height();
    });

    jQuery.each( elements, function(){
        this.height(highest);
    });
}


function checkGoogleEarthArrows()
{
    var googleEarthList = $("#googleEarth .items");
    var itemCount = googleEarthList.children("li").size();
    var googleEarthArrows = $("#googleEarth .browse");


    if (itemCount < 9)
    {
        googleEarthArrows.hide("fast");
        var leftMargin = ((8.5-itemCount)*60)/2
        googleEarthList.attr("style", "left:"+leftMargin+"px;");

    }
}





/**
 * CountDown class
 * @version 1.0
 * @author Thierry Jossermoz
 * 
 * @param int duration (seconds)
 * @param hash options (function onRefresh, function onFinish)
 * @return CountDown
 */
function CountDown(duration, options) {

    options = jQuery.extend({
        onRefresh: function() {},
        onFinish: function() {}
    }, options);

    this.onRefresh = options.onRefresh;
    this.onFinish = options.onFinish;

    this._duration = duration;
    this._start = new Date();
    this._timer = window.setInterval((function(context) {
        // return function bound to context's execution scope
        return function() {
            context._refresh();
        };
    })(this), 100);
}

CountDown.prototype = {
    // Protected properties
    _timer: null, // Interval
    _start: null, // Date
    _duration: 0, // int
    _elapsed: 0,  // int

    // Protected methods
    _refresh: function() {
        var currentDate = new Date(), previousElapsed = this.getElapsed();
        this._elapsed = parseInt((currentDate.getTime() - this._start.getTime()) / 1000);
        if (this._elapsed === this._duration) {
            window.clearInterval(this._timer);
            this.onFinish();
        } else if (this._elapsed !== previousElapsed) {
            this.onRefresh();
        }
    },
  
    // Public accessors
    getDuration: function() {
        return this._duration;
    },
    getElapsed: function() {
        return this._elapsed;
    },
    getRemaining: function() {
        return this.getDuration() - this.getElapsed();
    },

    // Callbacks
    onRefresh: null,
    onFinish: null
};


function configResortMenu()
{
    var area = $("#resortDropDown");
    var menu = $("#resortDropDown ul")
    var otherButtons = $("#mainNav > ul a[href != '/resort']");
    area.hide();
    var button = $("#mainNav a[href='/resort']");
    var xPos = button.position().left;
    var width = button.innerWidth();
    area.css("left", xPos+"px");
    area.css("width", width+"px");
    

    button.mouseenter( function(e) {

        button.addClass("hovered");
        menu.hide();
        area.show();
        menu.slideDown("fast");

    });

    area.mouseleave ( function(e) {

       area.fadeOut("slow");
       button.removeClass("hovered");

    });

        otherButtons.mouseenter ( function(e) {

       area.fadeOut("slow");
       button.removeClass("hovered");

    });
}


