$(function(){
    
    // links with rel external should open in new window
    $('a[rel="external"]').attr( 'target', '_blank' );
    
    // track the opening of PDF files with Google Analytics
    $("#content a[href$='.pdf']").click(function(){
        window.open($(this).attr( "href" ));
        pageTracker._trackPageview($(this).attr( "href" ));
        return false;
    });
    
    // track certain outgoing links
    $("a.track").live('click', function(){
    	var href = $(this).attr("href");
        pageTracker._trackPageview(href);
        setTimeout(function(){
        	document.location.href = href;
        }, 500);
        return false;
    });
    
    // fader for promo banners
    $('#promo-fader').innerfade({ speed: 800, timeout: 3500, type: 'sequence', containerheight: '206px'});
    setInterval("$.promorotate('#rotate');", 4500);
    
    // handle month selections in the nature calendar
    $('#natureCalendar div').hide();
    $('#ncJan').show();
    $('#natureCalendarNav a').click(function(){
        var selectedMonth = $(this).attr('href');
        $('#natureCalendar div:visible').fadeOut(500,function(){
            $(selectedMonth).fadeIn(500, function(){
                if(jQuery.browser.msie) this.style.removeAttribute('filter');
            });
        });
        $('#natureCalendarNav li').removeClass('selected');
        $(this).parent().addClass('selected');
        return false;
    });
    
	
    // Lazy load from validation script
    $.getScript('http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js', function(){
    	
    	// Handle subscribe form
		$('#frm-subscribe')
			.find('#email')
			.data('default_value', $('#email').val().toString())
			.focus(function(){
				if($(this).val()==$(this).data('default_value'))
				{
					$(this).val('');
				}
			})
			.blur(function(){
				if($(this).val()=='')
				{
					$(this).val($(this).data('default_value'));
				}				
			})
			.end()
			.validate({
				submitHandler: function(form){
					$.post('/subscribe.php', $(form).serialize(), function(){
						$('#frm-subscribe').replaceWith('<div id="subscribe-success">Thank you. Your subscription was successful.</div>');
					});
				},
				rules: {
					'cm-mburi-mburi': {
						required: true,
						email: true
					}
				},
				messages: {
					'cm-mburi-mburi': {
						required: 'Email required',
						email: 'Address invalid'
					}
				}
			});

            // New accommodation page booking form
            $('#booking-form form').validate({
				rules: {
                    'Name': 'required',
					'Email': {
						required: true,
						email: true
					},
                    'Preferred Dates': 'required',
                    'Guest Info': 'required'
				},
				messages: {
					'Email': {
						required: 'Email required',
						email: 'Address invalid'
					}
				}
			});
		
    });

    // handle enquiry box on new accommodation page
    $('a.enquire').click(function(){
        var property = $(this).attr('title');
        $('#TB_ajaxContent h3').text('Accommodation Enquiry - ' + property);
        $('#TB_ajaxContent input[name=property]').val(property);
    });

    // show inclusions on the new accom page
    $('a.showinclusions').click(function(){
        $(this).closest('tr.propertyrecord').addClass('inclusionsactive').next().show();
        $(this).css('visibility', 'hidden');
        return false;
    });

    $('a.showinlineinclusions').click(function(){
        $(this).css('visibility', 'hidden').next().show();
        return false;
    });
    
	// add link tracking behaviors
	$.trackLinkClicks();
	
});

jQuery.promorotate = function(selector)
{
	var speed = 750;
	var container = $(selector);
	var active_element = $(container).children(':visible');
	active_element.slideUp(speed, function(){
		if(active_element.next().length == 0)
		{
			$(container).children(':first-child').slideDown(speed);			
		}
		else
		{
			active_element.next().slideDown(speed);
		}
	});
}

jQuery.trackLinkClicks = function() {
	
    var filetypes = /\.(zip|exe|doc*|xls*|ppt*|mp3)$/i;

    $('a').each(function(){
        var href = $(this).attr('href');
        if ((href.match(/^https?\:/i)) && (!href.match(document.domain))){
            $(this).click(function() {
                var extLink = href.replace(/^https?\:\/\//i, '');
                _gaq.push(['_trackEvent', 'External', 'Click', extLink]);       
            }); 
        }
        else if (href.match(/^mailto\:/i)){
            $(this).click(function() {
                var mailLink = href.replace(/^mailto\:/i, '');
                _gaq.push(['_trackEvent', 'Email', 'Click', mailLink]);
            });
        }
        else if (href.match(filetypes)){
            $(this).click(function() {
                var extension = (/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined;
                var filePath = href.replace(/^https?\:\/\/(www.)lordhoweisland\.info\//i, '');
                _gaq.push(['_trackEvent', 'Download', 'Click - ' + extension, filePath]);
            });
        }
    });	
}
