$(document).ready(function(){
    // Increase Font Size
    $("#increase_font").click(function(){
        var currentFontSize = $('html').css('font-size');
        var currentFontSizeNum = parseFloat(currentFontSize, 10);
        var newFontSize = currentFontSizeNum*1.1;
        $('html').css('font-size', newFontSize);
        return false;
    });
    // Decrease Font Size
    $("#decrease_font").click(function(){
        var currentFontSize = $('html').css('font-size');
        var currentFontSizeNum = parseFloat(currentFontSize, 10);
        var newFontSize = currentFontSizeNum*0.9;
        $('html').css('font-size', newFontSize);
        return false;
    });
    // Search sumbit on enter
    $("#gmTerms").keyup(function(event){
        if(event.keyCode == 13){
            $("#gmSubmit").click();
        }
    });

    // Search sumbit on enter
    $("#searchTerms").keyup(function(event){
        if(event.keyCode == 13){
        	var q = $('#searchTerms').val();
    		window.location = '/Pages/googleSearch.aspx?q=' + q;
        }
    });

});

function disable_stylesheets(){
    for(i=0;i<document.styleSheets.length;i++){
        void(document.styleSheets.item(i).disabled=true);
        }
    }

// Base master search redirect
function gmQuery() {
    d1 = $('#gmTerms').val();
    window.location = '/Pages/googleSearch.aspx?q=' + d1;
    }

// Header banner image selector
function showHeaderImage(page){
  	//  var defaultImg = "/Style%20Library/images/banner01.jpg"; - default
    var defaultImg = "/Style%20Library/images/government_banner.jpg";
    var defaultAlt = "Arkansas.gov - Offical Website for the State of Arkansas";
    var url = ""+document.location;
    var pages=new Array(
    //"url selector", "image path","alt tag"
    "aboutArkansas/Pages", "/Style%20Library/images/aboutarkansas_banner.jpg", "Arkansas.gov - About Arkansas",
    "tourism/Pages", "/Style%20Library/images/tourism_banner.jpg", "Arkansas.gov - Tourism",
    "residents/Pages", "/Style%20Library/images/residents_banner.jpg", "Arkansas.gov - Residents",
    "services/Pages", "/Style%20Library/images/onlineservices_banner.jpg", "Arkansas.gov - Online Services",
    "government/Pages", "/Style%20Library/images/government_banner.jpg", "Arkansas.gov - Government",
    "employment/Pages", "/Style%20Library/images/employment_banner.jpg", "Arkansas.gov - Employment",
    "education/Pages", "/Style%20Library/images/education_banner.jpg", "Arkansas.gov - Education",
    "business/Pages", "/Style%20Library/images/business_banner.jpg", "Arkansas.gov - Business"
    );
    for(var i=0; i<pages.length; i+=3){
        if( url.match(pages[i]) ){
            document.write('<img src="'+pages[i+1]+'" alt="'+((pages[i+2] != null && pages[i+2].length > 1)?pages[i+2]:defaultAlt)+'" height="74" width="960" />');
            return;
        }
    }
    document.write('<img src="'+defaultImg+'" alt="'+defaultAlt+'">');
}

// feature tabs
function hideFeatureTab(selector){

    $('#featureContent' + selector).hide();
    $('#featurePanel' + selector).hide();

	$('#featureTab' + selector).css('z-index', 9);
	$('#featurePanel' + selector).css('z-index', 9);	
	$('#featureTab' + selector).addClass('inactive');
}

function showFeatureTab(selector){

	$('#featureTab' + selector).removeClass('inactive');
	$('#featureTab' + selector).css('z-index', 100);
	$('#featurePanel' + selector).css('z-index', 100);
    $('#featurePanel' + selector).show();
    $('#featureContent' + selector).show();
	
}

function toggleFeatureTabs(){
    $(".featurePanel, .featureContent").hide();
    $(".featureTab").addClass("inactive");
    
    $('.featureContainer').mouseleave(
    	function(){
    		hideFeatureTab(1);
    		hideFeatureTab(2);
    		hideFeatureTab(3);
    	}
    );
    $('#featureTab1').mouseenter(
    	function(){
    		if ( $(this).hasClass('inactive') == true){
    		    hideFeatureTab('2');
    			hideFeatureTab('3');

    			showFeatureTab('1');
    		}else{
    			hideFeatureTab('1');
    		}
    	}
    );
    $('#featureTab2').mouseenter(
    	function(){
    		if ( $(this).hasClass('inactive') == true){
    			hideFeatureTab('1');
    			hideFeatureTab('3');
    			showFeatureTab('2');
    		}else{
    			hideFeatureTab('2');
    		}
    	}
    );

    $('#featureTab3').mouseenter(
    	function(){
    		if ( $(this).hasClass('inactive') == true){
    	    	hideFeatureTab('1');
    			hideFeatureTab('2');
	
    			showFeatureTab('3');
    		}else{
    			hideFeatureTab('3');
    		}
    	}
    );
    
}

function setCookie(c_name,value,exdays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate() + 365);
	var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString() + "; path=/");
	document.cookie=c_name + "=" + c_value;
}

function MobileView(){
	setCookie('mobile', true, 365);
	window.location.reload();
}

		
$(document).ready(function(){

	toggleFeatureTabs();
});


// prod
var service_endpoint = 'http://www.ark.org/directory-svc/endpoint.php';
var service_endpoint_token = '6907891706be837e76385f9fbbed3365';
var panelAnimationInProgress = 0;
var backgroundImages = null;
var currentBackgroundImage = 0;

function getQueryParam(name){
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );
	if( results == null ){
		return "";
	}else{
		return decodeURIComponent(results[1].replace(/\+/g, " "));
	}
}
	
/**
 * Wrap Urls in a proxy service to provide caching.  Increased performance + avoids problems with rate-limited services.
 */
function ProxyUrl(opts){
	var proxy_base = 'http://www.arkansas.gov/directory-svc/proxy.php' ;

	var proxy_url = proxy_base + '?url=' + encodeURIComponent(opts.url);

	if (typeof(opts.jsonp) != 'undefined' && opts.jsonp == 1){
		proxy_url += "&jsonp=1" ;
	}
	
	if (typeof(opts.maxage) != 'undefined' && opts.maxage > 0){
		proxy_url += "&maxage=" + opts.maxage;
	}
	
	if (typeof(opts.callback) != 'undefined' && opts.callback.length > 0){
		proxy_url += "&callback=" + opts.callback;
	}
	
	if (typeof(opts.token) != 'undefined' && opts.token.length > 0){
		proxy_url += "&token=" + opts.token;
	}
	
	return proxy_url;
}

function isNullorEmpty(val){
	if (typeof(val) != undefined && val != null && val != 'null' && val.length > 0){
		return false;
	}else{
		return true;
	}
}

/**
 * Helper function to convert a url and a title to a hyperlink.
 */
function Url2Link(url, title){
	if (!isNullorEmpty(url)){
		return '<a href="' + url + '"' + ' title="' + url + '"' + '>' + title + '</a>' ;	
	}else{
		return title ;
	}
}

/**
 * Helper function to convert a email address to a hyperlink.
 */
function Email2Link(email){
	if (email.length > 0){
		return '<a href="mailto:' + email + '"' + ' title="' + email + '"' + '>' + email + '</a>' ;
	}else{
		return email ;
	}
}
/**
	Replace URLS in text strings with hyperlinks.  Also replaces twitter #hashtags and @usernames with the appropriate links
	inputText: Text string to linkify
*/
function linkify(inputText) {
	if (typeof(inputText) == 'undefined'){
		return inputText;
	}
	var replaceText, replacePattern1, replacePattern2, replacePattern3, hashtagPattern, userPattern;
	
	// URLs starting with http://, https://, or ftp://
	replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
	replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
	
	// URLs starting with www. (without // before it, or it'd re-link the ones done above)
	replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
	replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
	
	// Change email addresses to mailto:: links
	replacePattern3 = /(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})/gim;
	replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');

	// Change twitter hashtags to search link
	hashtagPattern = /(^|\s)#(\w+)/g;
	
	replacedText = replacedText.replace(hashtagPattern, '$1#<a href="http://search.twitter.com/search?q=%23$2">$2</a>');

	// Change twitter @usernames to links
	userPattern = /(^|\s)@(\w+)/g;
	replacedText = replacedText.replace(userPattern, '$1@<a href="http://www.twitter.com/$2">$2</a>');
	
	return replacedText
}


function htmlentities( s ){
	// http://kevin.vanzonneveld.net
	// +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// *     example 1: htmlentities('Kevin & van Zonneveld');
	// *     returns 1: 'Kevin &amp; van Zonneveld'
 
	var div = document.createElement('div');
	var text = document.createTextNode(s);
	div.appendChild(text);
	return div.innerHTML;
}

function GetAgencyDetail(item){

	var html = '';

	if (!isNullorEmpty(item.detail.Address)){
		html+= '<p>' + item.detail.Address + '</p>';
	}

	if (!isNullorEmpty(item.detail.CityStateZip)){
		html+= '<p>' + item.detail.CityStateZip + '</p>';
	}

	if (!isNullorEmpty(item.detail.Email)){
		html+= '<p>' + Email2Link(item.detail.Email.replace(/"/g, '')) + '</p>';
	}

	if (!isNullorEmpty(item.detail.Agency.Url)){
		html+= '<p>' + Url2Link(item.detail.Agency.Url, item.detail.Agency.Url)+ '</p>';
	}

	if (!isNullorEmpty(item.detail.Phone)){
		html+= '<p>' + item.detail.Phone + ' (p)</p>';
	}

	if (!isNullorEmpty(item.detail.Fax)){
		html+= '<p>' + item.detail.Fax + ' (f)</p>';
	}

	if (!isNullorEmpty(item.detail.TDD)){
		html+= '<p>' + item.detail.TDD + ' (tdd)</p>';
	}

	if (!isNullorEmpty(item.detail.StateDirectoryLink) && isNullorEmpty(item.detail.Agency.Url)){
		html+= '<p>' + Url2Link(item.detail.StateDirectoryLink, 'Open in State Directory') + '</p>';
	}

	return html;
}

function ToggleSuggestionDetail(id){
	var detailSelector = '#detail_' + id;
	var displayStatus = $(detailSelector).css('display') ;

	$('#suggestions .detail').hide();
	if (displayStatus == 'none'){
		$(detailSelector).slideDown();
	}
}

function Coalesce(value1, value2){

	if (!isNullorEmpty(value1)){
		return value1;
	}

	if (!isNullorEmpty(value2)){
		return value2;
	}
	return '';
}

function GetPeopleAgencySuggestions(q, selector, count){

	var url = ProxyUrl({
				url: service_endpoint + '?type=agencySuggestions&q=' + encodeURIComponent(q) + '&output=json&r=' + Math.random(),
				jsonp: 1,
				callback: 'jquery',
				token: service_endpoint_token
				});
				
	$.ajax({
		url: url,
		dataType: 'jsonp',
		success: function(data){
			var max = count;
			
			if (data.items.length < max){
				max = data.items.length;
			}
			var html = '' ;
			if (data.items.length > 0){
				html+= '<ul>';
				
				for (var i = 0; i < max; i++){
					var item = data.items[i];
					
					var detailHtml = GetAgencyDetail(item) ;
					
					if (item.detail.Type == 'Person'){
						html+= '<li>';
						html+= '&#187;&nbsp;';
						html+= '<a href="javascript:void(0)" onclick="ToggleSuggestionDetail(' + item.id + ')"' + '">' + item.detail.DisplayName.replace(/"/g, '') + '</a>';
						html+= '<span class="personAgency">';
						html+= Url2Link(item.detail.Agency.Url, item.detail.Agency.Name);
						html+= '</span>';
						html+= '<div class="detail hidden" id="detail_' + item.id + '">' + detailHtml + '</div>';
						html+= '</li>';
					}else{
						html+= '<li>';
						html+= '&#187;&nbsp;';
						var agencyUrl = Coalesce(item.url,item.detail.StateDirectoryLink);
						html+= Url2Link(agencyUrl, item.detail.DisplayName);
						html+= '</li>';
					}
				}
				
				html+= '</ul>';
			}else{
				html+= '<p class="nomatch">No matching people/agencies. ';
				html+= Url2Link('/Pages/googleSearch.aspx?q=' + encodeURIComponent(q), 'Search all of Arkansas.gov for "' + htmlentities(q) + '"?') ;
				html+= '</p>';
			}
			
			$(selector).html(html);
	  }
	});
}

function PeopleAgencySearch(q, selector, count){

	var url = ProxyUrl({
				url: service_endpoint + '?type=agencySuggestions&q=' + encodeURIComponent(q) + '&max=' + count + '&output=json&r=' + Math.random(),
				jsonp: 1,
				callback: 'jquery',
				token: service_endpoint_token
				});
				
	$.ajax({
		url: url,
		dataType: 'jsonp',
		success: function(data){
			var max = count;
			
			if (data.items.length < max){
				max = data.items.length;
			}
			var html = '' ;
			if (data.items.length > 0){
				html+= '<ul>';
				
				for (var i = 0; i < max; i++){
					var item = data.items[i];
					
					var detailHtml = GetAgencyDetail(item) ;
					
					if (item.detail.Type == 'Person'){
						html+= '<li>';
						html+= '<strong>' + item.detail.DisplayName.replace(/"/g, '') + '</strong>';
						html+= '<span class="personAgency">';
						html+= Url2Link(item.detail.Agency.Url, item.detail.Agency.Name);
						html+= '</span>';
						html+= '<div class="detail" id="detail_' + item.id + '">' + detailHtml + '</div>';
						html+= '</li>';
					}else{
						html+= '<li>';
						html+= '<strong>' + item.detail.DisplayName + '</strong>';
						html+= '<div class="detail" id="detail_' + item.id + '">' + detailHtml + '</div>';
						html+= '</li>';
					}
				}
				
				html+= '</ul>';
			}else{
				html+= '<p class="nomatch">No matching people/agencies. ';
				html+= Url2Link('/Pages/googleSearch.aspx?q=' + encodeURIComponent(q), 'Search all of Arkansas.gov for "' + htmlentities(q) + '"?') ;
				html+= '</p>';
			}
			
			$(selector).html(html);
	  }
	});
}

function GetServiceSuggestions(q, selector, count){

	var url = ProxyUrl({
				url: service_endpoint + '?type=serviceSuggestions&q=' + encodeURIComponent(q) + '&output=json&r=' + Math.random(),
				jsonp: 1,
				callback: 'jquery',
				token: service_endpoint_token
				});
				
	$.ajax({
		url: url,
		dataType: 'jsonp',
		success: function(data){
			var max = count;
			
			if (data.items.length < max){
				max = data.items.length;
			}
			
			var html = '' ;
			if (data.items.length > 0){
				html+= '<ul>';
				
				for (var i = 0; i < max; i++){
					var item = data.items[i];

					html+= '<li>';
					html+= '&#187;&nbsp;';
					html+= Url2Link(item.url, item.name);
					html+= '</li>';
				}
				html+= '</ul>';
			}else{
				html+= '<p class="nomatch">No matching services. ';
				html+= Url2Link('/Pages/googleSearch.aspx?q=' + encodeURIComponent(q), 'Search all of Arkansas.gov for "' + htmlentities(q) + '"?') ;
				html+= '</p>';
			}
			
			$(selector).html(html);
	  }
	});
}

function pluralizeTitle(count, title){
	title = count + ' ' + title;
	if (count == 1){
		return title;
	}else{
		return title + 's';
	}
}

