$(document).ready(function() {
	
	queryTermDefault = 'Search Disney Youth';
	emptyQueryDefault = 'Enter Search Term(s)';
	
	url = ($(location).attr('href'));
	
	if (url.indexOf('search') == -1){
		$('.queryTerm')[0].value = queryTermDefault;
	}

	$('.queryTerm').focus(function(){
		if(this.value == queryTermDefault || this.value == emptyQueryDefault){
			this.value = '';
			
			if($('input.queryTerm').hasClass('error')){
				$('input.queryTerm').removeClass('error')
			}
		}
	});
	
	$('.queryTerm').blur(function(){
		if(this.value==''){
			this.value = queryTermDefault;
		}
	});
	
	$('#searchForm').submit(function() {
		if($('.queryTerm').val() == '' || $('.queryTerm').val() == emptyQueryDefault || $('.queryTerm').val() == queryTermDefault){
			$('input.queryTerm').addClass('error');
			$('.queryTerm').val(emptyQueryDefault);
			return false;
		}
		else{
			if($('input.queryTerm').hasClass('error')){
				$('input.queryTerm').removeClass('error')
			}
			return true;
		}
	});

	//get user selection
	if (document.globalNavInterestForm) {
		var user_input = document.globalNavInterestForm.interestSelect[0].value;
		var btnImg = "<a href='" + user_input + "'></a>";	
		if(!document.getElementById){return;}
		document.getElementById('globalNavInterestSelectPanelGo').innerHTML=btnImg;
	}
	
    $('#btnShare').click(function() {
    	fireMyPopup();
        return false;
    });

    $('#btnCloseShare').click(function() {
    	fadeOutMyPopup();
        return false;
    });

    $('#fadeIn').click(function () {
    	fadeOutMyPopup();
   	});
    
    setTimeout('btnShareHomepage()',20000);
});

WDPRO_LOADER.require("element");
WDPRO_LOADER.require("connection");
WDPRO_LOADER.require("json");

WDPRO_LOADER.addCallback(function() {
		//alert('wd')
        var $D = WDPRO.util.Dom;
        var $C = YAHOO.util.Connect;
        var $E = YAHOO.util.Event;
        var $J = YAHOO.lang.JSON;

    // 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);
            }
        });
    }
});

function getInterestBtn() {		
		//get user selection
		var index = document.globalNavInterestForm.interestSelect.selectedIndex;
		var user_input = document.globalNavInterestForm.interestSelect[index].value;		
		var btnImg = "<a href='" + user_input + "'></a>";
			
		if(!document.getElementById){return;}
		document.getElementById('globalNavInterestSelectPanelGo').innerHTML=btnImg;
}

//BEGIN Functions for Share module
function call_facebook(actualURL,pageName) {
	var cmp = 'SOC-DYPUSEN_Facebook_dyp-' + pageName + '_Share';
	window.open('http://www.facebook.com/sharer.php?u='  + actualURL + '?cmp=' + cmp);
}
function call_twitter(shortURL) {
	var cmp = 'SOC-DYPUSEN_Twitter_dyp-';
	window.open('http://twitter.com/home?status=Disney Youth Groups has the right program for your youth group! Come perform, learn, celebrate, and play! ' + shortURL);
}

//Browser safe opacity handling function
function setOpacity( value ) {
	document.getElementById("shareDiv").style.opacity = value / 10;
	document.getElementById("shareDiv").style.filter = 'alpha(opacity=' + value * 10 + ')';
	document.getElementById("fadeIn").style.opacity = value/15;
	document.getElementById("fadeIn").style.filter = 'alpha(opacity=' + value * 7 + ')';
}

function resize() {
	window_width = ''; blanket_height = '';
	var frame = document.getElementById("fadeIn"); 
	
	/* Getting width height */ 
	if (typeof window.innerWidth != 'undefined') {
		viewportheight = window.innerHeight;
	} else {
		viewportheight = document.documentElement.clientHeight;
	}
	if ((viewportheight > document.body.parentNode.scrollHeight) && (viewportheight > document.body.parentNode.clientHeight)) {
		blanket_height = viewportheight;
	} else {
		if (document.body.parentNode.clientHeight > document.body.parentNode.scrollHeight) {
			blanket_height = document.body.parentNode.clientHeight;
		} else {
			blanket_height = document.body.parentNode.scrollHeight;
		}
	}
	/* end of getting height */
	
	/* Getting width width */
	if (typeof window.innerWidth != 'undefined') {
		viewportwidth = window.innerHeight;
	} else {
		viewportwidth = document.documentElement.clientWidth;
	}
	if ((viewportwidth > document.body.parentNode.scrollWidth) && (viewportwidth > document.body.parentNode.clientWidth)) {
		window_width = viewportwidth;
	} else {
		if (document.body.parentNode.clientWidth > document.body.parentNode.scrollWidth) {
			window_width = document.body.parentNode.clientWidth;
		} else {
			window_width = document.body.parentNode.scrollWidth;
		}
	}

	/* end of getting width */
	frame.style.width = "4000px"; 
	frame.style.height = "2000px"; 
	frame.style.top = '-48px'; // Disney
	frame.style.left = '-135px';
} 

function fadeInMyPopup() {
	for( var i = 0 ; i <= 100 ; i++ )
		setTimeout( 'setOpacity(' + (i / 10) + ')' , 8 * i );
	document.getElementById("fadeIn").style.zIndex = 9000;
	document.getElementById("content").style.zIndex = 9001;
	document.getElementById("shareDiv").style.zIndex = 9002;
}

function fadeOutMyPopup() {
	for( var i = 0 ; i <= 100 ; i++ ) {
		setTimeout( 'setOpacity(' + (10 - i / 10) + ')' , 8 * i );
	}
	setTimeout('closeMyPopup()', 800 );
}

function closeMyPopup() {
	document.getElementById("shareDiv").style.display = "none";
	document.getElementById("fadeIn").style.display = "none";
	document.getElementById("content").style.zIndex = 10;
}

function fireMyPopup() {
	setOpacity( 0 );
	document.getElementById("shareDiv").style.display = "block";
	document.getElementById("fadeIn").style.display = "block";
	resize();
	fadeInMyPopup();
}

function btnShareHomepage() {
	if (document.getElementById("btnShare")) {
		document.getElementById("btnShare").style.display = "block";
	}
}

//END Functions for Share module

