

/*---------------
	BELOW IS THE COMMUNICATION MODEL FOR THE STATES AND PARKS GRID.
	DEVELOPED BY: CODIN PANGELL, FL2 2009
---------------*/

//Global Variables
var statesObj; //store the statesObject for later use
var featuredObj; //store the featuredObject for later use
var interestListObj; //store the interestlistObject for later use
var regionListObj; //store the regionlistObject for later use
var parksObj; //store the parksObject for later use
var stateObjarr; //the statesObject as an array (not a JSON object)
var parksObjarr; //the parksObject as an array (not a JSON object)
var currentFeatured; //stores position in the featuredObj

$(document).ready(function(){

	//load footer 
	loadFooter();
	
	//get involved
	getinvolved();
	
	$("#cells").html(""); //clear html
	
	//display:loader
	$('.blockScreen').css('filter','alpha(opacity=70)').fadeIn(1000);
	
	//Load the Featured Parks on the Right of the page
	$.getJSON("json_interface.aspx?action=homeFeatured", function(json) {
		featuredObj = json;
		initiate_featured();
	});
	
	//Load the Featured List checkboxes
	$.getJSON("json_interface.aspx?action=interestList", function(json) {
		interestListObj = json;
		initiate_interestListboxes();
	});
	
	
	//Load the Region List checkboxes
	$.getJSON("json_interface.aspx?action=regionList", function(json) {
		regionListObj = json;
		initiate_regionListboxes();
	});
	
	
	//Load Grid Content Below
	$.getJSON("json_interface.aspx?action=states", function(json) {
		statesObj = json;
		
		//determine if a deep link is used. Initiate parsing.
		var fullurl = window.location.toString();
		if (fullurl.indexOf('#/most_viewed')>0){
			Initiate_States('viewed');
		}else if (fullurl.indexOf('#/most_popular')>0){
			Initiate_States('popular');
		}else if (fullurl.indexOf('#/most_unknown')>0){
			Initiate_States('unknown');
		}else if (fullurl.indexOf('#/alphabetically')>0){
			Initiate_States('alphabetically');
		}else if (fullurl.indexOf('#/state')>0){ //move over to state loading cycle
			//parse out the state name and a sorting type from the URL
			var _tempUrl=fullurl.indexOf('#')
			_tempUrl=fullurl.substring(fullurl.indexOf('#'));
			_tempUrl=_tempUrl.split("#/state/").join("");
			_tempUrl=_tempUrl.split("-").join(" "); //represents a space if somehow one gets in URL from DCMS (like north dakota)
			var _sortType="alphabetically"
			if (_tempUrl.indexOf("most_popular")>0){
				_sortType="most_popular";
			}
			if (_tempUrl.indexOf("alphabetically")>0){
				_sortType="alphabetically";
			}
			if (_tempUrl.indexOf("most_viewed")>0){
				_sortType="most_viewed";
			}
			var _stateName;
			if (_tempUrl.indexOf("/most_viewed")>-1 || _tempUrl.indexOf("/most_popular")>-1 || _tempUrl.indexOf("/alphabetically")>-1){
				_tempUrl=_tempUrl.split("/most_viewed").join("");
				_tempUrl=_tempUrl.split("/most_popular").join("");
				_stateName=_tempUrl.split("/alphabetically").join("");
			}else{
				_stateName=_tempUrl;
			}
			//find the state via name from the state JSON object
			var _foundFlag=0;
			$.each(statesObj.states,function(i,item){
				if (item.stateName.toLowerCase()==_stateName.toLowerCase()){
					_foundFlag=1;
					loadParks(item.stateId,_sortType);
					return;
				}
			});
			if (_foundFlag==0){ //state was not found. So send the person back to the main sort by state grid.
				loadParks('alphabetically');
			}
		}else{ //alphabetically is default
			Initiate_States('alphabetically');
		}
	});
	
	//set the deep linking items
	$('.deepLinkedItem a').click(function() {  
		$.address.title($(this).attr('title'));
	});
	
	//set the main sorting links
	$('#viewed').click(function() { Initiate_States('viewed'); return false; });
	$('#popular').click(function() { Initiate_States('popular'); return false; });
	$('#unknown').click(function() { Initiate_States('unknown'); return false; });
	$('#alphabetically').click(function() { Initiate_States('alphabetically'); return false; });
});
/*----------------------------------
	State Sorting and Communication
----------------------------------*/
function Initiate_States(ty){

	//clear out the active nav item
	$('#viewed').removeClass('selected');
	$('#popular').removeClass('selected');
	$('#unknown').removeClass('selected');
	$('#alphabetically').removeClass('selected');
	
	//sort stateObjarray based on clicks in descending order
	stateObjarr = eval(statesObj.states);
	$('#'+ty).addClass('selected');
	switch (ty){
		case "viewed":
			stateObjarr.sort(compareTotals);
			break;
		case "alphabetically":
			stateObjarr.sort(compareAlphabetically);
			break;
		case "popular":
			stateObjarr.sort(compareSpotTags);
			break;
		case "unknown":
			stateObjarr.sort(compareUnkown);
			break;
	}
	
	//---Initially fade out the existing items before the fade in
	$.each(stateObjarr,function(i,item){
		$("#cell-"+i).fadeOut(1000);
		if ( i == stateObjarr.length-1 ){ //all items are faded. Now load new set.
			setTimeout('completeLoad()',1000)
		}
	});
}
/*----------------------------------
	Main Page Load For States
----------------------------------*/
function completeLoad(){
	
	//Set all checkboxes for the regions and interests once a main section is entered
	$('.regionCheckboxes').attr('checked',true);
	$('.interestCheckboxes').attr('checked',true);
	
	//add the callout spot to all results
	var spotCallout="<div id='spot-callout-container'><img src='data/images/spot-callout.gif' width='320' height='115' id='spot-callout' alt='Where\'s your spot?' /></div>"
	$("#cells").html(spotCallout); //clear previous html

	//display or redisplay list
	$.each(stateObjarr,function(i,item){
		var _html = '<div class="cell" id="cell-' + i + '" style="display:none;" onclick="javascript:loadParks('+item.stateId+');">';
		_html += '<img src="data/uploads/'+unknown(item.thumbnail)+'" width="164" height="120" alt="State" />';
		_html += '<span class="cell-title">'+unknown(item.stateName)+'</span>';
		if (unknown(item.parkCount)==1){
			_html += '<span class="cell-meta">'+unknown(item.parkCount)+' Place</span>';
		}else{
			_html += '<span class="cell-meta">'+unknown(item.parkCount)+' Places</span>';
		}
		_html += '<span class="cell-location-tag">Region: '+unknown(item.region)+'</span>';
		_html += '<div class="cell-tags">';
		_html += '<span class="tag-number">'+unknown(item.SpotTags)+'</span>';
		_html += '</div>';
		_html += '</div>';
		$("#cells").append(_html)
		
	});
	$('<div class="clear"></div>').appendTo($('#cells'));	
	
	setTimeout('unblock()',2000); //give the screen a second to load
	
	
}
function unblock(){
	//hide:loader. If user goes back to home make sure the 
	$('.blockScreen').css('filter','alpha(opacity=70)').fadeOut(1000, function(){
		if ($("#featured").css('display')=='none'){
			$("#featured").toggle(1000);
		}
		$(".cell").fadeIn(1000);
	});
}
//multidimension stateObjarray sorting functions
function compareUnkown(a, b){	return b.unknownRanking - a.unknownRanking;	}
function compareSpotTags(a, b){	return b.SpotTags - a.SpotTags;	} 
function compareTotals(a, b){	return b.clicks - a.clicks;	}
function compareAlphabetically(a,b) {
  if (a.stateName < b.stateName)
     return -1;
  if (a.stateName > b.stateName)
    return 1;
  return 0;
}
function compareParksAlphabetically(a,b) {
  if (a.parkName < b.parkName)
     return -1;
  if (a.parkName > b.parkName)
    return 1;
  return 0;
}



/*----------------------------------
	Executed From Bread Crumb to Reload the States Grid
----------------------------------*/
function backHome(){
	SetPageUrl('/alphabetically'); //set URL
	//set up the page template for states
	$('#region-container').toggle(1000);
	$('#unknown').fadeIn(1000);
	$('.sort-cta').html('sort states by:');
	//set the main sorting links
		$('#viewed').unbind('click');
		$('#popular').unbind('click');
		$('#alphabetically').unbind('click');
		$('#viewed').click(function() { Initiate_States('viewed'); return false; });
		$('#popular').click(function() { Initiate_States('popular'); return false; });
		$('#alphabetically').click(function() { Initiate_States('alphabetically'); return false; });
	//remoev breadcrumbs
	$('#secondary-controls').toggle(1000);
	$('.regionCheckboxes').attr('checked',true);
	//remove all state 
	$.each(parksObj.parks,function(i,item){
		$("#cell-park-"+i).fadeOut(1000, function(){
			//loader:show
			$('.blockScreen').css('filter','alpha(opacity=70)').fadeIn(1000);
			
			Initiate_States('alphabetically');
		});
	});
}

/*----------------------------------
	Featured Parks Callout on Right side of page
----------------------------------*/
function initiate_featured(){
	
	//ensure there are featured locations available
	
	featuredObj = $.shuffle(featuredObj);
	
	
	
	if (featuredObj.featured[0]!=undefined){
		var _header='<h2 style="background:transparent url(data/images/featured-locations-h2.gif) top left no-repeat;">Featured Locations</h2>';
		$("#featured").css('display','none');
		$("#featured").html(_header);
		
		var _html='';
		currentFeatured=0;
		
		
		_html+='<a href="detail.aspx#/'+unknown(featuredObj.featured[0].state)+'/'+unknown(featuredObj.featured[0].parkId)+'/'+unknown(featuredObj.featured[0].parkName)+'" id="featuredLink" style="border:none;"><img src="data/uploads/'+unknown(featuredObj.featured[0].thumbnail)+'" width="200" height="100" alt="Featured Location" id="featured-location-img"  style="border:none;" /></a>';
		_html+='<span id="park-title">'+unknown(featuredObj.featured[0].parkName)+'</span>';
		_html+='<span id="park-location">'+unknown(featuredObj.featured[0].state)+'</span>';
		_html+='<span id="tags"><!--tagged '+unknown(featuredObj.featured[0].SpotTags)+' times &middot; -->1 of '+featuredObj.featured.length+'</span>';//remove tag count from the listing (10.26 -CP)
			_html+='<div id="featured-controls">';
				_html+=determinefeaturedPaging();
			_html+='</div>';
		

		$("#featured").append(_html);
	}
}
function FeaturedPaging(ty){

	if (ty=="-"){
		currentFeatured--;
	}else if (ty==undefined){
	}else{
		currentFeatured++;
	}
	$("#featured-location-img").fadeOut(500,function(){
		//change content in the divs
		$('#featured-location-img').attr('src',"data/uploads/"+unknown(featuredObj.featured[currentFeatured].thumbnail));
		$('#featuredLink').attr('href','detail.aspx#/'+unknown(featuredObj.featured[currentFeatured].state)+'/'+unknown(featuredObj.featured[currentFeatured].parkId)+'/'+unknown(featuredObj.featured[currentFeatured].parkName));
		$('#park-title').html(unknown(featuredObj.featured[currentFeatured].parkName));
		$('#park-location').html('Fort Smith, '+unknown(featuredObj.featured[currentFeatured].state));
		//remove tag count from the listing (10.26 -CP)
		//$('#tags').html('tagged '+unknown(featuredObj.featured[currentFeatured].SpotTags)+' times &middot; '+(currentFeatured+1)+' of '+featuredObj.featured.length);
		$('#tags').html((currentFeatured+1)+' of '+featuredObj.featured.length);
		$('#featured-controls').html(determinefeaturedPaging());
		$("#featured-location-img").fadeIn(500)
	
	});
	
	
}
function determinefeaturedPaging(){
	var _html='';
	if (currentFeatured>0){ //show previous
		_html+='<img src="data/images/left-small.gif" width="16" height="16" alt="prev" onclick="javascript:FeaturedPaging(\'-\');" /> '
	}
	if (currentFeatured<featuredObj.featured.length-1){ //next button
		_html+='<img src="data/images/right-small.gif" width="16" height="16" alt="next" onclick="javascript:FeaturedPaging(\'+\');" />'
	}
	return _html
}


/*----------------------------------
	Create Interest List Checkboxes
----------------------------------*/
function initiate_interestListboxes(){
	var _html='';
	$.each(interestListObj.interests,function(i,item){
		_html+='<li><input type="checkbox" name="int-cb-'+i+'" id="int-cb-'+i+'" class="checkbox interestCheckboxes"  onclick="javascript:changeInterest('+item.interestId+','+i+');" checked/><label for="int-cb-'+i+'">'+unknown(item.interestName)+'</label></li>';
		if (i==1 || i==3 || i==5 || i==7 || i==9 || i==11 || i==13 || i==15 || i==17 || i==19){
			_html+='<div style="clear:both;"></div>';
		}
	});
	$("#interest-list").html(_html);
}
/*----------------------------------
	Create Region List Checkboxes
----------------------------------*/
function initiate_regionListboxes(){
	var _html='';
	$.each(regionListObj.regions,function(i,item){
		_html+='<li><input type="checkbox" name="reg-cb-'+i+'" id="reg-cb-'+i+'" class="checkbox regionCheckboxes" onclick="javascript:changeRegion('+item.regionId+','+i+');" checked/><label for="reg-cb-'+i+'">'+unknown(item.regionName)+'</label></li>';
	});
	$("#region-list").html(_html);
}

/*----------------------------------
	Change Region checkbox call
----------------------------------*/
function changeRegion(regionId,regionIndex){

	var _action;
	if ($('#reg-cb-'+regionIndex).attr('checked')==true){	_action="add";	}else{	_action="rem";	}

	//determine if the regionId matches regions displayed and readjust the markup
	$.each(stateObjarr,function(i,item){
		if (item.regionId==regionId){
			if (_action=="rem"){
				$("#cell-"+i).fadeOut(1000);
			}else if(_action=="add"){
				//before displaying this state, ensure that there isn't an interest associated with it that is deactivated.
				//----------------------------------------------------------------
				
				
				var _current_state_interests=StateInterestFunction(i,item); //obtain an array of the states interests
				if (_current_state_interests=="," || _current_state_interests==",,"){ //no interests are assigned to a states parks (at all)
					if ($("#cell-"+i).css('display')!="block"){	$("#cell-"+i).fadeIn(2000);	} //show item if not already displayed
				}
				//loop through the state array to see if the interest boxes are checked. (checked: show, unchecked: don't show
				$.each(interestListObj.interests,function(y,interestItem){ //loop through entire interest list
					if ($('#int-cb-'+y).attr('checked')==true){
						for (var x=0;x<=_current_state_interests.length-1;x++){ //compare the state interest list to what is checked (based on entire interest list)
							if (_current_state_interests[x]==interestItem.interestId){ //show the item because it is checked. Otherwise it isn't needed because it isn't checked.
								if ($("#cell-"+i).css('display')!="block"){	$("#cell-"+i).fadeIn(2000);	} //show item if not already displayed
							}
						}
					}
				});	
			}
		}
	});
}
/*----------------------------------
	Change Interest checkbox call
----------------------------------*/
function changeInterest(interestId,interestIndex){
	var _action;
	if ($('#int-cb-'+interestIndex).attr('checked')==true){	_action="add";	}else{	_action="rem";	}
	
	//-----
	// FUNCITON SERVES STATE GRID SORTING AND PARKS SORTING.
	//-----
	if ($("#region-container").css('display')=="block"){	//load State Grid sorting
		
		//Each state has an entire list of interests assigned to it. It is comma delimited. Add all of them to an array and then remove duplicates.
		$.each(stateObjarr,function(i,item){
			var _current_state_interests=StateInterestFunction(i,item);
			
			if(_action=="add"){
				var _addFlag=0;
				//loop through the state array to see if the item appears in it.
				for (var x=0;x<=_current_state_interests.length-1;x++){
					if (_current_state_interests[x]==interestId){
						_addFlag++;
					}
				}
				if (_addFlag>0){ //show the state if it isn't part of an unselected region.
					$.each(regionListObj.regions,function(y,regionItem){
						if ($('#reg-cb-'+y).attr('checked')==true && stateObjarr[i].regionId==regionItem.regionId){
							if ($("#cell-"+i).css('display')!="block"){ //show item if not already available
								$("#cell-"+i).fadeIn(2000);
							}
						}
					});
				}
			}
			
			if(_action=="rem"){ //make sure all interest items for this state are removed. If they are, then it is ok to remove the state.
				var _removeFlag=0;
				$.each(interestListObj.interests,function(y,interestItem){
					for (var x=0;x<=_current_state_interests.length-1;x++){ //NOTE: IF A STATE DOESN'T HAVE ANY PARKS WITH INTERESTS ASSOCIATED IT WILL IMMEDIATELY BE REMOVED.
						if ($('#int-cb-'+y).attr('checked')==true && _current_state_interests[x]==interestItem.interestId){
							_removeFlag++;
						}
					}
				});
				if (_removeFlag==0){$("#cell-"+i).fadeOut(1000);}//no items associated with the state are checked. Remove item
			}
		});
	
	}else{	//load the parks sorting
		
		
		$.each(parksObj.parks,function(i,item){
			
			var _current_park_interests=ParksInterestFunction(i,item);
			
			if(_action=="add"){
				var _addFlag=0;
				//loop through the park array to see if the item appears in it.
				for (var x=0;x<=_current_park_interests.length-1;x++){
					if (_current_park_interests[x]==interestId){
						_addFlag++;
					}
				}
				if (_addFlag>0){ // the interest is located within the park
					if ($("#cell-park-"+i).css('display')!="block"){ //show item if not already available
						$("#cell-park-"+i).fadeIn(2000);
					}
				}
			}
			
			if(_action=="rem"){ 
			
				//loop through the interest list assigned to the park. Compare to checked boxes. only remove the park if all associated items are unchecked.
				var _removeFlag=0;
				var _proceeedWithRemoval=0;
				
				for (var x=0;x<=_current_park_interests.length-1;x++){
					if (_current_park_interests[x]==interestId){ //this park has the requested interest
						_proceeedWithRemoval=1;
					}
				}
				
				if (_proceeedWithRemoval==1){
					//loop through all interests assigned to the park and make sure all checkboxes are removed.
					$.each(interestListObj.interests,function(y,interestItem){
						for (var x=0;x<=_current_park_interests.length-1;x++){
							if ($('#int-cb-'+y).attr('checked')==true && _current_park_interests[x]==interestItem.interestId){
								_removeFlag++;
							}
						}
					});
					if (_removeFlag==0){$("#cell-park-"+i).fadeOut(1000);}//no items associated with the park are checked. Remove item
				}
			}
		});
	}
}
function ParksInterestFunction(i,item){
	var _current_park_interests=new Array();
	if (item.interestList.indexOf(",")>0 && item.interestList!=undefined){
		_current_park_interests=item.interestList.split(",");
		_current_park_interests=_current_park_interests.unique(); //remove duplicate items if they exist
	}else{
		_current_park_interests[0]=item.interestList;
	}
	return _current_park_interests
}
function StateInterestFunction(i,item){
	if (_current_state_interests=="," || _current_state_interests==",,"){
		return "";
	}
	
	var _current_state_interests=new Array();
	if (item.stateInterests.indexOf(",")>-1 && item.stateInterests!=undefined){
		_current_state_interests=item.stateInterests.split(",");
		_current_state_interests=_current_state_interests.unique(); //remove duplicate items if they exist
	}else{
		_current_state_interests[0]=item.stateInterests;
	}
	
	for (var i=0; i<_current_state_interests.length-1;i++){
		if (_current_state_interests[i]==','){
			_current_state_interests[i]='';
		}
	}
	return _current_state_interests
}



/*----------------------------------
	State Park Loading And Sorting
----------------------------------*/
function loadParks(stateId,_sortType){
	
	//remove the region list box. Regions don't matter since we are now in a state
	$('#region-container').toggle(1000, function(){
	
		//loader:show
		$('.blockScreen').css('filter','alpha(opacity=70)').fadeIn(1000);
		$('.blockScreen').css('height',$(document).height()+'px');
		
		
		$('.regionCheckboxes').attr('checked',true); //recheck all of the region boxes for the future when a person backs out of the park list.
	
		//Increment the clicks for this state
		$.getJSON("json_interface.aspx?action=incrementState&stateId="+stateId, function() {});
			
		//Communicate with Webservice to obtain the parks within this state
		$.getJSON("json_interface.aspx?action=parkList&stateId="+stateId, function(json) {
			parksObj = json;
			
			if (_sortType==undefined){ //sort type only passed from deep linking
				//fade out all states.
				$.each(stateObjarr,function(i,item){
					$("#cell-"+i).fadeOut(1000);
					setTimeout('continueParkLoading()',1000);
					setTimeout('finishParkLoading(\'alphabetically\')',1100);
					
				});
			}else{ //load the page with the requested sorting.
				setTimeout('continueParkLoading()',1000);
				setTimeout('finishParkLoading(\''+_sortType+'\')',1100);
			}
			
		});
		
	});
}
var _currentState='';
function continueParkLoading(){

	//initialize page layout for the parks template.
	$('#unknown').fadeOut(1000);
	$('.sort-cta').html('sort parks by:');
	//set the main sorting links
	$('#viewed').unbind('click');
	$('#popular').unbind('click');
	$('#alphabetically').unbind('click');
	
	$('#viewed').click(function() { finishParkLoading('most_viewed'); return false; });
	$('#popular').click(function() { finishParkLoading('most_popular'); return false; });
	$('#alphabetically').click(function() { finishParkLoading('alphabetically'); return false; });
	
	//handle a situation if no parks are available for a state
	if (parksObj.parks[0]==undefined){
		return;
	}
	//set up the secondary nav (bread crumb)
	$('#selected_state').html(parksObj.parks[0].stateName);
	
	//change the attributes of the rel for the main sorting links
	var _state=parksObj.parks[0].stateName;
	if (_state.indexOf(" ")>0){
		_state=_state.split(" ").join("-")
	}
	_currentState=_state
	$('#viewed').attr('rel','address:/state/'+_state+'/most_viewed');
	$('#popular').attr('rel','address:/state/'+_state+'/most_popular');
	$('#alphabetically').attr('rel','address:/state/'+_state+'/alphabetically');
	SetPageUrl('/state/'+_state+'/alphabetically'); //default view
	
	
	
	
}

function finishParkLoading(_sortType){

	//$('.interestCheckboxes').attr('checked',true); //recheck all of the region boxes for the future when a person backs out of the park list.
	//clear out the active nav item
	$('#popular').removeClass('selected');
	$('#viewed').removeClass('selected');
	$('#alphabetically').removeClass('selected');
	
	if (_sortType==undefined){	_sortType="most_viewed";	} //default view for parks
	//sort the parks
	parksObjarr = eval(parksObj.parks); 
	switch (_sortType){
		case "most_viewed":
			$('#viewed').addClass('selected');
			parksObjarr.sort(compareTotals);
			SetPageUrl('/state/'+_currentState+'/most_viewed');
			break;
		case "alphabetically":
			$('#alphabetically').addClass('selected');
			parksObjarr.sort(compareParksAlphabetically);
			SetPageUrl('/state/'+_currentState+'/alphabetically');
			break;
		case "most_popular":
			$('#popular').addClass('selected');
			parksObjarr.sort(compareSpotTags);
			SetPageUrl('/state/'+_currentState+'/most_popular');
			break;
	}
	
	//add the callout spot to all results
	var spotCallout="<div id='spot-callout-container'><img src='data/images/spot-callout.gif' width='320' height='115' id='spot-callout' alt='Where\'s your spot?' /><div id='secondary-controls'><ul><li><a href='javascript:backHome();' id='all_states'>All States</a></li><li class='divider'></li><li class='deepLinkedItem'><a href='#/state/"+_currentState+"/' class='selected' id='selected_state' data='New Description Tag Item 1' rel='address:/most_popular'>"+_currentState.split('-').join(' ')+"</a></li></ul><div class='clear'></div></div></div>"
	$("#cells").html(spotCallout); //clear previous html
	
	$('#secondary-controls').toggle(1000);
	
	
	//load park items.
	$.each(parksObjarr,function(i,item){
		if (item!=undefined){
			var _html = '<div class="cell" id="cell-park-' + i + '" style="display:none;" onclick="javascript:parkDetail('+i+');">';
			var _thumb=item.thumbnail;
			var _image;
			if (_thumb==undefined || _thumb==""){
				_image="noimageavailable.jpg";
			}else{
				_image=_thumb;
			}
			_html += '<img src="data/uploads/'+unknown(_image)+'" width="164" height="120" alt="State" />';
			_html += '<span class="cell-title">'+unknown(item.parkName)+'</span>';
			_html += '<span class="cell-location-tag">&nbsp;</span>';
			_html += '<div class="cell-tags">';
			_html += '<span class="tag-number">'+unknown(item.SpotTags)+'</span>';
			_html += '</div>';
			_html += '</div>';
			$("#cells").append(_html)
		}
	});
	
	
	setTimeout('unblock()',1000);
	
}
function parkDetail(parkIndex){
		//increment click count
		var _result;
		$.getJSON("json_interface.aspx?action=incrementParks&parkName="+parksObj.parks[parkIndex].parkName+"&parkId="+parksObj.parks[parkIndex].parkId, function() {_result});
		
		//load detail page
		document.location="detail.aspx#/"+parksObj.parks[parkIndex].stateName+"/"+parksObj.parks[parkIndex].parkId+"/"+parksObj.parks[parkIndex].parkName;
		
}

/*----------------------------------
	Get Involved
----------------------------------*/
function getinvolved(){
	
	$.getJSON("json_interface.aspx?action=getinvolved", function(json) {
		var _html='';
		
		_html+='<div class="get-involved-col">';
				_html+='<h1>'+urldecode(json.involved[0].mainTitle)+'</h1>'
				_html+='<p>'+urldecode(json.involved[0].mainBody)+'<br /><br /><a href="'+urldecode(json.involved[0].volunteerLink)+'" target="_blank"><img src="data/images/adopt-btn.gif"  style="border:none;" /></a></p>';
        _html+='</div>';
		_html+='<div class="get-involved-col" id="completed-form">';
        	_html+='<h1>'+urldecode(json.involved[0].stayInformedTitle)+'</h1>';
            _html+='<p>'+urldecode(json.involved[0].stayInformedBody).split('[lbr]').join('<br />')+'</p>';
            _html+='<form name="newsletter-form" id="newsletter-form">';
            _html+='<fieldset>';
            	_html+='<input type="text" id="newsletter-name" name="newsletter-name" value="First Name"  onfocus="if(this.value == \'First Name\') this.value = \'\';" onblur="if(this.value == \'\') this.value = \'First Name\';" style="width:95px;" class="get-involved-text" />&nbsp;';
				_html+='<input type="text" id="last-name" name="last-name" value="Last Name"  onfocus="if(this.value == \'Last Name\') this.value = \'\';" onblur="if(this.value == \'\') this.value = \'Last Name\';" style="width:95px;" class="get-involved-text" />';
                _html+='<input type="text" id="newsletter-email" name="newsletter-email" value="Email" class="get-involved-text" onfocus="if(this.value == \'Email\') this.value = \'\';" onblur="if(this.value == \'\') this.value = \'Email\';" style="width:205px;" />';
				_html+='<input type="text" id="newsletter-zip" name="newsletter-zip" value="Zip Code" class="get-involved-text" onfocus="if(this.value == \'Zip Code\') this.value = \'\';" onblur="if(this.value == \'\') this.value = \'Zip Code\';" style="width:205px;margin-bottom:15px;" /><br />';
				_html+='<input type="button" id="get-involved-submit" value="SUBMIT" onclick="javascript:checkInformed();"/>';
            _html+='</fieldset>';
            _html+='</form>';
			_html+='<br /><p>'+urldecode(json.involved[0].donateBody).split('[lbr]').join('<br />')+'</p>';
        _html+='</div>';
    	_html+='<div class="get-involved-col" id="share-with-friends" style="display:none;">';
        	_html+='<h1>'+json.involved[0].volunterTitle+'</h1>';
            _html+='<p>'+urldecode(json.involved[0].volunteerBody).split('[lbr]').join('<br />')+'<br /><br /><img src="data/uploads/'+json.involved[0].shareThumbnail+'" class="download-thumb" /><a href="data/uploads/'+json.involved[0].shareDownload+'" target="_blank"><img src="data/images/download.gif" /></a></p>';
				
			_html+='<p>Share with your friends</p>';
            _html+='<p><a href="http://www.facebook.com/sharer.php?u='+window.location.toString()+'&title='+json.involved[0].shareFaceBookTitle+'" target="_blank"><img src="data/images/facebook-share.gif" /></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="http://www.twitthis.com/twit?url='+window.location.toString()+'&title='+json.involved[0].shareTwitterTitle+'" target="_blank"><img src="data/images/twitter-share.gif" /></a></p>';

		_html+='</div>';

		$('#get-involved').html(_html);
	});
	
}
function checkInformed(){
	if ($('#newsletter-name').val()=='First Name'){
		alert("Enter your first name");
		return;
	}
	
	if ($('#last-name').val()=='Last Name'){
		alert("Enter your last name");
		return;
	}
	
	if ($('#newsletter-email').val()=='Email'){
		alert("Enter your email address");
		return;
	}
	if (is_valid_email($('#newsletter-email').val())!=false){
		$.ajax({ type: "POST",
			url: "json_interface.aspx?action=form&username="+$('#newsletter-name').val()+"&last="+$('#last-name').val()+"&email="+$('#newsletter-email').val()+"&zip="+$('#newsletter-zip').val(),
			dataType: "json"
		})
		$('#newsletter-form').css('display','none');
		$('#completed-form').append('<h1 style="color:#8EAEDA">Thank you for your commitment to the National Parks.</h1>');
		$('#share-with-friends').css('display','block');
		
		
		return;
	}else{
		alert("Please enter a valid email address");
	}
	
}

/*----------------------------------
	Globally Reused Functions
----------------------------------*/
//Set url
function SetPageUrl(str) {
	$.address.value(str);
	googleTracker(str);
return false;
}

//check email
function is_valid_email(email){
	return /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email);
}


//ensure values are present
function unknown(str){	
	var ret = (str==undefined) ? "" : str;
	if (ret.indexOf("%27")>-1)	{	ret=ret.split("%27").join("'")	}
	return ret
}

//remove duplicates from arrays
Array.prototype.unique = function () {
	var r = new Array();
	o:for(var i = 0, n = this.length; i < n; i++){
		for(var x = 0, y = r.length; x < y; x++){
			if(r[x]==this[i]){
				continue o;
			}
		}
		r[r.length] = this[i];
	}
	return r;
}

/*----------------------------------
	Google Page Tracking
----------------------------------*/

function googleTracker(url)
{
	//alert("PageTracker: "+url);
	//pageTracker._trackPageview(url);
}
