// To avoid conflict with other libraries the CMS is using
jQuery.noConflict();

jQuery(document).ready(function($){
	// z-index fix for IE6/7 on home page
	var zIndexNumber = 1000;
	$("#home div").each(function() {
		$(this).css('zIndex', zIndexNumber);
		zIndexNumber -= 10;
	});
	
	// Empty field check
	$.fn.checkEmpty = function() { 
    	var field = $(this).text().replace(/ /g,'');
		if (field == "") {
			return true;
		}
		else {
			return false;	
		}
	};
	
	// Open link in new window (as opposed to using the "target" attribute)
	$('a[rel=external]').click(function(){
        window.open(this.href);
        return false;
    });
	
	$("#supporters a").each(function() {
		if ($(this).attr("href").replace(/ /g,'') == "") {
			$(this).css({cursor: "default"});
			$(this).click(function() {return false;});
		}
	});
	
	// URL parameters function
	$.extend({
		getUrlVars: function(){
			var vars = [], hash;
			var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
			for(var i = 0; i < hashes.length; i++)
			{
				hash = hashes[i].split('=');
				vars.push(hash[0]);
				vars[hash[0]] = hash[1];
			}
			return vars;
		},
		getUrlVar: function(name){
			return $.getUrlVars()[name];
		}
	});
	
	// CHOOSE A DESTINATION JUMP MENU
	$("#btnSubmit").click(function() {
		if ($("#ddlDestinationMenu option:selected ").val() != "") {		
			window.location.href = $("#ddlDestinationMenu option:selected").val();
		}
		return false;											
	});
	
	// FOOTER SUBSCRIBE EMAIL FIELD	
	$("#txtNewsletterEmail").each(function() {
		var defaultValue = "enter email address";
		var currentValue;
		
		$(this).val(defaultValue);
		
		$(this).focus(function() {
			currentValue = $(this).val();
			if(currentValue == (defaultValue || "")) {
				$(this).val("");
			}
		}).blur(function() {
			currentValue = $(this).val().replace(/ /g,'');
			if(currentValue == "") {
				$(this).val(defaultValue);
			}
		});							   
	});
	
	
	
	// BLOG RECENT POSTS MODULE
	if ($("#blogArticlesModule").length) {
		$("#blogArticlesModule .post-body p").truncatable({limit: 90});
	}
	
	// FOOTER NAV
	$("#footerNav ul li:even").addClass("border");
	
	$("#heroBanner div.slide a").click(function() {
		var bannerLink = $(this).attr("href");
		if (bannerLink == "") {
			$(this).attr("href", "#").css({cursor: "default"});
			return false;
		}
	});
	
	// Superfish drop-down with HoverIntent
	$("ul#nav_768815").superfish({
		autoArrows:		false,
		animation:		{height:'show'},
		delay:			400,
		speed:			400
	});
	
	// Breadcrumbs
	$("#breadcrumbs a:not(:last)").addClass("grey");
	
	/* CAROUSEL */
	
	// Overwrite current active slide behaviour
	$.fn.cycle.updateActivePagerLink = function(pager, currSlideIndex) { 
		$(pager).find('li').removeClass('selected').filter('li#'+currSlideIndex).addClass('selected'); 
	};
	
	// Call Cycle
	$("#heroBanner").cycle({ 
		fx:    'fade', 
		speed:  1000,
		pager:  '#carouselNav',
		pagerAnchorBuilder: function(idx, slide) { 
			return $("<li id="+ (idx) + "><a href='#' >" + (idx+1) + "</a></li>").insertBefore("#next"); 
		},
		slideExpr: 'div.slide',
		prev:    '#prev a',
        next:    '#next a'
	 });
	
	// Pause button
	$("#pause").click(function() {
		$("#heroBanner").cycle("pause");
		return false;
	});
	// Resume cycle by going to another slide
	$("#heroBanner li:not(#pause)").click(function() {
		$("#heroBanner").cycle("resume");
	});
	
	// HOME MODULE
	$(".module a img").parent().css({
		// Add properties to "a" element to prepare for overlay
		position: "relative", 
		display: "block", 
		width: "234px", 
		height: "115px"
	});
	
	$.fn.moduleOverlay = function() {
		$(this).append("<span class='overlay'></span>");
		$("span.overlay").css({opacity: 0.35});
		return this;
	};
	
	$("#home .module > a").hover(function() {
		// Create overlay span on hover
		$(this).moduleOverlay();
		$(this).parent().find("h3 a").addClass("hover");
	}, function() {
		$("span.overlay").remove();
		$(this).parent().find("h3 a").removeClass("hover");
	});
	
	$("#home .module h3 a").hover(function() {
		$(this).parent().prev().moduleOverlay();
	}, function() {
		$("span.overlay").remove();
	});
	
	// INTRO ACCORDION
	
	if(!$("#intro").hasClass("resort")) { // Remove "if" statement to enable accordion for Resort page
		$("#intro > div").hide();
		$("#intro h2").addClass("expand").click(function() {
			$(this).next().slideToggle(500);
			$(this).toggleClass("collapse");
			return false;
		}).hover(function() {
			$(this).addClass("grey");
		}, function() {
			$(this).removeClass("grey");
		});
	}
	
	// TABS
	$(".tabContent").hide(); //Hide all content
	$("ul#tabs li:first").addClass("active").show(); //Activate first tab
	$(".tabContent:first").show(); //Show first tab content

	// On Click Event
	$("ul#tabs li a").click(function() {
		$("ul#tabs li").removeClass("active"); //Remove any "active" class
		$(this).parent().addClass("active"); //Add "active" class to selected tab
		$(".tabContent").hide(); //Hide all tab content

		var activeTab = $(this).attr("href"); //Find the href attribute value to identify the active tab + content
		$(activeTab).show();
		return false;
	});
	
	// Hide empty fields on package detail page
	$(".sideInfo ul li span, #mSkillLevel p, #mFact p").each(function() {
		if ($(this).checkEmpty() === true) {
			$(this).parent().hide();	
		}
	});
	
	// Print function
	$("#print a").click(function() {
		window.print();
		return false;
	});
	
	
	// // Split Skill Level string and put into list
	(function() {
		var string = $("#mSkillLevel div").text();
		var splitString = string.split(",");
		$("#mSkillLevel div").html("<ul></ul>");
		for(i = 0; i < splitString.length; i++){
			$("<li><strong>" + splitString[i] + "</strong></li>").appendTo("#mSkillLevel ul"); 
		}
	})();
	
	//BOOKINGS
	
	// Append price to Booking button on package detail page
	$("#bookingLinks li span").each(function() {
		if ($(this).text() == "0" || $(this).checkEmpty() === true) {
			$(this).parent().hide();
		}
		else {
			var price = $(this).text();
			$(this).prev().append("&nbsp;$" + price);
			$(this).hide();
		}
	});
	// Pass Booking Price into Booking form page
	$("#bookingLinks li a").each(function() {
		var originalLink = $(this).attr("href");
		var price = $(this).next().text();
		var newLink = originalLink + "&price=" + price; // With price parameter appended
		$(this).attr("href", newLink);
	});
	
	if ($("#booking").hasClass("item")) {
		// Add price to Booking page
		var packagePrice = $.getUrlVar("price");
		var depositPrice = (packagePrice * 0.2).toFixed(2);
		
		$("#price").html("AU$"+packagePrice);
		$("#Amount").val(depositPrice);
		
		// Place Booking heading after module
		$("#booking h3:first").hide().clone().insertAfter(".module:first").show();
		
		// Calculate value
		/*$("#CAT_Custom_128167").change(function() {
			var persons = $("option:selected",this).val();
			$("#Amount").val(depositPrice * persons);
		});*/
	}
	
	// SUBSCRIBE
	(function() {
		var email = $.getUrlVar("email");
		$("#EmailAddress").val(email);
	}());
	
	$("#newsletterForm form").bind("submit", function(){
		var originalLink = $("#newsletterForm a").attr("href");
		var email = $("#txtNewsletterEmail").val();
		window.location.href = originalLink + "?&email=" + email; // With email parameter appended
		return false;
	});
	
	$("#newsletterForm a").click(function() {
		var originalLink = $(this).attr("href");
		var email = $("#txtNewsletterEmail").val();
		var newLink = originalLink + "?&email=" + email; // With email parameter appended
		$(this).attr("href", newLink);									  
	});
	
	// WEB APP LISTING - Change 'No items found' message
	$("#itemList").each(function() {
		$(this).html($(this).html().replace("No items found.","<hr /><p>There are no listings for this section.</p>"));
	});
	
	if($("#itemList h2").hasClass("resortDetail")) {
		$("#itemList").html("<h2>Special Packages</h2><hr /><p class='leftMargin20px'>Coming soon.</p>");	
	}
	
	// BLOG COMMENT CONFIRMATION
	$(".confirmationMessage").each(function() {
		if ($(this).text() != "") {
			$(this).show();	
		}
	});
	
	// BLOG COMMENTS TO DISPLAY ONLY ON INDIVIDUAL POST PAGE
	if(!$(".blog-container .post-body .btn93px").length) {
		$("#primaryContent .commentDisplay").show();
	}
	
	// FANCYBOX
	if ($(".link a:first").hasClass("fancyboxLink")) {
		$("a.fancyboxLink").fancybox();
	}
	else if($("div.item:first").hasClass("mediaAndPress")) {
		$("div.hide span.itemType").each(function() {
			var galleryRel = $(this).text();
			$(this).parent().find(".fancyboxLink").attr("rel",galleryRel);
			
			if (galleryRel == "Video Appearances" && !($.browser.msie && ($.browser.version=="6.0" || $.browser.version=="7.0"))) {
				var videoID = $(this).parent().find(".youtubeVideo").attr("id");
				var videoLink = "#"+videoID;
				$(this).parent().find(".fancyboxLink").attr("href", videoLink);
			}
		});	
		
		$(".item a").click(function() {
			var medium = $(this).attr("title");
			$("a[rel="+medium+"]:first").trigger("click");
			return false;
		});
		
	}
	
	// COUNTRIES - hide "Read more" text
	$("#countries #intro div a:contains('Read more')").hide();

});
// VIDEO FUNCTION
function addVideo(id, url) {
	var so = new SWFObject('/extras/player-licensed.swf','ply','470','320','9','#ffffff');
	so.addParam('allowfullscreen','true');
	so.addParam('allowscriptaccess','always');
	so.addParam('wmode','transparent');
	so.addVariable('file',url);
	so.write(id);
}