
// ------------------------------------------------------------------
// These functions use the same 'format' strings as the
// java.text.SimpleDateFormat class, with minor exceptions.
// The format string consists of the following abbreviations:
//
// Field        | Full Form          | Short Form
// -------------+--------------------+-----------------------
// Year         | yyyy (4 digits)    | yy (2 digits), y (2 or 4 digits)
// Month        | MMM (name or abbr.)| MM (2 digits), M (1 or 2 digits)
//              | NNN (abbr.)        |
// Day of Month | dd (2 digits)      | d (1 or 2 digits)
// Day of Week  | EE (name)          | E (abbr)
// Hour (1-12)  | hh (2 digits)      | h (1 or 2 digits)
// Hour (0-23)  | HH (2 digits)      | H (1 or 2 digits)
// Hour (0-11)  | KK (2 digits)      | K (1 or 2 digits)
// Hour (1-24)  | kk (2 digits)      | k (1 or 2 digits)
// Minute       | mm (2 digits)      | m (1 or 2 digits)
// Second       | ss (2 digits)      | s (1 or 2 digits)
// AM/PM        | a                  |
//
// NOTE THE DIFFERENCE BETWEEN MM and mm! Month=MM, not mm!
// Examples:
//  "MMM d, y" matches: January 01, 2000
//                      Dec 1, 1900
//                      Nov 20, 00
//  "M/d/yy"   matches: 01/20/00
//                      9/2/00
//  "MMM dd, yyyy hh:mm:ssa" matches: "January 01, 2000 12:30:45AM"
// ------------------------------------------------------------------

var MONTH_NAMES=new Array('January','February','March','April','May','June','July','August','September','October','November','December')
var MONTH_SHORT=new Array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
var DAY_NAMES=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday')
var DAY_SHORT=new Array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
function LZ(x) {return(x<0||x>9?"":"0")+x}

// ------------------------------------------------------------------
// isDate ( date_string, format_string )
// Returns true if date string matches format of format string and
// is a valid date. Else returns false.
// It is recommended that you trim whitespace around the value before
// passing it to this function, as whitespace is NOT ignored!
// ------------------------------------------------------------------
function isDate(val,format) {
	var date=getDateFromFormat(val,format);
	if (date==0) { return false; }
	return true;
	}

// ------------------------------------------------------------------
// formatDate (date_object, format)
// Returns a date in the output format specified.
// The format string uses the same abbreviations as in getDateFromFormat()
// ------------------------------------------------------------------
function formatDate(date,format) {
	format=format+"";
	var result="";
	var i_format=0;
	var c="";
	var token="";
	var y=date.getYear()+"";
	var M=date.getMonth()+1;
	var d=date.getDate();
	var E=date.getDay();
	var H=date.getHours();
	var m=date.getMinutes();
	var s=date.getSeconds();
	var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;
	// Convert real date parts into formatted versions
	var value=new Object();
	if (y.length < 4) {y=""+(y-0+1900);}
	value["y"]=""+y;
	value["yyyy"]=y;
	value["yy"]=y.substring(2,4);
	value["M"]=M;
	value["MM"]=LZ(M);
	value["MMMM"]=MONTH_NAMES[M-1];
	value["MMM"]=MONTH_SHORT[M-1];

	value["NNN"]=MONTH_NAMES[M+11];
	value["d"]=d;
	value["dd"]=LZ(d);
	value["E"]=DAY_NAMES[E+7];
	value["EE"]=DAY_NAMES[E];
	value["H"]=H;
	value["HH"]=LZ(H);
	if (H==0){value["h"]=12;}
	else if (H>12){value["h"]=H-12;}
	else {value["h"]=H;}
	value["hh"]=LZ(value["h"]);
	if (H>11){value["K"]=H-12;} else {value["K"]=H;}
	value["k"]=H+1;
	value["KK"]=LZ(value["K"]);
	value["kk"]=LZ(value["k"]);
	if (H > 11) { value["a"]="PM"; }
	else { value["a"]="AM"; }
	value["m"]=m;
	value["mm"]=LZ(m);
	value["s"]=s;
	value["ss"]=LZ(s);
	while (i_format < format.length) {
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
		if (value[token] != null) { result=result + value[token]; }
		else { result=result + token; }
		}
	return result;
	}



// ------------------------------------------------------------------
// getDateFromFormat( date_string , format_string )
//
// This function takes a date string and a format string. It matches
// If the date string matches the format string, it returns the
// getTime() of the date. If it does not match, it returns 0.
// ------------------------------------------------------------------
function getDateFromFormat(val,format, isTime) {
	val=val+"";
	format=format+"";
	var i_val=0;
	var i_format=0;
	var c="";
	var token="";
	var token2="";
	var x,y;
	var now=new Date();
	var year=now.getYear();
	var month=now.getMonth()+1;
	var date=1;
	var hh=0;
	var mm=0;
	var ss=0;
	var ampm="";

	while (i_format < format.length) {
		// Get next token from format string
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
		// Extract contents of value based on format token
		if (token=="yyyy" || token=="yy" || token=="y") {
			if (token=="yyyy") { x=4;y=4; }
			if (token=="yy")   { x=2;y=2; }
			if (token=="y")    { x=2;y=4; }
			year=_getInt(val,i_val,x,y);
			if (year==null) { return 0; }
			i_val += year.length;
			if (year.length==2) {
				if (year > 70) { year=1900+(year-0); }
				else { year=2000+(year-0); }
				}
			}
		else if (token=="MMMM"||token=="MMM"||token=="NNN"){
			month=0;

			for (var i=0; i<MONTH_NAMES.length; i++) {
				var month_name=MONTH_NAMES[i];
				if (token=="MMM")
				   month_name=MONTH_SHORT[i];

				if (val.substring(i_val,i_val+month_name.length).toLowerCase()==month_name.toLowerCase()) {
					if (token=="MMM"||(token=="NNN"&&i>11)) {
						month=i+1;
						if (month>12) { month -= 12; }
						i_val += month_name.length;
						break;
						}
					}
				}
			if ((month < 1)||(month>12)){return 0;}
			}
		else if (token=="EE"||token=="E"){
			for (var i=0; i<DAY_NAMES.length; i++) {
				var day_name=DAY_NAMES[i];
				if (val.substring(i_val,i_val+day_name.length).toLowerCase()==day_name.toLowerCase()) {
					i_val += day_name.length;
					break;
					}
				}
			}
		else if (token=="MM"||token=="M") {
			month=_getInt(val,i_val,token.length,2);
			if(month==null||(month<1)||(month>12)){return 0;}
			i_val+=month.length;}
		else if (token=="dd"||token=="d") {
			date=_getInt(val,i_val,token.length,2);
			if(date==null||(date<1)||(date>31)){return 0;}
			i_val+=date.length;}
		else if (token=="hh"||token=="h") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<1)||(hh>12)){return 0;}
			i_val+=hh.length;}
		else if (token=="HH"||token=="H") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<0)||(hh>23)){return 0;}
			i_val+=hh.length;}
		else if (token=="KK"||token=="K") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<0)||(hh>11)){return 0;}
			i_val+=hh.length;}
		else if (token=="kk"||token=="k") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<1)||(hh>24)){return 0;}
			i_val+=hh.length;hh--;}
		else if (token=="mm"||token=="m") {
			mm=_getInt(val,i_val,token.length,2);
			if(mm==null||(mm<0)||(mm>59)){return 0;}
			i_val+=mm.length;}
		else if (token=="ss"||token=="s") {
			ss=_getInt(val,i_val,token.length,2);
			if(ss==null||(ss<0)||(ss>59)){return 0;}
			i_val+=ss.length;}
		else if (token=="a") {
			if (val.substring(i_val,i_val+2).toLowerCase()=="am") {ampm="AM";}
			else if (val.substring(i_val,i_val+2).toLowerCase()=="pm") {ampm="PM";}
			else {return 0;}
			i_val+=2;}
		else {
			if (val.substring(i_val,i_val+token.length)!=token) {return 0;}
			else {i_val+=token.length;}
			}
		}
	// If there are any trailing characters left in the value, it doesn't match
	if (i_val != val.length) { return 0; }
	// Is date valid for month?
	if (month==2) {
		// Check for leap year
		if ( ( (year%4==0)&&(year%100 != 0) ) || (year%400==0) ) { // leap year
			if (date > 29){ return 0; }
			}
		else { if (date > 28) { return 0; } }
		}
	if ((month==4)||(month==6)||(month==9)||(month==11)) {
		if (date > 30) { return 0; }
		}
	// Correct hours value
	if (hh<12 && ampm=="PM") { hh=hh-0+12; }
	else if (hh>11 && ampm=="AM") { hh-=12; }
	if (isTime)
		{
		year=1900
		month=1
		date=0
		}

	var newdate=new Date(year,month-1,date,hh,mm,ss);
	dateval = getExcelDateValue(newdate)
	return dateval
	}

//------------------------------------------------------------------
//getExcelDateValue(millisecond)
//converts the millisecond to excel date value

function getExcelDateValue(millisecond){
	var newdate1=new Date(1900,0,1,0,0,0).getTime();
	dateval= (millisecond-newdate1)/(24*60*60*1000)+1
	if (dateval>1)
		dateval=dateval+1
	//since python2.5 float accepts only 7 digit decimal value so there is a 1 sec difference, 28/12/1983 08:07 ==> 28/12/1983 08:06
	//so we are ceiling to 7 digit decimal point (eg:  30678.3381944444 to  30678.3381945)
	if(Math.floor(dateval) != dateval){
		var tempDateVal = dateval * 10000000
		tempDateVal = Math.ceil(tempDateVal)
		dateval = tempDateVal/10000000
	}
	return dateval
}

// ------------------------------------------------------------------
// parseDate( date_string [, prefer_euro_format] )
//
// This function takes a date string and tries to match it to a
// number of possible date formats to get the value. It will try to
// match against the following international formats, in this order:
// y-M-d   MMM d, y   MMM d,y   y-MMM-d   d-MMM-y  MMM d
// M/d/y   M-d-y      M.d.y     MMM-d     M/d      M-d
// d/M/y   d-M-y      d.M.y     d-MMM     d/M      d-M
// A second argument may be passed to instruct the method to search
// for formats like d/M/y (european format) before M/d/y (American).
// Returns a Date object or null if no patterns match.
// ------------------------------------------------------------------
function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
function parseDatetoValue(val,format)
{
	if (format.indexOf('hh')>=0)
	     format=format.replace('hh','HH')
	if (format.indexOf('a')>=0)
	     format=format.replace('a','')
	d=getDateFromFormat(val,format);
	if (d!=0) {  return new Array(d,format,'Category005'); }
	/* return 0 otherwise */
	return new Array(0,format,'Category005');
}

function parseDate(val) {
	var preferEuro=(arguments.length==2)?arguments[1]:false;
	//val=trim(val,' ')
	generalFormats=new Array('y-M-d','MMM dd, yyyy','MMM dd, yy','MMM d, yy','MMM d,y','y-MMM-d','d-MMM-y','MMM d','d/M/yy h:mm','d/M/yyyy h:mm','d/M/yy h:m','d/M/yyyy h:m');
	monthFirst=new Array('MM/dd/yyyy','MM/dd/yy','M/d/yyyy','M/d/yy','M/d/y','M-d-y','M.d.y','MMM-d','M/d','M-d','dd/MM/yyyy hh:m:ss','MM/dd/yyyy hh:m:ss','MM/dd/yyyy hh:m');
	dateFirst =new Array('d/M/y','d-M-y','d.M.y','d-MMM','d/M','d-M','dd/MM/yyyy hh:mm:ss','dd/MM/yy HH:mm','dd/MM/yyyy hh:mm','MM/dd/yyyy hh:mm:ss','MM/dd/yyyy HH:mm','dd/MM/yyyy HH:mm','MM/dd/yyyy hh:mm',"h:m:sa","h:m:s a","h:m:s","hh:mm","hh:m:ssa","hh:m:ss a","HH:m:ss");

	var checkList=new Array('generalFormats',preferEuro?'dateFirst':'monthFirst',preferEuro?'monthFirst':'dateFirst');
	var d=null;
	for (var i=0; i<checkList.length; i++) {
		var l=window[checkList[i]];
		for (var j=0; j<l.length; j++) {
			var isTime = false
		    if( l[j].indexOf('h')==0 || l[j].indexOf('H')==0)
		    	isTime = true

			d=getDateFromFormat(val,l[j],isTime);
			if (d!=0) {
				if( isTime)
					return new Array(d,l[j],'Category006');
				else
					return new Array(d,l[j],'Category005');
				 }
			}
		}
	return null;
	}

// ------------------------------------------------------------------
// Utility functions
// ------------------------------------------------------------------
function _isInteger(val) {
	var digits="1234567890";
	for (var i=0; i < val.length; i++) {
		if (digits.indexOf(val.charAt(i))==-1) { return false; }
		}
	return true;
	}

function _getInt(str,i,minlength,maxlength) {
	for (var x=maxlength; x>=minlength; x--) {
		var token=str.substring(i,i+x);
		if (token.length < minlength) { return null; }
		if (_isInteger(token)) { return token; }
		}
	return null;
	}
toBooleanformat= function(dt,format) {
	dt=''+dt
	val= (dt.toLowerCase()=='true'||parseInt(dt)>=1 || dt.toLowerCase()=='yes')? "TRUE":"FALSE";
	if (format=='Yes/No' || format=='Boolean' )
	{
        if( val=='TRUE')
           return 'Yes'
        else
           return 'No'
    }
    else
    	return val
  }
toBoolean = function(dt) {
	dt=''+dt
	val= (dt.toLowerCase()=='true'||parseInt(dt)>=1||dt.toLowerCase()=='yes' )? "TRUE":"FALSE";
	return val
};


// -----------------------------------------------------------------------
//   function to parse whether given data is number,string, boolean
// -----------------------------------------------------------------------


getformat=function(n)
{
	output=new Array();
	if( n.length==0 ) return 'String'
	prefix_currency="'$','Rs.'"

	var i,c,f,comma,symbol='',sign='',decimal='',decimalval='';
	currency=''
	temp=''

	//Checks for Boolean
	if (n.toLowerCase()=='true' || n.toLowerCase()=='false') return 'Boolean'

	if (n.indexOf('%')==0 || n.indexOf('%')==n.length-1)
	{
	   symbol='%'
	   n=n.replace("%","")
	}
	else
	{

	//Checks for currency prefix
	for(i=0;i< n.length;i++)
	{
		if(n.charAt(i)=='-' || n.charAt(i)=='+')
		{
			sign='-'
			if (i>0)
			{
				temp1="'"+temp+"'"
				if (prefix_currency.indexOf(temp1)>=0 )
				{
					n=n.replace(temp,"")
					currency=temp;
					break;
				}
			}
		}
		if (sign=='-' && i==0)   temp=""
		else
		{
			if  (_isInteger(n.charAt(i)))
			{
				temp1="'"+temp+"'"
				if (prefix_currency.indexOf(temp1)>=0 )
				{
					n=n.replace(temp,"")
					currency=temp;
					break;
				}
				else
				{
					if(i<2 && temp=='')     break
					else if(temp.indexOf('..')>0){
						temp=temp.replace('..','.')
						temp1="'"+temp+"'"
						if (prefix_currency.indexOf(temp1)>=0 )
						{
							n=n.replace(temp,"")
							currency=temp;
							break;
						}
					}
					else	return 'String'
				}
			}
			else	 temp=temp+n.charAt(i)
		}
	}
	}

	value=''

	if (n.charAt(0)=='-'|| n.charAt(0)=='+')
	{
		sign=n.charAt(0);
		value=sign;
		n=n.substring(1)
	}
	if(n.len>0)
	{
		ntemp=n.replace(',','')
		ntemp=ntemp.replace('.','')
		if(!(_isInteger(ntemp)))  return 'String'
	}

	if (n.indexOf('.')>=0)
	{
		s=n.split('.')
		decimal='.'
		if(s.length>2)	return 'String'
		decimalval=s[1]
		n=s[0]
		if (!(_isInteger(s[1])))  return 'String'
	}
	if (n.indexOf(',')>=0)
	{
		s=n.split(',')
		comma=','
		for (var i=0;i<s.length;i++)
		{
			if (!(_isInteger(s[i])))  return 'String'
			else if (i==0 && s[i].length<1)	return 'String'
			else if (i==s.length-1 && s[i].length<3) return 'String'
			else if (i>0 && s[i].length<=1)	return 'String'
			else  value=value+s[i]
		}
	}
	else
	{
		if (!(_isInteger(n)))	return 'String'
		else  value=value+n
	}
	if (decimal=='.')  value=value+'.'+decimalval
	output.push(value)
	format=''
	if (currency.length >0)   format=format+currency
	//if (sign=='-')  format=format+'-'
	if (comma==',')  format=format+' #,###'
	else  	format=format+'###'
	if (decimal=='.')  format=format+'.##'
	if (symbol=='%') format=format+symbol
	output.push(format)
	return output
}

// -----------------------------------------------------------------------
//   function to  format number
// -----------------------------------------------------------------------


formatNumber = function(n,format){
	if(n == null || n == '' || isNaN(n))
	   n='0'
	n=n.replace(/,/g,'')
    prefix_currency="'Rs.','$','$b','$U','Bs','BZ$','C$','CHF','Din','DZD','ETB','fr.','Fr.','Ft','Gs','HK$','J$','KM','kn','kr','L.','Lm','Ls','mop','N','NT$','Php','PhP','Q','R','R$','RD$','RM','Rp','Rs','RWF'"

	format=(format)? format+'':'#,###.##';
	var i,c,f,comma,symbol='',sign='',decimals='',integers='';
	var fInt,fDec,nInt,nDec,len=0,cnt=0;
	if(n<0) sign='-';
	n+='';if(sign) n=n.replace('-','');
	temp=''
	if (format.charAt(0)=='#'|| format.charAt(0)=='-' )
	    symbol=''
	else
	{
		 for(i=0;i<=format.length;i++)
		 {
			if (format.charAt(i)=='#' || format.charAt(i)=='-')
			    {
				    if (temp=='')  break
				      else if (prefix_currency.indexOf(temp)>=0 ){ symbol=temp;break;}
			     }else
			       temp=temp+format.charAt(i)
		 }
	}

	format=format.replace(symbol,'')
	if(format.indexOf(',')>=0) comma=',';
	if(format.indexOf('$')>=0) symbol='$';
	else if(format.indexOf('%')>=0)	{symbol='%'; format.replace("%","")}
	s=format.split('.');

	fInt=((s[0]==''||s[0]==null||s[0]=='undefinded')? '':s[0]);
	fInt=fInt.split('').reverse().join('');
	fDec=(s[1]==''||s[1]==null||s[1]=='undefinded')? '':s[1];
	s=n.split('.');
	nInt=((s[0]==''||s[0]==null||s[0]=='undefinded')? '':s[0]);
	nInt=nInt.split('').reverse().join('');;
	nDec=(s[1]==''||s[1]==null||s[1]=='undefinded')? '':s[1];
	if (nInt) len=nInt.length;
	if (fInt.length>len) len=fInt.length;
	for(i=0;i<len;i++){
		c=nInt.charAt(i);
		f=fInt.charAt(i);
		cnt++;
		if(integers.length==3 && cnt==4 &&  i<len  && comma && (c||f=='0')) {integers+=comma; }
		else { if (integers.length>5 &&  i<len  && cnt==3 && comma && (c||f=='0' ) ) {integers+=comma;}}
		if(f=='0' && !c) integers+='0';
		else if(c) integers+=c;
		if (integers.length==5 && cnt==4) cnt=1;
		if (integers.length>5 && cnt==3) cnt=1;
	}

	if(fDec) len=fDec.length;

	for(i=0;i<len;i++){
		c=nDec.charAt(i);
		f=fDec.charAt(i);
		if((f=='#' || f=='0') && !c) decimals+='0';
		else if((f=='#' || f=='0') && c) decimals+=c;
	}

	if (!(integers)&& decimals)
		integers=0
	if (fDec.indexOf('*')>0 && fDec.length>0)
	   decimals=nDec
	f=((integers+'').split('').reverse().join(''))+((decimals)? '.'+decimals:'');

	if(symbol=='%') f+=symbol;
	    else f=symbol+sign+f;
	return f;
};


// -----------------------------------------------------------------------
//  interface function to determine the datatype
// -----------------------------------------------------------------------


function parsedata(val)
{
     if (val !=null) {
	 	originalValue = val
		if ((typeof val).toLowerCase()=="boolean")
	 	   format="Boolean"
	 	else
	 	{
			val = trim(val)
			format = getformat(val)
	 	}

	 	if (format == 'Boolean') {
			if (toBoolean(val)=="TRUE")
		  		 val=1.0
		    if(toBoolean(val)=="FALSE")
		   		val=0.0
			return (new Array(val, 'True/False', 'Category011'))
		}
		else
			if (format == 'String') {
			    dateArray=parseDate(originalValue)
				if (dateArray!=null &&  dateArray.length==3 ) {
					return (dateArray)
				}
				else {
					return (new Array(originalValue, 'Text', 'Category010'))
				}
			}
			else
				return (new Array(format[0], format[1], 'Category002'))
	 }
	 else
	   return (new Array(val, 'Text', 'Category010'))
}

function getformattedDate(val,format)
{
				val = '' + val
				if(''+val.length>0)
				{
					dateval = (parseFloat(trim(val)))
					if (dateval > 1)
						dateval = dateval - 1
					value = (dateval - 1) * (24 * 60 * 60 * 1000)
					var newdate1 = new Date(1900, 0, 1, 0, 0, 0).getTime() + value
					return formatDate(new Date(newdate1), trim(format))
					}
				else
					return val
}
function parseBoolean(val,format)
{
	value= toBoolean(val)
	if (value=="TRUE")
	   return 1
	else
	   return 0
}

function formatdata(val,format,datatype)
{
if (datatype != null && formatjson[datatype])
		datatype=formatjson[datatype]['SheetName']

if (val != null && datatype !=null) {
	    if (datatype=='Custom' && (format.indexOf('dd')>=0 || format.indexOf('yy')>=0|| format.indexOf('hh')>=0))
		{
 			return getformattedDate(val,format)
		}

		if (datatype == "Text" || datatype == "String" || datatype == "Password")
			return val
		else
			if (datatype == "Boolean")
				return toBooleanformat(val,format)
			else
				if (datatype == "Date" || datatype == "Time" ) {
				return getformattedDate(val,format)
				}
				else {
					if (format.indexOf('#')>=0) {
						val = '' + val
						return formatNumber(trim(val), trim(format))
				}
				else
				  return val
				}

}if (val!=null && format!=null){
	if(format == 'Boolean' ||format=='Yes/No' || format=='True/False')
		return toBooleanformat(val,format)
	else if (format=="Text" || format=="String" || format == "Password")
	    return val
	else if (format.indexOf('#') >= 0) {
		 val=''+val
		return formatNumber(trim(val), trim(format))
	}
	else {
		return getformattedDate(val,format)
	}
}
   return val
}

function parseValue(value,format)
{
 if (format == 'Yes/No'|| format=='True/False' || format=='Boolean')
    return parseBoolean(value,format)
 else if(format=='Text' || format=='String' || format == 'Password')
    return value
 else
   return parsedata(value)[0]

}
