jQuery.noConflict();

deeplocal.dg = {};
  
var createPlaceMap = null;
var geocoder = null;
var catId = 4014;
var searchString = "";
var searchData = null;
var areWeSearching = false;
var lastTotal = 0;
var maxCount = 0;
var lastSearch = "";
var currentPage = 0;
var currentTotal = 0;
var currentShown = 0;
var loading = false;
var waitingFor = 0;
var recenterClick = null;

deeplocal.dg.subcategories = new Array();
deeplocal.dg.categorylist = new Array();
deeplocal.dg.fullcategorylist = new Array();
deeplocal.dg.categoryIcons = new Array();



var tag_array = new Array();

redrawMapHandler = function(overlay, point) {
					deeplocal.gumband.markerMgr.refresh();
					getAllPlaces();
				}

jQuery(window).load(function(){
deeplocal.gumband.customerId = 500;

if (GBrowserIsCompatible()) {
	var myMap = document.getElementById("create_place_map");

		createPlaceMap = new GMap2(myMap);


	createPlaceMap.setCenter(new GLatLng(40.441590790335276, -80.01153945922852), 14);		
	createPlaceMap.addControl(new GSmallMapControl());
	geocoder = new GClientGeocoder();

	deeplocal.gumband.markerMgr = new MarkerManager(createPlaceMap, {trackMarkers:true});	
		
	GEvent.addListener(createPlaceMap, "dragstart", function() {
	  createPlaceMap.closeInfoWindow();
	});

	GEvent.addListener(createPlaceMap, 'dragend', redrawMapHandler );
}

		   
	jQuery('#map_options input').click( function(){
		getAllPlaces();
	});

	//This function will populate the category lists AND it will build the div objects for searching.
	
	deeplocal.gumband.getAllCategories(catId, false, buildCatList);


	//Set Handler to repopulate sub categories..
	jQuery('#parent_category').change(function(){		
			deeplocal.dg.populateSubCatList();
	});

	//Make sure sub categories are populated.
	deeplocal.dg.populateSubCatList();
	
	
	/* Re-set the Form Submit functions */
	
	jQuery('#dg_search_form').submit(function(){
				searchGuide();	
				return false;
			});
			
	jQuery('#map_options_form').submit(function(){
			getAllPlaces();		
			return false;
	});
	
	
	jQuery('#move_map_form').submit(function(){
	
			moveMapToAddressSubmit();
			return false;
	
	});
	
			
});

function moveMapToAddressSubmit(){
	
	var myAddress = jQuery("#move_map_input").attr("value");
	
	moveMapToAddress(myAddress);
	getAllPlaces();
	//return false;
}

function moveMapToAddress(address){
		
      if (geocoder) {
        geocoder.getLatLng(address, function(point) {
											if (!point) {
											  alert(address + " not found");
											} else {
											  createPlaceMap.setCenter(point, 13);
											}
										  });
      }
    }

deeplocal.dg.buildCategoryLists = function(data){
	
	var parent_category = jQuery('#parent_category').get(0);
	parent_category.options[parent_category.options.length] = new Option("All Categories", "Category");
	if(data.length > 0){
			
		jQuery.each(data, function(i,item){
			
			parent_category.options[parent_category.options.length] = new Option(item.name, item.id);
			
			deeplocal.dg.fullcategorylist[""+item.id] = item.name;
			deeplocal.dg.categoryIcons[""+item.id] = item.icon;
			
	 	    deeplocal.gumband.getAllCategories( item.id, false, deeplocal.dg.addSubTypes);			
			deeplocal.dg.categorylist[''+item.id] = deeplocal.dg.subcategories;
					
		});
	}
}


deeplocal.dg.addSubTypes = function(data){
				
	var subcategories = new Array();
	var childOf = 0;
	if(data.length > 0 ){
	
		jQuery.each(data, function(i,item){
		 subcategories[''+item.id] = item.name;
		 deeplocal.dg.fullcategorylist[''+item.id] = item.name;
		 deeplocal.dg.categoryIcons[''+item.id] = item.icon;
		 childOf = item.childOf;  
		   
		});
		deeplocal.dg.categorylist[''+childOf] = subcategories;
	}
}


deeplocal.dg.populateSubCatList = function(){

	var parent_category_id = jQuery('#parent_category').val();
	var sub_cat_list = jQuery('#category_input').get(0);
	
	sub_cat_list.options.length=0;
	sub_cat_list.options[sub_cat_list.length] = new Option("All Types", "Type");

	 sub_list = deeplocal.dg.categorylist[parent_category_id+''];				
			for(i in sub_list){
				if(typeof sub_list[i] != "function"){
					sub_cat_list.options[sub_cat_list.length] = new Option(sub_list[i], i);										
				}
			}
			
	if(sub_cat_list.length > 1){
		sub_cat_list.selectedIndex=1;			
	}
}
	

buildCatList = function(data){
	
	deeplocal.dg.buildCategoryLists(data);
	
	var catDisplay = jQuery('#map_options').get(0);
	if(data.length > 0){
		jQuery.each(data, function(i,item){
			var diningOption = "dining_option_"+item.id;	
			var catItemList = "<input class='top_cat_checkbox' type='checkbox' id='" + 
								diningOption + "' name='" + diningOption +"' value="+item.id+" />";
			
			catItemList = catItemList +	"<label for='"+diningOption+"'><img src='"+item.icon+"'>" + item.name + "</label>";
				
			var	newItem = document.createElement("div");
			
			newItem.className= 'select_category_item';
			newItem.innerHTML = catItemList;
			deeplocal.dg.fullcategorylist[""+item.id] = item.name;
			deeplocal.dg.categoryIcons[""+item.id] = item.icon;
			catDisplay.appendChild(newItem);
		});
	}
	
	jQuery('.select_category_item input').click( function(){
		areWeSearching=false;		
		resetSearchForm('dg_search_form');
		getAllPlaces();
		}
	);
}

   
deeplocal.gumband.createMarker = function(posn, title, desc, icon) {
	var pointIcon = new GIcon(G_DEFAULT_ICON);
	if(typeof icon == "undefined") icon = "/includes/2007design/images/blank.png";		
	pointIcon.image = icon;
	pointIcon.iconSize = new GSize(24,24);
	pointIcon.shadowSize = new GSize(1,1);
	pointIcon.iconAnchor = new GPoint(-12,12);
	pointIcon.infoWindowAnchor = new GPoint(16, 13);
					
	var marker = new GMarker(posn, {title: title, icon: pointIcon, draggable:false });

	deeplocal.gumband.markerMgr.addMarker(marker, 3);
	return marker;
}


getAllPlaces = function(action){
	if(action == 'next') {
		++currentPage;
		if(currentPage >= maxCount){ --currentPage; return;}
	}

	if(action == 'previous') {
		--currentPage;
		if(currentPage < 0){ ++currentPage; return;}
	}

	/* Remove the current List
		Then iterate through the check boxes up top... if they're checked... show em!" */
	
	if(deeplocal.gumband.markerMgr.getMarkerCount(createPlaceMap.getZoom()) > 0){
		  deeplocal.gumband.markerMgr.refresh();
	}
	
	if(areWeSearching != true){		
		jQuery('#place_list .place_list_block').remove();
			  
		if(deeplocal.gumband.markerMgr.getMarkerCount(createPlaceMap.getZoom()) > 0){
			  deeplocal.gumband.markerMgr.clearMarkers();
			  deeplocal.gumband.markerMgr.refresh();
		}
					
		var lati = createPlaceMap.getCenter().lat();
		var longi = createPlaceMap.getCenter().lng();
		
		var myTopCategories = jQuery('.top_cat_checkbox');
		//going to search, reset the total counter

		if(!action){
			currentTotal = 0;
			currentPage = 0;
			currentShown = 0;
			maxCount = 0;
			lastTotal = 0;
			jQuery('#moreLink').click(function(){if(!loading && waitingFor == 0) getAllPlaces('next');});
			jQuery('#previousLink').click(function(){if(!loading && waitingFor == 0)getAllPlaces('previous');});
			jQuery.each(myTopCategories, function(i,item){
				if(item.checked){
					deeplocal.gumband.getNumEntitiesInCategory(item.value, undefined, lati, longi, undefined, undefined, setTotal);
					pageAll(item.value, lati, longi);
				}
			});
		} else {
		
			jQuery.each(myTopCategories, function(i,item){
				if(item.checked){
					pageAll(item.value, lati, longi);
				}
			});
		
		}
	} //End Are we searching if.
}

function setTotal(data){
	currentTotal = currentTotal + data;
	maxCount = Math.ceil(currentTotal / 25);	
}

function adjustVisibleCount(data){
	jQuery('#place_search_results').get(0).innerHTML = currentTotal + " Places Found.";
	lastTotal = currentShown;
}

function getCategory(catId){
	return deeplocal.dg.fullcategorylist[""+catId];
}

function parseEntities(data){

	waitingFor = data.length;
	if(waitingFor == 0){
		setLoading(false);
	}

	if(data.length > 0){
		
		jQuery.each(data, function(i,item){
			//console.dir(item);
			var	myCategory = getCategory(item.categoryId);
			
			var myPlaceCatTarget = "#place_cat_type_"+item.placeId;
						
		
		if(jQuery(myPlaceCatTarget).get(0)){
				var myCatDesc =  jQuery(myPlaceCatTarget).get(0);
				myCatDesc.innerHTML =  myCategory;
			}else{
				
				tag_array[item.id]= item.tags;
				
		var reviewUrl = "";
		
		if((typeof tag_array[item.id][0].ppg_review_url != "undefined") && tag_array[item.id][0].ppg_review_url != null && tag_array[item.id][0].ppg_review_url !=""){
			reviewUrl = "<div style='font-size:11px; clear:both;padding-top:5px; padding-bottom:5px;'>Post-Gazette Review: <a href='" + tag_array[item.id][0].review_url + "'>click here</a></div>";
		}
		
		
		var starContent = "<div style='font-size:11px; clear:both;padding-top:5px; padding-bottom:5px;'>";

		if((typeof tag_array[item.id][0].currentRating != "undefined") && tag_array[item.id][0].currentRating != null && tag_array[item.id][0].currentRating !="" )	{
			var currentRating = 0;
			currentRating = parseInt(tag_array[item.id][0].currentRating);
			

			for(var m = 0; m < 5; m++){
				
				if(m < currentRating){
					starContent += "<div class='star'><\/div> ";
				} else {
					starContent += "<div class='star star_off'><\/div> ";
				}
			
			}
			
		} else {
			for(var m = 0; m < 5; m++){
				starContent += "<div class='star star_off'><\/div> ";
			
			}
		}
		
		starContent += "<\/div>";
		
		
					var listContent = "<div class='place_list_block'>"+
					"<div class='place_cat_type' id='place_cat_type_" + item.id + "' title='"+item.categoryId+"'>"+ 
					myCategory + "<\/div>"+
					"<div class='place_title_list' id='place_title_list_"+item.id+"'>"+
					"<a>" + item.name + "</a><\/div>" + 
						"<div style='display: none;' id='place_entity_"+ item.id +"'>"+ 
							item.id +"<\/div>" +
						"<div class='place_phone_number' id='place_phone_number_"+ item.id +"' style='display:none;'>"+ item.tags[0].phone + "<\/div>"+
						"<div class='place_address_list' id='place_address_list_" + item.id + "'><\/div>" +
						"<div class='place_description_list' id='place_description_list_" + item.id + "'><\/div>"+
						starContent + reviewUrl +"<div class='dg_detail_link' style='clear:left;'><a href='/diningguide/dg_detail.asp?entId="+ item.id + "'>More &raquo;</a><\/div><\/div>";

						jQuery('#place_list').append(listContent);
				currentShown++;
			}				
			//deeplocal.gumband.getPlace(item.placeId, parsePlaces);
			
			parsePlaces(item.place, item.id);
			
		 });
	}
	adjustVisibleCount(0);

}

function setLoading(isLoading){
	loading = isLoading;
	if(loading){
		jQuery('#place_search_results').get(0).innerHTML ="Loading.";
		jQuery(".top_cat_checkbox").attr('disabled','disabled');
	} else {
		jQuery(".top_cat_checkbox").removeAttr("disabled");
	}
}

function parsePlaces(data, entityId){

		var title = data.name;

		var posn = new GLatLng(data.latitude, data.longitude);
		var catid = jQuery("#place_cat_type_" + entityId).attr("title");
		var marker = deeplocal.gumband.createMarker(posn,title, data.description, deeplocal.dg.categoryIcons[catid]);
		
		var myCategory = deeplocal.dg.fullcategorylist[catid];
										
		var myTitleList = "#place_title_list_" + entityId;
		var myAddressList = "#place_address_list_"+entityId;
		var myDescriptionList = "#place_description_list_"+entityId;
		var myEntity = '#place_entity_'+entityId;
		
		var myTitle  = jQuery(myTitleList).get(0);
		var myAddress = jQuery(myAddressList).get(0);	
		var myDescription = jQuery(myDescriptionList).get(0);			

		


		//WHY DO I HAVE TO CALL [0] ???
		//This doesn't make sense. I'm setting an array of objects... whatev
				
		var phoneNumber = tag_array[entityId][0].phone;
		
		var ppg_rating 	= tag_array[entityId][0].ppg_review_rating;
		var price 		= tag_array[entityId][0].price;
		var windowContent = "<div class='place_cat_type'>"+ myCategory + "</div>";
		
		windowContent += "<div class='place_title_list' style=''>" + myTitle.innerHTML +
							 "<\/div> ";


		/*
		JLF 20080916 - Removed from popups; descriptions are too long.
		if(data.description != null && data.description !="" )	{
			windowContent += "<div class='place_description_popup'>" + 
							data.description + "</div>";
		
		
		}
		*/
		windowContent +="<div class='place_address_list'>";
					
		if(data.address1 != null){ windowContent+= data.address1 + "<br /> "; }
		if(data.address2 != null && data.address2 !="null"){ windowContent+= data.address2 + "<br /> "; }
		if(data.city != null){ windowContent+= data.city + ", "; }
		if(data.state != null){ windowContent+= data.state + ", "; }
		if(data.zip != null){ windowContent+= data.zip ; }
					
		windowContent +="<\/div>";



		windowContent += "<div style='clear:both; height:16px;padding-top:5px;padding-bottom:5px;'>";

		if((typeof tag_array[entityId][0].currentRating != "undefined") && tag_array[entityId][0].currentRating != null && tag_array[entityId][0].currentRating !="" )	{
			var currentRating = 0;
			currentRating = parseInt(tag_array[entityId][0].currentRating);
			

			for(var m = 0; m < 5; m++){
				
				if(m < currentRating){
					windowContent += "<div class='star'><\/div> ";
				} else {
					windowContent += "<div class='star star_off'><\/div> ";
				}
			
			}
			
		} else {
			for(var m = 0; m < 5; m++){
				windowContent += "<div class='star star_off'><\/div> ";
			
			}
		}
		
		windowContent += "<\/div>";
		
		if(phoneNumber != null && phoneNumber != ""){					
			windowContent +="<div class='place_phone_popup'>" + phoneNumber + "</div>";
			}
			
		   windowContent +="<div class='dg_detail_link'><a href='/diningguide/dg_detail.asp?entId="+ entityId+"'>More &raquo;</a></div>";
					
		if(myDescription)myDescription.innerHTML = data.description;
		var add2 = "";
		if(data.address2 != null && data.address2 !="null") add2 = data.address2;
		myAddress.innerHTML = data.address1 + " " 
					+ add2 + " " + data.city + ", " + data.state + " " + data.zip;
		
		//

		marker.bindInfoWindowHtml(windowContent);
				
				jQuery("#place_title_list_"+entityId).click(function(){
					createPlaceMap.setCenter(posn);
					clickedMarker = marker;
					doHiddenMarkerClick();
				});
		
		//remove the array item, so we can make things clean 
		tag_array.splice(entityId,0);
		waitingFor--;
		if(waitingFor == 0){
			setLoading(false);
		}
}


var clickedMarker = undefined; 

function doHiddenMarkerClick(){
	if(!clickedMarker.isHidden()){
		GEvent.trigger(clickedMarker, 'click');
		clickedMarker = undefined;
		if(recenterClick){
			clearInterval(recenterClick);
			recenterClick = undefined;
		}
	} else {
		if(!recenterClick){
			recenterClick = setInterval("doHiddenMarkerClick()", 500);	
		}
	}
}



function searchGuide(action){
	areWeSearching = true;			
	searchData = null;
	/*clear out any checklists */
	var myTopCategories = jQuery('.top_cat_checkbox');
	resetSearchForm('map_options_form');
	
	if(action == 'next') {
		++currentPage;
		if(currentPage >= maxCount){ --currentPage; return;}
	}

	if(action == 'previous') {
		--currentPage;
		if(currentPage < 0){ ++currentPage; return;}
	}
	
	try{	
	
		var PriceInput			= 			jQuery('#searchByPrice_input').get(0);
		var ParentCategoryInput =			jQuery('#parent_category').get(0);
		var ChildCategoryInput 	=			jQuery('#category_input').get(0);
		var RatingInput   		= 			jQuery('#searchByRating_input').get(0);
		var LocationInput 		=           jQuery('#searchByLocation_input').get(0);
		var search_by_txt 		= 			jQuery('#search_by_txt').get(0).value;
		
		var myPriceInput = PriceInput.options[PriceInput.selectedIndex].value;
		var myParentCategoryInput = ParentCategoryInput.options[ParentCategoryInput.selectedIndex].value;
		var myChildCategoryInput = ChildCategoryInput.options[ChildCategoryInput.selectedIndex].value;
		var myRatingInput        = RatingInput.options[RatingInput.selectedIndex].value;
		var myLocationInput		 = LocationInput.options[LocationInput.selectedIndex].value;
							
		var myTags = "";
		var myTagValues = "";
		var query = "&";
	
		if(search_by_txt != null && search_by_txt !="" && search_by_txt !="enter search terms"){
				query = query+"search="+search_by_txt+"&";
		}
		
		if ( myPriceInput !='Price' || myRatingInput != 'Rating' || myLocationInput !='Location'){	
					
				if(myPriceInput != "Price"){
					
						if(myTags.length > 0){
						
							myTags = myTags + "|price";
							myTagValues = myTagValues + "|"+ myPriceInput;
						}else{
							myTags =  "price";
							myValues = myPriceInput;
						}
				}
				
				if(myRatingInput != "Rating"){
					if(myTags.length > 0){
						myTags = myTags + "|ppg_review_rating";
						myValues = myValues + "|"+ myRatingInput;
					}else{
						myTags = "ppg_review_rating";
						myValues = myRatingInput;
					}	
				}
	
				if(myLocationInput !="Location"){
						if(myTags.length > 0){
								myTags = myTags + "|location";
								myValues = myValues + "|" + myLocationInput;
						}else{									
								myTags = "location";
								myValues = myLocationInput;				
						}
				}			
			query = query + "tags="+myTags+"&values="+myValues+"&";
		}
	
		var categorySearchId = 4014;
		
		if(myParentCategoryInput != "Category" && myChildCategoryInput == "Type"){
				query = query+"catId="+myParentCategoryInput+"&";
		
		} else if( myParentCategoryInput !="Category" && myChildCategoryInput !="Type"){
				query = query+"catId="+myChildCategoryInput+"&";
		}else{
				query = query+"categoryList="+categorySearchId+"&";
		}
		
		searchString = deeplocal.gumband.endpoint+ "items?customer=500&full=true&action=find" + query;

		jQuery('#moreLink').click(function(){if(!loading && waitingFor == 0)searchGuide('next');})
		jQuery('#previousLink').click(function(){if(!loading && waitingFor == 0)searchGuide('previous');})

		if(!action){
			currentTotal = 0;
			currentPage = 0;
			currentShown = 0;
			maxCount = 0;
			lastTotal = 0;
			getNumSearchResults(searchString);
			pageSearch(searchString);
		} else {
			pageSearch(searchString);
		}
	}catch(e){
	}	
}

function pageAll(value, lati, longi){
	var currentStart = currentPage * 25;
	//going to search, reset the total counter
	deeplocal.gumband.returnEntitiesInCategory(value, undefined, lati, longi, currentStart, 25,true, parseEntities);
	setLoading(true);
}


function pageSearch(searchString){

	if(typeof searchString == "undefined"){
		searchString = lastSearch;
	} else {
		lastSearch = searchString;		
	}
	var currentStart = currentPage * 25;

	searchString += "startIndex=" + currentStart + "&getCount=" + 25;
	//going to search, reset the total counter
	currentTotal = 0;

	getSearchResults(searchString);
}

function getSearchResults(search_string){
	/* Clear the list in the bottom */
	jQuery('#place_list .place_list_block').remove();
	
	/* Refresh the map */
			
	if(deeplocal.gumband.markerMgr.getMarkerCount(createPlaceMap.getZoom()) > 0){
		  deeplocal.gumband.markerMgr.clearMarkers();
		  deeplocal.gumband.markerMgr.refresh();
	}
	jQuery.getJSON(search_string + "&jsoncallback=?", searchEntities);	
	setLoading(true);

}

function getNumSearchResults(search_string){
	jQuery.getJSON(search_string + "&format=count&jsoncallback=?", setTotal);	
}

function searchEntities(data){
	searchData = data;
	parseEntities(data);
}		

function clickclear(thisfield, defaulttext) {
	if (thisfield.value == defaulttext) {
		thisfield.value = "";
	}
}

function clickrecall(thisfield, defaulttext) {
	if (thisfield.value == "") {
		thisfield.value = defaulttext;
	}
}

function resetSearchForm(str){	
	var dg_search_form = jQuery('#'+str).get(0);
	dg_search_form.reset();
}