function findPosX(obj)
{
  var curleft = 0;
  if(obj.offsetParent)
      while(1) 
      {
        curleft += obj.offsetLeft;
        if(!obj.offsetParent)
          break;
        obj = obj.offsetParent;
      }
  else if(obj.x)
      curleft += obj.x;
  return curleft;
}

function findPosY(obj)
{
  var curtop = 0;
  if(obj.offsetParent)
      while(1)
      {
        curtop += obj.offsetTop;
        if(!obj.offsetParent)
          break;
        obj = obj.offsetParent;
      }
  else if(obj.y)
      curtop += obj.y;
  return curtop;
}
//This function gets called when the end-user clicks on some date.
function selected(cal, date) {
  cal.sel.value = date; // just update the date in the input field.
  if (cal.dateClicked)
    cal.callCloseHandler();
}

// And this gets called when the end-user clicks on the _selected_ date,
// or clicks on the "Close" button.  It just hides the calendar without
// destroying it.
function closeHandler(cal) {
  cal.hide();                        // hide the calendar
//  cal.destroy();
  if (cal.sel.onchange) {
	  cal.sel.onchange();
  }
  _dynarch_popupCalendar = null;
}

// This function shows the calendar under the element having the given id.
// It takes care of catching "mousedown" signals on document and hiding the
// calendar if the click was outside.
function showCalendar(id, format, showsTime, showsOtherMonths) {
  var el = document.getElementById(id);
  if (el.disabled == true) {
    return false;
  }
  if (_dynarch_popupCalendar != null) {
    // we already have some calendar created
    _dynarch_popupCalendar.hide();                 // so we hide it first.
  } else {
    // first-time call, create the calendar.
    var cal = new Calendar(1, null, selected, closeHandler);
    // uncomment the following line to hide the week numbers
    // cal.weekNumbers = false;
    if (typeof showsTime == "string") {
      cal.showsTime = true;
      cal.time24 = (showsTime == "24");
    }
    if (showsOtherMonths) {
      cal.showsOtherMonths = true;
    }
    _dynarch_popupCalendar = cal;                  // remember it in the global var
    cal.setRange(1900, 2070);        // min/max year allowed.
    	    
    cal.create();
  }
  _dynarch_popupCalendar.setDateFormat(format);    // set the specified date format
  _dynarch_popupCalendar.parseDate(el.value);      // try to parse the text in field
  _dynarch_popupCalendar.sel = el;                 // inform it what input field we use

  // the reference element that we pass to showAtElement is the button that
  // triggers the calendar.  In this example we align the calendar bottom-right
  // to the button.
  var calButton = document.getElementById(id + "_img");
  var calX = findPosX(calButton) + 24;
  var calY = findPosY(calButton);
  _dynarch_popupCalendar.showAt(calX, calY);        // show the calendar

  return false;
}

var phoneCounter = 1;
function addPhone() {
	var phoneTable = document.getElementById("phones_table");
	var rowCount = phoneTable.rows.length;
	var lastRow = phoneTable.rows[rowCount - 1];
	var lastRowButton = lastRow.cells[1];
	lastRowButton.innerHTML = "<input type='button' class='remove_phone' onclick='removePhone(" + phoneCounter + ")'/>";
	var newRow = phoneTable.insertRow(rowCount);
	newRow.id = "phoneTableRow_" + (phoneCounter + 1);
	var inputRow = newRow.insertCell(0);
	var buttonRow = newRow.insertCell(1);
	inputRow.innerHTML = "<input type='text' name='phones' />";
	buttonRow.innerHTML = "<input type='button' class='add_phone' onclick='addPhone()'/>";
	phoneCounter++;
}

function removePhone(index) {
	var phoneTable = document.getElementById("phones_table");
	for (i = 0; i < phoneTable.rows.length; i++) {
		if (phoneTable.rows[i].id == "phoneTableRow_" + index) {
			phoneTable.deleteRow(i);
			break;
		}
	}
}
function showCantonLoader() {
	document.getElementById('canton_loader').style.display='';
}
function hideCantonLoader() {
	document.getElementById('canton_loader').style.display='none';
}
function centerMap() {
	var reference_combo = document.getElementById('reference');
	var point = map_references[reference_combo.options[reference_combo.selectedIndex].value];
	map.setCenter(point,16);
}
function centerBusinessMarker() {
	var reference_combo = document.getElementById('reference');
	var point = map_references[reference_combo.options[reference_combo.selectedIndex].value];
	businessMarker.setLatLng(point);
	map.setCenter(point,16);
}
var circleOverlay;
function centerOnUserLocation() {
	if (navigator.geolocation) {  
        navigator.geolocation.getCurrentPosition(function(position) {
		    var point = new GLatLng(position.coords.latitude, position.coords.longitude);
			map.setCenter(point,15);
			if (!circleOverlay) {
				circleOverlay = getCircleOverlay(position.coords.latitude, position.coords.longitude, position.coords.accuracy);
				map.addOverlay(circleOverlay);
			}
        });
    } else {  
        alert("El navegador utilizado no soporta esta caracteristica. Descargue Firefox 3.5");
    }
}
function getCircleOverlay (lat, lon, err) { // math lifted from maps.forum.nu. you want map examples, go there.
	with (Math) {
		var points = Array();
		var d = err/6378800;
		// accuracy / meters of Earth radius = radians
		var lat1 = (PI/180)* lat;
		// radians
		var lng1 = (PI/180)* lon;
		// radians
		for (var a = 0 ; a < 361 ; a+=10 ) {
			var tc = (PI/180)*a;
			var y = asin(sin(lat1)*cos(d)+cos(lat1)*sin(d)*cos(tc));
			var dlng = atan2(sin(tc)*sin(d)*cos(lat1),cos(d)-sin(lat1)*sin(y));
			var x = ((lng1-dlng+PI) % (2*PI)) - PI ;
			// MOD function
			var point = new GLatLng(parseFloat(y*(180/PI)),parseFloat(x*(180/PI)));
			points.push(point);
		}
	}
	return new GPolygon(points,'#0000ff',1,1,'#0000ff',0.2)
}
function showChallengesLoader(callback) {
	$("#loading_challenges").fadeIn(500);
	$("#challenges").fadeOut(1500, callback);
}
function hideChallengesLoader() {
	$("#loading_challenges").fadeOut(500);
	$("#challenges").fadeIn(1500);
}
function showRemoteBusinessLoader(callback) {
	$("#loadingFromRemoteBusiness").fadeIn(500);
	$("#reservations").fadeOut(1500, callback);
}
function hideRemoteBusinessLoader() {
	$("#loadingFromRemoteBusiness").fadeOut(500);
	$("#reservations").fadeIn(1500);
}
var dateChangedUrl;
function dateChanged(calendar) {
	if (calendar.dateClicked) {
		showChallengesLoader(function() {
			var typeValue = document.getElementById("type").value;
			$('#challenges').load(dateChangedUrl + '?date=' + y + "-" + m + "-" + d + "&type=" + typeValue, null, hideChallengesLoader);
		});
		var y = calendar.date.getFullYear();
		var m = calendar.date.getMonth() + 1;
		var d = calendar.date.getDate();
	}
}
function loadReservationsForDate(reservationDate) {
	currentDate = reservationDate;
	showRemoteBusinessLoader(function() {
		var url = contextUrl + 'remoteBusiness/updateReservations/' + idValue + '?date=' +
		reservationDate + 
		"&playField.id=" + playFieldIdValue + "&playField.name=" + playFieldNameValue +
		"&playField.scheduleFrom=" + playFieldScheduleFromValue +
		"&playField.scheduleTo=" + playFieldScheduleToValue;
		$('#reservations').load(url, null, hideRemoteBusinessLoader);
	});
}
function changeReservationDate(calendar) {
	if (calendar.dateClicked) {
		var y = calendar.date.getFullYear();
		var m = calendar.date.getMonth() + 1;
		var d = calendar.date.getDate();
		var reservationDate = y + "-" + m + "-" + d;
		loadReservationsForDate(reservationDate);
	} 
}
function typeFilterChanged() {
	showChallengesLoader(function() {
		var typeValue = document.getElementById("type").value;
		var y = cal.date.getFullYear();
		var m = cal.date.getMonth() + 1;
		var d = cal.date.getDate();
		$('#challenges').load('updateChallenges?date=' + y + "-" + m + "-" + d + "&type=" + typeValue, null, hideChallengesLoader);
	});
}
function isDisabled(date) {
	var today = new Date();
	today.setDate(today.getDate() - 1);
	var MINUTE = 60 * 1000;
	var HOUR = 60 * MINUTE;
	var DAY = 24 * HOUR;
	return date.getTime() < today.getTime() || ((date.getTime() - today.getTime()) / DAY) > 20;
}
// Debe sobreescribirse si se necesita
var myCarouselShowed = function() {}
var showMyCarousel = function() {
	$('#carousel').fadeIn(1500);
	myCarouselShowed();
}
var globalWindowLoad = function() {
	$('#carousel').Carousel(
		{
			itemWidth: 150,
			itemHeight: 100,
			itemMinWidth: 50,
			items: 'a',
			reflections: 0,
			rotationSpeed: 1
		}
	);
	myWindowLoad();
	$('#main_logo').fadeOut(1000, showMyCarousel);
	$.ImageBox.init(
		{
			loaderSRC: loadingUrl,
			closeHTML: closeHtml
		}
	);
};
var loadFishEye = function(){
	$('#fisheye').Fisheye(
		{
			maxWidth: 50,
			items: 'a',
			itemsText: 'span',
			container: '.fisheyeContainter',
			itemWidth: 40,
			proximity: 90,
			halign : 'center'
		}
	)
};
var showReservationForm = function(hour) {
	showRemoteBusinessLoader(function() {
		var url = contextUrl + 'remoteBusiness/createReservation/' + idValue + '?date=' +
		currentDate + 
		"&playField.id=" + playFieldIdValue + "&playField.name=" + playFieldNameValue +
		"&playField.scheduleFrom=" + playFieldScheduleFromValue +
		"&playField.scheduleTo=" + playFieldScheduleToValue +
		"&hour=" + hour;
		$('#reservations').load(url, null, hideRemoteBusinessLoader);
	});
}
var createReservation = function() {
	var errorsDiv = document.getElementById("errors");
	errorsDiv.style.display="none";
	var phoneValue = document.getElementById("ownerPhone").value;
	var emailValue = document.getElementById("email").value;
	var hourValue = document.getElementById("hour").value;
	var searchTeamValue = document.getElementById("searchTeam").checked;
	var refereeValue = document.getElementById("referee").checked;
	var ok = true;
	var phoneErrorRef = document.getElementById("phoneError");
	var emailErrorRef = document.getElementById("emailError");
	phoneErrorRef.style.display="none";
	emailErrorRef.style.display="none";
	
	if (!phoneValue.match("[0-9]{4}-[0-9]{4}")) {
		phoneErrorRef.style.display = "";
		ok = false;
	}
	if (!emailValue.match(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i)) {
		emailErrorRef.style.display = "";
		ok = false;
	}
	if (ok) {
		showRemoteBusinessLoader(function() {
			var hourValue = document.getElementById("hour").value;
			var url = contextUrl + 'remoteBusiness/reserve/' + idValue + '?date=' +
			currentDate + 
			"&playField.id=" + playFieldIdValue + "&playField.name=" + playFieldNameValue +
			"&playField.scheduleFrom=" + playFieldScheduleFromValue +
			"&playField.scheduleTo=" + playFieldScheduleToValue +
			"&reservation.field=" + playFieldIdValue +
			"&reservation.date=" + currentDate +
			"&reservation.email=" + emailValue +
			"&reservation.phone=" + phoneValue +
			"&reservation.searchTeam=" + searchTeamValue +
			"&reservation.referee=" + refereeValue +
			"&reservation.hour=" + hourValue;
			$('#reservations').load(url, null, hideRemoteBusinessLoader);
		});
	} else {
		errorsDiv.style.display = "";
	}
}
function showLoader(id) {
	document.getElementById(id).style.display = "";
}
function hideLoader(id) {
	document.getElementById(id).style.display = "none";
}
function ajaxTable(tableDivId, baseUrl) {
	var tableDiv = document.getElementById(tableDivId);
	var links = document.getElementsByTagName('A');
	for(var i = 0; i < links.length; i++) {
		if (links[i].parentNode.className.substr(0, 8) == 'sortable' ||
			links[i].parentNode.className == 'paginateButtons') {
			if (esPadre(tableDiv, links[i])) {
				var href = links[i].href;
				links[i].href = "#";
				var params = href.substring(href.indexOf('?') + 1, href.length);
				var paramArray = params.split("&");
				var paramsToUse = paramArray;
				var paramsString = "?";
				if (baseUrl.indexOf("?")>0) {
					paramsString = "&";
				}
				for (var j = 0; j < paramsToUse.length; j++) {
					paramsString += paramsToUse[j];
					if (j != paramsToUse.length - 1) {
						paramsString += "&";
					}
				}
				links[i].onclick = new Function("showLoader('loader');$('#" +
						tableDivId + "').load('" + baseUrl + paramsString +
						"', null, function() {hideLoader('loader');});return false;");
			}
		}
	}
}
function esPadre(padre, hijo) {
	var actual = hijo;
	var respuesta = false;
	while (actual.parentNode && !respuesta) {
		if (actual.parentNode.id == padre.id) {
			respuesta = true;
		} else {
			actual = actual.parentNode;
		}
	}
	return respuesta;
}
function replaceContent(url) {
	myWindowLoad = function() {};
	showLoader("loader_main_content");
	$("#main__content").load(url + "?ajax=true", null, function() {
		$(document).ready(function() {
		hideLoader("loader_main_content");
		ajaxBackLinks();
		myWindowLoad();
		});
	});
	return false;
}
function ajaxDiv(divId) {
	var divRef = document.getElementById(divId);
	var links = document.getElementsByTagName('A');
	for(var i = 0; i < links.length; i++) {
		if (esPadre(divRef, links[i])) {
			links[i].onclick = new Function("return replaceContent('" + links[i].href + "');");
		}
	}
}
function ajaxBackLinks() {
	var links = document.getElementsByTagName('A');
	for(var i = 0; i < links.length; i++) {
		if (links[i].parentNode.className == 'back_link') {
			links[i].onclick = new Function("return replaceContent('" + links[i].href + "');");
		}
	}
}
function selectAllOrNone(divId, all) {
	var divRef = document.getElementById(divId);
	var inputs = document.getElementsByTagName('input');
	for(var i = 0; i < inputs.length; i++) {
		if (inputs[i].type == "checkbox" && esPadre(divRef, inputs[i])) {
			if (all) {
				inputs[i].checked = "checked";
			} else {
				inputs[i].checked = "";
			}
		}
	}
}
function filtrarEquipos() {
	var genderValue = document.getElementById("gender").value;
	var provinceValue = document.getElementById("province").value;
	showLoader("filter_loader");
	$("#teamsToDiv").load("filterTeamsTo?gender=" + genderValue
		+ "&province=" + provinceValue, null, function() {
		$(document).ready(function() {
		hideLoader("filter_loader");
		var selectedTeamsRef = document.getElementById("selectedTeams");
		if (selectedTeamsRef.value != "") {
			var teamArray = selectedTeamsRef.value.split(",");
			var divRef = document.getElementById("teamsToDiv");
			var inputs = document.getElementsByTagName('input');
			for(var i = 0; i < inputs.length; i++) {
				if (inputs[i].type == "checkbox" && esPadre(divRef, inputs[i])) {
					if (teamArray.indexOf(inputs[i].value) != -1) {
						inputs[i].checked = "checked";
					} else {
						inputs[i].checked = "";
					}
				}
			}
		}
		selectedTeamsRef.value = "";
		});
	});
	return false;
}
function validateTeamsToSelected() {
	var valid = false;
	var divRef = document.getElementById("teamsToDiv");
	var inputs = document.getElementsByTagName('input');
	for(var i = 0; i < inputs.length; i++) {
		if (inputs[i].type == "checkbox" && esPadre(divRef, inputs[i])) {
			if (inputs[i].checked) {
				valid = true;
				break;
			}
		}
	}
	if (!valid) {
		alert("Debe seleccionar un equipo");
	}
	return valid;
}