var map;
var g_xCurrentMarker;

function dir_search() {
  var l_aFilters = new Array();
  var l_nFilterCount = $('#dir_filter input').length;

  var l_bAtLeastOneFilter = false;
  for(var i=1; i<=l_nFilterCount; i++){
      if($('#filter_'+i).is(':checked')){
          l_aFilters[i] = true;
          l_bAtLeastOneFilter = true;
      }else{
          l_aFilters[i] = false;
      }
  }

  if(l_bAtLeastOneFilter == false){
      alert("You must select at least one Type of Establishment to search for.");
      return false;
  }
  var l_sCity = $('#dir_city select').val();
  var l_sKeyword = $('#dir_keyword input').val();
  var l_nZip = $('#dir_zip input').val();
  var l_nDistance = $('#dir_distance select').val();
  getSearchListings(1, l_aFilters[1], l_aFilters[2], l_aFilters[3], l_aFilters[4], l_aFilters[5], l_aFilters[6], l_aFilters[7], l_aFilters[8], l_sCity, l_nZip, l_nDistance, l_sKeyword);
  return false;
}

$(document).ready(function(){ 	
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("dir_map"));
		map.setCenter(new GLatLng(37.4419, -122.1419), 15);
		//map.setUIToDefault();
		map.addControl(new GSmallZoomControl3D());
	}
	
	$('.letter_content').click(function(){
		$(this).addClass('dir_alphabet_selected').siblings().removeClass('dir_alphabet_selected');								
		var l_sLetter = $(this).html();
		getListings(1, l_sLetter);
	});
	
	$('#dir_view_all').click(function(){
		$(this).addClass('dir_alphabet_selected').siblings().removeClass('dir_alphabet_selected');
		getListings();
	});
	
	//collect search values and call getSearchListings on these values
	$('#dir_search').click(function(){
      return dir_search();
	});
	
	// Fetch all the listings by default
	getListings();
});

function assignClearPrintEmail(){ 
	$('#print_map').hover(
		function(){$(this).addClass('hover').children('a').addClass('hover');},
		function(){$(this).removeClass('hover').children('a').removeClass('hover');
	});
	$('#clear_map, #email_map').hover(
		function(){$(this).addClass('hover');},
		function(){$(this).removeClass('hover');
	});
	
	$('#clear_map').click(function(){
		myMapClear();							   
	});
	
	$('#email_map').click(function(){
		$(this).toggleClass('selected').next().slideToggle();							   
	});
	
	$('#email_map_popup .close_icon').click(function(){
		$(this).parent().slideUp().prev().removeClass('selected');
	});
	
	$('#send_mymap').click(function(){
		myMapSend();	
		return false;
	});
}


function plotOnMap(p_xPoint, p_sLetter, p_bMyMap){
	$.scrollTo("#site_container", { duration:500, onAfter:function () { 
		if(g_xCurrentMarker)
			map.removeOverlay(g_xCurrentMarker);
		if(p_bMyMap == true)
			l_nMarkerPath = "/image/map_markers/blue_marker"+p_sLetter+".png";	
		else
			l_nMarkerPath = "http://www.google.com/mapfiles/marker"+p_sLetter+".png";
		
		var l_xIcon = new GIcon();
		l_xIcon.image = l_nMarkerPath;
		l_xIcon.iconAnchor = new GPoint(6, 20);

		markerOptions = { icon:l_xIcon };
		
		l_xMarker = new GMarker(p_xPoint, markerOptions);
		g_xCurrentMarker = l_xMarker;
		
		map.panTo(p_xPoint); 
		map.addOverlay(l_xMarker);
		//alert(map.getZoom());
		
	} });
}


function showMyMap(p_nResultCount){
	l_axArgs = [];
	l_axArgs.data = "a=showMyMap&resultCount="+p_nResultCount;

	InterviewAjax.makeAjaxCall("/ajax/ajax.php", l_axArgs, onShowMyMapCallback);
}

function onShowMyMapCallback(p_sResult){
	$('#dir_listing_container').hide();
	$("#my_map_container").hide().html(p_sResult).fadeIn(200);
}

function showResults(){
	$('#my_map_container').hide();
	$("#dir_listing_container").fadeIn(200);
	$(".entry_viewmap").eq(0).children("a").trigger("click");
}

function showAllCategories(p_xMoreLink) {
	$(p_xMoreLink).hide().prev().children('span').show();
}

function getListingById(p_nId) {	
	l_axArgs = [];
	l_axArgs.data = "a=getListingById&id="+ p_nId;

	InterviewAjax.makeAjaxCall("/ajax/ajax.php", l_axArgs, onGetListingsCallback);
}

//retrieve all listings or those starting with a specified letter
function getListings(p_nPage, p_sLetter) {
	if(p_nPage == null)
		p_nPage = 1;
	if(p_sLetter == null)
		p_sLetter = '';
		
	l_axArgs = [];
	l_axArgs.data = "a=getListings&page="+ p_nPage +"&letter="+ p_sLetter;

	InterviewAjax.makeAjaxCall("/ajax/ajax.php", l_axArgs, onGetListingsCallback);
}

//retrieve listings using the search fields and search button
function getSearchListings(p_nPage, p_bAuctionHouse, p_bAntiquesShop, p_bFineArtGallery, p_bService, p_bMuseum, p_bPrivateDealer, p_bReproduction, p_bDesignShop, p_sCity, p_nZip, p_nDistance, p_sKeyword) {
	l_axArgs = [];
	l_axArgs.data = "a=getSearchListings&page="+ p_nPage +"&auctionHouse="+ p_bAuctionHouse +"&antiquesShop="+ p_bAntiquesShop + "&fineArtGallery=" + p_bFineArtGallery + "&service="+ p_bService +"&museum="+ p_bMuseum + "&privateDealer="+ p_bPrivateDealer + "&reproduction="+ p_bReproduction +"&designShop="+ p_bDesignShop +"&city="+ p_sCity +"&zip="+ p_nZip +"&distance="+ p_nDistance +"&keyword="+ p_sKeyword;

	InterviewAjax.makeAjaxCall("/ajax/ajax.php", l_axArgs, onGetListingsCallback);
}

function onGetListingsCallback (p_sResult) {
	$("#my_map_container").hide();
	$("#dir_listing_container").hide().html(p_sResult).fadeIn(200);
}


//functions for removing or adding to My Map
function myMapAdd(p_nId){
	l_axArgs = [];
	l_axArgs.data = "a=myMapAdd&id="+ p_nId;

	InterviewAjax.makeAjaxCall("/ajax/ajax.php", l_axArgs, onMyMapAddRemoveCallback);
}
function myMapRemove(p_nId){
	l_axArgs = [];
	l_axArgs.data = "a=myMapRemove&id="+ p_nId;

	InterviewAjax.makeAjaxCall("/ajax/ajax.php", l_axArgs, onMyMapAddRemoveCallback);
}
function myMapClear(){
	l_axArgs = [];
	l_axArgs.data = "a=myMapClear";

	InterviewAjax.makeAjaxCall("/ajax/ajax.php", l_axArgs, onMyMapAddRemoveCallback);
}
function onMyMapAddRemoveCallback(p_sResult){
	$("#return_div").html(p_sResult);
}



function myMapSend(){
	var l_sTo = $('#mymap_to').val();
	var l_sFrom = $('#mymap_from').val();
	var l_sMsg = $('#mymap_message').val();
	
	/* explode the comma-separated "To:" email addresses into an array of strings, 
	then remove any empty strings or strings of spaces from this array. finally,
	trim leading and trailing white space from the email addresses */
	var l_aToSplit = l_sTo.split(',');
	l_aToSplit = removeEmpties(l_aToSplit);
	for(var i in l_aToSplit){
		l_aToSplit[i] = trim(l_aToSplit[i]);
	}
	
	//validation and error output
	$('#mymap_errors').html('');
	errors = new Array();
	errors = validateMapEmailForm(l_aToSplit, l_sFrom);
	if(errors.length > 0)	{
		$('#mymap_errors').html(_xGlobal.printErrors(errors));					
		return;
	}
	
	if($('#mymap_cc').is(':checked'))
		l_aToSplit += ","+l_sFrom;
	
	l_axArgs = [];
	l_axArgs.data = "a=myMapSend&to="+ l_aToSplit +"&from="+ l_sFrom +"&msg="+ l_sMsg;

	InterviewAjax.makeAjaxCall("/ajax/ajax.php", l_axArgs, onMyMapSendCallback);
}

function onMyMapSendCallback(p_sResult){
	$("#return_div").html(p_sResult);
	resetForm('email_mymap_form');
}

/* validates a From address, and an array of email addresses */
function validateMapEmailForm(p_aTo, p_sFrom){
	r_asErrors = new Array();			
	
	/* if the array is empty, ask for a valid email address */
	if(p_aTo.length == 0)
		r_asErrors.push("Please enter a valid email address in the \"To\" field.");
	if(p_aTo.length > 10)
		r_asErrors.push("Please limit your email address entries in the \"To\" field to 10.");
	
	for(var i=0; i < p_aTo.length; i++){
		if(/^[_a-zaA-Z0-9-]+([.+_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+([.a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,4})$/.test(p_aTo[i]) == false){
			var l_sStripTagsString = p_aTo[i].replace(/(<([^>]+)>)/ig,""); //makes sure HTML tags are not output in error message
			r_asErrors.push("\""+l_sStripTagsString+"\" is not a valid email address.");
		}
	}

	if(/^[_a-zaA-Z0-9-]+([.+_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+([.a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,4})$/.test(p_sFrom) == false)
		r_asErrors.push("\"Your Email Address\" is in an invalid format.");
	
	return r_asErrors;
}


/* trims white space off of 
the ends of a string */
function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}

/* removes empty strings and strings 
consisting of spaces from a given array */
function removeEmpties(p_aStringArray){
	for(var i=0; i < p_aStringArray.length; i++){
		if(/^[\s]*$/.test(p_aStringArray[i]) == true || p_aStringArray[i] == ''){
			p_aStringArray.splice(i, 1);
			i--; //if match is spliced out, index needs to be adjusted to account for shift
		}
	}
	return p_aStringArray;
}


/* cure-all form reset. pass in 
form id, and form will be cleared */
function resetForm(p_xFormId){
	f = document.getElementById(p_xFormId);
	
	for(var i=0; i < f.elements.length; i++){
		if(f.elements[i].type == 'text' || f.elements[i].type == 'password' || f.elements[i].nodeName == 'TEXTAREA')
			f.elements[i].value = '';
		else if(f.elements[i].type == 'checkbox' || f.elements[i].type == 'radio')
			f.elements[i].checked = false;
		else if(f.elements[i].nodeName == 'SELECT')
			f.elements[i].selectedIndex = 0;
	}
}

