Ext.namespace('ProxCons');
Ext.BLANK_IMAGE_URL = 'js/ext/resources/images/default/s.gif';

function putCookie(cookieName, cookieValue) {
	document.cookie = cookieName+"="+cookieValue+"; expires=Monday, 04-Apr-2050 05:00:00 GMT";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

ProxCons.index = function(config) {
	Ext.QuickTips.init();
	
	this.config = {};
	Ext.apply(this.config,config);
	
	this.cadastro = {};
	this.login = {};
	this.indique = {};
	this.initBotoesRodape();
	
	
	//## LOGIN ##
	this.login.login = new Ext.form.TextField({
		id: 'idLogin',
		name: 'login',
		allowBlank: false,
		renderTo: this.config.login.loginId,
		blankText: this.config.cadastro.cpf.blankText,
		fieldClass: 'formCadastrese',
		style: 'width: 195px;height:19px;',
		scope: this
	});
	
	var usuario = readCookie('pc_usuario');
	if (usuario != null) {
		Ext.get("idLogin").dom.value = usuario;
	}
	
	//## SENHA ##
	this.login.senha = new Ext.form.TextField({
		name: 'senha',
		allowBlank: false,
		renderTo: this.config.login.senhaId,
		blankText: this.config.cadastro.obrigatorio,
		fieldClass: 'form_arial_11_333',
		inputType: 'password',
		style: 'width: 195px;height:19px;',
		scope: this
	});
	
	//## NOME INDIQUE ##
	this.indique.nomeIndicador = new Ext.form.TextField({
		name: 'nomeIndicador',
		allowBlank: false,
		renderTo: this.config.indique.nomeIndicador,
		blankText: this.config.indique.obrigatorio,
		fieldClass: 'form_arial_11_333',
		style: 'width: 175px;height:19px;',
		scope: this
	});
	
	//## EMAIL INDIQUE ##
	this.indique.emailIndicado = new Ext.form.TextField({
		name: 'emailIndicado',
		allowBlank: false,
		renderTo: this.config.indique.emailIndicado,
		blankText: this.config.indique.obrigatorio,
		fieldClass: 'form_arial_11_333',
		vtype: 'email',
		vtypeText: this.config.indique.emailInvalido,
		style: 'width: 175px;height:19px;',
		scope: this
	});
	
		
	//## CPF ##
	this.cadastro.cadastroCPF = new Ext.form.TextField({
		name: 'cadastroCPF',
		allowBlank: false,
		renderTo: this.config.cadastro.cpf.id,
		blankText: this.config.cadastro.cpf.blankText,
		fieldClass: 'formCadastrese',
		validator: this.validaCPF,
		style: 'height:19px;',
		scope: this
	});
	
	//## NOME ##
	this.cadastro.nome = new Ext.form.TextField({
		name: 'cadastroNome',
		allowBlank: false,
		renderTo: this.config.cadastro.nome.id,
		blankText: this.config.cadastro.obrigatorio,
		fieldClass: 'formCadastrese',
		validator: this.validaNome,
		style: 'height:19px;',
		scope: this
	});
	
	//## CADASTRO SENHA 2 ##
	this.cadastro.senha2 = new Ext.form.TextField({
		name: 'cadastroSenha2',
		allowBlank: false,
		renderTo: this.config.cadastro.senha2.id,
		blankText: this.config.cadastro.obrigatorio,
		fieldClass: 'formCadastrese',
		inputType: 'password',
		invalidText: this.config.cadastro.senha2.invalidText,
		validator: this.validaSenha2,
		style: 'height:20px;',
		scope: this
	});
	
	//## CADASTRO SENHA 1 ##
	this.cadastro.senha1 = new Ext.form.TextField({
		name: 'cadastroSenha1',
		allowBlank: false,
		renderTo: this.config.cadastro.senha1.id,
		blankText: this.config.cadastro.obrigatorio,
		fieldClass: 'formCadastrese',
		inputType: 'password',
		scope: this,
		style: 'height:20px;',
		validator: this.validaSenha1
	});
	
	
	//## EMAIL ##
	this.cadastro.email = new Ext.form.TextField({
		name: 'cadastroEmail',
		allowBlank:false,
		renderTo:'divCadastroEmail',
		blankText: this.config.cadastro.obrigatorio,
		fieldClass:'formCadastrese',
		vtype: 'email',
		style: 'height:20px;',
		vtypeText: this.config.cadastro.email.invalidoText
	});
	
	//## CATEGORIA ##
	this.cadastro.categoria = new Ext.form.ComboBox({
		id: 'idCategoria',
		hiddenName : 'cadastroCategoria',
		renderTo: this.config.cadastro.categoria.id,
		blankText: this.config.cadastro.obrigatorio,
		typeAhead: true,
		editable: false,
		enableKeyEvents: true,
		fieldClass: 'formCadastrese',
		emptyText: this.config.cadastro.categoria.emptyText,
		loadingText: this.config.cadastro.categoria.loadingText,
		mode: 'remote',
		allowBlank: false,
		width: 258,
		triggerAction: 'all',
		displayField: 'label',
		valueField: 'value',
		store:new Ext.data.Store({
			proxy: new Ext.data.HttpProxy({
				method: 'GET',
				url: 'index/cadastroComboLoad'
			}),
			reader: new Ext.data.ArrayReader({
				},
				Ext.data.Record.create([
					{name: 'label'},
   					{name: 'value'}
				])
			)
		})
	});	
	this.flashObj = Ext.get('swf_apresentacao');
	Ext.get('btCadastrar').on('click',this.sendForm,this);
	Ext.get('btLogon').on('click',this.loginIn,this);
	Ext.get('esqueceu').on('click',this.esqueceuFn,this);
	Ext.get('indique_submit').on('click',this.indiqueFn,this);
};

ProxCons.index.prototype = ({
  
  esqueceuFn: function ()  {
    this.flashObj.hide();
    new Ext.Window({
			autoCreate : true,
			title: "Esqueceu a Senha?",
			resizable:false,
			frame: true,
			minimizable : false,
			maximizable : false,
			stateful: false,
			modal: true,
			shim:true,
			buttonAlign:"center",
			width:530,
			height:180,
			minHeight: 80,
			plain:false,
			footer:true,
			closable:true,
			scope: this,
			close: function () {
				this.scope.flashObj.show();
				this.hide();
			},
			animCollapse: true,
			animateTarget: 'esqueceu',
			items: [{
				xtype: 'panel',
				baseCls: '',
				height: 40,
				items: [{
					xtype: 'box',
					autoEl: {html:'<table width="100%"><tbody class="formCadastrese"><tr valign="middle"><td align="center">Digite seu CPF para que seja enviado uma nova senha para o e-mail cadastrado em sua conta. </td></tr><tr><td align="center"><br>CPF:<input id="cpfFieldEsq" type:"text"></td></tr><tr><td align="center"><br>Caso não tenha nenhum e-mail cadastrado entre em contato conosco via e-mail ou telefone.</td></tr></tbody></table>'},
					baseCls: ''
				}]
			}],
			buttons: [{
				text: "Continuar",
				handler: this.esqueceuSenhaContinuar,
				scope: this
			}]
		}).show();
  },
  
  esqueceuSenhaContinuar: function (botao,janela,aviao) {
    var cpf = Ext.get("cpfFieldEsq").dom.value;
    this.scope = this;
    if(this.validaCPF(cpf)) {
      botao.ownerCt.hide();
      new Ext.form.BasicForm('senderF').submit({
        url: "index/esqueceuASenha",
        success: this.esqueceuIndexSuccess,
        failure: this.esqueceuIndexFail,
        scope: this,
        params: {
          cpf: cpf
        }
      });
    } else {
      Ext.MessageBox.show({
          title: 'ERRO!',
          msg: this.invalidText,
          width: 300,
          buttons: Ext.MessageBox.OK,
          icon: Ext.MessageBox.ERROR
      });
    }
  },
  
  esqueceuIndexSuccess: function(form,action) {
    Ext.MessageBox.show({
      title: 'Sucesso',
      msg: action.result.msg,
      width:300,
      buttons: Ext.MessageBox.OK,
      fn: function(e){
        window.indexMain.flashObj.show();
      },
      icon: Ext.MessageBox.SUCCESS
    });
  },
  
  esqueceuIndexFail: function(form,action) {
    Ext.MessageBox.show({
      title: 'ERRO',
      msg: action.result.msg,
      width:300,
      buttons: Ext.MessageBox.OK,
      fn: function(e){
        window.indexMain.flashObj.show();
      },
      icon: Ext.MessageBox.ERROR
    });
  },

	selectedCategoriaLogon: function(e) {
		if(e.ownerCt.findByType('combo')[0].isValid()) {
			if(e.ownerCt.findByType('combo')[0].value == 'paciente')  {
				this.flashObj.show();
				e.ownerCt.hide();
				window.location =  "paciente/main.jsp?" + new Date().getTime();
			} else if(e.ownerCt.findByType('combo')[0].value == 'profissional')  {
				this.flashObj.show();
				e.ownerCt.hide();
				window.location =  "profissional/main.jsp?" + new Date().getTime();
			} else if(e.ownerCt.findByType('combo')[0].value == 'atendente')  {
				this.flashObj.show();
				e.ownerCt.hide();
				window.location =  "atendente/main.jsp?" + new Date().getTime();
			} else {
			
			}
		}
	},

	//## VALIDAÇÕES ##//
	validaSenha1: function (texto) {
		if(/^.{4,255}$/.test(texto)) {
			return true;
		} else {
			this.invalidText = this.scope.config.cadastro.minimo;
			return false;
		}
	},
	validaSenha2: function () {
		if(this.scope.cadastro.senha2.el.dom.value == this.scope.cadastro.senha1.el.dom.value) {
			return true;
		} else {
			return false;
		}
	},
	validaNome: function (texto) {
		if(/^[a-z çÇáÁéÉíÍóÓúÚâÂêÊîÎôÔûÛãÂõÕA-Z]{4,250}$/.test(texto)) {
			return true;
		} else {
			if(/^.{4,255}$/.test(texto)) {
				// Caracter invalido
				this.invalidText = this.scope.config.cadastro.nome.invalidoText;
			} else {
				// Quantia minima nao atingida
				this.invalidText = this.scope.config.cadastro.minimo;
			}
			return false;
		}
	},
	
	validaCPF: function (cpf) {
		if (!(/^\d+$/.test(cpf))) {
			this.invalidText = this.scope.config.cadastro.cpf.numeros;
			return false;
		}
		if (cpf.length == 11)  { 
			if (cpf == "00000000000" ||   
					cpf == "11111111111" ||   
					cpf == "22222222222" ||   
					cpf == "33333333333" ||   
					cpf == "44444444444" ||   
					cpf == "55555555555" ||   
					cpf == "66666666666" ||   
					cpf == "77777777777" ||   
					cpf == "88888888888" ||   
					cpf == "99999999999") {  

				this.invalidText = this.scope.config.cadastro.cpf.invalido;
				return false;  
			}  
			var a = [];  
			var b = 0;  
			var c = 11;  
			for (i=0; i<11; i++){  
				a[i] = cpf.charAt(i);  
				if (i < 9){
					 b += (a[i] * --c);
				}  
			}
			if ((x = b % 11) < 2) {
				a[9] = 0;
			} else { 
				a[9] = 11-x;
			}  
			b = 0;  
			c = 11;  
			for (y=0; y<10; y++) {
				b += (a[y] * c--);
			}   
			if ((x = b % 11) < 2) { 
				a[10] = 0; 
			} else { 
				a[10] = 11-x; 
			}
			if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10])) {  
				this.invalidText = this.scope.config.cadastro.cpf.invalido;
				return false; 
			}
		} else {  
			this.invalidText = this.scope.config.cadastro.cpf.invalido;
			return false;
		}
		return true;
	},
	
	loginIn: function (e) {
		e.stopEvent();
		var theForm = new Ext.form.BasicForm('loginForm',{});
		theForm.add(this.login.login);
		theForm.add(this.login.senha);
		if (theForm.isValid()) {
			this.flashObj.hide();
			theForm.submit({
				url: 'index/loginFormSubmit',
				method: 'POST',
				header: ['Accept-Charset utf-8;q=0.7,*;q=0.7'],
				success: this.onSucessLogin,
				failure: this.onFailLogin,
				clientValidation: true,
				waitMsg:  this.config.login.submit,
				scope: this
			});
		} else {
			this.flashObj.hide();
			Ext.MessageBox.show({
	           title: this.config.login.titleError,
	           msg: this.config.login.emBranco,
	           icon: Ext.MessageBox.ERROR,
	           width:300,
	           buttons: Ext.MessageBox.OK,
	           fn: this.showFlash,
	           animEl: 'btLogon',
	           form: theForm
       		});
		}
	},
	
	indiqueFn: function (e) {
		e.stopEvent();
		var theForm = new Ext.form.BasicForm('form_indique',{});
		theForm.add(this.indique.nomeIndicador);
		theForm.add(this.indique.emailIndicado);
		if (theForm.isValid()) {
			this.flashObj.hide();
			theForm.submit({
				url: 'index/indicacaoFormSubmit',
				method: 'POST',
                header: ['Accept-Charset utf-8;q=0.7,*;q=0.7'],
				success: this.onSucessIndique,
				failure: this.onFailIndique,
				clientValidation: true,
				waitMsg:  this.config.indique.submit,
				scope: this,
				params: {
				   nomeIndicador: this.indique.nomeIndicador.getValue(),
				   emailIndicado: this.indique.emailIndicado.getValue()
				}
			});
		} else {
			this.flashObj.hide();
			Ext.MessageBox.show({
	           title: this.config.indique.titleError,
	           msg: this.config.indique.emBranco,
	           icon: Ext.MessageBox.ERROR,
	           width:300,
	           buttons: Ext.MessageBox.OK,
	           fn: this.showFlash,
	           animEl: 'indique_submit',
	           form: theForm
       		});
		}
	},

	confirmaEmailForm: function () {
		this.flashObj.hide();
		new Ext.Window({
			autoCreate : true,
			title: 'Confirme seu email...',
			resizable:false,
			frame: true,
			minimizable : false,
			maximizable : false,
			stateful: false,
			modal: true,
			shim:true,
			buttonAlign:"center",
			width:400,
			height:150,
			minHeight: 80,
			plain:false,
			footer:true,
			closable:true,
			scope: this,
			close: function () {
				this.hide();
				this.scope.flashObj.show();
			},
			animCollapse: true,
			animateTarget: 'btCadastrar',
			items: [{
				xtype: 'panel',
				baseCls: '',
				height: 40,
				items: [{
					xtype: 'box',
					autoEl: {html:'<table width="100%"><tbody class="formCadastrese"><tr valign="middle"><td align="center">Confirme seu endereço de email para completar o cadastro</td></tr></tbody></table>'},
					baseCls: ''
				}]
			},{
				xtype: 'form',
				id: 'confirmEmailForm',
				baseCls: '',
				layout: 'column',
				frame: false,
				items: [{
					xtype: 'panel',
					baseCls: '',
					items: [{
						xtype: 'box',
						fieldClass: 'formCadastrese',
						autoEl: {html:'<table width="100%"><tbody class="formCadastrese"><tr valign="middle"><td align="right">Email:</td></tr></tbody></table>'},
						width: 150,
						baseCls: ''
					}]		
				},{
					xtype: 'panel',
					baseCls: '',
					items: [{
						id: 'email2',
						xtype: 'textfield',
                        fieldLabel: 'Email:',
                        name: 'email2'
 					}]
				}]
			}],
			buttons: [{
				text: 'Concluir Cadastro',
				handler: this.submitForm,
				scope: this
			}]
		}).show();
		Ext.getCmp('email2').focus(true,500);
	},
	
	sendForm: function (e) {
		e.stopEvent();
		var theForm = new Ext.form.BasicForm('cadastroFormX',{});
		theForm.add(this.cadastro.cadastroCPF);
		theForm.add(this.cadastro.nome);
		theForm.add(this.cadastro.senha2);
		theForm.add(this.cadastro.senha1);
		theForm.add(this.cadastro.email);
		theForm.add(this.cadastro.categoria);
		if (theForm.isValid()) {
			this.confirmaEmailForm();
		} 
		else {
			this.flashObj.hide();
			Ext.MessageBox.show({
	           title: this.config.cadastro.errorTitle,
	           msg: this.config.cadastro.errorMsg,
	           icon: Ext.MessageBox.ERROR,
	           width:300,
	           buttons: Ext.MessageBox.OK,
	           fn: this.showFlash,
	           animEl: 'btCadastrar'
       		});
		}
	},
	
	focuseEmailConfirm: function(e) {
		e.ownerCt.focus();
		Ext.getCmp('email2').focus(true, 400);
	},
	
	submitForm: function(e) {
		var emailConfirmCmp = Ext.getCmp('email2'); 	
		if (emailConfirmCmp) {
			var email2 = emailConfirmCmp.getValue();
			var email1 = this.cadastro.email.getValue();
			if (email2.toLowerCase() != email1.toLowerCase()) {
				Ext.MessageBox.show({
			           title: 'Erro de validação',
			           msg: 'Email não confere. Verifique o preenchimento do cadastro',
			           icon: Ext.MessageBox.ERROR,
			           width:300,
			           buttons: Ext.MessageBox.OK,
			           fn: this.focuseEmailConfirm,
			           animEl: 'btCadastrar'
		       	});
			}
			else {
				this.flashObj.show();
				e.ownerCt.hide();
				var theForm = new Ext.form.BasicForm('cadastroFormX',{});
				theForm.add(this.cadastro.cadastroCPF);
				theForm.add(this.cadastro.nome);
				theForm.add(this.cadastro.senha2);
				theForm.add(this.cadastro.senha1);
				theForm.add(this.cadastro.email);
				theForm.add(this.cadastro.categoria);
		        this.cadastro.cadastroCPF.setValue(encode(this.cadastro.cadastroCPF.getValue()));
		        this.cadastro.nome.setValue(encode(this.cadastro.nome.getValue()));
		        this.cadastro.senha2.setValue(encode(this.cadastro.senha2.getValue()));
		        this.cadastro.senha1.setValue(encode(this.cadastro.senha1.getValue()));
		        this.cadastro.email.setValue(encode(this.cadastro.email.getValue()));
		        this.cadastro.categoria.setValue(encode(this.cadastro.categoria.getValue()));
				this.flashObj.hide();
				theForm.submit({
					url: 'index/cadastroFormSubmit',
					method: 'POST',
					success: this.onSucessCadastro,
					failure: this.onFailCadastro,
					failure: this.onFailCadastro,
					clientValidation: false,
					waitMsg: this.config.cadastro.submit,
					scope: this
				});
		        this.cadastro.cadastroCPF.setValue(decode(this.cadastro.cadastroCPF.getValue()));
		        this.cadastro.nome.setValue(decode(this.cadastro.nome.getValue()));
		        this.cadastro.senha2.setValue(decode(this.cadastro.senha2.getValue()));
		        this.cadastro.senha1.setValue(decode(this.cadastro.senha1.getValue()));
		        this.cadastro.email.setValue(decode(this.cadastro.email.getValue()));
		        this.cadastro.categoria.setValue(decode(this.cadastro.categoria.getValue()));
			}
		}
	},
	
	onSucessCadastro: function (form, action) {
		var msg = action.options.scope.config.cadastro.sucessMsg;
		if (action.form.el.dom.cadastroCategoria.value == 'profissional') {
			msg += "<p>Não deixe de preencher sua Cidade, Especialidade e Telefone de Atendimento para que os pacientes possam encontrá-lo nas buscas! Divulgar os seus serviços não custa nada!";
		}
		//action.form.reset();
		Ext.MessageBox.show({
	           title: action.options.scope.config.cadastro.sucessTitle,
	           msg: msg,
	           icon: Ext.MessageBox.SUCCESS,
	           width:300,
	           buttons: Ext.MessageBox.OK,
	           fn: this.openMainPage,
	           animEl: 'btCadastrar'
       	});
	},
	
	openMainPage: function() {
		var categoria = Ext.getCmp('idCategoria').value;
		if (categoria == 'paciente') {
			window.location = "paciente/main.jsp?" + new Date().getTime();
		}
		else if (categoria == 'profissional') {
			window.location = "profissional/main.jsp?" + new Date().getTime();
		}
		else if (categoria == 'atendente') {
			window.location = "atendente/main.jsp?" + new Date().getTime();
		}
	},
	
	onFailCadastro: function (form, action) {
		action.form.el.dom.cadastroSenha1.value = "";
		action.form.el.dom.cadastroSenha2.value = "";
		Ext.MessageBox.show({
	           title: action.options.scope.config.cadastro.errorTitle,
	           msg: action.result.msg,
	           icon: Ext.MessageBox.ERROR,
	           width:300,
	           buttons: Ext.MessageBox.OK,
	           fn: this.showFlash,
	           animEl: 'btCadastrar'
       	});
	},
	
	onSucessIndique: function (form, action) {
		action.form.reset();
		Ext.MessageBox.show({
	           title: action.options.scope.config.indique.sucessTitle,
	           msg: action.options.scope.config.indique.sucessMsg,
	           icon: Ext.MessageBox.SUCCESS,
	           width:300,
	           buttons: Ext.MessageBox.OK,
	           fn: this.showFlash,
	           animEl: 'indique_submit'
       	});
	},
	
	onFailIndique: function (form, action) {
		Ext.MessageBox.show({
	           title: action.options.scope.config.indique.errorTitle,
	           msg: action.result.msg,
	           icon: Ext.MessageBox.ERROR,
	           width:300,
	           buttons: Ext.MessageBox.OK,
	           fn: this.showFlash,
	           animEl: 'indique_submit'
       	});
	},
	
	onSucessLogin: function (form, action) {
		putCookie('pc_usuario', Ext.get("idLogin").dom.value);
		if(action.result.quantia == '-1' && action.result.paciente == '-1' && action.result.profissional== '-1' && action.result.atendente== '-1') {
			window.location = "admin/index.jsp";
		} else if(action.result.quantia == '1') {
			//Direciona para a pagina do devido
			if(action.result.paciente == '1') {
				window.location = "paciente/main.jsp?" + new Date().getTime();
			}
			if(action.result.profissional== '1') {
				window.location = "profissional/main.jsp?" + new Date().getTime();
			}
			if(action.result.atendente== '1') {
				window.location = "atendente/main.jsp?" + new Date().getTime();
			}
		} else {
			var array = [];
			for(i = 0; i< action.result.quantia;i++) {
				var tipo = [];
				if(action.result.paciente == '1') {
					tipo = ['paciente','Paciente'];
					array[i] = tipo;
					action.result.paciente = '0';
					continue;
				}
				if(action.result.profissional== '1') {
					tipo = ['profissional','Profissional da Saúde'];
					array[i] = tipo;
					action.result.profissional = '0';
					continue;
				}
				if(action.result.atendente== '1') {
					tipo = ['atendente','Secretária'];
					array[i] = tipo;
					action.result.atendente = '0';
					continue;
				}
			}
			this.flashObj.hide();
			new Ext.Window({
				autoCreate : true,
				title: this.config.cadastro.categoria.emptyText,
				resizable:false,
				frame: true,
				minimizable : false,
				maximizable : false,
				stateful: false,
				modal: true,
				shim:true,
				buttonAlign:"center",
				width:400,
				height:150,
				minHeight: 80,
				plain:false,
				footer:true,
				closable:true,
				scope: this,
				close: function () {
					this.hide();
					this.scope.flashObj.show();
				},
				animCollapse: true,
				animateTarget: 'btLogon',
				items: [{
					xtype: 'panel',
					baseCls: '',
					height: 40,
					items: [{
						xtype: 'box',
						autoEl: {html:'<table width="100%"><tbody class="formCadastrese"><tr valign="middle"><td align="center">' + this.config.cadastro.categoria.preLogin + '</td></tr></tbody></table>'},
						baseCls: ''
					}]
				},{
					xtype: 'form',
					id: 'chooseLoginForm',
					baseCls: '',
					layout: 'column',
					frame: false,
					items: [{
						xtype: 'panel',
						baseCls: '',
						items: [{
							xtype: 'box',
							fieldClass: 'formCadastrese',
							autoEl: {html:'<table width="100%"><tbody class="formCadastrese"><tr valign="middle"><td align="right">Categoria:</td></tr></tbody></table>'},
							width: 150,
							baseCls: ''
						}]		
					},{
						xtype: 'panel',
						baseCls: '',
						items: [{
							xtype: 'combo',
							fieldClass: 'formCadastrese',
							width: 150,
							mode: 'local',
							emptyText: this.config.cadastro.categoria.emptyText,
							editable: false,
							hiddenName: 'choiceLogin',
							store: new Ext.data.SimpleStore({
								fields: ['value', 'display'],
								data: array
							}),
							blankText: this.config.cadastro.obrigatorio,
							allowBlank: false,
							displayField: 'display',
							valueField: 'value',
							triggerAction: 'all',
							baseCls: ''
						}]
					}]
				}],
				buttons: [{
					text: this.config.cadastro.categoria.continuar,
					handler: this.selectedCategoriaLogon,
					scope: this
				}]
		}).show();
			
		}
	},
	
	onFailLogin: function (form, action) {
		action.form.el.dom.senha.value = "";
		Ext.MessageBox.show({
	           title: action.options.scope.config.login.error,
	           msg: action.result.msg,
	           icon: Ext.MessageBox.ERROR,
	           width:300,
	           buttons: Ext.MessageBox.OK,
	           fn: this.showFlash,
	           animEl: 'btLogon'
       	});
	},
	
	showFlash: function () {
		Ext.get('swf_apresentacao').show();
	},
  
  initBotoesRodape: function() {
    Ext.get("saibamais").on("click",this.popupMenuRodape,this);
    Ext.get("saibamaisGrande").on("click",this.popupMenuRodape,this);
    Ext.get("planos").on("click",this.popupMenuRodape,this);
    Ext.get("contato").on("click",this.popupMenuRodape,this);
    Ext.get("faq").on("click",this.popupMenuRodape,this);
  },
  
  popupMenuRodape:function(event,target,b,c) {
    var id = target.id;
    var title = "";
    var url = "";
    var width = 0;
    var height = 0;
    var contentType = "text/html;charset=ISO-8859-1";
    if(id === "saibamais") {
      title = "Saiba Mais";
      url = "saibamais.html";
      width = 987;
      height = 547;
    } else if(id === "saibamaisGrande") {
        title = "Saiba Mais Sobre O Sistema";
        url = "saibamais_sistema.html";
        width = 987;
        height = 547;
    } else if(id === "planos") {
      title = "Planos";
      url = "planos.html";
      width = 987;
      height = 601;
    } else if(id === "contato") {
      title = "Contato";
      url = "contato.html";
      width = 987;
      height = 452;
    } else if(id === "faq") {
      title = "FAQ";
      url = "faq.html";
      width = 987;
      height = 479;
    } else {
      return;
    }
    this.flashObj.hide();
    if (!this.rodapeWindow) {
      this.rodapeWindow = new Ext.Window({
        autoCreate: true,
        title: title,
        resizable: false,
        frame: true,
        minimizable: false,
        maximizable: false,
        stateful: false,
        modal: true,
        shim: true,
        buttonAlign: "center",
        width: width,
        height: height,
        minHeight: 80,
        plain: false,
        footer: true,
        closable: true,
        scope: this,
        close: function(){
          this.hide();
          this.scope.flashObj.show();
        },
        animCollapse: true,
        animateTarget: target.id,
        items: [{
          xtype: 'panel',
          baseCls: '',
          height: 40,
          items: [{
            xtype: 'box',
            autoEl: {
              html: '<div id="areaToLoadRodape"></div>'
            },
            baseCls: ''
          }]
        }]
      });
    } else {
      this.rodapeWindow.setHeight(height);
      this.rodapeWindow.setWidth(width);
      this.rodapeWindow.setTitle(title);
      this.rodapeWindow.center();
    }
    this.rodapeWindow.show();
    Ext.get("areaToLoadRodape").load({
        url: url,
        scripts: true,
        text: "Carregando... Por favor Aguarde!",
		headers: {
			'Content-Type': contentType
		},
		timeout: 60000,
		failure: this.loadFailure
    });
    
  },
  
  loadFailure: function(form, action) {
    
  }
});

prepareSendForm = function() {
  Ext.get("imagem").on("click",sendIndexForm);
};

sendIndexForm = function() {
  Ext.get("meuDiv").mask("Enviando Email! Aguarde...", 'x-mask-loading');
  new Ext.form.BasicForm('sendForm').submit({
    url: "sendIndexMsg",
    success: sendMessageIndexSuccess,
    failure: sendMessageIndexFail,
    scope: this,
    params: {
    }
  });
};

sendMessageIndexSuccess = function(form,action) {
  Ext.get("meuDiv").unmask();
  window.indexMain.rodapeWindow.hide();
  Ext.MessageBox.show({
    title: 'Sucesso',
    msg: action.result.msg,
    width:300,
    buttons: Ext.MessageBox.OK,
    fn: function(e){
      window.indexMain.flashObj.show();
    },
    icon: Ext.MessageBox.SUCCESS
  });
  
};

var highlightMe = function(a) {
  if (a.style.backgroundColor != "rgb(223, 232, 246)" && a.style.backgroundColor != "#dfe8f6") {
    a.style.backgroundColor = "#E2FFD6";
  }
};

var unHighlightMe = function(a) {
  if (a.style.backgroundColor != "rgb(223, 232, 246)" && a.style.backgroundColor != "#dfe8f6") {
    a.style.backgroundColor = "";
  }
};

var selecMe = function(a) {
  Ext.get("link01").dom.style.backgroundColor = "";
  Ext.get("link02").dom.style.backgroundColor = "";
  Ext.get("link03").dom.style.backgroundColor = "";
  Ext.get("link04").dom.style.backgroundColor = "";
  Ext.get("link05").dom.style.backgroundColor = "";
  Ext.get("link06").dom.style.backgroundColor = "";
  Ext.get("link07").dom.style.backgroundColor = "";
  Ext.get("link08").dom.style.backgroundColor = "";
  Ext.get("link09").dom.style.backgroundColor = "";
  Ext.get("link10").dom.style.backgroundColor = "";
  a.style.backgroundColor = "#DFE8F6";
  var text = "<b>Resposta:</b>&nbsp;&nbsp;&nbsp;";
  if(a.id == "link01") {
     text += "Sim. O profissional poderá criar diferentes serviços correspondentes a cada consultório em que trabalha. O sistema permite ao profissional criar até 5 serviços personalizados: Nome do Serviço, Descrição, Horários de Atendimento, Convênios e Lembrete.";
  } else if(a.id == "link02") {
     text += "Sim. Basta ter acesso a internet e você poderá acessar sua agenda de qualquer lugar. Para isso, basta acessar o site www.proximaconsulta.com.br e realizar o login com suas informações.";
  } else if(a.id == "link03") {
     text += "A PróximaConsulta enviará mensalmente e anualmente ao profissional relatórios com números consolidados de consultas e de pacientes. Nestes relatórios o profissional poderá verificar a sua evolucão no decorrer do tempo.";
  } else if(a.id == "link04") {
     text += "Sim. Todos usuários cadastrados na PróximaConsulta poderão realizar buscas avançadas de profissionais liberais por Estado, Cidade, Área de Atuação, Especialidade ou Convênio. O usuário poderá então analisar a Descrição de cada Profissional (seu Marketing Pessoal) e solicitar a inclusão ou não deste profissional em sua Lista particular de Profissionais.";
  } else if(a.id == "link05") {
     text += "Sempre que uma consulta é cancelada ou alterada, o paciente é notificado através do seu e-mail cadastrado no sistema. Através deste mesmo e-mail o paciente também será notificado sobre consultas agendadas (lembrete um dia antes da consulta).";
  } else if(a.id == "link06") {
     text += "Para o profissional compartilhar sua agenda, basta cadastrar no sistema (tab Meus Dados) o CPF de sua secretária. Os serviços para sua secretária são gratuitos.";
  } else if(a.id == "link07") {
     text += "Sim. Se a atendente possuir internet em casa, ela poderá acessar sua agenda e realizar os agendamentos para você.";
  } else if(a.id == "link08") {
     text += "Sim. O sistema permite que uma mesma atendente possa trabalhar com a agenda de até 5 profissionais liberais.";
  } else if(a.id == "link09") {
     text += "Todos os pacientes com acesso a internet poderão em seu Histórico de Consultas avaliar o atendimento de sua secretária. Profisionais que trabalham ou já trabalharam com os serviços de sua secretária também poderão avaliá-la.";
  } else if(a.id == "link10") {
     text += "Sim. É necessário cadastrá-los um a um (NOME e CPF são campos obrigatórios). Caso tenha dificuldade em cadastrá-los, entre em contato conosco: faleconosco@proximaconsulta.com.br.";
  }
  Ext.get("responseArea").dom.innerHTML = text;
};


sendMessageIndexFail = function(form,action) {
  Ext.get("meuDiv").unmask();
  Ext.MessageBox.show({
    title: 'ERRO',
    msg: action.result.msg,
    width:300,
    buttons: Ext.MessageBox.OK,
    icon: Ext.MessageBox.ERROR
  });
};

