function showWaiting(show) {
  div = document.getElementById("pleaseWait");
  if (!div) return;
  if (show) {
    div.style.display = "block";
  } else {
    div.style.display = "none";
  }
}

function loadEvents(params) {
  req = GXmlHttp.create();
  if (req != null) {
    req.onreadystatechange = function() { processEvents(req); };
    req.open("GET", "/includes/events.php?" + params, true);
    req.send(null);
    showWaiting(true);
  }
}


function processEvents(req) {
  if (req.readyState == 4) {
    showWaiting(false);
    if (req.status == 200)
      showEvents(req.responseXML);
  }
}


function getItem(xml, item) {
  var a = xml.getElementsByTagName(item);
  if (!a || a.length < 1 || a[0].childNodes.length < 1)
    return '';
  var d = '';
  for(var i = 0; i < a[0].childNodes.length; ++i)
  	d += a[0].childNodes[i].nodeValue;
  return d;
}


var markers = [];
function showEvents(xml) {
  var e;
  e = document.getElementById('dataTable');     if (e) e.innerHTML = getItem(xml, 'tableHtml');
  e = document.getElementById('divPagination'); if (e) e.innerHTML = getItem(xml, 'paginationHtml');

  var events = xml.getElementsByTagName('eventData');
  for(var i = 0; i < events.length; ++i){
    markers[markers.length] = createMarker(
      new GLatLng(parseFloat(getItem(events[i], 'latitude')), parseFloat(getItem(events[i], 'longitude'))),
      '<div style=\'text-align: left; white-space: nowrap;\'>'
      + '<div style=\'width: 200px; height: 150px; overflow: hidden;\'><img src=\"/includes/image.php?table=event&column=flier_tn&id='+getItem(events[i], 'id')+'\" /></div>'
      + '<strong>'+getItem(events[i], 'eventName')+'</strong><br />'
      + 'Venue:'+getItem(events[i], 'locationName')+'<br />'
      + (getItem(events[i], 'city') ? getItem(events[i], 'city')+', '+getItem(events[i], 'state')+' '+getItem(events[i], 'zip')+'<br />' : '')
      + '<a href=\"'+getItem(events[i], 'url')+'\">[ Details ]</a></div>',
      e ? icon : iconNear);
  }

  if (events.length > 0) {
    zoomToBounds(map, markers, e ? cityCenter : markers[0].center);
    map.addOverlays(markers);
    if (!e) GEvent.trigger(markers[0],'click');
  }
}


function zoomToBounds(map, ary, center)
{
  var bounds = arrayBounds(ary);
  if (typeof center == 'undefined' ) {
    var center_lat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) / 2.0;
    var center_lng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) / 2.0;
    var center = new GLatLng(center_lat, center_lng)
  } else {
    var lat = Math.max(Math.abs(bounds.getNorthEast().lat() - center.lat()), Math.abs(bounds.getSouthWest().lat() - center.lat()));
    var lng = Math.max(Math.abs(bounds.getNorthEast().lng() - center.lng()), Math.abs(bounds.getSouthWest().lng() - center.lng()));
    bounds = new GLatLngBounds(new GLatLng(center.lat() - lat, center.lng() - lng), new GLatLng(center.lat() + lat, center.lng() + lng))
  }
  var zoom = map.getBoundsZoomLevel(bounds);
  if (zoom > 16) zoom = 16;
  map.setCenter(center, zoom);
}


// Creates a marker whose info window displays the given number
function createMarker(point, label, icon)
{
  var marker = new GMarker(point, icon);

  // Show this marker's index in the info window when it is clicked
  var html = label;

  GEvent.addListener(marker, "click", function()
  {
    marker.openInfoWindowHtml(html);
  });

  return marker;
}

// Call this once instead of multiple .addOverlay /////////////
GMap2.prototype.addOverlays=function(markers)
{
	for (var i = 0; i < markers.length; ++i)
	{
		map.addOverlay(markers[i]);
	} 	
};

// Return a GMap bounds object the size of an array of markers
function arrayBounds(ary)
{
    // compute the bounds for an array of markers
    var bounds = new GLatLngBounds();
    if (ary && ary.length > 0)
	{
        for (var i = 0; i < ary.length; i++)
		{
            var marker = ary[i];
            if (marker)
			{
                bounds.extend(marker.getPoint());
            }
        }
    }
    return bounds;
}

// Create icons ///////////////////////////////////////////////////////////
var icon, iconNear;
function createIcons() {
  icon = new GIcon();

  icon.image = "/images/icons/point-red.png";
  icon.shadow = "/images/icons/point-shadow.png";
  icon.iconSize = new GSize(12, 20);
  icon.shadowSize = new GSize(22, 20);
  icon.iconAnchor = new GPoint(6, 20);
  icon.infoWindowAnchor = new GPoint(5, 1);

  iconNear = new GIcon(icon);
  iconNear.image = "/images/icons/point-blue.png";
}

/**************************************************************************************************************/

/******* INTERACTIVE DB_ADMIN TABLES (used for colorized visual effects) ************************/
var lastFocused = null;
function addHighlights()
{
	var content = document.getElementById('content');
  	var inputs = content.getElementsByTagName("input");
	var textareas = content.getElementsByTagName("textarea");
	var selects = content.getElementsByTagName("select");

	var numInputs = inputs.length;
	var numTextAreas = textareas.length;
	var numSelects = selects.length;

	for ( i=0; i < numInputs; i++ )
	{
		var currentInput = inputs[i];
		currentInput.onfocus = onFocus;
		currentInput.onblur = onBlur;
		currentInput.onmouseover = onOver;
		currentInput.onmouseout = onOut;
	}

	for ( i=0; i < numTextAreas; i++ )
	{
		var currentTextArea = textareas[i];
		currentTextArea.onfocus = onFocus;
		currentTextArea.onblur = onBlur;
		currentTextArea.onmouseover = onOver;
		currentTextArea.onmouseout = onOut;
	}

	for ( i=0; i < numSelects; i++ )
	{
		var currentSelect = selects[i];
		currentSelect.onfocus = onFocus;
		currentSelect.onblur = onBlur;
		currentSelect.onmouseover = onOver;
		currentSelect.onmouseout = onOut;
	}
}
function onFocus()
{
		lastFocused = this;
		this.style.background = '#FFFFFF';
		this.style.border = '1px solid #CC6600';
		this.style.color = '#CC6600';
}
function onBlur()
{
	this.style.background = '#ECECEC';
	this.style.border = 'solid 1px #B0B0B0';
	this.style.color = '#000000';
}
function onOver()
{
	if (this != lastFocused)
	{
		this.style.background = '#F8F8F8';
		if (this.type == "button") this.style.cursor = 'pointer';
	}
}
function onOut()
{
	if (this != lastFocused)
	{
		this.style.background = '#ECECEC';
		this.style.border = 'solid 1px #B0B0B0';
		this.style.color = '#000000';
	}
}
/*********************************************************/



function flashMapCode(id, type_)
{
  var dimensions = { 'small': [ 425, 445 ], 'wide': [ 728, 445 ] };
  var w = dimensions[type_][0], h = dimensions[type_][1];
  return '' +
'<embed width="' + w + '" height="' + h + '" align="middle" quality="high"\n' +
'   src="http://www.beatmaps.com/flash/' + type_ + '.swf?sourceID=' + id + '"\n' +
'   pluginspage="http://www.macromedia.com/go/getflashplayer"\n' +
'   type="application/x-shockwave-flash" name="beatmaps"\n' +
'   allowscriptaccess="sameDomain" bgcolor="#ffffff">\n' +
'</embed>';
}

function htmlEncode(s)
{
  return s.replace(/</, '&lt;').replace(/\n/, '<br/>\n');
}

var mapDialogs = {};
function expandShowMap(id, prefix)
{
  if (!mapDialogs[prefix]) {
    var html = '' +
'      <div style="text-align: left">' +
'        <div style="font-size: larger; font-weight: bold;">' +
'          Use this code to include an interactive beatmaps.com map on your website or MySpace profile:' +
'        </div>' +
'        <br/>' +
'        <div id="divMapTabs' + prefix + '" class="yui-navset">' +
'          <ul class="yui-nav">' +
'            <li class="selected"><a href="#tab1"><em>Small</em></a></li>' +
'            <li><a href="#tab2"><em>Wide</em></a></li>' +
'          </ul>' +
'          <div class="yui-content">' +
'            <div><div class="htmlcode">' + htmlEncode(flashMapCode(id, 'small')) + '</div><div>' + flashMapCode(id, 'small') + '</div></div>' +
'            <div><div class="htmlcode">' + htmlEncode(flashMapCode(id, 'wide' )) + '</div><div>' + flashMapCode(id, 'wide' ) + '</div></div>' +
'          </div>' +
'        </div>' +
'      </div>';
    document.getElementById("divMap" + prefix).innerHTML = html;
    var tabs = new YAHOO.widget.TabView("divMapTabs" + prefix);
    var dialog = new YAHOO.widget.Panel("divMap" + prefix,
              { width : "750px", 
                fixedcenter : true, 
                visible : false,  
                close: true, 
                constraintoviewport : true
               } );
    dialog.setHeader("Interactive beatmaps.com map");
    dialog.render();
    mapDialogs[prefix] = dialog;
  }
  mapDialogs[prefix].show();
}

function hideShowMap(prefix)
{
  mapDialogs[prefix].hide();
}
