/**************************************************
 * Validations
 **************************************************/

/***
 * Validates if a given string is a numeric string
 * @param sText the string
 * @returns {Boolean} true if is a valid phone number
 */
function isNumeric(sText)
{
	var ValidChars = "0123456789";
	var IsNumber=true;
	var Char;
	for (i = 0; i < sText.length && IsNumber == true; i++) 
	{ 
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1)
			IsNumber = false;
	}
	return IsNumber;
}

/***
 * Validates if a determined string is a valid portuguese phone number
 * (without country code)
 * @param sText the string with the phone number
 * @returns {Boolean} true if is a valid phone number
 */
function isValidPhoneNumber(sText)
{
	if(sText[0] == '9' && sText.length == 9)
		return true;
	return false;
}

/**************************************************
 * Cookies						
 **************************************************/

/***
 * Stores a cookie in the browser cache
 * @param name a string with the cookie name
 * @param value a string with the cookie value
 * @param days the number of days to persist the cookie
 */
function createCookie(name, value, days) 
{
	logDebug("[widget-framework-util] createCookie("+name+","+value+","+days+")");
	
	if (days) 
	{
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		var expires = "; expires=" + date.toGMTString();
	}
	else var expires = "";
	document.cookie = name + "=" + value + expires + "; path=/";
}

function createCookieWithSeconds(name, value, seconds) 
{
	logDebug("[widget-framework-util] createCookie("+name+","+value+","+seconds+")");
	
	if (seconds) 
	{
		var date = new Date();
		date.setTime(date.getTime() + (seconds * 1000));
		var expires = "; expires=" + date.toGMTString();
	}
	else var expires = "";
	document.cookie = name + "=" + value + expires + "; path=/";
}

/***
 * Reads a cookie
 * @param name a string with the cookie name
 * @returns a string with the cookie value.
 */
function readCookie(name) 
{
	logDebug("[widget-framework-util] readCookie("+name+")");
	
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for (var i = 0; i < ca.length; i++) 
	{
		var c = ca[i];
		while (c.charAt(0) == ' ') c = c.substring(1, c.length);
		if (c.indexOf(nameEQ) == 0) 
		{
			logDebug("\t Cookie value: "+ c.substring(nameEQ.length, c.length));
			return c.substring(nameEQ.length, c.length);
		}
	}

	logDebug("\t Cookie not found");
	return null;
}
/****************************************************
 * Logging / Debug
 ****************************************************/

/***
 * If the console variable is available (it is not in IE) and isDebug is set, logs a 
 * debug message to the console
 * @param message the message to log
 */
function logDebug(message)
{
	var isDebug = "";
	//readFromQueryString code duplicated here, in order to properly log readFromQueryString call (would be recursive if we didn't)
	var parameterName = "debug"
	parameterName = parameterName.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
	var regexS = "[\\?&]" + parameterName + "=([^&#]*)";
	var regex = new RegExp(regexS);
	var results = regex.exec(window.location.href);
	if(results != null)
		isDebug = decodeURIComponent(results[1].replace(/\+/g, " "));

	if(isDebug == "true" && (typeof(console != "undedined") || typeof(console.log != "undefined")))
		console.log(message);
}
/****************************************************
 * Query strings
 ****************************************************/

/***
 * Reads a parameter from the query string
 * @param name a string with the name of the query string parameter
 * @returns a string with the query string parameter value
 */
function readFromQueryString(name)
{
	logDebug("[widget-framework-util] readFromQueryString("+name+")");
	
	name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
	var regexS = "[\\?&]" + name + "=([^&#]*)";
	var regex = new RegExp(regexS);
	var results = regex.exec(window.location.href);
	var s = null;
	if(results == null)
		s = "";
	else
		s = decodeURIComponent(results[1].replace(/\+/g, " "));
	
	logDebug("\t Parameter value: " + s);
	return s;
}

// some general purpose javascript functions
function getElementById(elementId) {
  if (document.getElementById) { // DOM3 = IE5, NS6
    return document.getElementById(elementId);
  }
  else if (document.layers) { // Netscape 4
    return document.elementId;
  }
  else { // IE 4
    return document.all.elementId;
  }
}

function initializeMap(divId, latitudes, longitudes, labels, addresses) {
  var count = latitudes.length;
  var i;

  if (GBrowserIsCompatible() && count > 0) {
    var map = new GMap2(document.getElementById(divId));
    var center = new GLatLng(latitudes[0], longitudes[0]);

    if (count == 1) {
      map.setCenter(center, 12);
    } else {
      map.setCenter(center, 1);
    }

    var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(5, 5));
    var topLeft = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(5, 5));

    map.addControl(new GMapTypeControl(), topLeft);
    map.addControl(new GSmallMapControl(), topRight);

    for (i = 0; i < count; i++) {
      var marker = createGMapMarker(map, latitudes[i], longitudes[i], labels[i], addresses[i]);
      map.addOverlay(marker);
    }
  }
}

function createGMapMarker(map, latitude, longitude, label, address) {
  var location = new GLatLng(latitude, longitude);
  var marker = new GMarker(location);

  GEvent.addListener(marker, 'click', function() {
    var info = "";
    if (label != null && label != "") {
      info += "<b>" + label + "</b>";
    }
    if (address != null && address != "") {
      info += "<br/>Address: " + address;
    }

    if (info != "") {
      map.openInfoWindowHtml(location, info);
    }
  });
  return marker;
}
function showWidgetOnClick(elementId){
  $('#widget-div-main-'+elementId).click(function(e){
    if(configWidgetShowingPopupId != null){
      if(configWidgetShowingPopupId != 'widget-div-popup-'+elementId)  {
        $('#'+configWidgetShowingPopupId).fadeOut(1500);
      }
    }
    if(configWidgetSelectedMainDivId != null){
      if(configWidgetSelectedMainDivId != 'widget-div-main-'+elementId)  {
        $('#'+configWidgetSelectedMainDivId).css({background:'darkgray'});
      }
    }

    configWidgetShowingPopupId = 'widget-div-popup-'+elementId;
    configWidgetSelectedMainDivId = 'widget-div-main-'+elementId;
    var height = $('#widget-div-popup-'+elementId).height();
    var width = $('#widget-div-popup-'+elementId).width();
    leftVal=e.pageX+"px";
    topVal=e.pageY+"px";
    $('#widget-div-main-'+elementId).css({background:'cadetblue'});
    $('#widget-div-popup-'+elementId).css({left:leftVal,top:topVal}).show();
  });
}
function hideWidget(wigetId){
  configWidgetShowingPopupId = null;
  configWidgetSelectedMainDivId = null;
  $('#widget-div-popup-'+wigetId).fadeOut(1500);
  $('#widget-div-main-'+wigetId).css({background:'darkgray'});
}
