/*
Funções de formatação de datas
converte data string iso8601 p/ tipo Date
http://delete.me.uk/2005/03/iso8601.html*/
function setISO8601(string, timezone) {
	if (!string)
		return null;

	var regexp="([0-9]{4})(-([0-9]{2})(-([0-9]{2})(T([0-9]{2}):([0-9]{2})(:([0-9]{2})?)?(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
	var d = string.match(new RegExp(regexp));

	var offset = 0;
	var year = d[1];
	var month = d[3] - 1;
	var day = d[5];
	var date = new Date(year, month, day, 12);
	if (d[7]) { date.setHours(d[7]); }
	if (d[8]) { date.setMinutes(d[8]); }
	if (d[10]) { date.setSeconds(d[10]); }
//	if (d[12]) { //pega o timezone concatenado na data ISO8601.
//		offset = (Number(d[14]) * 60) + Number(d[15]);      //converte o timezone para minutos.
//		offset *= ((d[13] == '-') ? -1 : 1);
//	}
	if (timezone && timezone != "")
		offset += setTimezoneToMinutes(timezone); // se é um FUSO, sempre SOMO c/ a hora UTC (zulu)
	else
		if (d[11]) /*Verifica se a data possui um Z no final dizendo que esta em ZULU Time.*/
			offset -= date.getTimezoneOffset(); /*pega o timezone offset da data passada, na máquina cliente.*/
		else
			offset = 0; /*nao executa nenhuma operacao na data*/

	time = (Number(date) + (offset * 60 * 1000));
	var formata_data = new Date();
	return formata_data.setTime(Number(time));
}

//chamada setTimezoneToMinutes("(2:00)"); ou setTimezoneToMinutes("2:00")
function setTimezoneToMinutes(timezone){
	var arrTimezone = new Array();
	var my_timezone;
	try{
		if (timezone.substring(1,0) == "(" && timezone.substring(timezone.length-1,timezone.length) == ")"){
			timezone = timezone.substring(1,timezone.length - 1); //remove os parenteses do timezone
			arrTimezone = timezone.split(':');                    //hora primeira posição do array, minutos na segunda posição.
			my_timezone = ((arrTimezone[0] * 60) + (arrTimezone[0] >= 0 ? 1 : -1)*arrTimezone[1] );
		}else{
			//caso o timezone não esteja entre parenteses.
			arrTimezone = timezone.split(':'); //hora na primeira posição do array, minutos na segunda posição.
			my_timezone = ((arrTimezone[0] * 60) + (arrTimezone[0] >= 0 ? 1 : -1)*arrTimezone[1] );
		}
	}catch(err){
		my_timezone = ""; //retorna timezone vazio se houver algum erro.
	}
	return my_timezone;
}

function getMonthName(month, idioma){
	var arrMonthPtb = new Array("Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro");
	var arrMonthEnu = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
	var arrMonthEsp = new Array("Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Deciembre");

	if (idioma == "ptb")
		return arrMonthPtb[month];
	else
		if (idioma == "enu")
			return arrMonthEnu[month];
	else
		if (idioma == "esp")
			return arrMonthEsp[month];

	return arrMonthPtb[month]; //default
}

/* chamada: FormatDateTime ("2005-08-22T20:02:34Z", "%d/%m/%Y - %Hh%M") */
function FormatDateTime(strISO8601, formatType, timezone, idioma){
	/*
		 FomatType takes the following values
			%d/%m/%Y - %H:%M:%S:%z (file date_format.xml)
			%d -> day      -> optional
			%m -> month	(numeric)   -> optional : Case Sensitive
			%n -> month (full name) -> optional
			%r -> mont  (short name) -> optional
			%y -> year	   -> optional
			%h -> hour     -> optional
			%M -> minute   -> optional     : Case Sensitive
			%s -> second   -> optional
			%z -> GMT time -> optional
			%L -> GMT time without parentheses -> optional.

			%m e %M possuem significados diferentes. Ver descrição acima.
	*/
	var datetime;
	if (!timezone) timezone = "";

	if (!isDate(strISO8601)){
		datetime = setISO8601(strISO8601, timezone);
	}
	else
		datetime = strISO8601;

	if (!datetime)
		return ""; //retorna vazio, se retornar null a saída será undefined.

	if (!formatType) {
		formatType = (idioma == "enu") ? "%m/%d/%y " : "%d/%m/%y";
	}

	if (!formatType && !idioma)
		formatType = "%d/%m/%y";  //short-date -> ptb.

	var strDate = new String(datetime);
	var myDate;
	myDate = new Date(datetime);
	strDate = String(myDate);

	// Get the date variable parts
	var Day     = myDate.getDate();
	var Month   = myDate.getMonth() + 1;
	var Hour    = myDate.getHours();
	var Minutes = myDate.getMinutes();
	var Seconds = myDate.getSeconds();
	var Year    = myDate.getFullYear();

	//converte para string, para colocar o zero a esquerda quando houver apenas um caracter
	var strMonth   = new String(Month);
	var strDay     = new String(Day);
	var strHour    = new String(Hour);
	var strMinutes = new String(Minutes);
	var strSeconds = new String(Seconds);
	var strYear    = new String(Year);

	if (strMonth.length==1){
		strMonth = "0"+strMonth;
	}
	if (strDay.length == 1){
		strDay = "0"+strDay;
	}
	if (strHour.length == 1){
		strHour = "0"+strHour;
	}
	if (strMinutes.length == 1){
		strMinutes  = "0"+strMinutes;
	}
	if (strSeconds.length == 1){
		strSeconds  = "0"+strSeconds;
	}

	newFormattedDate = "";
	for (var i = 0; i < formatType.length - 1; i++){
		if (formatType.charAt(i) == "%"){
			switch(formatType.charAt(i)+formatType.charAt(i+1)){
				case '%d' : case '%D' : newFormattedDate = newFormattedDate + strDay;   break;
				case '%m' : newFormattedDate = newFormattedDate + strMonth; break;
				case '%n' : case '%N' : newFormattedDate = newFormattedDate + getMonthName(Month - 1, idioma);  break;
				case '%r' : case '%R' : newFormattedDate = newFormattedDate + getMonthName(Month - 1, idioma).substring(0,3);  break;
				case '%y' : case '%Y' : newFormattedDate = newFormattedDate + strYear;  break;
				case '%h' : case '%H' : newFormattedDate = newFormattedDate + strHour;  break;
				case '%M' : newFormattedDate = newFormattedDate + strMinutes; break;
				case '%s' : case '%S' : newFormattedDate = newFormattedDate + strSeconds; break;
				case '%z' : case '%Z' : newFormattedDate = newFormattedDate = newFormattedDate + " (GMT " + printTimeZoneOffset(myDate) + ")";  break;
				case '%l' : case '%L' : newFormattedDate = newFormattedDate = newFormattedDate + " GMT " + printTimeZoneOffset(myDate);  break;
			}
			++i;
		}else{
			newFormattedDate = newFormattedDate + formatType.charAt(i);
		}
	}
	return newFormattedDate;
}
/*Fim da função de formatação de datas*/

/*Funcao isDate equivalente ao vbscript*/
function isDate(value){
	return !isNaN(new Date(value));
}

/*Funcao trim equivalente ao do vbscript*/
function trim(str){
	return str.replace(/^\s*|\s*$/g,"");
}

// integer division
function div(x,y) {var q=x/y; return q < 0 ? Math.floor(Math.abs(q)) : Math.floor(q);};

/* Retorna o TimeZoneOffset em horas */
function printTimeZoneOffset(myDate){
	var offset, isNegative = false;
	offset = myDate.getTimezoneOffset(); // minutos UTC - minutos Maquina

	minuteOffset	= (Math.abs(offset) % 60);
	hourOffset		= div(offset, 60);

	var strMinuteOffset = new String(minuteOffset);
	var strHourOffset   = new String(hourOffset);

	if (strMinuteOffset.length	== 1)	strMinuteOffset = "0" + strMinuteOffset;
	if (strHourOffset.length	== 1)	strHourOffset	= "0" + strHourOffset;

	return (offset > 0 ? '-' : '+' ) + strHourOffset + ':' + strMinuteOffset;
}

//compara short-dates.
function dateDiff(p_Interval, p_Date1, p_Date2){
	if(!isDate(p_Date1)){alert("invalid date: '" + p_Date1 + "'"); return false;}
	if(!isDate(p_Date2)){alert("invalid date: '" + p_Date2 + "'"); return false;}

	var dt1 = new Date(p_Date1);
	var dt2 = new Date(p_Date2);

	// get ms between dates (UTC) and make into "difference" date
	var iDiffMS = dt2.valueOf() - dt1.valueOf();
	var dtDiff = new Date(iDiffMS);

	// calc various diffs
	var nYears  = dt2.getUTCFullYear() - dt1.getUTCFullYear();
	var nMonths = dt2.getUTCMonth() - dt1.getUTCMonth() + (nYears!=0 ? nYears*12 : 0);
	var nQuarters = parseInt(nMonths/3);	//<<-- different than VBScript, which watches rollover not completion

	var nMilliseconds = iDiffMS;
	var nSeconds = parseInt(iDiffMS/1000);
	var nMinutes = parseInt(nSeconds/60);
	var nHours = parseInt(nMinutes/60);
	var nDays  = parseInt(nHours/24);
	var nWeeks = parseInt(nDays/7);


	// return requested difference
	var iDiff = 0;
	switch(p_Interval.toLowerCase()){
		case "yyyy": return nYears;
		case "q": return nQuarters;
		case "m": return nMonths;
		case "y": 		// day of year
		case "d": return nDays;
		case "w": return nDays;
		case "ww":return nWeeks;		// week of year	// <-- inaccurate, WW should count calendar weeks (# of sundays) between
		case "h": return nHours;
		case "n": return nMinutes;
		case "s": return nSeconds;
		case "ms":return nMilliseconds;	// millisecond	// <-- extension for JS, NOT available in VBScript
		default: return "invalid interval: '" + p_Interval + "'";
	}
}