var var_tabs;
var help;

function validateITDate( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains only
    valid dates with 2 digit month, 2 digit day,
    4 digit year. Date separator can be /.
    Uses combination of regular expressions and
    string parsing to validate date.
    Ex. dd/mm/yyyy

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.

REMARKS:
   Avoids some of the limitations of the Date.parse()
   method such as the date separator character.
*************************************************/
  var objRegExp = /^\d{1,2}\/\d{1,2}\/\d{4}$/
 
  //check to see if in correct format
  if(!objRegExp.test(strValue))
    return false; //doesn't match pattern, bad date
  else{
    var strSeparator = '/';
    var arrayDate = strValue.split(strSeparator); 
    //create a lookup for months not equal to Feb.
    var arrayLookup = { '01' : 31,'03' : 31, 
                        '04' : 30,'05' : 31,
                        '06' : 30,'07' : 31,
                        '08' : 31,'09' : 30,
                        '10' : 31,'11' : 30,'12' : 31}
    var intDay = parseInt(arrayDate[0],10); 

    //check if month value and day value agree
    if(arrayLookup[arrayDate[1]] != null) {
      if(intDay <= arrayLookup[arrayDate[1]] && intDay != 0)
        return true; //found in lookup table, good date
    }
    
    //check for February (bugfix 20050322)
    //bugfix  for parseInt kevin
    //bugfix  biss year  O.Jp Voutat
    var intMonth = parseInt(arrayDate[1],10);
    if (intMonth == 2) { 
       var intYear = parseInt(arrayDate[2]);
       if (intDay > 0 && intDay < 29) {
           return true;
       }
       else if (intDay == 29) {
         if ((intYear % 4 == 0) && (intYear % 100 != 0) || 
             (intYear % 400 == 0)) {
              // year div by 4 and ((not div by 100) or div by 400) ->ok
             return true;
         }   
       }
    }
  }  
  return false; //any other values, bad date
}

jQuery(document).ready(function() {
	var_tabs = $("#contenuto > ul").tabs();
	ridimensiona();
	carica_mappa();
	$(window).bind('resize', ridimensiona);	
});

function ridimensiona() {
	alt = $(window).height() - 175;
	if (alt < 300) alt = 300;
	$('#map').height(alt);
	$('#container_sms').height(alt);
	larg = $(window).width() - 250; 
	if (larg < 500) larg = 500;
	$('#map').width(larg);
}

function carica_punti() {
	var search_date = $('#searchdate_mappa').val();
	//alert(search_date);
	if(search_date && search_date.length > 0){
		//verificare formato
		//if( !search_date.match(/^[0-3]?[1-9]\/[0-1]?[1-9]\/\d\d\d\d$/)){
		if ( !validateITDate( search_date ) ) {
			alert("Il formato della data deve essere g/mm/aaaa");
			return;
		}
	} else {
		search_date = '';
	}
	//alert('go ajax!');
	$.ajax({  
		url: 'leggi_posizioni_apparecchio.php',
		type: 'POST',
		data: '&data_search='+search_date,
		dataType: 'xml', 
		success: function(xml){
			rimuoviTutti();
			$('#elenco_sms').html('');
			 var i = 0;
			$('sms', xml).each(function(){
				i++;
				numero = $('numero', this).text();
				num_sms = $('num_sms', this).text();
				ora_invio = $('ora_invio', this).text();
				latitudine = $('latitudine', this).text();
				longitudine = $('longitudine', this).text();
				batteria = $('batteria', this).text();
				gps = $('gps', this).text();
				gsm = $('gsm', this).text();
				tipo_sms = $('tipo_sms', this).text();
				
				if (num_sms == 'primo') icona = 'start';
				else if (num_sms == 'ultimo') icona = 'end';
				else icona = 'normal';
				
				messaggio = tipo_sms + "<br />" + latitudine + ", " + longitudine + "<hr />Inviato il: " + ora_invio + "<br />Stato batteria: " + batteria + "%<br />Segnale GPS: " + gps + "<br />Segnale GSM: " + gsm;
				inserisciMarker(latitudine, longitudine, messaggio, icona);
				if (num_sms == 'ultimo') {
					map.setZoom(14);
					map.panTo(new GLatLng(latitudine, longitudine));
				}
				
				$('#elenco_sms').append("<div class='sms_ricevuto'><a href='#' onclick='map.panTo(new GLatLng(" + latitudine + ", " + longitudine + "));return false;'>" + i + " - " + ora_invio + "</a></div>");
				
			});
		}
	});
};

function cambia_apparecchio_visualizzato(serial_check) {
	var selected = var_tabs.data('selected.tabs');
	//alert('serial_check:'+serial_check);
	$.ajax({
		url: 'imposta_apparecchio_visualizzato.php', 
		data: 'app=' + serial_check, 
		success: function() {
			carica_punti();
			if (selected > 1) var_tabs = $("#contenuto > ul").tabs('load', selected);
		}
	});
}

function esegui_squillo() {
	$.ajax({ 
		url: 'invia_sms.php', 
		type: "GET", 
		data: "squillo=1", 
		success: function(text) {
			risultato = text.substring(0, 2);
			messaggi = text.substring(2, text.length);
			
			alert(messaggi);
		}
	});
};

jQuery(document).unload(function() {
	GUnload();
});

function showHelp(servizio) {
	var position = $('#help_img_'+servizio).position();
	//alert(servizio);
	//alert(help[servizio]);
	$('#help_inlinea_content').html(help[servizio]);//qui devo leggere la variabile js che si chiama servizio
	$('#help_inlinea').css( {'top' : position.top+20, 'left' : 10 } );
	$('#help_inlinea').show('fast');
}


