﻿
var CodeFormatter ;


	CodeFormatter =  new Object() ;

	CodeFormatter.Regex = new Object() ;

	// Regex for line breaks.
	CodeFormatter.Regex.BlocksOpener = /\<(P|DIV|H1|H2|H3|H4|H5|H6|ADDRESS|PRE|OL|UL|LI|TITLE|META|LINK|BASE|SCRIPT|LINK|TD|AREA|OPTION)[^\>]*\>/gi ;
	CodeFormatter.Regex.BlocksCloser = /\<\/(P|DIV|H1|H2|H3|H4|H5|H6|ADDRESS|PRE|OL|UL|LI|TITLE|META|LINK|BASE|SCRIPT|LINK|TD|AREA|OPTION)[^\>]*\>/gi ;

	CodeFormatter.Regex.NewLineTags	= /\<(BR|HR)[^\>]\>/gi ;

	CodeFormatter.Regex.MainTags = /\<\/?(HTML|HEAD|BODY|FORM|TABLE|TBODY|THEAD|TR)[^\>]*\>/gi ;

	CodeFormatter.Regex.LineSplitter = /\s*\n+\s*/g ;

	// Regex for indentation.
	CodeFormatter.Regex.IncreaseIndent = /^\<(HTML|HEAD|BODY|FORM|TABLE|TBODY|THEAD|TR|UL|OL)[ \/\>]/i ;
	CodeFormatter.Regex.DecreaseIndent = /^\<\/(HTML|HEAD|BODY|FORM|TABLE|TBODY|THEAD|TR|UL|OL)[ \>]/i ;
	CodeFormatter.Regex.FormatIndentatorRemove = new RegExp('    ') ;

	CodeFormatter.Format = function( html )
	{
		// Line breaks.
		var sFormatted	= html.replace( this.Regex.BlocksOpener, '\n$&' ) ; ;
		sFormatted		= sFormatted.replace( this.Regex.BlocksCloser, '$&\n' ) ;
		sFormatted		= sFormatted.replace( this.Regex.NewLineTags, '$&\n' ) ;
		sFormatted		= sFormatted.replace( this.Regex.MainTags, '\n$&\n' ) ;
		
		// Indentation.
		var sIndentation = '' ;
		
		var asLines = sFormatted.split( this.Regex.LineSplitter ) ;
		sFormatted = '' ;
		
		for ( var i = 0 ; i < asLines.length ; i++ )
		{
			var sLine = asLines[i] ;
			
			if ( sLine.length == 0 )
				continue ;
			
			if ( this.Regex.DecreaseIndent.test( sLine ) )
				sIndentation = sIndentation.replace( this.Regex.FormatIndentatorRemove, '' ) ;

			sFormatted += sIndentation + sLine + '\n' ;
			
			if ( this.Regex.IncreaseIndent.test( sLine ) )
				sIndentation += '    ' ;
		}

		return sFormatted.trim() ;
	}
