//control variables
var MyWidth=960;
var MyHeight=600;
var curri = -1;
var currj = -1;
var currk = -1;
var currpage = -1;
var tab = "";
var boolMap = true;
var map = null;
var poly = null;
var bounds = new GLatLngBounds();
var boundsMap = new GLatLngBounds();
var nearMarker = null;
var record = null;

//info + result arrays
var eventMarkers = []; //map overlay markers
var miniInfo = [];  //info window for result events
var DataResponse = "";

//form values
var queryProgression = "";
var perpage=25;
var title = "";
var fromDate = "";
var toDate = "";
var nearLocation="";
var nearLat="";
var nearLng="";
var within="";
var tagstr = "" ;
var typestr="";
var sort=0;

window.dhtmlHistory.create();
var historyChange = function()
{
	var txt = parsehash();
	if(txt != "@") callajax(txt); 
	else showSharedEvent();
};

function add_Event(event, elm, handler, bubble) 
{
	if (elm.addEventListener)
		elm.addEventListener(event, handler, bubble);
	else if (elm.attachEvent)
		elm.attachEvent("on"+event, handler);
}

function del_Event(event, elm, handler, bubble) 
{
	if (elm.removeEventListener)
		elm.removeEventListener(event, handler, bubble);
	else if (elm.detachEvent)
		elm.detachEvent("on"+event, handler);
}

function getObjectMethodClosure(object, method) 
{
	return function(arg) 
	{
		return object[method](arg); 
	}
}
var element = getObjectMethodClosure(document, "createElement");
var txtNode = getObjectMethodClosure(document, "createTextNode");

/*
 * Slider
 */
function Slider(id, orientation)
 {
	this.setWidth = function (width)
	{
		this.width = width;
	}

	this.drag = function (event) 
	{
		if (!event) var event = window.event;
		var deltaX=event.clientX - parseInt(sl.s.style.left,10);
		
		var X1=parseInt(sl.s1.style.left,10);

		add_Event("mousemove", document, moveHandler, true);
		add_Event("mouseup", document, upHandler, true);

		function moveHandler(e)
		{
			var x; 
			var newvalue;
			if (!e) e=window.event;
	
			x = e.clientX - deltaX;
			if (x>X1-12) x=X1-12;
			if (x<0) x=0;
			sl.s.style.left=(x) + "px";
			newvalue = x;
			
			if (newvalue != sl.value) 
			{
				sl.value = newvalue;
				sl.onChange(newvalue, 0);
			}
		}
	
		function upHandler(e) {
			if (!e) e=window.event;
			del_Event("mouseup", document, upHandler, true);
			del_Event("mousemove", document, moveHandler, true);
		}
	}
	
	
	this.drag1 = function (event) 
	{
		if (!event) var event = window.event;
		var deltaX1=event.clientX - parseInt(sl.s1.style.left,10);
		
		var X=parseInt(sl.s.style.left,10);

		add_Event("mousemove", document, moveHandler, true);
		add_Event("mouseup", document, upHandler, true);

		function moveHandler(e) 
		{
			var x;
			var newvalue;
			if (!e) e=window.event;
	
			x = e.clientX - deltaX1;
			if (x<X+12) x=X+12;
			if (x>sl.width-10) x=sl.width-10;
			sl.s1.style.left=(x) + "px";
			newvalue = x - 9 ;
				
			if (newvalue != sl.value1) 
			{
				sl.value1 = newvalue;
				sl.onChange(newvalue, 1);
			}
		}
	
		function upHandler(e) 
		{
			if (!e) e=window.event;
			del_Event("mouseup", document, upHandler, true);
			del_Event("mousemove", document, moveHandler, true);
		}
	}
	

	this.onChange = function (value, option) 
	{
		var x  = parseInt(value/3,10) - 15;
		if(option == 1) document.getElementById('ToDateInput').value = getFutureDate(getCurrentYear(), getCurrentMonth(), getCurrentDate(), (x-1));
		else document.getElementById('FromDateInput').value = getFutureDate(getCurrentYear(), getCurrentMonth(), getCurrentDate(), x);
	}

	this.createSlider = function() 
	{
		var bar = element("div");
		bar.className="bar";
		document.getElementById(this.id).appendChild(bar);
		
		// Set slider image as background element to fix IE quirk
		var img = element("div");
		img.setAttribute("id","knob");
		img.className="knob";
		img.style.left="0px";
		
		var img1 = element("div");
		img1.setAttribute("id","knob1");
		img1.className="knob";
		img1.style.left="327px";
		

		img.onmousedown = this.drag;
		this.s = img;
		this.s1 = img1;
		
		img1.onmousedown = this.drag1;
		
		document.getElementById(this.id).appendChild(img);
		document.getElementById(this.id).appendChild(img1);
	}
	
	// Initialize class
	this.id = id;
	this.orientation = "horizontal";
	this.height = 10;
	this.width = 337;
	this.s = null;
	this.s1=null;
	this.value=0;
	this.value1=318;
	var sl = this;
	
	this.createSlider();
}


function SetView()
{
	if (parseInt(navigator.appVersion)>3) {
	 MyWidth = screen.width;
	}
	else if (navigator.appName == "Netscape" 
		&& parseInt(navigator.appVersion)==3
		&& navigator.javaEnabled()
	   ) 
	{
	 var jToolkit = java.awt.Toolkit.getDefaultToolkit();
	 var jScreenSize = jToolkit.getScreenSize();
	 MyWidth = jScreenSize.width;
	}
	
	if( typeof( window.innerWidth ) == 'number' ) 
	{
		//Non-IE
		MyHeight = window.innerHeight;
    } 
	else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) 
	{
		//IE 6+ in 'standards compliant mode'
		MyHeight = document.documentElement.clientHeight;
    } 
	else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) 
	{
		//IE 4 compatible
		MyHeight = document.body.clientHeight;
    }
}

function SetViewResult()
{
	var MapHeight = (MyHeight-300);
	document.getElementById("Map").style.height= MapHeight + "px";
	document.getElementById("Result").style.height= (MyHeight-244) + "px";
	document.getElementById("Result").style.overflow= "auto";
	//document.getElementById("RightPanel").style.height= (MyHeight-38) + "px";	
}
function SetInput(option)
{
	var txt = document.getElementById(option);
	if((txt.value=="Keyword(eg:music)") || (txt.value=="Location(eg:Champaign)"))
	txt.value = "";
}
function ShowHint(option)
{
if(removeSpaces(document.getElementById(option).value) == "") document.getElementById(option).value="";
switch(option)
	{
	case"InputKeyWord":
		if(document.getElementById(option).value=="") document.getElementById(option).value="Keyword(eg:music)";
	break;
	case "InputLocation":
		if(document.getElementById(option).value=="") document.getElementById(option).value="Location(eg:Champaign)";
	break;
	case "FromDateInput":
		if(document.getElementById(option).value=="") document.getElementById(option).value="From Date";
	break;
	case "ToDateInput":
		if(document.getElementById(option).value=="") document.getElementById(option).value="To Date";
	break;
	}
}

function SetFocus(option)
{
	document.getElementById(option).focus();
	document.getElementById(option).value = "";
}

function Load()
{
	dhtmlHistory.initialize();
	var customarray=new Array('music', 'sport', 'education', 'politics', 'economy', 'school', 'art', 'family');
	var obj = actb(document.getElementById('InputKeyWord'),customarray); 
	slider = new Slider("DateImage", "horizontal");
	dhtmlHistory.addListener(historyChange);
	historyStorage.reset();
	SetView();
	SetViewResult();
	if(GBrowserIsCompatible)
	{
		map = new GMap2(document.getElementById("Map"));
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
		map.setCenter(new GLatLng(40.11031, -88.227682), 13);
	}
	else alert("Sorry the Google Map API is not compatible with this browser!");
	var Hash = dhtmlHistory.getCurrentHash();
	historyChange();
}

function renderResult(data)
{
var temphtml="";
eval("var result2=" + data);
if (result2.rsp.stat=="ok" )
	{
	var total=result2.rsp.results.total;
	var pagecount = parseInt((total * 1 + perpage -1)/perpage,10);
	var records=result2.rsp.results.records;
	var startCount=(currpage - 1) * perpage +1;
	var endCount=(total>currpage * perpage)?currpage * perpage : total;
	temphtml+='<div id="ResultTitle" class="ResultTitle"><div class="ResultPanelStatus" id="ResultPanelStatus">Result: ' + startCount +'-' + endCount + ' of ' +total + '</div>';
	temphtml+='<div class="SortBy" id="SortBy">Sort by: <select name="Sort" id="Sort" onchange=\'SortRecords(this.selectedIndex)\'><option value="Relevance">Relevance</option>' + 
	'<option value="Date_0">Start Date &darr;</option><option value="Date_1">Start Date &uarr;</option>' + 
	'<option value="Venue_0">Venue Name &darr;</option><option value="Venue_1">Venue Name &uarr;</option></select></div></div>';
	temphtml+='<div id="Result" class="Result">';
	
	var nextPage = '<div id="ResultPages">';
	// if(currpage-1>0) nextPage = nextPage + '<a href="javascript:void(0)" onclick="nextSearch('+ (currpage*1-1) + ')" style="text-decoration:none;"><<</a> ';
	// nextPage = nextPage + currpage + ' ';
	if(currpage>1) nextPage = nextPage + '<a href="javascript:void(0)" onclick="nextSearch('+ (currpage*1-1) + ')">&lt;</a>';
	for(i = Math.max(currpage,1); i <= Math.min(currpage*1+4,pagecount); i++)
		{
		if(i!= currpage)
			nextPage = nextPage + '<a href="javascript:void(0)" onclick="nextSearch('+ i + ')">' + i +'</a>';
		else nextPage = nextPage + '<span class="current">' + i + '</span>'  ;
		}
	if(currpage + 4 <pagecount) 
		{
		nextPage = nextPage + '<a href="javascript:void(0)" onclick="nextSearch('+ (currpage*1+5) + ')">&gt;</a>';
		}
	// nextPage = nextPage + '<a href="javascript:void(0)" onclick="nextSearch('+ (currpage*1+1) + ')" style="text-decoration:none;">>></a>';
	nextPage = nextPage + '</div> ';	
	
	
	for(var i=0;i<records.length;i++)
		{
		temphtml+='<div class="dayout" id="'+ i + '" onMouseover="showEventMarker(' + i + ')">';
        temphtml+='<div class="time">';
		var time=records[i].time;
		if(time.length>0) 
		{
			if(!isNA(time[0].date_url))
			{
				temphtml+='<a target="blank" href='+ time[0].date_url +' class="date">';
				temphtml+=time[0].start_date;
				temphtml+='</a>';
			}
			else temphtml+=time[0].start_date;;
		}
		var event_hash = records[i].event_hash;
		//temphtml+='<a title="Email this Event" onclick="EmailEvent(\'' + event_hash + '\')" class="mail" href="javascript:void(0)">Email this Event</a>';

        if(time.length>0)
		{
			temphtml+= '<div id="More_Date_Canvas' + i + '" class="moredate">';
			temphtml+= '<div id="More_Date' + i +'"><a title="Click to view more detail" href = "javascript:More_Date(' + i + ')">[More Detail]</a></div>';
            temphtml+= '</div>';
		}
        temphtml+='</div>';
		temphtml+='<div><span class="number">'+ records[i].count +'</span>';
		var event_title = truncate(records[i].title, Math.min(records[i].title.length,20));
		if(!isNA(records[i].url)) temphtml+='<a href='+ records[i].url + ' target="_blank" class="title">' + event_title +'</a>';
		else temphtml+='' + event_title + '</div>';
		temphtml+='</div>';
		temphtml+='<div><strong>Venue:</strong>';
		var event_venue = "";
		if(records[i].venue_name != null) event_venue = truncate(records[i].venue_name, Math.min(records[i].venue_name.length,25));
		if ((event_venue == null) || (event_venue == "")) event_venue = truncate(records[i].venue_address, Math.min(records[i].venue_address.length,25));
		if(!isNA(records[i].venue_url))
			temphtml+='<a href=' + records[i].venue_url + ' target="_blank">' +event_venue+ '</a>'; 
		else 
			temphtml+='&nbsp;'+event_venue;
		temphtml+='</div>';
		if(!isNA(records[i].description)) 
		{
			var des = records[i].description.replace(/<b><font color=red>/g, "").replace(/<\/b>/g, "");
			temphtml+='<div class="clear"><strong>Description:</strong> '  + truncate(des, Math.min(des.length, 95))  +'</div>' ;
		}
		var sources=records[i].sources;
		if(sources.length==0) temphtml+='</div>';
		else
			{
			temphtml+='<div class="Sources"><strong>Sources:</strong>';
			if(sources.length<2)
				{
				temphtml+='<a href=' + sources[0].url + ' target="_blank">' + sources[0].name + '</a>';
				}	
			else
				{
				temphtml+='<a href=' + sources[0].url + ' target="_blank">' + sources[0].name + '</a>, ';
				temphtml+='<span id="source' + i + '">...<a href=\'javascript:MoreSources(' + i + ')\' title="More Sources" class="sourcemore">[More]</a></span>';
				}
			temphtml+='</div></div>';	
			}			
		setMiniInfo(i, records[i]);
		}
	temphtml+='</div>' + nextPage;
	}

return temphtml;
}

function truncate(str, length)
{
	if(removeSpaces(str).length <= length) return removeSpaces(str);
	var pos = str.indexOf(' ',length);
	if(pos!=-1) str = str.substring(0,pos);
	str = removeSpaces(str) + "...";
	return str;
}

function renderTags(option)
{
if(DataResponse == "NO RESULTS") return;
var temphtml="";
tab = option;
document.getElementById("topicTab").className = "tab";
document.getElementById("sourceTab").className = "tab";
document.getElementById("venueTab").className = "tab";
document.getElementById("timeTab").className = "tab";
var txt = option + "Tab";
document.getElementById(txt).className = "selected";
eval("var tags2=" + DataResponse);
switch(option)
	{
	case "venue":
	var tagsArr=tags2.rsp.venue_tags;
	break;
	case "source":
	var tagsArr=tags2.rsp.source_tags;
	break;
	case "time":
	var tagsArr=tags2.rsp.time_tags;
	break;
	case "topic":
	var tagsArr=tags2.rsp.topic_tags;
	break;
	}
var total = Math.min(tags2.rsp.results.total,perpage);
var j = 0;
for(i=0;i<tagsArr.length;i++)
	{
	var tag_type = tagsArr[i].type;
	var content = tagsArr[i].content;
	var count = parseInt(tagsArr[i].count);
	if(tag_type == "source") count = 12 + (12 * count)/tags2.rsp.results.total;
	else 
	{
		count = Math.min(count, total);
		count = 12 + (12 * count)/total;
	}
	count = parseInt(count);
	
	temphtml += '<a href=\'javascript:getTagEvents("' + tag_type + '","' + escape(content) + '",1)\' style = "text-decoration:none; font-size:' + count + 'px;';
	if(j%2 == 0) temphtml += 'color:#404C4E;">';
	else temphtml += 'color:#006633;">';
temphtml+= content + '</a><wbr>&nbsp;';
	j++;
	}
document.getElementById("CommonTagsContent").innerHTML = temphtml;
}

function setQueryProgression() //prev form
{
	if(title=="Keyword(eg:music)") title="";
	if(nearLocation=="Location(eg:Champaign)") nearLocation="";
	if(fromDate =="From Date") fromDate = "";
	if(toDate == "To Date") toDate = "";
	if(title=="" && fromDate=="" && toDate=="" && nearLocation=="" && tagstr == "") queryProgression = 'All events'; 
	else
	{
		queryProgression = "Events";
		if(removeSpaces(title) != "")
		{
			var temp = removeSpaces(title);
			queryProgression = queryProgression + '&nbsp;for&nbsp;<a href=javascript:void(0) onclick=SetFocus("InputKeyWord")>' + temp + '</a>';
		}
		if(fromDate!="")
		{
			queryProgression = queryProgression + '&nbsp;from&nbsp;<a href=javascript:void(0) onclick=SetFocus("FromDateInput")>' + fromDate + '</a>';
		}
		if(toDate!="")
		{
			queryProgression = queryProgression + '&nbsp;to&nbsp;<a href=javascript:void(0) onclick=SetFocus("ToDateInput")>' + toDate + '</a>';
		}
		if(removeSpaces(nearLocation) != "")
		{
			var temp = removeSpaces(nearLocation);
			queryProgression = queryProgression + '&nbsp;near&nbsp;' + '<a href=javascript:void(0) onclick=SetFocus("InputLocation")>' + nearLocation + '</a>';							
			if(within!="") queryProgression+= '&nbsp;by&nbsp;' + '<a href=javascript:void(0) onclick=SetFocus("Within")>' + within  + ' miles</a>' ;
		}
		if(tagstr!="")
		{
		var tagArr=tagstr.split('@');
		for(var i=0;i<tagArr.length;i++)
			{
			queryProgression+= '&nbsp;<span id="EventTags">>&nbsp;<a href=javascript:void(0) onclick=delTag(' + i + ')>' + tagArr[i] + '<sup>(x)</sup></a></span>'; 
			}
		}
		queryProgression += "";
	}
	document.getElementById("QuerySentenceContent").innerHTML=queryProgression;	
}

function delTag(i)
{
var tagArr = tagstr.split('@');
var typeArr = typestr.split('@');
tagstr="";
typestr="";
if(i>0)
	for(j=0;j<i;j++) 
	{
	if(j<i-1) 
		{
		tagstr+=tagArr[j]+'@';
		typestr+=typeArr[j]+'@';
		}
	else 
		{
		tagstr+=tagArr[j];
		typestr+=typeArr[j];
		}
	}

querydatabase(1);
}

function renderPage()
{
	if(DataResponse == "NO RESULTS")
	{							
		document.getElementById("ResultPages").innerHTML = "";				
		document.getElementById("ResultPanelStatus").innerHTML = "&nbsp;&nbsp;<b> NO RESULT</b>"; 
		document.getElementById("SortBy").innerHTML="";
		document.getElementById("Result").innerHTML="";	
		document.getElementById("CommonTagsContent").innerHTML= "&nbsp;&nbsp;<b> NO TAGS</b>";
	}
	else
	{
		document.getElementById("ResultPanel").innerHTML= renderResult(DataResponse);
		curri = 0;
		document.getElementById("Sort").selectedIndex = sort;
		if(tab!= "") renderTags(tab);
		else renderTags("source");
		SetViewResult()
		renderMapResults(DataResponse);	
		showEventInfo();
		eventMarkers[0].openInfoWindowTabsHtml(miniInfo[0], {maxWidth:250});
	}
	if(nearLat != "")
	{
		var point = new GLatLng(parseFloat(nearLat), parseFloat(nearLng));
		addMarker(point);
		map.addOverlay(nearMarker);
		drawCircle(point, 100);
		addListenerMarker();
	}
}

function querydatabase(page) 
{
	getParamFromDOM(page);
	if(sort == "") document.getElementById("SortBy").innerHTML = "";	
	updateFeedLink();
	callajax(page);
}


function callajax(page)
{
	document.getElementById("CommonTagsContent").innerHTML= "";
	document.getElementById("ResultPanelStatus").innerHTML = "Result:"; 
	document.getElementById("Result").innerHTML="<center>SEARCHING...</center>";
	document.getElementById("ResultPages").innerHTML = "";
	if(sort == "") document.getElementById("SortBy").innerHTML = "";
	clearOverlay();
	currpage = page;
	var Hash = "?title="+title+"&fromDate="+fromDate+"&toDate="+toDate
		+"&nearLocation="+nearLocation+"&nearLat="+nearLat+"&nearLng="+nearLng+"&within="+within
		+"&tagstr="+tagstr.replace(/&/g,"~")+"&typestr="+typestr
		+"&page="+page+"&perpage="+perpage+"&sort="+sort;
	setQueryProgression();
	var ajaxRequest;  // The variable that makes Ajax possible!
	var data;	
	
	try	{		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
	} catch (e)
	{		// Internet Explorer Browsers
		try		{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try	{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e)	{	// Somethin went wrong
				alert("Your browser broke!");
				return false;
			}
		}
	}
	// Create a function that will receive data sent from the server
	ajaxRequest.onreadystatechange = function()
	{
		if(ajaxRequest.readyState == 4)
		{		
			var data = ajaxRequest.responseText;
			DataResponse = data;
			Hash = urlencode(Hash);
			dhtmlHistory.add(Hash);
			renderPage(DataResponse);
		}
	}
	if ((nearLocation == null)||(nearLocation==""))
	{
	   ajaxRequest.open("GET", "getdata.php" + Hash, true);
	}
	else
	{
	    ajaxRequest.open("GET", "getdata1.php" + Hash, true);
	}
	ajaxRequest.send();
	   
}




function showEventMarker(i)
{
	if (curri==i) 
		return;
	curri=i;
	for(var k=0;k<eventMarkers.length; k++)
	{
		if(k==i) 
		{
			if(!isNA(eventMarkers[i]))
			{
				map.removeOverlay(eventMarkers[i]);
				map.addOverlay(eventMarkers[i]);
				eventMarkers[i].openInfoWindowTabsHtml(miniInfo[i], {maxWidth:250});
			}
			showEventInfo();
		}
		else 
		{
		document.getElementById(k).className="dayout";
			}
	}
}

function showEventInfo()
{
	eval("var response = " + DataResponse);
	document.getElementById(curri).className="dayover";
	var record = response.rsp.results.records[curri];
	if(!isNA(record.performer) && removeSpaces(record.performer) != "")
	{
		document.getElementById("Performer").style.display = "";
		var tempHTML = "<b>Performer:</b> " + record.performer;
		document.getElementById("Performer").innerHTML = tempHTML;
	}
	else document.getElementById("Performer").style.display = "none";
	if(!isNA(record.cost) && removeSpaces(record.cost) != "" && removeSpaces(record.cost) != "0")
	{
		document.getElementById("Cost").style.display = "";
		var tempHTML = "<b>Cost:</b> $" + record.cost;
		document.getElementById("Cost").innerHTML = tempHTML;
	}
	else document.getElementById("Cost").style.display = "none";
	if(!isNA(record.contact) && removeSpaces(record.contact) != "")
	{
		document.getElementById("Contact").style.display = "";
		var tempHTML = "<b>Contact:</b> " + record.contact;
		document.getElementById("Contact").innerHTML = tempHTML;
	}
	else document.getElementById("Contact").style.display = "none";
	if(!isNA(record.sponsor) && removeSpaces(record.sponsor) != "")
	{
		document.getElementById("Sponsor").style.display = "";
		var tempHTML = "<b>Sponsor:</b> " + record.sponsor;
		document.getElementById("Sponsor").innerHTML = tempHTML;
	}
	else document.getElementById("Sponsor").style.display = "none";
	if(!isNA(record.registration) && removeSpaces(record.registration) != "")
	{
		document.getElementById("Registration").style.display = "";
		var tempHTML = "<b>Registration:</b> " + record.registration;
		document.getElementById("Registration").innerHTML = tempHTML;
	}
	else document.getElementById("Registration").style.display = "none";
	var tempHTML = "";
	if (record.crawled_date != "0000-00-00 00:00:00")
	   tempHTML = "(Crawled on <b>" + record.crawled_date + "</b>)";
	if(!isNA(record.description) && removeSpaces(record.description) != "")
	{
       tempHTML = "<b>Description:</b> " + record.description + tempHTML;
	}	
	document.getElementById("Description").innerHTML = tempHTML;
}


function renderMapResults(data) 
{
	
	eval("var data1=" + data);
	// map view  Create a base icon for all of our markers that specifies the shadow, icon dimensions, etc.
	var baseIcon = new GIcon();
	baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
	baseIcon.iconSize = new GSize(20, 34);
	baseIcon.shadowSize = new GSize(37, 34);

	baseIcon.iconAnchor = new GPoint(9, 34);
	baseIcon.infoWindowAnchor = new GPoint(9, 2);
	baseIcon.infoShadowAnchor = new GPoint(18, 25);		    										
	// Creates a marker whose info window displays the letter corresponding to the given index.
	function createMarker(point, index, address) 
	{
		// Create a lettered icon for this point using our icon class
		 var icon = new GIcon(baseIcon);
		icon.image = "images/show/red_marker" + (index+1) + ".png";
					
		// Set up our GMarkerOptions object
		var markerOptions = {icon:icon, title:address};	
		var markerOverlay = new GMarker(point, markerOptions);
		eventMarkers[index]=markerOverlay;
														
		// The new marker "mouseover" listener        
		GEvent.addListener(markerOverlay,"mouseover", function() 
		{						
		});									
				
		GEvent.addListener(markerOverlay,"mouseout", function() 
		{					
		});	
														
		GEvent.addListener(markerOverlay, "click", function() 
		{
			if(!isNA(eventMarkers[index]))
			{
				eventMarkers[index].openInfoWindowTabsHtml(miniInfo[index], {maxWidth:250});
			}
			showEventMarker(index);
			var count = parseInt((MyHeight-255)/90,10);
			count = parseInt((count+1)/2,10);
			if(index>count)
				document.getElementById("Result").scrollTop = (index-count) * 90;
			else document.getElementById("Result").scrollTop = 0;
			
		});
		
		return markerOverlay;
	}
	var records=data1.rsp.results.records;
	var j = records.length;
	eventMarkers = new Array(j);
	boundsMap = new GLatLngBounds();
	for(var i=0; i<j; i++)
	{
		var latitude = records[i].latitude;
		var longitude = records[i].longitude;
		var address = records[i].venue_name;
		var point = "";
		if(latitude!=null && longitude!=null) //skip missing addresses
			point = new GLatLng(latitude, longitude);
		else
			point = new GLatLng(40.1163889, -88.2433333);
		map.addOverlay(createMarker(point, i, address));	
		boundsMap.extend(point);         
	}	
 	if(nearLat == "") map.setCenter(boundsMap.getCenter()); 
}


function setMiniInfo(index, temprec) 
{
var tabHTML = '<div class="FirstLine">';
if(temprec.url!=null) tabHTML += ' <a href=' + temprec.url + ' target="_blank" style="text-decoration:none;font-size:13px;font-weight:bold;">' + temprec.title + '</a>';
else tabHTML += '' + temprec.title + ''; 
tabHTML+='</div>';
var tab1 = new GInfoWindowTab("Event", tabHTML);	
miniInfo[index]=[tab1];	
}

function removeSpaces(data)
{
	data=data.replace(/"/g, '');
	while(data.indexOf('  ')>-1)
		data=data.replace(/  /g, ' ');
	if (data == " ") data = "";
	return data;
}

function clearOverlay(onComplete) //clear out all the result overlays
{		
	map.clearOverlays() ;
	nearMarker = null;
	poly = null;
	eventMarkers = new Array();
	miniInfo = new Array();
	if(onComplete) onComplete();
}

function getTagEvents(type, tag, page)
{
curri = -1;
currj = -1;
currk = -1;
if(tagstr!="") 
	{
	var tagArr = tagstr.split("@");
	for(i = 0; i<tagArr.length; i++)
		if(tag == tagArr[i]) return;
	tagstr = tagstr + '@' + tag;
	typestr = typestr + '@' + type;
	}
else 
	{
	tagstr = tag;
	typestr = type;
	}

querydatabase(1);
}

function firstSearch()
{
tagstr="";
typestr="";
curri = -1;
currj = -1;
currk = -1;

querydatabase(1);
}

function nextSearch(page)
{
curri= -1;
currj= -1;
currk= -1;

querydatabase(page);
}

oldlink = '';
function updateFeedLink()
{
    var link = document.getElementById('DataFeedLink');
    var page = 1;
    getParamFromDOM(page);
    	
    var feedlink = "?search="+title+"&fromDate="+fromDate+"&toDate="+toDate
		+"&nearLocation="+nearLocation+"&nearLat="+nearLat+"&nearLng="+nearLng+"&within="+within
		+"&tags="+tagstr.replace(/&/g,"~")+"&tagtype="+typestr
		+"&page="+page+"&perpage="+perpage+"&sort="+sort;
    if (oldlink != feedlink)
    {
        link.href = 'datafeed.php'+feedlink;
        oldlink = feedlink; 
    }    
}

function drawCircle(center, nodes)
{	
	if(poly != null)
	{
		map.removeOverlay(poly);
	}
	var radius = document.getElementById('Within').value;
    if (radius == '' || radius==0) 
		return; 
	
	radius = radius * 1.609344; //1 mile = 1.609344 km
    var latConv = center.distanceFrom(new GLatLng(center.lat()+0.1, center.lng()))/100;
    var lngConv = center.distanceFrom(new GLatLng(center.lat(), center.lng()+0.1))/100;

    var points = [];
	//bounds = new GLatLngBounds();
    var step = parseInt(360/nodes)||10;
    for(var i=0; i<=360; i+=step)
	{
		var pint = new GLatLng(center.lat() + (radius/latConv * Math.cos(i * Math.PI/180)), center.lng() + 
			(radius/lngConv * Math.sin(i * Math.PI/180)));
		points.push(pint);
    }
    poly = new GPolyline(points);
    poly.color = "#677CFF";
    map.addOverlay(poly);
	
 	// bounds = new GLatLngBounds();
    // var inc = parseInt(points.length/4,10);
    // bounds.extend(points[0]); //this is for fit function
    // bounds.extend(points[inc]); //this is for fit function
    // bounds.extend(points[2*inc]); //this is for fit function
    // bounds.extend(points[3*inc]); //this is for fit function
	//map.setZoom(map.getBoundsZoomLevel(bounds));
    if(radius < 1) map.setCenter(center, 14);
	else if(radius<3) map.setCenter(center, 13);
	else if(radius <5) map.setCenter(center, 12);
	else if(radius <10) map.setCenter(center, 11);
	else map.setCenter(center, 10);
}

function getLocation(onComplete) //get form field near_location
{
	if(nearMarker!=null)
	{
		map.removeOverlay(nearMarker);
	}
	if(poly != null)
	{
		map.removeOverlay(poly);
	}
	var geocoder = new GClientGeocoder();
	geocoder.getLatLng(document.getElementById("InputLocation").value,
        function(point) 
		{
            if (!point)
			{
				nearMarker = null;
				poly = null;
				nearLat = "";
				nearLng = "";
				if(onComplete) onComplete();
			}
			else 
			{
				addMarker(point)
				map.addOverlay(nearMarker);
				map.setCenter(point);
				drawCircle(point, 100);
				addListenerMarker();
				if(onComplete) onComplete();
            }
        }
		);
}

function get_Lat_Lng(onComplete)
{	
	var geocoder = new GClientGeocoder();
	geocoder.getLatLng(document.getElementById("InputLocation").value,
        function(point) 
		{
            if (!point)
			{
				nearMarker = null;
				poly = null;
				nearLat = "";
				nearLng = "";
			}
			if(onComplete) onComplete();
        }
		);
}

function addMarker(point)
{
	var baseIcon = new GIcon();
	baseIcon.shadow = "";
	baseIcon.iconSize = new GSize(30, 55);
	baseIcon.iconAnchor = new GPoint(9, 34);
	baseIcon.infoWindowAnchor = new GPoint(9, 2);
	baseIcon.infoShadowAnchor = new GPoint(18, 25);
	var icon = new GIcon(baseIcon);
	icon.image = "images/location.png";
	nearMarker = new GMarker(point, {icon: icon, draggable: true, title: "Drag to your desired location"});
	nearLat = point.lat();
	nearLng = point.lng();
}

function addListenerMarker()
{
	GEvent.addListener(nearMarker, "dragend", function()
	{
		var geocoder1 = new GClientGeocoder();
		nearLat = nearMarker.getPoint().lat();
		nearLng = nearMarker.getPoint().lng();
		geocoder1.getLocations(nearLat+","+nearLng,function(response)
		{
			if (response && response.Status.code == 200)
			{ document.getElementById("InputLocation").value=response.Placemark[0].address; }
		});
		drawCircle(nearMarker.getPoint(), 100);
	});
	var myinfo = '<div class = "FirstLine">Drag me to your desired location</div>';
	GEvent.addListener(nearMarker, "click", function() 
	{
		nearMarker.openInfoWindowHtml(myinfo);
	});
}

function MoreSources(k)
{
	if(currk != -1) 
		HideSources(currk);
	currk = k;
	var temphtml = "";
	eval("var response = " + DataResponse);
	var sources = response.rsp.results.records[k].sources;
	var temp = "";
	for(var i = 1; i<sources.length;i++)
	{	
		if(i<sources.length - 1) 
			temphtml += '<a href=' + sources[i].url + ' target="_blank">' + sources[i].name + '</a>, ';
		else 
			temphtml += '<a href=' + sources[i].url + ' target="_blank">' + sources[i].name + '</a>';
	}
	temphtml += '<a href=\'javascript:HideSources(' + k + ')\' class="sourcemore">[Hide]</a>';
	var txt="source" + k;
	document.getElementById(txt).innerHTML=temphtml;
}
	
function HideSources(k)
{
	currk = -1;
	var txt="source" + k;
	var temphtml = '...<a href=\'javascript:MoreSources(' + k + ')\' class="sourcemore">[More]</a>';
	document.getElementById(txt).innerHTML=temphtml;
}

function SortRecords(key)
{
sort = key;
nextSearch(1);
}

function getToday()
{
	var year = getCurrentYear()+"";
	var month = getCurrentMonth()+"";
	var date = getCurrentDate()+"";
	if(month.length==1)
		month="0"+month;
	if(date.length==1)
		date="0"+date;
	return year+"-"+month+"-"+date;
}

function getCurrentYear()
{
	var today=new Date();
	var year = today.getFullYear();
	return year;
}

function getCurrentMonth()
{
	var today=new Date();
	var month = today.getMonth();
	month++;
	return month;
}

function getCurrentDate()
{
	var today=new Date();
	var date = today.getDate();
	return date;
}

function getFutureDate(year, month, date, interval)
{
	if(interval>0)
	{
		if(date+interval > 28 && month==2)
		{
			var m = (date+interval-28)/30;
			if((date+interval-28)%30 == 0)
			{
				date = 30;
				month = month + m;
			}
			else
			{
				m = parseInt(m,10);
				date=date+interval-(28+m*30);
				month = month + m + 1;	
			}
		}
		else if(date+interval > 30 && month!=2)
		{
			var m = (date + interval)/30;
			if((date + interval)%30 == 0)
			{
				date = 30;
				month = month + m -1;
			}
			else
			{
				m = parseInt(m,10);
				date = date+interval-m*30;
				month = month + m;
			}
		}
		else if(date+interval <= 28 && month==2)
			date = date+interval;
		else if(date+interval<=30 &&  month!=2)
			date=date+interval;
		if(month>12)
		{
			month=month - 12;
			year++;
			if(month==2 && date>28) 
			{
				month++;
				date = date - 28;
			}
		}
	}
	else 
	{
		if(date+interval>0) date = date +interval;
		else if(date+interval <1 && month == 3)
		{
		date = 28 + date + interval;
		month--;
		}
		else if(date+interval <1 && month !=3)
		{
		date = 30 + date + interval;
		month--;
		}
		if(month<1)
		{
		month=12;
		year--;
		}
	}
	month=month+"";
	date=date+"";
	if(month.length==1)
		month="0"+month;
	if(date.length==1)
		date="0"+date;
	return year+"-"+month+"-"+date;
}

function getInterval(date1, date2)
{
var arr1 = date1.split("-");
var arr2 = date2.split("-");
var interval = (parseInt(arr2[0],10) - parseInt(arr1[0],10)) * 365 + (parseInt(arr2[1],10) - parseInt(arr1[1],10)) * 30 + parseInt(arr2[2],10) - parseInt(arr1[2],10);
return interval;
}

function showSliderDate(option)
{
	var interval = 0;
	var pattern =/^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$/;
	if(option == 1)
	{
		if(document.getElementById("ToDateInput").value.match(pattern))
		{	
			if(document.getElementById("FromDateInput").value.match(pattern)) 
			{
				interval = getInterval(document.getElementById("FromDateInput").value, document.getElementById("ToDateInput").value);
				if(interval<=0) document.getElementById("ToDateInput").value = document.getElementById("FromDateInput").value;
			}
			interval = getInterval(getToday(), document.getElementById("ToDateInput").value);
			if((interval > 90)||(interval <-15)) document.getElementById("knob1").style.left = "327px"; 
			else 
				{
				document.getElementById("knob1").style.left = Math.max(((16+interval) * 3+9),(parseInt(document.getElementById("knob").style.left,10)+12)) + "px";
				}
		}
		else document.getElementById("knob1").style.left = "327px"; 
	}
	if(option == 0)
	{
		if(document.getElementById("FromDateInput").value.match(pattern)) 
		{	
			if(document.getElementById("ToDateInput").value.match(pattern))  
			{
				interval = getInterval(document.getElementById("FromDateInput").value, document.getElementById("ToDateInput").value);
				if(interval<=0) document.getElementById("FromDateInput").value = document.getElementById("ToDateInput").value;
			}
			interval = getInterval(document.getElementById("FromDateInput").value, getToday());
			if((interval > 15)||(interval <-90)) document.getElementById("knob").style.left = "0px";
			else document.getElementById("knob").style.left = ((15-interval) * 3) + "px";
		}
		else document.getElementById("knob").style.left = "0px";
	}
}

function showtime(time)
{
var timeArr = time.split(':');
var t = "";
if(timeArr[0] == '00') t = "12:" + timeArr[1] + "AM" ;
else if (timeArr[0] <= '11') t = timeArr[0] + ":" + timeArr[1] + "AM" ;
else if(timeArr[0] == '12') t = "12:" + timeArr[1] + "PM" ;
else t = (timeArr[0] - 12) + ":" + timeArr[1] + "PM" ;
return t;
} 

function getParamFromDOM(page)
{
	nearLocation = removeSpaces(document.getElementById('InputLocation').value);	
	if(nearLocation == "Location(eg:Champaign)") nearLocation = "";
	within = document.getElementById('Within').value;	
	var queryString = "";
	title = removeSpaces(document.getElementById('InputKeyWord').value);
	if(title == "Keyword(eg:music)") title = "";
	fromDate = removeSpaces(document.getElementById('FromDateInput').value);
	if(fromDate == "From Date") fromDate = "";
	toDate = removeSpaces(document.getElementById('ToDateInput').value);
	if(toDate == "To Date") toDate = "";
	if(nearLocation=="")
	{
		nearLat = "";
		nearLng = "";
		within = "";
		newHash();
	}
	else get_Lat_Lng(newHash);
	
	function newHash()
	{
		// queryString = "?title="+title+"&fromDate="+fromDate+"&toDate="+toDate
		// +"&nearLocation="+nearLocation+"&nearLat="+nearLat+"&nearLng="+nearLng+"&within="+within
		// +"&tagstr="+tagstr+"&typestr="+typestr
		// +"&page="+page+"&perpage="+perpage+"&sort="+sort;
		//window.location.hash = queryString;
	}
}

function parsehash()
{
	var index = "";
	var page = 1;
	var type = 10;
	
	function initStatus()
	{
		document.getElementById('InputKeyWord').value = "Keyword(eg:music)"; 
		document.getElementById('FromDateInput').value = "From Date";
		document.getElementById('ToDateInput').value = "To Date";
		document.getElementById('InputLocation').value = "Location(eg:Champaign)";
		document.getElementById('Within').selectedIndex = 0;
		fromDate = "";
		toDate = "";
		tagstr = "";
		typestr = "";
		sort = 0;
		nearLocation = "";
		nearLat = "";
		nearLng = "";
		within = "";
	}
	
	var Hash = unescape(dhtmlHistory.getCurrentHash());
	if(Hash != "")
	{
		if(Hash.indexOf('event_hash')>-1) 
		{
			initStatus();
			return "@";
		}	
		var sp = Hash.split("&");
		for(var i = 0; i < sp.length; i++)
		{
			name = sp[i].split("=")[0];
			value = sp[i].split("=")[1];
			if(name == "page") {page = value; continue;}
			if(name == "?title") {value = value.replace(/\+/g," "); title = value; if(value=="") value = "Keyword(eg:music)"; document.getElementById('InputKeyWord').value = value; continue;}
			if(name == "fromDate") {fromDate = value; if(value=="") value = "From Date"; document.getElementById('FromDateInput').value = value; continue;}
			if(name == "toDate") {toDate = value; if(value == "") value = "To Date"; document.getElementById('ToDateInput').value = value; continue;}
			if(name == "nearLocation") 
				{
				value = value.replace(/\+/g," ");
				nearLocation = value;
				if(value == "")
					value = "Location(eg:Champaign)";
				document.getElementById('InputLocation').value = value;
				continue;
				}
			if(name == "sort") {sort = value; continue;}
			if(name == "tagstr") {tagstr = value.replace("~","&").replace(/\+/g," "); continue;}
			if(name == "typestr"){typestr = value; continue;}
			if(name == "within")
			{
				switch(value)
				{
					case "": document.getElementById('Within').selectedIndex = 0; break;
					case "0.1": document.getElementById('Within').selectedIndex = 1; break;
					case "0.25": document.getElementById('Within').selectedIndex = 2; break;
					case "1": document.getElementById('Within').selectedIndex = 3; break;
					case "3": document.getElementById('Within').selectedIndex = 4; break;
					case "5": document.getElementById('Within').selectedIndex = 5; break;
					case "10": document.getElementById('Within').selectedIndex = 6; break;
				}
				within = value;
				continue;
			}
			if(name == "nearLat") {nearLat = value; continue;}
			if(name == "nearLng") {nearLng = value; continue;}
		}
		showSliderDate(0);
		showSliderDate(1);
		return page;
	}
	else
	{
		initStatus();
		return page;
	}
}

function handle_onEnter(e)
{
	if(window.event) // IE
	{
	keynum = e.keyCode;
	}
	else if(e.which) // Netscape/Firefox/Opera
	{
	keynum = e.which;
	}
	if(keynum == 13) 
	{
		firstSearch();
	}
}

function EmailEvent(event_hash)
{
	var load = window.open('emailevent.php?event_hash=' + event_hash,'','scrollbars=no,menubar=no,height=700,width=700,resizable=yes,toolbar=no,location=no,status=no');
}

function More_Date(i)
{
	if(currj != -1) 
		Hide_Date(currj);
	currj = i;
	var temphtml = '<div id="More_Date' + i +'" class="moredatepanel">';
	eval("var response = " + DataResponse);
	var time = response.rsp.results.records[i].time;
	for(var j = 0; j<time.length; j++)
	{
		if(!isNA(time[j].start_date)) 
		{
			if(time[j].date_url != null) temphtml += '<a target="_blank" href=' + time[j].date_url + '>';
			temphtml+=time[j].start_date;
			for(k=0;k<time[j].detail_time.length;k++)
			{
				if(!isNA(time[j].detail_time[k].start_time) && time[j].detail_time[k].start_time!="00:00:00" && time[j].detail_time[k].start_time!="00:00:01") 
					temphtml+='&nbsp;' + showtime(time[j].detail_time[k].start_time); 
				if(!isNA(time[j].detail_time[k].end_time) && time[j].detail_time[k].end_time!="00:00:00" && time[j].detail_time[k].end_time!="23:59:59") 
					temphtml+=' to ' + showtime(time[j].detail_time[k].end_time); 
			}
			if(!isNA(time[j].end_date) && time[j].end_date!="0000-00-00" && time[j].end_date!= time[j].start_date)
				temphtml+=" to " + time[j].end_date;
			if(time[j].date_url != null) temphtml += "</a>";
			temphtml+="<br>";
		}
	}
    temphtml+='<a href = "javascript:Hide_Date(' + i + ')" class="close">[Close]</a><br>';
	temphtml+='</div>';
	var st = "More_Date_Canvas" + i;
	document.getElementById(st).style.position = "relative" ;
	document.getElementById(st).innerHTML = temphtml;
}

function Hide_Date(i)
{
	currj = -1;
	var temphtml = '<div id="More_Date' + i +'"><a title="Click to view more detail" href = "javascript:More_Date(' + i + ')">[More Detail]</a></div>';
	var st = "More_Date_Canvas" + i;
	document.getElementById(st).style.position = "" ;
	document.getElementById(st).innerHTML = temphtml;
}

function showSharedEvent()
{
	clearOverlay();
	document.getElementById("CommonTagsContent").innerHTML= "";
	var Hash = unescape(dhtmlHistory.getCurrentHash());
	var event_hash= Hash.split("=")[1];
	currpage = 1;

	var ajaxRequest;  // The variable that makes Ajax possible!
	var data;	
	
	
	try	{		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
	} catch (e)
	{		// Internet Explorer Browsers
		try		{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try	{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e)	{	// Somethin went wrong
				alert("Your browser broke!");
				return false;
			}
		}
	}
	// Create a function that will receive data sent from the server
	ajaxRequest.onreadystatechange = function()
	{
		if(ajaxRequest.readyState == 4)
		{		
			var data = ajaxRequest.responseText;
			DataResponse = data;
			Hash = urlencode(Hash);
			dhtmlHistory.add(Hash);
			renderPage(DataResponse);
			document.getElementById(0).className = "dayover" ;
		}
	}
	
	document.getElementById("ResultPanelStatus").innerHTML = "Result:"; 
	if(sort == "") document.getElementById("SortBy").innerHTML = ""; 
	document.getElementById("Result").innerHTML="<center>SEARCHING...</center>";
	document.getElementById("ResultPages").innerHTML = "";
	
	ajaxRequest.open("GET", "getsharedevent.php?event_hash=" + event_hash , true);
	ajaxRequest.send(null); 

}

function urlencode(s) 
{
	s = encodeURIComponent(s);
	return s.replace(/~/g,'%7E').replace(/%20/g,'+');
}

window.onresize = function(){SetView(); SetViewResult();};

function isNA(val)
{
    if ((val == null) || (val == '') || (val == '-')) return true;
    return false;
}
