// {{{
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 class="x-box-bl"><div class="x-box-br"><div class="x-box-bc">',
				
					
				'</div></div></div>',
				'</div></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, 'bl-bl', [10, -90]);
            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('b').pause(5).ghost("b", {remove:true});
		}
    };
}();
// }}} 


Ext.namespace('Ext.myStatusBar');

Ext.myPanelTitle = function() {

    return {  	
	update : function()
	{
		var isready = 0;
		if (Ext.getCmp ("AccueilPanel") && Ext.getCmp("AcceuilRoot")
		&&  Ext.getCmp ("AccueilPanel")!= undefined && Ext.getCmp("AcceuilRoot")!= undefined
		&& Ext.getCmp("AcceuilRoot").root && Ext.getCmp("AcceuilRoot").root != undefined 
		&& Ext.getCmp("AcceuilRoot").root.childNodes[0] != undefined && Ext.getCmp("AcceuilRoot").root.childNodes[0])
		{
			Ext.getCmp ("AccueilPanel").setTitle(Ext.getCmp("AcceuilRoot").root.childNodes[0].text);
			Ext.getCmp ("AccueilPanel").setTitle("Acceuil");
			isready++;
			
		}
		if (Ext.getCmp ("DemarchePanel") && Ext.getCmp("DemarcheRoot")
		&& Ext.getCmp ("DemarchePanel") != undefined && Ext.getCmp("DemarcheRoot") != undefined
		&& Ext.getCmp("DemarcheRoot").root && Ext.getCmp("DemarcheRoot").root != undefined 
		&& Ext.getCmp("DemarcheRoot").root.childNodes[0] != undefined && Ext.getCmp("DemarcheRoot").root.childNodes[0])
		{
			isready++;
			Ext.getCmp ("DemarchePanel").setTitle(Ext.getCmp("DemarcheRoot").root.childNodes[0].text);
			Ext.getCmp ("DemarchePanel").setTitle("Démarches et Inscriptions");
		}
		if (Ext.getCmp ("AgentPanel") && Ext.getCmp("AgentRoot")
		 && Ext.getCmp ("AgentPanel") != undefined  && Ext.getCmp("AgentRoot") != undefined
		&& Ext.getCmp("AgentRoot").root && Ext.getCmp("AgentRoot").root != undefined 
		&& Ext.getCmp("AgentRoot").root.childNodes[0] != undefined && Ext.getCmp("AgentRoot").root.childNodes[0] )
		{
			isready++;
			Ext.getCmp ("AgentPanel").setTitle(Ext.getCmp("AgentRoot").root.childNodes[0].text);
			Ext.getCmp ("AgentPanel").setTitle("Agents");
		}
		if (Ext.getCmp ("LoginPanel")
		&& Ext.getCmp ("LoginPanel") != undefined )
		{			
			isready++;
			Ext.getCmp ("LoginPanel").setTitle("Connexion/Deconnexion");
		}
		if (isready > 2)
		{
			var panel = Ext.getCmp('west-panel');
			if (panel &&  (Ext.get('loggedId') && typeof(Ext.get('loggedId')) !='undefined'))
				panel.getLayout().setActiveItem(1);
		}
		else
		{
			setTimeout("Ext.myPanelTitle.update()", 500);
		}	
	 } 
	}
}();
Ext.myStatus = function() {

	var Status;
	var lastVarnum;
	
    return {  	
	update : function()
	{
		var currentTime = new Date()
		var rannum = Math.floor(Math.random()*5);
		var statusText;
		statusText = Ext.Info[rannum];
		{  
			statusBar = Ext.getCmp('basic-statusbar');
			statusBar.setText(statusText);
		}
		 setTimeout("Ext.myStatus.update()", 3500);
	 }
 
	}
}();

Ext.Tree = function() {

    return {
        
         
        Login : function (){
        
            var isAlreadyLogged = Ext.get('loggedId');
            if (isAlreadyLogged)
            {
                Ext.get("login-form-box").boxWrap();
                 Ext.form.Field.prototype.msgTarget = "side";
                 
                var loginForm = new Ext.form.FormPanel({
                   method: "post",
                   labelWidth: 85,
                   buttonAlign: "right",
                   url: "processlogin.php",
                   baseParams: {action: "logout"},
                   labelSeperator:"",
                   labelAlign: "right",
                   buttonAlign: "center",
                   waitMsgTarget : true
                  }
                 );
                 
                 
                 loginForm.form.on("actioncomplete", function(t,a) {
                    window.location.reload(true);
                 });
                 loginForm.form.on("actionfailed", function() {
                    Ext.MessageBox.alert(Ext.LangConsulat.loginError, Ext.LangConsulat.loginErrorCorrection);
                 });
                 loginForm.addButton(Ext.LangConsulat.Quit, function() { loginForm.form.submit(); });
                 loginForm.render("login-form");
            }
            else
            {
                 Ext.get("login-form-box").boxWrap();
                 Ext.form.Field.prototype.msgTarget = "side";
                var loginForm = new Ext.form.FormPanel({
                   method: "post",
                   labelWidth: 85,
                   buttonAlign: "right",
                   url: "processlogin.php",
                   baseParams: {action: "login"},
                   labelSeperator:"",
                   labelAlign: "right",
                   buttonAlign: "center",
                   waitMsgTarget : true
                  }
                 );
                 loginForm.form.on("actioncomplete", function(t,a) {
                    window.location.reload(true);
                 });
                 loginForm.form.on("actionfailed", function() {
                    Ext.MessageBox.alert(Ext.LangConsulat.loginError, Ext.LangConsulat.loginErrorCorrection);
                 });
                 loginForm.add (
                  new Ext.form.TextField(
                   {
                    name: "user",
                    fieldLabel: Ext.LangConsulat.login,
                    width: 100,
                    allowBlank: false
                   }
                  ),
                  new Ext.form.TextField(
                   {
                    name: "password",
                    fieldLabel: Ext.LangConsulat.password,
                    inputType: "password",
                    width: 100,
                    allowBlank: false
                   }
                  )
                 );
                 loginForm.addButton(Ext.LangConsulat.submit, function() { loginForm.form.submit(); });
                 loginForm.addButton(Ext.LangConsulat.clear, function() {loginForm.form.reset(); });
                 loginForm.render("login-form");
            }
        }
	};
}();

// run this function when document becomes ready
Ext.onReady(function() {

         // The only requirement for this to work is that you must have a hidden field and
    // an iframe available in the page with ids corresponding to Ext.History.fieldId
    // and Ext.History.iframeId.  See history.html for an example.
    Ext.History.init();

    Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
        
	var iconPath = 'imgicons/';

    var ChargementTxt               = Ext.LangConsulat.ChargementTxt;
    var ResetOrderTxt               = Ext.LangConsulat.ResetOrderTxt;
    var UndockableModeTxt           = Ext.LangConsulat.UndockableModeTxt;
    var IndependentModeTxt          = Ext.LangConsulat.IndependentModeTxt;
    var CollapseAllTxt              = Ext.LangConsulat.CollapseAllTxt;
    var ExpandAllTxt                = Ext.LangConsulat.ExpandAllTxt;
    var ShadowedDockTxt             = Ext.LangConsulat.ShadowedDockTxt;
    var FindTxt                     = Ext.LangConsulat.FindTxt;
    var FindDockToolTipTxt          = Ext.LangConsulat.FindDockToolTipTxt;
    
	  var loadFn = function(btn, statusBar){
        btn = Ext.getCmp(btn);
        statusBar = Ext.getCmp(statusBar);

        btn.disable();
        statusBar.showBusy();

        (function(){
            statusBar.clearStatus({useDefaults:true});
            btn.enable();
        }).defer(2000);
    };

	
    {
        var dt = new Date();
        var dateFormated = "Fr : " + dt.format('d-m-y H:i');                 //January 10, 2007, 3:05 pm
        var gmtdiff = dt.format('O');
        if (gmtdiff[0] == '+')
            dt = dt.add(Date.HOUR, - gmtdiff[2]);
        else 
            dt = dt.add(Date.HOUR, gmtdiff[2]);
        dateFormated = dateFormated + "<br/>Tg : " + dt.format('d-m-y  H:i');                 //January 10, 2007, 3:05 pm
        Ext.get ("togodatepanel").dom.innerHTML = dateFormated
    }
	
	// }}}

	// install onclick handler to unmask body (for debugging)
	//Ext.fly('loading-mask').on('click', unmask);
	//Ext.get('loading-mask').on('click', unmask);

	// initialize state manager, we will use cookies
	//Ext.state.Manager.setProvider(new Ext.state.CookieProvider());

	// initialize QuickTips
	Ext.QuickTips.init();
	Ext.apply(Ext.QuickTips, {interceptTitles: true});

	
	
	
    var elAgent = (Ext.get ("panel-a") != undefined);
	var panel0;
    if (elAgent)
    {
    	panel0 =  new Ext.Panel(
	   {
		    title : 'panel-a'
			, id : 'AgentPanel'
		    , contentEl : 'panel-a'
    		, iconCls: iconPath + 'lightbulb.png'
			, autoScroll: true
    	});
        
        
    }
    
	// Introduction
	var panel1 = new Ext.Panel({
		title : 'panel-1'
		, id : 'AccueilPanel'
		, contentEl : 'panel-1'
		, iconCls: iconPath + 'lightbulb.png'
		, collapsed: elAgent
		, autoScroll: true
	});

	// extjs
    
	// drag & drop
	var panel2 = new Ext.Panel(
	{
		title : 'panel-2'
		, id : 'DemarchePanel'
		, contentEl : 'panel-2'
		, iconCls: iconPath + 'mouse.png'
		, autoScroll: true
    });

    
	var panel3 = new Ext.Panel(
	{
		title : 'Login'
		, id : 'LoginPanel'
		, contentEl : 'panel-3'
		, iconCls: iconPath + 'lock_edit.png'
		, autoScroll: true
		
	});
    
	var panel4 = new Ext.Panel(
	{
		title : 'panel-4'
		, contentEl : 'panel-4'
		, iconCls: iconPath + 'magnifier.png'	
		, autoScroll: true	
	});
    

	// theme selector    
	var panel5 = new Ext.Panel(
	{
		title : 'panel-5'
		, contentEl : 'panel-5'
		, iconCls: iconPath + 'palette.png'	
		, autoScroll: true	
	});

	var ctheme = new Ext.form.ComboBox({
		typeAhead: true
		, triggerAction: 'all'
		, transform: 'theme-combo'
		, forceSelection: true
		//, width: 140
		//, listWidth: 158
	});
	// change theme on combo select
	ctheme.on('select', function() {
		Ext.util.CSS.swapStyleSheet('theme', 'ext/resources/css/' + this.getValue());
	}, ctheme);
    

	
         var acceuilTree;   
		{
			acceuilTree = new Ext.tree.TreePanel(
			   {  
			    renderTo: 'menuAccueilId',
				id: 'AcceuilRoot',
				autoScroll : true,
				animate:true, 
				loader: new Ext.tree.TreeLoader({dataUrl:'get_tree.php', baseParams: {partofTree : 'accueil'}}),
				//enableDD:true,
				containerScroll: true,
				autoCreate: true
				, rootVisible:false
				, root: {
							nodeType: 'async',
							text: 'Accueil',
							draggable: false,
							id: 'source'
							}
				});
			

			// render the tree
			acceuilTree.render();							
			acceuilTree.addListener("click", NodeLoad);
		}
		var demarchesTree;
		{
			demarchesTree = new Ext.tree.TreePanel(
			   {  
			    renderTo: 'menuDemarchesId',   
				id: 'DemarcheRoot',
				animate:true, 
				loader: new Ext.tree.TreeLoader({dataUrl:'get_tree.php', baseParams: {partofTree : 'inscription'}}),
				//enableDD:true,
				containerScroll: true,
				autoScroll : true,
				autoCreate: true,
				rootVisible:false
				, root :{        
				nodeType: 'async',
				text: 'Ext JS',
				draggable:false,
				id:'source'
				}
			});
			demarchesTree.render();
			demarchesTree.addListener("click", NodeLoad);
		}
		
		var agentTree;
		if (Ext.get ("panel-a") != undefined)
		{
			agentTree = new Ext.tree.TreePanel(
			   {  
			    renderTo: 'menuAgentsId',
				id: 'AgentRoot',
				animate:true, 
				loader: new Ext.tree.TreeLoader({dataUrl:'get_tree.php', baseParams: {partofTree : 'agents'}}),
				//enableDD:true,
				containerScroll: true,
				autoScroll : true,
				autoCreate: true,
				rootVisible:false
				, root :{        
				nodeType: 'async',
				text: 'Ext JS',
				draggable:false,
				id:'source'
				}
			});		
			// render the tree
			agentTree.render();						
			agentTree.addListener("click", NodeLoad);
		}
	// {{{
	// create layout 
        viewport = new Ext.Viewport
		({
            layout: 'border',
            items: [
            // create instance immediately
			new Ext.BoxComponent(
			{
                region: 'north',
				//id: 'north',
				el: 'north-body'
			}), 
			{
					// lazily created panel (xtype:'panel' is default)
					region: 'south',
					contentEl: 'south',
					//id: 'south',
					split: true,
					height: 28,
					minSize: 28,
					maxSize: 28,
					collapsible: true,
					//title: 'South',
					margins: '0 0 0 0',
					items:[{
					xtype: 'button',
					id: 'basic-button',
					text: 'Do Loading',
					handler: loadFn.createCallback('basic-button', 'basic-statusbar')
					}],
					 bbar: new Ext.ux.StatusBar({
            id: 'basic-statusbar',

            // defaults to use when the status is cleared:
            defaultText: 'Ext.LangConsulat.welcome',
            //defaultIconCls: 'default-icon',
        
            // values to set initially:
            text: Ext.LangConsulat.welcome,
            //iconCls: 'x-status-valid',

            // any standard Toolbar items:
            items: [
                '-',
                "<a href=\"#\" onClick=\"pageLoad('html/plansite.php')\">Plan du site</a> | <a href=\"#\" onClick=\"pageLoad('html/prive.php')\">Protection des donn&eacute;es</a> | <a href=\"#\" onClick=\"pageLoad('html/ferie.php')\">Jours  F&eacute;ri&eacute;s</a> | <a href=\"#\" onClick=\"pageLoad('html/poste.php')\">Bureau  de  poste</a>",
                '-',
                "<b>&copy; Consulat Togo </b>2008"
		   ]
        })
            }
			
			,
			{
                region: 'west',
                id: 'west-panel', // see Ext.getCmp() below
                //title: 'West',
                split: true,
                width: 250,
                minSize: 200,
                maxSize: 400,
                collapsible: true,
                margins: '0 0 0 0',
                layout: {
                    type: 'accordion',
					activeOnTop: true,
                    animate: true,
					sequence: true,
					collapseFirst: true,
					fill: true,
					titleCollapse: true
					, activeItem: 0
                },
                items: (panel0 != undefined) ? 
							[panel0, panel1, panel2, panel3//, panel4, panel5
							]
							:
							[panel1, panel2, panel3
							//, panel4, panel5
							]
            },
            // in this instance the TabPanel is not wrapped by another panel
            // since no title is needed, this Panel is added directly
            // as a Container
            new Ext.TabPanel({
                region: 'center', // a center region is ALWAYS required for border layout
				id: 'center',
                deferredRender: false,
                activeTab: 0,     // first tab initially active
                autoScroll: true,
                items: [{
                    contentEl: 'center1',
					title: '',
                    id: 'tableId'
                    //, closable: true,
                }, {
                    contentEl: 'center2',
					title: '',
                    id: 'demoId',
                    autoScroll: true
                }, {
                    contentEl: 'center3',
					title: '',
                    id: 'codeId',
                    autoScroll: true
                }, {
                    contentEl: 'center4',
					title: '',
                    id: 'htmlId',
                    autoScroll: true
                }, {
                    contentEl: 'center5',
					title: '',
                    id: 'formsId',
					frame: true,
                    autoScroll: false
                }]
            })]
        });      

	
    Ext.Tree.Login();
   
	pageLoad('html/accueil.php');
	
	setTimeout("Ext.myStatus.update()", 3500);
	setTimeout("Ext.myPanelTitle.update()", 500);
	
	
}); // end of onReady


function PanelLoad(nodeid, url, val)
{
	if ((val == 'html' && url == "demarches/recu.php"))
		val = 'demo';
	var el = Ext.get('demoId');
	file = 'load.php?';
	if (val == 'forms')
	{
		// detection
		var useAcrobat = navigator.mimeTypes && navigator.mimeTypes["application/pdf"];
		if (useAcrobat == false)
		{
		   Ext.MessageBox.alert('Installation', '<a href="http://www.adobe.com/products/acrobat/readstep2.html">Adobe Acrobat</a>');
		}
		file = 'forms.php?';
	}
	params = '&randomId=' + new Date(new Date().getTime()+(1000*60*60*24*30));
	try {
		el.load({url: file + val + '=' + url + params, scripts:true});
	}
	catch(err)
	{
	}
	var title;
	if (val == 'demo')
	{ 
		viewport.currentUrl = url;
	}
	else
	{
		title = val;
		if (val == 'forms')
			title = 'formulaire';
	}
	var region = viewport.get("center");
	region.get('demoId').setTitle(title);
	region.activate('demoId');

};


function NodeLoad(node, e)
{
	val = null;
	if (node.attributes['code'] != undefined)
		val = 'code';
	else  if (node.attributes['html'] != undefined)
		val = 'html';
	else  if (node.attributes['forms'] != undefined)
		val = 'forms';
	else  if (node.attributes['demo'] != undefined)
		val = 'demo';
   
	if (val != null)
	{
		PanelLoad(node.attributes['id'], node.attributes[val], val);
		Ext.History.add(node.attributes['id'] + '|' + node.attributes[val] + '|' + val);
	}
	return true;
};

// Handle this change event in order to restore the UI to the appropriate history state
Ext.History.on('change', function(token){
        if(token){
			var parts = token.split('|');
		
            PanelLoad(parts[0], parts[1], parts[2]);
        }else{
            // This is the initial default state.  Necessary if you navigate starting from the
            // page without any existing history token params and go back to the start state.            
			pageLoad('html/accueil.php');	
        }
    });

function pageLoad(url)
{    
    Ext.get('demoId').load({url: 'load.php?demo=' + url + '&randomId=' + new Date(new Date().getTime()+(1000*60*60*24*30)), scripts:true});
    
    viewport.currentUrl = url;    
    var region = this.viewport.get("center");   
    region.activate('demoId');
    
    var panel = region.get('htmlId');
    if (panel.el.isVisible())
    {
        if (node.attributes[val] == "login_resume.php")
            Ext.get('htmlId').load({url: 'load.php?demo=' + url, scripts:true});
        else
            Ext.get('htmlId').load({url: 'load.php?html=' + url, scripts:true});
    }
    
    //region.disable('codeId');
    //region.disable('htmlId');
    //region.disable('tableId');
    //region.disable('formsId');
};

/**
 * @version 0.4
 * @author nerdydude81
 */
Ext.override(Ext.Element, {
    /**
     * @cfg {string} printCSS The file path of a CSS file for printout.
     */
    printCSS: null
    /**
     * @cfg {Boolean} printStyle Copy the style attribute of this element to the print iframe.
     */
    , printStyle: false
    /**
     * @property {string} printTitle Page Title for printout. 
     */
    , printTitle: document.title
    /**
     * Prints this element.
     * 
     * @param config {object} (optional)
     */
    , print: function(config) {
        Ext.apply(this, config);
        
        var el = Ext.get(this.id).dom;
        var c = document.getElementById('printcontainer');
        var iFrame = document.getElementById('printframe');
        
        var strTemplate = '<HTML><HEAD>{0}<TITLE>{1}</TITLE></HEAD><BODY onload="{2}"><DIV {3}>{4}</DIV></BODY></HTML>';
        var strLinkTpl = '<link rel="stylesheet" type="text/css" href="{0}"/>'
        var strAttr = '';
        var strFormat;
        var strHTML;
        
        //Get rid of the old crap so we don't copy it
        //to our iframe
        if (iFrame != null) c.removeChild(iFrame);
        if (c != null) el.removeChild(c);
        
        //Copy attributes from this element.
        for (var i = 0; i < el.attributes.length; i++) {
            if (Ext.isEmpty(el.attributes[i].value) || el.attributes[i].value.toLowerCase() != 'null') {
                strFormat = Ext.isEmpty(el.attributes[i].value)? '{0}="true" ': '{0}="{1}" ';
                if (this.printStyle? this.printStyle: el.attributes[i].name.toLowerCase() != 'style')
                    strAttr += String.format(strFormat, el.attributes[i].name, el.attributes[i].value);
            }
        }
        
        var strLink ='';
        if(this.printCSS){
            if(!Ext.isArray(this.printCSS))
                this.printCSS = [this.printCSS];
            
            for(var i=0; i<this.printCSS.length; i++) {
                strLink += String.format(strLinkTpl, this.printCSS[i]);
            }
        }
        
        //Build our HTML document for the iframe
        strHTML = String.format(
                strTemplate
                , strLink
                , this.printTitle
                , Ext.isIE? 'document.execCommand(\'print\');': 'window.print();'
                , strAttr
                , el.innerHTML
        );
        
        //I coun't get FF to print a hidden iframe,
        //so I encapsulated it in a hidden div.
        c = document.createElement('div');
        c.setAttribute('style','width:0px;height:0px;' + (Ext.isSafari? 'display:none;': 'visibility:hidden;'));
        c.setAttribute('id', 'printcontainer');
        el.appendChild(c);
        
        //IE doesn't like style attributes anymore?
        if (Ext.isIE)
            c.style.display = 'none';
        
        iFrame = document.createElement('iframe');
        iFrame.setAttribute('id', 'printframe');
        iFrame.setAttribute('name', 'printframe');
        c.appendChild(iFrame);
        
        //Write our new document to the iframe
        iFrame.contentWindow.document.open();        
        iFrame.contentWindow.document.write(strHTML);
//iFrame.contentWindow.window.print(); 

        iFrame.contentWindow.document.close();
    }
});

Ext.override(Ext.Component, {
    printEl: function(config) {
        this.el.print(Ext.isEmpty(config)? this.initialConfig: config);
    }
    , printBody: function(config) {
        this.body.print(Ext.isEmpty(config)? this.initialConfig: config);
    }
}); 




