// From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
var emailRegEx = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;
 
var baseSearchUrl = "http://api.donorschoose.org/common/json_feed.html?APIKey=I98eM0hy&teacherType=5&showFacetCounts=true";
var searchOptions = new Array();
var displayPages = 8;
var pageSize = 10;
var navAction;
var popStart = 0;
var prevHash = undefined;
var pageTitles = new Array();
var errorMessages = new Array();
var displayingSynopsis = false;
var hashChangeEnabled = true;
var mapClosed = true;
var ajaxLoaderOpen = false;

var votePrvntDblSubmit = false;

var lastProjectId = null;

var currentPage = 0;
var totalPages = 0;

var cfId = -1;
var clId = -1;

function thankyouPageComplete(pageNum)
{
	if(pageNum == null)
		pageNum = 0;
		
    // Create pagination element with options
    $("#pagination").pagination(photos.length, {
        callback: thankyouPageCallback,
        items_per_page: 30,
        first_page_items: 15,
        next_text: 'Next',
        prev_text: 'Prev',
        next_show_always: false,
        prev_show_always: false,
        current_page: pageNum
    });
    
    if(photos.length <= 15)
    	totalPages = 1;
    else
    	totalPages = 1 + Math.ceil((photos.length - 15) / 30);
    
    thankyouPageCallback(pageNum,null);   
}

function thankyouPageCallback(page_index, jq)
{
	// update the global currentPage
	currentPage = page_index;
	
    // Get number of elements per pagination page:
    var items_per_page = 30;
    
    var min_elem = page_index * items_per_page - 15 + 1;
    var max_elem = Math.min((page_index+1) * items_per_page - 15, photos.length);
        
    var newcontent = '<ul>';
    
    // only display 15 thumbs on the first page (so that we can display the larger image):
    if(page_index == 0)
    {
        min_elem = 1;
        max_elem = Math.min(15, photos.length);
        newcontent = '<a href="'+featuredPhoto[1]+'" onclick="return false;"><img src="'+featuredPhoto[0]+'" alt=""/></a><br/><ul>';
    }    
    
    var pagerText = "Thank You's " + min_elem + "-" + max_elem + " of " + photos.length;
    
    // Iterate through a selection of the content and build an HTML string        
    for(var i=Math.max(page_index*items_per_page-15,0);i<max_elem;i++)
    {
        newcontent += '<li><a href="' + photos[i][1] + '" onclick="return false;"><img src="'+photos[i][0]+'" alt=""/></a></li>';
    }
    
    newcontent += '</ul>';
    
    // Replace old content with new content
    $('#gallery').html(newcontent);
    
    $('#pagerText').html(pagerText);
    
    $('#gallery a').lightBox({
    	hideEmbed: false,
        imageLoading: 'images/photos/lightbox-ico-loading.gif',
        imageBlank: 'images/photos/lightbox-blank.gif',
        imageBtnClose: 'images/photos/closeBtn.gif',
        imageBtnNext: 'images/photos/nextBtn.gif',
        imageBtnPrev: 'images/photos/prevBtn.gif',
        containerBorderSize: 0,
        displayCaption: false,
        clickCallback: galleryClick,
        alwaysDisplayFirstLast: true
    });
    // Prevent click eventpropagation
    return false;
}

function clickFirstGalleryImage()
{
	$('#gallery a :first').click();
	clearInterval(cfId);
	
	closeAjaxLoader();
}

function clickLastGalleryImage()
{
	$('#gallery a :last').click();
	clearInterval(clId);
	
	closeAjaxLoader();
}

/*
 * Callback function from lightbox. 
 * Direction value options:
 *  next - when the next navigational button is clicked
 *  prev - when the previous navigational button is clicked
 *  open - when a lightbox is opened
 */
function galleryClick(direction, firstOrLast)
{
	switch(direction)
	{
		case "next":
			if(firstOrLast)
			{
				openAjaxLoader();
			
				$('#lightbox-secNav-btnClose').click();
				
				// on the last page, go to the first:
				if(currentPage == totalPages - 1)
					thankyouPageComplete(0);
				// otherwise go to the next page:
				else
					thankyouPageComplete(currentPage+1);
					
				$.scrollTo(0);
				
				// wait 500 ms then click the first gallery image:		
				cfId = setInterval(clickFirstGalleryImage, 500);
				
			}
		break;
		
		case "prev":
			if(firstOrLast)
			{
				openAjaxLoader();
			
				$('#lightbox-secNav-btnClose').click();
				
				// on the first page and we have more than one page, go to the last:
				if(currentPage == 0 && currentPage != totalPages-1)
					thankyouPageComplete(totalPages-1);
				// otherwise go to the previous page:
				else
					thankyouPageComplete(currentPage-1);
				
				$.scrollTo(0);
				
				// wait 500 ms then click the last gallery image:		
				clId = setInterval(clickLastGalleryImage, 500);
			}
		break;
		
		default:
	}
	return false;
}

function enableVoting()
{
    // we're not allowing voting anymore:
    votePrvntDblSubmit = false;
    //votePrvntDblSubmit = true;
}

function disableVoting()
{
    votePrvntDblSubmit = false;
}

function loadPageTitles()
{
    pageTitles["#/howItWorks"] = "SONIC(R) Limeades for Learning(SM)"; 
    pageTitles["#/searchProjects"] = "SONIC(R) Limeades for Learning(SM) - Find A Project";
    pageTitles["#/toolbox"] = "SONIC(R) Limeades for Learning(SM); - Teacher Toolbox"; 
    pageTitles["#/blog"] = "SONIC(R) Limeades for Learning(SM) - What's New"; 
    pageTitles["#/favoriteProjects"] = "SONIC(R) Limeades for Learning(SM) - Favorite Projects"; 
    //pageTitles["#/mostPopularProjects"] = "SONIC(R) Limeades for Learning(SM) - Most Popular";
    pageTitles["#/fundedProjects"] = "SONIC(R) Limeades For Learning(SM) - Map";
    pageTitles["#/thankyou"] = "SONIC(R) Limeades For Learning(SM) - Thank You Notes";
}

function loadErrorMessages()
{
    errorMessages["errors.l4l.comment.explicit"] = "Explicit words have been detected in your comment.";
    errorMessages["errors.l4l.name.explicit"] = "Explicit words have been detected in your name.";
    errorMessages["default"] = "An error has occurred. Please check you entries and try again.";
}

// get metric cookie if exist else create it
var persistentId = getMetricCookie();
// Also see if they have a remember me cookie set
var signinEmail = getRememberMeCookie();
// See if they have seen the main flash movie

var favs = new Array();
var popular = new Array();
   
   function resetSearch()
   {
        searchOptions = new Array();
           
        $("#searchCriteriaList").empty();
        $(".expandableOptHeaderActive").removeClass("expandableOptHeaderActive");
           
        // state may have been selected prior to search reset, just in case  
        // remove display of any location (city,county,district) dialogs
        $(".locationJson").remove();
        // Re-show the state list dialog
        $(".stateListHeader").show();

        $(".expandableOptSubContent").hide('slow');
        $(".expandableOptContent").hide('slow');
           
        $("#keywords").val("");
   }
   
   function buildSearchUrl()
   {
       var searchUrl = baseSearchUrl;
       for(var i=0; i<searchOptions.length; i++)
       {
           if ( searchOptions[i] != null )
           {
               searchUrl += "&" + searchOptions[i].name + "=" + searchOptions[i].value;
           }
       }
       return searchUrl;
   }
   
   function addSearchOption(name, value)
   {
       searchOptions.push({"name":name,"value":value});
   }
   
   function getProjectById(id)
   {
       // alert("bar: " + id);
       searchUrl = baseSearchUrl + "&keywords=" + id;
       
       getSearchResults(searchUrl, true);     
   }
   
   function searchOptionExists(optionToCheck)
   {
       for(var i=0; i<searchOptions.length; i++)
       {
           if(searchOptions[i].name == optionToCheck)
               return true;
       }
       return false;
   }
   
   function displaySynopsis(projectId)
   {
           //retrieve the project only if the content hasn't been populated yet:
           var fullSynopsis = $("#fullSynopsis_"+projectId);
           if(fullSynopsis && (fullSynopsis.html() == null || fullSynopsis.html() == ""))
               getServerKeywordSearch(projectId,displaySynopsisCallback,false);
           
           //    getSingleProjectById(projectId,displaySynopsisCallback,false,"&showSynopsis=true");
           else(displaySynopsisCallback(null,projectId));
           
   }
   
   function displaySynopsisCallback(dcProject,projectId)
   {
           var fullSynopsis = null;
           if(dcProject)
           {
            var fullSynopsis = $("#fullSynopsis_"+dcProject.id);
            if(fullSynopsis)
            {
                if(dcProject.synopsis)
                    fullSynopsis.append(dcProject.synopsis);
                else
                    fullSynopsis.append("View full details at DonorsChoose.org");
                
                fullSynopsis.append("&nbsp;&nbsp;&nbsp;").append(
                               $("<span/>").attr("class","hideFullSynopsis")   
                               .append($("<strong/>").append("(Hide)")));     
            
            }
        }
        else if(projectId)
            fullSynopsis = $("#fullSynopsis_"+projectId);
            
        fullSynopsis.prev($(".shortDesc")).slideUp("fast");    
        fullSynopsis.slideDown("fast");                 
           $(".hideFullSynopsis").click(function(){ $(this).parent().slideUp("fast");  $(this).parent().prev($(".shortDesc")).slideDown("fast"); });

        displayingSynopsis = false;
   }
   
   function getServerKeywordSearch(id, callback, checkHistorical)
   {
           var found = false;
           var mySearchUrl = micrositeUrl + "mobile/wapKeywordSearch.do?format=json&keywords="+ id + "&historical="+checkHistorical;

           openAjaxLoader();
           $.ajax({
               type: "GET",
                      url: mySearchUrl,
                      dataType: "json",
                      success : function(dcResult) { 
                          var dcProject = null;
                          switch(dcResult.totalProposals)
                          {
                              case 0:
                               break;
                           default:
                               var proposals = dcResult.proposals;
                                  $.each(proposals, function(i, proposal)
                               {
                                if(proposal.id == id)
                                {
                                    dcProject = proposal;
                                    found = true;
                                }
                               });
                          }
                          if(found || checkHistorical == true)
                          {
                              closeAjaxLoader(); 
                              if(callback)
                              {
                                  // call the passed in callback function, passing
                                  // in the resulting donor's choose project:
                                  callback(dcProject);
                              }
                          }
                          else if(checkHistorical == false)
                          {
                              getServerKeywordSearch(id, callback, true);
                          }
                      },
                      error : function(xOption, status, thrownError) {
                          closeAjaxLoader();
                          logErrorMessage("getServerKeywordSearch","Error returned from jsonp ajax call. Status Text: " + xOption.statusText + " Method Info - id: "+id + " checkHistorical: " + checkHistorical);
                          alert("We're sorry. The system is having issues. Please try again later."); 
                      },
                      async: true
              });
   }
   
   function getSingleProjectById(id, callback, checkHistorical, additionalSearchCriteria)
   {
          var found = false;
          
          if(checkHistorical == null)
                  checkHistorical = false;

          searchUrl = baseSearchUrl + "&keywords=" + id + "&noIEcache=" + (new Date().getTime());
          
          if(additionalSearchCriteria)
                  searchUrl += additionalSearchCriteria;
                  
          if(checkHistorical == true)
                  searchUrl += "&historical=true";

          openAjaxLoader();
          try{
              $.ajax({
                      type: "GET",
                      url: searchUrl,
                      dataType: "jsonp",
                      success : function(dcResult) { 
                          var dcProject = null;
                          switch(dcResult.totalProposals)
                          {
                              case 0:
                               break;
                           default:
                               var proposals = dcResult.proposals;
                                  $.each(proposals, function(i, proposal)
                               {
                                if(proposal.id == id)
                                {
                                    dcProject = proposal;
                                    found = true;
                                }
                               });
                          }
                          if(found || checkHistorical == true)
                          {
                              closeAjaxLoader(); 
                              if(callback)
                              {
                                  // call the passed in callback function, passing
                                  // in the resulting donor's choose project:
                                  callback(dcProject);
                              }
                          }
                          else if(checkHistorical == false)
                              getSingleProjectById(id, callback, true);
                      },
                      error : function(xOption, status) {
                          closeAjaxLoader(); 
                          logErrorMessage("getSingleProjectById","Error returned from jsonp ajax call. Status Text: " + xOption.statusText + " Method Info - id: " + id + " checkHistorical: " + checkHistorical);
                          alert("We're sorry. The system is having issues. Please try again later."); 
                      },
                      async: true
              });
          }
          catch(err)
          {
                  closeAjaxLoader();
          }
   }
   function logErrorMessage(method, info)
   {
           if(info == null)
               info = "";
               
           if(method != null && method != "")
           {
            info = info + " Browser Info: " + navigator.userAgent + " " + navigator.appVersion;
               var postData = "fileName=sonic-cause.js&method="+method+"&info="+info+"&callback=jsonError";
               try
               {
                   $.ajax({
                          type: "POST",
                          url: errorAction,
                          dataType: "jsonp",
                          data: postData,
                          async: true,
                          success : function(eResult) { },
                          error : function(xOption, status) { }
                      });
                  } catch(err) { }
              }
   }
   
   function getCompletedProjects()
   {
       searchUrl = baseSearchUrl + "&historical=true";
       getSearchResults(searchUrl);
   }
   
   function getSearchResults(searchUrl, checkHistorical, showResultsTask, preTask, preTaskShortCircuit, postTask, showLoader)
   {
          if (checkHistorical == null) { checkHistorical = false; }
       if (showResultsTask == null) { showResultsTask = showSearchResults; }
       if (preTask == null) { preTask = noResults;}
       if (preTaskShortCircuit == null) { preTaskShortCircuit = showEmptyResults;}
       if (showLoader == null) { showLoader = true; }
    
//alert(searchUrl);
           
       if(showLoader)
               openAjaxLoader();
               
       try
       {
           $.ajax({
               type: "GET",
               url: searchUrl,
               dataType: "jsonp",
               success : function(dcResult) {
                   if(dcResult.totalProposals == 0 && checkHistorical == true)
                   {
                           //search again for already funded projects:
                           getSearchResults(searchUrl + "&historical=true", false, showResultsTask, preTask, preTaskShortCircuit, postTask, showLoader);
                   }
                   else
                   {
                        if (preTask) { if ( preTask(dcResult) == true ) { closeAjaxLoader(); return preTaskShortCircuit();  } } 
                        showResultsTask(dcResult);  closeAjaxLoader(); 
                        if (postTask) { postTask(dcResult); } 
                   }
                                               },
               error : function(xOption, status) {  
                       closeAjaxLoader(); 
                       logErrorMessage("getSearchResults","Error returned from jsonp ajax call. Status Text: " + xOption.statusText + " Method Info - searchUrl: " + searchUrl + " checkHistorical: " + checkHistorical);
                       alert("We're sorry. The system is having issues. Please try again later."); 
                   },
               async: true
           });    
       }
       catch(err)
       {
               logErrorMessage("getSearchResults","An exception was thrown on the parsing of " + escape(searchUrl) + ". Error: " + err.description);
               closeAjaxLoader();
       }
       return false;
   }
   
   function getPageResults(startIndex)
   {
       addSearchOption("index", startIndex);
       getSearchResults(buildSearchUrl());
       searchOptions.pop();
   }
   

   function showSearchResults(dcResult)
   {
       // Clear previous results
       $("#searchCriteriaList").empty();
       $("#pagerTop").empty();
       $("#searchResults").empty();
       $("#pagerBottom").empty();
       
       buildSearchTermsList();
       buildPagerRow(dcResult);
       buildSearchResults(dcResult.proposals);
       applyFacetCounts(dcResult.facetCounts);
       getSonicVotes(dcResult.proposals);
   }
   
   function showEmptyResults()
   {
       // Clear previous results
       $("#searchCriteriaList").empty();
       $("#pagerTop").empty();
       $("#searchResults").empty();
       $("#pagerBottom").empty();
       
       buildSearchTermsList();
       
       $("<tr/>").addClass("noResults")
               .append($("<td/>").attr("valign", "top")
                   .append($("<div/>").append("We couldn't find any projects that match your search. Make sure all keywords are spelled correctly and try entering fewer search terms.")).append($("<img/>").attr("src","images/spacer.gif").attr("alt","spacer").attr("width","1").attr("height","380")))
       .appendTo("#searchResults");
   }
   
   function getSonicVotes(proposals)
   { 
   /*
       //WE ARE DISABLING VOTING, NO NEED FOR RETRIEVING VOTE COUNTS:
       var idList = "idList=";
       $.each(proposals, function(i, proposal)
       {
             if ( i > 0 ) {idList += ",";}
             idList += proposal.id;
       });
     
       var voteCountUrl = actionPrefix + "voteCounts.do?" + idList + "&noIEcache=" + (new Date().getTime());
       
       //openAjaxLoader();
       $.ajax({
           type: "GET",
           url: voteCountUrl,
           dataType: "json",
           success : function(voteCountResult) { 
                           $.each(voteCountResult.projects, function(i, project)
                           {
                                 $("#votes"+project.id).empty().append(project.count);
                                 
                                 // if project.funded > 0 change vote to sonic funded button:
                                 if(project.funded > 0)
                                 {
                                     //alert("change " + project.id + " button to btn_sonicFunded.gif");
                                     changeToSonicFunded(project.id);
                                 }
                           });
                           //closeAjaxLoader(); 
                       },
           error : function(xOption, status) { 
                   //closeAjaxLoader(); 
                   logErrorMessage("getSonicVotes","Error returned from json ajax call. Status Text: " + xOption.statusText + " Method Info - voteCountUrl: " + voteCountUrl);
                   alert("We're sorry. The system is having issues. Please try again later."); 
               },
           async: true
       });    
   */
   }

   function applyFacetCounts(facetCounts)
   {
       // Remove previous facet counts.
       $(".facetCount").remove();
       
       // Build state, city, county, district facets
       if ( facetCounts.location != null )
       {
           var zones = facetCounts.location.zone;
           if ( zones != null )
           {
                  $(".zoneFacet").removeClass("greyed");
               $(".zoneFacet").each( function(i) {
                  if ( zones[this.innerHTML] != null) { $(this).append($("<span/>").attr("class","facetCount").html(" (" + zones[this.innerHTML] + ")")); }
                     else { $(this).addClass("greyed"); }
               });
           }
           
           var cities = facetCounts.location.city;
           if ( cities != null )
           {
                  $(".cityFacet").removeClass("greyed");
               $(".cityFacet").each( function(i) {
                  if ( cities[this.innerHTML] != null) { $(this).append($("<span/>").attr("class","facetCount").html(" (" + cities[this.innerHTML] + ")")); }
                     else { $(this).addClass("greyed"); }
               });
           }
           
           var communities = facetCounts.location.community;
           if ( communities != null )
           {
                  $(".communityFacet").removeClass("greyed");
               $(".communityFacet").each( function(i) {
                  if ( communities[this.innerHTML] != null) { $(this).append($("<span/>").attr("class","facetCount").html(" (" + communities[this.innerHTML] + ")")); }
                     else { $(this).addClass("greyed"); }
               });
           }
           
           var counties = facetCounts.location.county;
           if ( counties != null )
           {
                  $(".countyFacet").removeClass("greyed");
               $(".countyFacet").each( function(i) {
                  if ( counties[this.innerHTML] != null) { $(this).append($("<span/>").attr("class","facetCount").html(" (" + counties[this.innerHTML] + ")")); }
                     else { $(this).addClass("greyed"); }
               });
           }
           
           var districts = facetCounts.location.district;
           if ( districts != null )
           {
               $(".districtFacet").removeClass("greyed");
               $(".districtFacet").each( function(i) {
                  if ( districts[this.innerHTML] != null) { $(this).append($("<span/>").attr("class","facetCount").html(" (" + districts[this.innerHTML] + ")")); }
                     else { $(this).addClass("greyed"); }
               });
           }
       }
       
       var subjects = facetCounts.subject;
       if ( subjects != null )
       {
           // Flatten out subjects.  DC API returns object of subcategories for each subject category.  
           // We want the all at the same level to make the thing work.
           for( subject in subjects ) 
           { 
               if (typeof(subjects[subject]) == "object")
               {
                   for ( subsub in subjects[subject])
                   {
                       // alert(subsub + " = " + subjects[subject][subsub]);
                       subjects[subsub] = subjects[subject][subsub];
                   }
               }
           }

           $(".subjectFacet").each( function(i) {
              // replace encoded &amp; with just &, and get rid of any padded spacing characters:
              var subjectName = this.innerHTML.replace(/&amp;/i, "&").replace(/^\s+|\s+$/, '');

              // replace encoded &amp; with just & which comes over in the JSON
              if ( subjects[subjectName] != null) { 
                  if (typeof(subjects[subjectName]) != "object")
                  {
                      $(this).append($("<span/>").attr("class","facetCount").html(" (" + subjects[subjectName] + ")"));
                  }
              }
           });
       }
       
       var proposalTypes = facetCounts.proposalType;
       if ( proposalTypes != null )
       {
           $(".proposalFacet").each( function(i) {
                  if ( proposalTypes[this.innerHTML] != null) { $(this).append($("<span/>").attr("class","facetCount").html(" (" + proposalTypes[this.innerHTML] + ")")); }
           });
       }
       
       var gradeTypes = facetCounts.gradeType;
       if ( gradeTypes != null )
       {
           $(".gradeFacet").each( function(i) {
                  if ( gradeTypes[this.innerHTML] != null) { $(this).append($("<span/>").attr("class","facetCount").html(" (" + gradeTypes[this.innerHTML] + ")")); }
           });
       }
   }
   

   function buildSearchTermsList()
   {
       var searchTerms = "";
       if ( searchOptions.length == 0)
       {
           $("#searchCriteria").hide();
           $("#searchInfo").hide();
       }
       else
       {
           $("#searchCriteria").show();
           $("#searchInfo").show();
       }
       
       for(var i=0; i<searchOptions.length; i++)
       {
           var queryParam = searchOptions[i].name + "_" + searchOptions[i].value;
           //alert("Search Term Name for " + unescape(queryParam) + " = " + searchTermName(queryParam));
           $("#searchCriteriaList").append($("<li/>").append(searchTermName(queryParam)).append($("<a/>").attr("href","").attr("searchOptName", searchOptions[i].name).attr("searchOptVal", searchOptions[i].value).addClass("removeSearchFilter").attr("alt","Remove").attr("title","Remove").append("X")));                      

       }
       
       // Now that we've created the new removeSearchFilter links, bind the click handler to them.
       $(".removeSearchFilter").click( function() {
           if ( $(this).parent().hasClass("expandableOptSubHeader") || $(this).parents().hasClass("expandableOptSubContent") )
          {
              $('.expandableOptions .expandableOptSubHeader').next().hide("slow");
          }
          removeSearchFilter($(this).attr("searchOptName"), $(this).attr("searchOptVal"));
          return false;
       });
       $(".facetCount").remove();
   }
   
   var searchTermNames = new Array();
  
   function searchTermName(queryParam)
   {
       //alert(queryParam);
       if ( queryParam.substr(0,9) == "keywords_" )
           return "Keyword(s): " + unescape(queryParam.substring(9));
       else
           return searchTermNames[unescape(queryParam)];
   }
 
   
   function buildSearchResults(proposals)
   {        
           // alert("buildSearchResults");
         $.each(proposals, function(i, proposal)
         {
             var imageURL = proposal.imageURL;
            if(proposal.imageURL == null || proposal.imageURL == "")
                imageURL = "http://www.donorschoose.org/images/examples/default.gif";
                
            var teacherLabel = proposal.teacherName;
            if(proposal.imageURL == null || proposal.imageURL == "")
                teacherLabel = "";
            else
                teacherLabel += "'s Classroom";
                
            var schoolLabel = "";
            if(proposal.schoolName != null && proposal.schoolName != "")
            {
                schoolLabel = $("<span/>").attr("id","schoolName"+proposal.id).append(proposal.schoolName);
            }
               
            $("<tr/>").attr("id","sr" + i)
            .append(
               $("<td/>").attr("valign", "top")
               .append(
                   $("<div/>").attr("id","imageBlock" + i).attr("class","image")
                   .append(
                           $("<img/>").attr("alt", "").attr("src", imageURL).error(function(){ $(this).attr("src", "http://www.donorschoose.org/images/examples/default.gif");})
                    )
                    .append($("<br/>")).append($("<span/>").attr("id","teacherName"+proposal.id).append(teacherLabel)).append(schoolLabel)
                   //.append(
                   //    $("<div/>").attr("class", "votesCast").attr("align","left").attr("id","votesCast"+proposal.id).append("Sonic Votes Cast: ").append($("<span/>").attr("id","votes"+proposal.id).append("0"))
                   // )
               )
            )
            .append(
               $("<td/>").attr("id","projDescBlock" + i).attr("valign", "top")
               .append(
                   $("<div/>")
                   .append(
                       $("<h3/>")
                       .append(
                               $("<div/>").attr("id","resultTitle").append($("<a/>").attr("class","titleDCLink").attr("target","_NEW").attr("href", proposal.proposalURL).append(proposal.title))
                       )
                   )
                   .append(
                       $("<div/>").attr("class","desc")
                       .append(
                           $("<div/>").attr("class","shortDesc").attr("style","display:inline").append(proposal.shortDescription)
                           .append("&nbsp;&nbsp;&nbsp;").append(
                                   $("<span/>").attr("class","showFullSynopsis").attr("projectId",proposal.id)   
                                   .append($("<strong/>").append("(Details)")))
                       )
                       .append(
                           $("<div/>").attr("class","fullSynopsis").attr("id","fullSynopsis_"+proposal.id).attr("style","display:inline").hide()
                       )
                      .append(
                           $("<p/>").attr("class","myStudentsNeed").append(proposal.fulfillmentTrailer)                                                        
                       )
                       
                   )
               )
            )
            .appendTo("#searchResults");

            $(".showFullSynopsis").click(function(){
                if( displayingSynopsis == false)
                {
                    displayingSynopsis = true;
                    displaySynopsis($(this).attr("projectId"));
                }                  
            });           
           
            $("<tr/>").attr("id","srBtns" + i)
            .append($("<td/>").addClass("tdSearchBtns")
               .append(
                   $("<div/>").attr("id","emailThis" + i)))
              .append($("<td/>").addClass("tdSearchBtns")
              .append(
                      $("<div/>").attr("id","srButtons"+proposal.id).attr("class","voteForProject")
              )
              ).appendTo("#searchResults");
                   
            if ( proposal.fundingStatus != "funded" )
            {
                /*$("#emailThis"+i).append($("<button/>").attr("class","stafButton ui-button ui-state-default ui-corner-all").attr("projectId",proposal.id).append("&nbsp;")
                        .click(function() {
                            $.scrollTo(0);
                            $("#stafProjectId").attr("value",$(this).attr("projectId"));
                            $('#stafDialog').dialog('open');
                         })
                 )*/
                 
                $("#srButtons"+proposal.id)
                 /*
                 // DISABLE VOTING:
                 .append($("<button/>").attr("id","vote"+proposal.id).attr("class","voteButton ui-button ui-state-default ui-corner-all").attr("projectId",proposal.id).append("&nbsp;")
                       .click(function() {
                           $.scrollTo(0);
                           $("#projectid").attr("value",$(this).attr("projectId"));
                           setupVoteRemoveCookieLink();
                           $('#voteDialog').dialog('open');
                        })
               )*/
                .append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;")
                    .append($("<a/>").attr("class","donateLink").attr("onclick","trackView('#/donateClick/"+proposal.id+"')").attr("target","_NEW").attr("href", proposal.proposalURL).append( $("<img/>").attr("alt", "Donate Now").attr("src", imgsUrl + 'btns/donate.png')) )
            }
            
            if ( signinEmail == null || notUserFavorite(proposal.id))
            {
                $("#srButtons"+proposal.id)
                .append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;")
                .append($("<button/>").attr("id","favs" + proposal.id).attr("class","favsButton ui-button ui-state-default ui-corner-all").attr("projectId",proposal.id).append("&nbsp;")
                        .click(function () { addToFavsClick($(this).attr("projectId")); })
                        

                 )
            }
            else
            {
                $("#srButtons"+proposal.id)
//                .append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;")
                .append($("<button/>").attr("id","favs" + proposal.id).attr("class","favsButtonRemove ui-button ui-state-default ui-corner-all").attr("projectId",proposal.id).append("&nbsp;")
                        .click(function() { removeFromFavsClick($(this).attr("projectId")); })
                 )
            }
            

         });
   }

   function noResults(dcResult)
   {
       if ( dcResult == null || dcResult.proposals == null || dcResult.proposals.length == 0 )
       {
           return true;
       }
       return false;
   }
   
   function buildPagerRow(dcResult)
   {
       $("<tr/>").attr("id","pagerRow").appendTo("#pagerTop");
       
       if ( dcResult != null )
       {
           var lastPageProject = (parseInt(dcResult.index/pageSize, 10)+1)*pageSize;
           if ( lastPageProject > dcResult.totalProposals ) lastPageProject = dcResult.totalProposals;
    
           $("<td/>").append("Projects ").append($("<strong/>").append(parseInt(dcResult.index,10)+1 + "-" + lastPageProject))
            .append(" of ").append($("<strong/>").append(dcResult.totalProposals)).appendTo("#pagerRow");
            
            trackView("#/search/"+ (parseInt(dcResult.index,10)+1) + "-" + lastPageProject + "/" + dcResult.totalProposals);
    
            var totalPages = parseInt(dcResult.totalProposals/pageSize,10); 
            if ( dcResult.totalProposals%pageSize > 0 ) totalPages += 1;
            var currentPage = parseInt(dcResult.index/pageSize,10);
            var start = parseInt(currentPage/displayPages,10) * displayPages;
            var end = start + displayPages;
            if (end > totalPages) { end = totalPages; }
            
        // Only display the pager list if there are more than one page of results.
            if ( start < end-1 )
            {
                $("<td/>").attr("class","pagesList").appendTo("#pagerRow");        
                if (start > 0) 
                {
                   var aPg = document.createElement("a");
                   $(aPg).attr("idxValue", currentPage-1);
                   $(aPg).click(function(event){ var idx = parseInt(($(this).attr("idxValue")) * pageSize,10); getPageResults(idx); event.preventDefault(); });
                   $(aPg).append("Previous");
                   $(".pagesList").append("&nbsp;").append($(aPg));
                }
                
                for ( i=start; i < end; i++ )
                {
                
                   var aPg = document.createElement("a");
                   $(aPg).attr("idxValue", i);
                   $(aPg).click(function(event){ var idx = parseInt(($(this).attr("idxValue")) * pageSize,10); getPageResults(idx); event.preventDefault(); });
                   if ( i == currentPage )
                   {
                       $(aPg).append($("<u/>").append(parseInt(i+1,10)));
                   }
                   else
                   {
                       $(aPg).append(parseInt(i+1,10));
                   }
                   $(".pagesList").append("&nbsp;").append($(aPg));
        
                }
                
                if (totalPages > displayPages && dcResult.index < (totalPages-1) * pageSize) 
                {
                   var aPg = document.createElement("a");
                   $(aPg).attr("idxValue", currentPage + 1);
                   $(aPg).click(function(event){ var idx = parseInt(($(this).attr("idxValue")) * pageSize,10); getPageResults(idx); event.preventDefault(); });
                   $(aPg).append("Next");
                   $(".pagesList").append("&nbsp;").append($(aPg));
                }
            }
        }
        else
        {
               $("<td/>").append("Projects ").append($("<strong/>").append("0 of 0")).appendTo("#pagerRow");
        }
        // Set bottom pager content to the same as top.
        $("#pagerRow").clone(true).appendTo($("#pagerBottom"));

   }
   
   function findSearchOption(optionName)
   {
       var rebuildSearchOptions = false;
       for (var i=0; i < searchOptions.length; i++)
       {   
           if ( searchOptions[i].name == optionName )
           {
               return searchOptions[i];
           }
           // subject is special case because we have optionName of subject1...subject5 and we want to replace 
           // any that start with "subject". I.E. can't have something like both subject1 and subject3 selected 
           // at the same time.
           if ( optionName.substr(0,7) == "subject"  && searchOptions[i].name.substr(0,7) == "subject" )
           {
               searchOptions[i] = null;
               rebuildSearchOptions = true;
           }
       }
       
       // compress options by removing nulled out values if there were any.
       if ( rebuildSearchOptions )
       {
           var oldOptions = searchOptions;
           searchOptions = new Array();
           for (var i=0; i < oldOptions.length; i++)
           {
               if ( oldOptions[i] != null )
               {
                   addSearchOption(oldOptions[i].name, oldOptions[i].value);
               }
           }
       }
       return null;
   }
   
   function submitKeywordSearch()
   {
       // Validate?
       if ( $("#keywords").val() != null && $("#keywords").val().length > 0 )
       {
              $("#validateSearchCriteria").empty();
           optionSearch("keywords", $("#keywords").val());
       }
       else
       {
           $("#validateSearchCriteria").text("No valid keywords were entered.").effect("highlight",{},1500);
           removeSearchFilter("keywords","");
       }
   }
   
   function optionSearch(name, value, searchableDomElement)
   {
       // alert(name + " = " + value);
       if ( name != null && value != null)
       {
            var option = findSearchOption(name);
            if ( option != null )
            {
                option.value = escape(value);
            }
            else
            {
                addSearchOption(name, escape(value));
            }
            
            // If this is a location search, add "state" name to search preferences and 
            // add cities,counties,districts selection headers/dialogs.
            if ( name == "zone" )
            {
                // alert("state selected: " + name + " = " + value);
                // Clear any previous city/county/districts if other state was previously selected.
                $(".locationJson").remove();
                
                // Also remove any state community values (previous city/county/district) from search options.
                 var oldOptions = searchOptions;
                searchOptions = new Array();
                for (var i=0; i < oldOptions.length; i++)
                {
                   if ( oldOptions[i].name.match("community") == null  )
                   {
                       addSearchOption(oldOptions[i].name, oldOptions[i].value);
                   }
                }

                // Since they have picked a state, hide the state selection dialog header 
                // until they remove the selected state.
                 $(".stateListHeader").hide();
                 
                 getJsonData(name,value);
            }
            
            // If this is a new community (city/county/district) search.  Hide the other community dialogs
            if ( name == "community" )
            {
                $(".locationJson").hide();
            }
            
            getSearchResults(buildSearchUrl());
       }
   }

   function removeSearchFilter(name, value)
   {
       if ( name != null && value != null)
       {
           if ( name == "zone")
           {
               // We are removing state so remove display of any location (city,county,district) dialogs
               $(".locationJson").remove();
               // Re-show the state list dialog
               $(".stateListHeader").show();
           }
           else if (name == "community")
           {
               // Removing previous community location. re-show city,county,district dialogs 
               $(".locationJson").show();
           }
           else if (name == "keywords")
           {
                  // Removing keywords, clear out the search box:
                  $("#keywords").val("");
           }
           else if (name.indexOf("subject") != -1)
           {
                       // expandableOptSubContent needs to be hidden 
                       // (which is found directly after the expandableOptSubHeader)
                       $(".expandableOptSubHeader").each( function() {
                           if($(this).attr("searchoptname") == name)
                               $(this).next().hide('slow');
                       });
           }
           
           var oldOptions = searchOptions;
           searchOptions = new Array();
           for (var i=0; i < oldOptions.length; i++)
           {
               // Add back all the options that don't match the remove name and value.  Or
               // if the name is a zone (state), remove any community values (city, county,
               // district) as well.
               if ( (oldOptions[i].name != name && oldOptions[i].value != value)  )
               {
                   if ( name == "zone" && oldOptions[i].name.match("community") != null ) { 
                       // Clear selected state and  any previous city/county/districts
                           continue; 
                   }
                   addSearchOption(oldOptions[i].name, oldOptions[i].value);
               }
           }

           getSearchResults(buildSearchUrl());
       }
   }
      
   function getJsonData(zonename, zoneval)
   {
       // alert("getJsonData for " + zonename + " = " + zoneval);
       var jsonUrl = jsonDataUrl+zoneval+".json";

       openAjaxLoader();
       $.ajax({
           type: "GET",
           url: jsonUrl,
           dataType: "json",
           success: function(resp,statusMsg) { closeAjaxLoader();   buildCityCountyDistrict(resp); },
           error: function(msg) { 
                   closeAjaxLoader(); 
                   logErrorMessage("getJsonData","Error returned from json ajax call. Status Text: " + msg.statusText + " Method Info - zonename: " + zonename + " zoneval: " + zoneval);
                      
                   alert("We're sorry. The system is having issues. Please try again later."); 
           },
           async: true
        });           
   }
   
   function buildCityCountyDistrict(stateDataObj)
   {   
       // Since we are adding "after" stateList we need to go in reverse order district, county, city/community.
       if ( stateDataObj.districts != null )
       {
           $(".stateListHeader").after($("<li/>").addClass("districtListHeader").addClass("locationJson").append("District"));
               $(".districtListHeader").after($("<li/>").addClass("districtList").addClass("locationJson").append($("<div/>").attr("id","districtListDialog").attr("title", "SELECT A DISTRICT")));
    
           $.each(stateDataObj.districts, function(i, district)
           {

               if ( district != null && district.community != null )
               {
                   $("#districtListDialog").addClass("locationJson");
                   $("#districtListDialog").append($("<a/>").attr("href","").attr("searchOptName","community").attr("searchOptVal",district.community).addClass("searchableLink").addClass("districtFacet").append(district.name)).append($("<br/>"));
               }
           });
           
           
           $('.districtListHeader').click(function () { 
               $("#districtListDialog").dialog('open');
           }).next().hide();
           
           // Setup click handlers for district searchable links.
           $("#districtListDialog .searchableLink").click(function() { 
               // ensure there is a facet count before adding to search options:
                  if($(this).html().indexOf("facetCount") > -1)
                  { 
                   $("#validateSearchCriteria").empty();
                   $("#districtListDialog").dialog('close'); 
                   optionSearch($(this).attr("searchOptName"), $(this).attr("searchOptVal"), $(this));
               }
               return false;
           });
           
           $("#districtListDialog").dialog({
               bgiframe: true,
               autoOpen: false,
               position: "middle",
               width: 300,
               height: 400,
               show: 'clip',
               hide: 'clip',
               modal: true,
               close: function() {
               }
           });
       }
       
       if ( stateDataObj.counties != null )
       {
           $(".stateListHeader").after($("<li/>").addClass("countyListHeader").addClass("locationJson").append("County"));
               $(".countyListHeader").after($("<li/>").addClass("countyList").addClass("locationJson").append($("<div/>").attr("id","countyListDialog").attr("title", "SELECT A COUNTY")));
    
           $.each(stateDataObj.counties, function(i, county)
           {
               if ( county != null && county.community != null )
               {
               $("#countyListDialog").addClass("locationJson").append($("<a/>").attr("href","").attr("searchOptName","community").attr("searchOptVal",county.community).addClass("searchableLink").addClass("countyFacet").append(county.name)).append($("<br/>"));
               }
           });
           
           
           $('.countyListHeader').click(function () { 
               $("#countyListDialog").dialog('open');
           }).next().hide();
           
           // Setup click handlers for county searchable links.
           $("#countyListDialog .searchableLink").click(function() { 
               // ensure there is a facet count before adding to search options:
                  if($(this).html().indexOf("facetCount") > -1)
                  { 
                   $("#validateSearchCriteria").empty();
                   $("#countyListDialog").dialog('close'); 
                   optionSearch($(this).attr("searchOptName"), $(this).attr("searchOptVal"), $(this));
               }
               return false;
           });
           
           $("#countyListDialog").dialog({
               bgiframe: true,
               autoOpen: false,
               position: "middle",
               width: 300,
               height: 400,
               show: 'clip',
               hide: 'clip',
               modal: true,
               close: function() {
               }
           });
       }
       
       if ( stateDataObj.cities != null )
       {
           $(".stateListHeader").after($("<li/>").addClass("cityListHeader").addClass("expandableOptSubHeader").addClass("locationJson").append("City"));
               $(".cityListHeader").after($("<li/>").addClass("cityList").addClass("locationJson").append($("<div/>").attr("id","cityListDialog").attr("title", "SELECT A CITY")));
    
           $.each(stateDataObj.cities, function(i, city)
           {
               if ( city != null && city.community != null )
               {
               $("#cityListDialog").addClass("locationJson").append($("<a/>").attr("href","").attr("searchOptName","community").attr("searchOptVal",city.community).addClass("searchableLink").addClass("cityFacet").append(city.name)).append($("<br/>"));
               }
           });
           
           
           $('.cityListHeader').click(function () { 
               $("#cityListDialog").dialog('open');
           }).next().hide();
           
           // Setup click handlers for city searchable links.
           $("#cityListDialog .searchableLink").click(function() { 
               // ensure there is a facet count before adding to search options:
                  if($(this).html().indexOf("facetCount") > -1)
                  { 
                   $("#validateSearchCriteria").empty();
                   $("#cityListDialog").dialog('close'); 
                   optionSearch($(this).attr("searchOptName"), $(this).attr("searchOptVal"), $(this));
               }
               return false;
           });
           
           $("#cityListDialog").dialog({
               bgiframe: true,
               autoOpen: false,
               position: "middle",
               width: 300,
               height: 400,
               show: 'clip',
               hide: 'clip',
               modal: true,
               close: function() {
               }
           });
       }
       
       if ( stateDataObj.communities != null )
       {
           $(".stateList").after($("<li/>").addClass("communityListHeader").addClass("locationJson").append("Community"));
               $(".communityListHeader").after($("<li/>").addClass("communityList").addClass("locationJson").append($("<div/>").attr("id","communityListDialog").attr("title", "SELECT A COMMUNITY")));
    
           $.each(stateDataObj.communities, function(i, community)
           {
               if ( community != null && community.community != null )
               {
               $("#communityListDialog").addClass("locationJson").append($("<a/>").attr("href","").attr("searchOptName","community").attr("searchOptVal",community.community).addClass("searchableLink").addClass("communityFacet").append(community.name)).append($("<br/>"));
               }
           });
           
           
           $('.communityListHeader').click(function () { 
               $("#communityListDialog").dialog('open');
           }).next().hide();
           
           // Setup click handlers for community searchable links.
           $("#communityListDialog .searchableLink").click(function() { 
               // ensure there is a facet count before adding to search options:
                  if($(this).html().indexOf("facetCount") > -1)
                  { 
                   $("#validateSearchCriteria").empty();
                   $("#communityListDialog").dialog('close'); 
                   optionSearch($(this).attr("searchOptName"), $(this).attr("searchOptVal"), $(this));
               }
               return false;
           });
           
           $("#communityListDialog").dialog({
               bgiframe: true,
               autoOpen: false,
               position: "middle",
               width: 300,
               height: 400,
               show: 'clip',
               hide: 'clip',
               modal: true,
               close: function() {
               }
           });
       }


       $(".searchableLink").each(  function(i) {
           var queryParam = $(this).attr("searchOptName") + "_" + $(this).attr("searchOptVal");
           searchTermNames[unescape(queryParam)]=$(this).html();
       });  
       
       return false;
   }
   
   function setPageSize(size)
   {
       pageSize = size;
       optionSearch("max", size);
   }
   
   function showHelpModal() 
   {
        // Get the DOM element which will hold the modal content
        var dialogElem = $(this).next(".helpModalDialog");
        // For some reason the div gets destroyed from the DOM when the dialog is
        // created. Make a copy so we can open multiple times.
        dialogElem.clone().insertAfter(this);
        // Insert iframe content, pulling the href from the link element.
        var h = parseInt($(this).attr("height"),10);
        var w = parseInt($(this).attr("width"),10);
        $("<iframe/>").attr("src", $(this).attr("href")).attr("width", w).attr(
                "height", h).appendTo(dialogElem);
        // Create dialog
        dialogElem.dialog( {
            autoOpen :true,
            bgiframe :true,
            height :h + 60,
            width :w + 30,
            show :500,
            hide :500,
            modal :true
        });
    
        dialogElem.bind('dialogclose', function(event, ui) {
            $(this).dialog('destroy');
        });

    return false;
    }
   
  
   
   function checkLength(o,n,min,max,updateTipsFunc) {
       if ( o.val().length > max || o.val().length < min ) {
           o.addClass('ui-state-error');
           if ( min == max )
           {
               updateTipsFunc("Length of " + n + " must be "+max+".");
           }
           else
           {
                  updateTipsFunc("Length of " + n + " must be between "+min+" and "+max+".");               
           }
           return false;
       } else {
           return true;
       }

   }

   function checkRegexp(o,regexp,n,updateTipsFunc) {
       if ( !( regexp.test( o.val() ) ) ) {
           o.addClass('ui-state-error');
           updateTipsFunc(n);
           return false;
       } else {
           return true;
       }
   }   


   function updateBadgePreview() {
           $("#badgeLayoutPreview").attr("src", micrositeUrl + "images/badge/" + $("#badgeLayout").val());
   }
      
   function selectBadgeLayout(image) {
           $(".selectedImage").removeClass("selectedImage");
           $(image).addClass("selectedImage");
           $('#badgeLayout').val($(image).attr("src"));
   }
   
   function updateBadgeTips(t) {
           if ( $("#validateBadgeTips").text().length > 0 )
           {
               $("#validateBadgeTips").append($("<br/>"));
           }
           $("#validateBadgeTips").append(t);
           $("#validateBadgeTips").effect("highlight",{},1500);
   }
   
   function submitBadgeForm() {
   
          var piValid = true;
          
          $("#validateBadgeTips").empty();
          $("#badgeForm :input").removeClass('ui-state-error');
          
          var projectId = $("#badgeProjectId");
          
          
          // ensure the projectId is both provided and an actual project:
          piValid = piValid && checkRegexp(projectId,/^([0-9]){5,7}$/,"Please enter a valid project id.",updateBadgeTips);
       
       if(piValid)
       {
               getSingleProjectById(projectId.val(), finalizeSubmitBadgeForm);
       }
       else
       {
               finalizeSubmitBadgeForm(null, piValid);
       }
       return false;
   }
   
   function finalizeSubmitBadgeForm(dcProject, pValid) {
          if(pValid == undefined)
                  pValid = true;
                  
          var piValid = pValid;
          var lValid = true;
       
       var projectId = $("#badgeProjectId");
          var layout = $("#badgeLayout");
          
       if(piValid)
       {
           if(dcProject == null)
           {
                   piValid = false;
                   projectId.addClass('ui-state-error');
                   updateBadgeTips("Please enter a valid project id.");
           }
       }
                        
          // ensure a layout is provided
          lValid = lValid && checkRegexp(layout,/^.+$/,"Please select a layout.",updateBadgeTips);
          
          if(piValid && lValid) {
                  // generate the badge
                  var port = "";
            
            if(document.location.port != "" && document.location.port != 80)
            {
                port = ":" + document.location.port;
            }
            var imgSrc = layout.val();
            if(layout.val().indexOf("http://") == -1) {
                imgSrc = "http://" + document.domain + port + micrositeUrl + layout.val();
            }
            var projLink = "http://" + document.domain + port + micrositeUrl + "index.jsp?projectId=" + projectId.val();
            var code = '<a href="'+projLink+'" target="_blank"><img src="'+imgSrc+'" /></a>'

            $("#badgeCode").val(code);
            $("#badgeCode").width('50');
            
            $("#badgePreview").html(code);

            $("#badgeDialog").dialog('open');
            
            setNavAction("#/toolbox/badge/success");
          }
          
          // return false so the form doesn't submit.
          return false;
   }
   
   function updateFlierTips(t) {
           if ( $("#validateFlierTips").text().length > 0 )
           {
               $("#validateFlierTips").append($("<br/>"));
           }
           $("#validateFlierTips").append(t);
           $("#validateFlierTips").effect("highlight",{},1500);
   }
   
   function submitFlierForm()
   {
       var nValid = true;
          var piValid = true;
          var fValid = true;
          
          $("#validateFlierTips").empty();
          $("#flierForm :input").removeClass('ui-state-error');
          
          var name = $("#flierName");
          var projectId = $("#flierProjectId");
          var format = $("#flierFormat");
          
          // ensure a name is provided
       nValid = nValid && checkRegexp(name,/^.+$/,"Please provide your name.",updateFlierTips);
       
          // ensure the projectId is both provided and an actual project:
          piValid = piValid && checkRegexp(projectId,/^([0-9]){5,7}$/,"Please enter a valid project id.",updateFlierTips);
       
          // ensure a format is provided
          fValid = fValid && checkRegexp(format,/^.+$/,"Please select a format.",updateFlierTips);
          
       // if all fields are there and deemed valid, proceed with
       // pulling the project by id to validate it exists
       if(piValid && nValid && fValid)
       {
               getSingleProjectById(projectId.val(), finalizeSubmitFlierForm);
       }

       return false;
   }
   
   function finalizeSubmitFlierForm(dcProject, pValid) {
          if(pValid == undefined)
                  pValid = true;
                     
          var piValid = pValid;
                
          var name = $("#flierName");
          var format = $("#flierFormat");
          var projectId = $("#flierProjectId");
          
          if(piValid)
       {
           if(dcProject == null)
           {
                   piValid = false;
                   projectId.addClass('ui-state-error');
                   updateFlierTips("Please enter a valid project id.");
           }
       }

          if(piValid) {
                  // popuplate name, format, project name and project description on confirm form
               $("#flierConfirmForm #name").val($("#flierName").val());
               $("#flierConfirmForm #format").val($("#flierFormat").val());
               $("#flierConfirmForm #projectName").val(dcProject.title);
               $("#flierConfirmForm #projectNameLabel").html(dcProject.title);
               $("#flierConfirmForm #projectDescription").val(dcProject.shortDescription);
               
               $("#flierConfirmDialog").dialog('open');
          }

          return false;
   }
 
   function updateFlierConfirmTips(t) {
           if ( $("#validateFlierConfirmTips").text().length > 0 )
           {
               $("#validateFlierConfirmTips").append($("<br/>"));
           }
           $("#validateFlierConfirmTips").append(t);
           $("#validateFlierConfirmTips").effect("highlight",{},1500);
   }
     
   function validateFlierConfirmForm()
   {
         var pdValid = true;
           
           $("#validateFlierConfirmTips").empty();
           $("#flierConfirmForm :input").removeClass('ui-state-error');
          
        pdValid = pdValid && checkRegexp($("#flierConfirmForm #projectDescription"), /^(.|\r|\n)+$/, "Project description is required.", updateFlierConfirmTips);
        
           return pdValid;
   }
   
   function updateVoteTips(t) {

       if ( $("#validateVoteTips").text().length > 0 )
       {
           $("#validateVoteTips").append($("<br/>"));
       }
       $("#validateVoteTips").append(t);
       $("#validateVoteTips").effect("highlight",{},1500);
       $("#votecode").select();
   }

   function submitVote() {
       var vcValid = true;
       var eValid = true;
          // clear previous errors
       $("#validateVoteTips").empty(); 
       $("#voteForm :input").removeClass('ui-state-error');
       
       var votecode = $("#votecode");
       var projectid = $("#projectid");
       var trackEmail = $("#trackEmail");
          
       vcValid = vcValid && checkLength(votecode,"Vote Code",7,7,updateVoteTips);
       vcValid = vcValid && checkRegexp(votecode,/^([0-9a-zA-Z])+$/,"Sorry. Vote Codes only have letters and numbers.",updateVoteTips);
       
       if ( $("#trackVotes").is(':checked') )
       {
           eValid = eValid && checkLength(trackEmail,"e-mail",6,255,updateVoteTips);
           eValid = eValid && checkRegexp(trackEmail, emailRegEx, "Please enter a valid e-mail address.",updateVoteTips);
       }
       
       if (vcValid && eValid) {
           
           // See if the voter wants to track the votes and setup "remember me" cookie
           if ( $("#trackVotes").is(':checked') ) 
           {
               signinEmail = trackEmail.val();
               
               if ( $("#voteRememberMe").is(':checked') )
               {
                   setRememberMeCookie(signinEmail);
                   setupVoteRemoveCookieLink();
               }
            }
           else
           {
               // If we are here and know who they are, then they must have set remember me cookie
               // before. Re-set it so the expiration date gets updated.
               if ( signinEmail != null )
               {
                   setRememberMeCookie(signinEmail);
               }
           }
                    
           sendVoteToServer(votecode.val(), projectid.val(), persistentId, signinEmail);
       }
       else
       {
               enableVoting();
       }
       return false;
   }

   function sendVoteToServer(votecode, projectId, persistentId, signinEmail)
   {
       var voteUrl = actionPrefix + "vote.do?code=" + escape(votecode) + "&persistentId=" + escape(persistentId) + "&projectId=" + escape(projectId) + "&noIEcache=" + (new Date().getTime());
       if ( signinEmail != null )
       {
           voteUrl += "&email="+escape(signinEmail)
       }
       
       openAjaxLoader();
       $.ajax({
           type: "GET",
           url: voteUrl,
           dataType: "json",
           success : function(voteResult) { 
           
                           if ( voteResult.status == "success" )
                           {                           
                           if(navAction.indexOf("#/favoriteProjects") == 0)
                                   loadFavorites(true);
                              else if ( navAction.indexOf("#/searchProjects") == 0 )
                                getSearchResults(buildSearchUrl());
                           //else if (navAction.indexOf("#/mostPopularProjects") == 0 )
                           //    loadPopular(0);
                                                          
                              $('#votes'+voteResult.projectId).empty().html(voteResult.voteCount);
                              $("#voteConfirmationMsg").html($('#teacherName'+voteResult.projectId).html() + " and the class thank you for your vote.  They now have a total of " + voteResult.voteCount + " votes.");
                              
                           trackView(location.hash+"/voteSuccess/"+escape(projectId));
            
                              $("#voteDialog").dialog('close'); 
                           
                              // If we know who they are then this got added to favs. Update button.
                              if ( signinEmail != null )
                              {
                                  addFav(voteResult.projectId, false);
                              }
                             
                             
                           $('#voteConfirmDialog').dialog('open'); 
                           $('#voteConfirmDialog').dialog('moveToTop');
                           }
                           else if ( voteResult.status == "error" )
                           {
                               var errorMsg = "Sorry.  There has been an error trying to record your vote. Please try again.";
                               switch(voteResult.cause)
                               {
                                   case "INVALID_VOTE_CODE":
                                   case "VOTE_CODE_DOES_NOT_EXIST":
                                       errorMsg = "Sorry. Looks like you've entered an invalid code. Please verify your code and try again. Codes are case sensitive.  If you can't get your code to work <a href='./faqs.html#contactUs' target='_blank'>Contact Us</a> for help.<br/><br/>";
                                       break;
                                   case "VOTE_CODE_ALREADY_USED":
                                       errorMsg = "Sorry, that code has already been used. Please enter another code.  If you have questions you can <a href='./faqs.html#contactUs' target='_blank'>Contact Us</a> for help.<br/><br/>";
                                       break;
                                   case "NO_METRIC_COOKIE": 
                                   case "NO_PROJECT_ID":
                                   case "UNKNOWN_ERROR":
                                   default:
                               }
                               updateVoteTips(errorMsg);
                           }
                           enableVoting();
                           closeAjaxLoader();
                              
                       },
           error : function(xOption, status) {  
                   enableVoting();
                   $("#voteDialog").dialog("close"); 
                   logErrorMessage("sendVoteToServer","Error returned from json ajax call. Status Text: " + xOption.statusText + " Method Info - votecode: " + votecode + " projectId: " + projectId + " persistentId: " + persistentId + " signinEmail: " + signinEmail);
                   alert("We're sorry. The system is having issues. Please try again later."); 
           },
           async: true
       });    
       
       return false;
   }
   
   function setupVoteRemoveCookieLink()
   {
       $(".showTrackVotes").hide(); 
       
      if ( signinEmail != null )
      {
           $(".trackVotes").hide();
             
           $("#voteRemoveCookieLinkWrapper").empty();
           $("#voteRemoveCookieLinkWrapper").append("Not " + signinEmail + "? ").append($("<a/>").attr("href","").attr("class","removeCookieLink").append("Sign Out"));
           $("#voteRemoveCookieLinkWrapper").show(); 
           
           // setup handler to remove persistent cookie
           $(".removeCookieLink").click( function() {
               signinEmail = null;
               clearRememberMeCookie();
               setupVoteRemoveCookieLink();
               setupFavsRemoveCookieLink();
               
               
               //refresh search results
               if ( navAction.indexOf("#/searchProjects") == 0 )
                    getSearchResults(buildSearchUrl());
                //else if (navAction.indexOf("#/mostPopularProjects") == 0 )
                //    loadPopular(0);
               else if (navAction.indexOf("#/fundedProjects") == 0 )
                       loadFundedProjects(lastState, lastCity);
                       
               //$("#trackVotes").attr("checked",true);
               //$(".trackVotes").click();
               
               return false;
           });
           
      }
      else
      {
           $(".trackVotes").show();
           $("#voteRemoveCookieLinkWrapper").hide(); 
      }
      return false;
    }  
   
   function setRememberMeCookie(rememberEmail)
   {
       var now = new Date();
       var nextyear = new Date();
       nextyear.setFullYear(now.getFullYear() + 1);
       document.cookie = "limeades4LearningRememberMe=" + rememberEmail + "; expires=" + nextyear.toGMTString() + "; path=/";
   }
   
   function getRememberMeCookie()
   {
       var cname = "limeades4LearningRememberMe";
       return getCookie(cname);
   }

   
   function clearRememberMeCookie()
   {
       var past = new Date();
       past.setFullYear(past.getFullYear() - 1);
       document.cookie = "limeades4LearningRememberMe=; expires=" + past.toGMTString() + "; path=/";
       return false;
   }
   
   function setMetricCookie()
   {
       var now = new Date();
       var tenyear = new Date();
       tenyear.setFullYear(now.getFullYear() + 10);
       var randomstring = "L4L" + Math.floor(Math.random()*100001) + "L4L" + (new Date().getTime());
       document.cookie = "limeades4LearningMetric=" + randomstring + "; expires=" + tenyear.toGMTString() + "; path=/";
       return randomstring;
   }
   
   function getMetricCookie()
   {
       var cname = "limeades4LearningMetric";
       var cookie = getCookie(cname);
       if (cookie == null || cookie.length == 0)
       {
           cookie = setMetricCookie();
       }
       return cookie;
   }

   function setViewedMovie()
   {
       var now = new Date();
       var tenyear = new Date();
       tenyear.setFullYear(now.getFullYear() + 10);
       document.cookie = "limeades4LearningViewedMovie=true; expires=" + tenyear.toGMTString() + "; path=/";
   }
   
   function hasViewedMovie()
   {
       var cname = "limeades4LearningViewedMovie";
       var cookie = getCookie(cname);
       if (cookie == null || cookie.length == 0)
       {
           return false;
       }
       return true;
   }
   
   function getCookie(cname)
   {
       cname += "=";
       var cvalue = null;
       var allcookies = document.cookie.split(";");
       for (var i=0; i < allcookies.length; i++)
       {
           var c = allcookies[i];
           while (c.charAt(0)==' ') c = c.substring(1,c.length);
           if (c.indexOf(cname) == 0) cvalue = c.substring(cname.length,c.length);
       }

       return cvalue;
   }
   
   function updateSignupTips(t) {
       $("#validateSignupTips").text(t).effect("highlight",{},1500);
   }
   
   function notificationSignup() {
           var bValid = true;
           
           // clear previous errors
          $("#notificationSignupForm :input").removeClass('ui-state-error');
          $("#validateSignupTips").empty(); 
           
        var email = $("#notificationsEmail");
        bValid = bValid && checkLength(email,"e-mail",6,255,updateSignupTips);    
        bValid = bValid && checkRegexp(email, emailRegEx, "Please enter a valid e-mail address.",updateSignupTips);

        if ( bValid )
        {
            signupForNotifications(email.val());
        }
        return bValid;
   }

   function signupForNotifications(email)
   {
       var projectId = $("#projectid").val();
       var signupUrl = actionPrefix + "notificationsSignup.do?projectId=" + escape(projectId) + "&email=" + escape(email) + "&persistentId=" + escape(persistentId);

       openAjaxLoader();
       $.ajax({
           type: "GET",
           url: signupUrl,
           dataType: "json",
           success : function(notificationResult) { 

                        closeAjaxLoader();
                           if ( notificationResult.status == "success" )
                           {
                               setupNotificationSignupConfirmation();
                             }
                           else if ( notificationResult.status == "error" )
                           {
                               var errorMsg = "Sorry.  There has been an error trying sign you up for notications about this project. (" + notificationResult.cause + ")";
                               logErrorMessage("signupForNotifications","Error returned from "+signupUrl+". Error Message: " + errorMsg);
                               alert(errorMsg);
                           }
                       },
           error : function(xOption, status) {  
                   $("#signupDialog").dialog("close"); 
                   logErrorMessage("signupForNotifications","Error returned from json ajax call. Status Text: " + xOption.statusText + " Method Info - email: " + email);
                   alert("We're sorry. The system is having issues. Please try again later."); 
           },
           async: true
       });    
       
       return false;
   }

   function voteConfirmDoneButton() {
       $("#voteConfirmDialog").dialog('close');
       $('#votesCast'+$("#projectid").val()).effect("highlight", {color:"#ff5555"}, 3000);
       // Reset checkbox values so they are not checked on next vote.
       $("#followups").attr("checked",false);
       $("#getoffers").attr("checked",false);
   } 
   
  var cruiserSignup = false; 
  function voteConfirmSignupButton() {
      
      if ( $("#getoffers").is(':checked') )
      {
           cruiserSignup = true;
      }
      
      if ( $("#followups").is(':checked') )
      {
            trackView(location.hash+"/voteSuccess/notifications");
           // If we already know who they are, send to server
           if ( signinEmail != null )
           {
               signupForNotifications(signinEmail);
           }
           else
           {
               // get email.
               $("#signupDialog").dialog('open');
           }
      }
      else if ( cruiserSignup )
      {   
          $("#signupConfirmDialog").dialog('close');
          trackView(location.hash+"/voteSuccess/cruiserSignup");
          window.open(joinCruisers,'_JoinCruisers');
      }else{
          alert("Please choose to become a SONIC Cruiser and/or to receive email communications");
          return;
      }
      
      voteConfirmDoneButton()
   } 
   
  
   function setupNotificationSignupConfirmation()       
   {       
       $("#signupDialog").dialog('close');
       
       if ( cruiserSignup ) 
       {
           $("#signupConfirmDialog").dialog('option', 'buttons', {
               'Continue To Cruiser Registration':  function() {  $("#signupConfirmDialog").dialog('close'); window.open(joinCruisers,'_JoinCruisers');},
               'Cancel': function() {  $("#signupConfirmDialog").dialog('close'); } });
       }
       else
       {
           $("#signupConfirmDialog").dialog('option', 'buttons', {'Done': function() {  $("#signupConfirmDialog").dialog('close'); } });
       }
       addDialogButtonStyles();
       
       $("#notificationSignupForm")[0].reset();
       $('#signupConfirmDialog').dialog('open');

       cruiserSignup = false;             
   }
   
   function updateStafTips(t) {
       $("#validateStafTips").text(t).effect("highlight",{},1500);
   }
   
   
   function sendToAFriend(stafURL)
   {
          var stafValid = validateSTAF();
       
       if (stafValid) {
           // Get all input elements of the spreadTheWord form that are not buttons.
           // build the post
           var allInputs = $("#spreadTheWordForm :input[type!=button]");
           var postData = "";
           var genericSTAF = false;
           var stafProjectId = "";
           
           for (var i=0; i < allInputs.length; i++)
           {
                  var paramName = $(allInputs[i]).attr("name");
                  var paramValue = escape($(allInputs[i]).val());

                  if(paramName == 'stafProjectId')
                  {
                      if (paramValue == '' || paramValue == null)
                          genericSTAF = true;
                      else
                          stafProjectId = paramValue;
                  }
                          
               postData += paramName + "="  + paramValue;
               if ( i+1 < allInputs.length ) postData += "&";
           }
           
           // if we need to send the generic staf, set the referralType here:
           if(genericSTAF)
                   postData = postData.replace(/L4LSTAF/,"L4LSTAF_GENERIC");
           postData += "&response=json";
           
           openAjaxLoader();
           $.ajax({
               type: "POST",
               url: stafURL,
               dataType: "json",
               data: postData,
               success: function(resp,statusMsg) { 
                       closeAjaxLoader();  
                       if( resp.status == "true" ) { 
                           trackView("#/stafSuccess/"+stafProjectId); 

                        $("#spreadTheWordForm")[0].reset();
                           $("#stafDialog").dialog('close');
                           alert("Thank You! Your message has been sent.");
                       } 
                       else { 
                           if( resp.message != "action failed" ) {
                            var errors = resp.errors;
        
                                  $.each(errors, function(i, error)
                               {
                                   var messageToDisplay = errorMessages[error];
                                   if(messageToDisplay == null)
                                       messageToDisplay = errorMessages["default"];
                                updateStafTips(messageToDisplay);
                               });
                           } 
                           else {
                               logErrorMessage("sendToAFriend","Error returned from json call. Response: " + resp.message);
                               updateStafTips("We're sorry. The system is having issues. Please try again later."); 
                           } 
                       }
               },
               error: function(msg) { 
                       closeAjaxLoader(); 
                       logErrorMessage("sendToAFriend","Error returned from json ajax call. Status Text: " + msg.statusText + " Method Info - stafURL: " + stafURL);
                   
                       updateStafTips("We're sorry. The system is having issues. Please try again later."); 
               },
               async: true
            });

       }
       return false;

   }
   
   function validateSTAF()
   {
       // clear previous errors
       $("#validateStafTips").empty(); 
       $("#spreadTheWordForm :input").removeClass('ui-state-error');
       
           var fromName = $("#fromName");
           var fromEmail = $("#fromEmail");
           var commaEmails = $("#commaEmails");
           var comment = $("#comment");
           var referralTypeName = $("#referralTypeName");
           
           // ensure there is a referralTypeName set on the form:
           if(referralTypeName == null || referralTypeName == "")
               referralTypeName.val("L4LSTAF");
           
       // validate form
           var stafValid = true;

       stafValid = stafValid && checkLength(fromName,"Your Name",1,50,updateStafTips);
       stafValid = stafValid && checkLength(fromEmail,"Your E-mail",6,255,updateStafTips);
       stafValid = stafValid && checkLength(commaEmails,"Friends E-mail",6,255,updateStafTips);
       stafValid = stafValid && checkLength(comment,"Message",0,501,updateStafTips);
       if ( fromEmail.val() != null && fromEmail.val().length > 0 )
       {
       var invalidEmailLabel = fromEmail.val();
       if(invalidEmailLabel.length > 20)
               invalidEmailLabel = invalidEmailLabel.substring(0,20) + "...";
               
           stafValid = stafValid && checkRegexp(fromEmail, emailRegEx, "Your E-mail (" + invalidEmailLabel + ") is an invalid e-mail address.",updateStafTips);
       }

       if ( commaEmails.val() != null && commaEmails.val().length > 0 )
       {
           var toEmails = commaEmails.val().split(",");
           for(var i=0; i < toEmails.length; i++)
           {
               var testEmail = toEmails[i].replace(/^\s\s*/, '').replace(/\s\s*$/, '');
               if ( !( emailRegEx.test(testEmail) ) )
               {
                   var invalidEmailLabel = testEmail;
                   if(invalidEmailLabel.length > 20)
                       invalidEmailLabel = invalidEmailLabel.substring(0,20) + "...";
                   commaEmails.addClass('ui-state-error');
                   updateStafTips("Friend's E-mail (" + invalidEmailLabel + ") is an invalid e-mail address.");
                   stafValid  = false;
                   break;
               }
           }
       }
       
       return stafValid;
   }

   function updateAddToFavsTips(t) {
       $("#validateAddToFavsTips").text(t).effect("highlight",{},1500);
   }
   
   function addToFavsSignup() {
           var bValid = true;
       
            // clear previous errors
           $("#addToFavsSignupForm :input").removeClass('ui-state-error');
           $("#validateAddToFavsTips").empty(); 
           
          var email = $("#addToFavsEmail");
               
           bValid = bValid && checkLength(email,"e-mail",6,255,updateAddToFavsTips);

           bValid = bValid && checkRegexp(email, emailRegEx, "Please enter a valid e-mail address.",updateAddToFavsTips);

           return bValid;
   }
   
   function addFav(proj, asyncOptional)
   {                  
          var asyncVal = true
          if(asyncOptional != null)
                  asyncVal = asyncOptional;
                  
       var projectId = proj;
       
       if(proj == null)
           projectId = $("#favsprojectid").val();
       
       var actionUrl = actionPrefix + "addFavorite.do?projectId=" + escape(projectId) + "&email=" + escape(signinEmail) + "&persistentId=" + escape(persistentId)+ "&noIEcache=" + (new Date().getTime());

       openAjaxLoader();
       $.ajax({
           type: "GET",
           url: actionUrl,
           dataType: "json",
           success : function(addFavResult) { 
                           closeAjaxLoader();
                           if ( addFavResult.status == "success" )
                           {
                               $.scrollTo(0);
                               $('#addToFavsConfirmDialog').dialog('open');                            
                               favs = addFavResult.projects;
                               $("#favs"+projectId).empty().append("&nbsp;").unbind( "click" )
                                .click(function() { removeFromFavsClick(projectId);});
                               
                               if ( navAction.indexOf("#/searchProjects") == 0 )
                                   getSearchResults(buildSearchUrl());
                               //else if (navAction.indexOf("#/mostPopularProjects") == 0 )
                               //    loadPopular(0);
                               else if ( navAction.indexOf("#/fundedProjects") == 0 )
                                   loadFundedProjects(lastState, lastCity);
                               
                               trackView(location.hash + "/favoriteAdd/" + escape(projectId));
                           }
                           else if ( addFavResult.status == "error" )
                           {
                               var errorMsg = "Sorry.  There has been an error trying add this project to your favorites. (" + addFavResult.cause + ")";
                               
                               logErrorMessage("addFav","Error returned from " + actionUrl + ". Error Message: " + errorMsg);
                               alert(errorMsg);
                           }
                       },
           error : function(xOption, status) { 
                   closeAjaxLoader(); 
                   logErrorMessage("addFav","Error returned from json ajax call. Status Text: " + xOption.statusText + " Method Info - proj: " + projectId);
                   alert("We're sorry. The system is having issues. Please try again later."); 
           },
           async: asyncVal
       });    
       
       return false;
       
   }

   
   function removeFav()
   {
       var projectId = $("#favsprojectid").val();
       
       var actionUrl = actionPrefix + "removeFavorite.do?projectId=" + escape(projectId) + "&email=" + escape(signinEmail) + "&persistentId=" + escape(persistentId)+ "&noIEcache=" + (new Date().getTime());
       
       openAjaxLoader();
       $.ajax({
           type: "GET",
           url: actionUrl,
           dataType: "json",
           success : function(removeFavResult) { 
                           closeAjaxLoader();
                           if ( removeFavResult.status == "success" )
                           {
                               
                               favs = removeFavResult.projects;

                               if ( navAction.indexOf("#/favoriteProjects") == 0)
                               {
                                   $("#favoriteProjects").click();
                               }
                               else
                               {
                                   $("#favs"+projectId).empty().append("&nbsp;").unbind( "click" )
                                   .click( function () { addToFavsClick(projectId); });
                                   if ( navAction.indexOf("#/searchProjects") == 0 )
                                       getSearchResults(buildSearchUrl());
                                   //else if ( navAction.indexOf("#/mostPopularProjects") == 0 )
                                   //    loadPopular(0);
                                   else if ( navAction.indexOf("#/fundedProjects") == 0 )
                                       loadFundedProjects(lastState, lastCity);
                               }
                               trackView(location.hash + "/favoriteRemove/" + escape(projectId));
                           }
                           else if ( removeFavResult.status == "error" )
                           {
                               closeAjaxLoader();
                               var errorMsg = "Sorry.  There has been an error trying remove this project from your favorites. (" + removeFavResult.cause + ")";
                               
                               logErrorMessage("removeFav","Error returned from "+actionUrl+". Error Message: "+ errorMsg);
                               alert(errorMsg);
                           }
                       },
           error : function(xOption, status) {  
                   logErrorMessage("removeFav","Error returned from json ajax call. Project ID: " + projectId);
                   alert("We're sorry. The system is having issues. Please try again later."); 
           },
           async: true
       });    
       
       return false;
       
   }
   
   function addToFavsClick(projectId) {
          $.scrollTo(0);
       $("#favsprojectid").attr("value",projectId);
       if ( signinEmail == null )
       {
           $('#addToFavsDialog').dialog('open');
       }
       else
       {
           addFav();
       }
   }
   function removeFromFavsClick(projectId)
   {
       $("#favsprojectid").attr("value",projectId);
        removeFav();
   }
   
   function notUserFavorite(projId)
   {
       for (var i=0; i < favs.length; i++)
       {
           // alert("fav: " + favs[i] + ", proj: " + projId);
          if (favs[i] == projId) { return false; }
       }
       return true;
   }
   
   function getFavorites(callback, showActive)
   {
       if (signinEmail != null)
       {
           var favoritesUrl = actionPrefix + "findFavorites.do?email=" + signinEmail + "&noIEcache=" + (new Date().getTime()) ;

           openAjaxLoader();
           $.ajax({
               type: "GET",
               url: favoritesUrl,
               dataType: "json",
               success : function(favsResult) { 
                               favs = favsResult.projects;
                               
                               if(callback)
                                   callback(favsResult.projects, showActive);
                               else
                                   closeAjaxLoader();
                           },
               error : function(xOption, status) { 
                       closeAjaxLoader(); 
                       logErrorMessage("getFavorites","Error returned from json ajax call. FavoritesURL: " + favoritesUrl);
                       alert("We're sorry. The system is having issues. Please try again later."); 
               },
               async: true
           });    
       }
   }
   
   function loadFavorites(showActive) 
   {
       setupFavsRemoveCookieLink();
       if (signinEmail != null)
       {
             getFavorites(loadFavoritesCallback, showActive);
       }
       else
       {
           $("#centerContent").load("./bodycontent/favs.html", null, favEmailNotKnown);
       }
       return false;  
    } 
    
    function loadFavoritesCallback(favsVal, showActive)
    {
    $("#centerContent").load("./bodycontent/favs.html", null, function() {
        searchOptions = new Array();
        var ids = "";
        if(favsVal != null)
        {
            for (var i=0; i < favsVal.length; i++)
            {
                ids += favsVal[i];
                if ( i+1 < favsVal.length) { ids  += " OR "; }
            }
        }
        
        if ( showActive == null || showActive )
        {
            var searchUrl = baseSearchUrl + "&keywords=(" + escape(ids) + ")";
            getSearchResults(searchUrl, false, showMinimalSearchResults, null, showEmptyActiveFavs, favoriteActiveHeader);
        }
        else
        {
            var searchUrl = baseSearchUrl + "&historical=true&keywords=(" + escape(ids) + ")";
            getSearchResults(searchUrl, false, showMinimalSearchResults, null, showEmptyFundedFavs, favoriteFundedHeader);
        }
    });
    }
   
   function favEmailNotKnown()
   {
          favoriteFundedHeader();
          $("<tr/>").append($("<td/>").addClass("noResults").attr("valign", "top").append($("<p/>").addClass("myFavesRed").append("Please enter your e-mail address into the form on the right to view your favorite projects.")).append($("<img/>").attr("src","images/spacer.gif").attr("alt","spacer").attr("width","1").attr("height","333"))).appendTo("#searchResults");
   }
   function setupFavsRemoveCookieLink()
   {
      if ( signinEmail != null )
      {
           $("#favProjForm").hide();
           $("#activeFundedPrjBtns").show();
             
                       
           // set height of favoriteProjectsContainer smaller
             $("#favoriteProjectsContainer.ui-accordion-content").height("31px");
             
           $("#favsRemoveCookieLinkWrapper").empty();
           $("#favsRemoveCookieLinkWrapper").append("Not " + signinEmail + "? ").append($("<a/>").attr("href","").attr("id","favsRemoveCookieLink").addClass("favsRemoveCookieLink").append("Sign Out"));
           $("#favsRemoveCookieLinkWrapper").show(); 
           
           // setup handler to remove persistent cookie
           $("#favsRemoveCookieLink").click( function() {
               signinEmail = null;
               clearRememberMeCookie();
               setupFavsRemoveCookieLink();
               return false;
           });
             
      }
      else
      {
          if(navAction.indexOf("#/favoriteProjects") == 0)
          {
             // set height of favoriteProjectsContainer to 150px:
             $("#favoriteProjectsContainer.ui-accordion-content").height("150px");
             
           $("#favProjForm").show();
           $("#favsRemoveCookieLinkWrapper").hide(); 
           $("#activeFundedPrjBtns").hide();
           $("#centerContent").load("./bodycontent/favs.html", null, favEmailNotKnown);
        }
      }
      return false;
    }  

   function showEmptyFundedFavs()
   {
       showEmptyFavs("Already Funded");
   }
   
   function showEmptyActiveFavs()
   {
       showEmptyFavs("Need to be Funded");
   }
   
   function showEmptyFavs(statusType)
   {
       // Clear previous results
       $("#searchCriteriaList").empty();
       $("#pagerTop").empty();
       $("#searchResults").empty();
       $("#pagerBottom").empty();
       
       
       favoriteHeader(statusType);
       
       var label = "";
       if(statusType == 'Need to be Funded')
       {
               label = "need to be funded.";
               
               $("#showActiveFavs img").attr("src","images/fb_NF-ON.gif");
               $("#showFundedFavs img").attr("src","images/fb_AF-OFF.gif");
       }
       else if(statusType == 'Already Funded')
       {
               label = "have already been funded.";
               
               $("#showActiveFavs img").attr("src","images/fb_NF-OFF.gif");
               $("#showFundedFavs img").attr("src","images/fb_AF-ON.gif");
       }
               
       $("<tr/>").addClass("noResults").append($("<td/>").attr("valign", "top").append($("<div/>")
       .append("You have no favorite projects that " + label))).appendTo("#searchResults");
   }
   
   function favoriteHeader(statusType)
   {
          var projectsLabel = "";
          
          if(statusType != null && statusType != "")
          {
                  projectsLabel = ": " + statusType;
          }
          
       $("<tr/>").attr("id","pagerRow").appendTo("#pagerTop");

       $("<td/>").append("MY FAVORITE PROJECTS" + projectsLabel).appendTo("#pagerRow");          
       // Set bottom pager content to the same as top.
       $("#pagerRow").clone(true).appendTo($("#pagerBottom"));
       $("#pagerTop #pagerRow td").attr("valign","bottom");
       $("#pagerTop #pagerRow").attr("valign","bottom");
   }
   
   function favoriteActiveHeader()
   {
          if(signinEmail != null)
          {
           favoriteHeader("Need to be Funded");
           $("#showActiveFavs img").attr("src","images/fb_NF-ON.gif");
        $("#showFundedFavs img").attr("src","images/fb_AF-OFF.gif");
       }
       else
        favoriteHeader("");
   }

   function favoriteFundedHeader()
   {
          if(signinEmail != null)
          {
           favoriteHeader("Already Funded");
           $("#showActiveFavs img").attr("src","images/fb_NF-OFF.gif");
        $("#showFundedFavs img").attr("src","images/fb_AF-ON.gif");
       }
       else
        favoriteHeader("");
   }
   
   function updateFavsProjTips(t) {
       $("#validateFavProjForm").text(t).effect("highlight",{},1500);
   }
   
   function validateFavsProjSignup() {
       var bValid = true;
       
       // clear previous errors
       $("#favProjForm :input").removeClass('ui-state-error');
       $("#validateFavProjForm").empty(); 
           
       var email = $("#favsEmail");

       bValid = bValid && checkLength(email,"e-mail",6,255,updateFavsProjTips);
       bValid = bValid && checkRegexp(email, emailRegEx, "Please enter a valid e-mail address.",updateFavsProjTips);
       return bValid;
   }
   
   function getPopular()
   {
       if ( popStart == null ) { popStart = 0; }
       
       var popularUrl = actionPrefix + "findPopular.do?startIndex=" + popStart + "&noIEcache=" + (new Date().getTime());

       openAjaxLoader();
       $.ajax({
               type: "GET",
               url: popularUrl,
               dataType: "json",
               success : function(popResult) { 
                               popular = popResult.projects;

                               searchOptions = new Array();
                               var ids = "";
                               
                               for (var i=0; i < popular.length; i++)
                               {
                                  ids += popular[i].id;
                                  if ( i+1 < popular.length) { ids  += " OR "; }
                               }
                               searchUrl = baseSearchUrl + "&keywords=(" + escape(ids) + ")";

                               getSearchResults(searchUrl, false, showMinimalSearchResults, sortProjectsByVoteCount, null, popularHeader);
                               //closeAjaxLoader();
                           },
               error : function(xOption, status) { 
                       closeAjaxLoader(); 
                       logErrorMessage("getPopular","Error returned from json ajax call. PopularURL: " + popularUrl);
                       alert("We're sorry. The system is having issues. Please try again later."); 
               },
               async: true
       });    
   }
   
   function loadPopular(startIndex)
   {
       if ( startIndex != null ) { popStart = startIndex; } else { popStart = 0; }
        
       $("#centerContent").load("./bodycontent/search.html", null, getPopular);
   }
   
   function sortProjectsByVoteCount(dcResult)
   {
       if ( dcResult.proposals != null && popular != null && dcResult.proposals.length > 0)
       {
           var sortedProposals = new Array();
           var idx = 0; // needs its own index in case a popular project has
           for (var i=0; i < popular.length; i++)
           {
               for(var j=0; j < dcResult.proposals.length; j++)
               {
                   if ( popular[i].id == dcResult.proposals[j].id )
                   {
                       sortedProposals[idx] = dcResult.proposals[j];
                       idx++;
                   }
               }
           }
           dcResult.proposals = sortedProposals;
       }
       else
       {
           return true;
       }
       return false;
   }
   
   function showMinimalSearchResults(dcResult)
   {
       // Clear previous results
       $("#searchCriteriaList").empty();
       $("#pagerTop").empty();
       $("#searchResults").empty();
       $("#pagerBottom").empty();
       
       buildSearchResults(dcResult.proposals);
       getSonicVotes(dcResult.proposals);
   }
   
   function popularHeader()
   {
       $("<tr/>").attr("id","pagerRow").appendTo("#pagerTop");
       
       $("<td/>").append("Most Popular Projects").appendTo("#pagerRow");  
       
       $("<td/>").attr("class","pagesList").appendTo("#pagerRow");      
       if (popStart > 0) 
       {
              $("<a/>").append("&lt; Previous 10").click(function(event){ loadPopular(parseInt(popStart-10,10)); event.preventDefault(); }).appendTo(".pagesList");
              if ( popular.length == 10 ) { $(".pagesList").append("&nbsp; . . . &nbsp;"); }
       }
       if (popular.length == 10)
       {
           var aPg = document.createElement("a");
           $(aPg).click(function(event){ loadPopular(parseInt(popStart+10,10)); event.preventDefault(); });
           $(aPg).append("Next 10 &gt;");
           $(".pagesList").append("&nbsp;").append($(aPg));
       }
       
       // Set bottom pager content to the same as top.
       $("#pagerRow").clone(true).appendTo($("#pagerBottom"));       
   }
   
   function limitText(limitField, limitCount, limitNum) 
   {
    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);
    } else {
        limitCount.value = limitNum - limitField.value.length;
    }
   }

   function selectTextArea(objId)
   {
           document.getElementById(objId).select();
   }
   
    function selectDiv(objId)
    {
        deselectDiv();
        if(document.selection)
        {
            var range = document.body.createTextRange();
            range.moveToElementText(document.getElementById(objId));
            range.select();
        }
        else if (window.getSelection)
        {
            var range = document.createRange();
            range.selectNode(document.getElementById(objId));
            window.getSelection().addRange(range);
        }
    }
    function deselectDiv()
    {
        if(document.selection)
            document.selection.empty();
        else if (window.getSelection)
            window.getSelection().removeAllRanges();
    }
    
   // popup the toolbox dialog box
   function showToolboxDialog(name)
   {
      $('#'+name).dialog('open');
   }
   
   function addDialogButtonStyles()
   {
       $.each($(".ui-dialog-buttonpane > button "), function() {
           var btxt = $(this).html();
           if ( 'Submit Vote' == btxt ||  'Sign Up' == btxt || 'Add' == btxt || 
                'View Favorites' == btxt || 'Send To Friend' == btxt || 'Select Text' == btxt || 'Proceed' == btxt || 
                'Sign Me Up!' == btxt || 'Continue To Cruiser Registration' == btxt )
           {
               $(this).addClass("greenDialogSubmit");
           }
           if ( 'Cancel' == btxt || 'Close' == btxt ||  'No Thanks' == btxt || 'Done' == btxt )
           {
               $(this).addClass("greyDialogCancel");
           }
       });
   }
   
   // create function for flash movie to call to open up the search:
   function openSearch()
   {
        $("#searchProjects").click();
   }
   
   function bindClickHandlers()
   {
       $("#navAccordion").accordion('enable');
       
       // Add handlers for navigation panels
       $("#searchProjects").click( function() {
              closeMap();
           setNavAction("#/searchProjects");
           resetSearch();
           $("#centerContent").load("./bodycontent/search.html", null, function() { getSearchResults(buildSearchUrl()); });
              return false;
       });
       
       $("#howItWorks").click( function() {
              closeMap();
           setNavAction("#/howItWorks");
           $("#centerContent").load("./bodycontent/howItWorks.html",null, function() { embedSwf(); });
           return false;
       });
       
       $("#toolbox").click( function() {
              closeMap();
           $("#navAccordion").accordion('activate',false);
           setNavAction("#/toolbox");
           $("#centerContent").load("./bodycontent/tools.html", null, function(){ addWhyRollovers();});
           return false;
       });
       
       $("#blog").click( function() {
              closeMap();
              $("#navAccordion").accordion('activate',false);
              setNavAction("#/blog");
           $("#centerContent").xslt(blogRSS, "xsl/newsBody.xsl");
           return false;
       });
             
       $("#favoriteProjects").click( function() { 
           closeMap();

               if(navAction != null && navAction.indexOf("#/fundedProjects") == 0)
               {
                   setNavAction("#/favoriteProjects/alreadyFunded");
                   loadFavorites(false);
               }
               else
               {
                      //$("#showActiveFavs").click();
                   setNavAction("#/favoriteProjects");
                      loadFavorites(true); 
               }
           
             return false;
           });
       /*
       $("#mostPopularProjects").click( function() {
              closeMap();
           $("#navAccordion").accordion('activate',false);
           setNavAction("#/mostPopularProjects");
           loadPopular(0);
           return false;
       });
       */
       // Search subnav click handlers
       $(".searchableLink").click( function() {
                      // ensure there is a facet count before adding to search options:
                      if($(this).html().indexOf("facetCount") > -1)
                      { 
                       $("#validateSearchCriteria").empty();
                       optionSearch($(this).attr("searchOptName"), $(this).attr("searchOptVal"), $(this));
                   }
                   return false;
       });

       return false;
   }
   
   function setNavAction(action)
   {
          // analytics call:
          trackView(action);

       if(navigator.appName == "Microsoft Internet Explorer" && navigator.userAgent.indexOf("MSIE 6") != -1)
               hashChangeEnabled = false;
              
          navAction = action;
          
          if(hashChangeEnabled)
               location.hash = navAction;
               
       prevHash = undefined;
       
       // attempt to set the page title according to the current action:
       setPageTitle(navAction);
       
       // attempt to set the 'navActive' class to navAction:
       setNavActive(navAction);
       
          // clear querystring as to not mess up further bookmarking:
       if(window.location.search != "")
       {
               window.location.search = "";
       }
   }
   
   function checkNavChange()
   {
        if(hashChangeEnabled)
        {
           if (location.hash && prevHash == undefined)
           {
               // Page was clean loaded with just index.jsp.  Initialize.
               prevHash = location.hash;
           }
           else if ( location.hash && prevHash != location.hash )
           {
               // Hash has changed without a click handler setting prevHash to undefined (must be browser forward/back buttons).  
               // Reload page so correct click handler will be called.
               prevHash = location.hash;
               
               location.reload();
           }
           else if ( !location.hash && prevHash )
           {
               // Went back to index.jsp. Set hash so we can use forward button.
               location.replace("#/howItWorks");
           }
        }   
    
        // For some reason the My Favorite Projects accordion item doesn't always trigger/listen to the height
        // that I set it to and defaults to what's set in the CSS
        // Created check in this checkNav loop to ensure the nav container stays 31px tall if we know the email address:
        if(signinEmail != null)
        {
            // set height of favoriteProjectsContainer smaller
            $("#favoriteProjectsContainer.ui-accordion-content").height("31px");
        }
        else
        {
            $("#favoriteProjectsContainer.ui-accordion-content").height("150px");
        }
   }
   
   function setNavActive(navAction)
   {
           $(".navActive").removeClass("navActive");
           var actions = navAction.split("/");
           if(actions.length >= 2)
           {
               var primaryAction = navAction.split("/")[1];
               if($("#"+ primaryAction) != null)
               {
                   $("#"+primaryAction).addClass("navActive");
               }
           }
   }
   
   function setPageTitle(selNav)
   {
           var lastSlash = selNav.lastIndexOf("/");
           
        if ( pageTitles[selNav] != null && pageTitles[selNav].length > 0 )
        {
            document.title = pageTitles[selNav];
        }
           else if(lastSlash > 0)
           {
               // try again to find the pageTitle using the parent before going to the default:
               setPageTitle(selNav.substring(0,lastSlash));
           }
        else
        {
            document.title = "Limeades for Learning";
        }
   }
   
   function addWhyRollovers()
   {
          $(".why-popup").click(function() { return false; });
       $(".why-popup").mouseover(function() {  $(this).children("em").stop(true, true).animate({opacity: "show", top: "-100px"}, "slow"); });
       $(".why-popup").mouseout( function() {  $(this).children("em").animate({opacity: "hide", top: "-120px"}, "fast"); });
       $(".why-popup-large").mouseover(function() {  $(this).children("em").stop(true, true).animate({opacity: "show", top: "-170px"}, "slow"); });
       $(".why-popup-large").mouseout( function() {  $(this).children("em").animate({opacity: "hide", top: "-220px"}, "fast"); });
   }
   
   function changeToSonicFunded(buttonId)
   {
           if($("#vote"+buttonId))
           {
               $("#vote"+buttonId).replaceWith(
               $("<div/>").attr("id","fundedButton"+buttonId).attr("style","display:inline;")
                   .append($("<em/>").attr("class","why-popup-sonicFunded").attr("id","em-"+buttonId).attr("style","display:none;").append($("<div/>").attr("style","padding: 10px 10px 10px 10px; color:white; line-height:15px;").html("This project has received $600 in funding from Sonic. But this teacher still needs your help. Click Donate to contribute to the amount still needed.")))
                   .append($("<button/>").attr("class","fundedButton ui-button ui-state-default ui-corner-all"))                   
               );

               $("#fundedButton"+buttonId).unbind("click").click(function() { return false; });
               $("#fundedButton"+buttonId).bind("mouseenter", function() { $("#em-"+buttonId).stop(true, true).animate({opacity: "show", top: "-125px"}, "slow"); });
               $("#fundedButton"+buttonId).bind("mouseleave", function() { $("#em-"+buttonId).animate({opacity: "hide", top: "-140px"}, "fast"); });       
               
           }
   }

   function openAjaxLoader()
   {
           if($("#loadingAjax").dialog('isOpen') == false)
            $("#loadingAjax").dialog('open');
   }
   
   function closeAjaxLoader()
   {
           if($("#loadingAjax").dialog('isOpen') && votePrvntDblSubmit)
               $("#loadingAjax").dialog('close');
   }
   
   function singleLoadProjectCallback()
   {
        getProjectById(lastProjectId);
           lastProjectId = null;
   }
   
    function embedSwf() {
        // embed the swf if there is a swfContent div:
        if($("#swfContent") != null) {
            var params = {};
            params.wmode = "transparent";
                
            var flashvars = {};
            flashvars.video1 = video1;
            flashvars.video2 = video2;
            flashvars.played = hasViewedMovie();
                
            var attributes = {};
            attributes.id = "content";
                
            swfobject.embedSWF ( "tab_cc.swf", "swfContent", "616px", "443px", "9.0.23",null, flashvars, params, attributes );
            
            if ( hasViewedMovie() == false )
            {
                setViewedMovie();
            }
        }
    }

   function setupL4L()
   {
       $.ajaxSetup({
               timeout: 30000
       });
           
       // setup the navigation accordion
       // SFD - removing collapsible because it makes "remove from favorites"
        // look broken by closing favs accordion.
       // $("#navAccordion").accordion({active:false, autoHeight: false,
        // collapsible: true });
       $("#navAccordion").accordion({active:false, autoHeight: false, collapsible: false });

       loadPageTitles();
       loadErrorMessages();
       
       bindClickHandlers();
       
       $('.expandableOptions .expandableOptHeader').click(function() {
           //if($(this).text() == "Location")
           //{
               //    if(searchOptionExists("zone"))
                   //    return false;
           //}
       
           $("#validateSearchCriteria").empty();
           if ( $(this).hasClass("expandableOptHeaderActive") )
           {
              $(this).removeClass("expandableOptHeaderActive");
           }
           else
           {
               $(this).addClass("expandableOptHeaderActive");
           }
           $(this).next().toggle('slow');
           return false;
       }).next().hide();
       
       $('.expandableOptions .expandableOptSubHeader').click(function() {
           $("#validateSearchCriteria").empty();
           // close all other sub categories before opening the selected one.
           $('.expandableOptions .expandableOptSubHeader').next().hide("slow");
           $(this).next().show('slow');
           return false;
       });

       $('.stateListHeader').click(function () { 
           $("#stateListDialog").dialog('open');
       }).next().hide();
       
       // This is called when a state is selected (clicked).
       $("#stateListDialog .searchableLink").click(function() { 
           // ensure there is a facet count before adding to search options:
              if($(this).html().indexOf("facetCount") > -1)
              { 
                   $("#validateSearchCriteria").empty();
                   $("#stateListDialog").dialog('close'); 
           }
       });
       
       $("#favProjForm").submit( function() {
           
           if ( validateFavsProjSignup() )
           {
               signinEmail = $("#favsEmail").val();

               if ( $("#favsProjRememberMe").is(':checked') )
               {
                   setRememberMeCookie(signinEmail);
               }
           
               $("#favsEmail").attr("value","");
               $("#favsProjRememberMe").attr("checked",false);
               loadFavorites(true);
               
               setNavAction("#/favoriteProjects/signin");
           }
           return false;
       });
       

       // Setup the Donors Choose search items
       $("#keywordSearch").submit( function() {
           submitKeywordSearch();
           return false;
       });
       
 
       // Setup display names for searchable links.
       $(".searchableLink").each(  function(i) {
           var queryParam = $(this).attr("searchOptName") + "_" + $(this).attr("searchOptVal");
           searchTermNames[unescape(queryParam)]=$(this).html();
       });  
                   
       
       // Start with all subcategories closed.
       $('.expandableOptions .expandableOptSubHeader').next().hide();
       

       $("#stateListDialog").dialog({
           autoOpen: false,
           bgiframe: true,
           position: "center",
           width: 300,
           height: 400,
           show: 'clip',
           hide: 'clip',
           modal: true,
           close: function() {
           }
       });
   
        
       $("#trackVotes").click( function() {
           if ( $("#trackVotes").is(':checked') )
           {
               $(".showTrackVotes").show();
           }
           else
           {
               $(".showTrackVotes").hide();
           }   
       });
      
      votePrvntDblSubmit = true;

       $("#voteDialog").dialog({
           bgiframe: true,
           autoOpen: false,
           width: 400,
           height: 'auto',
           show: 'clip',
           hide: 'clip',
           modal: true,
           buttons: {
               'Submit Vote': function() { 
                      if ( votePrvntDblSubmit )
                      {
                          disableVoting();
                       submitVote();
                      }
               },
               Cancel: function() {
                      enableVoting();
                   $(this).dialog('close');
               }
           },
           close: function() {
               // clear old votecode from form.
               enableVoting();
               $("#votecode").attr("value","");
               $("#trackEmail").attr("value","");
               $("#trackVotes").attr("checked",false);
               $("#voteRememberMe").attr("checked",false);
               $("#validateVoteTips").empty(); 
               $("#voteForm :input").removeClass('ui-state-error');
               setupVoteRemoveCookieLink();
           }
       });
       
       $('#voteDialog').keypress(function(e) {
            if (e.keyCode == 13) {
               if ( votePrvntDblSubmit )
                   {
                       disableVoting();
                   submitVote();
                   }
               return false;
            }
        });
        
       $("#voteConfirmDialog").dialog({
           bgiframe: true,
           autoOpen: false,
           width: 400,
           height: 'auto',
           show: 'clip',
           hide: 'clip',
           modal: true,
           buttons: {
               'Sign Me Up!':  function() { voteConfirmSignupButton();},
               'No Thanks': function() { voteConfirmDoneButton($(this));}
           }
       });
       
 

       $("#signupDialog").dialog({
           bgiframe: true,
           autoOpen: false,
           width: 350,
           height: 'auto',
           show: 'clip',
           hide: 'clip',
           modal: true,
           buttons: {
               'Sign Up': function() { 
              
                   if ( notificationSignup() ) {
                       return false;
                   }
               },
               Cancel: function() {
                   $(this).dialog('close');
               }
           },
           close: function() {
               $("#notificationSignupForm :input").removeClass('ui-state-error');
                $("#validateSignupTips").empty(); 
           }
       });
          
                 
       $("#signupConfirmDialog").dialog({
           bgiframe: true,
           autoOpen: false,
           width: 350,
           height: 'auto',
           show: 'clip',
           hide: 'clip',
           modal: true,
           close: function() {
           }
       });
       
      
       $("#addToFavsDialog").dialog({
           bgiframe: true,
           autoOpen: false,
           width: 350,
           height: 'auto',
           show: 'clip',
           hide: 'clip',
           modal: true,
           buttons: {
               'Add': function() { 
                   if ( addToFavsSignup() ) {
                       signinEmail = $("#addToFavsEmail").val();
                       addFav();
                       $(this).dialog('close'); 
                       $("#addToFavsForm")[0].reset();
                       
                       return false;
                   }
               },
               Cancel: function() {
                   $(this).dialog('close');
               }
           },
           close: function() {
               $("#addToFavsForm :input").removeClass('ui-state-error');
               $("#validateAddToFavsTips").empty(); 
           }
       });
       
       $("#addToFavsDialog").keypress(function(e) {
            if (e.keyCode == 13) {
                if ( addToFavsSignup() ) {
                     signinEmail = $("#addToFavsEmail").val();
                    addFav();
                    $(this).dialog('close'); 
                    $("#addToFavsForm")[0].reset();
                       
                    return false;
                }
                return false;
            }
        });
       
                  
       $("#addToFavsConfirmDialog").dialog({
           bgiframe: true,
           autoOpen: false,
           width: 350,
           height: 'auto',
           show: 'clip',
           hide: 'clip',
           modal: true,
           buttons: {
               'View Favorites': function() { 
                   $(this).dialog('close');
                   $("#favoriteProjects").click();
                   return false;
               },
               'Close': function() {
                   $(this).dialog('close');
               }
           },
           close: function() {
           }
       });
                     
       $("#showFundedFavs").click( function() {
               var currentSrc = $(this).children("img").attr("src");

               if(currentSrc.indexOf("ON") == -1)
               {
                   loadFavorites(false); 
                   setNavAction("#/favoriteProjects/alreadyFunded");
                   $("#showFundedFavs img").attr("src","images/fb_AF-ON.gif");
                   $("#showActiveFavs img").attr("src","images/fb_NF-OFF.gif");
               }

               return false;
       } );
       
       $("#showActiveFavs").click( function() { 
               var currentSrc = $(this).children("img").attr("src");
               
               if(currentSrc.indexOf("ON") == -1)
               {
                   loadFavorites(true);                
                   setNavAction("#/favoriteProjects/needFunded");
                   $("#showActiveFavs img").attr("src","images/fb_NF-ON.gif");
                   $("#showFundedFavs img").attr("src","images/fb_AF-OFF.gif");
               }
               return false;
       } );
       
       // My Favorite Projects > Needs to be Funded/Already Funded hover stylings:
       $("#activeFundedPrjBtns img").hover( 
           function() {
                  var currentSrc = $(this).attr("src");
                  if(currentSrc.indexOf("ON") == -1)
                  {
                          $(this).attr("src",currentSrc.replace("OFF","OVER"));
                  }
           },
           function () {
               var currentSrc = $(this).attr("src");
                  if(currentSrc.indexOf("ON") == -1)
                  {
                          $(this).attr("src",currentSrc.replace("OVER","OFF"));
                  }
           }
       );
       
       $("#stafDialog").dialog({
           bgiframe: true,
           autoOpen: false,
           width: 400,
           height: 'auto',
           show :'drop',
           hide :'drop',
           modal: true,
           buttons: {
               'Send To Friend': function() { sendToAFriend(actionPrefix+"staf.do"); return false;},
               Cancel: function() {
                   $("#validateStafTips").empty(); 
                   $("#spreadTheWordForm :input").removeClass('ui-state-error');
                   $("#spreadTheWordForm")[0].reset();
                   $(this).dialog('close');
               }
           },
           close: function() {
              $("#validateStafTips").empty(); 
              $("#spreadTheWordForm :input").removeClass('ui-state-error');
           }
       });
       
       $("#stafDialog").keypress(function(e) {
            if (e.keyCode == 13) {
                sendToAFriend(actionPrefix+"staf.do");
                return false;
            }
        });
       
       $("#badgeDialog").dialog({
              bgiframe: true,
              autoOpen: false,
              width: 400,
              height: 'auto',
              show: 'drop',
              hide: 'drop',
              modal: true,
              buttons: {
               'Close': function() {
                       $(this).dialog('close');
               },
                     'Select Text': function() {
                         selectTextArea('badgeCode');
                     }
                  
              }
       });
       
       $("#flierConfirmDialog").dialog({
              bgiframe: true,
              autoOpen: false,
              width: 400,
              height: 'auto',
              show: 'drop',
              hide: 'drop',
              modal: true,
              buttons: {
                    'Proceed': function() {
                            if(validateFlierConfirmForm()) {      
                                trackView("#/toolbox/flyers/success");        
                        $("#flierConfirmForm").submit();
                                $(this).dialog('close');
                            }
                    },
                    'Close': function() {
                            $(this).dialog('close');
                    }
              }
       });
       
        $("#logoDialog").dialog({
              bgiframe: true,
              autoOpen: false,
              width: 400,
              height: 'auto',
              show: 'drop',
              hide: 'drop',
              modal: true,
              buttons: {
                  'Close': function() {
                          $(this).dialog('close');
                  }
              }
       });
       
       $("#sigsDialog").dialog({
              bgiframe: true,
              autoOpen: false,
              width: 400,
              height: 'auto',
              show: 'drop',
              hide: 'drop',
              modal: true,
              buttons: {
                  'Close': function() {
                          $(this).dialog('close');
                  }
              }
       });             
       
       $("#loadingAjax").dialog({
           bgiframe: true,
           autoOpen: false,
           draggable: false,
           width: 100,
           height: 100,
           minHeight: 100,
           dialogClass: 'loadingAjax',
           show: 'fade',
           hide: 'fade',
           modal: true
       });
       
       $("#ie6Dialog").dialog({
           bgiframe: true,
           autoOpen: false,
           draggable: false,
           width: 300,
           height: 'auto',
           dialogClass: 'ie6Dialog',
           show: 'clip',
           hide: 'clip',
           modal: true,
           buttons: {
                   "I'LL WING IT" : function () { 
                       $(this).dialog('close');
                   }
               }
       });
             
       $("#spreadTheWord").click(function() {
           $.scrollTo(0);
           $("#stafProjectId").attr("value","");
           $('#stafDialog').dialog('open');
           return false;
       });
       
       $("#thankyou").click(function() {
            closeMap();
            $("#navAccordion").accordion('activate',false);
            resetSearch();
            setNavAction("#/thankyou");
            $("#centerContent").load("./bodycontent/thankyou.html",null,function() { thankyouPageComplete(); });
            return false;
       });
       
       addWhyRollovers();
       addDialogButtonStyles();
        var qs = new Querystring();
        var project = qs.get("projectId");
        if ( project != null && project.length > 0 )
        {
            // get specific project
            loadProjectContinue = false;
            lastProjectId = project;
            $("#centerContent").load("./bodycontent/search.html",null,singleLoadProjectCallback);
        }
        else
        {
            var selNav =  location.hash;
            if ( selNav != null && selNav.length > 0 )
            {
                // check to see if multi levels were specified (e.g. toolbox/badges) split with /:
                var hashVals = selNav.split("/");
                if($("#"+hashVals[1]) != null)
                {
                    $("#"+hashVals[1]).click();
                }
                location.hash = selNav;
                prevHash = selNav;
                // if loading the funded map we're going ot have to wait for the header swf to fully load before opening
                // display the homepage swf so that the site doesn't look like you're missing flash
                // also if no page title is found for the hashVal passed in, display the swf in the body content
                if(selNav.indexOf("#/fundedProjects") == 0 || pageTitles["#/"+hashVals[1]] == null)
                {
                    embedSwf();
                }
            }
            else
                embedSwf();
        }
        if($.browser.msie)
        {
            if ( $.browser.version.substr(0,1) < 7 )
            {
            	if(!/MSIE 7\.0/i.test(window.navigator.userAgent) 
 	            && !/MSIE 8\.0/i.test(window.navigator.userAgent))
		    $("#ie6Dialog").dialog("open");
            }
        }
        window.setInterval(checkNavChange, 200);        
   }
