
/* Polyfills */
String.prototype.padZero = function(len, c) {
	var s = '', c = c || '0', len = (len || 2) - this.length;
	while (s.length < len)
		s += c;
	return s + this;
}
String.prototype.allTrim = function() {
	return this.replace(/ /g, '');
}

String.prototype.toCurrency = function() {
	var res = Number(this.replace(/[^0-9\,-]+/g,"").replace(',','.'));
	if (isNaN(res))
		return null;
	else
		return res;
} 

Number.prototype.padZero = function(len, c) {
	return String(this).padZero(len, c);
}

Number.prototype.formatAsCurrency = function() {
	return this.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits:2});

}

/**
 * Number.prototype.format(n, x, s, c)
 * 
 * @param integer n: length of decimal
 * @param mixed   s: sections delimiter
 * @param mixed   c: decimal delimiter
 */
Number.prototype.format = function(n, s, c) {
    var re = '\\d(?=(\\d{' + (3 || 3) + '})+' + (n > 0 ? '\\D' : '$') + ')',
        num = this.toFixed(Math.max(0, ~~n));

    return (c ? num.replace('.', c) : num).replace(new RegExp(re, 'g'), '$&' + (s || ','));
};


Number.prototype.toFormattedValue = function(){
	return this.format(2,'.',',');
}

String.prototype.toFormattedValue = function(){
	if (this==null || this=='')
		return '';
	var n=parseFloat(this.replace(',','.'));
	return n.toFormattedValue();
}


String.prototype.formatAsDateTime = function() {
	var dt = new Date(this.toString());
	//var dt = new Date(Date.fromISO(this.toString()));// new Date(this.toString());
	//var dt = new Date(Date(this.toString().replace(/-/g, '/')));
	return dt.getDate().padZero(2) + "/" + (dt.getMonth() + 1).padZero(2) + "/"
			+ dt.getFullYear() + " " + dt.getHours().padZero(2) + ":"
			+ dt.getMinutes().padZero(2);
}

String.prototype.formatAsDateTimeSec = function() {
	var dt = new Date(this.toString())
	//var dt = new Date(Date.fromISO(this.toString()));// new Date(this.toString());
	//var dt = new Date(Date(this.toString().replace(/-/g, '/')));
	return dt.getDate().padZero(2) + "/" + (dt.getMonth() + 1).padZero(2) + "/"
			+ dt.getFullYear() + " " + dt.getHours().padZero(2) + ":"
			+ dt.getMinutes().padZero(2) +":"+dt.getSeconds().padZero(2);
}


String.prototype.formatAsDate = function() {
	var dt = new Date(this.toString())
	//var dt = new Date(Date.fromISO(this.toString()));// new Date(this.toString());
	//var dt = new Date(Date(this.toString().replace(/-/g, '/')));
	return dt.getDate().padZero(2) + "/" + (dt.getMonth() + 1).padZero(2) + "/"
			+ dt.getFullYear();
}

String.prototype.formatAsTime = function() {
	var dt = new Date(this.toString())
	//var dt = new Date(Date.fromISO(this.toString()));// new Date(this.toString());
	//var dt = new Date(Date(this.toString().replace(/-/g, '/')));
	return dt.getHours().padZero(2) + ":" + dt.getMinutes().padZero(2);
}


Date.fromISO= (function(){
    var testIso = '2011-11-24T09:00:27+0200';
    // Chrome
    var diso= Date.parse(testIso);
    if(diso===1322118027000) return function(s){
        return new Date(Date.parse(s));
    }
    // JS 1.8 gecko
    var noOffset = function(s) {
      var day= s.slice(0,-5).split(/\D/).map(function(itm){
        return parseInt(itm, 10) || 0;
      });
      day[1]-= 1;
      day= new Date(Date.UTC.apply(Date, day));  
      var offsetString = s.slice(-5)
      var offset = parseInt(offsetString,10)/100; 
      if (offsetString.slice(0,1)=="+") offset*=-1;
      day.setHours(day.getHours()+offset);
      return day.getTime();
    }
    if (noOffset(testIso)===1322118027000) {
       return noOffset;
    }  
    return function(s){ // kennebec@SO + QTax@SO
        var day, tz, 
//        rx = /^(\d{4}\-\d\d\-\d\d([tT][\d:\.]*)?)([zZ]|([+\-])(\d{4}))?$/,
        rx = /^(\d{4}\-\d\d\-\d\d([tT][\d:\.]*)?)([zZ]|([+\-])(\d\d):?(\d\d))?$/,
            
        p= rx.exec(s) || [];
        if(p[1]){
            day= p[1].split(/\D/).map(function(itm){
                return parseInt(itm, 10) || 0;
            });
            day[1]-= 1;
            day= new Date(Date.UTC.apply(Date, day));
            if(!day.getDate()) return NaN;
            if(p[5]){
                tz= parseInt(p[5], 10)/100*60;
                if(p[6]) tz += parseInt(p[6], 10);
                if(p[4]== "+") tz*= -1;
                if(tz) day.setUTCMinutes(day.getUTCMinutes()+ tz);
            }
            return day;
        }
        return NaN;
    }
})()


Number.prototype.roundTo2Digits = function() {
	return Math.round(this * 100) / 100;
}

if (!String.prototype.includes) {
	String.prototype.includes = function() {
		'use strict';
		return String.prototype.indexOf.apply(this, arguments) !== -1;
	};
}


String.prototype.hashCode = function() {
	  var hash = 0, i, chr, len;
	  if (this.length == 0) return hash;
	  for (i = 0, len = this.length; i < len; i++) {
	    chr   = this.charCodeAt(i);
	    hash  = ((hash << 5) - hash) + chr;
	    hash |= 0; // Convert to 32bit integer
	  }
	  return hash;
	};
	
Date.prototype.asDateString = function() {
	if (this==null)
		return "";
	var dd=this.getDate().padZero(2,'0');
	var mm=(this.getMonth()+1).padZero(2,'0');
	var yy=this.getYear()+1900;
	
	return dd+'/'+mm+'/'+yy
}	

var cumulativeOffset = function(element) {
    var top = 0, left = 0;
    do {
        top += element.offsetTop  || 0;
        left += element.offsetLeft || 0;
        element = element.offsetParent;
    } while(element);

    return {
        top: top,
        left: left
    };
};

if (!Array.prototype.forEach) {
    Array.prototype.forEach = function(fn, scope) {
        for(var i = 0, len = this.length; i < len; ++i) {
            fn.call(scope, this[i], i, this);
        }
    }
}

/* END Polyfills */
	
function addDays(date, days) {
	var newDate = new Date();
	newDate.setDate(date.getDate() + days);
	return newDate;
}

function addMonths(date, months) {
	return new Date(new Date(date).setMonth(date.getMonth()+months));
}

function removeURLParameter(url, parameter) {
    //prefer to use l.search if you have a location/link object
    var urlparts= url.split('?');   
    if (urlparts.length>=2) {

        var prefix= encodeURIComponent(parameter)+'=';
        var pars= urlparts[1].split(/[&;]/g);

        //reverse iteration as may be destructive
        for (var i= pars.length; i-- > 0;) {    
            //idiom for string.startsWith
            if (pars[i].lastIndexOf(prefix, 0) !== -1) {  
                pars.splice(i, 1);
            }
        }

        url= urlparts[0] + (pars.length > 0 ? '?' + pars.join('&') : "");
        return url;
    } else {
        return url;
    }
}


