var nt = {
    init : {
            allow_console : function(){if(typeof console == 'object' && console.firebug && navigator.userAgent.indexOf('Firefox') != 0  ){return true;} else if(typeof console == 'object' && navigator.userAgent.indexOf('Webkit') != 0 ) {return true;} else { return false; }}
    },
    console :{
                log 	 : function(cmd){if(nt.init.allow_console()){console.log(cmd);}},
                debug 	 : function(cmd){if(nt.init.allow_console()){console.debug(cmd);}},
                info 	 : function(cmd){if(nt.init.allow_console()){console.info(cmd);}},
                warn 	 : function(cmd){if(nt.init.allow_console()){console.warn(cmd);}},
                error 	 : function(cmd){if(nt.init.allow_console()){console.error(cmd);}},
                trace 	 : function(cmd){if(nt.init.allow_console()){console.trace();}},
                group 	 : function(title){if(nt.init.allow_console()){console.group(title);}},
                groupEnd : function(cmd){if(nt.init.allow_console()){console.groupEnd();}},
                dir 	 : function(obj){if(nt.init.allow_console()){console.dir(obj);}},
                trace 	 : function(cmd){if(nt.init.allow_console()){console.trace();}}
            }
};

$(document).ready(function() {
                
        loadingSurLien();
        
	//lors du click, les infos disparaissent
        var marginEncour = 0;

        //$("div#connexion #password").hide();
        
        $("dl.zend_form ul.errors").css({position:"absolute",marginTop: "-3px",marginLeft: "-30px"});
        $("dl.zend_form ul.errors li").each(function(){
            marginEncour = marginEncour + 12;
            $(this).css({marginTop:marginEncour+"px"});
        });


	/*$("div#connexion #login").focus(function(){
            var valLogin = $("#login").val();
            if(valLogin =="identifiant"){
                $(this).val("");
            }
        });
        $(" div#connexion #login").blur(function(){
            var valLogin = $("#login").val();
            if(valLogin ==""){$("#login").val("identifiant")}
        });

        $(" div#connexion #passwordTexte").focus(function(){
            $(this).hide();
            $("#password").show();
            $("#password").focus();
        });

	$("div#connexion #password").focus(function(){
            $(this).val("");
        });

        $("div#connexion #password").blur(function(){
            var valPassword = $("#password").val();
            if(valPassword == ""){
                $("#password").hide();
                $("#passwordTexte").show();

            }
        });*/
	
	/*$('fieldset fieldset').each(function() {
		$(this).children('dd').fadeOut('fast');
	});
	$('fieldset fieldset').each(function() {
		$(this).children('dt').fadeOut('fast');
	});
	$('fieldset fieldset').each(function() {
		$(this).children('dl').fadeOut('fast');
	});
	*/
       
	$('legend').toggle(function() {
		$(this).parent('fieldset').children('dt').fadeIn('slow');
		$(this).parent('fieldset').children('dd').fadeIn('slow');
		$(this).parent('fieldset').children('dl').fadeIn('slow');
	},function() {
		$(this).parent('fieldset').children('dt').fadeOut('slow');
		$(this).parent('fieldset').children('dd').fadeOut('slow');
		$(this).parent('fieldset').children('dl').fadeOut('slow');

        });
	
	
	/** 
	 * Configuration du plugin TableTools pour datatables.
	 */
	if (window['TableToolsInit']) {
		TableToolsInit.sSwfPath = SiteBaseDirectory+"js/swf/ZeroClipboard.swf";
	   	TableToolsInit.sPrintInfo = "<h6>Vue Impression</h6><p>Utilisez s'il vous plaît la fonction 'Impression' de votre navigateur pour imprimer cette table.Appuyez sur la touche 'ECHAP' lorsque vous avez fini.</p>";
	   	TableToolsInit.sSaveExcel = "Exporter pour Excel";
	   	TableToolsInit.sSaveCsv = "Exporter en CSV";
	   	TableToolsInit.sCopyClipboard = "Copier dans le presse-papier";
	   	TableToolsInit.sRowsClipboad = " ligne(s) dans le presse-papier";
	   	TableToolsInit.sPrintTable = "Imprimer le tableau";
	   	TableToolsInit.sCopied = "Copie ";
	   	TableToolsInit.oFeatures = {
			"bCsv": true,
			"bXls": true,
			"bCopy": false,
			"bPrint": true
		};
	}
        
    //Gestion du changement de langues
    $("div#zone-lang a.lang").click(function(event) {
        
        //On recupere la page en cours
        var path = window.location.pathname;
        
        //On recupere la locale
        var id =  $(this).attr("id");
        var locale = id.substr(5);
        
        //On envoie pour le reload
        $.blockUI({ message: '<p class="loading"><img src="'+SiteBaseDirectory+ 'images/busy.gif" /> Validation en cours...</p>' });
        changeLang(locale, path);
        event.preventDefault();
	});
    
    //Gestion du changement de type de declaration
    $("div#zone-type-declaration a.typeDeclaration").click(function(event) {
        
        //On recupere la page en cours
        var path = window.location.pathname;
        
        //On recupere la locale
        var id =  $(this).attr("id");
        var id_type_declaration = id.substr(16);
        
        //On envoie pour le reload
        $.blockUI({ message: '<p class="loading"><img src="'+SiteBaseDirectory+ 'images/busy.gif" /> Validation en cours...</p>' });
        changeTypeDeclaration(id_type_declaration, path);
        event.preventDefault();
	});
        
	
});

function addLoadingAndReload(destination) {
    if (destination != '' || destination != undefined) {
        location.replace(SiteBaseDirectory + destination);
    } else {
        location.reload();
    }
}

function hideLoading() {
	$.unblockUI();
}


function animeLoading() {
	/*$('#LOADING').children('img').attr('src',SiteBaseDirectory+ 'images/loading_'+((id_loading %4) + 1)+'.gif');
	id_loading = id_loading + 1;
	timeout = setTimeout("animeLoading();", 300)*/
}



function arrondir(resultat) {
      resultat = Math.round(resultat*100)/100;
      return addSeparator(resultat.toFixed(2));
}

function addSeparator(nStr) {
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ' ' + '$2');
	}
	value = x1 + x2;

        return value.replace('.',',');
}

function loadingSurLien(){
    $("a").click(function() {
        var valClass = $(this).attr('class');
        var aPosition = "";
        if (valClass != undefined) {
        	aPosition = valClass.indexOf("none");
        }
        
        var valLiClass = $(this).parent('li').attr('class');
        var liPosition = "";
        if (valLiClass != undefined) {
        	liPosition = valLiClass.indexOf("none");
        } else {
        	var liPosition = -1;
        }
        
        if(aPosition == -1 && liPosition == -1) {
           $.blockUI({message: '<p class="loading"><img src="'+SiteBaseDirectory+ 'images/busy.gif" /> Chargement en cours...</p>'});
        }
    });
}

function dateFormat(format, date) {
	if (date == undefined) {
		date = new Date();
	}
	if (typeof date == 'number') {
		time = new Date();
		time.setTime(date);
		date = time;
	} else if (typeof date == 'string') {
		date = new Date(date);
	}
	var fullYear = date.getYear();
	if (fullYear < 1000) {
		fullYear = fullYear + 1900;
	}
	var hour = date.getHours();
	var day = date.getDate();
	var month = date.getMonth() + 1;
	var minute = date.getMinutes();
	var seconde = date.getSeconds();
	var milliSeconde = date.getMilliseconds();
	var reg = new RegExp('(d|m|Y|H|i|s)', 'g');
	var replacement = new Array();
	replacement['d'] = day < 10 ? '0' + day : day;
	replacement['m'] = month < 10 ? '0' + month : month;
	replacement['Y'] = fullYear;
	replacement['Y'] = fullYear;
	replacement['H'] = hour < 10 ? '0' + hour : hour;
	replacement['i'] = minute < 10 ? '0' + minute : minute;
	replacement['s'] = seconde < 10 ? '0' + seconde : seconde;
	return format.replace(reg, function($0) {
		return ($0 in replacement) ? replacement[$0] : $0.slice(1,
				$0.length - 1);
	});
}


function changeLang(locale, path) {
    
    var data = {locale: locale};
    
    //Envoi un Post pour modifier l'héritage choisi
    $.post(SiteBaseDirectory+"tools/changelang",
        data,
        function(json){
    		addLoadingAndReload(path.substr(1));
        },
        "json"
    );
}

function changeTypeDeclaration(id_type_declaration, path) {
    
    var data = {id_type_declaration: id_type_declaration};
    
    //Envoi un Post pour modifier l'héritage choisi
    $.post(SiteBaseDirectory+"tools/changetypedeclaration",
        data,
        function(json){
                //path.substr(1)
    		addLoadingAndReload(json);
        },
        "json"
    );
}


function loaderOn(conteneur) {
        $(conteneur).children("div.loader").remove();
        $(conteneur).prepend('<div class="loader"><img src="'+SiteBaseDirectory+'images/busy.gif" alt="Loading..." /></div>');
}

function loaderOff(conteneur) {
    $(conteneur).children("div.loader").remove();
}


/*
 * Methode qui permet de formater un nombre en javascript
 */

function number_format(number, decimals, dec_point, thousands_sep) {
        // http://kevin.vanzonneveld.net
        // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
        // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
        // +     bugfix by: Michael White (http://getsprink.com)
        // +     bugfix by: Benjamin Lupton
        // +     bugfix by: Allan Jensen (http://www.winternet.no)
        // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
        // +     bugfix by: Howard Yeend
        // +    revised by: Luke Smith (http://lucassmith.name)
        // +     bugfix by: Diogo Resende
        // +     bugfix by: Rival
        // +      input by: Kheang Hok Chin (http://www.distantia.ca/)
        // +   improved by: davook
        // +   improved by: Brett Zamir (http://brett-zamir.me)
        // +      input by: Jay Klehr
        // +   improved by: Brett Zamir (http://brett-zamir.me)
        // +      input by: Amir Habibi (http://www.residence-mixte.com/)
        // +     bugfix by: Brett Zamir (http://brett-zamir.me)
        // +   improved by: Theriault
        // +      input by: Amirouche
        // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
        // *     example 1: number_format(1234.56);
        // *     returns 1: '1,235'
        // *     example 2: number_format(1234.56, 2, ',', ' ');
        // *     returns 2: '1 234,56'
        // *     example 3: number_format(1234.5678, 2, '.', '');
        // *     returns 3: '1234.57'
        // *     example 4: number_format(67, 2, ',', '.');
        // *     returns 4: '67,00'
        // *     example 5: number_format(1000);
        // *     returns 5: '1,000'
        // *     example 6: number_format(67.311, 2);
        // *     returns 6: '67.31'
        // *     example 7: number_format(1000.55, 1);
        // *     returns 7: '1,000.6'
        // *     example 8: number_format(67000, 5, ',', '.');
        // *     returns 8: '67.000,00000'
        // *     example 9: number_format(0.9, 0);
        // *     returns 9: '1'
        // *    example 10: number_format('1.20', 2);
        // *    returns 10: '1.20'
        // *    example 11: number_format('1.20', 4);
        // *    returns 11: '1.2000'
        // *    example 12: number_format('1.2000', 3);
        // *    returns 12: '1.200'
        // *    example 13: number_format('1 000,50', 2, '.', ' ');
        // *    returns 13: '100 050.00'
        // Strip all characters but numerical ones.
        number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
        var n = !isFinite(+number) ? 0 : +number,
                prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
                sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
                dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
                s = '',
                toFixedFix = function (n, prec) {
                        var k = Math.pow(10, prec);
                        return '' + Math.round(n * k) / k;
                };
        // Fix for IE parseFloat(0.55).toFixed(0) = 0;
        s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
        if (s[0].length > 3) {
                s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
        }
        if ((s[1] || '').length < prec) {
                s[1] = s[1] || '';
                s[1] += new Array(prec - s[1].length + 1).join('0');
        }
        return s.join(dec);
}



function in_array(array, p_val) {
    var l = array.length;
    for(var i = 0; i < l; i++) {
        if (array[i] == p_val) {
            return true;
        }
    }
    return false;
}



function openPopup(name, title, windowWidth, windowHeight) {
	var centerWidth = (window.screen.width - windowWidth) / 2;
    var centerHeight = (window.screen.height - windowHeight) / 2;

    window.open(name,title,'titlebar=no,channelmode=no,fullscreen=no,resizable=no,scrollbars=no,status=no,toolbar=no,menubar=no,location=no,directories=no,width='+windowWidth+',height='+windowHeight+', left='+centerWidth+', top='+centerHeight);
    
}
