//
//		 PAFAppResources: Initialize client side of Portlet Application Framework
//

Portal.Portlet.PAFAppResources = Portal.Portlet.extend({

   // Init function.
   // init() called when page loads. Required for all portlet JS objects.
   //
   init: function(path, name, notifier) {
      var oThis = this;  // Use <oThis> instead of <this> for registering callbacks
      this.base(path, name, notifier);  // Call superclass constructor

      // Initialize client side of portal application framework
      // Make forms post to current URL ins
      // FIXME: We need to include query string here, too, I think...
      
      document.forms[0].action = window.location.pathname;

      

      
   }
});

//
//		 myncbiAppResources: Describe portlet here
//

//		 Notes:
//		   - text commented as // are instructions and hints to the programmer
//		   - replace text commented as /* */ with your code
//		   - please retain uncommented code

Portal.Portlet.myncbiAppResources = Portal.Portlet.PAFAppResources.extend({

   // Init function.
   // init() called when page loads. Required for all portlet JS objects.
   //
   init: function(path, name, notifier) {
      var oThis = this;  // Use <oThis> instead of <this> for registering callbacks
      this.base(path, name, notifier);  // Call superclass constructor
      
      
      if( $('myncbiusername') )
      {
      	 document.forms[0].action = window.location.pathname;
      	 //console.info("Changed form action from to " + window.location.pathname + " from site-wide Javascript" );
      }
      else
      {
      	 document.forms[0].action = 'https://' + window.location.host + '/portal/signin.cgi?js';
      }
      
   }
});
      
Portal.Portlet.MyNCBI_SavedSearches_Portlet = Portal.Portlet.extend({
		   init: function(path, name, notifier) {
		      var oThis = this;  // Use <oThis> instead of <this> for registering callbacks
		      this.base(path, name, notifier);  // Call superclass constructor
		      
		      
		      if( this.getInputs('schedule') ){
		          var schedule = this.getInputs('schedule');
		      }
		      var val = '';
		      if(schedule){
    		      for( var i = 0; i < schedule.length; i++)
    		      {
    		      	if( schedule[i].checked == true ) { val = schedule[i].value; }
    		      }
    		      if( val == 'no')
    		      {
    		      	 this.disable();
    		      }
		      }
		      
		      
		      
		      //Ajax requests for search backend.
		      try
        	      { 
            	      //check to see the json object was created in the page, if so, we're making a request.
            	      if( typeof requests != 'undefined')
            	      { 
            	          //for the elements in the JSON, get the needed info
                          for ( id in requests.searches )
                          {
                             var oThis = this; 
                             var site = document.forms[0]['p$st'].value;  
                             var args = {
                                 'cmd' : 'getsearchresponse',
                                 'Db' : requests.Db,
                                 'HistoryId' : requests.HistoryId,
                                 'id' : id,
                                 'term' : requests.searches[id].term,
                                 'LastRun' : requests.searches[id].LastRun,
                                 'Field' : requests.searches[id].Field,
                                 'Condition' : requests.searches[id].Condition,
                                 'LimitsString' : requests.searches[id].Limits,
                                 'LimitsMsgString' : requests.searches[id].LimitMsg
                             }
                             
                             //make the request, sending Portal what it needs to call the "XmlHttpHandler" action and return
                             //the outputs based on output-set (which yields a JSON object)
                             var resp = xmlHttpCall(site, this.path, "XmlHttpHandler", args, this.receive, {}, this); 
                          }
            	      } 
        	      }
		      catch(err)
                  {
                
                  }
		      
		      
		      
try{		      
    Ext.namespace('Ext.Ncbi');
	
	Ext.Ncbi.parseJSON = function(str) {
        try { 
            var oConfig = eval('({' + str + '})');
        }
        catch (err) {
            if (window.console) console.error(err.name + ' in JSON Config Object');
        }
        return oConfig;
    }

	
			
    if (Ext.grid.GridPanel) { // don't extend grid if GridPanel isn't loaded (ext-big.js isn't included)
    
        Ext.grid.TableGrid = function(table, config) {
            config = config || {};
            Ext.apply(this, config);
            var cf = config.fields || [], ch = config.columns || [];
            table = Ext.get(table);
            
            var ct = table.insertSibling();
            
            var fields = [], cols = [];
            var headers = table.query("thead th");
            if (headers.length < 1) throw new Error('No properly marked up table headers. Make sure to use thead and th elements properly');
            for (var i = 0, h; h = headers[i]; i++) {
                var text = h.innerHTML;
                var name = 'tcol-'+i;
                // need to fix this up to get date formatted properly
                
                // deal with each columns config settings 
                var sortable = true;
                var hideable = true;
                var colConfig = {}; // the config object on widget
                
                // these are deprectaed html attributes
                var deprecatedSortAttr = h.getAttribute('tgrd-sortable');
                var deprecatedHideAttr = h.getAttribute('tgrd-hideable');
                var deprecatedTypeAttr = h.getAttribute('tgrd-type');
                colConfigStr = h.getAttribute('config');
    
    
                if (colConfigStr) {
                    colConfig = Ext.Ncbi.parseJSON(colConfigStr);
                    if (colConfig.sortable === undefined){
                        colConfig.sortable = true; // default
                    } else {
                        sortable = colConfig.sortable;
                    }
                    if (colConfig.hideable == undefined) {
                        colConfig.hideable = true; // default
                    } else {
                         hideable = colConfig.hideable;
                    }
                } 
                else if (deprecatedSortAttr){
                    if (window.console) console.warn('Using a deprecated attribute on a heading. Use "config" attribute instead');
                    if (deprecatedSortAttr.toLowerCase() == 'false') {
                        sortable = false;
                    } else {
                        sortable = true;
                    }
                }
                if (deprecatedHideAttr) {
                    if (window.console) console.warn('Using a deprecated attribute on a heading. Use "config" attribute instead');
                    if (deprecatedHideAttr.toLowerCase() == 'false') {
                        hideable = false;
                    } else {
                        hideable = true;
                    }
                }
         
                //var typeValue = h.getAttribute('tgrd-type');
                var typeValue = null;
                if (deprecatedTypeAttr){
                    typeValue = deprecatedTypeAttr;
                }
                else if(colConfig && colConfig.type) {
                    typeValue = colConfig.type;
                }
    
            function sortmyDate(mydate){
             var date = mydate.match(/^<.*>(.*)<\/(SPAN|span)>/)[1];
             var result;
                if( date === 'yesterday' ) {
                    result = 0;
                } else if( date === 'never') {
                    result = -2;
                } else if( date === 'today') { 
                    result = -1;
                } else if( /days ago/.test(date) ) {
                    result = parseInt( date, 10);
                } else if( date === 'last month')  {
                    result = 50;
                } else if( /months ago/.test(date) ) {
                    result = (parseInt( date, 10 ) + 50)
                } else if( date === 'last year') {
                    result = 100;
                } else if( /years ago/.test(date) ) {
                    result = (parseInt( date, 10 ) + 100);
                }    
                //console.info( date + ' ' + result);
                return result;
            }
            
            function sortmyTitle( x ){
                var y = x.match(/^<.*>(.*)<\/(?:A|a)>(?:\(|\s)/)[1];
                var result;
                result = y.toLowerCase();
                //console.info( y + ' -- ' + result);
                return result;
            }
            
            function sortmySchedule( x ){
                var result;
                if( x === 'none') {
                    result = 0;
                } else if ( x === 'daily') {
                    result = 1;
                } else if ( x === 'weekly') {
                    result = 2;
                } else if ( x === 'monthly') {
                    result = 3;
                }
                return result;
            }

            var fieldObj;
            
            if(i == 2)
            {
                fieldObj = {
                    name: name,
                    mapping: 'td:nth('+(i+1)+')/@innerHTML',
                    sortType : sortmyDate
                }; 
            }
            else if ( i == 3 )
            {
                fieldObj = {
                    name: name,
                    mapping: 'td:nth('+(i+1)+')/@innerHTML',
                    sortType : sortmySchedule
                };
            }
            else if ( i == 1 )
            {
                fieldObj = {
                    name: name,
                    mapping: 'td:nth('+(i+1)+')/@innerHTML',
                    sortType : sortmyTitle
                };
            }
            else
            {
                fieldObj = {
                    name: name,
                    mapping: 'td:nth('+(i+1)+')/@innerHTML'
                }; 
            }
                
                switch (typeValue) {
                    case 'float':
                        fieldObj.type = 'float';
                        break;
                        
                    case 'int':
                        fieldObj.type = 'int';
                        break;
                        
                    //Need to get this working 
                    case 'shortDate':
                        fieldObj.type = 'date';
                        fieldObj.dateFormat = 'm/d/Y';
                        break;
                        
                    default:
                        fieldObj.type = 'string';
                }
    
                fields.push(Ext.applyIf(cf[i] || {}, fieldObj));
                
                function change(val){
                    alert('called');
                    if(val > 0){
                        return '<span style="color:green;">' + val + '</span>';
                    }else if(val < 0){
                        return '<span style="color:red;">' + val + '</span>';
                    }
                    return val;
                }
                 var rendererValue; // how the column data is displayed
                 var deprecatedFormatAttr = h.getAttribute('tgrd-format');
                 if (deprecatedFormatAttr && deprecatedFormatAttr == 'usMoney') {
                    if (window.console) console.warn('Using a deprecated attribute on a heading. Use "config" attribute instead');
                    rendererValue = deprecatedFormatAttr; 
                 }
                 else if (colConfig && colConfig.renderer) {
                    rendererValue = colConfig.renderer;
                 }
                 /* need to get this working at some point else if (typeValue == 'shortDate') {
                    rendererValue = Ext.util.Format.dateRenderer('m/d/Y'); 
                 }
                 */
                 else {
                    rendererValue = null;
                 }
                cols.push(Ext.applyIf(ch[i] || {}, {
                  'header': text,
                  'dataIndex': name,
                  'renderer': rendererValue,
                  'width': h.offsetWidth,
                  'tooltip': h.title,
                  'sortable': sortable,
                  'hideable': hideable
                }));
            }
            var ds  = new Ext.data.Store({
            reader: new Ext.data.XmlReader({
              record:'tbody tr'
            }, fields)
            });
            
            ds.loadData(table.dom);
            
            var cm = new Ext.grid.ColumnModel(cols);
            
            if (config.width || config.height) {
            ct.setSize(config.width || 'auto', config.height || 'auto');
            } else {
            ct.setWidth(table.getWidth());
            }
            
            if (config.remove !== false) {
            table.remove();
            }
            
            Ext.applyIf(this, {
            'ds': ds,
            'cm': cm,
            'sm': new Ext.grid.RowSelectionModel(),
            autoHeight: true,
            autoWidth: false
            });
            Ext.grid.TableGrid.superclass.constructor.call(this, ct, {});
        };
            
       Ext.extend(Ext.grid.TableGrid, Ext.grid.GridPanel);
    }
			
}
catch(err)
{
console.warn(err);
}			
			
			
			
			
			
			
			
	var t = $C('tgrd', 'class', $('content'), 'table');
	for(i=0;i<t.length;i++){
		t[i].style.width = '664px'; 
		var x = new Ext.grid.TableGrid(t[i], { // se extensions section at top of ext.ncbi.js
           enableHdMenu: false
        });
	}	
		      
		      
		      
		      
		      
		      
		      
		   },

		   send: { },

		   listen: {
		   
		   
		   "delete<click>":function(e,target,name){
		   
		       var myvalue = target.getAttributeNode('value').nodeValue;
		   
		   		var _alert = function(){
		   			var z = document.createElement('div');
					z.className = 'alert';
					z.setAttribute('id', (myvalue + '_alert') );
					z.innerHTML = "You haven't selected anything to delete!";
					if( $(myvalue + '_alert') == null ){
					    if( target.nextSibling )
					    { 
					    target.parentNode.insertBefore( z, target.nextSibling.nextSibling );
					    }
					    else 
					    {
					    target.parentNode.insertBefore( z, target.nextSibling );
					    }
					}
		   		};
		   
		   		var x = this.getValue( myvalue ); 
		   		if( utils.isArray( x ) )
		   		{
		   			var y;
		   			for(var i=0; i<x.length; i++)
		   			{
		   				if( $(x[i]).checked == true ) { y = true; }
		   			}
		   			if( y == true ) { 
		   			    if( confirm("Are you sure you want to delete these searches?") ){
    		   			    this.setValue('Db', myvalue );
        		   			this.setValue('cmd', 'delete' );	    
    		   			    document.forms[0].submit(); 
		   			    }
		   			}
		   			else { _alert(); }
		   		}
		   		else //it is a string 
		   		{
		   			if( $(x).checked ) { 
		   			    if( confirm("Are you sure you want to delete this search?") ){
        		   			this.setValue('Db', myvalue ); 
        		   			this.setValue('cmd', 'delete' );
        		   			document.forms[0].submit(); 
        		   		}
		   			}
		   			else { _alert(); }
		   		}
		   },
		   
		   
		   'whatsnew<click>':function(e,target,name){
		   
		       var myvalue = target.getAttributeNode('value').nodeValue;
		   
		   		var _alert = function(){
		   			var z = document.createElement('div');
					z.className = 'alert';
					z.setAttribute('id', (myvalue + '_alert') );
					z.innerHTML = "Please choose a search to show what's new.";
					if( $(myvalue + '_alert') == null ){
						target.parentNode.insertBefore( z, target.nextSibling );
					}
		   		};
		   
		   		var x = this.getValue( myvalue ); 
		   		if( utils.isArray( x ) )
		   		{
		   			var y;
		   			for(var i=0; i<x.length; i++)
		   			{
		   				if( $(x[i]).checked == true ) { y = true; }
		   			}
		   			if( y == true ) { 
    		   			this.setValue('Db', myvalue ); 
    		   			this.setValue('cmd', 'whatsnew2' );
    		   			document.forms[0].submit(); 
		   			}
		   			else { _alert(); }
		   		}
		   		else //it is a string 
		   		{
		   			if( $(x).checked ) { 
    		   			this.setValue('Db', myvalue ); 
    		   			this.setValue('cmd', 'whatsnew2' );
    		   			document.forms[0].submit(); 
		   			}
		   			else { _alert(); }
		   		}
		   
		   },
		   
		   'whatsnew<blur>':function(e,target,name){
		       var myvalue = target.getAttributeNode('value').nodeValue;
		       if( $(myvalue + '_alert') ){
    	           target.parentNode.removeChild( $(myvalue + '_alert') );
    	       }
		   },
		   
		   'delete<blur>':function(e,target,name){
		       var myvalue = target.getAttributeNode('value').nodeValue;
		       if( $(myvalue + '_alert') ){
    	           target.parentNode.removeChild( $(myvalue + '_alert') );
    	       }
		   },
		   
		   
		   'displaynewitems<click>':function(e,target,name){
		       this.setValue('position', target.className);
		       Portal.requestSubmit();
		   },
		   
	   		'selectall<click>':function(e,target,name){
    		    var all = this.getInputs(target.value);
    		    for(var i=0; i<all.length; i++){
    		        all[i].checked = target.checked;
    		    }
    		},
		   
		   "schedule<click>":function(e,target,name){
		   		if(target.value != 'no')
		   		{
		   			this.enable();
		   		} else {
		   			this.disable();
		   		}
		   },
		   
		   "Close<click>":function(e,target,name){
		   		window.close();
		   },
		   
		   "unsubscribe-cancel<click>" : function(e,target,name){
		       $('cmd').value = "unsubscribe-cancel";
		       document.forms[0].submit();
		   },
		   
		   "unsubscribe<click>" : function(e,target,name){
		       $('cmd').value = "unsubscribe";
		       document.forms[0].submit();
		   }

		   },

			'disabled' : ['monthlyday','weeklyday','emailformat','reportformat','resultmax','sendzero','addtext'],

			'disable': function()
			{
				for( var i=0; i<this.disabled.length; i++)
				{
					this.getInput( this.disabled[i] ).disabled = true;
					if( this.disabled[i] == 'emailformat' )  //email format has 2 radio buttons!
					{ 
						this.getInputs( 'emailformat' )[0].disabled = true;
						this.getInputs( 'emailformat' )[1].disabled = true;
					}
				}
			},
			
			'enable':function()
			{
				for( var i=0; i<this.disabled.length; i++)
				{
					this.getInput( this.disabled[i] ).disabled = false;
					if( this.disabled[i] == 'emailformat' )  //email format has 2 radio buttons!
					{ 
						this.getInputs( 'emailformat' )[0].disabled = false;
						this.getInputs( 'emailformat' )[1].disabled = false;
					}
				}
			},
			
			'receive': function(responseObject, userArgs) 
			{
			     try {
              	 // Handle timeouts
              	 if (responseObject.status == 408) {
                  	 	//display the error in the general error alert box already (display: none) on the page
                        var gen_error = document.getElementById('gen_error');
                        gen_error.innerHTML = 'The server could not be reached, please try again later.';
                        gen_error.display = 'block';
                  	 	return; 
              	 	}
              	 
			     var resp = responseObject.responseText;
			    
			     // Looks like we got something...
   	             resp = '(' + resp + ')';
                 var JSONobj = eval(resp);
                 
                 //find the div with the loader image, and get rid of it
			     var x = document.getElementById(JSONobj.id);
			     x.removeChild(x.childNodes[0]);
			     
			     if( JSONobj.NumberNewItems > 0 )
			     {
    			     var link = document.createElement('a');
    			     var href = 'http://' + window.location.hostname + '/sites/myncbi/searches/' + JSONobj.id + '/whatsnew/';
    			     var title = JSONobj.NumberNewItems + ' new items';
    			     link.setAttribute('href', href);
    			     link.setAttribute('title', title);
    			     link.innerHTML = title;
    			    
    			     x.appendChild(link);
    			 } else {
    			     x.innerHTML = 'No new items';
    			 }
			     } catch (e) {
			         //display the error in the general error alert box already (display: none) on the page
                     var gen_error = document.getElementById('gen_error');
                     gen_error.innerHTML = e;
                     gen_error.display = 'block';
                 }
			}
			

		}, {

});
