Ext.onReady(function() {

    Ext.QuickTips.init();
    Ext.form.Field.prototype.msgTarget = 'side';
    
});

Ext.lib.Event.resolveTextNode = Ext.isGecko ? function(node){
	if(!node){
		return;
	}
	var s = HTMLElement.prototype.toString.call(node);
	if(s == '[xpconnect wrapped native prototype]' || s == '[object XULElement]'){
		return;
	}
	return node.nodeType == 3 ? node.parentNode : node;
} : function(node){
	return node && node.nodeType == 3 ? node.parentNode : node;
};

var data = new Date();
var gg, mm, aaaa;
gg = data.getDate() + "/";
mm = data.getMonth() + 1 + "/";
aaaa = data.getFullYear();
    
var curDateTime = new Date()
var curHour = curDateTime.getHours()
var curMin = curDateTime.getMinutes()
var curTime = 
    ((curHour < 10) ? "0" : "") + curHour + ":" 
    + ((curMin < 10) ? "0" : "") + curMin
    
function IsNumeric(sText) {
    var ValidChars = "0123456789";
    var IsNumber=true;
    var Char;

    for (i = 0; i < sText.length && IsNumber == true; i++) { 
        Char = sText.charAt(i); 
        if (ValidChars.indexOf(Char) == -1) 
            IsNumber = false;
    }
    return IsNumber;
}

function IsFloat(sText) {
    var ValidChars = "0123456789,";
    var IsNumber=true;
    var Char;

    for (i = 0; i < sText.length && IsNumber == true; i++) { 
        Char = sText.charAt(i); 
        if (ValidChars.indexOf(Char) == -1) 
            IsNumber = false;
    }
    return IsNumber;
}
  
function checkPhoneNumber(val) {
	if (val.length > 16)
        return false;
    else if (val.length < 9)
        return false;
    else if (!IsNumeric(val.substring(1, val.length))) 
        return false;
    else if (!val.indexOf('+') == 0 && IsNumeric(val.substring(1, val.length))) 
        return false;
    return true;
}

String.prototype.startsWith = function(str)
{return (this.match("^"+str)==str)}

String.prototype.endsWith = function(str)
{return (this.match(str+"$")==str)}

// Add the additional 'advanced' VTypes
Ext.apply(Ext.form.VTypes, {
    password : function(val, field) {
        if (field.initialPassField) {
            var pwd = Ext.getCmp(field.initialPassField);
            return (val == pwd.getValue());
        }
        return true;
    },
    passwordText : 'Le password non corrispondono',
    
    smssender : function(val, field) {
        if (val.length > 16) {
            return false;
        }
        else if (val.length>11 && !IsNumeric(val.substring(1, val.length))) {
            return false;
        }
        else if (val.length>11 &&
                 !val.indexOf('+') == 0 && 
                 IsNumeric(val.substring(1, val.length))) {
            return false;
        }
        return true;
    },
    
    phoneNumber : function(val, field) {
        if (val == '+39')
            return true;
            
        if (!checkPhoneNumber(val))
            return false;
        
        return true;
    },
    phoneNumberText : 'Il numero di telefono deve essere in formato internazionale (es: +393351234567)',
    
    taxCheck : function(val, field) {
        if (field.alternateToCheck){
            if (Ext.getCmp(field.alternateToCheck).getValue().length == 0 && val.length == 0)
                return false;
            else{
                Ext.getCmp(field.alternateToCheck).clearInvalid();
                field.clearInvalid();
                return true;
            }
        }
        else
            return false;
    },
    taxCheckText : 'E\' necessario compilare uno tra i campi <i>Codice Fiscale</i> o <i>Partita Iva</i>',
    
    rechargeValue : function(val, field) {
         if (!IsNumeric(val)) {
            return false;
         }
         else if (val < 25){
            return false;
         }
         return true;
    }
    
    
});

function S4() {
    return (((1+Math.random())*0x10000)|0).toString(16).substring(1) 
}


function newguid() {
   return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}   

function getDateFromDays(numDays,direction)
{
    var current = Date.parse(new Date());
    var dayLength = 86400000;

    return (direction?current - (dayLength*numDays):current + (dayLength*numDays));
}
function lz(numero, cifre) {
	n = String(numero);
	while (n.length<cifre) { 
		n="0"+n 
	}
	return n;
}
function dateFormat(data, formato) { 
// (c) br1 - 2002 

	var giorni = new Array('Domenica','Luned&igrave;','Marted&igrave;','Mercoled&igrave;','Gioved&igrave;','Venerd&igrave;','Sabato');
	var mesi = new Array('Gennaio','Febbraio','Marzo','Aprile','Maggio','Giugno','Luglio','Agosto','Settembre','Ottobre','Novembre','Dicembre');

// preparo la data...  verificare di passarla corretta!
	var adesso = new Date(data); 
	var anno = adesso.getFullYear();
	var mese = adesso.getMonth()+1;
	var giorno = adesso.getDate();
	var settim = adesso.getDay();
	var ore = adesso.getHours();
	var minuti = adesso.getMinutes();
	var secondi = adesso.getSeconds();

// preparo la stringa di risposta
	var rVal = '';

	if (formato.length==0) { 
// assenza del secondo parametro
		return String(adesso); 
	} else {

	// inizio loop
		while (formato.length>0) {

	// verifico se c'e' qualche separatore e lo aggiungo
			while (formato.length>0 && String("ymdphnst").indexOf(formato.charAt(0).toLowerCase())<0) {
				rVal += formato.charAt(0);
				formato = formato.substr(1);
			}

	// Separo il gruppo
			if (formato.length>0) {
				ff = formato.charAt(0);
				formato = formato.substr(1);
				while (formato.length>0 && formato.charAt(0).toLowerCase()==ff.charAt(0).toLowerCase()) {
					ff += formato.charAt(0);
					formato = formato.substr(1);
				}

	// espando il formato nella stringa corrispondente
				ff = ff.toLowerCase();	 // operazione preliminare... tutto in minuscolo
				switch (ff) 	{ 
					case "yy" : 
						rVal += String(anno).substr(2); 
						break; 
					case "yyyy" : 
						rVal += String(anno); 
						break; 
					case "m" : 
						rVal += String(mese); 
						break; 
					case "mm" : 
						rVal += lz(mese,2);
						break; 
					case "mmm" : 
						rVal += mesi[mese-1].substr(0,3);
						break; 
					case "mmmm" : 
						rVal += mesi[mese-1];
						break; 
					case "d" : 
						rVal += String(giorno); 
						break; 
					case "dd" : 
						rVal += lz(giorno,2); 
						break; 
					case "ddd" : 
						rVal += giorni[settim].substr(0,3);
						break; 
					case "dddd" : 
						rVal += giorni[settim];
						break; 
					case "p" : 
						var inizio = new Date(anno, 0, 0); 
						rVal += Math.floor((adesso - inizio) / 86400000);
						break; 
					case "ppp" : 
						var inizio = new Date(anno, 0, 0); 
						rVal += lz(Math.floor((adesso - inizio) / 86400000),3);
						break; 
					case "h" : 
						rVal += String(ore); 
						break; 
					case "hh" : 
						rVal += lz(ore,2); 
						break; 
					case "n" : 
						rVal += String(minuti); 
						break; 
					case "nn" : 
						rVal += lz(minuti,2); 
						break; 
					case "s" : 
						rVal += String(secondi); 
						break; 
					case "ss" : 
						rVal += lz(secondi,2); 
						break; 
					case "t" : 
						rVal += lz(ore,2)+":"+lz(minuti,2)+":"+lz(secondi,2); 
						break; 
					default :  // il numero dei caratteri del formato non e' permesso
						rVal += ff.replace(/./gi,"?");
				} 

			}

		} // fine loop principale

		return rVal;
	}
}

function renderDate(v){
    
    if (!v)
        return '';
    else
        return v.slice(0, 10);
        
        //return Date.parseDate(v.slice(1, 10), 'd/m/Y');
        //return new Date(parseFloat(v.slice(6, 19))).toLocaleString();
}



if (typeof Number.prototype.toFixed=="undefined"){ 
    Number.prototype.toFixed=function(n){ 
        return (n>0)?new String(Math.round(this*new Number("1e+"+n))).replace(
            new RegExp("(\\d+)(\\d{"+n+"})$"),"$1.$2"):new String(Math.round(this)); 
    }; 
}; 

function euroMoney4(v){   
    try{
        return parseFloat(v.replace(',', '.')).toFixed(4) + ' &euro;';
    }catch(err){
        return parseFloat(v).toFixed(4) + ' &euro;';
    }
}

function euroMoney2(v){      
    try{
		if (!IsNumeric(v))
			return v;
		else
			return parseFloat(v.replace(',', '.')).toFixed(2) + ' &euro;';
    }catch(err){
        return parseFloat(v).toFixed(2) + ' &euro;';
    }
}

function renderRetVal(v){
	if (v.startsWith("OK"))
		return '<img src="/Resources/Images/icons/accept.png" alt="' + v + '"/>';
	else
		return '<img src="/Resources/Images/icons/exclamation.png" alt="' + v + '"/>';
}

function renderTrueFalse(v){
	if (v == '')
		return v;
		
	if (v == true || v == 'true' || v == 'vero')
		return 'S&igrave;';
	else
		return 'No';
}

function euroMoney(v){
    try{
        return parseFloat(v.replace(',', '.')).toFixed(2) + ' &euro;';
    }catch(err){
        return parseFloat(v).toFixed(2) + ' &euro;';
    }
    
}

function euroRound(v){
    try{
        return parseFloat(v.replace(',', '.')).toFixed(2);
    }catch(err){
        return parseFloat(v).toFixed(2);
    }
    
}

Ext.example = function(){
    var msgCt;

    function createBox(t, s){
        return ['<div class="msg">',
                '<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>',
                '<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc"><h3>', t, '</h3>', s, '</div></div></div>',
                '<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>',
                '</div>'].join('');
    }
    return {
        msg : function(title, format){
            if(!msgCt){
                msgCt = Ext.DomHelper.insertFirst(document.body, {id:'msg-div'}, true);
            }
            msgCt.alignTo(document, 't-t');
            var s = String.format.apply(String, Array.prototype.slice.call(arguments, 1));
            var m = Ext.DomHelper.append(msgCt, {html:createBox(title, s)}, true);
            m.slideIn('t').pause(15).ghost("t", {remove:true});
        },

        init : function(){
            var t = Ext.get('exttheme');
            if(!t){ // run locally?
                return;
            }
            var theme = Cookies.get('exttheme') || 'aero';
            if(theme){
                t.dom.value = theme;
                Ext.getBody().addClass('x-'+theme);
            }
            t.on('change', function(){
                Cookies.set('exttheme', t.getValue());
                setTimeout(function(){
                    window.location.reload();
                }, 250);
            });

            var lb = Ext.get('lib-bar');
            if(lb){
                lb.show();
            }
        }
    };
}();

Ext.override(Ext.layout.FormLayout, {
	renderItem : function(c, position, target){
		if(c && !c.rendered && (c.isFormField || c.fieldLabel) && c.inputType != 'hidden'){
			var args = this.getTemplateArgs(c);
			if(typeof position == 'number'){
				position = target.dom.childNodes[position] || null;
			}
			if(position){
				c.itemCt = this.fieldTpl.insertBefore(position, args, true);
			}else{
				c.itemCt = this.fieldTpl.append(target, args, true);
			}
			c.actionMode = 'itemCt';
			c.render('x-form-el-'+c.id);
			c.container = c.itemCt;
			c.actionMode = 'container';
		}else {
			Ext.layout.FormLayout.superclass.renderItem.apply(this, arguments);
		}
	}
});
Ext.override(Ext.form.Field, {
	getItemCt : function(){
		return this.itemCt;
	}
});

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

var cookieProvider = new Ext.state.CookieProvider({
    expires: new Date(new Date().getTime()+(1000*60*60*24*30)) //30 days
});

Ext.state.Manager.setProvider(cookieProvider);