﻿/* Formating dates */

cDateFormatToken = function( nTokenRef, sTokenRegEx )
{
	this.nTokenRef = nTokenRef
	this.sTokenRegEx = sTokenRegEx
}

cDateFormatToken.CN_TOKEN_DAY = 1
cDateFormatToken.CN_TOKEN_MONTH = 2
cDateFormatToken.CN_TOKEN_YEAR = 3

cDateFormatToken.tokens = new Object()

cDateFormatToken.tokens[ 'm' ] = new cDateFormatToken( cDateFormatToken.CN_TOKEN_MONTH, '[0-9]{2}' )
cDateFormatToken.tokens[ 'n' ] = new cDateFormatToken( cDateFormatToken.CN_TOKEN_MONTH, '[0-9]{1,2}' )

cDateFormatToken.tokens[ 'd' ] = new cDateFormatToken( cDateFormatToken.CN_TOKEN_DAY, '[0-9]{2}' )
cDateFormatToken.tokens[ 'j' ] = new cDateFormatToken( cDateFormatToken.CN_TOKEN_DAY, '[0-9]{1,2}' )

cDateFormatToken.tokens[ 'Y' ] = new cDateFormatToken( cDateFormatToken.CN_TOKEN_YEAR, '[0-9]{4}' )
cDateFormatToken.tokens[ 'y' ] = new cDateFormatToken( cDateFormatToken.CN_TOKEN_YEAR, '[0-9]{2}' )

cDateFormat = function( sFormat )
{
	this.sFormat = sFormat
	this.aResults = new Array()
	var sRegExFormat = this.sFormat
	var sRexExResult = ''
	while( sRegExFormat.length > 0 )
	{
		if( typeof cDateFormatToken.tokens[ sRegExFormat.charAt( 0 ) ] != 'undefined' )
		{
			sRexExResult += '(' + cDateFormatToken.tokens[ sRegExFormat.charAt( 0 ) ].sTokenRegEx + ')'
			this.aResults[ this.aResults.length++ ] = cDateFormatToken.tokens[ sRegExFormat.charAt( 0 ) ].nTokenRef
		}
		else
		{
			sRexExResult += sRegExFormat.charAt( 0 )
		}
		sRegExFormat = sRegExFormat.substr( 1 )
	}
	this.hRegExp = new RegExp( sRexExResult )
}

cDateFormat.prototype.parse = function( sDate )
{
	var hDate = new Date()
	var aResult = sDate.match( this.hRegExp )
	var sResult = ''
	for( var nI = 0; nI < this.aResults.length; nI++ )
	{
		switch( this.aResults[ nI ] )
		{
			case cDateFormatToken.CN_TOKEN_DAY:
												hDate.setDate( aResult[ nI + 1 ] )
												break
			case cDateFormatToken.CN_TOKEN_MONTH:
												hDate.setMonth( new Number( aResult[ nI + 1 ] ) - 1 )
												break
			case cDateFormatToken.CN_TOKEN_YEAR:
												hDate.setYear( aResult[nI + 1 ] )
												break
		}
	}
	return hDate
}


cDateFormat.prototype.toString = function( hDate )
{
	var sRegExFormat = this.sFormat
	var sMonth = new String( hDate.getMonth() + 1 )
	sRegExFormat = sRegExFormat.replace( /m/g, ( sMonth.length == 1 ? '0' : '' ) + sMonth  )
	sRegExFormat = sRegExFormat.replace( /n/g, sMonth )

	var sDay = hDate.getDate().toString()
	sRegExFormat = sRegExFormat.replace( /d/g, ( sDay.length == 1 ? '0' : '' ) + sDay  )
	sRegExFormat = sRegExFormat.replace( /j/g, sDay )
	
	var sYear = hDate.getFullYear().toString()
	sRegExFormat = sRegExFormat.replace( /Y/g, sYear  )
	sRegExFormat = sRegExFormat.replace( /y/g, sYear.substr( 2 ) )
	
	return sRegExFormat
}