﻿var loggedInUserName="";
var isDefaultPage=false;
var mainAreaHeight,mainAreaWidth;

//var leftTitleHeightDiff=36;
var headerBarOffsetHeight=45;
var currentPage="";

var activeMode="";
var heightOffset=100;
var offsetForDoublePanes=36;
 var viewportwidth;
 var viewportheight;
 
 var paneBorderWidth=3;
//var isResizing=false;
//var resizeCount=0;


var loadMask=null;
var centerLoading=null;

var clickedLat=null;
var clickedLong=null;

 var welcomeSearchBool=false;


//var sHeight = window.screen.availHeight;
//var sWidth = window.screen.availWidth;

//$get("ctl00_MainContentPlaceHolder_HiddenScreenSize").value= sWidth + ","+sHeight;

//This checks to see if the current page is the main page, (the body has loaded). the variable is used in the pageLoad function
//which gets called in the master page i think :P

function bodyOnLoad()
{

 var searchOptions = readCookie("searchOptions");
    if (searchOptions !=null && searchOptions!=undefined){
     //  alert(searchOptions);
    } else {
   //  alert("no cookie yet");
        createCookie("searchOptions",entrySortType+"|"+groupByCatYesNo,0);
    }

//var communityPanel = Ext.getCmp("ctl00_MainContentPlaceHolder_CommunityPanel");

//var sHeight = window.screen.availHeight;
//var sWidth = window.screen.availWidth;

////$get("ctl00_MainContentPlaceHolder_HiddenScreenSize").value= sWidth + ","+sHeight;
//if (sWidth < 1100)
//{
//    communityPanel.bodyStyle="background: url(Images/earthwashoutblue_1024.jpg);";
//}
//else if (sWidth >1100 && sWidth <= 1440)
//{
//     communityPanel.bodyStyle="background: url(Images/earthwashoutblue_1440.jpg);";
//} 
//else if (sWidth > 1440 && sWidth < 2000)
//{
//    communityPanel.bodyStyle="background: url(Images/earthwashoutblue.jpg);";
//}
//else if (sWidth > 1920)
//{
//     communityPanel.bodyStyle="background: url(Images/earthwashoutblue_2200.jpg);";
//} else {
//    communityPanel.bodyStyle="background: url(Images/earthwashoutblue.jpg);";
//}
//var cPanelDom = $get("ctl00_MainContentPlaceHolder_CommunityPanel");
//cPanelDom.style.backgroundImage = "url(Images/earthwashoutblue_1440.jpg";

//var cPanelBodyDom = $get("ctl00_MainContentPlaceHolder_CommunityPanel_Body");
//cPanelBodyDom.style.background = "url(Images/earthwashoutblue_1440.jpg";
//communityPanel.render();
//communityPanel.reload(true);
//communityPanel.reload(null);


   //alert("bodyLoad");
    initMessage();
    closeMessage();
    //isDefaultPage=true;
    
    //If the url parameter is being used, then the page has changed, so maybe refresh
    if(querySt("Entry")!=null && querySt("Entry")!=undefined)
    {
    entriesToOpen=querySt("Entry");
     //alert("active mode parameter: " + activeMode);
    }
    
     //Use a cookie to save the current mode..
    var activeModeCookie = readCookie("activeModeCookie");
    if (activeModeCookie !=null && activeModeCookie!=undefined){
    //THIS IS A TEMP thing...only is an issue when someone searches from any page that isn't the default.aspx (i.e. login)...
    //To remedy, store the last search items in a cookie, and then read the cookies when the page loads, to remember the user's last search
        if (activeModeCookie=="SEARCHRESULTS")activeModeCookie="modeHome";
        activeMode=activeModeCookie;
    }
    
    //If the URL parameter was set for the mode, then set that mode.
    if (querySt("mode")!=null && querySt("mode")!=undefined)
    {
        activeMode = querySt("mode");
    }
    
    if (activeMode=="") activeMode="modeHome";
   
     setModeButtonStyles(activeMode);
  
    //var blah = $get("chkAll");
    //Select all categories by default
    selectAllCategories();
    
    if (isMainPage()) {
    
       // bottomMiddleCP = $find("bottomMiddleContentBehavior");       
       // topMiddleCP = $find("topMiddleContentBehavior");
        document.getElementById("entryKWSimple").focus();
        
       
        if (querySt("search")!=null && querySt("search")!=undefined)
        {
            activeMode="SEARCHRESULTS";
            document.getElementById("entryKWSimple").value=querySt("search");
            welcomeSearchBool=true;
            //validateSimpleSearch();
            
        }
        
        //The page has so set the mode
        setMode(activeMode,true);
        if (entriesToOpen!=""){
            if (entriesToOpen.indexOf(",")!=-1){
                var entries=entriesToOpen.split(",");
                  for (var i=0;i<entries.length;i++)
                    {
                     displayEntry(parseInt(entries[i]));
                    }
            } else {
               var entryToOpen = parseInt(entriesToOpen);
               if (entryToOpen!=NaN && entryToOpen!=-1)
               {
                 displayEntry(entryToOpen);
               }
            }

            entriesToOpen="";
        }
        
        if (welcomeSearchBool) validateSimpleSearch();
        
          //Initiate Side panels
          UpdateBookmarksSection(activeMode);
          UpdateNewsFeedsSection(activeMode);
          UpdateLatestQASection(activeMode);
      
    
   }
}

//function selectAllCategories(selAllChkBox)
//{
//     var bookmarks = document.getElementsByName("CategoryChkBox");
//        if (bookmarks.length!=0){
//            for (var i=0;i<bookmarks.length;i++)
//            {
//                if (selAllChkBox.checked==true){
//                    bookmarks[i].checked=true;
//                } else {
//                    bookmarks[i].checked =false;
//                }
//            }
//        }
//}

var entriesToOpen="";
function pageLoad(sender, args)
{

}

function clickGoogleChk(chkBox)
{
    if (chkBox.checked){
        boolIncludeGoogleResult=true;
    } else {
        boolIncludeGoogleResult=false;
    }
}

function setMode(modeButtonID,boolRefreshContent)
{
//If people are switching modes, remove the event listener, as it will get added back when the map is intialized
if (mapClickListener != null) GEvent.removeListener(mapClickListener);
projectMap=null;
addProjectMarker=null;

var addProjectWindow = Ext.getCmp(addProjectWindow);
if (addProjectWindow!=null) {
    if (addProjectWindow.isVisible()) addProjectWindow.close();

}
//clear calendars
    toggleCalendar("");

 if (intervalID!=null){
 clearInterval(intervalID);
 intervalID=null;
 }
 
//fake out the resize event
window.onresize=doody;
//UnTip();
createCookie("activeModeCookie",modeButtonID,0);
//alert(modeButtonID);
    //$get("ctl00_activeMode").value = modeButtonID;
    //Set the javascript global variable, and switch the button styles
   // theLastMode = modeButtonID;
    
    activeMode=modeButtonID;
    setModeButtonStyles(modeButtonID);
    
 
   // document.getElementById("ActiveButtonMode").value=modeButtonID;
    //alert("just set the hidden element to: "+ document.getElementById("ActiveButtonMode").value);
    //Check if we're at the main page, which will typically the case, but if logging in...
    if (isMainPage())
    {
        if (activeMode.toUpperCase()=="MODEHOME")
        {
           
             doLoadHome(boolRefreshContent);
             
             //Reset story cache;
             storyIndex=0;
             storyCache=null;
            
             Climate1StopWebService.GetFeaturedStoriesForCache(onGetStoryCacheSuccess,onGetStoryCacheFail,"storyDiv");
             
//             //Put the play button over the viz thumbnail
//             placePlayButton($get);
        }
        else if (activeMode.toUpperCase()=="MODEADDENTRY")
        {
           // showMainLoading("Preparing Entry Form...");
            doLoadAddEntry(boolRefreshContent);
           
        } else if (activeMode.toUpperCase()=="SEARCHRESULTS"){
        
            //Should check here to see if the google checkbox is checked...assume for now that it is.
            //prepareTabsForDoubleSearch();
            //var communityPanel = Ext.getCmp("ctl00_MainContentPlaceHolder_CommunityPanel");
            //communityPanel.getBody().update("");
    
          //  showMainLoading("Searching Entries, one moment...");
            doSearchResults(boolRefreshContent);
            
        } else if (activeMode.toUpperCase()=="MODECALENDAR"){
            doCalendar(boolRefreshContent);
        } else if (activeMode.toUpperCase()=="MODEABOUT"){
            doAbout(boolRefreshContent);
        } else if (activeMode.toUpperCase()=="MODEDISCUSS"){
            doDiscuss(boolRefreshContent);
        } else if (activeMode.toUpperCase()=="MODEDATAVISUALIZATION"){
            doDataVisualization(boolRefreshContent);
        }
        
        //UpdateLatestEntriesSection(activeMode);
        //hideMainLoading();
    } else {
    //alert("not main page, so go back to main page and call: " +activeMode);
        window.location = "Default.aspx";
    }
  //  setTimeout("window.onresize=resize",1000);
    //window.onresize = resize;

}

function doDiscuss(boolRefresh)
{
    var topMiddlePanel = Ext.getCmp("ctl00_MainContentPlaceHolder_CommunityPanel");
    topMiddlePanel.setTitle("<center><span class='PanelTitle'><img src='Images/topicDiscussionTitle.png' width='162px' height='20px' border='0'/></span></center>");
    
       var eastPanel = Ext.getCmp("ctl00_MainContentPlaceHolder_EastPanel");
   var westPanel = Ext.getCmp("ctl00_MainContentPlaceHolder_WestPanel");
   
   if (eastPanel!=null && eastPanel.collapsed) eastPanel.expand();
   if (westPanel!=null && westPanel.collapsed) westPanel.expand();
   
//     tabs = Ext.getCmp("searchResultTabPanel");
//            if (tabs!=null){
//                tabs.destroy();
//            }
//    var bottomMiddlePanel = Ext.getCmp("ctl00_MainContentPlaceHolder_LatestEntriesPanel");
//    bottomMiddlePanel.collapse();
    
    UpdateCommunitySection(activeMode);    
}

function doAbout(boolRefresh)
{
    var topMiddlePanel = Ext.getCmp("ctl00_MainContentPlaceHolder_CommunityPanel");
    topMiddlePanel.setTitle("<center><span class='PanelTitle'><img src='Images/aboutTitle.png' width='249px' height='20px' border='0'/></span></center>");
    
//     tabs = Ext.getCmp("searchResultTabPanel");
//            if (tabs!=null){
//                tabs.destroy();
//            }
//    var bottomMiddlePanel = Ext.getCmp("ctl00_MainContentPlaceHolder_LatestEntriesPanel");
//    bottomMiddlePanel.collapse();
    
    
   UpdateCommunitySection(activeMode);
}

function doCalendar(boolRefresh)
{

    var topMiddlePanel = Ext.getCmp("ctl00_MainContentPlaceHolder_CommunityPanel");
    topMiddlePanel.setTitle("<center><span class='PanelTitle'><img src='Images/communityCalendarTitle.png' width='206px' height='20px' border='0'/></span></center>");

       var eastPanel = Ext.getCmp("ctl00_MainContentPlaceHolder_EastPanel");
      var westPanel = Ext.getCmp("ctl00_MainContentPlaceHolder_WestPanel");
   
   if (eastPanel!=null && eastPanel.collapsed) eastPanel.expand();
   if (westPanel!=null && westPanel.collapsed) westPanel.expand();
   

//    
//     tabs = Ext.getCmp("searchResultTabPanel");
//            if (tabs!=null){
//                tabs.destroy();
//            }
//    var bottomMiddlePanel = Ext.getCmp("ctl00_MainContentPlaceHolder_LatestEntriesPanel");
//    bottomMiddlePanel.collapse();
   
     UpdateCommunitySection(activeMode);
}

function doDataVisualization(boolRefresh)
{
 var topMiddlePanel = Ext.getCmp("ctl00_MainContentPlaceHolder_CommunityPanel");
   
   var eastPanel = Ext.getCmp("ctl00_MainContentPlaceHolder_EastPanel");
   var westPanel = Ext.getCmp("ctl00_MainContentPlaceHolder_WestPanel");
   
   if (eastPanel!=null) eastPanel.collapse();
   if (westPanel!=null) westPanel.collapse();
    //Clear the content
    topMiddlePanel.getBody().update("");
    
    
    //Show the loading mask...
   // loadMask = new Ext.LoadMask(topMiddlePanel.getBody(), {msg:"Preparing Data and Visualization..."});
   // loadMask.show();
    
    //Change the title
    topMiddlePanel.setTitle("<center><span class='PanelTitle'><img src='Images/dataVizTitle.png' width='225px' height='20px' border='0'/></span></center>");
  // topMiddlePanel.autoScroll=false;
  //Add the Data and Visualization tabs
    
    var tabs = new Ext.TabPanel({
    renderTo: topMiddlePanel.getBody(),
    activeTab: 0,
    border:false,
    bodyBorder:false,
    layoutOnTabChange:true,
    autoScroll:true,
    bodyStyle:"backgroundColor:transparent;",
    items: [{
        id: 'projectsTab',
        title: 'Current Projects Map',
        html: 'Loading...',
        unstyled:true,
         layout: 'fit',
         height:800,
         autoHeight:true,
         autoWidth:true
       
    },{
        id: 'observedDataTab',
        title: 'Historical Observations',
        html: 'Loading...',
        unstyled:true,
         layout: 'fit',
         autoWidth:true
        // autoHeight:true,
         //autoScroll:true
         
    },{
        id: 'projectionsDataTab',
        title: 'Modeled Projections',
        html: 'Loading...',
        unstyled:true,
         layout: 'fit',
         autoWidth:true
         //autoScroll:true
         //autoHeight:true
    },{
        id: 'handpickedToolsTab',
        title: 'Featured Climate Tools',
        html: 'Loading...',
        unstyled:true,
         layout: 'fit',
         autoWidth:true,
         autoHeight:true
         //autoScroll:true
         //autoHeight:true
    }]
});

//Now that the tabs have been added, update the content for each one.
UpdateDataAndVisualizationTab(activeMode,"projectsTab");
UpdateDataAndVisualizationTab(activeMode,"observedDataTab");
UpdateDataAndVisualizationTab(activeMode,"projectionsDataTab");
UpdateDataAndVisualizationTab(activeMode,"handpickedToolsTab");
//setTimeout("loadMask.hide();",4000);
  // var myMask = new Ext.LoadMask(topMiddlePanel.getBody(), {msg:"Preparing Data and Visualization..."});
 //myMask.show();
  //  Ext.net.Mask.show("ctl00_MainContentPlaceHolder_CommunityPanel");

    
//     var communityPanel = Ext.getCmp("ctl00_MainContentPlaceHolder_CommunityPanel");
//               communityPanel.getBody().update("");
               
   // UpdateCommunitySection(activeMode);
}

function doSearchResults(boolRefresh)
{
    var topMiddlePanel = Ext.getCmp("ctl00_MainContentPlaceHolder_CommunityPanel");
    topMiddlePanel.setTitle("<center><span class='PanelTitle'><img src='Images/searchResultsTitle.png' width='152px' height='20px' border='0'/></span></center>");
    
     var eastPanel = Ext.getCmp("ctl00_MainContentPlaceHolder_EastPanel");
   var westPanel = Ext.getCmp("ctl00_MainContentPlaceHolder_WestPanel");
   
   if (eastPanel!=null && eastPanel.collapsed) eastPanel.expand();
   if (westPanel!=null && westPanel.collapsed) westPanel.expand();
   
}


function doLoadAddEntry(boolRefresh)
{
     var topMiddlePanel = Ext.getCmp("ctl00_MainContentPlaceHolder_CommunityPanel");
    topMiddlePanel.setTitle("<center><span class='PanelTitle'><img src='Images/addEntryTitle.png' width='224px' height='20px' border='0'/></span></center>");
    
     var eastPanel = Ext.getCmp("ctl00_MainContentPlaceHolder_EastPanel");
   var westPanel = Ext.getCmp("ctl00_MainContentPlaceHolder_WestPanel");
   
  if (eastPanel!=null && eastPanel.collapsed) eastPanel.expand();
   if (westPanel!=null && westPanel.collapsed) westPanel.expand();
//     tabs = Ext.getCmp("searchResultTabPanel");
//            if (tabs!=null){
//                tabs.destroy();
     //       }
//    var bottomMiddlePanel = Ext.getCmp("ctl00_MainContentPlaceHolder_LatestEntriesPanel");
//    bottomMiddlePanel.collapse();
 
    //Call the js function to get the add entry content from the web service
     UpdateCommunitySection(activeMode);

}

function doLoadHome(boolRefresh)
{
    var topMiddlePanel = Ext.getCmp("ctl00_MainContentPlaceHolder_CommunityPanel");
  
    topMiddlePanel.setTitle("<center><span class='PanelTitle'><img src='Images/communityTitle.png' width='142px' height='20px' border='0'/></span></center>");
    var eastPanel = Ext.getCmp("ctl00_MainContentPlaceHolder_EastPanel");
   var westPanel = Ext.getCmp("ctl00_MainContentPlaceHolder_WestPanel");
   
   if (eastPanel!=null && eastPanel.collapsed) eastPanel.expand();
   if (westPanel!=null && westPanel.collapsed) westPanel.expand();
//     tabs = Ext.getCmp("searchResultTabPanel");
//            if (tabs!=null){
//                tabs.destroy();
//            }
            
    //var bottomMiddlePanel = Ext.getCmp("ctl00_MainContentPlaceHolder_LatestEntriesPanel");
   // bottomMiddlePanel.expand();    
    
    //Fetch the community section
    UpdateCommunitySection(activeMode);
     
}

function showProjectEntryWindow(latitude,longitude)
{
    Ext.QuickTips.init();

    // turn on validation errors beside the field globally
   // Ext.form.Field.prototype.msgTarget = 'side';
    //Create a new entry window to add some project information
    //Use the lat long to associate the project with a location.
    
//    var win = new Ext.Window({
//    title: 'formpanel defaults should be applyIf',
//    items: [{
//        xtype: 'formpanel',
//        bodyStyle: 'color:blue',
//        items: [{
//            xtype: 'panel',
//            html: 'I don\'t want to overwrite the defaults'
//        }, {
//            xtype: 'panel',
//            html: 'I wanna overwrite the defaults',
//            bodyStyle: 'color:blue'
//        }]
//    }]
//});
//win.show();

        var formItems = [];
        
          var continents = [
        ['AF', 'Africa'],
        ['AS', 'Asia'],
        ['EU', 'Europe'],
        ['NA', 'North America'],
        ['SA', 'South America'],
        ['OC', 'Oceania'],
        ['AN', 'Antarctica']
         ];

         var countryStore =  new Ext.data.Store({
                fields: ['countryID', 'countryName'],
                
                url: "Climate1StopWebService.asmx/GetCountriesForExtJS",
                reader: new Ext.data.XmlReader({
                       record:"CountryItem",
                       id: 'countryID',
                       fields: ['countryID', 'countryName']
                        //root: 'ArrayOfCountryItem'
                })
                });
//        var tooltipProject = new Ext.ToolTip({
//            trackMouse:true,
//            target:"buttonHelpProjectName",
//            html:"this is a tooltip"
//        });
        
        //Project name
        var compProjectName = new Ext.form.CompositeField({
        xtype: 'compositefield',
        fieldLabel: "Project Title",
        msgTarget:"side",
        invalidText:"This field is required",
        items: [
            {
                 id:"txtProjectName",
                 xtype: "textfield",
                 width:300,
                 tabIndex:1,
                // msgTarget:"side",
                 allowBlank:false
                

            },
            {
               // id:"buttonHelpProjectName",
                xtype:"button",
                text:"<b>?</b>",
                tooltip:"This appears in the search result as the entry title."
                
            }
        ]
        });
        
           //Project description
        var compProjectDesc = new Ext.form.CompositeField({
        xtype: 'compositefield',
        fieldLabel: "Project Description",
         msgTarget:"side",
        items: [
            {
                 id:"txtProjectDesc",
               // fieldLabel: "Project Description",
                allowBlank:false,
                xtype: "textarea",
              //  anchor: "-5",
                height:150,
                width:300,
                tabIndex:2,
                maxLength:500
                

            },
            {
              //  id:"buttonHelpProjectDesc",
                xtype:"button",
                text:"<b>?</b>",
                tooltip:"Provide some detail about your project."
                
            }
        ]
        });
        
         //Project URL
        var compProjectURL = new Ext.form.CompositeField({
        xtype: 'compositefield',
        fieldLabel: "Website URL",
        msgTarget:"side",
        items: [
            {
                 xtype: "textfield",
                id:"txtURLInfo",
                //fieldLabel: "Website URL",
                allowBlank:false,
                tabIndex:3,
               // anchor: "-2",
              //  padding:5,
               // msgTarget:"side",
                width:300
                

            },
            {
                //id:"buttonHelpProjectURL",
                xtype:"button",
                text:"<b>?</b>",
                tooltip:"Enter in a hyperlink that people can click on for more information"
                
            }
        ]
        });
        
         //Project keywords
        var compProjectKW = new Ext.form.CompositeField({
        xtype: 'compositefield',
        fieldLabel: "Keywords (5 max)",
        msgTarget:"side",
        items: [
            {
                 xtype: "textfield",
                id:"txtKeywords",
                //fieldLabel: "Website URL",
                allowBlank:false,
                tabIndex:4,
               // anchor: "-2",
              //  padding:5,
               // msgTarget:"side",
                width:300
                

            },
            {
                //id:"buttonHelpProjectURL",
                xtype:"button",
                text:"<b>?</b>",
                tooltip:"Help users find your entry easily by providing a few relevant keywords. Separate each word with a comma. For example: adaptation, temperature, increase, drought"
                
            }
        ]
        });
          //Project continent
        var compProjectContinent = new Ext.form.CompositeField({
        xtype: 'compositefield',
        fieldLabel: "Continent",
        items: [
            {
                 xtype: "combo",
                 tabIndex:8,
                id:"comboBoxContinent",
                //fieldLabel: 'Continent',
                hiddenName:'continent',
                store: new Ext.data.ArrayStore({
                    fields: ['abbr', 'continent'],
                    data : continents // from states.js
                }),
                valueField:'abbr',
                displayField:'continent',
                typeAhead: true,
                mode: 'local',
                triggerAction: 'all',
                emptyText:'Select a continent...',
                selectOnFocus:true,
                width:250,
                listeners: {
                  select: function(f,r,i){
                 var countryCombo = Ext.getCmp("comboBoxCountry");
                 countryCombo.setDisabled(true);
                 countryCombo.setValue('');
                 countryCombo.store.removeAll();
                  //  populateAddProjectCountriesBox(r.data.abbr);
                    //countryCombo.store.reload(null);
                 countryCombo.store.reload({
                    params: {
                                continent: r.data.abbr
                            }
                 });
               
                    countryCombo.setDisabled(false);
                    //Ext.Msg.alert('Title',r.data.abbr);
                  }
                }
                

            },
            {
                //id:"buttonHelpProjectURL",
                xtype:"button",
                text:"<b>?</b>",
                tooltip:"You may associate your entry with a continent and, if desired, also specify a country"
                
            }
        ]
        });
        
        var compProjectCountry = new Ext.form.CompositeField({
        xtype: 'compositefield',
        fieldLabel: "Country",
        items: [
            {
                xtype: "combo",
                tabIndex:9,
                id:"comboBoxCountry",
                hiddenName:'country',
                store:countryStore,
                valueField:'countryID',
                displayField:'countryName',
                typeAhead: true,
                mode: 'local',
                triggerAction: 'all',
                emptyText:'Select a country...',
                selectOnFocus:true,
                width:250
        

            },
            {
                //id:"buttonHelpProjectURL",
                xtype:"button",
                text:"<b>?</b>",
                tooltip:"If you specify a continent, you may also specify a country"
                
            }
        ]
        });
        
           var compProjectThemes = new Ext.form.CompositeField({
            xtype: 'compositefield',
            fieldLabel: "Theme/Sector",
            items: [
                {
                    xtype:"combo",
                    tabIndex:7,
                    id:"comboBoxThemeSector",
                        //fieldLabel: 'Theme/Sector',
                    hiddenName:'theme',
                    store: new Ext.data.Store({
                        fields: ['themeID', 'themeName'],
                        
                        url: "Climate1StopWebService.asmx/GetThemeSectorsForExtJS",
                        reader: new Ext.data.XmlReader({
                               record:"ThemeSectorItem",
                               id: 'themeID',
                               fields: ['themeID', 'themeName']
                                //root: 'ArrayOfCountryItem'
                        })
                    }),
                   // store:countryStore,
                    valueField:'themeID',
                    displayField:'themeName',
                    typeAhead: true,
                    mode: 'remote',
                    triggerAction: 'all',
                    emptyText:'Select a theme/sector...',
                    selectOnFocus:true,
                    width:250
            

                },
                {
                    //id:"buttonHelpProjectURL",
                    xtype:"button",
                    text:"<b>?</b>",
                    tooltip:"You may associate your entry with one sector/theme. This will allow users who have subscribed to a certain theme, to find your entry easily "
                    
                }
        ]
        });
        
         //Project start date
        var compProjectDateRange = new Ext.form.CompositeField({
        xtype: 'compositefield',
        fieldLabel: "Date Range",
        items: [
           {
               xtype: "displayfield",
               tabIndex:5,
               //id:"dateField1",
              // vtype:"daterange",
              // fieldLabel:"From",
              // editable:false,
              html:"From",
               width:25
                

            },
            {
               xtype: "datefield",
               id:"dateField1",
               vtype:"daterange",
               tabIndex:6,
              // fieldLabel:"From",
               editable:false,
               listeners: {
                 select: function(dateObj,theDate){
                    var dateField2 = Ext.getCmp("dateField2");
                    dateField2.setMinValue(theDate);
                }
                }
                

            },
             {
               xtype: "displayfield",
               //id:"dateField1",
              // vtype:"daterange",
              // fieldLabel:"From",
              // editable:false,
               html:"&nbsp;To",
               width:15
                

            },
            {
               xtype: "datefield",
               id:"dateField2",
               vtype:"daterange",
              // fieldLabel:"To",
                editable:false

            },
            {
                //id:"buttonHelpProjectURL",
                xtype:"button",
                text:"<b>?</b>",
                tooltip:"If your entry is associated with a specific time period, choose the start/end dates here"
                
            }
        ]
        });
        
            //add the fields to the form items collection
           //formItems.push(txtProjectName);
            formItems.push(compProjectName);
           // formItems.push(tooltipProject);
            formItems.push(compProjectDesc);
            formItems.push(compProjectURL);
            formItems.push(compProjectKW);
            
            formItems.push(compProjectDateRange);
            formItems.push(compProjectThemes);
            
            
            formItems.push(compProjectContinent);
            formItems.push(compProjectCountry);
            
           // formItems.push(compProjectEndDate);
           
            
           
            
            //Create the form and add the field items to it
            var formPanel = new Ext.form.FormPanel({
                id:"addProjectForm",
                title:"Please enter some information about your project...",
                //monitorPoll:500,
                //monitorValid:true,
                padding:"5px 15px 5px 5px;",
                width:475,
                height:500,
                
                items:formItems
            });
            
            
            //Create a window items collection, just add the form panel to it.
            var windowItems =[];
            windowItems.push(formPanel);
            
        //Create the window and add the formpanel items to it, then show the form
        var window = new Ext.Window({
            id:"addProjectWindow",
            title: "Add Project Entry",
            width: 500,
            height: 510,
            closable:true,
            buttonAlign: "center",
            layout: "fit",
            autoScroll:true,
            closable:false,
            //iconCls: 'project-icon',
            items:windowItems,
            buttons: [{
                text: "OK",
                handler: validateProjectInfo

                }, {
                text: "Cancel",
                handler: cancelAddProject
            }]
        }); 
        
        //Show the form.
       window.show();
    
}
//var simpleArray = eval("[['f','Foo'],['b','Bar']]");

function cancelAddProject(b,e)
{
    Ext.getCmp("addProjectWindow").close();
    if (projectMap!=null){
        if (addProjectMarker!=null) projectMap.removeOverlay(addProjectMarker);
    }
}

function validateProjectInfo(b,e)
{
//alert("you closed me!");
var addProjectForm = Ext.getCmp("addProjectForm");

if (addProjectForm.getForm().isValid())
{
    var entryName = Ext.getCmp("txtProjectName").getValue();
    var entryDesc = Ext.getCmp("txtProjectDesc").getValue();
    var entryURL = Ext.getCmp("txtURLInfo").getValue();
    var entryWords = Ext.getCmp("txtKeywords").getValue();
    var entryContinent = Ext.getCmp("comboBoxContinent").getValue();
    if (entryContinent==null || entryContinent=="") entryContinent="ALL";
    
    var entryCountry = Ext.getCmp("comboBoxCountry").getValue();
    if (entryCountry==null || entryCountry=="")entryCountry=-1;
    
    var entryTheme = Ext.getCmp("comboBoxThemeSector").getValue();
    if (entryTheme==null || entryTheme=="")entryTheme="-1";
    
     var entryStartDate = Ext.getCmp("dateField1").getValue();
     var entryEndDate = Ext.getCmp("dateField2").getValue();
     
    if (entryStartDate!="" && entryEndDate=="") entryEndDate=entryStartDate;
    if (entryEndDate!="" && entryStartDate=="") entryStartDate=entryEndDate;
   if (entryStartDate!="" && entryEndDate!=""){
    entryStartDate = entryStartDate.format("M/dd/yyyy");
    entryEndDate = entryEndDate.format("M/dd/yyyy");
    }
   
    
    
    
    
    if (Sys.Services.AuthenticationService.get_isLoggedIn()) {
       // $get("submitEntryButton").disabled = true;
            //Make the call to the webservice to insert the information into the database
            Climate1StopWebService.AddEntry(entryName,entryDesc,3,entryURL,entryWords,entryStartDate,entryEndDate,entryContinent,entryCountry,entryTheme,clickedLat,clickedLong,onAddProjectEntryToMapSuccess,onAddEntryFail,"AddEntry");
        } else {
        notLoggedInMessage("You must be logged in to add an entry");return false;
           // alert("You must be logged in to add an entry");
           // window.location = "Login.aspx?ReturnMode=modeAddEntry";
           //window.location = "Login.aspx";
        }
    
    
    //Get values from form and add the project and project location record
    
    Ext.getCmp("addProjectWindow").close();
}
else
{
    Ext.Msg.show({icon: Ext.MessageBox.ERROR, title:"Required Fields Missing", msg: 'Please enter information in all required fields.', buttons:Ext.Msg.OK});
} 



}

function enterAddProjectClickMode()
{

 Ext.Msg.alert("Project Location", "Please click your project's location on the map...");
   // alert("Please click your project's location on the map...");
    
   //projectMap.setOptions({ draggableCursor: 'crosshair' }); 
    if (projectMap!=null){
        var yellowIcon = new GIcon(G_DEFAULT_ICON);
        yellowIcon.image = "Images/addProjectMarkerIcon.png";

        // Set up our GMarkerOptions object
        markerOptions = { icon:yellowIcon };
                        
            //Bind to the click event.
            projectMapClickListener = GEvent.bind(projectMap, "click", this, function(overlay, latlng) { 
           // if (projectMapClickCounter==0) { 
              if (latlng) { 
              if (addProjectMarker!=null) projectMap.removeOverlay(addProjectMarker);
               // map.clearOverlays();
                addProjectMarker = new GMarker(latlng,markerOptions);
                projectMap.addOverlay(addProjectMarker) 
                
                //clicked coords vars
                clickedLat = latlng.lat();
                clickedLong = latlng.lng();
                
                setTimeout("showProjectEntryWindow();",500);
                
                //alert(latlng.lat() + "," + latlng.lng());
               // projectMapClickCounter++; 
              } else if (overlay instanceof GMarker) { 
                //alert(latlng.lat() + "," + latlng.lng());
              } 
            //} else { 
           //     if (projectMapClickListener!=null) GEvent.removeListener(projectMapClickListener); 
           // } 
           
           //projectMap.setOptions({ draggableCursor: 'crosshair' }); 
           // projectMap.setOptions({ draggableCursor: 'move' }); 
               if (projectMapClickListener!=null) GEvent.removeListener(projectMapClickListener); 
              });  
    }
    //Bind to the click event of the map
    
    
}

function setModeButtonStyles(btnID)
{
    var headerBar = document.getElementById("headerBar");

    var links=headerBar.getElementsByTagName('a');

    var modeElem;
    var idName;
    for (var i=0;i<links.length;i++)
    { 

        if (links[i].id.indexOf("mode")!=-1)
        {
            modeElem = document.getElementById(btnID);
            if (btnID.toUpperCase()==links[i].id.toUpperCase())
            {
                links[i].blur();
                if (links[i].id.toUpperCase()=="MODEADDENTRY"){
                    FM.removeClass(links[i],"modeAE");
                    FM.addClass(links[i],"modeActive");
                } else {
                    //modeElem.style.backgroundImage ="url(../Images/modeActive.png)" 
                   // modeElem.setAttribute("class", "modeActive"); 
                    //modeElem.setAttribute("className", "modeActive"); 
                    FM.removeClass(links[i],"mode");
                    FM.addClass(links[i],"modeActive");
                }
            } else {
            if (links[i].id.toUpperCase()=="MODEADDENTRY"){
                    FM.removeClass(links[i],"modeActive");
                    FM.addClass(links[i],"modeAE");
                } else {
                    FM.removeClass(links[i],"modeActive");
                    FM.addClass(links[i],"mode");
                }
                
               // modeElem.setAttribute("class", "mode"); 
                //modeElem.setAttribute("className", "mode"); 
            }
               
        }
    }
}


//function onSimpleSearchResize()
//{
//    var simpleSearch = Ext.getCmp("ct100_MainContentPlaceHolder_SimpleSearchPanel");
//     var advancedSearch = Ext.getCmp("ctl00_MainContentPlaceHolder_AdvancedSearchPanel");
//}


function onCollapseAdvancedSearch()
{
    //var simpleSearch = Ext.getCmp("ct100_MainContentPlaceHolder_SimpleSearchPanel");
    
     var advancedSearch = Ext.getCmp("ctl00_MainContentPlaceHolder_AdvancedSearchPanel");
     if (simpleSearch != undefined && simpleSearch!=null)
     {
     simpleSearch.expand();
     setTimeout("document.getElementById('entryKWSimple').focus()",500);
     }
     
}
function showNewsFeedsTab()
{
    var newsContent = document.getElementById("ctl00_MainContentPlaceHolder_NewsFeedsTab");
    if (newsContent!=null && newsContent.innerHTML.indexOf("headline")==-1){
        UpdateNewsFeedsSection(activeMode);
    }
    
}

var simpleSearch;
function onCollapseSimpleSearch(obj)
{

    simpleSearch = obj;
    //var simps = Ext.getCmp("ctl00_MainContentPlaceHolder_SimpleSearchPanel");
    var advancedSearch = Ext.getCmp("ctl00_MainContentPlaceHolder_AdvancedSearchPanel");
     
     if (advancedSearch!=undefined)
     {
      advancedSearch.expand();
      setTimeout("document.getElementById('entryKW').focus()",500);
      
     }
    
}
function openAdvancedSearch()
{
    var advancedSearch = Ext.getCmp("ctl00_MainContentPlaceHolder_AdvancedSearchPanel");
     
     if (advancedSearch!=undefined)
     {
      advancedSearch.expand();
      setTimeout("document.getElementById('entryKW').focus()",500);
      
     }
}
//function onExpandAdvancedSearch()
//{
//    var advancedSearch = Ext.getCmp("ctl00_MainContentPlaceHolder_AdvancedSearchPanel");
//    var simpleSearch = Ext.getCmp("ct100_MainContentPlaceHolder_SimpleSearchPanel")
//}

function isMainPage()
{
    
   var locationURL = window.location.href;
   var slashIndex = locationURL.lastIndexOf("/");

   currentPage = locationURL.substr(slashIndex + 1, locationURL.length - slashIndex);
   var questionMarkIndex = currentPage.indexOf("?");
   //alert(questionMarkIndex);
   var currentPageUpper = currentPage.toUpperCase();
   
   if ((currentPageUpper.indexOf("DEFAULT.ASPX?")!=-1) && (questionMarkIndex != -1)) {
       currentPage = currentPage.substring(0, questionMarkIndex);
      //alert(currentPage);
   }
   //var currentPageUpper = currentPage.toUpperCase();
   //alert(currentPageUpper);
   // if (isDefaultPage || currentPage.toUpperCase()=="DEFAULT.ASPX" || currentPage.toUpperCase()=="")
    if (currentPage.toUpperCase()=="DEFAULT.ASPX" || currentPage=="")
    {
        return true;
    } else {
        return false;
    }
}

//Function to get querystring info
function querySt(ji) {
hu = window.location.search.substring(1);
gy = hu.split("&");
for (i=0;i<gy.length;i++) {
ft = gy[i].split("=");
if (ft[0] == ji) {
return ft[1];
}
}
}

//These functions fire when a collapseable panel is expanded/collapsed
//function expandHandler(sender,args )
//{
//    if (sender._id=="bottomMiddleContentBehavior")
//    {
//       $get("tdTopMiddlePanel").style.borderBottom="";        
//    }
//}

//function collapseHandler( sender  , args ){

//    if (sender._id=="bottomMiddleContentBehavior")
//    {
//       $get("tdTopMiddlePanel").style.borderBottom="solid 3px navy";
//    }
//}
// Make sure the "FM" namespace object exists
if (typeof FM != 'object') {
    FM = new Object();
}

/**
 * Checks a given class attribute for the presence of a given class
 *
 * @author  Dan Delaney     http://fluidmind.org/
 * @param   element         DOM Element object (or element ID) to remove the class from
 * @param   nameOfClass     The name of the CSS class to check for
 */
FM.checkForClass = function(element, nameOfClass) {
    if (typeof element == 'string') { element = document.getElementById(element); }

    if (element.className == '') {
        return false;
    } else {
        return new RegExp('\\b' + nameOfClass + '\\b').test(element.className);
    }
}


/**
 * Adds a class to an element's class attribute
 *
 * @author  Dan Delaney     http://fluidmind.org/
 * @param   element         DOM Element object (or element ID) to add the class to
 * @param   nameOfClass     Class name to add
 * @see     checkForClass
 */
FM.addClass = function(element, nameOfClass) {
    if (typeof element == 'string') { element = document.getElementById(element); }

    if (!FM.checkForClass(element, nameOfClass)) {
        element.className += (element.className ? ' ' : '') + nameOfClass;
        return true;
    } else {
        return false;
    }
}


/**
 * Removes a class from an element's class attribute
 *
 * @author  Dan Delaney     http://fluidmind.org/
 * @param   element         DOM Element object (or element ID) to remove the class from
 * @param   nameOfClass     Class name to remove
 * @see     checkForClass
 */
FM.removeClass = function(element, nameOfClass) {
    if (typeof element == 'string') { element = document.getElementById(element); }

    if (FM.checkForClass(element, nameOfClass)) {
        element.className = element.className.replace(
            (element.className.indexOf(' ' + nameOfClass) >= 0 ? ' ' + nameOfClass : nameOfClass),
            '');
        return true;
    } else {
        return false;
    }
}


/**
 * Replaces a class with another if the class is present
 *
 * @author  Dan Delaney     http://fluidmind.org/
 * @param   element         DOM Element object (or element ID) to remove the class from
 * @param   class1          Class name to replace
 * @param   class2          Class name to replace it with
 * @see     checkForClass
 * @see     addClass
 * @see     removeClass
 */
FM.replaceClass = function(element, class1, class2) {
    if (typeof element == 'string') { element = document.getElementById(element); }

    if (FM.checkForClass(element, class1)) {
        FM.removeClass(element, class1);
        FM.addClass(element, class2);
        return true;
    } else {
        return false;
    }
}


/**
 * Toggles the specified class on and off
 *
 * @author  Dan Delaney     http://fluidmind.org/
 * @param   element         DOM Element object (or element ID) to toggle the class of
 * @param   nameOfClass     Class name to toggle
 * @see     checkForclass
 * @see     addClass
 * @see     removeClass
 */
FM.toggleClass = function(element, nameOfClass) {
    if (typeof element == 'string') { element = document.getElementById(element); }

    if (FM.checkForClass(element, nameOfClass)) {
        FM.removeClass(element, nameOfClass);
    } else {
        FM.addClass(element, nameOfClass);
    }

    return true;
}

function doResize()
{
//pageLoad(null,null);
    

    //Get the available view dimensions
    getAvailableDimensions();
    mainAreaHeight=viewportheight-heightOffset;

    
    leftPanel = $get("ctl00_leftContentPanel");
    leftPanel.style.height=mainAreaHeight+"px";

    //Initiate the right side
    dockRightPanels();
    
    if (isMainPage()) {
        //The page has reloaded, and we happen to be viewing the main page, in the "home" mode, so dock the panels
        setMode(activeMode,true);

   }

    
}
function doody()
{
//alert("blah");
}
function resize()
   {
    var currentSize = getViewportSize();
    if (currentSize[0] != g_prevSize[0] || currentSize[1] != g_prevSize[1])
    {
     g_prevSize = currentSize;
     doResize();
     //debug.value = 'the window was resized: ' +
          //         document.documentElement.clientWidth + ', ' +
          //         document.documentElement.clientHeight;
    }
   }


   function getViewportSize()
   {
    var size = [0, 0];
    if (typeof window.innerWidth != 'undefined')
    {
     size = [ window.innerWidth, window.innerHeight ];
    }
    else if (typeof document.documentElement != 'undefined' &&
             typeof document.documentElement.clientWidth != 'undefined' &&
             document.documentElement.clientWidth != 0)
    {
     size = [ document.documentElement.clientWidth, document.documentElement.clientHeight ];
    }
    else
    {
     size = [ document.getElementsByTagName('body')[0].clientWidth,
              document.getElementsByTagName('body')[0].clientHeight ];
    }

    return size;
   }


function getAvailableDimensions()
{
 // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
 
 if (typeof window.innerWidth != 'undefined')
 {
      viewportwidth = window.innerWidth,
      viewportheight = window.innerHeight
 }
 
// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)

 else if (typeof document.documentElement != 'undefined'
     && typeof document.documentElement.clientWidth !=
     'undefined' && document.documentElement.clientWidth != 0)
 {
       viewportwidth = document.documentElement.clientWidth,
       viewportheight = document.documentElement.clientHeight
 }
 
 // older versions of IE
 
 else
 {
       viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
       viewportheight = document.getElementsByTagName('body')[0].clientHeight
 }
}

if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();