// Global Variables
  var map;
  var clusterer;
  var justLoaded = new Boolean(false);

// timerSearch is a global timer set to clear the Search's message window
var timerSearch;
// timerAjaxSearch is a global timer set to keep track of how long it is
// taking for the Geogad server to respond. If it is longer than some
// prefered value, the program redirects the user input to another operation.
var timerAjaxSearch;


// These constants are the same as defined by GeogadConstants
//  MOST_VIEWED = 1;
//  HIGHEST_RATED = 2;             
//  MOST_RECENT = 3;
//  ALPHABETICAL = 4;  
//  LIMIT = 20;

// These global constants are defined based on the data returned from the database for
// the two different functions. Since we can't be sure which gets back first, the 
// page selector is called twice.

var totalNumTS = 0;
var globalCurrentPage = 1;

// This code calls the HTML wait image
  var waitcode = '<center>Getting your data....</center><br/><br/><center><img id="wait_image" alt="Request being processed" src="images/wait.gif" /></center>';

// This code calls the HTML error info
  var errorcode = '<center><h3 style="color: #dd2200; margin: 1em;">Problem Getting Your Data</h3><span style="font-size: 120%; margin: 1em;">Please try again later.</span></center>';

// This code calls the HTML error info
  var noRecCode = '<center><h3 style="color: #dd2200; margin: 1em;">No Matching Tour Stops</h3><span style="font-size: 120%; margin: 1em;">Try expanding your search parameters.</span></center>';

// Create our audio marker icon
var iconA = new GIcon();
iconA.image = "images/markerA.gif";
iconA.shadow = "images/shadow_small.png";
iconA.iconSize = new GSize(12, 20);
iconA.shadowSize = new GSize(22, 20);
iconA.iconAnchor = new GPoint(6, 20);
iconA.infoWindowAnchor = new GPoint(5, 1);

// Create our video marker icon
var iconV = new GIcon();
iconV.image = "images/markerV.gif";
iconV.shadow = "images/shadow_small.png";
iconV.iconSize = new GSize(12, 20);
iconV.shadowSize = new GSize(22, 20);
iconV.iconAnchor = new GPoint(6, 20);
iconV.infoWindowAnchor = new GPoint(5, 1);



/* first set of options is for the visual overlay.*/
  var boxStyleOpts = {
//    opacity:.2,
//    border:"2px solid red"
  }

  /* second set of options is for everything else */
  var otherOpts = {
          buttonStartingStyle: {display:'block',color:'black',background:'white',width:'7em',textAlign:'center',
            fontFamily:'Verdana',fontSize:'12px',fontWeight:'bold',border:'1px solid gray',cursor:'pointer'},
    buttonHTML:"<img src='images/viewmag+.png' />",
    buttonStyle:{width:'32px', background:'transparent', border:'none', marginLeft:'10px'},
          buttonZoomingHTML: 'Drag a region on the map (click here to reset)',
          buttonZoomingStyle: {background:'#FFFFC8', marginLeft:'5px'},
    backButtonHTML:"<img src='images/viewmag-.png' />",
     backButtonStyle: {width:'32px', background:'transparent', display:'none', border:'none', marginLeft:'10px'},
          backButtonEnabled: true, 
          overlayRemoveTime: 1500
  };

  /* third set of options specifies callbacks */
  var callbacks = {
//    buttonclick:function(){display("Looks like you activated DragZoom!")},
//    dragstart:function(){display("Started to Drag . . .")},
//    dragging:function(x1,y1,x2,y2){display("Dragging, currently x="+x2+",y="+y2)},
//    dragend:function(nw,ne,se,sw,nwpx,nepx,sepx,swpx){display("Zoom! NE="+ne+";SW="+sw)}
  };
 	

function searchWaitMessage(infoBox, topBox, bottomBox) {
	searchClearTimers();

//var ce = document.getElementById("check_error");
//ce.innerHTML += "<br/> In searchWaitMessage   ";
//ce.innerHTML += " infoBox = "+infoBox+" topBox = "+topBox+" bottomBox = "+bottomBox+"<br/>";


	clearTSDisplay(infoBox, topBox, bottomBox);
	var rt = document.getElementById(infoBox);
	rt.innerHTML = waitcode;
}

function searchProblemMessage(infoBox, topBox, bottomBox) {
	searchClearTimers();

//var ce = document.getElementById("check_error");
//ce.innerHTML += "<br/> In  searchProblemMessage  ";
//ce.innerHTML += " infoBox = "+infoBox+" topBox = "+topBox+" bottomBox = "+bottomBox+"<br/>";

	clearTSDisplay(infoBox, topBox, bottomBox);
	var rt = document.getElementById(infoBox);
	rt.innerHTML = errorcode;
}

function searchNoRecMessage(infoBox, topBox, bottomBox) {
	searchClearTimers();

//var ce = document.getElementById("check_error");
//ce.innerHTML += " <br/>In searchNoRecMessage   ";
//ce.innerHTML += " infoBox = "+infoBox+" topBox = "+topBox+" bottomBox = "+bottomBox+"<br/>";

	clearTSDisplay(infoBox, topBox, bottomBox);
	var rt = document.getElementById(infoBox);
	rt.innerHTML = noRecCode;
}


function searchClearMessage(infoBox, topBox, bottomBox) {
	searchClearTimers();

//var ce = document.getElementById("check_error");
//ce.innerHTML += "<br/> In searchClearMessage   ";
//ce.innerHTML += " infoBox = "+infoBox+" topBox = "+topBox+" bottomBox = "+bottomBox+"<br/>";


	clearTSDisplay(infoBox, topBox, bottomBox);
	var rt = document.getElementById(infoBox);
	rt.innerHTML = '';
}

function searchClearTimers() {
// free callback timer here
   window.clearTimeout(timerSearch);
   window.clearTimeout(timerAjaxSearch);
}


function isAjaxSupportedSearch() {
// Check if request can be created by is not used
   var request = null;
   if(typeof window.XMLHttpRequest != 'undefined')
   {
     request = new XMLHttpRequest();
   }
   else if(typeof window.ActiveXObject != 'undefined')
   {
     try { request = new ActiveXObject('Microsoft.XMLHTTP'); }
     catch(err) { request = null; }
   }
   if (request != null)
   	return(true); 
   else 
   	return(false); 
}


function onLoad() {
  var points = [];
  var route;
  

//var ce = document.getElementById("check_error");
//ce.innerHTML += "Inside onLoad";
//ce.innerHTML += " Init_Point_Data = " + Init_Point_Data;
//ce.innerHTML = " Init_TSInfo = " + Init_TSInfo;

    if (GBrowserIsCompatible()) {

	var xcenter = 0;
	var ycenter = -122.419;
        if (typeof origMainLat != 'undefined') 
		if (!isNaN(origMainLat)) 
			 xcenter = origMainLat;
        if (typeof origMainLon != 'undefined') 
		if (!isNaN(origMainLon)) 
			 ycenter = origMainLon;
	if ((xcenter == 0) && (ycenter == -122.419)) { 
        	if (typeof origCoords != 'undefined') {
			if (!isNaN(origCoords[4]))
				xcenter = origCoords[4];
			if (!isNaN(origCoords[5]))
				ycenter = origCoords[5];
		}
	}

	var mainZoom = 1;
        if (typeof origMainZoom != 'undefined') 
		if (!isNaN(origMainZoom)) 
			 mainZoom = parseInt(origMainZoom, 10);

    	map = new GMap2(document.getElementById("map"));

	map.setCenter(new GLatLng(xcenter, ycenter), mainZoom);

 	var mainType = "G_NORMAL_MAP";  
        if (typeof origMainType != 'undefined') 
		if (origMainType.length > 0) {
			mainType = origMainType;
		}
	if (mainType == "G_NORMAL_MAP")
		map.setMapType(G_NORMAL_MAP);
	else if (mainType == "G_SATELLITE_MAP")
		map.setMapType(G_SATELLITE_MAP);
	else if (mainType == "G_HYBRID_MAP")
		map.setMapType(G_HYBRID_MAP);

    	map.addControl(new GSmallMapControl());
	var bottomRight = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(2, 2));
    	map.addControl(new GMapTypeControl(), bottomRight);
        map.addControl(new DragZoomControl(boxStyleOpts, otherOpts, callbacks));

	var displayNumTS = document.getElementById("mainNumTS");
	displayNumTS.innerHTML = " <span class='numTitle'>Total Found:</span> 0 tour stops";
   	clusterer = new Clusterer( map ); 
	clusterer.SetCountBox("mainNumTS");
	clusterer.SetDisplayInfoBox("tsMainInfoDisplay");
	clusterer.SetTopPageSelector("topPageSelector");
	clusterer.SetBottomPageSelector("bottomPageSelector");

    } else {
	var missingmap = "http://www.geogad.com/geogad/gmapmissing";
        if (typeof mapErrorPage != 'undefined') 
		if (mapErrorPage != null) 
			 missingmap = mapErrorPage;
	window.location = missingmap;
    }

    // Load initial data from page data
    justLoaded = new Boolean(true);
    plotMainMapPoints(Init_Point_Data);
    searchClearTimers();
    timerSearch = window.setTimeout( 'displayTSInfoMainMap(Init_TSInfo)', 700 );

}

// Ajax and Main program version
function plotMainMapPoints(data) {

//var d = new Date();
//var diff = d.getTime();
//var ce = document.getElementById("check_error");
//ce.innerHTML += "<br/>Inside plotMainMapPoints Time = "+diff;
//ce.innerHTML += " Init_Point_Data = " + data + "<br/>";

   searchClearTimers();

// check for returned data
   if ((data == "") || (data == null)) {
	searchProblemMessage("tsMainInfoDisplay", "topPageSelector", "bottomPageSelector");
        return;
   }


   var str = eval( '(' + data + ')' );
//   var str =  data
//ce.innerHTML += "<br/> End time = "+d.getTime()+"   Time diff = "+(d.getTime() - diff);
//
// data comes in as a JSON object
   var thisFormat = str.Format;
   var thisLimit = str.Limit;
   var thisOffset = str.Offset;
   var thisSWX = str.swx;
   var thisSWY = str.swy;
   var thisNEX = str.nex;
   var thisNEY = str.ney;
   var thisNickname = str.Nickname;
   var numRecords = str.NumRecords;

//----------------------------------------------------------------------------

// Need to remove all map points

   if (numRecords <= 0 ) {
	clusterer.RemoveAll();
	searchClearMessage("tsMainInfoDisplay", "topPageSelector", "bottomPageSelector");
        return;	
   } 
//-----------------------------------------------------------------------------


   // Load new tour stop info into node
   var i;
   var results = str.Results;
   for (i in str.Results) {

   	var tsid = results[i].TourStopID;
   	var author = results[i].Author;
   	var date = results[i].Date;
   	var name = results[i].Name;
   	var lat = results[i].Lat;
   	var lon = results[i].Long;
   	var mylat = parseFloat(lat);
   	var mylong = parseFloat(lon);

   	var format = results[i].Format;
   	var length = results[i].Length;

   	var shortTitle = (name==null ? 'Tour Stop'+i : name);
   	var popupTitle = '<div class="markerBlock" >';

   	popupTitle += '<div class="tsInfoTitle"><a class="plain" href="tourstop?tsid='+tsid+'">'+shortTitle+'</a></div>';
   	popupTitle += '<div class="photoBlock"><a  class="plain" href="tourstop?tsid='+tsid+'">';
   	var imgFile = BaseURL + tsid + "/JPG/" + tsid + "_0small.jpg";
   	if (format.indexOf("audio") != -1)
 		popupTitle += '<img class="tsInfoPicAudio" alt="Click here to go to '+shortTitle+' listing."  src="'+imgFile+'" />';
   	else
 		popupTitle += '<img class="tsInfoPicVideo" alt="Click here to go to '+shortTitle+' listing."  src="'+imgFile+'" />';
   	popupTitle += '</a></div>';
   	popupTitle += '<div class="markerInfo" >';
   	popupTitle += 'From: <a class="plain" href="user?cid='+author+'">'+author+'</a><br/>';
   	popupTitle += 'Added: '+date+'<br/>';
   	if (format.indexOf("audio") != -1) 
   		popupTitle += 'Format: Audio<br/>';
   	else
   		popupTitle += 'Format: Video<br/>';
   	popupTitle += 'Time: '+ length;

	popupTitle +=  '</div></div>';

	shortLink = '<a class="plain" href="tourstop?tsid='+tsid+'">'+shortTitle+'</a>';	

    	if (isNaN(mylat) || isNaN(mylong)) { 
		//	Problem; just skip
    	} else {
		addmarker(lat, lon, popupTitle, shortLink, shortTitle, format, tsid);
    	}
   }
}


function addmarker(lat, lon, title, link, shortT, format, tsID) {

//var ce = document.getElementById("check_error");
//ce.innerHTML += "<br/> In addmarker";

	var mypoint = new GLatLng(lat, lon);
	var iconFinal = iconA;
	if (format.indexOf("audio")!=-1)
		iconFinal = iconA;
	else	
		iconFinal = iconV;
	var newmarker = new GMarker(mypoint, {title: shortT, icon: iconFinal});
	clusterer.AddMarker( newmarker, shortT, link, title, tsID );
//ce.innerHTML += " Out of addmarker";

}




function displayTSInfoMainMap(data) {   

//var ce = document.getElementById("check_error");
//ce.innerHTML += " Checking In displayTSInfoMainMap";
//ce.innerHTML = " Checking In displayTSInfoMainMap: data = "+data;
//ce.innerHTML += " -----------------------------------------";

   justLoaded = false;

   searchClearTimers();

// check for returned data
   if ((data == "") || (data == null)) {
	searchProblemMessage("tsMainInfoDisplay", "topPageSelector", "bottomPageSelector");
        return;
   }
 //                       var ce = document.getElementById("check_error");                     
 //         ce.innerHTML = "<xmp>  <pre><code>" + data.Limit + "</code></pre> </xmp>";
   var str = eval( '(' + data + ')' );
//   var str =  data.parseJSON(); ;
//   var str = data.toJSONString();
//          ce.innerHTML += "<xmp>  <pre><code>" + str.Limit + "</code></pre> </xmp>";

//   var str = data;

// data comes in as a JSON object
   var thisFormat = str.Format;
   var thisLimit = str.Limit;
   var thisOffset = str.Offset;
   var thisSWX = str.swx;
   var thisSWY = str.swy;
   var thisNEX = str.nex;
   var thisNEY = str.ney;
   var thisNickname = str.Nickname;
   var numRecords = str.NumRecords;

//----------------------------------------------------------------------------

// display pages of info in tsMainInfoDisplay

//ce.innerHTML += " <br/>Checking In displayTSInfoMainMap numRecords = "+numRecords;

   if (numRecords <= 0 ) {
//ce.innerHTML += " noRecCode should be sent";

//var ce = document.getElementById("check_error");
//ce.innerHTML += " <br/>In searchNoRecMessage   ";
//ce.innerHTML += " infoBox = "+infoBox+" topBox = "+topBox+" bottomBox = "+bottomBox+"<br/>";
	searchNoRecMessage("tsMainInfoDisplay", "topPageSelector", "bottomPageSelector");
        return;	
   } 
//-----------------------------------------------------------------------------

//ce.innerHTML += " Before addPageNum";
// Set global variables and format page selector
globalPageLength = thisLimit;
globalCurrentPage = Math.floor(thisOffset / thisLimit) + 1;
addPageNum(totalNumTS, globalPageLength, globalCurrentPage, "tsMainInfoDisplay", "topPageSelector", "bottomPageSelector");

   // Clear any children previously created for this node
   var tsinfoMain = document.getElementById("tsMainInfoDisplay");
   removeChildrenRecursively(tsinfoMain);

   // Load new tour stop info into node
   var i = 0;
   var results = str.Results;
   for (i in str.Results) {

   if (i > 0) {
        var linediv = document.createElement('div');
        linediv.setAttribute('class','indivTSInfo'); 
        linediv.setAttribute('className','indivTSInfo'); 
        tsinfoMain.appendChild(linediv);   
    }

   	var tsid = str.Results[i].TourStopID;
   	var tsDivText = FormatTSBox(str.Results[i]);
	displayTourStop(tsid, tsDivText, "tsMainInfoDisplay");


   }


   // Kludge because IE and Opera have issues with dynamic boxes and inserting divs as separating lines
   var browser=navigator.appName;
   if ((browser=="Microsoft Internet Explorer")||(browser=="Opera"))
   {
   	// Set the height of the TS Display Box based on the number of TS
	i = parseInt(i,10);
   	var boxHeight =  MIN_DISPLAY_BOX_HEIGHT * (2*i+1); 
   	if (boxHeight > 1470) { boxHeight = 1470; }
   	tsinfoMain.style.height = boxHeight+"px";
	tsinfoMain.style.overflow = 'auto';
   }
	

//ce.innerHTML += " Out displayTSInfoMainMap ";

}	


function FormatTSBox(str) {
   
//var ce = document.getElementById("check_error");
//ce.innerHTML += " In FormatTSBox"; 

   // Problem getting data
   if (str == null) { return(null); }


   var tsid = str.TourStopID;
   var author = str.Author;
   var date = str.Date;
   var name = str.Name;
   var shortDescr = str.ShortDescr;
   var longDescr = str.LongDescr;
   var format = str.Format;
   var length = str.Length;
   var tempRating = parseFloat(str.Rating);
   var tempNumRating = parseInt(str.NumRating, 10);
   var rating = -1.0;
   var numRating = -1;
   var prevView = str.PrevViewed;


   if (!isNaN(tempRating)) 
	rating = parseFloat(tempRating);
   if (!isNaN(tempNumRating)) 
   	numRating = parseInt(tempNumRating, 10);

   var result = '';

   title = (name.length < 1) ? 'Tour Stop '+tsid : name;

   result += '<div id="ts'+tsid+'" class="indivTSInfo"  style="text-align:left; border:none;" >';
   result += '<div class="tsInfoTitle"><a class="plain" href="tourstop?tsid='+tsid+'">'+title+'</a></div>';
   result += '<div class="photoBlock" style="float:left;"><a class="plain" href="tourstop?tsid='+tsid+'">';

   var imgFile = BaseURL + tsid + "/JPG/" + tsid + "_0small.jpg";
   if (format.indexOf("audio") != -1)
 	result += '<img class="tsInfoPicAudio" alt="Click here to go to '+title+'."  src="'+imgFile+'" />';
   else
 	result += '<img class="tsInfoPicVideo" alt="Click here to go to '+title+'."  src="'+imgFile+'" />';

   result += '</a></div>';

// Check if we need both descriptions
   if (shortDescr != null)
	if (shortDescr.length >= 1)
   		if (longDescr != null)
			if (longDescr.length >= 1)
				if (shortDescr.length >= longDescr.length) {
// Replace any single quotes ("'" with "\'" );                                    
                                     
//shortDescr = shortDescr.replace(/'/g, "\'");

result += '<div class="tsDescInfo" style="width:180px;">';
result += '<span class="tsDescText" >'+shortDescr+'</span></div>';

				} else {
					// Include both descriptions
//shortDescr = shortDescr.replace(/'/g, "\'");
//longDescr = longDescr.replace(/'/g, "\'");

result += '<div class="tsDescInfo" style="width:180px;">';
result += '<span class="tsDescText" id="shortDescTS'+tsid+'" name="shortDescTS'+tsid+'" style="display:inline; visibility: visible">'+shortDescr+'...</span>';
result += '<span class="tsDescText" id="longDescTS'+tsid+'" name="longDescTS'+tsid+'" style="display:none; visibility: hidden">'+longDescr+'</span>';
result += '<br/>';
result += '<span id="smallLinkTS'+tsid+'" name="smallLinkTS'+tsid+'" style="display:inline; visibility: visible" class="moreClick" ';  
result += ' onmouseover="this.style.textDecoration=\'none\'; this.style.cursor=\'pointer\'"  onmouseout="this.style.textDecoration=\'underline\'; this.style.cursor=\'auto\';" ';
result += ' onClick="toggle_visible(\'shortDescTS'+tsid+'\', \'longDescTS'+tsid+'\'); toggle_visible(\'smallLinkTS'+tsid+'\', \'longLinkTS'+tsid+'\'); "  >(more info)</span> ';
result += '<span id="longLinkTS'+tsid+'" name="longLinkTS'+tsid+'" style="display:none; visibility: hidden" class="moreClick" ';
result += ' onmouseover="this.style.textDecoration=\'none\';  this.style.cursor=\'pointer\'"  onmouseout="this.style.textDecoration=\'underline\'; this.style.cursor=\'auto\';" '; 
result += ' onClick="toggle_visible(\'longDescTS'+tsid+'\', \'shortDescTS'+tsid+'\'); toggle_visible(\'longLinkTS'+tsid+'\', \'smallLinkTS'+tsid+'\'); "  >(less info) </span> ';

result += '</div>';
				}

   result += '<div class="tsInfoBlock" >';
   
   if (prevView != null)
	if (prevView)
		   result += '<span class="boldcenter">[Previously Viewed]</span><br/>';
   
   result += 'From: <span class="regLink"><a class="plain" href="user?cid='+author+'">'+author+'</a></span><br/>';
   result += 'Added: '+date+'<br/>';
   if (format.indexOf("audio") != -1) 
   	result += 'Format: Audio<br/>';
   else
   	result += 'Format: Video<br/>';
   result += 'Time: '+ length +'<br/><br/>';

   // Check for ratings
//   if (numRating > 0) {
	numFullStars = parseInt(rating, 10);
	numHalfStars = rating - numFullStars;
	if (numHalfStars >= 0.5)
		numHalfStars = 1;
	else 
		numHalfStars = 0;
	totalStars = 0;
//	result += '<div style="white-space: nowrap">';
   	for (i=0; i<numFullStars; i++) {
//		result += '<img class="stars" alt="Full star"  src="images/full_star.gif" />'
		totalStars++;
	}
	if (numHalfStars >= 1) {
//		result += '<img class="stars" alt="Half star"  src="images/half_star.gif" />'
		totalStars++;
	}
	numEmptyStars = 5 - totalStars;
//   	for (i=0; i<numEmptyStars; i++) 
//		result += '<img class="stars" alt="No star"  src="images/empty_star.gif" />'
//	if (numRating > 1) 
//		result += '<br/>' + numRating + ' Ratings';
//	else
//		result += '<br/>' + numRating + ' Rating';
	
//	result += '</div>';

//   }



   result += '</div><div style="clear:both"></div>';
//ce.innerHTML += " result4 is OK = <XMP> "+result+" </XMP>"; 


   return(result);

}

 
// Dynamically creates a TS Display box for the formatted data 
// and appends it to the bottom of the main display box
function displayTourStop(tsid, str, infoBox) {

   if ((str == null) || (str.length < 1)) {
   	return;
   } 
   if (tsid < 0) {
   	return;
   } 

   var box = document.getElementById(infoBox);

   var newdiv = document.createElement('div');
   var divIdName = 'tsDiv'+tsid;
   newdiv.setAttribute('id',divIdName);
   newdiv.setAttribute('name',divIdName);

   newdiv.setAttribute('class','TSDragBlock'); 
   newdiv.setAttribute('className','TSDragBlock'); 
   newdiv.innerHTML = str;

   // Append new child node to tsInfoMain
   box.appendChild(newdiv);

}

function addPageNum(numTS, pageLength, commentCurrentPage, infoBox, topBox, bottomBox) {

setCoords();

   var commentsReturnCount = numTS;
   var totalCommentPages = Math.ceil(numTS / pageLength);
   var commentPageSelectCode = "";

//var ce = document.getElementById("check_error");
//ce.innerHTML += " In addPageNum";
//ce.innerHTML += "numTS = "+numTS+" pageLength = "+pageLength+" totalCommentPages = "+totalCommentPages+"<br/>";
//ce.innerHTML += " numTS / pageLength = "+ (numTS / pageLength) + " totalCommentPages = "+totalCommentPages+"<br/>"; 
//ce.innerHTML += " commentCurrentPage = "+commentCurrentPage;

//ce.innerHTML += " infoBox = "+infoBox+" topBox = "+topBox+" bottomBox = "+bottomBox+"<br/>";


    if ((commentsReturnCount > 0) && (totalCommentPages >= 2)) {        
        commentPageSelectCode += "<div><div class='leftPage'>";
        commentPageSelectCode += "<span class='dots'>Page:</span>";                        
        if (commentCurrentPage > 3) {
            // Print out
            commentPageSelectCode += "<span class='go2Page' title='Newest Page' ";
            commentPageSelectCode += "onmouseover='this.style.borderBottom=\"none\"; this.style.cursor=\"pointer\";' onmouseout='this.style.borderBottom=\"1px solid #0000ff\"; this.style.cursor=\"auto\";' "; 
            commentPageSelectCode += "onclick='getNewTSPage( 1, \""+infoBox+"\");' "; 
            commentPageSelectCode += ">Newest</span>";
            commentPageSelectCode += "<span class='dots'>...</span>";
        }


        if ((commentCurrentPage-2) > 0) {
            commentPageSelectCode += "<span class='go2Page' title='Page "+(commentCurrentPage-2)+"'";
            commentPageSelectCode += "onmouseover='this.style.borderBottom=\"none\"; this.style.cursor=\"pointer\";' onmouseout='this.style.borderBottom=\"1px solid #0000ff\"; this.style.cursor=\"auto\";' "; 
            commentPageSelectCode += "onclick='getNewTSPage( "+(globalCurrentPage-2)+", \""+infoBox+"\");' "; 
            commentPageSelectCode += ">"+(commentCurrentPage-2)+"</span>";
        }
        if ((commentCurrentPage-1) > 0) {
            commentPageSelectCode += "<span class='go2Page' title='Page "+(commentCurrentPage-1)+"' ";
            commentPageSelectCode += "onmouseover='this.style.borderBottom=\"none\"; this.style.cursor=\"pointer\";' onmouseout='this.style.borderBottom=\"1px solid #0000ff\"; this.style.cursor=\"auto\";' "; 
            commentPageSelectCode += "onclick='getNewTSPage( "+(globalCurrentPage-1)+", \""+infoBox+"\");' "; 
            commentPageSelectCode += ">"+(commentCurrentPage-1)+"</span>";
        }        
            commentPageSelectCode += "<span class='currentPage' title='Current Page'>"+commentCurrentPage+"</span>";
        if ((commentCurrentPage+1) <= totalCommentPages) {
            commentPageSelectCode += "<span class='go2Page' title='Page "+(commentCurrentPage+1)+"' ";
            commentPageSelectCode += "onmouseover='this.style.borderBottom=\"none\"; this.style.cursor=\"pointer\";' onmouseout='this.style.borderBottom=\"1px solid #0000ff\"; this.style.cursor=\"auto\";' "; 
            commentPageSelectCode += "onclick='getNewTSPage( "+(globalCurrentPage+1)+", \""+infoBox+"\");' "; 
            commentPageSelectCode += ">"+(commentCurrentPage+1)+"</span>"; 
        } 
        if ((commentCurrentPage+2) <= totalCommentPages) {
            commentPageSelectCode += "<span class='go2Page' title='Page "+(commentCurrentPage+2)+"' ";
            commentPageSelectCode += "onmouseover='this.style.borderBottom=\"none\"; this.style.cursor=\"pointer\";' onmouseout='this.style.borderBottom=\"1px solid #0000ff\"; this.style.cursor=\"auto\";' "; 
            commentPageSelectCode += "onclick='getNewTSPage( "+(globalCurrentPage+2)+", \""+infoBox+"\");' "; 
            commentPageSelectCode += ">"+(commentCurrentPage+2)+"</span>";            
        } 
        if ((commentCurrentPage+3) <= totalCommentPages) {
            commentPageSelectCode += "<span class='dots'>...</span>";                
            commentPageSelectCode += "<span class='go2Page' title='Oldest Page' ";
            commentPageSelectCode += "onmouseover='this.style.borderBottom=\"none\"; this.style.cursor=\"pointer\";' onmouseout='this.style.borderBottom=\"1px solid #0000ff\"; this.style.cursor=\"auto\";' "; 
            commentPageSelectCode += "onclick='getNewTSPage( "+totalCommentPages+", \""+infoBox+"\");' "; 
            commentPageSelectCode += ">Oldest</span>";
        } 
        commentPageSelectCode += "</div><div class='rightPage'>";    
        if ((commentCurrentPage-1) > 0) {
            commentPageSelectCode += "<span class='go2Page' title='Previous Page' ";
            commentPageSelectCode += "onmouseover='this.style.borderBottom=\"none\"; this.style.cursor=\"pointer\";' onmouseout='this.style.borderBottom=\"1px solid #0000ff\"; this.style.cursor=\"auto\";' "; 
            commentPageSelectCode += "onclick='getNewTSPage( "+(globalCurrentPage-1)+", \""+infoBox+"\");' "; 
            commentPageSelectCode += ">Prev</span>";
        }        
        if ((commentCurrentPage+1) <= totalCommentPages) {
            commentPageSelectCode += "<span class='go2Page' title='Next Page' ";
            commentPageSelectCode += "onmouseover='this.style.borderBottom=\"none\"; this.style.cursor=\"pointer\";' onmouseout='this.style.borderBottom=\"1px solid #0000ff\"; this.style.cursor=\"auto\";' "; 
            commentPageSelectCode += "onclick='getNewTSPage( "+(globalCurrentPage+1)+", \""+infoBox+"\");' "; 
            commentPageSelectCode += ">Next</span>";                
        }  


        commentPageSelectCode += "</div>";     
 //       commentPageSelectCode += "</div>"; 
        commentPageSelectCode += "<div style='clear:both'></div>";
    
    }

 
   var elem = document.getElementById(bottomBox);
   elem.innerHTML = commentPageSelectCode;
   elem = document.getElementById(topBox);
   elem.innerHTML = commentPageSelectCode;

//var ce = document.getElementById("check_error");
//ce.innerHTML += "<br/> result4 is OK = <XMP> "+commentPageSelectCode+" </XMP>"; 

}

// This function relies on the array visibleTS for this clusterer 
// which lists the visible markers.
// The only other required data is the pageNumber, the timePeriod
// and the ordering.
function getNewTSPage(pageNum, box) {
//var ce = document.getElementById("check_error");
//ce.innerHTML += " In getNewTSPage justLoaded = "+justLoaded;

   if (justLoaded) {
   	justLoaded = new Boolean(false);
	return;
   }

//ce.innerHTML += " After justLoaded check ";

   var functionCall;
   if (box.indexOf("tsMainInfoDisplay") != -1)
   	functionCall = displayTSInfoMainMap;

// Calculate offset for this page
   var offset = (pageNum - 1) * globalPageLength;
//ce.innerHTML += " offset= "+offset;

   if (isAjaxSupportedSearch()) {
//ce.innerHTML += " In isAjaxSupportedPage ";	

   if (typeof origTagSearch == 'undefined') 
	origTagSearch = '';
   if (typeof origCoords == 'undefined') 
	origCoords = '';
   if (typeof origAuthors == 'undefined') 
	origAuthors = '';
   if (typeof origNickname == 'undefined') 
	origNickname = '';
   if (typeof origFormat == 'undefined') 
	origFormat = '';
   if (typeof origTimePeriod == 'undefined') 
	origTimePeriod = '';


//ce.innerHTML += " origTagSearch = ["+origTagSearch+"]";

//ce.innerHTML += " <br/> clusterer.visibleTS.length = ["+clusterer.visibleTS.length+"]";

//	for ( i = 0; i < clusterer.visibleTS.length; i++) {
//ce.innerHTML += " MarkerCall ("+i+") = "+clusterer.visibleTS[i];
//	}

			
//ce.innerHTML += " Before JGetTagInfo.getSearchTSTotal ";
      
// Added the 2JS boolean on Oct 31, 2009 - only way to call it      
JGetTagInfo.getSearchTSTotal(null, clusterer.visibleTS, null, null, null, origNickname, null, origTimePeriod, origOutputFormat, globalPageLength, offset, false, false, true, false, true, null, "tourstops", SID, functionCall);
	searchClearTimers();


	searchWaitMessage("tsMainInfoDisplay", "topPageSelector", "bottomPageSelector");
	timerAjaxSearch = window.setTimeout('searchProblemMessage("'+box+'")', 60000); 
   } else { 
//ce.innerHTML += " In NOT isAjaxSupportedPage ";
// tourstops?cp=2  or tourstops?tags=something&cp=2&authors=Geogad
	var newURL;
        var fullURL = window.location.href;
	var params = gpn(fullURL);
//ce.innerHTML += " params.length =  "+params.length;
	if (params.length > 0) {
// There are parameters
// Rebuild URL with found parameters and without any #text info
		var paramsStart = fullURL.indexOf("?");
        	newURL = fullURL.substring(0, paramsStart);
		newURL += "?cp=" + pageNum;;
		for (i in params) 
			if (params[i].indexOf("cp") < 0 )
				newURL += (((i%2) == 0) ? "&" : "=") + params[i];


//				newURL += "&" + params[i] + "=" + params[i+1];
//			i = i+1;
//ce.innerHTML += " newURL =  "+newURL;

//		}
	} else { // There are no params
		// Check for ending # and text

		var regexS = "#[\\w]*$";  
		var regex = new RegExp( regexS );  
		var results = regex.exec( fullURL );  
		if( results != null ) {
			var paramsStart = fullURL.lastIndexOf(results);
        		fullURL = fullURL.substring(0, paramsStart);
			
		} 
		if (fullURL.indexOf("?") > 0)
			newURL = fullURL + "&cp=" + pageNum;
		else 
			newURL = fullURL + "?cp=" + pageNum;				
	} 
//ce.innerHTML += " Final newURL =  "+newURL;

        document.location.href=newURL;

   } 
//ce.innerHTML += " Out getNewTSPage ";

}



// From http://www.netlobo.com/comments/url_query_string_javascript
// gpn stands for 'get parameter names'

function gpn(fullURL) 
{
	var params = new Array( );
	var regex = /[?&=]([^&=#]+)/g;;   //  /[\?&]([^=]+)=/g;
	while( ( results = regex.exec( window.location.href ) ) != null )
		params.push( results[1] );
	return params;
}

// Refreshes the map box coordinates to be passed to the main search programs.
// Uses the coords of the Main Search Map.
function setCoords() {
//var ce = document.getElementById("check_error");
//ce.innerHTML += " In DisplayCount   ";

    // Get the current bounds of the visible area.
    var bounds = map.getBounds();

    // Expand the bounds a little, so things look smoother when scrolling
    // by small amounts.
    var sw = bounds.getSouthWest();
    var ne = bounds.getNorthEast();


   var fullLat = bounds.isFullLat();
   var fullLon = bounds.isFullLng();
   var x_center = bounds.getCenter().lat();
   var y_center = bounds.getCenter().lng();

// Set coords to be read into search program
   var nelat = document.getElementById("ne_lat");
   var nelon = document.getElementById("ne_lon");
   var swlat = document.getElementById("sw_lat");
   var swlon = document.getElementById("sw_lon");
   var xcoord = document.getElementById("clat");
   var ycoord = document.getElementById("clng");

   if (fullLat && fullLon) {
   	nelat.value = '';
   	nelon.value = '';
   	swlat.value = '';
   	swlon.value = '';
	xcoord.value = '';
	ycoord.value = '';
   } else {
   	nelat.value = ne.lat();
   	nelon.value = ne.lng();
   	swlat.value = sw.lat();
   	swlon.value = sw.lng();
	xcoord.value = x_center;
	ycoord.value = y_center;
   }
//ce.innerHTML += " Out DisplayCount   ";


}

function clearTSDisplay(infoBox, topBox, bottomBox) {

//var ce = document.getElementById("check_error");
//ce.innerHTML += " In clearTSDisplay   ";
//ce.innerHTML += " infoBox = "+infoBox+" topBox = "+topBox+" bottomBox = "+bottomBox+"<br/>";


   	var tsinfoMain = document.getElementById(infoBox);

   	// Clear any children previously created for this node
   	removeChildrenRecursively(tsinfoMain);

	// Resize box
   	var boxHeight = MIN_DISPLAY_BOX_HEIGHT;
   	tsinfoMain.style.height = boxHeight;

	// Get rid of page selector
	addPageNum(0, 10, 1, infoBox, topBox, bottomBox);

}


function formdata(form) {

//var ce = document.getElementById("check_error");
//ce.innerHTML += " In formdata   ";

// Build a complete URL for the history

   var fullURL = window.location.href;
   var paramsStart = fullURL.indexOf("?");
   if (paramsStart > 0)
   	fullURL = fullURL.substring(0, paramsStart);

   // Doesn't send the page number ("cp") so that first page should always load
   // "pid" is only needed if JS fails.
//   var params = new Array( "sw_lat", "sw_lon", "ne_lat", "ne_lon", "clat", "clng",
   var params = new Array( "cid", "orderBySelect", "timeSelect", "formatSelect" );

   var endString = '';

   for ( i in params ) {
   	var item = document.getElementById(params[i]);
	if (item.value != null)
		if (item.value.length > 0)
			endString += params[i] + "=" + encodeURIComponent(item.value) + "&";
   }
   if (endString.length > 0) {
   	paramsStart = endString.length;
   	endString = endString.substring(0, paramsStart-1);
   }

// Add map info

//GMapType.GTypes mainType = map.getCurrentMapType();
var type = map.getCurrentMapType();
var temp ='';
if( type == G_NORMAL_MAP )     
	temp = "G_NORMAL_MAP";
else if( type == G_HYBRID_MAP )    
	temp = "G_HYBRID_MAP";
else if( type == G_SATELLITE_MAP )    
	temp = "G_SATELLITE_MAP";

   if (endString.length > 0) {   
	endString += "&mmt=" + encodeURIComponent(temp);
	endString += "&mmz=" + encodeURIComponent(map.getZoom());
   } else {
	endString += "mmt=" + encodeURIComponent(temp);
	endString += "&mmz=" + encodeURIComponent(map.getZoom());
   }

   // Get the current bounds of the visible area.
   var bounds = map.getBounds();

   // Expand the bounds a little, so things look smoother when scrolling
   // by small amounts.
   var sw = bounds.getSouthWest();
   var ne = bounds.getNorthEast();

   endString += "&sw_lat=" + encodeURIComponent(sw.lat());
   endString += "&sw_lon=" + encodeURIComponent(sw.lng());
   endString += "&ne_lat=" + encodeURIComponent(ne.lat());
   endString += "&ne_lon=" + encodeURIComponent(ne.lng());
   endString += "&clat=" + encodeURIComponent(map.getCenter().lat());
   endString += "&clng=" + encodeURIComponent(map.getCenter().lng());
   

// check if the program got here by the user pushing the advanced search button
   if (advSearchCheck == true) {
        advSearchCheck = false;
	var tempString = '';

	params = new Array( "allwords", "exactwords", "oneword", "nowords", "author" );
   	for ( i in params ) {
   		var item = document.getElementById(params[i]);
		if (item.value != null)
			if (item.value.length > 0)
				tempString += params[i] + "=" + encodeURIComponent(item.value) + "&";
   	}
	if (tempString.length > 0) {
   		paramsStart = tempString.length;
   		tempString = tempString.substring(0, paramsStart-1);
		if (endString.length > 0) {
			tempString = "&" + tempString;
			endString += tempString;
		} else {
			endString = tempString;
		}
		
	}
	// Clear simple search parameter
   	item = document.getElementById("tag");
	if (typeof item != 'undefined')
		if (item != null)
			item.value = '';

   } else { // Simple search
	var tempString = '';
   	var item = document.getElementById("tag");
	if (item.value != null)
		if (item.value.length > 0) {
			tempString += "tag=" + encodeURIComponent(item.value);
		}
	if (endString.length > 0) 
		if (tempString.length > 0)
			endString = endString + "&" + tempString;
	// Clear advanced search parameter
	params = new Array( "allwords", "exactwords", "oneword", "nowords", "author" );
   	for ( i in params ) {
   		item = document.getElementById(params[i]);
		if (typeof item != 'undefined')
			if (item != null)
				item.value = '';
   	}
   }

   // Added the search parameter to prevent clicks on tags from counting as searches
   // The search has to be entered by pushing on the "Search" button.
   if (endString.length > 0)
   	fullURL = fullURL + "?" + endString + "&search=true";
   form.action = fullURL;
   return(true);
   
}
