jQuery("document").ready(function() {
    navigation.initialize();
    search.initialize();
});

var search = {
	currentSearchValue : null,
	delayedFunction : null,
	suggestionIndex : -1,
		
    initialize : function() {
        this.registerEventHandlers();
        this.bindSuggestionEvents();
        currentSearchValue = jQuery("#searchKeywords").val();
    },

    registerEventHandlers : function() {
        var parentThis = this;
        jQuery("#searchKeywords").focus(function() {
        	var value = jQuery(this).val();
        	if(value == jQuery("#searchDefaultText").html() || value == currentSearchValue) {
        		jQuery(this).val("");
        	}
        });
        
        jQuery("#searchKeywords").blur(function() {
        	setTimeout(function() {jQuery("#searchSuggestions").hide()}, 200);
        	if(jQuery(this).val() == "") {
        		jQuery(this).val(jQuery("#searchDefaultText").html());
        	}
        });

        jQuery("#searchKeywords").keydown(function(e) {
        	var keyCode = e.keyCode || window.event.keyCode;
        	if(keyCode == 13 || keyCode == 27 || keyCode == 40 || keyCode == 38) {
        		//Up down arrow keys
        		parentThis.handleKeyPress(keyCode);
        	} else {
        		//Everything else
        		var keywords = jQuery(this).val() + String.fromCharCode(keyCode);
            	parentThis.queueShowSuggestions(parentThis, keywords);
        	}
        });
    },
    
    bindSuggestionEvents : function() {
        jQuery("#searchSuggestions ul li").hover(function() {
            jQuery(this).addClass("suggestionHover");
        }, function() {
        	jQuery(this).removeClass("suggestionHover");
        });
        
        jQuery("#searchSuggestions ul li").click(function() {
        	jQuery("#searchKeywords").val(jQuery(this).attr("id"));
        	jQuery("#searchSuggestions").hide();
        	jQuery("#searchForm").submit();
        });
    },
    
    queueShowSuggestions : function(parentThis, keywords) {
    	if(parentThis.delayedFunction != null) {
    		clearTimeout(parentThis.delayedFunction);
    		parentThis.delayedFunction = null;
    	}
    	parentThis.delayedFunction = setTimeout(function () {
    		parentThis.showSearchSuggestions(keywords);
    	} , 300);
    },
    
    showSearchSuggestions : function(keyword) {
    	var parentThis = this;
    	
    	if(keyword.length > 0) {
	    	var url = top.location.protocol + "//" + top.location.host + "/actions/searchSuggestionsAction.action?keyword=" + keyword;
	    	jQuery.getJSON(url, function(json) {
	    		jQuery("#searchSuggestions ul").remove();
	    		
	    		if(json.length > 0) {
	    			parentThis.suggestionIndex = -1;
		    		jQuery("<ul></ul>").appendTo("#searchSuggestions");
		    		jQuery.each(json, function(i, item) {
		    			var suggestion = jQuery("<li>" + item.query + " (" + item.count + ")</li>");
		    			suggestion.attr("id", item.query);
		    			suggestion.attr("class", "suggestion");
		    			suggestion.appendTo("#searchSuggestions ul");
		    		});
		
		    		parentThis.bindSuggestionEvents();
		    		jQuery("#searchSuggestions").show();
	    		} else {
	    			jQuery("#searchSuggestions").hide();
	    		}
	    	});
    	} else {
    		jQuery("#searchSuggestions").hide();
    	}
    }, 
    
	handleKeyPress : function(keyCode) {
    	if(keyCode == 13) {
    		//Handle enter button
    		jQuery("#searchKeywords").val(jQuery(".suggestionHover").attr("id"));
    		jQuery("#searchSuggestions").hide();
    	}
    	else if(keyCode == 27) {
    		//Handle escape button
    		jQuery("#searchSuggestions").hide();
    	}
    	else if(keyCode == 40 || keyCode == 38) {
    		//Handle up and down arrow keys
			if(keyCode == 38) {
				this.suggestionIndex--;
			} else {
				this.suggestionIndex++;
			}
			
			//Wrap as needed
			var numberOfSuggestions = jQuery(".suggestion").size();
			if(this.suggestionIndex >= numberOfSuggestions) {
				this.suggestionIndex = 0;
			} else if(this.suggestionIndex < 0) {
				this.suggestionIndex = numberOfSuggestions - 1;
			}
			
			var parentThis = this;
			jQuery(".suggestion").removeClass("suggestionHover");
			jQuery(".suggestion").each(function(index) {
				if(index == parentThis.suggestionIndex) {
					jQuery(this).addClass("suggestionHover");
				}
			});
    	}
    }
};

var navigation = {
    initialize : function() {
        this.registerEventHandlers();
        this.preloadImages();
    },

    registerEventHandlers : function() {
        var parentThis = this;
        //Display the submenu on mouseover for navigation
        jQuery("li.navCategory").hover(function() {
            jQuery("ul", this).show();
            parentThis.swapImages(this);
            parentThis.createAndShowIframeShim(this);
        }, function() {
            jQuery("ul", this).hide();
            parentThis.swapImages(this);
            parentThis.removeIframeShim(this);
        });
    },

    preloadImages : function() {
        jQuery(".rolloverImage").each(function() {
            var imagePath = jQuery.trim(jQuery(this).html());
            //var preload = jQuery("<img>").attr("src", imagePath);
        });
    },
    
    swapImages : function(element) {
        var rolloverImage = jQuery(element).find(".rolloverImage");
        var rolloverImageSrc = jQuery.trim(rolloverImage.html());
        if(rolloverImageSrc.length > 0) {
	        var currentImage = jQuery(element).find(".navTopImg");
	        var currentImageSrc = currentImage.attr("src");
	        currentImage.attr("src", rolloverImageSrc);
	        rolloverImage.html(currentImageSrc);
        }
    },

    createAndShowIframeShim : function(element) {
        //IE6 uses window controls for select boxes, which 
        //have an infinite zindex. This creates an iframe shim 
        //for IE6 browsers and places it behind the dropdown
        if ( jQuery.browser.msie && /6.0/.test(navigator.userAgent) ) {
            //Create the shim
            var parent = jQuery(element);
            var dropdown = parent.find("ul");
            if(dropdown.size() > 0) {
                parent.append('<iframe id="shim" scrolling="no" frameborder="0"/>');

                //Set the shim properties
                var shim = jQuery("#shim");
                shim.attr("width", dropdown.width() + 2);
                shim.attr("height", dropdown.height());
                jQuery("#shim").attr("src", 'javascript:"";');
            }
        }
    },

    removeIframeShim : function(element) {
        jQuery("#shim").remove();
    }
};

function open_popup(url, options) {
	window.open(url,"_new",options);
}

function openSizeChart(url) {
    window.open(url, '_new', 'toolbar=no, directories=no, location=no, status=yes, menubar=no, resizable=no, scrollbars=no, width=458, height=700, left=500, top=0');
}

function clearTextIfEquals(field, otherField) {
	if (field.value == otherField.value) {
		field.value = "";
	}
}

function submitRegFooterForm() {
  var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  if (!regFooterForm.email.value.match(re)) {
    window.alert('Please enter a valid email address.');
  }
  else {
document.regFooterForm.submit();
  }
}
