// POPUP FOR EMAIL A FRIEND ---------------------------------------
function popupWindow(url){
  var aWindow = window.open(url,"sendEmail","width=455,height=330,menubar=no,toolbar=no,resizable=no,scrollbars=no,copyhistory=no");  
}

function popupWindowNew(url, width, height){
this.width = width;
this.height = height;

  var aWindow = window.open(url,"sendFeedback","width=" + width +",height="+ height +",menubar=no,toolbar=no,resizable=no,scrollbars=no,copyhistory=no");   //alert("height= " + height);
}

// AJAX SEARCH BOX ------------------------------------------------
function suggest_plugin(){

}

//Testing function
function mobileTester(message)
{
	if($(window).width() <= 480)
		alert(message)
}


function querySt(ji) {
hu = window.location.search.substring(1);
gy = hu.split("&");
for (i=0;i<gy.length;i++) {
ft = gy[i].split("=");
if (ft[0] == ji) {
return ft[1];
}
}
}

// ON DOCUMENT.READY ---------------------------------------------
$(document).ready(function(){
		
		$("#searchQuery").jSuggest({
url: "http://ask.miamidade.gov/search-suggest",
type: "GET",
autoChange: true,
loadingImg: 'http://ask.miamidade.gov/images/ajax-loader.gif'
});
		
		link_scanner($(".left_links li a"), window.location.href, "sn_active")
		
		Modernizr.load({
			load: 'http://www.miamidade.gov/global_assets/templates_v5/js/toggle_nav.js',
			complete: function()
			{
				toggle_nav("#mainContainer", "#site_nav_link", "#navigation ul")
				toggle_nav(".webname", "h1", "#top_navigation")
			}
		});
		
		//var version = querySt("version_to_display")
		//mobileTester(version)	
		//Code to setup the navigation for mobiles.
		$("#top_navigation").attr("class", "hide_navigation")
		$("#navigation ul").attr("class", "hide_navigation")
			

	
	// GRAB INNERHTML FROM DIV - ASSIGN TO VARIABLE - PASS VARIABLE TO JCRUMB - WORKS!!
	var sp_webname = $("#sp_webname").text();

		var sp_section = document.getElementById('sp_section').innerHTML;
	if (sp_section == "" || sp_section == null)
	{	
		var sp_section = "sect_0";
	}
	var sp_pagetitle = document.getElementById('sp_pagetitle').innerHTML;
	sp_pagetitle = sp_pagetitle.replace(/;/gi,'');
	sp_pagetitle = sp_pagetitle.replace(/&amp/gi,'&');
	
	// top navigation - highlight current section
	$('#' + sp_section).addClass('n_active');
	

	
	// $('#' + siteProperties.section).addClass('n_active'); -- old line using namespace
	
	/*
	var currentPage;
	var num = $.url.segment() - 2;
	
	if($.url.segment(num) == sp_webname)
	{
		currentPage = "/" + sp_webname + "/" + $.url.attr("file")
	}
	else
	{
		currentPage = "/" + sp_webname + "/" + $.url.segment(num) + $.url.attr("file")
	}
	
	// var currentPage = "/" + siteProperties.webname + "/" + $.url.attr("file"); -- old line using namespace
	
		$.each($(".left_links li a"), function() {	
								   
		if($(this).attr("href").toUpperCase() == currentPage.toUpperCase())
		$(this).addClass("sn_active")
	});
	*/
	/*
	// top navigation - add "on" class to page no refresh
	$('#siteNavigation a').click(function(){			
		$('#siteNavigation a').not(this).removeClass('n_active');
		$(this).addClass('n_active');
	});
	
	 // side navigation - add "on" class to page no refresh
	$('.leftNav ul li a').click(function(){			
		$('.leftNav ul li a').not(this).removeClass('sn_active');
		$(this).addClass('sn_active');
	});
	*/
	
	// bread crumbs regex and init	
	/*
	var pageName = ''
	var text = document.title 
	
	if(text != ""){  
		var placement = text.indexOf("-") // first dash location (in a number) from left MIAMI-DADE
		var newStr = text.substr(placement + 1, text.length - 1) 
		var secondDash = newStr.indexOf("-"); // second dash location
		var shortStr = newStr.substr(secondDash + 1)   
		var thirdDash = shortStr.indexOf("-")   
		var deptName = newStr.substr(secondDash + 1, thirdDash)  
		pageName = shortStr.substr(thirdDash + 2)   
	}
	*/
	
	// bread crumbs regex and init
	
	//var pageTitleNode = document.createTextNode(siteProperties.pageTitle)

	//if(console)
	//console.log(pageTitleNode.nodeValue)
	
	$('#bc').html('Visited Pages: ');
	$('#bc').jCrumb({
		maxCrumbs:4,
		maxMemory : 12,
		seperator : "&raquo;",
	//	title : siteProperties.pageTitle -- old line using namespace
		title : sp_pagetitle
	});
	$('#bc').css('visibility','visible');
						   
						   
// ROW STRIPES -- RIGHT COLUMN
$('ul.stripeList li:nth-child(odd)').addClass('rowOdd'); 
$('ul.stripeList li:nth-child(even)').addClass('rowEven');

$('table.stripeRow tr:odd').addClass('rowEven');


// BOTTOM BAR SHOW / HIDE FUNCTIONALITY
	$("#min").click(function(){
		$("#floatingBar").slideToggle('slow', function(){
			$("#floatingBarOpen").slideToggle('slow')});	
		return false;
	});
	
	$("#max").click(function(){
		$("#floatingBarOpen").slideToggle('slow', function(){
			$("#floatingBar").slideToggle('slow')});	
		return false;
	});

	
});

	// side navigation - higlight current page
function link_scanner(link_list, string_to_compare, class_to_add)
	{
		this.link_list = link_list
		this.string_to_compare = string_to_compare
					
		
		//create function variables
		var index_of_querystring = string_to_compare.indexOf("?");
		
		//Set str to the correct value depending on whether or not there's a querystring.
		index_of_querystring == -1 ? str = string_to_compare.substr(string_to_compare.lastIndexOf("/") + 1, string_to_compare.length - 1) : str = string_to_compare.substr(index_of_querystring + 1, string_to_compare.length - 1)
		
		
		//Scan the link_list
		$.each(link_list, function(key, value)
		{
			$(this).removeClass("sn_active");
			var address = $(this).attr('href')
			var last_slash = address.lastIndexOf("/")
			var qs_index = address.indexOf("?")
			
			if(qs_index == -1)
			{
					var sanitized = address.substr(last_slash + 1, address.length -1)
				
					if(str == sanitized)
					{
						$(this).addClass(class_to_add)
						return false
					}
			}
			else
			{
				var sanitized = address.substr(qs_index + 1, address.length - 1)
				
				if(str == sanitized)
				{
					$(this).addClass(class_to_add)
					return false
				}
				
			}
		})
	}

	/*
	var original_filename = $.url.attr("file")
	var url_qs = $.url.attr("query")

	try
	{
	var filename = original_filename.substring(0, original_filename.indexOf("."))
	}
	catch(e)
	{
		return false
	}
	
	$.each($(".left_links li a"), function(key, value)
	{
    	var link = $(this).attr('href')
	    var last_slash = link.lastIndexOf("/")
    	var extension = link.indexOf(".")
		
		
	    if(last_slash != -1)
    	{
        	var clean_link = link.substring(last_slash + 1, extension)

	        if (filename === clean_link)
    	    {
        	    $(this).addClass("sn_active")
				return false
	        }
        
    	}
		
		if($(this).attr("href").indexOf("?") != -1)
		{
			var questionMark = $(this).attr("href").indexOf("?")

                                           
			if (url_qs != null && url_qs ===  $(this).attr("href").substr(questionMark + 1, $(this).attr("href").length - 1))
			{
				$(this).addClass("sn_active")	
				return false
			}
			else
			{
		    	$(this).removeClass("sn_active")
			}
		}                


	}) 
} 
*/

// .COM / .NET WARNING DISCLAIMER --------------------------------
//SETTING UP OUR POPUP
//0 means disabled; 1 means enabled;
var popupStatus = 0;

//loading popup with jQuery magic!
function loadPopup(){
	//loads popup only if it is disabled
	if(popupStatus==0){
		$("#pwBackgroundPopup").css({
			"opacity": "0.7"
		});
		$("#pwBackgroundPopup").fadeIn("slow");
		$("#popupWarning").fadeIn("slow");
		popupStatus = 1;
	}
}

//disabling popup with jQuery magic!
function disablePwPopup(){
	//disables popup only if it is enabled
	if(popupStatus==1){
		$("#pwBackgroundPopup").fadeOut("slow");
		$("#popupWarning").fadeOut("slow");
		popupStatus = 0;
	}
}

$.fn.centerInClient = function(options) {
    /// <summary>Centers the selected items in the browser window. Takes into account scroll position.
    /// Ideally the selected set should only match a single element.
    /// </summary>    
    /// <param name="fn" type="Function">Optional function called when centering is complete. Passed DOM element as parameter</param>    
    /// <param name="forceAbsolute" type="Boolean">if true forces the element to be removed from the document flow 
    ///  and attached to the body element to ensure proper absolute positioning. 
    /// Be aware that this may cause ID hierachy for CSS styles to be affected.
    /// </param>
    /// <returns type="jQuery" />
    var opt = { forceAbsolute: false,
                container: window,    // selector of element to center in
                completeHandler: null
              };
    $.extend(opt, options);
   
    return this.each(function(i) {
        var el = $(this);
        var jWin = $(opt.container);
        var isWin = opt.container == window;

        // force to the top of document to ENSURE that 
        // document absolute positioning is available
        if (opt.forceAbsolute) {
            if (isWin)
                el.remove().appendTo("body");
            else
                el.remove().appendTo(jWin.get(0));
        }

        // have to make absolute
        el.css("position", "absolute");

        // height is off a bit so fudge it
        var heightFudge = isWin ? 2.0 : 1.8;

        var x = (isWin ? jWin.width() : jWin.outerWidth()) / 2 - el.outerWidth() / 2;
        var y = (isWin ? jWin.height() : jWin.outerHeight()) / heightFudge - el.outerHeight() / 2;

        el.css("left", x + jWin.scrollLeft());
        el.css("top", y + jWin.scrollTop());

        // if specified make callback and pass element
        if (opt.completeHandler)
            opt.completeHandler(this);
    });
}

//CONTROLLING EVENTS IN jQuery
$(document).ready(function(){
	$("a").click(function(){
			ajmNewSiteURL = $(this).attr("href");
			var regex = /\.com|\.com\/|\.net|\.net\//;
			if(regex.test(ajmNewSiteURL)){
			
			if($(this).attr('class') == "exception")
			return true;	

			$("#popupWarning").centerInClient();
			loadPopup();
			return false;
		}
	});
			
	//CLOSING POPUP
	//Click the x event!
	$("#popupWarningClose").click(function(){
		disablePwPopup();
	});
	
	$("#pwAlertButton").click(function()
	{
		disablePwPopup();
		window.open(ajmNewSiteURL);
	});
	
	$("#cancelButton").click(function()
	{
		disablePwPopup();									  
	});
	
	//Click out event!
	$("#pwBackgroundPopup").click(function(){
		disablePwPopup();
	});
	//Press Escape event!
	$(document).keypress(function(e){
		if(e.keyCode==27 && pwPopupStatus==1){
			disablePwPopup();
		}
	});
	

});
