WDPRO = window.WDPRO || {};

WDPRO_LOADER.require("dom");
WDPRO_LOADER.require("event");
WDPRO_LOADER.require("element");
WDPRO_LOADER.require("container");
WDPRO_LOADER.require("formUtils");
WDPRO_LOADER.require("connection");
WDPRO_LOADER.require("selector");
WDPRO_LOADER.require("json");

/** Menu toggle **/
WDPRO_LOADER.addCallback(function() {
    var $D = WDPRO.util.Dom;
    var	$Q = YAHOO.util.Selector.query;
    var $C = YAHOO.util.Connect;
    var $E = YAHOO.util.Event;
    var $J = YAHOO.lang.JSON;
    
    var toggleNav = function( list ){
            var $D = WDPRO.util.Dom;
            var parent = list.parentNode;
            var parentUL = parent.getElementsByTagName( 'ul' );

            // get first ul only and assign property so other uls don't show
            if ( parentUL[0].style.display == "none" ) {
                $D.setStyle( parentUL[0], 'display', 'block');
            } else {
                $D.setStyle( parentUL[0], 'display', 'none');
            }
    }
    
    if( $D.get( 'leftNavList' ) ) {
        var navigation = $D.get( 'leftNavList' );
        var navSubUL = navigation.getElementsByTagName( 'ul' );
        var navSubLink = navigation.getElementsByTagName( 'a' );

        for ( i = 0; i < navSubLink.length; i++ ){
                if ( navSubLink[i].className.match( 'nested' ) ) {
                    navSubLink[i].onclick = function () {
                        toggleNav(this);
                        return;
                    }
                }
            // give parents a class
            navSubLink[i].parentNode.className = "expandable";
        }

        // hide nested uls
        for( i= 0; i < navSubUL.length; i++ ) {
            navSubUL[i].style.display = 'none';
        }
    }
    
    /** All a[rel=external] elements will show leaving site overlay **/
    
	$E.on($Q("a[rel=external]"), 'click', function(e) {
		$E.preventDefault(e);
		$D.replaceClass('siteMask', 'hide', 'masked');
		$D.get('siteMask').style.height = $D.getDocumentHeight() + "px";
		$D.get('confirmLeavingSite').href= this.href;
		$D.replaceClass('leavingSite', 'hide', 'show');
	});
    
	$E.on($D.getElementsByClassName("leavingSiteButton"), 'click', function(e) {
		$D.replaceClass('leavingSite', 'show', 'hide');
		$D.replaceClass('siteMask', 'masked', 'hide');
	});
    
    /** End leaving site overlay **/
	
    /** Start AutoSuggest **/
    var AutoSuggest = function() {
        var obj = this;
        var timeout = null;
        this.partialQuery = '';
        this.input = null;
        this.suggestionList = null;
        var cache = {};
        
        this.previous = function(input) {
            obj.input = input;
            var suggestionList = obj.getSuggestionList();
            var children = $D.getChildren(suggestionList);
            if (!children.length) {
                return;
            }
            --suggestionList.currentSuggestion; 
            hilightCurrentSuggestion(suggestionList);
        };
        
        this.next = function(input) {
            obj.input = input;
            var suggestionList = obj.getSuggestionList();
            var children = $D.getChildren(suggestionList);
            if (!children.length) {
                return;
            }
            ++suggestionList.currentSuggestion; 
            hilightCurrentSuggestion(suggestionList);
        };
        
        this.cancel = function(input) {
            obj.input = input;
            var suggestionList = obj.getSuggestionList();
            suggestionList.currentSuggestion = -1;
            hilightCurrentSuggestion(suggestionList);
            suggestionList.style.display = 'none';
        }
        
        var hilightCurrentSuggestion = function(suggestionList)
        {
            var children = $D.getChildren(suggestionList);
            
            if (suggestionList.currentSuggestion >= children.length) {
                // At bottom and guest pressed NEXT
                suggestionList.currentSuggestion = -1;
            } else if (suggestionList.currentSuggestion <= -2) {
                // At input box and guest pressed PREVIOUS
                suggestionList.currentSuggestion = children.length - 1;
            } else if (-1 ==suggestionList.currentSuggestion) {
                // Arriving at input box restores value
                if (obj.input.originalValue) {
                    obj.input.value = obj.input.originalValue;
                    obj.input.originalValue = false;
                }
            }
            
            if (suggestionList.currentSuggestion >= 0) {
                // Keep track of guest's original value
                if (!obj.input.originalValue) {
                    obj.input.originalValue = obj.input.value;
                }
                obj.input.value = children[suggestionList.currentSuggestion].innerHTML;
            }
            
            for (i in children) {
                $D.removeClass(children[i], 'current');
                if (i == suggestionList.currentSuggestion) {
                    $D.addClass(children[i], 'current');
                }
            }
            
            suggestionList.style.display = 'block';
        };
        
        this.suggest = function(partialQuery, input) {
            if (null !== timeout) {
                window.clearTimeout(timeout);
                timeout = null;
            }
            partialQuery = partialQuery.replace(/^\s+|\s+$/g, '');
            obj.partialQuery = partialQuery;
            obj.input = input;
            
            if (partialQuery.length < 3) {
                // empty out suggestions
                applySuggestions({});
            } else if (typeof(cache[partialQuery]) != 'undefined') {
                // use cache
                applySuggestions(cache[partialQuery]);
            } else {
                // get suggestions via ajax
                timeout = window.setTimeout(function(){obj.doSuggest();}, 1000);
            }
        };
        
        this.doSuggest = function() {
            // Ensure timeout is cleared
            window.clearTimeout(timeout);
            timeout = null;
            
            // Load suggestions
            //console.log('suggesting for:', obj.partialQuery);
            ajaxAutoSuggest(obj.partialQuery);
        };
        
        var handleSelectAutosuggestion = function(evt)
        {
            var target = $E.getTarget(evt);
            if ('LI' != target.tagName) {
                return;
            }
            var suggestionList = obj.getSuggestionList();
            suggestionList.style.display = 'none';
            obj.input.value = target.innerHTML;
            window.setTimeout(function(){
                obj.input.focus();
            }, 10);
        };
        
        this.getSuggestionList = function()
        {
            if (null === obj.suggestionList) {
                obj.suggestionList = document.createElement('ul');
                $D.addClass(obj.suggestionList, 'autosuggest');
                $E.on(obj.suggestionList, 'click', handleSelectAutosuggestion);
                obj.suggestionList.currentSuggestion = -1;
            }
            return obj.suggestionList;
        }
        
        var clearSuggestions = function(suggestionList)
        {
            var oldSuggestions = $D.getChildren(suggestionList);
            for (var i in oldSuggestions) {
                suggestionList.removeChild(oldSuggestions[i]);
            }
        };
        
        // Search box autosuggest
        onSuccessAutoSuggestResponse = function(r) {
            cache[r.argument.partialQuery] = $J.parse(r.responseText);
            applySuggestions(cache[r.argument.partialQuery]);
        };
        
        var applySuggestions = function(data)
        {
            var suggestionList = obj.getSuggestionList();
            
            // Clear previous suggestions if they exist
            clearSuggestions(suggestionList);
            if (data.length) {
                //console.log('gots data!');
                for (var i in data) {
                    var suggestion = document.createElement('li');
                    suggestion.innerHTML = data[i];
                    suggestionList.appendChild(suggestion);
                }
                $D.insertAfter(suggestionList, obj.input);
                suggestionList.style.display = 'block';
            } else {
                suggestionList.style.display = 'none';
            }
            suggestionList.currentSuggestion = -1;
        };
        
        var ajaxAutoSuggest = function(partialQuery) {
            var method = 'GET';
            var uri = '/search/autosuggest?format=json&q=' + encodeURIComponent(partialQuery);
            $C.asyncRequest(method, uri, {success: onSuccessAutoSuggestResponse, argument: {partialQuery: partialQuery}});
        };
    };
    var as = new AutoSuggest();
    
    var queryTermInputs = $D.getElementsByClassName('queryTerm');
    for (var i = 0, l = queryTermInputs.length; i < l; i++) {
        queryTermInputs[i].autocomplete = "off";
        $E.on(queryTermInputs[i], "keyup", function(evt) {
            //console.log('key', evt.keyCode);
            switch (evt.keyCode) {
                // Up
                case 38:
                    as.previous(this);
                    break;
                    
                // Down
                case 40:
                    as.next(this);
                    break;
                    
                // Escape
                case 27:
                    as.cancel(this);
                    break;
                    
                // All others
                default:
                    as.suggest(this.value, this);
            }
        });
    }
    
   /** End AutoSuggest **/
    
   /** Start Global Sports Footer + Mailing List Sign Up **/     
   if ($D.get("footerMailingSignUpSelectValue")){
    	$D.get("footerMailingSignUpSelectValue").innerHTML = "Choose a sport";
   } 
    
   $E.on($D.getElementsByClassName("footerMailingEmail"), "click", function(evt) {
	   if ((this.value == "Enter Email")){
 		   this.value = "";
		   $D.setStyle(this, 'color', '#C82A27');
		   $D.setStyle(this, 'font-weight', 'bold');
	   }
   })
   
   // needed for the "styled" select box
   $E.on($D.getElementsByClassName("footerMailingSignUpSelectOptions"), "click", function(evt) {
	   $D.get("footerMailingListSport").size = "8";
	   $D.addClass("footerMailingListSport", "optionOpen");
   })  

   // Setting ELM listID and folderID according to the sport selected; styling for the "styled" select box
   $E.on($D.get("footerMailingListSport"), "change", function(evt) {
	   $D.removeClass("footerMailingListSport", "optionOpen");
	   $D.get("footerMailingListSport").size = "1";
	   $Q("#sportsFooter input[id=folder]")[0].value = '100';
	   
	   switch(this.value) {
	   		case 'Baseball':
	   			$D.get('footerMailingSignUpSelectValue').innerHTML = "Disney Baseball";
	   			$Q("#sportsFooter input[id=list]")[0].value = '3491';
	   			break;
	   		case 'FieldHockey':
	   			$D.get('footerMailingSignUpSelectValue').innerHTML = "Disney Field Hockey";
	   			$Q("#sportsFooter input[id=list]")[0].value = '2941';
	   			break;
	   		case 'SpringTraining':
	   			$D.get('footerMailingSignUpSelectValue').innerHTML = "Disney Spring Training";
	   			$Q("#sportsFooter input[id=list]")[0].value = '2271';
	   			break;
	   		case 'SlowpitchSoftball':
	   			$D.get('footerMailingSignUpSelectValue').innerHTML = "Disney Slowpitch Softball";
	   			$Q("#sportsFooter input[id=list]")[0].value = '3688';
	   			break;
	   		case 'Soccer':
	   			$D.get('footerMailingSignUpSelectValue').innerHTML = "Disney Soccer";
	   			$Q("#sportsFooter input[id=list]")[0].value = '4212';
	   			break;
	   		case 'TrackAndField':
	   			$D.get('footerMailingSignUpSelectValue').innerHTML = "Disney Track & Field";
	   			$Q("#sportsFooter input[id=list]")[0].value = '3536';
	   			break;
	   		case 'CrossCountry':
	   			$D.get('footerMailingSignUpSelectValue').innerHTML = "Disney Cross Country";
	   			$Q("#sportsFooter input[id=list]")[0].value = '3872';
	   			break;
	   		case 'BravesSpringTraining':
	   			$D.get('footerMailingSignUpSelectValue').innerHTML = "Atlanta Braves Spring Training";
	   			$Q("#sportsFooter input[id=list]")[0].value = '6031';
	   			break;
	   		case 'Volunteer':
	   			$D.get('footerMailingSignUpSelectValue').innerHTML = "Volunteer";
	   			$Q("#sportsFooter input[id=list]")[0].value = '2933';
	   			break;
	   		case 'runDisney':
	   			$D.get('footerMailingSignUpSelectValue').innerHTML = "runDisney";
	   			$Q("#sportsFooter input[id=list]")[0].value = '2692';
	   			break;	   
	   		default:
	   			$D.get('footerMailingSignUpSelectValue').innerHTML = "Choose a sport";
	   			$Q("#sportsFooter input[id=list]")[0].value = '';
	   			$Q("#sportsFooter input[id=folder]")[0].value = '';
	   }
   });
   
   // Hide the mailing list dropdown if clicking anywhere outside the mailingSignUpSelectOptions div
   $E.on(document.body, "click", function(evt) {
       var target = $E.getTarget(evt);
       if ($D.get("footerMailingListSport")){
	       if (!$D.hasClass(target, 'footerMailingSignUpSelectOptions') && !$D.getAncestorByClassName(target, 'footerMailingSignUpSelectOptions')) {
	    	   $D.removeClass("footerMailingListSport", "optionOpen");
	    	   $D.get("footerMailingListSport").size = "1";
	       }
       }
   });
   
   $E.on($D.get("footerMailingListSubmitButton"), "click", function(evt) {
		$E.preventDefault(evt);

		// Clear all the errors messages
		var ulErrors = $D.getElementsByClassName("errors", "ul");
		for (var i=0; i<ulErrors.length; i++) {
			var parentElement = $D.getAncestorByTagName(ulErrors[i], 'dd');
			parentElement.removeChild(ulErrors[i]);			
		}
		
		var highlight = function(el) {
			$D.setStyle(el, 'border-color', '#F00');
			$D.setStyle(el, 'border-width', '2px');
		}
		var clearHighlight = function(el) {
			$D.setStyle(el, 'border-color', '#000');
			$D.setStyle(el, 'border-width', '0px');
		}
		
		var elRequired = $D.getElementsByClassName("footerMailingRequired");
		for (var i=0; i < elRequired.length; i++) {
			clearHighlight(elRequired[i]);
		}
		
		var requestInformationForm = $D.get('footerMailingListSignUpForm');
		var formConfig = WDPRO.util.FormValidator.createConfigByClasses(requestInformationForm, {notEmpty:"footerMailingRequired"});
		var validationResponse = WDPRO.util.FormValidator.validate(formConfig);
		var formErrors = validationResponse.errors;
		var actualFormErrorCount = formErrors.length;

		// Check e-mail address syntax
		var formEmailConfig = WDPRO.util.FormValidator.createConfigByClasses(requestInformationForm, {email:"footerMailingEmail"});
		var emailValidationResponse = WDPRO.util.FormValidator.validate(formEmailConfig);
		var formEmailErrors = emailValidationResponse.errors;
		var eMailAddressValidation = true;
		for (var i=0; i<formEmailErrors.length; i++) {
			var errEl = formEmailErrors[i].getElement();
			if (errEl.nodeName == "INPUT" || errEl.nodeName =="SELECT") {
			eMailAddressValidation = false;
			if (!errEl.value) {
				eMailAddressValidation = false;
				continue;
			}
			highlight(errEl);
			var textNode = document.createTextNode("Please enter a valid email address");
			var liElement = new YAHOO.util.Element(document.createElement('li'));
			liElement.appendChild(textNode);
			var ulElement = new YAHOO.util.Element(document.createElement('ul'));
			ulElement.addClass('errors');
			ulElement.appendChild(liElement);	
			var parentElement = new YAHOO.util.Element($D.getAncestorByTagName(errEl, 'dd'));
			parentElement.appendChild(ulElement);
			actualFormErrorCount++;
			}
		}
		
		// Ignore label elements that have a class of required
		// Place required field message below field elements
		for (var i= 0; i<formErrors.length; i++) {
			var errEl = formErrors[i].getElement();
			var errorElement = new YAHOO.util.Element(errEl);
			clearHighlight(errEl);
			if (errEl.nodeName == "LABEL") {
				actualFormErrorCount--;
			}
		}

		// User has filled out the form correctly
		if (actualFormErrorCount == 0) {
			 var email = $D.get("id").value;
			 var sport = $D.get("footerMailingListSport").value;
			 
			 var minutes = 0.5;
			 var date = new Date();
	         date.setTime(date.getTime()+(minutes*60*1000));
	         var expires = "; expires="+date.toGMTString();
	         var domain = "; domain = .go.com "
	         var path = "; path=/ ";
            
	         // Using cookies to pass data for mailing sign up selection as ELM uses success URL redirect, no POST data
			document.cookie = 'MailingEmail = ' + email + expires + path + domain;
			document.cookie = 'MailingSport = ' + sport + expires + path + domain;
			
			$D.get("footerMailingListSignUpForm").submit();
		}
		// User has filled out the form incorrectly
		else {
			for (var i=0; i<formErrors.length; i++) {
				var errEl = formErrors[i].getElement();
				highlight(errEl);

				if (errEl.nodeName == "INPUT" || errEl.nodeName =="SELECT") {
					if (errEl.id == "id"){
						highlight(errEl);
						var textNode = document.createTextNode("Please enter a valid email address");
					} else if (errEl.id == "footerMailingListSport") {
						highlight("footerMailingSignUpSelect");
						var textNode = document.createTextNode("Please choose a mailing list");
					} else {
						highlight(errEl);
						var textNode = document.createTextNode("Required field.");
					}
				var liElement = new YAHOO.util.Element(document.createElement('li'));
				liElement.appendChild(textNode);
				var ulElement = new YAHOO.util.Element(document.createElement('ul'));
				ulElement.addClass('errors');
				ulElement.appendChild(liElement);	
				var parentElement = new YAHOO.util.Element($D.getAncestorByTagName(errEl, 'dd'));
				parentElement.appendChild(ulElement);
				}


			}
			
		}
		
    });  
   /** End Global Sports Footer + Mailing List Sign Up **/
   
});

/** IE6 mouseover and hover fix **/
WDPRO_LOADER.addCallback(
    function() {

        // IE6 Events
        if (YAHOO.env.ua.ie > 5 && YAHOO.env.ua.ie < 7) {
            var lis = document.getElementById("topNavUl").getElementsByTagName("LI");

            YAHOO.util.Event.on(lis, 'mouseover', function(){
                YAHOO.util.Dom.addClass(this,'iehover');
            });
            YAHOO.util.Event.on(lis, 'mouseout', function(){
                YAHOO.util.Dom.removeClass(this,'iehover');
            });
        }

    }
);

/** Weather Module toggle **/
function toggleWeather(which){
    document.getElementById("weatherModuleToday").style.display = 'none'
    document.getElementById("weatherModuleTonight").style.display = 'none'
    document.getElementById("weatherModuleTomorrow").style.display = 'none'
    document.getElementById(which).style.display = 'block'
}

/** Promo Carousel **/
$(window).load(function() {
	if ($("#mycarousel").length) {
		$("#mycarousel").jcarousel({
		    wrap: "circular",
		    initCallback: mycarousel_initCallback
		});
	}
});

$("li.event-promo").live("mouseenter", function() {	
	var $currentPromo = $(this);
	$(".event-promo-wrapper", $currentPromo).addClass("active");
	$currentPromo.stop().animate({
		top: -10
	}, 200);
	$(".event-promo-top", $currentPromo).stop().animate({
		height: 143
	}, 200);
}).live("mouseleave", function() {
	var $currentPromo = $(this);
	$(".event-promo-wrapper", $currentPromo).removeClass("active");
	$currentPromo.stop().animate({
		top: 17
	}, 200);
	$(".event-promo-top", $currentPromo).stop().animate({
		height: 90
	}, 200);
});

function mycarousel_initCallback(carousel) {
	carousel.options.scroll = 1;
	
	//Adjust the width of the carousel if it contains less than 5 items:
	var promoCount = $("#mycarousel li.event-promo").length;
	var maxCarouselWidth = 960;
	
	if (promoCount < 5) {
		$("#event-promos").css("width",maxCarouselWidth-((5-promoCount)*189));
	}
	if (promoCount <= 5) {
		$(".event-promo-nav-button").hide();
	}	
}

