﻿/*
	Site: Imedex.com
	Author: MD Brewer
	Last modified: 02 Feb 2010
*/
Ext.ns('Application');
Ext.onReady(function(){
    // turn on validation errors beside the field globally
	Ext.QuickTips.init();
	Ext.form.Field.prototype.msgTarget = 'side';
	
	//link triggers for grid
	var linkMeetings = Ext.get('link-meetings');
	var linkRegister = Ext.get('link-register');
	var linkAbstracts = Ext.get('link-abstracts');
	var activeMenu;
	var DateToday = new Date();
	var strCopyright = '&copy; 1986 - '+DateToday.getFullYear()+' Imedex<sup>&reg;</sup>, LLC. All rights reserved. <a href="/appweb/about/terms.asp" title="Terms & Conditions">Terms &amp Conditions</a>.';
    
    var DescriptionExpander = new Ext.grid.RowExpander({
		tpl:new Ext.Template('<p><br /><b>Summary:</b><br />{ProjectDescription}</p>')
    });
    
    var dsJsonProjectsLive = new Ext.data.JsonStore({
		autoLoad:true,			
		url:'/appjson/jsnProjectsLive.asp',
		root:'Records',
		fields:[{name:'ProjectID'},
        {name:'ProjectName'},
        {name:'ProjectDescription'},
        {name:'ProjectTypeID'},
        {name:'ProjectType'},
        {name:'ProjectFocusID'},
        {name:'ProjectFocus'},
        {name:'SpecialtyCode'},
        {name:'SpecialtyName'},
        {name:'CountryCode'},
        {name:'Country'},
        {name:'location'},
        {name:'UrlAnnounce'},
        {name:'DateStart', type:'date'},
        {name:'DateEnd', type:'date'}] 
		//,sortInfo:{field:'DateEnd', direction:'DESC'}
	});
	
	var dsJsonProjectsArchive = new Ext.data.JsonStore({
		autoLoad:true,			
		url:'/appjson/jsnProjectsArchive.asp',
		root:'Records',
		fields:[{name:'ProjectID'},
        {name:'ProjectName'},
        {name:'ProjectDescription'},
        {name:'ProjectTypeID'},
        {name:'ProjectType'},
        {name:'ProjectFocusID'},
        {name:'ProjectFocus'},
        {name:'SpecialtyCode'},
        {name:'SpecialtyName'},
        {name:'CountryCode'},
        {name:'Country'},
        {name:'location'},
        {name:'UrlAnnounce'},
        {name:'DateStart', type:'date'},
        {name:'DateEnd', type:'date'}] 
		//,sortInfo:{field:'DateEnd', direction:'DESC'}
	});
	
	var dsJsonProjectsLiveSpecialtyList = new Ext.data.JsonStore({
		autoLoad:true,			
		url:'/appjson/jsnProjectsLiveSpecialtyList.asp',
		root:'Records',
		fields:[{name:'SpecialtyCode'},
        {name:'SpecialtyName'}], 
		sortInfo:{field:'SpecialtyName', direction:'ASC'}
	});
	
	var dsJsonProjectsLiveCountryList = new Ext.data.JsonStore({
		autoLoad:true,			
		url:'/appjson/jsnProjectsLiveCountryList.asp',
		root:'Records',
		fields:[{name:'CountryCode'},
        {name:'Country'}], 
		sortInfo:{field:'Country', direction:'ASC'}
	});
	
	/* DEPRECATED: 18 Jun 2008 MDB
	var dsJsonProjectsLiveType = new Ext.data.JsonStore({
		autoLoad:true,			
		url:'/appjson/jsnProjectsLiveType.asp',
		root:'Records',
		fields:[{name:'ProjectTypeID'},
        {name:'ProjectType'},], 
		sortInfo:{field:'ProjectType', direction:'ASC'}
	});
    */
    
    var dsJsonProjectsLiveFocus = new Ext.data.JsonStore({
		autoLoad:true,			
		url:'/appjson/jsnProjectsLiveFocus.asp',
		root:'Records',
		fields:[{name:'ProjectFocusID'},
        {name:'ProjectFocus'}], 
		sortInfo:{field:'ProjectFocus', direction:'ASC'}
	});

	if(Ext.get('search-grid')){
	    var gridProjectsLive = new Ext.grid.GridPanel({
            store:dsJsonProjectsLive,
            //TODO: Add image to each result row
            cm:new Ext.grid.ColumnModel([
			    DescriptionExpander,
	            {header:'Name',width:360, sortable:true, renderer:renderLiveProjectLink, dataIndex:'ProjectName'},
	            //{header:'Topic',width:120, sortable:true, dataIndex:'ProjectFocus'},
	            {header:'Location',width:150, sortable:true, dataIndex:'location'},
	            {header:'Start',width:90, sortable:true, renderer:Ext.util.Format.dateRenderer('M-d-Y'), dataIndex:'DateStart'},
	            {header:'End',width:90, sortable:true, renderer:Ext.util.Format.dateRenderer('M-d-Y'), dataIndex:'DateEnd'}
            ]),
            viewConfig:{forceFit:true,
	            enableRowBody:true,
	            emptyText:'<h4>No Live Meetings Available</h4>'
					    +'<p>There are currently no live meetings available that match the search criteria.</p>'
            },
            loadMask:true,
            trackMouseOver:false,
            sm:new Ext.grid.RowSelectionModel({selectRow:Ext.emptyFn}),
            width:690,
		    height:700,
		    frame:true,
            autoRowHeight:true,
            autoScroll:true,
            stripeRows:true,
            plugins:DescriptionExpander,
            //TODO: show the totalRecords in the title 'Available Courses (totalRecords)'
            //OR implement something similar to the footer of the paging grid example
            title:'Upcoming Meetings',
            /*tools:[{
			    id:'close',
			    qtip:'Hide',
			    handler: function(e, target, panel){
				    toggleGrid('search-grid','hide');
			    }
		    }],*/
            iconCls:'icon-grid',
		    renderTo:'search-grid'
        });
    }
    
    if(Ext.get('grid-meetings-archive')){
	    var gridProjectsArchive = new Ext.grid.GridPanel({
            store:dsJsonProjectsArchive,
            //TODO: Add image to each result row
            cm:new Ext.grid.ColumnModel([
			    DescriptionExpander,
	            {header:'Name',width:360, sortable:true, renderer:renderLiveProjectLink, dataIndex:'ProjectName'},
	            //{header:'Topic',width:120, sortable:true, dataIndex:'ProjectFocus'},
	            {header:'Location',width:150, sortable:true, dataIndex:'location'},
	            {header:'Start',width:90, sortable:true, renderer:Ext.util.Format.dateRenderer('M-d-Y'), dataIndex:'DateStart'},
	            {header:'End',width:90, sortable:true, renderer:Ext.util.Format.dateRenderer('M-d-Y'), dataIndex:'DateEnd'}
            ]),
            viewConfig:{forceFit:true,
	            enableRowBody:true,
	            emptyText:'<h4>No Recent Live Meetings Archived</h4>'
					    +'<p>There are currently no recent live meetings archived that match the search criteria.</p>'
            },
            loadMask:true,
            trackMouseOver:false,
            sm:new Ext.grid.RowSelectionModel({selectRow:Ext.emptyFn}),
            width:690,
		    height:700,
		    frame:true,
            autoRowHeight:true,
            autoScroll:true,
            stripeRows:true,
            plugins:DescriptionExpander,
            //TODO: show the totalRecords in the title 'Available Courses (totalRecords)'
            //OR implement something similar to the footer of the paging grid example
            title:'Past Meetings',
            /*tools:[{
			    id:'close',
			    qtip:'Hide',
			    handler: function(e, target, panel){
				    toggleGrid('search-grid','hide');
			    }
		    }],*/
            iconCls:'icon-grid',
		    renderTo:'grid-meetings-archive'
        });
    }
    
    if(Ext.get('form-search')){
        var formSearch = new Ext.FormPanel({
		    renderTo:'form-search',
		    border:false,
		    labelAlign:'top',
		    labelWidth:65,
		    width:160,
		    buttonAlign:'right',
		    items:[
			    /*new Ext.form.ComboBox({
				    fieldLabel:'Format',
				    id:'ProjectType',
				    store: dsJsonProjectsLiveType,
				    valueField:'ProjectTypeID',
				    displayField:'ProjectType',
				    mode:'local',
				    typeAhead:true,
				    triggerAction:'all',
				    selectOnFocus:true,
				    forceSelection:true,
				    width:160
			    })*/
			    new Ext.form.ComboBox({
				    fieldLabel:'Topic',
				    id:'ProjectFocus',
				    store: dsJsonProjectsLiveFocus,
				    valueField:'ProjectFocusID',
				    displayField:'ProjectFocus',
				    mode:'local',
				    typeAhead:true,
				    triggerAction:'all',
				    selectOnFocus:true,
				    //forceSelection:true,
				    //valueNotFoundText:'Selection invalid.',
				    width:160
			    })
			    ,new Ext.form.ComboBox({
				    fieldLabel:'Country',
				    id:'ProjectCountry',
				    store: dsJsonProjectsLiveCountryList,
				    valueField:'CountryCode',
				    displayField:'Country',
				    mode:'local',
				    typeAhead:true,
				    triggerAction:'all',
				    selectOnFocus:true,
				    //forceSelection:true,
				    //valueNotFoundText:'Selection invalid.',
				    width:160
			    })
			    /*,new Ext.form.DateField({
				    id:'DateStart',
				    fieldLabel:'Start Date',
				    //name:'datestart',
				    minValue:DateToday,
				    width:160
			    }),
			    new Ext.form.DateField({
				    id:'DateEnd',
				    fieldLabel:'End Date',
				    //name:'dateend',
				    minValue:DateToday,
				    width:160
			    })*/
		    ],
		    buttons: [{
			    text: 'Search',
			    formBind:true,
			    /*disabled:true,*/
			    handler:function(){
				    //check for filtering
				    //dsJsonProjectsLive.filter('ProjectTypeID','43');
				    //*NOTE: EXTJS keeps the value of the combo even if it is nothing
				    //**Resetting the form gets around this bug.
				    //dsJsonProjectsLive.clearFilter();
				    dsJsonProjectsLive.filterBy(filterGrid); 
				    formSearch.getForm().reset();
				    toggleGrid('search-grid','show');
			    }
		    }]
	    });
	}
	
	function toggleGrid (sObj,sState) {
		if(sState=='show'){
			gridProjectsLive.show();
			document.getElementById(sObj).className='';
		} else{
			gridProjectsLive.hide();
			document.getElementById(sObj).className='x-hide-offsets';			
		}
		return null;
	}
    
	function filterGrid(record){
		var bFlag=true;
		//var fProjectType=formSearch.findById('ProjectType').getValue();
		var fProjectFocus=formSearch.findById('ProjectFocus').getValue();
		var fProjectCountry=formSearch.findById('ProjectCountry').getValue();
		//var fProjectDateStart=formSearch.findById('DateStart').getValue();
		//var fProjectDateEnd=formSearch.findById('DateEnd').getValue();
        //if(fProjectCountry.length===0&&fProjectFocus.length===0){
		    //alert('Completed empty search');
		    //dsJsonProjectsLive.clearFilter();return true;
		//}
		
		//check date
		/*if (fProjectDateStart < DateToday)
			fProjectDateStart = DateToday;
		if (fProjectDateEnd < DateToday)
			fProjectDateEnd = DateToday+365;
		*/
		//alert(fProjectDateStart+' '+fProjectDateEnd+' '+record.data.DateStart+' '+record.data.DateEnd);	
				
		/*if (fProjectDateStart.length>0){			
			if (record.data.DateEnd>=DateToday && (record.data.DateEnd>=fProjectDateStart && record.data.DateStart<=fProjectDateEnd))
				bFlag=(bFlag&&true);
			else
				bFlag=(bFlag&&false);
		}
		/*if (fProjectDateEnd.length>0){
			if (fProjectDateEnd < DateToday)
				fProjectDateEnd = DateToday;
			if (record.data.DateStart<=fProjectDateEnd)
				bFlag=(bFlag&&true);
			else
				bFlag=(bFlag&&false);
		}*/		
		/*if (fProjectType.length>0){
			if (record.data.ProjectTypeID==fProjectType)
				bFlag=(bFlag && true);
			else
				bFlag=(bFlag&&false);
		}*/
		if(fProjectCountry.length>0){
		    if (record.data.CountryCode===fProjectCountry)
				bFlag=(bFlag&&true);
			else
				bFlag=(bFlag&&false);
		}
		if (fProjectFocus.length>0){
			if (record.data.ProjectFocusID===fProjectFocus)
				bFlag=(bFlag&&true);
			else
				bFlag=(bFlag&&false);
		}
		return bFlag;
	}

    function renderLiveProjectLink(value, obj, record, rowIndex, colIndex, ds){
		return '<a href="'+record.data.UrlAnnounce+'">'+record.get('ProjectName')+'</a>';
	}
	
	if(linkMeetings){
	    linkMeetings.on('click',function(){
		    //dsJsonProjectsLive.clearFilter();
		    toggleGrid('search-grid','show');
	    });
	}
	if(linkRegister){
	    linkRegister.on('click',function(){
		    //dsJsonProjectsLive.clearFilter();
		    toggleGrid('search-grid','show');
	    });
	}
	if(linkAbstracts){
	    linkAbstracts.on('click',function(){
		    //dsJsonProjectsLive.clearFilter();
		    toggleGrid('search-grid','show');
	    });
	}
	
    /* MENU INFORMATION */
    function createMenu(name){
	    //var el = Ext.get('link-'+name);
	    var el = Ext.get(name);
	    var tid = 0, menu, doc = Ext.getDoc();
		
	    var handleOver = function(e, t){
		    if(t != el.dom && t != menu.dom && !e.within(el) && !e.within(menu)){
			    hideMenu();
		    }	
	    };
				
	    var hideMenu = function(){
		    if(menu){
			    menu.hide();
			    el.setStyle('text-decoration', '');
			    doc.un('mouseover', handleOver);
			    doc.un('mousedown', handleDown);
		    }
	    }
		
	    var handleDown = function(e){
		    if(!e.within(menu)){
			    hideMenu();
		    }
	    }
		
	    var showMenu = function(){
		    clearTimeout(tid);
		    tid = 0;
			
		    if (!menu) {
			    menu = new Ext.Layer({shadow:'sides',hideMode: 'display'}, name+'-menu');
		    }
		    menu.hideMenu = hideMenu;
				
		    menu.el = el;
		    if(activeMenu && menu != activeMenu){
			    activeMenu.hideMenu();
		    }
		    activeMenu = menu;
			
		    if (!menu.isVisible()) {
			    menu.show();
			    menu.alignTo(el, 'tl-bl?');
			    menu.sync();
			    el.setStyle('text-decoration', 'underline');
				
			    doc.on('mouseover', handleOver, null, {buffer:150});
			    doc.on('mousedown', handleDown);
		    }
	    }
		
	    el.on('mouseover', function(e){
		    if(!tid){
			    tid = showMenu.defer(150);				
		    }
	    });
		
	    el.on('mouseout', function(e){
		    if(tid && !e.within(el, true)){
			    clearTimeout(tid);
			    tid = 0;				
		    }
	    });
    }
	
    if(Ext.get('link-elearn')){
        createMenu('link-elearn');
    }
    if(Ext.get('link-meetings')){
        createMenu('link-meetings');
    }
    if(Ext.get('link-login')){
    	createMenu('link-login');
    }
    
    var elLoading = Ext.get('loading');
    if (elLoading){
        setTimeout(function(){
        Ext.get('loading').remove();
        Ext.get('loading-mask').fadeOut({remove:true});
    }, 400);}
    
    var elCopyright = Ext.get('copyright');
    if (elCopyright){
        document.getElementById('copyright').innerHTML=strCopyright;
    }
    
    /* ACCOUNT FORMS */
    /*if(Ext.get('form-remind')){
		var formRemind = new Ext.FormPanel({
			labelWidth:80, // label settings here cascade unless overridden
			bodyStyle:'padding:5px 5px 0',
			width:350,
			defaults: {width: 170},
			defaultType:'textfield',
			id:'frmRemind',
			//url:'jsnChangePassword.asp', //handling in action object
			frame:true,
			buttonAlign:'left',
			renderTo:'form-remind',
			monitorValid:true,
			items: [{
				fieldLabel:'Email',
				id:'email_frmRemind',
				allowBlank:false,
				validator:function(){
					var sValue = Ext.getCmp('email_frmRemind').getValue();
					if (!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,6})+$/.test(sValue))
						return 'Enter a valid email address.';
					else
						return true;
				}
			},{
				id:'FormAction',
				inputType:'hidden',
				value:'remind'
			}],
			buttons: [{
				text:'Send Reminder',
				formBind:true,
				disabled:true,
				handler:function(){
					formRemind.getForm().submit({ 
						clientValidation:false,
						method:'POST', 
						success:function(form, action){ 
								var obj = Ext.decode(action.response.responseText); 
								Ext.Msg.alert('Success!',obj.ResponseMessage);
								formRemind.getForm().reset();
						}, 
						failure:function(form, action){ 
								obj = Ext.util.JSON.decode(action.response.responseText); 
								Ext.Msg.alert('Request Failed!',obj.ResponseMessage);
								formRemind.getForm().reset();
						},
						url:'/appjson/jsnLoginMailReminder.asp',
						waitTitle:'Locating', 
						waitMsg:'Finding requested account...'
					});
			//}
			},{
				text: 'Cancel',
				handler:function(){Ext.Msg.alert('Clicked','Cancel was clicked.');}
			}]
		});
	}
	if(Ext.get('form-login')){
	//if(Ext.get('link-account')){
		var panelLoginRemind = new Ext.Panel({
			id:'pnlLoginRemind',
			html:'<a id="linkReminder" href="http://www.imedex.com/appweb/myaccountreminder.asp">Forgot your password?</a>'
			//href="http://www.imedex.com/appweb/test-panel.html"
		});
		var formLogin = new Ext.FormPanel({
			labelWidth:80, // label settings here cascade unless overridden
			bodyStyle:'padding:5px 5px 0',
			width:350,
			defaults: {width: 170},
			defaultType:'textfield',
			id:'frmLogin',
			//url:'jsnChangePassword.asp', //handling in action object
			frame:true,
			buttonAlign:'right',
			monitorValid:true, //handling in window show and hide
			renderTo:'form-login',
			items: [{
				fieldLabel:'Email',
				id:'email',
				allowBlank:false,
				validator:function(){
					var sValue = Ext.getCmp('email').getValue();
					if (!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,6})+$/.test(sValue))
						return 'Enter a valid email address.';
					else
						return true;
				}
			},{
				fieldLabel:'Password',
				id:'password',
				inputType:'password',
				allowBlank:false,
				minLength:6,
				validator:function(){
					var sValue = Ext.getCmp('password').getValue();
					if (sValue < 6 || !/\d+/.test(sValue) || !/[A-Z]+/.test(sValue))
						return 'Password requirements are: min 6 chars, 1 capital letter, 1 number.';
					else
						return true;
				}
			},{
				id:'LoginAction',
				inputType:'hidden',
				value:'login'
			},panelLoginRemind
			]			
			/*],
			buttons: [{
				text: 'Login',
				formBind:true,
				disabled:true,
				handler:function(){
					formLogin.getForm().submit({ 
						clientValidation:false,
						method:'POST', 
						success:function(form, action){ 
								var obj = Ext.decode(action.response.responseText); 
								Ext.Msg.alert('Success!',obj.ResponseMessage,function(){
									formLogin.getForm().reset();
									//redirect the user
									window.location = 'http://www.imedex.com/appweb/about/myaccount.asp';
								});
						}, 
						failure:function(form, action){ 
								obj = Ext.util.JSON.decode(action.response.responseText); 
								Ext.Msg.alert('Login Failed!',obj.ResponseMessage,function(){Ext.getCmp('password').setValue('');Ext.getCmp('password').focus();});
						},
						url:'/appjson/jsnLogin.asp',
						waitTitle:'Connecting', 
						waitMsg:'Logging in...'
					});
				}
			}]*/
		/*});
		formLogin.addButton('Load', function(){
			Ext.Msg.alert('Loaded','The button is there.');
		});*/
		/*var winLogin = new Ext.Window({
			title:'Imedex Account Login',
			layout:'fit',
			width:320,
			height:160,
			closeAction:'hide',
			plain:true,
			modal:true,
			items: [formLogin]
		});
		winLogin.on('hide', function(){
			//reset form when hiding
			formLogin.stopMonitoring();
			formLogin.getForm().reset();
		});
		Ext.get('link-account').on('click',function(){
			formLogin.startMonitoring();
			winLogin.show(this);
		});*/
	//}
});