var facilities_list = new Array();
var filter_category='';
var filter_zipcode='';
var filter_borough='';
var filter_org='';
var categories_list=new Array();
//categories_list = ["After School Program","Business Solution Center","Child Health Clinic","Cultural Institution","DRIE Enrollment Center","EITC Assistance Center","Financial Education Site","Food provider","Food Stamp Center","Greenmarket","HomeBase Site","Hospital","Jail Release Services","Library","Medicare Drug Counseling","Pool","Quit Smoking Clinic","Recreation Center","Universal Pre-k","Workforce1 Career Center"];
var orgNameIndex=0;
var descriptionIndex=1;
var hoursIndex=2;
var phoneIndex=3;
var webAddressIndex=4;
var addressIndex=5;
var additionalAddressIndex=6;
var cityIndex=7;
var zipIndex=8;
var boroughIndex=9;
var facilityTypeIndex=10;
var resultsMessage='';
var boroughs_list=new Array();

var BoroughUrl = "/apps/311/LOV.htm?type=BoroughList";
$.getJSON_Synchronous(BoroughUrl,renderBoroughData);

function renderBoroughData(Data){
			boroughs_list = Data.Borough_List;
		} 

var CategoryUrl = "/apps/311/LOV.htm?type=categoryList";
$.getJSON_Synchronous(CategoryUrl,renderCategoryData);

function renderCategoryData(Data){
	     categories_list = Data.categories_list;
		} 


var aNames=new Array();

for(var i=0;i<facilities_list.length;i++){
	aNames[i]=facilities_list[i][orgNameIndex];
}

function categoriesContains(newEntry){
	for(var j=0;j<categories_list.length;j++){
		if(categories_list[j]==newEntry){
			return(true);
		}
	}
	return(false);
}
function filterCategory(){
	var theDropdown=document.getElementById('categories');
	var theCategory=theDropdown.options[theDropdown.selectedIndex].value;
	filter_category=theCategory;
}
function filterOrg(){
	//filter_org=theOrg;
	filter_org=document.getElementById("org").value;
}

function filterBorough(){
	var theDropdown=document.getElementById('boroughs');
	var theBorough=theDropdown.options[theDropdown.selectedIndex].value;
	filter_borough=theBorough;
}

function filterZipcode(){
	var theZipcode=document.getElementById('zipcode').value;
	filter_zipcode=theZipcode;
}
function checkZipcode(){
	var theZipcode=document.getElementById('zipcode').value;
	if(isNaN(theZipcode)){
		alert("The zipcode must be numeric only.");
		document.getElementById('zipcode').select();
	}else if(theZipcode.length!=5){
		if(theZipcode.length!=0){
			alert("The zipcode must be 5 digits.");
			document.getElementById('zipcode').select();
		}
	}
}

function writeDropdowns(){
   
  /* 	var Url = "http://geo-dev-1.nycnet/doitt/ff/json/311/otw/find.htm?meta_type=HHS&limit=50000";
	// In order to load data synchronously call custom method getJSON_Synchronous
	$.getJSON_Synchronous(Url, renderDataDropdowns);
	*/
	renderDataDropdowns(null);
}

function renderDataDropdowns(data){

	/*for(var i=0;i<data.facilities.length;i++){
		if(!categoriesContains(data.facilities[i].type)){
			categories_list[categories_list.length]=data.facilities[i].type;
		}
	}
	categories_list=categories_list.sort();*/
	
	document.write('<table cellspacing="0" cellpadding="0" border="0" width="627">');
	document.write('<tr><Td colspan="2"><img src="/apps/311/img/spacer.gif" width="600" height="14" /></td></tr>');
	document.write('<form onsubmit="writeResults();return(false);"><tr><td align="right" nowrap class="search_label" width="223">Category:</td>');
	document.write('<td class="search_field" width="385"><select name="categories" id="categories" style="width:385px;"><option value=""> - Select - </option>');
	for(var i=0;i<categories_list.length;i++){
		document.write('<option value="'+categories_list[i].category+'">'+categories_list[i].category+'</option>');		
	}
	document.write('</select></td></tr>');
	document.write('<tr><Td colspan="2"><img src="/apps/311/img/spacer.gif" width="600" height="3" /></td></tr>');
	document.write('<tr><td align="right" nowrap class="search_label" width="223">Borough:</td>');
	document.write('<td class="search_field" width="385"><select name="boroughs" id="boroughs" onchange="setZip(this.options[this.selectedIndex].value)"><option value=""> - Select - </option>');
	for(var i=0;i<boroughs_list.length;i++){
		document.write('<option value="'+boroughs_list[i].Borough+'">'+boroughs_list[i].Borough+'</option>');
	}
	document.write('</select></td></tr>');
	document.write('<tr><Td colspan="2"><img src="/apps/311/img/spacer.gif" width="600" height="3" /></td></tr>');
	document.write('<tr><td align="right" nowrap class="search_label" width="223" id="zipLabel">ZIP code:</td>');
	document.write('<td class="search_field" width="385"><input type="text" class="textbox" name="zipcode" id="zipcode" style="width:60px;" onblur=checkZipcode(); onfocus="this.select()"></td></tr>');
	document.write('<tr><Td colspan="2"><img src="/apps/311/img/or.gif" width="627" height="30" alt="or" /></td></tr>');
	document.write('<tr><td align="right" nowrap class="search_label" width="223">Organization Name:</td>');
	document.write('<td class="search_field" width="385"><input type="text" class="textbox" name="org" id="org" style="width:385px;" onfocus="this.select()"></td></tr>');
	document.write('<tr><Td colspan="2"><img src="/apps/311/img/spacer.gif" width="600" height="7" /></td></tr>');
	document.write('<tr><td colspan="2" class="buttons"><input type="button" class="button" value="Find Providers" style="width:129px;" onClick="writeResults()"> ');
	document.write('<input type="reset" class="button" value="Reset" style="width:62px;" onclick="clearResults()"></td></tr>');
	document.write('<tr><td colspan="2"><img src="/apps/311/img/spacer.gif" width="600" height="14" border="0" alt=""></td></tr></form>');
	document.write('</table>');
}
function clearResults(){
	document.getElementById("resultsRow").style.display="none";
	document.getElementById("resultsSpan").innerHTML="";
	if(document.getElementById("results_info")!=null){
		document.getElementById("results_info").innerHTML="";
	}
	if(document.getElementById("errMsg")!=null){
		document.getElementById("errMsg").innerHTML="";
	}
	filter_category='';
	filter_zipcode='';
	filter_borough='';
	filter_org='';
	setZip("");
	document.getElementById('topLinks').innerHTML="&nbsp;";
	document.getElementById('num_results').innerHTML="&nbsp;";
	document.getElementById('bottomLinks').innerHTML="&nbsp;";
	document.getElementById('num_results_bottom').innerHTML="&nbsp;";
}
function setZip(theValue){
	if(theValue.length==0){
		document.getElementById('zipcode').disabled=false;
		document.getElementById('zipLabel').className="search_label"
	}else{
		document.getElementById('zipcode').value='';
		document.getElementById('zipcode').disabled=true;
		document.getElementById('zipLabel').className="search_label_disabled"
	}	
}
function clearNonOrg(){
	if(document.getElementById('org').value.length>0){
		document.getElementById('boroughs').selectedIndex=0;
		document.getElementById('categories').selectedIndex=0;
		document.getElementById('zipcode').value='';
		setZip("");
	}
}
function clearFields(){
	document.getElementById('boroughs').selectedIndex=0;
	document.getElementById('categories').selectedIndex=0;
	document.getElementById('zipcode').value='';
	document.getElementById('org').value='';
	setZip("");
}
function isValid(theIndex){
	var valid=true;
	if(filter_org.length>0){
		//valid=valid&&getOrg(theIndex).toLowerCase()==filter_org.toLowerCase();
		if ((getOrg(theIndex).toLowerCase()).indexOf(filter_org.toLowerCase()) != -1) {
			valid=valid&&true;
		} else {
			valid=valid&&false;	
		}
	}else{
		if(filter_zipcode.length>0){
			valid=valid&&getZipcode(theIndex)==filter_zipcode;
		}
		if(filter_category.length>0){
			valid=valid&&getCategory(theIndex)==filter_category;
		}
		if(filter_borough.length>0){
			if(filter_borough=="Manhattan"){
				valid=valid&&(getBorough(theIndex).indexOf(filter_borough)>-1||getBorough(theIndex).indexOf("New York")>-1);
			}else{
				valid=valid&&getBorough(theIndex).indexOf(filter_borough)>-1;
			}
		}
	}
	return(valid);
}
function writeResults(){
	clearResults();
	document.getElementById("resultsRow").style.display="";
	document.getElementById("results_header").innerHTML='<span class="red_bold">Searching...</span>';
	document.getElementById("dividerTop").style.display="none";
	document.getElementById("dividerBottom").style.display="none";
	setTimeout(writeResultsText,10);
}
function writeResultsText(){
	filterCategory();
	filterOrg();
	filterBorough();
	filterZipcode();
	clearFields();
	 resultsMessage='';
	  var URLParams='';
	if(filter_category.length==0&&filter_org.length==0&&filter_zipcode.length==0&&filter_borough.length==0){
		document.getElementById("results_header").innerHTML='<span id="results_info"></span>';
		document.getElementById("results_info").innerHTML='Please enter search terms above';
		document.getElementById("dividerTop").style.display="none";
		document.getElementById("dividerBottom").style.display="none";
		return;
	}else{
		if(filter_org.length>0){
			resultsMessage=resultsMessage+filter_org;
			URLParams = URLParams + "&name="+filter_org;
		}else if(filter_category.length>0){
			resultsMessage=resultsMessage+filter_category;
			URLParams = URLParams + "&type="+filter_category;
			
			if(filter_zipcode.length>0){
				resultsMessage=resultsMessage+', '+filter_zipcode;
				URLParams = URLParams + "&zip_code="+filter_zipcode;
			}else if(filter_borough.length>0){
				resultsMessage=resultsMessage+', '+filter_borough;
				URLParams = URLParams + "&borough="+filter_borough;
			}
		}else if(filter_zipcode.length>0){
			resultsMessage=resultsMessage+filter_zipcode;
			URLParams = URLParams + "&zip_code="+filter_zipcode;
		}else if(filter_borough.length>0){
			resultsMessage=resultsMessage+filter_borough;
			URLParams = URLParams + "&borough="+filter_borough;
		}else{
			resultsMessage='Displaying all results';
		}
	}
    itemCount=0;
	
	var longUrl = "/apps/311/facilityFinder.htm?meta_type=HHS"+URLParams;
	//$.getJSON(longUrl,renderData);	
	$.ajax({
		url:longUrl,
		dataType:'json',
		success:renderData,
		error:renderDataError
		});
}

function getCategory(theIndex){
	return(facilities_list[theIndex][facilityTypeIndex]);
}
function getAddress(theIndex){
	var theAddress="";
	if(facilities_list[theIndex][addressIndex].length>0&&facilities_list[theIndex][addressIndex]!="N/A"){
		theAddress=theAddress+facilities_list[theIndex][addressIndex]+"<br>";
	}
	if(facilities_list[theIndex][additionalAddressIndex].length>0&&facilities_list[theIndex][additionalAddressIndex]!="N/A"){
		theAddress=theAddress+facilities_list[theIndex][additionalAddressIndex]+"<br>";
	}
	if(facilities_list[theIndex][cityIndex].length>0){
		var theCity=convertCase(facilities_list[theIndex][cityIndex]);
		theAddress=theAddress+" "+theCity+", NY";
	}
	if(facilities_list[theIndex][zipIndex].length>0){
		theAddress=theAddress+" "+facilities_list[theIndex][zipIndex];
	}
	return(theAddress);
}
function convertCase(theText){
	var returnText="";
	var theSplit=theText.split(" ");
	for(var i=0;i<theSplit.length;i++){
		returnText=returnText+theSplit[i].charAt(0).toUpperCase()+theSplit[i].substr(1).toLowerCase();
		if(i<theSplit.length-1){
			returnText=returnText+" ";
		}
	}
	return(returnText);
}
function getOrg(theIndex){
	return(facilities_list[theIndex][orgNameIndex]);
}
function getWeb(theIndex){
	return(facilities_list[theIndex][webAddressIndex]);
}
function getZipcode(theIndex){
	return(facilities_list[theIndex][zipIndex]);
}
function getPhone(theIndex){
	return(facilities_list[theIndex][phoneIndex]);
}
function getDisplayedHours(theIndex){
	var theHours=facilities_list[theIndex][hoursIndex];
	theHours=theHours.replace(/, |,/g,"<br>");
	return(theHours);
}
function getBorough(theIndex){
	return(convertCase(facilities_list[theIndex][boroughIndex]));
}
function getDescription(theIndex){
	return(facilities_list[theIndex][descriptionIndex]);
}

function checkType(type){
	var typeUppercase = type.toUpperCase(); 
	var flag =new Boolean(false); 

	if(typeUppercase=='POOL' || typeUppercase=='BEACH' || typeUppercase=='PARK'){
	   flag = true;
	}
    
   return flag;
}

function renderData(data){
	var spans=new Array();
	var theString='<table cellspacing="0" cellpadding="0" border="0" width="650">';
	for(var i=0;i<data.facilities.length;i++){
	
			theString=theString+'<tr id="inactive_top'+itemCount+'"><td class="inactive_entry_top"><a href="javascript:showEntry('+itemCount+')" class="title_link">'+data.facilities[i].name+'</a>';
			
		 if((data.facilities[i].type!=undefined && data.facilities[i].type.length>0) && checkType(data.facilities[i].type)==true){
			 if(data.facilities[i].address2!=undefined && data.facilities[i].address2.length>0 && data.facilities[i].address2!='N/A'){
					theString=theString+'<br>'+data.facilities[i].address2;
				}			
			} else {
				if(data.facilities[i].address!=undefined && data.facilities[i].address.length>0 && data.facilities[i].address!='N/A'){
					theString=theString+'<br>'+data.facilities[i].address;
				}else if(data.facilities[i].address2!=undefined && data.facilities[i].address2.length>0 && data.facilities[i].address2!='N/A'){
					theString=theString+'<br>'+data.facilities[i].address2;
				}
			}
			
			
			if(data.facilities[i].city!=undefined && data.facilities[i].city.length>0){
				theString=theString+'<br>'+data.facilities[i].city;
			}
			if((data.facilities[i].state!=undefined && data.facilities[i].state.length>0) || (data.facilities[i].zip_code!=undefined && data.facilities[i].zip_code.length>0)){
			    theString=theString+', ';
			}
			
			if(data.facilities[i].state!=undefined && data.facilities[i].state.length>0){
				theString=theString+data.facilities[i].state;
			}			
			if(data.facilities[i].zip_code!=undefined && data.facilities[i].zip_code.length>0){
				theString=theString+' '+data.facilities[i].zip_code;
			}
			
			if(data.facilities[i].phone!=undefined && data.facilities[i].phone.length>0){
				theString=theString+'<br>'+data.facilities[i].phone;
			}
			theString=theString+'</td></tr>';
			theString=theString+'<tr id="active_top'+itemCount+'"><td class="active_entry_top"><a href="javascript:hideEntry('+itemCount+')" class="title_link_active">'+data.facilities[i].name+'</a>';
			
		 if((data.facilities[i].type!=undefined && data.facilities[i].type.length>0) && checkType(data.facilities[i].type)==true){
			 if(data.facilities[i].address2!=undefined && data.facilities[i].address2.length>0 && data.facilities[i].address2!='N/A'){
					theString=theString+'<br>'+data.facilities[i].address2;
				}			
			} else {
				if(data.facilities[i].address!=undefined && data.facilities[i].address.length>0 && data.facilities[i].address!='N/A'){
					theString=theString+'<br>'+data.facilities[i].address;
				}else if(data.facilities[i].address2!=undefined && data.facilities[i].address2.length>0 && data.facilities[i].address2!='N/A'){
					theString=theString+'<br>'+data.facilities[i].address2;
				}
			}
			
			if(data.facilities[i].city!=undefined && data.facilities[i].city.length>0){
				theString=theString+'<br>'+data.facilities[i].city;
			}
			
			if((data.facilities[i].state!=undefined && data.facilities[i].state.length>0) || (data.facilities[i].zip_code!=undefined && data.facilities[i].zip_code.length>0)){
			    theString=theString+', ';
			}
			
			if(data.facilities[i].state!=undefined && data.facilities[i].state.length>0){
				theString=theString+data.facilities[i].state;
			}			
			if(data.facilities[i].zip_code!=undefined && data.facilities[i].zip_code.length>0){
				theString=theString+' '+data.facilities[i].zip_code;
			}
			
			if(data.facilities[i].phone!=undefined && data.facilities[i].phone.length>0){
				theString=theString+'<br>'+data.facilities[i].phone;
			}
			theString=theString+'</td></tr>';
			theString=theString+'<tr id="active_bottom'+itemCount+'"><td class="active_entry_bottom">';
			if(data.facilities[i].description.length>0){
				theString=theString+'<b><i>Description:</i></b><br>'+data.facilities[i].description;
			}
			
			 if(data.facilities[i].cross_street_one!=undefined && data.facilities[i].cross_street_one!='N/A' && data.facilities[i].cross_street_one.length>0 && data.facilities[i].cross_street_two!=undefined && data.facilities[i].cross_street_two.length>0 && data.facilities[i].cross_street_two!='N/A'){
				theString=theString+'<br><b><i>Cross Streets:</i></b><br>'+data.facilities[i].cross_street_one+', '+data.facilities[i].cross_street_two;
			}else if(data.facilities[i].cross_street_one!=undefined && data.facilities[i].cross_street_one!='N/A' && data.facilities[i].cross_street_one.length>0){
				theString=theString+'<br><b><i>Cross Street:</i></b><br>'+data.facilities[i].cross_street_one;
			}else if(data.facilities[i].cross_street_two!=undefined && data.facilities[i].cross_street_two!='N/A' && data.facilities[i].cross_street_two.length>0){
				theString=theString+'<br><b><i>Cross Street:</i></b><br>'+data.facilities[i].cross_street_two;
			}	

            if(data.facilities[i].hours_of_operation!=undefined && data.facilities[i].hours_of_operation.length>0){
				theString=theString+'<br><b><i>Hours Of Operation:</i></b><br>'+data.facilities[i].hours_of_operation;
			}			
			
			if(data.facilities[i].age_restriction!=undefined && data.facilities[i].age_restriction.length>0){
				theString=theString+'<br><b><i>Age Restriction:</i></b><br>'+data.facilities[i].age_restriction;
			}	
			
			if(data.facilities[i].url!=undefined&&data.facilities[i].url.length>0&&data.facilities[i].description.length>0){
				theString=theString+'<br><br>';
			}
			
			if(data.facilities[i].url!=undefined && data.facilities[i].url.length>0){
				theString=theString+'<b>For More Information:</b><br><a href="'+data.facilities[i].url+'">Visit the Web site</a>';
			}
			theString=theString+'</td></tr>';
			itemCount++;
			if(itemCount%resultsPerPage==0){
				theString=theString+'</table>';
				spans[spans.length]=theString;
				theString='<table cellspacing="0" cellpadding="0" border="0" width="650">';
			}
			
		}
	
	if(theString.length>63&&theString.substring(theString.length-8)!="</table>"){
		theString=theString+'</table>';
		spans[spans.length]=theString;
	}
	
	document.getElementById("results_header").innerHTML='<b>Search Results for:</b> <span id="results_info"></span>';
	document.getElementById("dividerTop").style.display="";
	document.getElementById("dividerBottom").style.display="";
	document.getElementById("results_info").innerHTML=resultsMessage;
	theSpans = spans;
	if(theSpans.length==0){
		resultsMessage=resultsMessage+'<br><br><span class="red">No results found</span>';
		document.getElementById("results_info").innerHTML=resultsMessage;
		document.getElementById("dividerTop").style.display="none";
		document.getElementById("dividerBottom").style.display="none";
	}else{
		showPage(0);
	}
	//return(spans);
}

function showEntry(theEntry){
	hideAll();
	var theId="inactive_top"+theEntry;
	document.getElementById(theId).style.display="none";
	theId="active_top"+theEntry;
	document.getElementById(theId).style.display="";
	theId="active_bottom"+theEntry
	document.getElementById(theId).style.display="";
}
function hideEntry(theEntry){
	var theId="inactive_top"+theEntry;
	document.getElementById(theId).style.display="";
	theId="active_top"+theEntry;
	document.getElementById(theId).style.display="none";
	theId="active_bottom"+theEntry
	document.getElementById(theId).style.display="none";
}

function showPage(thePage){
	currentPage=parseInt(thePage);
	var endPage=0;
	if(currentPage*resultsPerPage+resultsPerPage > itemCount){
		endPage = itemCount;
	} else{
	   endPage = currentPage*resultsPerPage+resultsPerPage;
	}	
	var numResultsText="Displaying "+(currentPage*resultsPerPage+1)+"-"+(endPage)+" of "+itemCount;
	document.getElementById('num_results').innerHTML=numResultsText;
	document.getElementById('num_results_bottom').innerHTML=numResultsText;
	document.getElementById('resultsSpan').innerHTML=theSpans[thePage];
	hideAll();
	var prevLink="";
	if(thePage>0){
		prevLink="<a href='javascript:showPage("+(thePage-1)+")'>Previous</a> | ";
	}
	var pageLinks=getPageLinks(thePage);
	var nextLink="";
	if(thePage<theSpans.length-1){
		nextLink=" | <a href='javascript:showPage("+(thePage+1)+")'>Next</a>";
	}
	document.getElementById('topLinks').innerHTML=prevLink+pageLinks+nextLink;
	document.getElementById('bottomLinks').innerHTML=prevLink+pageLinks+nextLink;
}
function renderDataError() {
           $("#errMsg").html("</br><p class='red'>Due to some technical difficulties, we could not process your search at this time. Please try again later.</p>");		
		   document.getElementById("results_header").innerHTML='<span class="red_bold"></span>';
			
    }
