// our map!
var map;
var mode = 'month';
var last_month = 0;

Event.observe(window, 'load', function() {
  if (GBrowserIsCompatible()) {
    // create our map within the given element
    map = new GMap2($('world-map'));
    map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());
    
    // start with the map in the desired location
    map.setCenter(new GLatLng(12.5545, 22.8515), 2);
  }

  // want clicking checkboxes to trigger off the search too
  $$('.tt_cb').each(function(elm){
    var cb = elm.down('input');
    Event.observe(cb, 'click', single_change);
  });

	// deal with the select all/none button
  Event.observe('all-tours', 'click', master_change);

  // switch to run in year mode on startup
  switch_mode();

  // set the default month and year
  set_month_header();

  // run the standard search as soon as the page loads
  run_search();
});

function clear_map(){
  map.clearOverlays();
}

function single_change() {
	// check to make sure the master control is in the right position
	var master_checked = true;
  $$('.tt_cb').each(function(elm){
    var cb = elm.down('input');
		if (!cb.checked)
			master_checked = false;
  });

	// may need to flick the master control
	if (master_checked != $('all-tours').checked)
		$('all-tours').checked = master_checked;
	
	// run a new search
	run_search();
}

function master_change() {
	var dirty = false;
	var master_checked = $('all-tours').checked;
	
	// update any single controls to match the master
  $$('.tt_cb').each(function(elm){
    var cb = elm.down('input');
		if (cb.checked != master_checked) {
			cb.checked = master_checked;
			dirty = true;
		}
  });

	// run a new search if any single controls changed
	if (dirty)
		run_search();
}


function add_tournament(id, lat, lon, name, alias, path, img_html, country, start_date, end_date, town, media){
  // put a marker in the center
  var latlon = new GLatLng(lat, lon);
  var marker = new GMarker(latlon);
  map.addOverlay(marker);
  
  var media_html = '';
  media.each(function(med) {
  	media_html += '<div style="float:left;margin-right:10px;">' + med.thumb_html + '</div>';
  });
  if (media_html != '') {
  	media_html = '<div class="clear"></div><div style="float:left;margin-top:5px;"><strong>Latest Media -</strong><br />' + media_html + '</div><div class="clear"></div>';
  }
  
  GEvent.addListener(marker, "mouseover", function() {
    var html = '';
    html += '<div>';
    html += ' <div class="cal-tourn-avatar">' + img_html + '</div>';
    html += ' <div class="cal-tourn-details">';
    html += '   <h2><a href="/tournaments/' + alias + '" class="glink" title="' + name + '">'+name+'</a></h2>';
    html += '   <p>'+town+', '+country+'<br />';
    html += '   '+dateFormat(start_date, "mmmm dd yyyy")+' - '+dateFormat(end_date, "mmmm dd yyyy")+'</p>';
    html += '   <p><a href="/tournaments/' + alias + '" title="View Profile">view profile &raquo;</a></p>';
    html += ' </div>';
    html += '</div>';
    html += media_html;
    
    marker.openInfoWindowHtml(html);
  });
}

function switch_mode() {
	if (mode == 'month') {
		// switch to year mode
	  mode = 'year';
 	  $('cal_mode').down('a').innerHTML = 'View By Month';
	  $('prev_link').src = '/images/buttons/btn_prev_year.gif';
	  $('next_link').src = '/images/buttons/btn_next_year.gif';
	  last_month = $('cr_month').value;
	  $('cr_month').value = '';
	  set_month_header();
	  run_search();
	} else {
		// switch to month mode
	  mode = 'month';
 	  $('cal_mode').down('a').innerHTML = 'View By Year';
	  $('prev_link').src = '/images/buttons/btn_prev_month.gif';
	  $('next_link').src = '/images/buttons/btn_next_month.gif';
	  $('cr_month').value = last_month;
	  set_month_header();
	  run_search();
	}
}

function goto_last() {
	if (mode == 'year') {
		var year = current_year();
		$('cr_year').value = year - 1;
	} else {
	  // current month / year
	  var month = current_month();
	  var year = current_year();
	  
	  // reset the year / month
	  if (month == 1) {
	    $('cr_month').value = 12;
	    $('cr_year').value = year - 1;
	  } else {
	    $('cr_month').value = month - 1;
	  }
	}
  
  // update the header
  set_month_header();
  // rerun the search
  run_search();
}
function goto_next() {
	if (mode == 'year') {
		var year = current_year();
		$('cr_year').value = year + 1;
	} else {
	  // current month / year
	  var month = current_month();
	  var year = current_year();
	  
	  // reset the year / month
	  if (month == 12) {
	    $('cr_month').value = 1;
	    $('cr_year').value = year + 1;
	  } else {
	    $('cr_month').value = month + 1;
	  }
	}

  // update the header
  set_month_header();
  // rerun the search
  run_search();
}

function current_month() {
  return parseInt($F('cr_month'));
}
function current_year() {
  return parseInt($F('cr_year'));
}

function set_month_header() {
  var year = current_year();

	if (mode == 'year') {
	  // set the year
	  $('month_header').innerHTML = year.toString();
	} else {
	  var month = current_month();	
	  // figure out the name of the month
	  var months = new Array("January","February","March","April","May","June","July","August","September","October","November","December")
	  var monthname = months[month-1];
	  // set the new month and year
	  $('month_header').innerHTML = monthname.toUpperCase() + ' ' + year.toString();
	}

  // rerun sifr
	if (typeof sIFR == "function") {
    $('month_header').removeClassName('sIFR-replaced')
    sIFR.replaceElement(named({sSelector:"#month_header", sFlashSrc:"/flash/din.swf", sColor:"#FFFFFF", sLinkColor:null, sBgColor:null, sHoverColor:null, nPaddingTop:0, nPaddingBottom:0, sFlashVars:"offsetTop=15&textalign=left&offsetLeft=0&offsetTop=0&offsetBottom=10", sWmode:"transparent" }));
  }
}

function run_search() {
  // primitive counting system to to ensure that we don't show delayed requests
  $('req_id').value = parseInt($('req_id').value) + 1;

  finishAjaxSubmit('tournament_search');
}

var last_req_id = 0;
function tournament_search_onSuccess(t){
  var result = t.responseJSON;
  // only show newer request responses
  if (result.req_id > last_req_id) {
    last_req_id = result.req_id;
    // clear out the old tournaments first
    clear_map();

    // now add all the new ones in
    result.tournaments.each(function(tournament){
      add_tournament(tournament.ID, tournament.LAT, tournament.LON, tournament.NAME, tournament.ALIAS, tournament.thumb_path, tournament.img_html, tournament.COUNTRY, tournament.START_DATE, tournament.END_DATE, tournament.TOWN, tournament.media);
    });
  }
}

