ProxCons.profissional = function(config) {
	this.config = {};
	Ext.apply(this.config,config);
	
	this.montaGrid();
    this.montaCombos();
    this.controlVideos();
	
	Ext.get("buscaAtendente").on("click",this.buscaPacienteFn,this);
    Ext.get("propagandaArea").dom.innerHTML ='<iframe  frameborder="0" style="width:450px;height:396px" src="principal/getPropagandaProfissionalSt?id='+new Date().getTime()+'"></iframe>';  
};


ProxCons.profissional.prototype = ({
  
  controlVideos: function () {
    Ext.get("video01").on("click",this.showVideo,this);
    Ext.get("video02").on("click",this.showVideo,this);
    Ext.get("video03").on("click",this.showVideo,this);
    Ext.get("video04").on("click",this.showVideo,this);
  },
  
  showVideo: function (event,element) {
    var id = element.parentNode.id;
    window.indexMain.flashObj.hide();
    
    var url = 'http://player.vimeo.com/video/26166315';
    if (id == 'video01') {
    	url = 'http://player.vimeo.com/video/26144571';
    }
    else if (id == 'video02') {
    	url = 'http://player.vimeo.com/video/26166315';
    }
    else if (id == 'video03') {
    	url = 'http://player.vimeo.com/video/26144690';
    }
    else if (id == 'video04') {
    	url = 'http://player.vimeo.com/video/26144724';
    }
    var conteudo = '<div id="media">'+
'<iframe src="' + url + '?title=0&amp;byline=0&amp;portrait=0" width="640" height="480" frameborder="0"></iframe>'
//            '<object id="csSWF" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="640" height="498" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,115,0">'+
//                '<param name="src" value="/media/videos/'+id+'/controller.swf"/>'+
//                '<param name="bgcolor" value="#1a1a1a"/>'+
//                '<param name="quality" value="best"/>'+
//                '<param name="allowScriptAccess" value="always"/>'+
//                '<param name="allowFullScreen" value="true"/>'+
//                '<param name="scale" value="showall"/>'+
//                '<param name="flashVars" value="autostart=false&thumb=FirstFrame.png&thumbscale=45&color=0x000000,0x000000"/>'+
//                '<embed name="csSWF" src="/media/videos/'+id+'/controller.swf" width="640" height="498" bgcolor="#1a1a1a" quality="best" allowScriptAccess="always" allowFullScreen="true" scale="showall" flashVars="autostart=false&thumb=FirstFrame.png&thumbscale=45&color=0x000000,0x000000" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash"></embed>'+
//            '</object>'+
        +'</div>';
        
        
    this.tempWindow =   new Ext.Window({
      autoCreate: true,
      title: "Visualizando Vídeo",
      resizable: false,
      frame: true,
      minimizable: false,
      maximizable: false,
      draggable:false,
      stateful: false,
      modal: true,
      shim: true,
      buttonAlign: "center",
      minHeight: 80,
      plain: false,
      footer: true,
      width: 650,
      closable: true,
      scope: this,
      animCollapse: true,
      items: [{xtype: 'box',
        autoEl: {
            html: conteudo
        },
        baseCls: ''
      }]
    });
        
    this.tempWindow.show();

    this.tempWindow.on("close",this.showDeafultWindow,this);
  },
  
  showDeafultWindow:function () {
    window.indexMain.flashObj.show();
  },
  
  montaCombos: function () {

	this.textNomeClinica =  new Ext.form.TextField({
	      name: 'pNomeClinica',
	      id: 'nomeClinicac',
	      allowBlank: true,
	      renderTo: 'nomeClinica',
	      width: 403,
	      fieldClass: 'form_arial_11_333',
	      scope: this
	    });
	    
    //AREA
    this.comboArea = new Ext.form.ComboBox({
      hiddenName: 'pAreaProfissionalh',
      id: 'pAreaProfissionalc',
      renderTo: 'areaArea',
      editable: false,
      listAlign: 'bl',
      fieldClass: 'form_arial_11_333',
      emptyText: 'Selecione uma Área',
      loadingText: "Loading...",
      mode: 'remote',
      width: 190,
      value: "",
      triggerAction: 'all',
      displayField: 'label',
      valueField: 'value',
      store: new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
          method: 'GET',
          url: 'extra/areaLoad'
        }),
        reader: new Ext.data.ArrayReader({}, Ext.data.Record.create([{
          name: 'label'
        }, {
          name: 'value'
        }]))
      }),
      listeners: { 'expand': function() { this.clearValue(); Ext.getCmp("pEspecialidade").store.removeAll(); Ext.getCmp("pEspecialidade").clearValue(); } }      
    });
    
    //ESPECIALIDADE
    this.comboEspecialidade  = new Ext.form.ComboBox({
  		hiddenName : 'pEspecialidadeh',
  		allQuery: tiraAcento(Ext.get('pAreaProfissionalh').dom.nextSibling.value),
  		id:'pEspecialidade',
  		emptyText: 'Selecione uma Especialidade',
  		renderTo: 'especialidadeArea',
  		editable: false,
        listAlign: 'bl',
  		fieldClass: 'form_arial_11_333',
  		loadingText: 'Loading...',
  		mode: 'remote',
  		width: 190,
        listWidth: 300,
  		value: "",
  		lazyInit : false,
  		triggerAction: 'all',
  		displayField: 'label',
  		valueField: 'value',
  		store: new Ext.data.Store({
	        proxy: new Ext.data.HttpProxy({
	          method: 'GET',
	          url: 'profissional/loadAreaEspecialidades'
	        }),
	        reader: new Ext.data.ArrayReader({}, Ext.data.Record.create([{
	          name: 'label'
	        }, {
	          name: 'value'
	        }]))
	    }),
        listeners: { 'expand': function() { this.clearValue(); } }
  	});
    
    //CONVENIOS
    this.comboConvenio = new Ext.form.ComboBox({
	    id:'conveniosList',
        hiddenName : 'conveniosListh',
		renderTo: 'convenioArea',
		editable: false,
        listAlign: 'bl',
        emptyText: 'Selecione um Convênio',
		fieldClass: 'form_arial_11_333',
		loadingText: "Loading....",
		mode: 'remote',
        width: 190,
        value: "",
		triggerAction: 'all',
		displayField: 'label',
		valueField: 'value',
		store:new Ext.data.Store({
	        sortInfo: {
	          field: 'label',
	          direction: "ASC"
	        },
			proxy: new Ext.data.HttpProxy({
				method: 'GET',
				url: 'extra/convenioLoad'
		}),
		reader: new Ext.data.ArrayReader({
			},
			Ext.data.Record.create([
				{name: 'label'},
	   			{name: 'value'}
			])
			)
		}),
		listeners: { 'expand': function() { this.clearValue(); } }
	});
    
    //Estados	
  	this.comboE = new Ext.form.ComboBox({
  		hiddenName : 'pEstadoh',
  		id:'pEstadoc',
  		baseCls: '',
  		emptyText: 'Selecione um Estado',
  		renderTo: 'estadoArea',
  		editable: false,
      listAlign: 'bl',
  		fieldClass: 'form_arial_11_333',
  		loadingText: "Loading...",
  		mode: 'remote',
  		value: '',
  		width: 190,
  		triggerAction: 'all',
  		displayField: 'label',
  		valueField: 'value',
  		store:new Ext.data.Store({
  			proxy: new Ext.data.HttpProxy({
  				method: 'GET',
  				url: 'extra/estadoLoad'
  			}),
  			reader: new Ext.data.ArrayReader({
  			},
  				Ext.data.Record.create([
  					{name: 'label'},
  	  			{name: 'value'}
  				])
  			)
  		}),
        listeners: { 'expand': function() { this.clearValue(); Ext.getCmp("pCidadec").store.removeAll(); Ext.getCmp("pCidadec").clearValue(); } }
  	});
  	
  	//Cidades
  	this.comboC = new Ext.form.ComboBox({
  		hiddenName : 'pCidadeh',
  		allQuery: this.comboE.value,
  		id:'pCidadec',
  		emptyText: 'Selecione uma Cidade',
  		renderTo: 'cidadeArea',
  		editable: false,
      listAlign: 'bl',
  		fieldClass: 'form_arial_11_333',
  		loadingText: 'Loading...',
  		mode: 'remote',
  		width: 190,
  		value: "",
  		lazyInit : false,
  		triggerAction: 'all',
  		displayField: 'label',
  		valueField: 'value',
  		store:new Ext.data.Store({
  			proxy: new Ext.data.HttpProxy({
  				method: 'POST',
  				url: 'extra/cidadeLoad'
  			}),
  			reader: new Ext.data.ArrayReader({
  			},
  				Ext.data.Record.create([
  					{name: 'label'},
     					{name: 'value'}
  				])
  			)
  		}),
        listeners: { 'expand': function() { this.clearValue(); } }
  	});
    this.comboArea.on('select',this.changedArea,this);
  	this.comboE.on('select',this.changedEstate,this);
    this.comboE.el.on("keyup",comboKeyPressed,this);
    this.comboE.on("blur",comboLostFocus,this);
  },

  changedArea: function(e) {
    Ext.get('especialidadeArea').update("");
    this.comboEspecialidade = new Ext.form.ComboBox({
  		hiddenName : 'pEspecialidadeh',
  		allQuery: tiraAcento(Ext.get('pAreaProfissionalh').dom.nextSibling.value),
  		id:'pEspecialidade',
  		emptyText: 'Selecione uma Especialidade',
  		renderTo: 'especialidadeArea',
  		editable: false,
  		listAlign: 'bl',
  		fieldClass: 'form_arial_11_333',
  		loadingText: 'Loading...',
  		mode: 'remote',
  		width: 190,
  		listWidth:300,
  		value: "",
  		lazyInit : false,
  		triggerAction: 'all',
  		displayField: 'label',
  		valueField: 'value',
  		store: new Ext.data.Store({
	        proxy: new Ext.data.HttpProxy({
	          method: 'GET',
	          url: 'profissional/loadAreaEspecialidades'
	        }),
	        reader: new Ext.data.ArrayReader({}, Ext.data.Record.create([{
	          name: 'label'
	        }, {
	          name: 'value'
	        }]))
  		}),
  		listeners: { 'expand': function() { this.clearValue(); } }
  	});
  },
  
  changedEstate: function(e) {
		Ext.get('cidadeArea').update("");
		this.comboC = new Ext.form.ComboBox({
			hiddenName : 'pCidadeh',
			allQuery: this.comboE.value,
			id:'pCidadec',
			renderTo: 'cidadeArea',
			editable: false,
      listAlign: 'bl',
			emptyText: 'Selecione uma Cidade',
			fieldClass: 'form_arial_11_333',
			loadingText: 'Loading...',
			mode: 'remote',
			width: 190,
			value: "",
			lazyInit : false,
			triggerAction: 'all',
			displayField: 'label',
			valueField: 'value',
			store:new Ext.data.Store({
				proxy: new Ext.data.HttpProxy({
					method: 'POST',
					url: 'extra/cidadeLoad'
				}),
				reader: new Ext.data.ArrayReader({
				},
					Ext.data.Record.create([
						{name: 'label'},
	   					{name: 'value'}
					])
				)
			}),
			listeners: { 'expand': function() { this.clearValue(); } }
		});
    this.comboC.el.on("keyup",comboKeyPressed,this);
    this.comboC.on("blur",comboLostFocus,this);
	},

	buscaPacienteFn: function () {
	if (!((this.comboE.value != "" && this.comboArea.value != "") || this.textNomeClinica.getValue() != "")) {
	    Ext.MessageBox.show({
	           title: 'ERRO',
	           msg: "É necessário preencher ao menos o nome, ou estado e área, para efetuar uma busca.",
	           width:320,
	           buttons: Ext.MessageBox.OK,
	           icon: Ext.MessageBox.ERROR
	    });
		return;
	}
    UpMessage.msg3('Buscando Profissionais', 'Aguarde por favor!',"popupAlertArea",2);
		this.store.load({
			params: {
				cidade: this.comboC.value,
                estado: this.comboE.value,
                area: this.comboArea.value,
                especialidade: this.comboEspecialidade.value,
                convenio: this.comboConvenio.value,
                nome : this.textNomeClinica.getValue()
			}
		});
    this.getFirstPropaganda();
	},
  
  getFirstPropaganda: function() {
    this.store.on({load:this.getFirstPropagandaLoaded,scope:this,single:true});
  },
  
  getFirstPropagandaLoaded: function() {
    if(this.store.getCount() !== 0) {
      this.clickedRowID = this.store.getAt(0).data.ID;
      new Ext.form.BasicForm('sender').submit({
        url: 'principal/getPropagandaProfissional',
        success: this.showUpPropagandaSuccess,
        scriptTag: true,
        scope: this,
        params: {id:this.clickedRowID}
      });
    } else {
      Ext.get("propagandaArea").dom.innerHTML ='<iframe  frameborder="0" style="width:450px;height:396px" src="principal/getPropagandaProfissionalSt?id='+new Date().getTime()+'"></iframe>';
      UpMessage.msg3('Nenhum profissional foi encontrado', 'Altere os dados do filtro e tente novamente.',"popupAlertArea",6);
    }
    for(var i=0;i<this.grid.getView().getRows().length;i++) {
      var prop = this.grid.getStore().getAt(i).data.PROP;
      if(prop === "true") {
          var row = this.grid.getView().getRow(i);
          if(i%2) {
            row.style.background = "#AACCFF";
          } else {
            row.style.background = "#CCDDEE";
          }
      }
    }
  },
	
	montaGrid: function () {
	
	  this.store = new Ext.data.Store({
      url: 'profissional/findProfissional',
      reader: new Ext.data.XmlReader(
        {
          record: 'Item'
        },[
          {name: 'Nome', mapping: 'ItemAttributes > Nome'},
          'Email', 'Contato', 'Atendente','ID','PROP'
        ])
    });
	    
    this.grid = new Ext.grid.GridPanel({
      store: this.store,
      columns: [
          {id:'nome',header: "Nome", width: 220, dataIndex: 'Nome',renderer: this.nameToLink , sortable: true},
          {header: "ID", width: 220, dataIndex: 'ID',sortable: false,hideable:false,hidden: true}
      ],
      renderTo:'listaDeProfissinais',
      autoExpandColumn:'nome',
      cls: 'arial_12_F87C01',
      width:460,
      stripeRows: true,
      height:165
    });
    
    this.grid.on('rowclick', this.rowClickEvent,this);
	},
  
  rowClickEvent: function(grid, rowIndex, event) {
    this.clickedRowID = grid.getStore().getAt(rowIndex).data.ID;
    new Ext.form.BasicForm('sender').submit({
      url: 'principal/getPropagandaProfissional',
      success: this.showUpPropagandaSuccess,
      failure: this.showUpPropagandaSuccess,
      scriptTag: true,
      scope: this,
      params: {id:this.clickedRowID}
    });
  },
  
  showUpPropagandaSuccess: function(form, action,c) {
    var propaganda = "";
    if(!action || !action.result || !action.result.msg  || action.result.msg === "null" || !action.result.success ) {
      propaganda = "<table height='100%' width='100%'>" +
        "<tr valign='middle'>" +
          "<td align='center' class='arial_12_333'>" +
            "Esse profissional n&atilde;o tem nenhuma propaganda cadastrada!" +
          "</td>" +
        "</tr>" +
      "</table>"; 
      //UpMessage.msg3('Esse profissional nao tem propaganda!', '',"popupAlertArea",3);
      Ext.get("propagandaArea").dom.innerHTML = propaganda;
    } else {
      propaganda = action.result.msg;
      //Ext.get("propagandaArea").dom.innerHTML ='<iframe  frameborder="0" style="width:450px;height:396px" src="principal/getPropagandaProfissionalSt?id='+action.options.params.id+'"></iframe>';
      Ext.get("propagandaArea").dom.innerHTML = decode(propaganda);
    }
    
  },
	
	nameToLink: function(value,grid,row) {
	    if(row.data.PROP === "true") {
	      return value;
	    } else {
	      return value;
	    }
	}

});

