(function($) {
	var searchInput = $("#searchInput"),
		searchButton = $("#searchButton"),
		defaultVal = searchInput.attr("placeholder"),
		errorVal = "Type a search term here first",
		searchSwitcher = $("#nygov-SearchSwitcher"),
		myURL = window.parent.location.href,
		isSoms = myURL.search(/SomsSUBDirectory/i),
		isDetailPage = myURL.search(/offenderDetails.jsp/i),
		loadFacebook,
		h1 = $("h1"),
		quickbarNav = $("#quickbarNav");

	isBB = false;
	isMobile = false;
	
	function searchText(){
		var $this = $(this),
			thisVal = $this.val();
		if (thisVal === defaultVal || thisVal === errorVal) {
			$this.val('').addClass('searchOn').removeClass('input_error');
		} else if (thisVal === '') {
			$this.val(defaultVal).removeClass('searchOn');
		}
	};
	$('#searchForm').submit(function(e){
		var searchVal = searchInput.val();
		if (searchVal === defaultVal || searchVal === " " || searchVal === "" || searchVal === errorVal) {
			searchInput.addClass('input_error').val(errorVal);
			searchButton.removeClass("clicked");
			e.preventDefault();    
		}
	});
	$('#searchInput').val(defaultVal).bind({
		focusin: searchText,
		focusout: searchText
	});
	
	if (isFacebook < 0 ) { // If we're NOT in facebook.

		if (isSoms > 0) { // if we ARE in SOMS (SOMS fixes: for client-side template changes needed for the times in-between deployments)
			
			quickbarNav.find("li:first-child").remove().end() // Removes About
			.find('a[href="../missing/index.htm"]').text("Missing Persons").end() // Changes Text to Missing Persons
			.append('<li><a href="http://www.facebook.com/NYSPublicSafety"><img src="../images/interface/find-us-on-facebook.png" class="qbFacebook"></a></li>') // Adds facebook Like image
			.next() // Move to Search DIV
			.find("#searchForm").attr("action", "http://search.criminaljustice.ny.gov/search"); // Changes URL for search box to ny.gov
			
			$("ul.leftnav").find("li:nth-child(3)").find("li:nth-child(2)").remove(); // Removes "In the News" from "Newsroom" left Nav
			
			$('meta[name="viewport"]').attr("content", "width=device-width"); // Page width on mobile devices
			
			$("table").find('p a[href^="../nsor/recipient.htm"]').find("img").addClass("viewMap"); // Fixes the view on map button for mobile/desktop users
			
			if (!$("#fb-root").length) { // check to see if fb-root already exists
				$("body").prepend('<div id="fb-root"></div>'); // if not, add it to the head of the document.
			}
		}
				
		//if ( (h1.length) && (isDetailPage <= 0) && (!$("h1.style4").length) && (!$("h1.featuredHeading").length) ) {
		// Add the LIKE button to the page IF:
			// There is a valid H1 tag to add it after
			// Not homepage.
			// Not Offender Detail Page
			// Not Missing child page
		// Then set the loadFacebook value to true so that it loads facebook.
		
		//		h1.after('<div class="fb-like" data-send="false" data-width="450" data-show-faces="false"></div>');
			
		//		loadFacebook = true; // This is for the loading of Facebook SDK, we don't want to load it if there is no like button on the page
			
		//}
		var thisURL = window.parent.location.href,
			isState = thisURL.search(/.state.ny.us/i),
			isWWW = thisURL.search(/www./i),
			newDomainLink = "";
			
		
		if (isState > 0){
			newDomainLink = thisURL.replace("state.ny.us", "ny.gov");
		$("head").prepend("<style>.newDomainReminder { font-size:14px; background-color:#afcefc; display:block; position:absolute; width:100%; padding-bottom:5px; height:70px; top:-90px; left:0px; box-shadow:0 0 4px #666; z-index:1000; text-align:left;}.newDomainReminder .centerer { width:700px; margin:0 auto;}.newDomainReminder .domainCloser a, .newDomainReminder .domainCloser a:visited { float:right; text-decoration:none; background-color:Coral; color:#FFF; font-weight:700; margin: 0 2px 0; padding:2px 7px; border-radius:50px; text-shadow:0 0 2px #666; box-shadow:0 0 2px #666; }.newDomainReminder .domainCloser a:hover {background-color:#990000;}.newDomainReminder p {padding-bottom:0;}.newDomainReminder a, .newDomainReminder a:visited {color:#00F;}.newDomainReminder h2 { background-color:#5879a9;}.newDomainReminder .btn { background-color:#82ea77;}</style>")
			if (isWWW < 0 ) {
				newDomainLink = newDomainLink.replace("http://", "http://www.");		
			}
			$("body").prepend('<div class="newDomainReminder"><div class="centerer"><p>Our website has moved.<br />Access our new site by clicking the link below and remember to update your bookmarks.</p><p><a href="' + newDomainLink + '">' + newDomainLink + '</a><span class="domainCloser"><a href="#">X</a></span></p></div></div>');
			setTimeout(function(){$(".newDomainReminder").animate({"top": 0});}, 1500);
			
			$(".domainCloser a").live("click", function(e){e.preventDefault(); $(".newDomainReminder").animate({"top": "-80px"});});
		}
		
		if (searchSwitcher.css("display") == "none") { // Since we're not in Facebook, lets check to see if we're on a mobile device by checking to see if the search switcher is hidden (a media query CSS style)
			
			isMobile = true;
		
		}
		
		if (isMobile) { // Never want isMobile to run if you're on Facebook. so we put it inside the "IS NOT FACEBOOK" check.
			
			var nav = $("#navigation"),
				quickbarHTML = "<li><a href='//www.criminaljustice.ny.gov/SomsSUBDirectory/search_index.jsp' class='button'>Sex Offender Search</a></li><li><a href='//www.criminaljustice.ny.gov/missing/index.htm' class='button'>Missing Persons</a></li>",
				mobileHeader = $("#mobileHeader"),
				mobileNav = $("#mobileNav"),
				leftNav = $("ul.leftnav"),
				subNav = $("#subnav"),
				localNav = $("#localnav"),
				googleSearchButton = $("#gs_f"),
				mobileToggler = $(".mobileToggler"),
				mobileTogglee = $(".mobileTogglee"),
				deviceBB = "blackberry",
				uagent = navigator.userAgent.toLowerCase(); //Initialize our user agent string to lower case.
			
			//**************************
			// Detects if the current browser is a BlackBerry of some sort.
			function DetectBlackBerry() {
			   if (uagent.search(deviceBB) > -1) {
				  return true; 
			   } else {
				  return false;
			   }
			}
			
			isBB = DetectBlackBerry();
			
			if (isBB) {
			
				$(".nonBB").css("display", "none");
				
			}
	
			if (nav.length) {
	
				quickbarNav.addClass("inline-block").html(quickbarHTML).appendTo(mobileHeader);
				
				nav.insertAfter(mobileNav);
	
				mobileNav.click(function(e){
					e.preventDefault();
					localNav.hide();
					subNav.hide();
	
					if (!isBB) {
						leftNav.fadeToggle();			
					} else {					
						leftNav.toggle();					
					}
				});
				
			} else {
	
				mobileNav.remove();
				
				mobileHeader.css("height", "4.06em");
				
				//***Whole section depends on old Missing children code.
				
				var myURL = document.location.href.match("/missing/inf");
				
				if (myURL) {
				
					$("table").addClass("missingInfoTable").each(function() {
						var $this = $(this),
							row = $this.find("tr:nth-child(2)"),
							cell = row.find("td:nth-child(2)");
					
						$("<tr />").html(cell).insertAfter(row);
					});
				}
				
				//*** END Old MECC Code
				
				
			} // End Navigation Changes
	
			$("head").append("<link rel='apple-touch-icon' href='http://www.criminaljustice.ny.gov/apple-touch-icon.png'><script src='http://www.criminaljustice.ny.gov/add2home.min.js'></script>"); 
			
			$(".button").live("click", function(){$(this).toggleClass("clicked");});
			
			if (subNav.length) {
				
				var subNavTitle = subNav.find("p").text();
				
				$("<a />", {
					"class": "button",
					"href": "#",
					"id": "subNavButton",
					text: subNavTitle + " Menu",
					click: function(e) {
						e.preventDefault();
						localNav.hide();
						leftNav.hide();
							
						if (!isBB) {
							
							subNav.fadeToggle();
						
						} else {
							
							subNav.toggle();
							
						}
					}
				}).insertBefore(subNav).wrap("<p class='subNavButtonWrap' />");
				
				if (localNav.length) {
					
					var localNavTitle = localNav.find("p").text();
					
					$("<a />", {
						"class": "button",
						"href": "#",
						"id": "localNavButton",
						text: localNavTitle,
						click: function(e) {
							e.preventDefault();
							subNav.hide();
							leftNav.hide();
							
							if (!isBB) {
								
								localNav.fadeToggle();
								
							} else {
								
								localNav.toggle();
								
							}
						}
					}).insertAfter("#subNavButton");
				} // end if localNav
			} // End if subNav
	
			if (mobileToggler.length && !isBB) { // Moblie Toggler Setup
					
				mobileToggler.each(function(){ // Append the H5 text from each of the What's new headings to their child containers
				
					var $this = $(this),
						h5 = "<p><strong>" + $this.text() + "</strong></p>";
					
					$this.next(mobileTogglee).prepend(h5);
				
				});
				
				mobileToggler.click(function(){
					var $this = $(this);
					$this.toggleClass("onToggled").next(mobileTogglee).slideToggle();
				});
	
			} else { // Make BB's not have the toggle functionality cause BB's suck at the internet.
			
				mobileTogglee.css("display", "inherit");
				
			} // END MobileToggler
	
			// Begin Search optimizations
			if (googleSearchButton.length) {
	
				googleSearchButton.val("Go").addClass("button");
				
			}
		//End if isMobile = true	
		} else {
	
			searchSwitcher.click(function(e){
										  
				e.preventDefault();
				$(this).addClass("invisible");
				$("#nygov-sw_searchbox").removeClass("invisible").addClass("isVisible");
				
			});
		} // End if isMobile = false
	}//End if isFacebook = true

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

// Event Tracker Instructions *******************/
// add to link: <a class="gaEventTracker" data-ga='{"evtCategory": "Category", "evtAction": "Event Type", "evtLabel": "Event Name"}'>
// Example:     <a class="gaEventTracker" data-ga='{"evtCategory": "Videos", "evtAction": "Press", "evtLabel": "Child Sexual Predators HQ"}'>
// Allows you to leave out an option if you dont want one. You WILL need to provide at least the evtCategory For proper google tracking

$.fn.gaEventTracker = function(options) {

	return this.each(function(){

		var $this = $(this),
			opts,
			defaults = {
				evtCategory: "Category Not Defined",
				evtAction: "",
				evtLabel: ""
			};

		if ($this.data("ga")) {
			
			var ga = $this.data("ga");
			
			defaults = {
				evtCategory: ga.evtCategory || "Category Not Defined",
				evtAction: ga.evtAction || "",
				evtLabel: ga.evtLabel || ""
			}

		}

		opts = $.extend({}, defaults, options);
		$this.attr('onClick', "_gaq.push(['_trackEvent', '" + opts.evtCategory + "', '" + opts.evtAction + "', '" + opts.evtLabel + "']);");
	});
};
$("#mainContent a.gaEventTracker").gaEventTracker();

$("#mainContent a[href$='.pdf'], #mainContent a[href$='.doc'], #mainContent a[href$='.docx'], #mainContent a[href$='.ppt'], #mainContent a[href$='.pptx'], #mainContent a[href$='.xls'], #mainContent a[href$='.xlsx']").each(gaDocumentTrack);


/*****************************
** gaDocumentTrack Overview
** 
** Checks to make sure there isn't a gaEventTracker Init'd yet, and then checks HREF value of the link
** and compares it to the window.location.pathname and inserts appropriate directory names into the google event tracker.
** Full support for External Documents categorized as: "External Document"
**
** Eric Steinborn 4/2011
*******************************/

function gaDocumentTrack() {
	
	var $this = $(this);

	if (!$this.data("ga")) {  // Only run if no data-ga has been declared previously, you dont want to overwrite the specific stuff.
		
		var	category = "Documents",
			action = "",
			label = $this.attr("href"),
			i = 0, z = 0, numSlashes = 0,
			oURL = window.location.pathname,
			splitURL = oURL.split("/");
	
			splitURL.remove(0); // removes first blank entry in the Array
			splitURL.remove(-1); // removes filename
	
		if (label.match(/(\.\.\/)/gi)) { // check for "../" in HREF attr
	
			numSlashes = label.match(/(\.\.\/)/gi).length; // how many slashes
			label = label.replace(/(\.\.\/)/gi, ""); // replace slashes with ""
	
			if (numSlashes === splitURL.length) { // if the number of slashes equals directories in splitURL

				action = "/" + label;

			} else {  // If numSlashes !=== splitURL.length (meat and potatoes)

				for (i; i < numSlashes; i++) {
	
					splitURL.remove(-1); // removes the last item in the array until numslashes are removed
					
				}
	
				for (z; z < splitURL.length; z++) {
	
					if (action === "") { // runs once at beginning
	
						splitURL.reverse(); // reverse the split to reassemble URL
	
						action = "/" + splitURL[z] + "/" + label; // /splitURL[0]/label
	
					} else { // runs until numSlashes has been fulfilled
	
						action = "/" + splitURL[z] + action; // /splitURL[z]/splitURL[0]/label
					}
	
				}
	
			}
	
		} else { // run if there are NO ../'s
		
			if (label.match("http://") && !oURL.match("/search")) { // External && not search!
	
				category = "External Documents";
				action = label;
				
			} else if (oURL.match("/search")) { // If Search, make it pretty.
				
				action = label.replace(/(http:\/\/www.criminaljustice.ny.gov)/gi, "");
	
			} else if (splitURL.length < 1) { // if not External && isRoot
	
				action = "/" + label;			 	
	
			} else { // If not root and not external
	
				action = "/" + splitURL.join("/") + "/" + label;
	
			}
	
		}
	
		oURL = oURL.replace("/index.htm", "/").replace("/index.html", "/"); // index URL's = "/"
	
		$this.gaEventTracker({
			"evtCategory": category,
			"evtAction": action,
			"evtLabel": oURL
		});
	}
}

//Load FB
if (loadFacebook) {
	(function(d, s, id) {
		var js, fjs = d.getElementsByTagName(s)[0];
		if (d.getElementById(id)) {return;}
		js = d.createElement(s); js.id = id; js.async=1;
		js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=220914501287244";
		fjs.parentNode.insertBefore(js, fjs);
	}(document, 'script', 'facebook-jssdk'));
} else setTimeout(function(){if (loadFacebook) {
	(function(d, s, id) {
		var js, fjs = d.getElementsByTagName(s)[0];
		if (d.getElementById(id)) {return;}
		js = d.createElement(s); js.id = id; js.async=1;
		js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=220914501287244";
		fjs.parentNode.insertBefore(js, fjs);
	}(document, 'script', 'facebook-jssdk'));
}}, 1500)
})(jQuery);
var _gaq = [['_setAccount', 'UA-15068527-1'], ['_trackPageview']];
(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.async=1;
g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js';
s.parentNode.insertBefore(g,s)}(document,'script'));

