
/**
	Setup the twitter account display.
	username: Twitter Username to show
	selector: jquery selector for the container where you want to display twitter account info.
*/
function SetupTwitterAccount(username, selector){
	var accountInfo = $(selector).html();
	accountInfo += '<a href="http://www.twitter.com/' + username + '" title="Go to Twitter Page">Latest Tweet by<br />' + username + '</a>' ;
	$(selector).html(accountInfo) ;
}

/**
	Display X number of tweets for a twitter user
	username: Twitter Username to show
	count: Number of tweets to display
	selector: jquery selector for the container where you want to display the tweets.  Examples: '#twitterstatus' or '.twitterstatus'
*/
function GetTwitterUserTimeLine(username, count, selector){

	var url = ProxyUrl({
				url: 'http://twitter.com/status/user_timeline/' + username + '.json?count=' + count,
				jsonp: 1,
				token: '59cee1c0b912a8244488c38437924958'
				});

	$.ajax({
	  url: url,
	  dataType: 'jsonp',
	  success: function(entries){
	  	var update = '<ul>';
		for (var i = 0; i < entries.length; i++){
			update += '<li>' ;
			update += linkify(entries[i].text) ;
			update += '</li>' ;
		}
		update += '</ul>' ;
		$(selector).html(update) ;
	  }
	});
}

/**
	Display top shared content from AddThis.
	username: AddThis username
	count: Number of updates to display
	selector: jquery selector for the container where you want to display the updates.  Examples: '#sharedText' or '.sharedText'
*/
function GetTopShared(username, count, selector){

	var url = ProxyUrl({
				url: 'http://q.addthis.com/feeds/1.0/shared.json?pubid=' + username,
				jsonp: 1,
				maxage: 43200, // 12 hours
				token: '929bb03c900ffe09267213deda7ff838'
				});

	$.ajax({
	  url: url,
	  dataType: 'jsonp',
	  success: function(entries){
	  
	  	var max = count;
		
		if (entries.length < max){
			max = entries.length;
		}
		
	  	var update = '<ul>';
		for (var i = 0; i < max; i++){
			update += '<li>' ;
			update += Url2Link(entries[i].url, entries[i].title) ;
			update += '</li>' ;
		}
		update += '</ul>' ;
		$(selector).html(update) ;
	  }
	});
}

/**
	Display X number of status updates for a facebook user
	username: Facebook User Name or Id
	count: Number of updates to display
	selector: jquery selector for the container where you want to display the updates.  Examples: '#facebookstatus' or '.facebookstatus'
*/
function GetFacebookUpdates(username, count, selector){
	
	var url = ProxyUrl({
				url: 'https://graph.facebook.com/' + username + '/feed?access_token=AAACJM5PwE6cBAAN8wU2Ck9i7t8RadrpApXZCDxTZC1IFu1kBMmqG1zBJnNPZCukw5U3hNCKqbZBaAHlwFJkjdm125mZAPnqYZD',
				jsonp: 1,
				callback: "jquery",
				token: "4bf84fa9fd59cfc94cb43341e26ec467"
				});

	$.ajax({
		url: url,
		dataType: 'jsonp',
		success: function(entries){
			
			var max = count;
			
			if (entries.data.length < max){
				max = entries.data.length;
			}
			
			var update = '<ul>';
	
			for (var i = 0; i < max; i++){
				if (typeof(entries.data[i].message) == 'undefined'){
					// No message for this post, go on to the next item (if there are any).
					if (max + 1 < entries.data.length){
						max++;
					}
				}else{
					update += '<li>';
					var messageBody = linkify(entries.data[i].message.substring(0, 240));
					
					if (messageBody.length < entries.data[i].message.length){
						messageBody += '...';
					}
					update += Url2Link('https://www.facebook.com/' + username, messageBody);
					update += '</li>';
				}
			}
			update += '</ul>';
			$(selector).html(update);
		}
	});
}

/**
	Display top services from the portal.
	count: Number of updates to display
	selector: jquery selector for the container where you want to display the services.  Examples: '#topServices' or '.topServices'
*/
function GetTopServices(count, selector, type){

	var view = '7FC1BAEA-A925-4BEE-92B0-74D67F0DE22C';
	if (type == 'citizen'){
		view = '2205ED25-E142-4B2D-BE74-D32B99CAC355';
	}

	var url = ProxyUrl({
				url: 'https://www.ark.org/ina_sharepointlistreader/listreader.svc/portal-edit/0336BE2D-9F1C-402C-A9D5-3DC34D7410F8/' + view + '?format=json',
				jsonp: 1,
				callback: 'jquery',
				token: '6907891706be837e76385f9fbbed3365'
				});
				
	$.ajax({
		url: url,
		dataType: 'jsonp',
		success: function(data){

		var max = count;
		
		if (data.Rows.length < max){
			max = data.Rows.length;
		}
		
		var update = '<ul>';
		for (var i = 0; i < max; i++){
			update += '<li>';
			update += Url2Link("/services/Pages/servicesDetail.aspx?Title=" + data.Rows[i].Title, data.Rows[i].shorttitle);
			update += '</li>';
		}
		update += '</ul>';
		$(selector).html(update) ;
	  }
	});
}

function GetFacebookAccounts(count, selector){

	var view = '63B675DB-220C-438C-9C5E-AFA4AB9ED8E5';

	var url = ProxyUrl({
				url: 'https://www.ark.org/ina_sharepointlistreader/listreader.svc/portal-edit/13A225CD-5AB7-474B-911E-9D16E3849B3A/' + view + '?format=json',
				jsonp: 1,
				callback: 'jquery',
				token: '6907891706be837e76385f9fbbed3365'
				});
				
	$.ajax({
		url: url,
		dataType: 'jsonp',
		success: function(data){

		var max = count;
		
		if (data.Rows.length < max){
			max = data.Rows.length;
		}
		
		var update = '<ul>';
		for (var i = 0; i < max; i++){
			update += '<li>';
			update += Url2Link(data.Rows[i].facebook, data.Rows[i].Title);
			update += '</li>';
		}
		update += '</ul>';
		$(selector).html(update) ;
	  }
	});
}
/**
	Get photos from a flickr Group
	ns_id: Flickr Id.  Example: 755036@N20
	count: How many photos to display?
	selector: jquery selector for the container where you want to display the photos.  Example: '#flickrGroupPool'
*/
function GetFlickrGroupPhotos(ns_id, count, selector){

	var url = ProxyUrl({
				url: 'http://api.flickr.com/services/feeds/groups_pool.gne?id=' + ns_id + '&format=json&nojsoncallback=1',
				jsonp: 1,
				callback: 'jquery',
				token: 'e448141cd7bd756ac1b9f5ebe9f593d1'
				});
				
	$.ajax({
	  url: url,
	  dataType: 'jsonp',
	  success: function(data){
		var max = count;
		
		if (data.items.length < max){
			max = data.items.length;
		}

		var htmlString = '' ;
		htmlString += '<ul class="flickrThumb">';

		for(var i=0; i < max; i++){
			var item = data.items[i];

			// The default image is medium sized with original aspect ratio.  Replace _m.jpg with _s.jpg in image source to get a 75x75 cropped photo.
			var croppedSource = (item.media.m).replace("_m.jpg", "_s.jpg");
			htmlString += '<li class="flickrThumb">';
			htmlString += '<a href="' + item.link + '" target="_blank">';
	        htmlString += '<img title="' + item.title + '" src="' + croppedSource + '" alt="' + item.title + '" />';
    	    htmlString += '</a>';
    	    htmlString += '</li>';
		}
		
		htmlString += '</ul>';
		
		$(selector).html(htmlString) ;
		
	  }
	});
}
	
function searchChanged(q){
	if ($.trim(q).length > 0){
		$('#suggestions').fadeIn();
		GetServiceSuggestions(q,'#serviceSearchResults', 5) ;
		GetPeopleAgencySuggestions(q, '#peopleSearchResults', 5) ;
		GetSiteSuggestions(q, '#siteSearchResults', 5, 'arkansas.govportal');
		$('p.suggestMore a').attr('href','/Pages/googleSearch.aspx?q=' + encodeURIComponent(q));
		$('#peopleSuggestions p.suggestMore a').attr('href','/Pages/peopleSearch.aspx?q=' + encodeURIComponent(q));
		$('#serviceSuggestions p.suggestMore a').attr('href','/services/Pages/servicesAlpha.aspx');

	}else{
		$('#suggestions').fadeOut();
	}
}


function GetServicesByLocation(){
	var city;
	var state;
	var county;
	var lat;
	var lon;
	
	var service_endpoint = 'http://www.arkansas.gov/nearme/svc.php?mode=geoip';
	var url = ProxyUrl({
		url: service_endpoint + '&r=' + Math.random(),
		jsonp: 1,
		callback: 'jquery',
		token: '116ef4c3736bd7fdd64c5654375ea20e'
		});
	$.ajax({ 
		url: url,
		dataType:'jsonp',
		success: function(results){
			city = results.city;
			state = results.state;
			county = results.county;
			lat = results.lat;
			lon = results.lon;
			
			var formattedLocation = city + ", " + state;
			$('#jobsData .nearmeLocation').prepend('Location: <strong>' + formattedLocation + '</strong> <a href="/aboutArkansas/Pages/arkansasMaps.aspx">Change &raquo;</a>');

			fetchNearbyServicesAndLocations(lat, lon, '', city, state, county);
		}
	});
}

function GetARWorksJobs(selector){
	
	var service_endpoint = 'http://www.arkansas.gov/nearme/svc.php?mode=jobs';
	var url = ProxyUrl({
		url: service_endpoint + '&r=' + Math.random(),
		jsonp: 1,
		callback: 'jquery',
		token: '116ef4c3736bd7fdd64c5654375ea20e'
		});
	$.ajax({ 
		url: url,
		dataType:'jsonp',
		success: function(results){
			var max = 4;
			
			if (results.length < max){
				max = results.length;
			}
			var update = '<ul>';
			for (var i = 0; i < max; i++){
				var result = results[i];
				update += '<li>';
				update += Url2Link(result.URL, result.Title + ' - ' + result.Location);
				update += '</li>';
			}
			update += '</ul>';
			$(selector).html(update) ;
		}
	});
}
	
function fetchNearbyServicesAndLocations(lat,lon,address, city, state, county){

	var user_city = 'Little Rock';
	var user_state = 'AR';
	var user_county = 'Pulaski';
	var service_endpoint = "http://www.arkansas.gov/nearme/svc.php?mode=nearme" + 
		"&lat=" + lat +
		"&lon=" + lon +
		"&address=" + escape(address) +
		"&city=" + encodeURIComponent(city) +
		"&state=" + encodeURIComponent(state) +
		"&county=" + encodeURIComponent(county);
		
	var url = ProxyUrl({
				url: service_endpoint + '&r=' + Math.random(),
				jsonp: 1,
				callback: 'jquery',
				token: '116ef4c3736bd7fdd64c5654375ea20e'
				});

	$.ajax({ 
		url: url,
		dataType:'jsonp',
		success: function(results, code, obj){
			ws_results = results;
			if( results.length == 0 ){
				return;
			}
			
			user_lat	= results.location.lat;
			user_lon	= results.location.lon;
			user_city	= results.location.city;
			user_state	= results.location.state;
			user_county = results.location.county;

			// State Jobs
			var jobs = results.jobs.state;
			$('#tabStateJobs').html( pluralizeTitle(jobs, 'State Job Opening') );
			
			// Private Jobs
			var pjobs = results.jobs.private;
			$('#tabPrivateJobs').html( pluralizeTitle(pjobs, 'Private Job Opening') );

			// Online Services
			var online = results.points.online.length + results.points.online_city.length + results.points.online_business.length + results.points.online_citizen.length;
			$('#tabOnlineServices').html( pluralizeTitle(online, 'Online Service') );
			
			// ADH Health Units
			var adh = results.points.adh.length;
			$('#tabADH').html( pluralizeTitle(adh, 'ADH Health Unit') ) ;
			
			// Child Support Offices
			var ocse = results.points.ocse.length;
			$('#tabOCSE').html( pluralizeTitle(ocse, 'Child Support Office') ) ;
			
			// DHS Offices
			var dhs = results.points.dhs.length;
			$('#tabDHS').html( pluralizeTitle(dhs, 'DHS Office') ) ;
			
			// Revenue Offices
			var revenue = results.points.revenue.length;
			$('#tabRevenue').html( pluralizeTitle(revenue, 'Revenue Office') ) ;
			
			// Workforce Offices
			var workforce = results.points.workforce.length;
			$('#tabWorkforce').html( pluralizeTitle(workforce, 'Workforce Office') ) ;
			
			// Lottery Retailers
			
			// State Parks
		}
	});
}
	function GetSiteSuggestions(q, selector, count, affiliate){
		
		var search_url = 'http://www.arkansas.gov/directory-svc/search_usa_gov.php?affiliate=' + encodeURIComponent(affiliate) + '&query=' + encodeURIComponent(q);
		var search_page_token = '116ef4c3736bd7fdd64c5654375ea20e';
		
		var url = ProxyUrl({
					url: search_url,
					jsonp: 1,
					callback: 'jquery',
					token: search_page_token
					});
					
		$.ajax({
			url: url,
			dataType: 'jsonp',
			success: function(data){
	
				html = '';
				if (data.endrecord > 0){
	
					var max = count;
					
					if (data.results.length < max){
						max = data.results.length;
					}
					
					html+= '<ul>';
					
					for(var i=0; i<max; i++){
						var item = data.results[i];
						html+= '<li>';
						html+= '&#187;&nbsp;';
						html+= Url2Link(item.unescapedUrl, item.title);
						html+= '</li>';
					}
					
					html+= '</ul>';
				}else{
					html+= '<p class="nomatch">No matching pages. ';
					html+= Url2Link('/Pages/googleSearch.aspx?q=' + encodeURIComponent(q), 'Search all of Arkansas.gov for "' + htmlentities(q) + '"?') ;
					html+= '</p>';
				}
				
				$(selector).html(html);
			}
		});
	}

function GetSiteSuggestionsYahoo(q, selector, count, sites, type){
	var appid = '75hmGSbV34GYyhqD5d40E0y_lM6t1PZu3PewSMBEiS5hEDNItv7tPkVqQfxZYg--';
	var url = 'http://boss.yahooapis.com/ysearch/web/v1/' + encodeURIComponent(q) + '?sites=' + sites + '&appid=' + appid + '&format=json&count=' + count + '&type=' + type;
	
	$.ajax({
		url: url,
		dataType: 'jsonp',
		success: function(data){

			html = '';
			if (data.ysearchresponse.count > 0){

				var max = count;
				
				if (data.ysearchresponse.resultset_web.length < max){
					max = data.ysearchresponse.resultset_web.length;
				}
				
				html+= '<ul>';
				
				for(var i=0; i<max; i++){
					var item = data.ysearchresponse.resultset_web[i];
					html+= '<li>';
					html+= '&#187;&nbsp;';
					html+= Url2Link(item.url, item.title);
					//html+= '<span class="displayUrl">' + Url2Link(item.url, item.dispurl) + '</span>';
					html+= '</li>';
				}
				
				html+= '</ul>';
			}else{
				html+= '<p class="nomatch">No matching pages. ';
				html+= Url2Link('/Pages/googleSearch.aspx?q=' + encodeURIComponent(q), 'Search all of Arkansas.gov for "' + htmlentities(q) + '"?') ;
				html+= '</p>';
			}
			
			$(selector).html(html);
		}
	});
}

function SuggestionsInit(){

	$('#suggestions p.suggestMore a').html('More');
	
	$('#suggestions').hide();
	$('#suggestions').mouseleave(function(){
		$('#suggestions').fadeOut();
	});
	
	$('#agencySuggestionDetail').hide();
	
	$('#searchTerms').click(function(){
		searchChanged(this.value);
	});

	$('#searchTerms').keyup(function(){
		searchChanged(this.value);
	});	
}

function addPanelMouseover(){
	$('div.panel').mouseenter(function(e){
		maximizePanel(this);
	});
	$('#panels').mouseleave(function(){
		restoreAllPanels();
	});	
}


function maximizePanel(selector){

	// Minimize all panels
	$('div.panel').removeClass("max");
	$('div.panel').removeClass("normal");	
	$('div.panel').addClass("min");

	// Maximize selected panel
	$(selector).addClass("max");
			
	$(selector).find("div.primary").hide();
	//$(selector).find("div.primary").fadeIn(500);
	$(selector).find("div.primary").show();

	
}

function restoreAllPanels(){		
	$('div.panel').removeClass("max");
	$('div.panel').removeClass("min");
	$('div.panel').addClass("normal");
}

function GovernmentTabsInit(){
	$('#jobsTab').addClass('active');
	
	$('#jobsTab').click(function(){
		DeactivateGovernmentTabs();
		$('#jobsData').show();
		$('#jobsTab').addClass('active');
	});
	
	$('#newsTab').click(function(){
		DeactivateGovernmentTabs();
		$('#newsData').show();
		$('#newsTab').addClass('active');
	});
	
	$('#calendarTab').click(function(){
		DeactivateGovernmentTabs();
		$('#calendarData').show();
		$('#calendarTab').addClass('active');
	});	
}

function DeactivateGovernmentTabs(){
	$('.tabData').hide();
	$('.governmentTab').removeClass("active");
}

function GetHomeBackground(){

	var list = '1FCB4222-0E8E-4E97-83F9-AFDF4471D080';
	var view = 'DB76748A-DDFF-4B95-9697-DDDCD3A85D13';
	
	var url = ProxyUrl({
				url: 'https://www.ark.org/ina_sharepointlistreader/listreader.svc/portal-edit/' + list + '/' + view + '?format=json',
				jsonp: 1,
				callback: 'jquery',
				token: '6907891706be837e76385f9fbbed3365',
				maxage: 1
				});
				
	$.ajax({
		url: url,
		dataType: 'jsonp',
		success: function(results){
			SetHomeBackgroundNavigation(results);
			InitializeHomeBackground();
	  }
	});
}

function GetPreviousHomeBackground(){
	var current = currentBackgroundImage;
	var previous = current;
	previous--;
	
	if (previous < 0){
		previous = backgroundImages.Rows.length - 1;
	}
	
	return previous;
}

function GetNextHomeBackground(){
	var current = currentBackgroundImage;
	var next = current;
	next++;
	
	if (next == backgroundImages.Rows.length){
		next = 0;
	}
	
	return next;
}

function PreviousHomeBackground(){
	var previous = GetPreviousHomeBackground();
	currentBackgroundImage = previous ;
		
	SetHomeBackground(backgroundImages.Rows[previous].RequiredField);
}

function NextHomeBackground(){
	var next = GetNextHomeBackground();
	currentBackgroundImage = next;
	
	SetHomeBackground(backgroundImages.Rows[next].RequiredField);
}

function PreloadNextBackground(){
	var next = GetNextHomeBackground();

	if ( $('#nextBackground').length){
		// already exists.  continue.
	}else{
		// Create hidden div, if it doesn't already exist.
		var hiddenBg = '<div id="nextBackground" style="display:none:"></div>';
		$('body').append(hiddenBg);
	}
	$('#nextBackground').css("background-image", "url(/" + backgroundImages.Rows[next].RequiredField + ")");
}

function SetBackgroundTitle(){
	var title = backgroundImages.Rows[currentBackgroundImage].Description;
	var NameOrTitle = backgroundImages.Rows[currentBackgroundImage].NameOrTitle
	
	if (isNullorEmpty(title) && !isNullorEmpty(NameOrTitle)){
		title = NameOrTitle;
	}
	
	$('#ipCopyright').html(title);
}

function InitializeHomeBackground(){
	SetBackgroundTitle();
	$('#ipCopyright').click(function(){
		document.location="/aboutArkansas/Pages/AboutthePhotographers.aspx";
	});
	
	PreloadNextBackground();
}

function SetHomeBackground(bgUrl){
	SetBackgroundTitle();
	$('#homeBody').css("background-image", "url(/" + bgUrl + ")");
	$('#ipCopyright').click(function(){
		document.location="/aboutArkansas/Pages/AboutthePhotographers.aspx";
	});
	
	PreloadNextBackground();
}

function SetHomeBackgroundNavigation(results){
	backgroundImages = results;
	
	$('#ipNext').click(function(){
		NextHomeBackground();
	});

	$('#ipPrevious').click(function(){
		PreviousHomeBackground();
	});
}


$(function(){
	// Hide the home button
	//$(".globalNavContainer td:lt(1)").hide(); // Hide the home tab.  Ugly.  Displays briefly, then disappears.

	// Get home background images
	GetHomeBackground();
		
	// Add mouseover event to all panels
	addPanelMouseover();
	
	SuggestionsInit();
	GetTopServices(5, '#topBusinessServices', 'business') ;
	GetTopServices(5, '#topCitizenServices', 'citizen') ;
	GetTopShared('arkansasgov', 5, '#topShared') ;
	GetFacebookUpdates('arkansasgov', 1, '#facebookText') ;
	GetFlickrGroupPhotos('755036@N20', 16, '#flickrGroupPool') ;
	SetupTwitterAccount('arkansasgov', '#twitterAcct') ;
	GetTwitterUserTimeLine('arkansasgov', 1, '#twitterText') ;	

	GovernmentTabsInit();
	GetServicesByLocation();
	
	GetARWorksJobs('#jobPostings');
	
	//showFeatureTab('1');
	
});
