/**
 * @author Kalapuc Roman (rkalapuc@gmail.com)
 * @copyright Finport Technologies Inc
 * @since 2006
 * @version 1.0
 */

function DateExt(){}

DateExt.prototype.daysBetween = function (d1,m1,y1,d2,m2,y2){
	var n1,n2,result;
		d2 = Math.floor(d2);
	    m2 = Math.floor(m2);
		if (m1>2) {
	        m1=m1+1;
	    } else {
	        m1=m1+13;
	        y1=y1-1;
	    }
	    
	    n1=Math.floor(36525*y1/100)+Math.floor(306*m1/10+d1);
	    if (m2>2) {
	        m2=m2+1;
	    } else {
	        m2=m2+13;
	        y2=y2-1;
	    }

	n2=Math.floor(36525*y2/100)+Math.floor(306*m2/10+d2);
	result=n2-n1;
	return result;		
}

DateExt.prototype.toTimestamp = function(date,mask) {
	var _tmpArr=this.explode(date,mask);
	
	if (_tmpArr!==false){
		days = this.daysBetween(1,1,1970,new Number(_tmpArr['d']),new Number(_tmpArr['m']),new Number(_tmpArr['Y']));
		return new Number(days*86400-3600);
	}
	
	return false;
}


DateExt.prototype.explode = function(date,mask){
	var maskRegexp = /#(.)/i;
	var match = maskRegexp.exec(mask);
	var strRegexp = new String();
	var pos = -1;
	var lexemaOrder = new Array();;
	var lexemaCount = 1;
	
	while (match!=null && match.length>1){
		pos = mask.indexOf(match[0]);
		if (pos!=-1){
			strRegexp+=mask.substr(0,pos);			
			mask = mask.substr(pos+match[0].length,mask.length-pos-match[0].length);
		}
		
		switch(match[1]){
			case 'd': 
				lexemaOrder[lexemaCount] = 'd';
				lexemaCount++;
				strRegexp+="(0?[1-9]|[12][0-9]|3[01])";
				break;
			case 'm':
				lexemaOrder[lexemaCount] = 'm';
				lexemaCount++;			
				strRegexp+="(0?[1-9]|1[012])"; 
				break;
			case 'y':
				lexemaOrder[lexemaCount] = 'y';
				lexemaCount++;			
				strRegexp+="([0-9]{2})";							
				break;
			case 'Y': 
				lexemaOrder[lexemaCount] = 'Y';
				lexemaCount++;						
				strRegexp+="((19|20){1}[0-9]{2})";
			break;			
		}
		match = maskRegexp.exec(mask);
	}
	strRegexp = "\\b"+strRegexp+"\\b";
	
	var regexpInstance = new RegExp(strRegexp);
	var resultArr = new Array();
	match = regexpInstance.exec(date);
	
	if (match != null){	
		for (i=1;i<=3;i++) {			
			if (typeof(match[i])!="undefined") {
				resultArr[lexemaOrder[i]] = match[i];
			}
		}
		return resultArr;
	}
	
	return false;
}

