var BF_MODULES_DOMAIN = "builderfusion.westfloridabuilders.com";

/**************************** LOGIN / MEMBERS ONLY ***************************/

var LOGIN_PAGE = "/member-login.html";


/*

Put a call to this function in the top/head of any page that requires that the user
is logged in:

    <script> isLoggedIntoBF(); </script>

*/

function isLoggedIntoBF()
{
    var loginURL = LOGIN_PAGE + "?forwardURL=" + escape(window.location.href);

    var bfweb = getCookie("BFWEB");
    if(!bfweb || bfweb.length==0 || bfweb.indexOf("|")<=0)
    {
        window.location.href = loginURL;
    }
    
    if (top != window) 
    {
        top.location.replace(window.location.href);
    }
}

/*

Put a call to this function anywhere on the page that displays the BF Login 
Module in the "memberFrame" IFRAME:

    <script> loginOnLoad(); </script>

*/

function loginOnLoad()
{
    if(window.attachEvent)
    {
        window.attachEvent("onload", function(i) { initializeLogin(); });
    }
    else
    {
        window.addEventListener("load", function(){ initializeLogin(); }, false); 
    }
}

/*

This function is called from the loginOnLoad function.

This function gets any applicable parameters from the query string
of the URL and then updates the "memberFrame" IFRAME with the 
appropriate URL.

    forwardURL : If the isLoggedInBF function determines that the 
                 user is not logged in, then it redirects to the
                 login page that contains the memberFrame.  This
                 parameter is added to the login module URL in that
                 frame.
                 
    loginError : If the username/password entered on the login module
                 is invalid, the module redirects back to this page
                 with the login module loaded in the memberFrame.
                 This parameter is added to the login module URL.

    forgotLogin: The value of this parameter will become the URL of the
                 memberFrame.
    

If there are no applicable parameters, then the memberFrame will go 
to the BF members only module.

*/

function initializeLogin(fURL)
{
    var x = window.location.search;
    var loginError = false;
    var forgotLogin = false;
    var forwardURL = "";
    if(x)
    {
        if(x.substring(0,1)=="?")
            x = x.substring(1);
    
        var params = x.split("&");
        if(params && params.length>0)
        {
            for(var i=0; i<params.length; i++)
            {
                if(params[i].indexOf("forwardURL=")==0)
                {
                    var vals = params[i].split("=");
                    forwardURL = unescape(vals[1]);
                }
                
                if(params[i].indexOf("loginError=")==0)
                {
                    var vals = params[i].split("=");
                    loginError = vals[1]=="true";
                }
                
                if(params[i].indexOf("forgotLogin=")==0)
                {
                    var vals = params[i].split("=");
                    forgotLogin = vals[1]=="true";
                }
            }
        }
    }
    
    if(!forwardURL)
        forwardURL = fURL;
        
    var bfweb = getCookie("BFWEB");
    var isLoggedIn = bfweb && bfweb.length>0 && bfweb.indexOf("|")>0;
     
    var purl = window.location.href.lastIndexOf("#")==-1 ? window.location.href : window.location.href.substring(0,window.location.href.lastIndexOf("#"));

    purl += "#bf_memberFrame";
    
    var url = "";
    
    if(loginError)
    {
        var url = "http://" + BF_MODULES_DOMAIN + "/bf/website/simple/login.jsp?forwardURL=" + escape("/bf/website/simple/members/index.jsp") + "&loginError=true";
    }
    
    else if(forgotLogin)
    {
        var url = "http://" + BF_MODULES_DOMAIN + "/bf/website/simple/forgotPassword.jsp";
    }
    
    else if(forwardURL)
    {
        var url = "http://" + BF_MODULES_DOMAIN + "/bf/website/simple/login.jsp?forwardURL=" + escape(forwardURL);
    }
    else if(isLoggedIn)
    {
        var url = "http://" + BF_MODULES_DOMAIN + "/bf/website/simple/members/index.jsp";
    }
    else
    {
        forwardURL = "http://" + BF_MODULES_DOMAIN + "/bf/website/simple/members/index.jsp?purl=" + escape(purl);
        var url = "http://" + BF_MODULES_DOMAIN + "/bf/website/simple/login.jsp?forwardURL=" + escape(forwardURL);
    }

    url += (url.indexOf("?")==-1?"?":"&") + "purl=" + escape(purl);

    var f = document.getElementById("frame_memberFrame");

    if(f)
    f.src = url;
}

/******************************** DIRECTORY **********************************/

function goToDirectory(frameName, params)
{
    // "var url" and "var monthViewURL" need to be changed to the domain of the site you are working on
    var x = window.location.search;
    var url = "http://" + BF_MODULES_DOMAIN + "/bf/website/directory/index.jsp";

    if(x && x.substring(0,1)=="?")
        x = x.substring(1);

    if(params && (params.substring(0,1) == "?" || params.substring(0,1) == "&"))
        params = params.substring(1);
    
    if(params)
    {
        if(x)
            x += "&" + params;
    else
        x = params;
    }
        

    
    if(x)
        url += "?" + x;


    if(!frameName)
        frameName = "dirFrame";

    
    purl = window.location.href.lastIndexOf("#")==-1 ? window.location.href : window.location.href.substring(0,window.location.href.lastIndexOf("#"));

    purl += "#bf_" + frameName;
    
    url += (url.indexOf("?")==-1?"?":"&") + "purl=" + escape(purl);
    

    var f = document.getElementById("frame_"+frameName);

    if(f)
    {
        f.src = url;
    }
    else if(window[frameName])
    {
        window[frameName].location.href=url;
    }
    else
    {
        //You specified the wrong frame name
    }
}


/********************************* CALENDAR **********************************/

/*

Put a call to this function anywhere on the page that displays the BF Calendar 
Module in the "calFrame" IFRAME:

    <script> calendarOnLoad(); </script>

*/

function calendarOnLoad()
{
    if(window.attachEvent)
    {
        window.attachEvent("onload", function(i) { goToCalendar("calFrame"); });
    }
    else
    {
        window.addEventListener("load", function(){ goToCalendar("calFrame"); }, false); 
    }
}

/*

This function is called from the calendarOnLoad function.  If there is an
"event_id" parameter on the query string of the URL of the HTML page, then
that parameter is added to the BF Calendar Module URL.

*/

function goToCalendar(frameName,monthView)
{
    // "var url" and "var monthViewURL" need to be changed to the domain of the site you are working on
    var x = window.location.search;
    var url = "http://" + BF_MODULES_DOMAIN + "/bf/website/simple/calendar.jsp";
    var monthViewURL = "http://" + BF_MODULES_DOMAIN + "/bf/website/simple/monthView.jsp";
    var eventId = 0;

    if(x && x.indexOf("event_id")>-1)
    {
        if(x.substring(0,1)=="?")
            x = x.substring(1);

        var params = x.split("&");
        if(params && params.length>0)
        {
            for(var i=0; i<params.length; i++)
            {
                if(params[i].indexOf("event_id=")==0)
                {
                    var vals = params[i].split("=");
                    eventId = parseInt(vals[1]);
                }
            }
        }
    }


    if(!frameName)
        frameName = "calFrame";

    if(eventId > 0)
    {
        url += "?page=eventDetails.jsp&event_id=" + eventId;
    }
    else if(monthView)
    {
        url = monthViewURL;
    }
    
    purl = window.location.href.lastIndexOf("#")==-1 ? window.location.href : window.location.href.substring(0,window.location.href.lastIndexOf("#"));

    purl += "#bf_" + frameName;
    
    url += (url.indexOf("?")==-1?"?":"&") + "purl=" + escape(purl);
    
    var f = document.getElementById("frame_"+frameName);

    if(f)
    {
        f.src = url;
    }
    else if(window[frameName])
    {
        window[frameName].location.href=url;
    }
    else
    {
        //You specified the wrong frame name
    }
}

function getUpcomingEventsURL(calendarPage,target,limit)
{
    var url = "http://" + BF_MODULES_DOMAIN + "/bf/website/simple/upcomingEvents.jsp?target=" 
        + (target?target:"_top") + "&calendarURL=" 
        + escape("http://" + window.location.hostname + (calendarPage.indexOf("/")==0?"":"/") 
        + calendarPage) + (limit?"&limit=" + limit : "");
        
    return url;
}


/************************************** RANDOM ADS *************************************/

var RANDOM_ADS_ID = "randomAds";

/*

Put a call to this function in the top/head of any page that displays randoms ads in an
HTML tag with an ID of RANDOM_ADS_ID:

    <script> ramdomizeAdsOnLoad(); </script>

*/

function ramdomizeAdsOnLoad()
{
    if(window.attachEvent)
    {
        window.attachEvent("onload", function(i) { randomizeAds(); });
    }
    else
    {
        window.addEventListener("load", function(){ randomizeAds(); }, false); 
    }
}

/*

This function is called from the randomizeAdsOnLoad function.

*/

function randomizeAds()
{
    var div = document.getElementById(RANDOM_ADS_ID);
    if(div)
    {
        var ads = div.getElementsByTagName("a");
        var numberOfAds = ads.length;
        var randomAds = new Array(numberOfAds);
        var hasIndex = new Object();

        for(var i=0; i<numberOfAds; i++)
        {
            var randomIndex = Math.floor(numberOfAds*Math.random());
            while(hasIndex[randomIndex])
                randomIndex = Math.floor(numberOfAds*Math.random());

            randomAds[randomIndex] = ads[i];
            hasIndex[randomIndex] = true;
        }

        for(var i=0; i<numberOfAds; i++)
        {
            var ad = randomAds[i];
            div.removeChild(ad);
            div.appendChild(ad);
        }

        div.style.display = "inline";
    }
}

/****************************** RESIZE IFRAMES *******************************/
/*
    DYNAMICALLY CHANGE IFRAME HEIGHT BASED ON THE CONTENT IN THE IFRAME
    Copyright (c) 2008 BuilderFusion, Inc.
    
    Written by Jason LuBean
    
    Installation
    
    1.  Include this JavaScript file on the page where you have at least one IFRAME tag that 
        you want the height to be resized, based on the height of the content in the IFRAME tag.
    
    2.  Invoke the "bfResizeIframe" function once on the page.  This function will check every 10
        millisecond to see if there is a hash at the end of the URL in the form 
        "#bf_frameName_frameHeight" where "frameName" is replaced with the IFRAME name and
        "frameHeight" is replaced with the height (in pixels) of the page (an integer).  If that
        hash exists and the corresponding IFRAME exists, it will set the height of the FRAME.
    
    3.  For each IFRAME you want resized, insert a DIV tag in the HTML where you want to the IFRAME
        to be inserted.  Specify an ID for that tag.  There is no need for any content to be in the
        DIV tag because the code MUST dynamically add the IFRAME tag in the DIV tag in order for 
        the browser to allow the code resize the IFRAME.  After the DIV tag (or in the window.onload),
        invoke the "bfLoadResizeIframe" function:
        
             <div id="__ID__"></div>
             <script>
                var frameName = "dirFrame";
                var frameURL = "http://demo.builderfusion.com/bf/website/directory/index.jsp";
                var frameWidthPixels = 700;  
                var frameHeightPixels = 200; 
                bfLoadResizeIframe(frameName,frameURL,frameWidthPixels,frameHeightPixels);
             </script>
    4.  For each URL that is displayed in an IFRAME tag, attach/add an "onload" event listener
        (see "bfResizeParentFrameOnLoad" function) that does the following (if the "purl" 
        parameter exists on the query/search string):
        
            1.  Get the height of the page ("document.height" for Firefox; 
                "document.body.scrollHeight" for IE)
            2.  Get the "purl" value from the query string.  It will end with a hash in the form 
                "#bf_frameName" where "frameName" is replaced with the actual name of the IFRAME.
            3.  Modify the "purl" value to include a hash at the end in the form 
                "#bf_frameName_frameHeight" where "frameName" is replaced with the IFRAME name and
                "frameHeight" is replaced with the height (in pixels) of the page (an integer)
            4.  Set "window.top.location" to the modified "purl" value.
            
    The page including this script will 

    This code has been tested in IE 7.0 and Firefox 2.0.
    

*/

var bfIframes = new Object();

function bfResizeIframe()
{

    window.setInterval(
        function()
        {
            if(window.location.hash && window.location.hash!="#" && window.frames && window.frames.length>0)
            {
                var x = window.location.hash.substring(1);
                if(x.indexOf("bf_")==0)
                {
                    var parts = x.split("_");
                    if(parts.length == 3)
                    {
                        var frameName = parts[1];
                        var y = parseInt(parts[2]);
                        if(!isNaN(y) && y > 0)
                        {
                            var frameHeight = y + "px";

                            var frameRef = bfIframes[frameName];

                            if(frameRef)
                            {
                                frameRef.height = frameHeight;
                            }

                        }

                    }
                }
            }
        }
        ,10
    );
}

function bfLoadResizeIframe(frameName,frameURL,frameWidth,frameHeight)
{
    var frameDiv=document.getElementById(frameName);

    if(frameDiv)
    {
        var purl = window.location.href.lastIndexOf("#")==-1 ? window.location.href : window.location.href.substring(0,window.location.href.lastIndexOf("#"));

        purl += "#bf_" + frameName;

        var url = frameURL ? (frameURL + (frameURL.indexOf("?")==-1?"?":"&") + "purl=" + escape(purl)) : "";

        var frameRef=document.createElement("iframe");
        var h={
            name:frameName,
            src:url,
            frameBorder:0,
            width:frameWidth,
            height:frameHeight,
            marginWidth:"0",
            marginHeight:"0",
            hspace:"0",
            vspace:"0",
            allowTransparency:"true",
            scrolling:"no"
        };
        for(var o in h)
        {
            frameRef.setAttribute(o,h[o])
        }

        if(frameRef.attachEvent)
        {
            frameRef.attachEvent("onload",
                function(i)
                {
                    window.scrollTo(0,0)
                }
            )
        }
        else
        {
            frameRef.addEventListener("load",
            function(){
            window.scrollTo(0,0)},
            false)
        }
        
        frameRef.id = "frame_" + frameName;

        frameDiv.appendChild(frameRef);

        bfIframes[frameName] = frameRef;
    }
}

/* FUNCTIONS FOR PAGES IN IFRAME */

function bfGetURLParams()
{
    var params = new Object();
    var search = location.search;
    if(search.indexOf("?") == 0)
    {
        var parts = search.substring(1).split("&");
        for(var i=0; i<parts.length; i++)
        {
            var part = parts[i];
            var pieces = parts[i].split("=");
            if(pieces.length==2)
            {
                params[pieces[0]] = unescape(pieces[1]);
            }
        }
    }
    
    return params;
}


function bfResizeParentFrame()
{
    var params = bfGetURLParams();
    var purl = params["purl"];

    if(purl)
    {
        var hashIndex = purl.lastIndexOf("#");
        var hash = hashIndex == -1 ? "" : purl.substring(hashIndex+1);
        purl = hashIndex == -1 ? purl : purl.substring(0,hashIndex);
        var parts = hash.split("_");
        var frameName = "";
        if(parts[0] == "bf" && parts.length>1)
            frameName = parts[1];
            
        if(frameName && parent != window && parent == top)
        {
            var frameHeight = document.height;
            if(!frameHeight)
                frameHeight = document.body.scrollHeight;
            window.top.location = purl + "#bf_" + frameName + "_" + frameHeight;
        }
    }
}

function bfResizeParentFrameOnLoad()
{
    if(window.attachEvent)
    {
        window.attachEvent("onload", function(i) { if(bfResizeParentFrame) bfResizeParentFrame(); });
    }
    else
    {
        window.addEventListener("load", function(){ if(bfResizeParentFrame) bfResizeParentFrame(); }, false); 
    }
}

/****************************** UTILITY FUNCTIONS ****************************/

function getCookie(label) 
{
    var labelLen = label.length;
    var cLen = document.cookie.length;
    var i = 0;
    while (i < cLen) {
        var j = i + labelLen;
        if (document.cookie.substring(i,j) == label) {
            var cEnd = document.cookie.indexOf(";",j);

            if (cEnd == -1)
                cEnd = document.cookie.length;


            return unescape(document.cookie.substring(j+1,cEnd));
        }

        i++;
    }

    return "";
}

