

function cssFormat(cssOrig){

	
	if(cssOrig==null) cssOrig="";	
	this.setCSS(cssOrig);	
	
}

cssFormat.prototype = {
	cssOriginal:"",
	css:"",
	setCSS:function(val){
		//alert(this.cssOriginal);
		this.cssOriginal = val;
		this.css = val;
		this.formatSelectors();
		this.formatContents();
	},
	formatContents:function(){
		this.css = this.css.replace(/\{\s*?\}/g,"{}");
		this.css = this.css.replace(/\{\s*?.[^\}\{]*\s*?\}/mgi, function(m){return format(m)});			
		var regex;
		function format(match){		
			//console.log(match);			
			//remove braces and space
			regex = /\{|\}/g;
			match = match.replace(regex,"").trim();
			//force spacing on : and ;
			regex = /(.[^;\{]*)\s*?:\s*?(.[^;]*);(\s*)/g;
			match = match.replace(regex,"$1:$2;");	
			//sort the properties alphabetically			
			match = cleanArray(match.split(";"));
			match = match.sort().join("; ");
			//add the last semi-colon
			if(match.trim().length>0)match+=";";
			return "{"+match+"}";
		}
	},
	formatSelectors:function(){
		this.css = this.css.replace(/.[^\}\/{]*\{/mg, function(m){return format(m)});	
		var regex;
		function format(match){			
			//seperate selectors by a line break
			regex = /\s*?,\s*?([a-z#\.])/gi;
			match = match.replace(regex, ",\n$1");
			//allow only one space between selector elements
			regex = /([#|\.|:][a-z]*)\s*([a-z]*[#|\.|:])/gi;
			match = match.replace(regex, "$1 $2");
			//remove spaces around psuedo class : indicators
			regex = /\s*?:\s*?([a-z])/gi;
			match = match.replace(regex, ":$1");
			//space >,~,+ indicators
			regex = /([a-z#\.][^\s]*)\s*?([>~+])\s*?([a-z#\.])/gi;
			match = match.replace(regex, "$1 $2 $3");
			//add space before open brace {
			regex = /([a-z\*])\s*?{/gi;
			match = match.replace(regex, "$1 {");
			return match;
		}
	}
	
};

function printm(match){
	console.log("\n\n"+match+"\n\n");
	return match;
}

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }

function cleanArray(arr){
	var tmpArray = [];
	for(var a=0;a<arr.length; a++){
		if(arr[a].toString().trim()!=""){
			tmpArray.push(arr[a]);
		}
	}
	return tmpArray;
}

var cssFormatter = new cssFormat();

if(!console){
	var console = {log:function(msg){
		alert(msg)
	}};
}
