var browser;
var pages;                                          // defines all of the pages in the site
var stylesheetObject;
var styleSheetUrl;                                  // sets the default stylesheet
var pageTitleObject;
/*************/
/* Help Menu */
/*************/
//var helpContainer;                                  // the container in which help text is written
//var helpContent;
var contentContainer;
var theIframe;
var defaultProject = { name:null, id:-1, orgName: null,
    toLocation: null, fromLocation: null, district: null,
    counties: null, phase: null, projectType: null, contactEmail: null
};
var currentPage = { id:-1, url:null, displayName:null,
    groupName:null, description:null, helpText:null,
    adminIndicator:'N'
};

/***********************/
/* Project Search Menu */
/***********************/
var advancedSearchContainer;
var basicSearchContainer;
//var psContainer;
//var psContent;

/*****************/
/* Define object */
/*****************/
function Application()
{
    this.initPageData = initPageData;
    //this.initPageDataMap = initPageDataMap;
    this.initNavigation = Navigation_initTabs;
    this.browser = getBrowser;
    this.getDefaultProject = getDefaultProject
    this.setDefaultProject = setDefaultProject;
    this.getPageTitle = getPageTitle;
    this.setPageTitle = setPageTitle;
    this.getPageTitleObject = getPageTitleObject;
    this.initPageTitle = initPageTitle;
    this.restorePageTitle = initPageTitle;
    this.getPages = getPages;
    this.getCurrentPage = getCurrentPage;
    this.setCurrentPage = setCurrentPage;
    this.getStylesheetURL = getStylesheetURL;
    this.setStylesheetURL = m_setStylesheetURL;
    this.initIframe = initIframe;
    this.getIframe  = getIframe;
    this.loadIframe = m_loadIframe;
    this.loadIframeExternalLink = m_loadIframeExternalLink;
    this.loadIframeInternalLink = m_loadIframeInternalLink;
    this.reloadIframe = m_reloadIframe;
    this.contentContainerObject = getContentContainer;
    this.refreshIframe = refreshIframe;
    this.initHelp = help_initHelp;
    this.initProjectSearch  = search_initializeSearch;
    this.showLoadingMessage = showLoadingMessage;
    this.hideLoadingMessage = hideLoadingMessage;
    this.loadNewProjectMilestone = projectSearch_setActiveProjectMilestone;
    //this.setCookies = setCookies;
    this.resetProjectSearch = search_startOver;
    this.showDiv = help_showDiv;
    this.toggleMapMaxRestore = toggleMapMaxRestore;
    this.isMapMax = false;
    this.showOnMap = showOnMap;
}

function getBrowser()
{
    if(browser == null) {browser = new Browser(); }
    return browser;
}

function getDefaultProject()
{
    return defaultProject;
}
function setDefaultProject(project)
{
    defaultProject = project;
    //setCookies();
}

/*function setCookies()
{
    var cookiestring = "currentPage=" + getCurrentPage().id;
    if(getDefaultProject().id != -1)
        cookiestring += ",defaultProject=" + getDefaultProject().id;
    cookiestring += ";expires=Fri, 3 Aug 2007 20:47:11 UTC;";
    //alert(cookiestring);
    document.cookie = cookiestring;
    alert(document.cookie);
}*/

function getPageTitle()
{
    return getPageTitleObject().innerHTML;
}

function getPageTitleObject()
{
    if(pageTitleObject == null) { pageTitleObject = document.getElementById("pageTitle"); }
    return pageTitleObject;
}

function setPageTitle(e)
{
    var sourceElement = getBrowser().getSourceElement(e);
    var thePage = getPages().getPage(sourceElement.innerHTML, 2);
    var theGroup = thePage.groupName;
    if(pageTitleObject == null) { getPageTitle(); }
    if(theGroup != null)
        pageTitleObject.innerHTML = theGroup + " >> " +  thePage.displayName;
    else
        pageTitleObject.innerHTML = thePage.displayName;
    //pageTitleObject.style.backgroundColor = "red";

}

function initPageTitle()
{
    //alert("get page title!");
    var thePage = getCurrentPage();
    //alert(thePage);
    var theGroup = thePage.groupName;
    if(pageTitleObject == null) { getPageTitle(); }
    if(theGroup != null && theGroup != "")
        pageTitleObject.innerHTML = theGroup + " >> " +  thePage.displayName;
    else
        pageTitleObject.innerHTML = thePage.displayName;
}

function getAdvancedSearchContainer()
{
    if(advancedSearchContainer == null) { advancedSearchContainer = document.getElementById("advanced"); }
    return advancedSearchContainer;
}

function getBasicSearchContainer()
{
    if(basicSearchContainer == null) { basicSearchContainer = document.getElementById("basic"); }
    return basicSearchContainer;
}

function getPages()
{
    if(pages == null) {pages = new Pages(); }
    return pages;
}

function getCurrentPage()
{
    if(currentPage.id == -1)
    {
        currentPage = pages.getPage(g_startPageName);
    }
    //if(currentPage == null)
    //    alert(currentPage);
    return currentPage;
}

function setCurrentPage(page)
{
    //currentPage = page;
    currentPage.id = page.id;
    currentPage.url = page.url;
    currentPage.groupName = page.groupName;
    currentPage.displayName = page.displayName;
    if(page.description != null)
        currentPage.description = page.description;
    if(page.helpText != null)
        currentPage.helpText = page.helpText;
    if(page.adminIndicator != null)
        currentPage.adminIndicator = page.adminIndicator;
}

function refreshStylesheetObjects()
{
    if(stylesheetObject == null) { stylesheetObject = document.getElementById("ss"); }
    if(stylesheetObject == null)
    {
        var objHead = document.getElementsByTagName("head");
        if (objHead[0])
        {
            var objCSS = objHead[0].appendChild(document.createElement('link'));
            objCSS.id = "someuniqueid";
            objCSS.rel = "stylesheet";
            //objCSS.href = getStylesheetURL();
            objCSS.type = 'text/css';
            stylesheetObject = objCSS;
        }
    }
    stylesheetObject.href = styleSheetUrl;
    refreshIframe();
    //necessary hack for IE because of page alignment when font size increases.
    setTimeout("help_restoreHelpData()", 10);
}
function getStylesheetURL()
{
    return styleSheetUrl;
}
function m_setStylesheetURL(ssURL)
{
    styleSheetUrl = ssURL;
    refreshStylesheetObjects();
}

function initPageData()
{
    /* The project Navigation and Current Page object need to be
       initialized when the page first loads.
    */
    //alert(app.browser().cssIsEnabled());
    //alert("g_startPageId: " + g_startPageId);
    WebPageLookup.getWebPageByName(callbackPageFunction, g_startPageName);
}

/*function initPageDataMap()
{
    //g_selectedTabIndex = 1;
    WebPageLookup.getWebPageByName(callbackPageFunction, g_mapperPage);
}*/

function callbackPageFunction(webPage)
{
    if(webPage == null)
    {
        alert(g_errorNoPageFound);
        return;
    }
    //alert(currentPage);
    setCurrentPage(webPage);
    //2.  Get the navigational structure:
    WebPageLookup.getMenu(callbackMenuFunction);
}

function callbackMenuFunction(webPageList)
{
    gMenuObject = webPageList;
    /* Once the navigational structure is returned, the application
       may initialize (1) help, (2) the current iFrame, (3) the project
       search, (4) the page title, and (5) the stylesheet.

       Dependencies:  projectSearch.js, help.js, navigation.js, scrollingDiv.js
    */
    app.initNavigation();
    app.initIframe();
    //alert("iframe initialized");
    app.initProjectSearch();
    //alert("project search initialized");
    app.initHelp();
    //alert("help initialized");



    app.initPageTitle();
    //if(currentPage.displayName != g_mapperPage)
    //{
        //after all of the immediate data has been loaded, load the help.
        //alert(currentPage.displayName + " | " + g_mapperPage);
        app.setStylesheetURL(g_defaultStylesheet);
        WebPageLookup.getWebPages(callbackPagesFunction);
    //}
    //else
    //{
    //    app.setStylesheetURL(g_defaultStylesheetMap);
    //}
    firefoxInitAdjustments();

    //
    window.onresize=function(){resizeMenu(g_helpControlName, g_helpSection); resizeMenu(g_searchControlName, g_searchSection); resizeContent(); };
}

function firefoxInitAdjustments()
{
    if(browser.isFirefox())
    {
        getContentContainer().style.height = document.getElementById("menus").clientHeight - 5;
        getContentContainer().parentNode.style.paddingBottom = 1;
    }

}

function callbackPagesFunction(webPageList)
{
    gMenuObject = webPageList;
    //alert("done loading details");
    //app.setCurrentPage(app.getPages().getPageByID(g_startPageId));
    help_restoreHelpData();
    hContainer.hideFooterText(g_helpControlName);
}

function initIframe()
{
    app.browser().removeChildren(getContentContainer());
    showLoadingMessage();
    theIframe = document.createElement("IFRAME");
    theIframe.id = "theIFrame";
    theIframe.frameBorder = 0;
    theIframe.padding = 0;
    getContentContainer().appendChild(theIframe);
    theIframe.height = "100%";
    theIframe.width = "100%";
    /*if(currentProjectId != null)
        theIframe.src = currentPage.url;// + "?tpid=" + currentProjectId;
    else
        theIframe.src = currentPage.url;*/
}

function getIframe()
{
    if(theIframe == null) { theIframe = document.getElementById("theIFrame"); }
    if(theIframe == null) { initIframe(""); }
    return theIframe;
}

function m_loadIframeInternalLink(url, displayName, groupName, id)
{
    currentPage.id = id;
    currentPage.groupName = groupName;
    currentPage.displayName = displayName;
    if(groupName != null && groupName != "")
        pageTitleObject.innerHTML = groupName + " >> " + displayName;
    else
        pageTitleObject.innerHTML = displayName;
    //setCookies();
    for(i=1; i<=navigation_numTabs; i++)
    {
        var lnk = app.browser().getChildren(document.getElementById(i));
        if (lnk.length > 0)
        //alert(lnk[0].innerHTML);// + " - " + groupName);
        if(lnk[0].innerHTML == groupName)
        {
            //alert("selected!");
            activeTab = document.getElementById(i);
            restoreDataAndStyles();
            break;
        }
    }
    //alert(activeTab);
    getIframe().src = url;
    getIframe().title = displayName;
}

function m_loadIframeExternalLink(url, displayName)
{
    currentPage.groupName = "";
    currentPage.displayName = displayName;
    pageTitleObject.innerHTML = displayName;
    getIframe().src = url;
    getIframe().title = displayName;
}

function m_loadIframe(displayName)
{
    activeTab = currentTab;
    app.setCurrentPage(getPages().getPage(displayName));
    if(currentPage.displayName.indexOf(g_mapperPage) >= 0)
    {
        if ($("MapFrameWrapper").src.indexOf(mapHarness) < 0) {
            $("MapFrameWrapper").src = currentPage.url;
            $("MapFrameWrapper").title = currentPage.displayName;
            Position.absolutize($("MapFrameWrapper"));
            Position.clone($("contentSectionCell"),$("MapFrameWrapper"));
        }
        Element.show($("MapFrameWrapper"));
    }
    else
    {
        Element.hide($("MapFrameWrapper"));
        showLoadingMessage();

        //Modified 4/8/08 by SV:  Adding some logic so that the colors,
        //active tabs, and help menu are also updated automatically:

         //page title:
        var theGroup = currentPage.groupName;
        pageTitleObject.innerHTML = theGroup + " >> " +  currentPage.displayName;

        //help text:
        if(currentPage.helpText != null)
        {
            var helpText = currentPage.helpText;
            if(helpText == null){ return; }
            var innerHTML =  helpText.replace("+"," ");
            var parentContainer = document.getElementById(g_helpSection);
            if(parentContainer != null)
            {
                hContainer = new ScrollingDiv(g_helpControlName);
                hContainer.addInnerHtml(parentContainer, unescape(innerHTML));
            }
        }

        //modify styles:
        currentTab = findCurrentTab(currentPage);
        activeTab = currentTab;
        clearTabStyles();
        modifyStyles();

        //load new page:
        if(currentPage.url.indexOf(".do") != -1)
        {
            //document.location.href = currentPage.url;
            if(currentPage.url.indexOf("?") != -1)
                 getIframe().src = currentPage.url + "&dummy=" + Math.random();
            else
                getIframe().src = currentPage.url + "?dummy=" + Math.random();
        }
        else
        {
            if(currentPage.url.indexOf("?") != -1)
                 getIframe().src = currentPage.url + "&dummy=" + Math.random();
            else
                getIframe().src = currentPage.url + "?dummy=" + Math.random();
        }
        getIframe().title = currentPage.displayName;
    }
}

function m_reloadIframe()
{
    //alert("Reloading iframe to: " + currentPage.url + "?dummy=" + Math.random());
    if (currentPage.url.indexOf(mapHarness)<0)
        getIframe().src = currentPage.url + "?dummy=" + Math.random();// + "?tpid=" + tpid;
}

function getHelpContainer()
{
    if(helpContainer == null) { helpContainer = document.getElementById("helpContainer"); }
    return helpContainer;
}

function getPSContainer()
{
    if(psContainer == null) { psContainer = document.getElementById("psContainer"); }
    return psContainer;
}

function getHelpContent()
{
    if(helpContent == null) { helpContent = document.getElementById("helpContent"); }
    return helpContent;
}

function getPSContent()
{
    if(psContent == null) { psContent = document.getElementById("psContent"); }
    return psContent;    
}

function getContentContainer()
{
    if(contentContainer == null)
    {
        contentContainer = document.getElementById("contentSection");
        //give the container some padding:
        //contentContainer.style.padding = 3;
    }
    return contentContainer;
}

function refreshIframe()
{
    showLoadingMessage();
    if(theIframe != null) { theIframe.src = currentPage.url; }
}

function showLoadingMessage()
{
    if(document.getElementById("imgLoaderMessage") != null)
    {
        document.getElementById("imgLoaderMessage").style.visibility = "visible";
    }
    else
    {
        var img = document.createElement("img");
        img.id = "imgLoaderMessage";
        img.src = "images/searching.gif";
        img.style.position = "absolute";
        img.style.top = "200px";
        img.style.left = "500px";
        img.align = "center";
        document.body.appendChild(img);
    }
}
function hideLoadingMessage()
{
    if(document.getElementById("imgLoaderMessage") != null)
    {
        document.getElementById("imgLoaderMessage").style.visibility = "hidden";
    }
}


function resizeMenu(controlName, parentControlName)
{
    //alert("resizeMenu");
    var mOuterDiv = $("outerDiv_" + controlName);
    var parentElement = $(parentControlName);
    if(app.browser().isFirefox())
    {
        mOuterDiv.style.height = parentElement.clientHeight - 55;
    }
    else
    {
        mOuterDiv.style.height = parentElement.clientHeight - 44;
    }
}

function resizeContent()
{
    if(browser.isFirefox())
    {
        //alert("is FF");
        getContentContainer().style.height = document.getElementById("menus").clientHeight - 5;
        getContentContainer().parentNode.style.paddingBottom = 1;
    }
}

function toggleMapMaxRestore() {
    if (app.isMapMax)
        Position.clone($("contentSectionCell"),$("MapFrameWrapper"));
    else
        Position.clone($("mainContainer"),$("MapFrameWrapper"));
    app.isMapMax = !app.isMapMax;
}

function showOnMap(featureClass, identifier) {    
    $("MapFrameWrapper").contentWindow.MapFrame.TextFrameW.showOnMap(featureClass, identifier);
}

function findCurrentTab(currentPage)
{
    for(i=0; i < tabTable.rows[0].cells.length; i++)
    {
        var anchorChildren = app.browser().getChildren(tabTable.rows[0].cells[i]);
        for(j=0; j < anchorChildren.length; j++)
        {
            if(anchorChildren[j].innerHTML == currentPage.groupName)
            {
                anchorMemory = null;
                return app.browser().getParentElement(anchorChildren[j]);
            }
        }
    }
}

