/*
* Global.js
* Javascript control for the global content on ALL pages
* Uses the juery library on majority of functions
* Includes Javascript dropdowns on the Global Nav(s)
* Doesn't include the homepage scroller for the parks. Refer myfuncomau.js 
*
* Last Updated 10/06/2010
* Author: GF
*/


// Switches to No-Conflict mode by re-writing all '$' as 'j' to avoid conflict with other Javascript libraries.
var j = jQuery.noConflict();


//Flag al pages only when JS is enabled
jQuery('html').addClass("js-enabled");



/* ---------------------------------------------------- */
/* Set equal heights on the fotter columns */
/* ---------------------------------------------------- */
jQuery(document).ready(function () {
    jQuery(".footerCol").equalHeights();
    jQuery(".feature").equalHeights();
    jQuery("#hotDeals .deal").equalHeights();
    jQuery(".squareblock").equalHeights();
});


/* ---------------------------------------------------- */
/* Initiate Drop downs for the GlobalNav Topbar lonks */
/* ---------------------------------------------------- */
jQuery(document).ready(function () {
	/*jQuery("#selectRegion").msDropDown();*/
	//var globalDropDown = jQuery("#globalNav select").msDropDown({ mainCSS: 'dd-header' });
	var secondBarDropDown = jQuery("#secondBar select:first").msDropDown({ mainCSS: 'dd-header' });
	jQuery("#regionSelect select").msDropDown({ mainCSS: 'dd-header' });
	jQuery("#subNav select#ticketDrop").msDropDown();
	jQuery("#subNav select#content_0_corporateleftcolumn_0_ticketDrop").msDropDown();

	if (typeof (secondBarDropDown) !== 'undefined') {

		secondBarDropDown.bind('change', function (e) {

			if (e == null || e.target == null || e.target.options == null || e.target.options.selectedIndex == null) {
				return;
			}

			// Get the selected index and then the element ID
			var selIndex = e.target.options.selectedIndex;
			var elemID = '#location' + (selIndex + 1);

			// if the jQuery object exists, show it and hide the rest
			if (jQuery(elemID).length > 0) {

				// Hide all the regions
				jQuery("#secondBar .parksNav").each(function () {
					jQuery(this).css('display', 'none');
				});

				// Show only the selected region.
				jQuery(elemID).css('display', 'block');
			}

		});

	}

});

   function changeHeader() {
   	alert('woo');
   }



/* --------------------------------------------------------- */
/* TopNav Dropdowns */
/* --------------------------------------------------------- */

jQuery(document).ready(function () {
    jQuery("#globalNav .rightNav div.dropBox").hide();

    jQuery("#globalNav .rightNav li a.hasDrop").click(function () {
        jQuery(".dropBox").hide();
        jQuery(this).parents("li").find(".dropBox").toggle();
        return false;
    });

    jQuery("#globalNav .rightNav li a.closeBox").click(function () {
        jQuery(".dropBox").hide();
        return false;
    });

    jQuery("#globalNav li.has-child a").hover(function () {
        jQuery("ul.allAtractions").show();
    }, function () {
        jQuery("ul.allAtractions").hide();
    });
});


/* --------------------------------------------------------- */
/* Member Content */
/* --------------------------------------------------------- */

//jQuery(document).ready(function () {
//    var str = jQuery.cookie("MemberID");
//    var str2 = jQuery.cookie("MemberGUID");
//    var str3 = jQuery.cookie("RegID");

//    if (((str != null) || (str3 != null)) && (str2 != null)) {
//        jQuery("div#memberloggedout").hide();
//        jQuery("div#memberloggedin").show();
//        jQuery("div#memberloggedoutofferSW").hide();
//        jQuery("div#memberloggedinofferSW").show();
//        jQuery("div#memberloggedoutofferSWR").hide();
//        jQuery("div#memberloggedinofferSWR").show();
//        jQuery("div#memberloggedoutofferWW").hide();
//        jQuery("div#memberloggedinofferWW").show();
//        jQuery("div#memberloggedoutofferMW").hide();
//        jQuery("div#memberloggedinofferMW").show();
//        return true;
//    } else {
//        jQuery("div#memberloggedin").hide();
//        jQuery("div#memberloggedout").show();
//        jQuery("div#memberloggedinofferSW").hide();
//        jQuery("div#memberloggedoutofferSW").show();
//        jQuery("div#memberloggedinofferSWR").hide();
//        jQuery("div#memberloggedoutofferSWR").show();
//        jQuery("div#memberloggedinofferWW").hide();
//        jQuery("div#memberloggedoutofferWW").show();
//        jQuery("div#memberloggedinofferMW").hide();
//        jQuery("div#memberloggedoutofferMW").show();
//        return true;
//    }

//});


/* --------------------------------------------------------- */
/* KidsFun JS */
/* --------------------------------------------------------- */

function MM_preloadImages() { //v3.0
    var d = document; if (d.images) {
        if (!d.MM_p) d.MM_p = new Array();
        var i, j = d.MM_p.length, a = MM_preloadImages.arguments; for (i = 0; i < a.length; i++)
            if (a[i].indexOf("#") != 0) { d.MM_p[j] = new Image; d.MM_p[j++].src = a[i]; } 
    }
}
function MM_swapImgRestore() { //v3.0
    var i, x, a = document.MM_sr; for (i = 0; a && i < a.length && (x = a[i]) && x.oSrc; i++) x.src = x.oSrc;
}
function MM_findObjQuery(n, d) { //v4.01
    var p, i, x; if (!d) d = document; if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
        d = parent.frames[n.substring(p + 1)].document; n = n.substring(0, p);
    }
    if (!(x = d[n]) && d.all) x = d.all[n]; for (i = 0; !x && i < d.forms.length; i++) x = d.forms[i][n];
    for (i = 0; !x && d.layers && i < d.layers.length; i++) x = MM_findObjQuery(n, d.layers[i].document);
    if (!x && d.getElementById) x = d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
    var i, j = 0, x, a = MM_swapImage.arguments; document.MM_sr = new Array; for (i = 0; i < (a.length - 2); i += 3)
        if ((x = MM_findObjQuery(a[i])) != null) { document.MM_sr[j++] = x; if (!x.oSrc) x.oSrc = x.src; x.src = a[i + 2]; }
}


/* --------------------------------------------------------- */
/* Booking Attractions Form on Homepage */
/* --------------------------------------------------------- */

function updateAction(form) {
    var comboValue
    var selIndex = form.whereTo.selectedIndex;
    comboValue = form.whereTo.options[selIndex].value;

    if (comboValue == "MW")
        form.action = 'https://shop.myfun.com.au/movieworld-tickets.asp';
    else if (comboValue == "SW")
        form.action = 'https://shop.myfun.com.au/seaworld-tickets.asp';
    else if (comboValue == "WnW")
        form.action = 'https://shop.myfun.com.au/wetnwild-tickets.asp';
    else if (comboValue == "AOS")
        form.action = 'https://shop.myfun.com.au/australianoutbackspectacular-tickets.asp';
    else if (comboValue == "PC") {
        form.VenueID.value = "30";
        form.AttractionID.value = "0";
        form.action = 'https://shop.myfun.com.au/attraction-highlight.asp';
    } else if (comboValue == "SAQ")
        form.action = 'https://shop.myfun.com.au/sydney-aquarium-tickets.asp';
    else if (comboValue == "STO")
        form.action = 'https://shop.myfun.com.au/sydney-tower-tickets.asp';
    else if (comboValue == "SWW")
        form.action = 'https://shop.myfun.com.au/wildlife-world-tickets.asp';
    else if (comboValue == "MOW")
        form.action = 'https://shop.myfun.com.au/oceanworld-tickets.asp';
    else if (comboValue == "MAQ") {
        form.VenueID.value = "26";
        form.AttractionID.value = "64";
        form.action = 'https://shop.myfun.com.au/attraction-highlight.asp';
    } else
        form.action = 'https://shop.myfun.com.au/';
}





/* --------------------------------------------------------- */
/* Box office checkout term and conditions checkbox */
/* --------------------------------------------------------- */
jQuery(document).ready(function () {
    jQuery('.termchk').click(function () {
        if (jQuery(this).is(':checked')) {
            jQuery('.termbar .popup').show();
        } else {
            jQuery('.termbar .popup').hide();
        }
    });

    jQuery('.termbar .popup .ok').click(function () {
        jQuery('.termbar .popup').hide();
        return false;
    });
});





/* --------------------------------------------------------- */
/* Web Forms IE fix */
/* --------------------------------------------------------- */
jQuery(document).ready(function () {

	if (jQuery.browser.msie) {

		if (jQuery('.scfForm input[type="submit"]').length > 0) {
			// Get the existing click event as a string so we can remove the offending prefix
			var currentClickEvent = jQuery('.scfForm input[type="submit"]')[0].attributes.onclick.nodeValue;
	
			// remove the offending prefix
			currentClickEvent = currentClickEvent.replace("if (typeof Sitecore === 'undefined') { Sitecore = new Object();}if (typeof Sitecore.Wfm === 'undefined') {Sitecore.Wfm = new Object();} Sitecore.Wfm.SubmitCtrId = this.id;", "");
			
			// Generate the new click event
			var newClickEvent = new Function(currentClickEvent);
	
			// Reset the click event to use the new click event
			jQuery('.scfForm input[type="submit"]').attr('onclick', '').click(newClickEvent);
		}
	}

});





/* --------------------------------------------------------- */
/* SubSites Navigation */
/* --------------------------------------------------------- */

jQuery(document).ready(function () {

	var intInitialSetup = 0;

	// On window resize: resize containers
	jQuery(window).resize(function () {
		resizeC()
	});

	// There is an issue displaying the menu where all the links are visible before javascript kicks in.
	// To overcome this, we set the overflow to hidden by default and re-set to visible once the javascript has loaded.
	if (jQuery("#globalNav").length > 0) {
		jQuery("#globalNav").css('overflow', 'visible');
	}
	if (jQuery("#globalNav ul.leftNav div.parksNav").length > 0) {
		jQuery("#globalNav ul.leftNav div.parksNav").css('display', 'block');
	}

	// Init
	jQuery('html').removeClass('no-js');
	resizeC();

	// Park header selection
	//This section shows the selected park navigation items and hides the rest
	var selIndex = jQuery('.ddChild').children('.selected').index() + 1;
	jQuery('.leftNav li').children('div:eq(' + selIndex + ')').show();

	for (i = 1; i < 5; i++) {
	    if (i != selIndex) {
	        jQuery('.leftNav li').children('div:eq(' + i + ')').hide();
	    }
	}

	jQuery('.leftNav .dd .ddChild span').live('click', function () {
		var a = jQuery(this),
			b = a.parents('li'),
			c = jQuery('.leftNav .dd .ddChild span').index(a);

		b.children('div:not(:eq(0))').hide();
		b.children('div:eq(' + (c + 1) + ')').show();
	});

	// Region wrap
	jQuery('.ddChild > a').each(function () {
		jQuery(this).html('<span>' + jQuery(this).text() + '</span>')
	});

	// Handle items on window resize
	function resizeC() {

		// Top menu splash reposition
		var vportW = jQuery('#topBar').width();
		if (vportW <= 1002) jQuery('.logo-section').css('left', '431px');
		else {
			marginL = (jQuery('#topBar').width() / 2) - 59;
			jQuery('.logo-section').css('left', marginL + 'px')
		}

		// Regional menu
		jQuery('#globalNav ul.leftNav div.parksNav').each(function () {

			var 
			display = 0,
			navId = '#' + jQuery(this).attr('id');
			// If not visible, make it visible to calculate width
			if (jQuery(this).css('display') == 'block') display = 1 // Display is 'block'
			if (display == 0) jQuery(this).css('display', 'block');

			var 
				ulW = jQuery(navId + '> ul').width(),
				vportW = jQuery('#topBar').width(),
				rightNavW = jQuery('#topBar .rightNav').outerWidth(),
				logoW = 215,
				remainingW = vportW - rightNavW - logoW - 100;

			// Set width to <li>
			// Calculate
			jQuery(navId + ' > ul > li').each(function () {
				jQuery(this).attr('data-width', jQuery(this).outerWidth())
			});
			// End set width

			// Reset
			if (display == 0) jQuery(this).css('display', 'none');

			jQuery(navId + ' > ul > li').addClass('top-level');
			// Append 'more' <li> items
			if (!jQuery(navId + ' > ul > li:last-child').hasClass('has-child')) {
				jQuery(navId + ' > ul').append('<li class="has-child"><a href="#">More</a><ul></ul></li>')
			}
			// Calculations
			var noOfItems = jQuery(navId + ' > ul > li').length - 1

			// Move over
			var lastItem = noOfItems - 1;
			for (x = lastItem; x >= 0; x--) {
				jQuery(navId + ' > ul > li:eq(' + x + ')').clone().prependTo(navId + ' .has-child ul');
				jQuery(navId + ' > ul > li:eq(' + x + ')').addClass('removable')
			}
			// Remove duplicates: top level
			jQuery(navId + ' > ul > li.removable').remove()
			// Do the initial adjustments
			resizeMenu(navId);

			var newSecondBarWidth = (vportW - rightNavW);

			jQuery('#globalNav #secondBar').css('width', newSecondBarWidth + 'px');
		});

		var vportW = jQuery('#topBar').width(),
			rightNavW = jQuery('#topBar .rightNav').outerWidth(),
			logoW = 215,
			remainingW = vportW - rightNavW - logoW - 180;
	}

	function resizeMenu(navContID) {
		var 
			display = 0;
		// If not visible, make it visible to calculate width
		if (jQuery(navContID).css('display') == 'block') display = 1 // Display is 'block'
		if (display == 0) jQuery(navContID).css('display', 'block');

		//ulW = jQuery(navContID + ' > ul').width(),
		var 
		// Set the width of the menu to the initial width of the more link
			ulW = jQuery(navContID + 'ul li.has-child').outerWidth(),
			vportW = jQuery('#topBar').width(),
			rightNavW = jQuery('#topBar .rightNav').outerWidth(),
			logoW = 215,
			remainingW = vportW - rightNavW - logoW - 180;

		// Reset
		if (display == 0) jQuery(navContID).css('display', 'none');

		// set the link index and get the width of the More element;
		var linkIndex = 0;
		var dropDownWidth = jQuery(navContID + ' ul li.has-child').outerWidth();

		// Loop
		var moved = 0;
		jQuery(navContID + ' ul ul li').each(function () {

			// There is an issue where by the width is sometimes incorrectly read, so we need to determine the width of the ul
			// based on the number of items in it; Thus if we are at index 0, the width should only be the width of the More element.
			var 
				dataWidth = parseInt(jQuery(this).attr('data-width')),
				newULWidth = (ulW + dataWidth);

			// Calculate the remaining width without the dropdown with so we always have room for that
			var widthWithoutMoreLink = (remainingW - dropDownWidth);

			if (newULWidth < widthWithoutMoreLink && moved == 0) {
				// Add this item to nav
				insertPosIndex = jQuery(navContID + ' > ul > li').length - 1;
				jQuery(this).clone().insertBefore(navContID + ' > ul > li:eq(' + insertPosIndex + ')');
				jQuery(this).remove();
				// Set new width
				ulW += dataWidth
				linkIndex++;
			}
			else moved = 1
		});
		activateDropdown(navContID)
	}

	// Hide/Show region nav dropdown
	function activateDropdown(navContID) {
		var ddwonItemCount = jQuery(navContID + ' .has-child ul li').length;
		if (ddwonItemCount == 0) jQuery(navContID + ' .has-child').css('display', 'none')
		else jQuery(navContID + ' .has-child').css('display', '')
	}

});
