// Validare input telefon
Ext.apply( Ext.form.VTypes, { 
	'telefon': function() {  
		var re = /^(\d{4}[-]?){1}(\d{6})$/;
		return function(v) { return re.test(v); }
	}(), 'telefonText' : 'Formatul este gresit, exemplu: 0234-555555 (cratima este optionala)'
});

//Validare input fax
Ext.apply( Ext.form.VTypes, { 
	'fax': function() {  
		var re = /^(\d{4}[-]?){1}(\d{6})$/;
		return function(v) { return re.test(v); }
	}(), 'faxText' : 'Formatul este gresit, exemplu: 0234-555555 (cratima este optionala)'
});

//Validare input mobil
Ext.apply( Ext.form.VTypes, { 
	'mobil': function() {  
		var re = /^(\d{4}[-]?){1}(\d{6})$/;
		return function(v) { return re.test(v); }
	}(), 'mobilText' : 'Formatul este gresit, exemplu: 0740-555555 (cratima este optionala)'
});

//Validare input CodJ
Ext.apply( Ext.form.VTypes, { 
	'codj': function() {  
		var re = /^(\d{4}[-]?){1}(\d{6})$/;
		return function(v) { return re.test(v); }
	}(), 'codjText' : 'Formatul este gresit, exemplu: 0234-555555 (cratima este optionala)'
});

//Validare input codR
Ext.apply( Ext.form.VTypes, { 
	'codr': function() {  
		var re = /^(\d{4}[-]?){1}(\d{6})$/;
		return function(v) { return re.test(v); }
	}(), 'codrText' : 'Formatul este gresit, exemplu: 0234-555555 (cratima este optionala)'
});

//Validare cont bancar
Ext.apply( Ext.form.VTypes, { 
	'contiban': function() {
		//RO| |XX| |yyyy| |ZZZZZZZZZZZZZZZZ|
		var re = /^(RO)(\d{2})([A-Z]{4})([A-z0-9]{16})$/;
		return function(v) { return re.test(v); }
	}(), 'contibanText' : 'Formatul este gresit, exemplu: RO49AAAA1B31007593840000'
});


/**
* hoverIntent is similar to jQuery's built-in "hover" function except that
* instead of firing the onMouseOver event immediately, hoverIntent checks
* to see if the user's mouse has slowed down (beneath the sensitivity
* threshold) before firing the onMouseOver event.
* 
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* hoverIntent is currently available for use in all personal or commercial 
* projects under both MIT and GPL licenses. This means that you can choose 
* the license that best suits your project, and use it accordingly.
* 
* // basic usage (just like .hover) receives onMouseOver and onMouseOut functions
* $("ul li").hoverIntent( showNav , hideNav );
* 
* // advanced usage receives configuration object only
* $("ul li").hoverIntent({
*	sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)
*	interval: 50,   // number = milliseconds of polling interval
*	over: showNav,  // function = onMouseOver callback (required)
*	timeout: 100,   // number = milliseconds delay before onMouseOut function call
*	out: hideNav    // function = onMouseOut callback (required)
* });
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @return    The object (aka "this") that called hoverIntent, and the event object
* @author    Brian Cherne <brian@cherne.net>
*/

jQuery.fn.hoverIntent = function(f,g) {
	// default configuration options
	var cfg = {
		sensitivity: 7,
		interval: 100,
		timeout: 0
	};
	// override configuration options with user supplied object
	cfg = $.extend(cfg, g ? { over: f, out: g } : f );

	//console.log(g);
	
	// instantiate variables
	// cX, cY = current X and Y position of mouse, updated by mousemove event
	// pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
	var cX, cY, pX, pY;

	// A private function for getting mouse position
	var track = function(ev) {
		cX = ev.pageX;
		cY = ev.pageY;
	};

	// A private function for comparing current and previous mouse position
	var compare = function(ev,ob) {
		ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
		// compare mouse positions to see if they've crossed the threshold
		if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
			$(ob).unbind("mousemove",track);
			// set hoverIntent state to true (so mouseOut can be called)
			ob.hoverIntent_s = 1;
			return cfg.over.apply(ob,[ev]);
		} else {
			// set previous coordinates for next time
			pX = cX; pY = cY;
			// use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
			ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
		}
	};

	// A private function for delaying the mouseOut function
	var delay = function(ev,ob) {
		ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
		ob.hoverIntent_s = 0;
		return cfg.out.apply(ob,[ev]);
	};

	// A private function for handling mouse 'hovering'
	var handleHover = function(e) {
		// next three lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut
		var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
		while ( p && p != this ) { try { p = p.parentNode; } catch(e) { p = this; } }
		if ( p == this ) { return false; }

		// copy objects to be passed into t (required for event object to be passed in IE)
		var ev = jQuery.extend({},e);
		var ob = this;

		// cancel hoverIntent timer if it exists
		if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }

		// else e.type == "onmouseover"
		if (e.type == "mouseover") {
			// set "previous" X and Y position based on initial entry point
			pX = ev.pageX; pY = ev.pageY;
			// update "current" X and Y position based on mousemove
			$(ob).bind("mousemove",track);
			// start polling interval (self-calling timeout) to compare mouse coordinates over time
			if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}

		// else e.type == "onmouseout"
		} else {
			// unbind expensive mousemove event
			$(ob).unbind("mousemove",track);
			// if hoverIntent state is true, then call the mouseOut function after the specified delay
			if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
		}
	};
	// bind the function to the two event listeners
	return this.mouseover(handleHover).mouseout(handleHover);
}

var LexCat = {

	archiveGrid : {},
	buyWizard   : {},
	newsWidget  : null,
	iconsPath    : 'img/icons/',

/* == LEGEND
=== === === === === === ===
NNN = Normal Next Normal ()
NNH = Normal Next Hoover()
NNS = Normal Next Select()
HNN = Hover Next Normal ()
HNS = Hover Next Select()
SNN = Select Next Normal()
SNH = Select Next Hover()
=== === === === === === === */

onHoverGetBg: function(o) {
	if(o.prev() && o.next()) {
		if(o.prev().is('.snn')) {
			o.prev().addClass('snh');
			o.removeClass().addClass('hnn');
			o.children("a").removeClass().addClass('hover');
		}
		else if(o.next().is('.snn')) {
			o.removeClass().addClass('hns');
			o.prev().removeClass().addClass('nnh');
		}
		else if(o.is('.snn')) {
			o.removeClass().addClass('snn');
		}
		else {
			o.prev().removeClass().addClass('nnh');
			o.removeClass().addClass('hnn');
			o.children("a").removeClass().addClass('hover');
		}
	}
}, 

onMouseOutGetBg: function(o) {
	
	if(o.prev() && o.next()) {
		if(o.prev().is('.snn')) {
			o.prev().removeClass('snh').addClass('snn');
			o.removeClass().addClass('nnn');
			o.children("a").removeClass();
		}
		else if(o.next().is('.snn')) {
			o.removeClass().addClass('nns');
			o.prev().removeClass().addClass('nnn');
		}
		else if(o.is('.snn')) {
			o.removeClass().addClass('snn');
		}
		else {
			o.prev().removeClass().addClass('nnn');
			o.removeClass().addClass('nnn');
			o.children("a").removeClass();
		}
	}
}, 

animateTabs: function(o) {

	var tabs = o.children().css("left", "0");
	//console.info(tabs);

	
	tabs.each(function(i){

		// t = time, b = begin, c = change, d = duration
		$(this).animate({left: ((i * 147) + 7), opacity: '90'}, (75.625*(i*25)/(i*1,5) + .75));
	
		$(this).hover(function(){
		
			LexCat.onHoverGetBg($(this));
			
		}, function(){
		
			LexCat.onMouseOutGetBg($(this));
			
		});
	});
}, 

primaryOnMouseOut: function() {

	var toolbar = $(this).parent().next();

	var comandaFlag = false;
	
	if($(this).parents("li").attr('id') == 'primary-comanda') {
		comandaFlag = true;
	}
	
	if(!toolbar.is('.visible') && !comandaFlag) {
		$(this).parents("li").removeClass();
		$(this).removeClass().addClass('selected');
	}
}, 

primaryOnHover: function() {
	
	var toolbars = $("#primary-navigation ul");
	var primaries = $("#primary-navigation>li>h3>a");
	var comandaFlag = false;
	
	if($(this).parents("li").attr('id') == 'primary-comanda') {
		comandaFlag = true;
		if($('.visible')) 
		{
			$('#frame').animate({className:'animator', top:0}, 200, 'easeout');
			$(this).parents('li').addClass('active');
		}
		if($.jSlider) {
			var current = $.jSlider.current;
			$.jSlider.slide($(current).attr('coordonate'), [2,0]);
			$.jSlider.current = $.jSlider.sections[9];
		}
	}	
	
	var toolbar = null;
	
	if(arguments[0] == "toolbar") {
		toolbar = $(arguments[1]);
	} else {
		toolbar = $(this).parent().next();
	}
	
	//console.dir(toolbar);
		
	$(toolbars).each(function(){
		if($(this).is('.visible')) { $(this).hide(); }
		$(this).parents("ul").removeClass().children("li").removeClass('selected');
	})

	//console.info($(this).parents('li'));
	$(this).parents('li').addClass('active');
	$(this).removeClass().addClass('active');
	//$(this).parents("ul").children("li").removeClass();
	toolbar.css('top', '10');
	
	//console.info(primaries.not($(this)));
	primaries.not($(this)).each(function(){$(this).removeClass('active').addClass('selected'); $(this).parents('li').removeClass();});

	//console.log($('#frame').css('top', 0));
	
	//animate frame first and then the tabs
	if(!toolbar.is('.visibile') && !comandaFlag) 
	{
		$('#frame').animate({className:'animator', top:'80'}, 250, 'easeout', function(){
			toolbar.fadeIn('normal').addClass('visible').animate({top:'105', visibility:'visible'}, 250, 'easeout', function() {LexCat.animateTabs(toolbar)});	
		});
	}			
}, 

initGrid: function() {
	
    var fm = Ext.form;
    var ps = 30;

    Ext.QuickTips.init();
	
    // create the Data Store
    var ds = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
           url: '/arhiva/arhiva.json'
           //url: 'http://localhost/lexcat/arhiva/arhiva.json'
        }),
        reader: new Ext.data.JsonReader({
            root: 'items',
            id: 'id',
            totalProperty: 'totalCount'
        }, [
			{name: 'denumire', mapping: 'denumire' },
            {name: 'rezumat', mapping: 'rezumat', type: 'string'},
            {name: 'data', mapping: 'date', type: 'date', dateFormat: 'Y-m-d'}
        ]),

        // turn on remote sorting
        remoteSort: true
    });
    ds.setDefaultSort('id', 'desc');

	function renderDescription(value, p, record){
        return String.format('<b>{0}</b>{1}', value, record.data['rezumat']);
    }
	
	function renderDescriptionPlain(value){
        return String.format('<b><i>{0}</i></b>', value);
    }
	
	function renderDate(value, p, r){
        return String.format('{0}<br />by {1}', value.dateFormat('M j, Y'), r.data['data']);
    }
    
	function renderDatePlain(value){
        return value.dateFormat('j F Y');
		//console.info(value);
	}
	
    // the column model has information about grid columns
    // dataIndex maps the column to the specific data field in
    // the data store
    var cm = new Ext.grid.ColumnModel([{
           id: 'topic', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
           header: "Descriere",
           dataIndex: 'denumire',
           width: 550,
           renderer: renderDescription,
           css: 'white-space:normal;'
        },{
		   id:'data_publicare',
           header: "Data aparitie",
           dataIndex: 'data',
           width: 100,
		   align: 'right',
		   renderer: renderDatePlain
        }]);

    // by default columns are sortable
    cm.defaultSortable = true;

    // create the editor grid
    var grid = new Ext.grid.Grid('topic-grid', {
        ds: ds,
        cm: cm,
        selModel: new Ext.grid.RowSelectionModel({singleSelect:true}),
        enableColLock: false,
				loadMask: true
    });
	
	this.archiveGrid = grid;

    // make the grid resizable, do before render for better performance
    var rz = new Ext.Resizable('topic-grid', {
        wrap:true,
        minHeight:100,
        pinned:true,
        handles: 's'
    });
    rz.on('resize', grid.autoSize, grid);

	 // render it
    grid.render();
	
	//console.info(grid);
    
	var gridFoot = grid.getView().getFooterPanel(true);

    // add a paging toolbar to the grid's footer
    var paging = new Ext.PagingToolbar(gridFoot, ds, {
        pageSize: ps,
        displayInfo: true,
        displayMsg: 'Afiseaza noutatile legislative {0} - {1} din {2}',
        emptyMsg: "Nu sunt noutati de afisat"
    });

    var gridHead = grid.getView().getHeaderPanel();
    
	gridHead.show();
	
	
    var tb = new Ext.Toolbar(gridHead);
	
    var quickMenuItems = ['<b class="menu-title">Cautare rapida</b>','-'];
	
    var quickMenu = new Ext.menu.Menu({
		id: 'quickMenu',
		items: quickMenuItems
    });
	
    tb.add({
		text: 'Cautare',
		tooltip: 'Cautare rapida printre descrierile de acte normative.'
		//,menu: quickMenu
    });
	
    var sftb = tb.addDom({
		tag: 'input',
		id: 'quicksearch',
		type: 'text',
		size: 30,
		value: '',
		style:'calenda'
    });
	
	//tb.addSpacer();
	//tb.addSeparator();
	
	tb.addFill();
	
	 // Menus can be prebuilt and passed by reference
    var fromDateMenu = new Ext.menu.DateMenu({
        handler : function(dp, date){
			Ext.get('from_date').dom.value = date.format('j M Y');
        }
    });
	
	var toDateMenu = new Ext.menu.DateMenu({
        handler : function(dp, date){
           Ext.get('to_date').dom.value = date.format('j M Y');
        }
    });
	
	
	// functions to display feedback
    function onPeriodClick(btn){
        //alert('Ai apasat pe butonul ' +  btn.text);
		ds.load({params: {start:0, limit:paging.pageSize, filter:'', from: Ext.getDom('from_date').value, to: Ext.getDom('to_date').value}});
    }
	
	/*
	tb.add({
		text: 'Perioada: ',
		tooltip: 'Cautare intr-o anumita perioada'
		//,menu: quickMenu
    });
	*/
	
	tb.add({
		text:'De la ',
		tooltip:'Stabiliti data pentru inceputul perioadei',
		menu:fromDateMenu,
		cls:'x-btn-text-icon calendar'
	});
	
	tb.addSpacer();
	
	var from_idate = tb.addDom({
		tag: 'input',
		id: 'from_date',
		type: 'text',
		size: 10,
		value: new Date().dateFormat('j M Y'),
		style: 'background: #F0F0F9;'
    });

	//tb.addSeparator();
	
	tb.add({
		text:'Pana la ',
		tooltip:'Stabiliti data pentru sfarsitul perioadei',
		menu:toDateMenu,
		cls:'x-btn-text-icon calendar'
	});
	
	tb.addSpacer();
	
	var to_idate = tb.addDom({
		tag: 'input',
		id: 'to_date',
		type: 'text',
		size: 10,
		value: new Date().dateFormat('j M Y'),
		style: 'background: #F0F0F9;'
    });
	
	tb.addSpacer();
	
	var periodBut = tb.add({
		cls: 'x-btn-text bmenu',
		text: 'Afiseaza',
		handler: onPeriodClick
	});
	
	//tb.addSeparator();
	
    var searchBox = new Ext.form.HistoryComboBox({
		hideTrigger: true,
		//hideClearButton: true,
		emptyText: "Tasteaza cuvantul cheie ...",
		//rememberOn: 'all'
		rememberOn: 'delay',
		mode: 'remote'
    });
    searchBox.applyTo('quicksearch');

    var searchRec = Ext.data.Record.create([
        {name: 'query', type: 'string'}
    ]);
	
    var onFilteringBeforeQuery = function(e) {
		grid.getSelectionModel().clearSelections();
		var value = searchBox.getValue();

        if (value.length==0) {
            ds.clearFilter();
        } else {
			
			if ((!value || value=='') && !ds.baseParams['filter']) {
				return;
			} else if (value.length>0) {
				ds.baseParams = {"filter":value};
				//Ext.get('ssfilterlabel').update("- filter on "+value);
			} else {
				ds.baseParams = {"filter":''};
				//Ext.get('ssfilterlabel').update("");
			}
			
			paging.cursor = 0;
			
			ds.load({params: {start:paging.cursor, limit:paging.pageSize, filter:value}});
        }
    };
    quickMenu.on('click', onFilteringBeforeQuery);
    searchBox.on("valueChange", onFilteringBeforeQuery);

	ds.load({params:{start: paging.cursor, limit: paging.pageSize}});
}, 

initNewsGrid: function() {
	
	//console.log('initNewsGrid...');
	
    var fm = Ext.form;
    var ps = 10;

    Ext.QuickTips.init();
	
    // create the Data Store
    var ds = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: 'http://www.lexcat.ro/arhiva/news.json'
        }),
        reader: new Ext.data.JsonReader({
            root: 'items',
            id: 'id',
            totalProperty: 'totalCount'
        }, [
			{name: 'denumire', mapping: 'denumire' },
			{name: 'rezumat', mapping: 'rezumat' },
            {name: 'data', mapping: 'date', type: 'date', dateFormat: 'Y-m-d'}
        ]),

        // turn on remote sorting
        remoteSort: true
    });
    ds.setDefaultSort('id', 'desc');

	function renderDescription(value, p, record){
        return String.format('<b>{0}</b>', value);
    }
	
	function renderDescriptionPlain(value){
        return String.format('<b><i>{0}</i></b>', value);
    }
	
	function renderDate(value, p, r){
        return String.format('{0}<br />by {1}', value.dateFormat('M j, Y'), r.data['data']);
    }
    
	function renderDatePlain(value){
        return value.dateFormat('j F Y');
		//console.info(value);
	}
	
    // the column model has information about grid columns
    // dataIndex maps the column to the specific data field in
    // the data store
    var cm = new Ext.grid.ColumnModel([{
           id: 'topic', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
           header: "Descriere",
           dataIndex: 'denumire',
           width: 200,
		   align:'left',
           renderer: renderDescription,
		   className:'x-grid-topic'
        },{
		   id:'data_publicare',
           header: "Data aparitie",
           dataIndex: 'data',
           width: 80,
		   align: 'right',
		   renderer: renderDatePlain
        }]);

    // by default columns are sortable
    cm.defaultSortable = false;

    // create the editor grid
    var grid = new Ext.grid.Grid('last_news_grid', {
        ds: ds,
        cm: cm,
        selModel: new Ext.grid.RowSelectionModel({singleSelect:true}),
        enableColLock: true,
		loadMask: true
    });
	
	grid.addListener('rowclick',
		function (grid, rowIndex, e) {
			LexCat.accordion(grid, rowIndex, e);
    	}
	);
	
	//this.archiveGrid = grid;
	
    // make the grid resizable, do before render for better performance
    var rz = new Ext.Resizable('last_news_grid', {
        wrap:true,
        minHeight:100,
        pinned:true,
        handles: 's'
    });
	
    rz.on('resize', grid.autoSize, grid);

	 // render it
    grid.render();
	
	/*
	var gridFoot = grid.getView().getFooterPanel(true);

    // add a paging toolbar to the grid's footer
    var paging = new Ext.PagingToolbar(gridFoot, ds, {
        pageSize: ps,
        displayInfo: true,
        displayMsg: 'Afiseaza noutatile legislative {0} - {1} din {2}',
        emptyMsg: "Nu sunt noutati de afisat"
    });
	*/
	ds.load({params:{start: 0, limit: 10}});
},

// }}}
// {{{
// Accordion in dialog 
accDlgShow: function(btn, e) {

	var dpanel4, stickyNote;
	var self = this;

	// {{{
	// lazy create the dialog
	if(!this.dlg) {

		// create the BasicDialog
		this.dlg = new Ext.BasicDialog('acc-dialog', {
			width: 450
			, height: 350
			, x: 560
			, y: 144
			, modal: false
			, shadow: true
			, proxyDrag: true
		});

		// add hide on escape pressed handler
		this.dlg.addKeyListener(27, this.dlg.hide, this.dlg);

		// create the Accordion
		this.acc = new Ext.ux.Accordion(this.dlg.body, {
			fitHeight: true
			, fitToFrame: true
			, fitContainer: true
			, desktop: 'center-accordions'
			, autoScroll: false
		});

		//get last 10 news
		 // create the Data Store
		//var view = new Ext.JSONView("")
		
		for(i = 1; i < 11; i++){
			this.acc.add(new Ext.ux.InfoPanel('dpanel-' + i, {
				icon: LexCat.iconsPath + 'newspaper.png'
			}));
		}
		
		// inform accordion of dialog resize
		this.dlg.on('resize', function(dlg, w, h) {
			this.setSize(dlg.body.getWidth(), dlg.body.getHeight());
		}, this.acc);

		// update text of show/hide button
		this.dlg.on('show', function() {
			btn.setText('Ascunde ultimele noutati legislative');
			this.setPanelHeight();

			// fix the firefox cursor bug
//				var dlgCt;
//				if(Ext.isGecko) {
//					dlgCt = Ext.get('acc-dialog');
//					dlgCt.setStyle('overflow','');
//					dlgCt.setStyle.defer(10, dlgCt, ['overflow','auto']);
//				}

		}, this.acc);
		this.dlg.on('hide', function() {btn.setText('Ultimele noutati legislative');});

//			this.acc.restoreState();
//			if(!dpanel4.collapsed) {
//				stickyNote.fitToParent();
//			}

	} 
	// end of dlg lazy creation
	// }}}

	// show/hide dialog on button click
	if(this.dlg.isVisible()) {
		this.dlg.hide(btn.el);
	}
	else {
		this.dlg.show(btn.el);
	}
	
	//console.dir(this.acc);
	
}, 
// end of function accDlgShow


createWizard: function(){
	
	//form for Step1
	/*
	* ================  Pasul 1  =======================
         */
    var formStep1 = new Ext.form.Form({
        labelAlign: 'right',
        labelWidth: 75
    });

    formStep1.column({width:500, labelWidth:75}); // open column, without auto close
    
	formStep1.fieldset(
        {legend:'Date contact'},
		
        new Ext.form.TextField({
            fieldLabel: 'Nume',
            name: 'data[nume]',
            allowBlank:false
        }),

		new Ext.form.TextField({
            fieldLabel: 'Prenume',
            name: 'data[prenume]',
            allowBlank:false
        }),
		
        new Ext.form.TextField({
            fieldLabel: 'Functie',
            name: 'data[functie]',
            allowBlank: false
        }),
		
		new Ext.form.TextField({
            fieldLabel: 'Email',
            name: 'data[email]',
            vtype:'email',
            allowBlank: false
        })
    );
	

    formStep1.end(); // closes the last container element (column, layout, fieldset, etc) and moves up 1 level in the stack

	//form 2
	var formStep2 = new Ext.form.Form({
        labelAlign: 'top'
    });
 
 
 	formStep2.column({width:220, labelWidth:180});
	
	formStep2.fieldset(
        
		{legend:'Date firma'},
		
        new Ext.form.TextField({
            fieldLabel: 'Nume firma',
            name: 'data[firma]',
            allowBlank: false
        }),

		new Ext.form.TextField({
            fieldLabel: 'Numar Registrul Comertului',
            name: 'data[codJ]',
			//vtype:'codj',
			allowBlank: false
        }),
		
		new Ext.form.TextField({
            fieldLabel: 'Cod fiscal',
            name: 'data[codR]',
			//vtype:'codr',
			allowBlank: false
        })
    );
	
	formStep2.fieldset(
	
		{legend: 'Date banca'},
		
		new Ext.form.TextField({
            fieldLabel: 'Cont bancar',
            name: 'data[cont]',
			vtype:'contiban',
			allowBlank: false
        }),
		new Ext.form.TextField({
            fieldLabel: 'Nume banca',
            name: 'data[banca]',
			allowBlank: false
        }),
		new Ext.form.TextField({
            fieldLabel: 'Filiala banca',
            name: 'data[filiala]',
			allowBlank: false
        })
	);
		
	formStep2.end();
	
	formStep2.column({
		width:200, style:'margin-left:10px', clear: true
	});
	
	formStep2.fieldset(
		{legend: 'Adresa firma'},
	
		 new Ext.form.TextArea({
            fieldLabel: 'Adresa',
            name: 'data[adresa]',
            grow: true,
			growMin: 30,
            preventScrollbars:true,
			allowBlank: false,
			width: 150
        }),
	
		new Ext.form.TextField({
            fieldLabel: 'Localitate',
            name: 'data[localitate]',
            /*grow: true,
            preventScrollbars:true,*/
            allowBlank: false
        }),
		
		new Ext.form.ComboBox({
            fieldLabel: 'Judeţ',
            hiddenName:'data[judet]',
            store: new Ext.data.SimpleStore({
                fields: ['abreviere', 'judet'],
                data : Ext.judete.lista // from judete.js
            }),
            displayField:'judet',
            typeAhead: true,
            mode: 'local',
            triggerAction: 'all',
            emptyText:'Alegeti judetul...',
            selectOnFocus:true,
            width:160,
			className:'combo',
			allowBlank: false
        }),
		
		new Ext.form.TextField({
            fieldLabel: 'Cod Poştal',
            name: 'data[cod_postal]',
            allowBlank: false
        })
	);
 
 	//formStep2.end();
 
	formStep2.fieldset(
		{legend:'Numere de telefon'},
		
		new Ext.form.TextField({
		    fieldLabel: 'Telefon',
		    name: 'data[telefon]',
			vtype:'telefon',
		    allowBlank: false
		}),
		
		new Ext.form.TextField({
		    fieldLabel: 'Fax',
		    name: 'data[fax]',
			vtype:'fax',
			allowBlank: false
		}),
		
		new Ext.form.TextField({
		    fieldLabel: 'Mobil',
			name: 'data[mobil]',
		    vtype:'mobil', 
			allowBlank: false
		})
	);
 
 	formStep2.end();
 
 	//form for Step 3
	var formStep3 = new Ext.form.Form({
        labelWidth: 175 // label settings here cascade unless overridden,
    });
	
	formStep3.fieldset({legend:'Modalitati plata', clear: true, style: 'margin-left:10px'});
	
	//simple.end();
	
	var optRamburs = new Ext.form.Radio({
			fieldLabel: 'Plata ramburs prin Posta',
			name: 'data[Checkout][payment_method_id]',
			inputValue: '1',
			boxLabel: 'Plata prin ramburs',
			checked: true,
			width:275
		});
		
	var optMB = new Ext.form.Radio({
			fieldLabel: 'Plata instant prin carte de credit prin MoneyBookers',
			name: 'data[Checkout][payment_method_id]',
			inputValue: '3',
			boxLabel: 'Plata online prin MoneyBookers',
			fieldClass: 'visa',
			width:275
		});
		
	var dialog;	
		
	function showDialog(frameaddress, dialogTitle)
	{
			//create template with iframe
			var template = new Ext.Template(
			'<iframe id="centerFrame" name="centerFrame" frameborder="no" style="border:0px none;" scrolling="yes" src="' + frameaddress + '" width="100%", height="100%"></iframe>'
);
		
		 //Create Dialogs
		if(!dialog){
			dialog = new Ext.LayoutDialog('order-dlg',{
				autoCreate: true,
				closable: true,
				syncHeightBeforeShow: true,
				modal: true,
				width: 800,
				height: 590,
				fixedcenter: true,
				shadow: false,
				resizable: false,
				proxyDrag: true,
				title: dialogTitle,
				center: {autoScroll:false}
			});
		
			dialog.addKeyListener(27, dialog.hide, dialog);
			dialog.addButton('Inchide', dialog.hide, dialog);
		
			var layout = dialog.getLayout();
			layout.beginUpdate();
			center = layout.add('center', new Ext.ContentPanel('dialogCenter', {autoCreate: true, fitToFrame:true, closable: false}));
		
			layout.endUpdate();
			var centerEl = center.getEl();
			template.overwrite(centerEl.dom, {});
		}
		dialog.show();
	}		
		
			
    formStep3.add(
		optRamburs,
		optMB
	);
	
	//simple.end();
	
	var wiz = new Ext.Widget.Wizard('Wizard',
		{           
			steps:[
                {label:'Date personale', form: formStep1},
                {label:'Date firma', form: formStep2},
				{label:'Modalitate plata', form: formStep3}
				
            ]
		}
	);
	
	this.buyWizard = wiz;
	
	/*
	what to do when the finish button is pressed and
	all data was validated
	*/
	wiz.on("finish", this.doSubmit);
},

doSubmit: function(form, wiz){

	var fs = form.getValues();
	var values = Ext.encode(fs);
	
	var mod_plata = $(fs).attr('data[Checkout][payment_method_id]');

	var options = {
		 url:'http://www.lexcat.ro/comanda'
		,success:LexCat.submitSuccess
		,method:'POST'
		,waitMsg:'Comanda se proceseaza...'
		,headers:{'X-Requested-With': 'XMLHttpRequest'}
	}

	//console.log('mod_plata is ' + mod_plata);

	if(mod_plata == '1') {
		form.submit(options);
	}
	else {		
		
		var dialog;	
			
		function showDialog(frameaddress, dialogTitle)
		{
				//create template with iframe
				var template = new Ext.Template(
				'<iframe id="centerFrame" name="centerFrame" frameborder="no" style="border:0px none;" scrolling="yes" src="' + frameaddress + '" width="100%" height="100%">Alternate content</iframe>'
			);
			
			 //Create Dialogs
			if(!dialog){
				dialog = new Ext.LayoutDialog('order-dlg',{
					autoCreate: true,
					closable: true,
					syncHeightBeforeShow: true,
					modal: true,
					width: 760,
					height: 590,
					fixedcenter: true,
					shadow: false,
					resizable: false,
					proxyDrag: true,
					title: dialogTitle,
					center: {autoScroll:false}
				});
			
				dialog.addKeyListener(27, dialog.hide, dialog);
				dialog.addButton('Inchide', dialog.hide, dialog);
			
				var layout = dialog.getLayout();
				layout.beginUpdate();
				center = layout.add('center', new Ext.ContentPanel('dialogCenter', {autoCreate: true, fitToFrame:true, closable: false}));
			
				layout.endUpdate();
				var centerEl = center.getEl();
				template.overwrite(centerEl.dom, {});
			}
			
			//console.dir(form);
			form.el.dom.setAttribute('action', frameaddress);
			form.el.dom.setAttribute('target', 'centerFrame');
			//form.el.un('submit', form.onSubmit, form);
			//form.on('beforeaction', function(form, action) { if (action=='submit') { form.el.dom.submit(); return false; } });
			form.el.dom.submit();
			dialog.show();
		}	
		//console.log('show dialog...');
		showDialog('http://www.lexcat.ro/comanda', 'Comanda online aplicatia LexCat prin MoneyBookers!');
	}
},

submitSuccess: function(form, action){
	Ext.MessageBox.alert('Comanda LexCat', action.result.mesaj + "\n" + action.result.mail + "\n");
	$(document.body).bind('click', function() {window.location.href = 'http://dev.lexcat.ro';});
},

showNews : function(){
    if(!this.newsWidget){ // lazy initialize the dialog and only create it once
        this.newsWidget = new Ext.LayoutDialog("news-grid", { 
                autoTabs:true,
                width:300,
                height:500,
                shadow:true,
                minWidth:200,
                minHeight:400,
                proxyDrag: true,
				center: {
					autoScroll: true,
					tabPosition: 'top',
					closeOnTab: true,
					alwaysShowTabs:true
				}
        });
        this.newsWidget.addKeyListener(27, this.newsWidget.hide, this.newsWidget);
        //this.newsWidget.addButton('Submit', this.newsWidget.hide, this.newsWidget).disable();
        this.newsWidget.addButton('Inchide', this.newsWidget.hide, this.newsWidget);
		var layout = this.newsWidget.getLayout();
        layout.beginUpdate();
	    layout.add('center', new Ext.ContentPanel('center', {title: 'Noutati legislative'}));
		LexCat.initNewsGrid();
	    layout.endUpdate();
    }
    this.newsWidget.show(showBtn.dom);
},

init: function() {
	
	//OTHER NASTY SHITS
	
	var self = this;
	//let's take care of menu
	var primaries = $("#primary-navigation>li>h3>a");
	var third =  $("li#noutati-tab");
	var legi_toolbar = $("ul#toolbar-legi");
	var support_toolbar = $("ul#toolbar-suport");
	
	third.removeClass().addClass('snn');
	third.children("a").removeClass().addClass('icon_select');
	
	//primaries.not(primaries.eq(2)).each(function(i){
	
	primaries.each(function(i){
	
		$(this).hoverIntent({
			sensitivity: 1,
			interval: 400,
			over: self.primaryOnHover,
			timeout: 400,
			out: self.primaryOnMouseOut
		});
		
	});
	
	if(($.browser.msie) && Math.round($.browser.version) < 7)  {self.primaryOnHover.call(self, "toolbar", support_toolbar);} // IE HAC ;)
	self.primaryOnHover.call(self, "toolbar", legi_toolbar);
  	
	// remove loading screen
	var objLoading = Ext.get('loading');
	var objMask = Ext.get('loading-mask');
	
	objMask.setOpacity(.8);
	objLoading.fadeOut({remove:true,duration: 1});
	objMask.fadeOut({duration:1.5,remove:true,easing: 'easeOut', endOpacity:0});
	//objMask.fadeOut({duration:0.5,remove:true,easing: 'easeOut', endOpacity:0});
	
	setTimeout(function(){
		
		$(document.body).ScrollTo(800, 'wrapper');
		
		/*= jSlider init
		=== === === === */
		$.jSlider.init(); 
		
		//Ext.onReady(LexCat.init, LexCat);
		
	}, 600);
	
	// }}}
	// {{{
	// create show/hide dialog button
	var btnDlg = new Ext.Button('news-accordion-button', {
		icon: this.iconsPath + 'new.png'
		, cls: 'x-btn-text-icon'
		, text: 'Ultimele noutati legislative'
		, scope: LexCat
		, handler: LexCat.accDlgShow
	});
}};

Ext.onReady(LexCat.init, LexCat);
// Full document ready