jQuery.noConflict();

var plauditAnalytics = (function($) {
	
	var isPageTrackerLoaded = function() {
		return typeof(_gaq) != "undefined" && _gaq != null;
	};
	
	return {
		trackPage: function(url) {
			if ( url.substring(0,1) != '/' )
				url = '/' + url;
			if ( isPageTrackerLoaded() ) {
				_gaq.push(['_trackPageview', url]);
			} else if ( typeof(console) != "undefined" ) {
				console.log("Google Analytics not loaded. Trying to track page: " + url);
			}
		},
		trackEvent: function(category, action, opt_label, opt_value) {
			if ( isPageTrackerLoaded() ) {
				_gaq.push(['_trackEvent', category, action, opt_label, opt_value]);
			} else if ( typeof(console) != "undefined" ) {
				console.log("Google Analytics not loaded. Trying to track event with category '" + category +"', action '" + action +"', opt_label '" + opt_label +"', and opt_value '" + opt_value +"'.");
			}
		},
		setupBinding: function() {
			$("a").filter("[href^='http://'], [href^='https://']").filter(":not([href*='://"+location.hostname+"'])").click(function(){
				plauditAnalytics.trackEvent("Outbound Link", "Click", $(this).attr("href"));
			});
			$("a").filter("[href^='mailto:']").click(function(){
				plauditAnalytics.trackEvent("Email Link", "Click", $(this).attr("href"));
			});
			$("form").filter("[action^='http://'], [action^='https://']").filter(":not([action*='://"+location.hostname+"'])").submit(function(){
				plauditAnalytics.trackEvent("Outbound Form Submissions", "Submit", $(this).attr("action"));
			});
		}
	};
})(jQuery);

var plauditUI = (function($){
	
	return {
			common: function(){
				$("tr:odd").addClass("odd");
				$("#main-search-form, #inline-search-form").placeHolder("Find something fun...");
				
				accRun = function(){
					$('#accordion div.contacts-sub-section').accordion({
						collapsible: true,
						active: false,
						disable: false
					});
					$('.contact-list').css({'display' : 'none'});
				};
				
				$('.contacts-sub-section h2').mouseenter(function(){
					$(this).css({'color' : '#557BA8'});
				});
				$('.contacts-sub-section h2').mouseleave(function(){
					$(this).css({'color' : '#D00'});
				});
				
				$('#accordion div.contacts-sub-section h2').click(function(){
					$(this).toggleClass('activeContactHead');
				});
				
			
				if ( $.browser.msie	&& parseInt($.browser.version) < 9 ) {
					// Some versions of ie do not submit the form using the first submit if the field only contains
					// one input field. We must have it use the first button so the correct JSF action runs.
					$('input').keypress(function(event){
						var input = $(this);
					    if (event.keyCode == 13) {
					    	var submitButtons = input.closest("form").find(":submit:first, input.submit:first, input[type='image']:first");
					    	if ( submitButtons.length > 0 ) {
					    		// handle the submit
					    		submitButtons.first().click();
					        	return false;
					    	}
					    	return true;
					    }
					});
				}
			},
		
			documentLibrary: function(){
				$('#library-list').each(function() {
					var $this = $(this);
					var root = '/';
					var ul = $("> ul", $this);
					
					checkDebug = 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];
							  }
							});
						
						debByName = $.getUrlVar('debug');
						if (debByName == 'debug'){
							script = 'library/document-library-js.scriptJsf' + '?debug=true';
						}else {
							script = 'library/document-library-js.scriptJsf';
						};
					};
					checkDebug();
					var baseURL = $("base").attr("href");
					
					if ( !$("body").hasClass("static") ) {
						var openFile = function(file) {
							pageTracker._trackPageview(
								(file.charAt(0) === '/')? file : '/'+ file
							);
							window.open( baseURL + file);
							return false;
						}
						
						if ( $this.hasClass("manual") ) {
							// Manually created library
							
							$("li", ul).each(function() {
								var $liThis = $(this);
								if ( !$liThis.hasClass("file") ) {
									$liThis.addClass("directory");
								}
							});
							
							ul.each(function() {
								var $ulThis = $(this);
								$ulThis.fileTree(
									{ 
										root: root,
										script: script,
										expandSpeed: 350,
										collapseSpeed: 250
									}, function(file) {
										openFile(file);
									}
								);
							});
						} else {
							if (ul.size() > 0 && ul.attr('title') != '') {
								root = ul.attr('title');
							}
							$this.fileTree(
								{ 
									root: root,
									script: script,
									expandSpeed: 350,
									collapseSpeed: 250
								}, function(file) {
									openFile(file);
								}
							);
						}
						
					}
				});
					
			}, // documentLibrary
			
			contactMap: {
                enabledRegions: null,
                map: null,
                hiddenRegions: ["MX_CAR"],
                
                init: function(){
                	// Generic values
                	var mapId = this.loadMap();
                    $("#contact-finder input:checked").prop('checked',false);
                    function addCover(){
                        if (mapId == "US" || mapId == "CA"){
                            var radioCount = $("#contact-finder input:checked").length
                            if (radioCount == 0){
                            	if(swfobject.hasFlashPlayerVersion("10.0.0")){
	                                $("#contact-map-wrap").append("<div id='contact-map-cover' />")
                            	}
							} else {
                                $("#contact-map-cover").remove();
                            }
                        }
                    }
                    addCover();
                },
                loadMap: function(){
                	var mapDiv = "contact-map",
                	mapWrapperDiv = $("#contact-map-wrap"),
                    flashVersion = "10.0.0",
                    expressInstall = "assets/flash/expressInstall.swf",
                    flashvars = {
                        colorDisabled :"F2F2F2", 
                        colorEnabled :"CCCCCC",
                        colorHover :"DD0000",
                        hoverSpeed :0.4
                    },
                    params = { menu :"false", wmode :"transparent" };
                	
                	// Hide any tooltips
                	this.hideToolTip();
                	
                	// Set map meta-data
                	if(mapWrapperDiv.length){
	                	this.map = mapWrapperDiv.data("map"),
	                	this.enabledRegions = mapWrapperDiv.data("regions").split(",");
                	}
                	
                	// Map Specific Values
                	var mapId = this.getMap();
                	
                	if (mapId == "world"){
                		var mapSwf = "assets/flash/contact-map-world.swf";
                		var mapWidth = "900";
	                    var mapHeight = "440";
                	}
                	if (mapId == "US"){
                		var mapSwf = "assets/flash/contact-map-us.swf";
	                    var mapWidth = "580";
	                    var mapHeight = "500";
	                  	accRun();
                	}
                	if (mapId == "CA"){
                		var mapSwf = "assets/flash/contact-map-ca.swf";
	                    var mapWidth = "580";
	                    var mapHeight = "500";
	                  	accRun();
                	}
                	
                	if (mapWrapperDiv.length == 1){
                        if(swfobject.hasFlashPlayerVersion("10.0.0")){
                            swfobject.createCSS(".contact-map", "height:515px; width:580px;");
                            swfobject.embedSWF(mapSwf, mapDiv, mapWidth, mapHeight, flashVersion, expressInstall, flashvars, params, {});
                        } else {
                            $("#sales-contact-list").show();
                        }
                	}
                	return mapId;
                },
                regionClick: function(e,xPos,yPos){
                	var $this = this;
                	var mapId = this.getMap();
                	
                	if(mapId == "world"){
                		window.location = $("base").attr("href") + "contact.html?country=" + e.toUpperCase();
                	} else {
                		$this.hideToolTip();
                		var toolTip = $("#tool-tip"),
                		flashAreaPosition = $("#contact-map-wrap").offset(),
						toolTipX = flashAreaPosition.left + xPos,
						toolTipY = flashAreaPosition.top + yPos;
                		
                		var contacts = $("#sales-contact-list").find("."+e).clone();
                		
                		contacts.each(function(i){
                			var mod = i % 2;
                			var currentItem;
                			$(this).removeAttr("class");
                			$(this).addClass("contact");
                			
                			if (mod == 1){
	                			$(this).addClass("last-of-row");
                			} 
                			toolTip.append($(this));
                		});
                		
                		toolTip.children("div").each(function(i) {
            		    	toolTip.children("div").slice(i,i+2).wrapAll('<div class="contact-row group">');
                		});
                		
                		toolTip.append("<a id='tool-tip-close' href='#'>Close</a>");
                		
                		var toolTipWidth = toolTip.width();
						var toolTipRightPosition = toolTipWidth + toolTipX;
						var documentWidth = jQuery(document).width();
						
						if ( toolTipRightPosition >= documentWidth ) {
							toolTipX =  Math.max(10, toolTipX - toolTipWidth - 10);
						}
                		
						toolTip.css({
							top: toolTipY, 
							left: toolTipX
						});
						
                		toolTip.show(100,function(){
		            		$("body").bind("click",function() {
		    			    	$this.hideToolTip();
		        			});
                		});
                		
	            		$("#tool-tip").click(function(e){
	            			e.stopPropagation();
	            		});
                		
                		$("#tool-tip-close").click(function(e){
                			$this.hideToolTip();
                			e.preventDefault();
                		});
                		
                	}
                },
                hideToolTip: function(){
                	$("body").unbind("click"); // Unbind click event from body. This is used for testing if the tooltip was clicked or not
                	$("#tool-tip").empty().hide();
                },
                getEnabledRegions: function(){
                    return this.enabledRegions;
                },
                getMap: function(){
                    return this.map;
                },
                getHiddenRegions: function(){
                    return this.hiddenRegions;
                }
            }
        }; // return
})(jQuery);

jQuery(function(){
	
	plauditAnalytics.setupBinding();
	plauditUI.common();
	plauditUI.documentLibrary();
	plauditUI.contactMap.init();
});

