﻿blogfrog = window.blogfrog || {};
var currentBFframe;

blogfrog.FullV1 = function(_data) {
    currentBFframe = this;
    this.config = { domain: "iframe.theblogfrog.com" };
    for (var key in _data)
        this.config[key] = _data[key];

    this.supportsCrossWindowMessaging = window.postMessage != 'undefined';
    this.faceboxLoaded = false;
    this.onJqueryLoadedCallbacks = [];
    this.bottomBuffer = 75;                // Bottom "overflow" Buffer
    var firstLoad = true;
    var ignoreHashChange = false;
    var backForwardCount = 0;

    this.scrollTop = function() {
        var viewportY = jQuery(window).scrollTop();
        var iframeTop = jQuery('#bf-iframe').offset().top;
        if (viewportY > iframeTop) {
            jQuery('html,body').animate({ scrollTop: iframeTop }, 250);
        }
    }

    this.onPostMessage = function(e) {
        if (e.origin.indexOf(this.config.domain) < 0)
            return;

        log('iframe parent: ' + e.data);

        if (e.data.substr(0, 8) == "bf-ready") {
            // document.getElementById("bf-iframe").height = "0px";
            // window.scroll(0, 0);
            document.getElementById("bf-iframe").contentWindow.postMessage("bf-get-height:", "*");
            if (firstLoad)
                document.getElementById("bf-iframe").contentWindow.postMessage("bf-link-base:" + window.location.href, "*");

            // Code to run after jQuery has been loaded
            var jQueryLoaded = function() {
                includeFacebox();
                // Fire off any callbacks that have been registered then clear queue
                var cbs = currentBFframe.onJqueryLoadedCallbacks;
                for (var i = 0; i < cbs.length; i++) {
                    try {
                        cbs[i]();
                    } catch (ex) { }
                    currentBFframe.onJqueryLoadedCallbacks = [];
                }
                //currentBFframe.scrollTop();
            }

            // Check for existance of jQuery
            if (typeof (jQuery) == "undefined" || jQuery("*") === null) {
                var jq = document.createElement('script');
                jq.type = 'text/javascript';
                jq.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js';
                document.getElementsByTagName('head')[0].appendChild(jq);
                jQueryNoConflict(jQueryLoaded);
            } else {
                jQueryLoaded();
            }

            if (firstLoad) {
                firstLoad = false;
            } else {
                if (e.data.length > 9) {
                    ignoreHashChange = true;
                    var url = e.data.substr(9);
                    location.replace("#" + url);
                    ignoreHashChange = false;
                }
                document.getElementById("bf-iframe").contentWindow.postMessage("bf-link-base:" + window.location.href, "*");
            }
        }
        else if (e.data.substr(0, 13) == "bf-set-height") {
            var newHeight = Number(e.data.substr(14).replace('px', '')) + this.bottomBuffer;
            document.getElementById("bf-iframe").height = newHeight + 'px';
        }
        else if (e.data.substr(0, 11) == "bf-set-url:" && backForwardCount < 10) {
            // The page url can get out of sync with the iframe url
            // when the back/forward buttons are used on some browsers.
            var url = e.data.substr(11);
            var currentLoc = location.hash.substr(1);
            if (currentLoc == "")
                currentLoc = "/" + this.config.commid;
            if (url != currentLoc) {
                // pages out of sync, for update of iframe
                backForwardCount++;
                window.frames["bf-iframe"].location.replace("http://" + this.config.domain + currentLoc);
            }
        }
        else if (e.data.substr(0, 11) == "bf-facebox:") {
            jQuery.facebox(e.data.substr(11));
        }
        else if (e.data.substr(0, 26) == "bf-facebox-unbind-overlay:") {
            jQuery.facebox(e.data.substr(26));
            $('#facebox_overlay').unbind('click');
        }
        else if (e.data.substr(0, 17) == "bf-facebox-close:") {
            document.getElementById('facebox_close_button').click();
        }
        else if (e.data.substr(0, 14) == "bf-scroll-top:") {
            if (typeof (jQuery) == 'undefined') {
                this.onJqueryLoadedCallbacks.push(currentBFframe.scrollTop);
            }
            else {
                currentBFframe.scrollTop();
            }

        }
        else if (e.data.substr(0, 13) == "bf-scroll-to:") {
            var scrollTo = 0;
            try { scrollTo = Number(e.data.substr(13)); } catch (ex) { }
            if (scrollTo > 0) {
                // Add the offset of the iframe to whatever the scroll-to location is
                var scrollToReply = function() {
                    scrollTo += jQuery('#bf-iframe').offset().top - 60;  // + top margin
                    jQuery("html, body").animate({
                        scrollTop: scrollTo
                    }, 1000);
                }
                // If jQuery isn't present, add it to the list of funcs to be fired on jquery's loading
                if (typeof (jQuery) == 'undefined') {
                    this.onJqueryLoadedCallbacks.push(scrollToReply);
                }
                else {
                    scrollToReply();
                }
            }
        }
        else if (e.data.substr(0, 14) == "bf-link-click:") {
            if (currentBFframe.config.fullpageload != 'undefined' && currentBFframe.config.fullpageload == true) {
                var loc = currentBFframe.config.basecommurl + "#" + encodeURIComponent(e.data.substr(14));
                document.location = loc;
            }
            else {
                document.getElementById("bf-iframe").height = "0px";
                if (this.loadingImg != null) {
                    this.loadingImg.style.display = "";
                }
            }
        }

    };

    this.hashChangeFunc = function() {
        if (!ignoreHashChange)
            document.getElementById("bf-iframe").contentWindow.postMessage("bf-get-url:", "*");
    };

    this.render = function() {
        log('iframe parent: render');

        var t = this;
        if (typeof window.addEventListener != 'undefined') {
            window.addEventListener('message', function(e) { t.onPostMessage(e); }, false);
            window.addEventListener('hashchange', function(e) { t.hashChangeFunc(); }, false);
        } else if (typeof window.attachEvent != 'undefined') {
            window.attachEvent('onmessage', function(e) { t.onPostMessage(e); });
            window.attachEvent('onhashchange', function(e) { t.hashChangeFunc(); });
        }

        this.bfContainer = document.getElementById('blogfrog-content');
        if (this.bfContainer == null) {
            // Create it if it doens't already exist
            document.write('<div id="blogfrog-content"></div>');
            this.bfContainer = document.getElementById('blogfrog-content');
        }

        var page;
        if (document.location.hash && document.location.hash != "" && document.location.hash != "#") {
            if (document.location.hash.substr(0, 1) == "#")
                page = "http://" + this.config.domain + decodeURIComponent(document.location.hash.substr(1));
            else
                page = "http://" + this.config.domain + decodeURIComponent(document.location.hash);
        } else {
            var qs = this.getQueryStringValue("bfurl");

            if (qs == "")
                page = "http://" + this.config.domain + "/" + this.config.commid;
            else
                page = "http://" + this.config.domain + decodeURIComponent(qs);
        }

        var e = document.createElement('iframe');
        e.id = 'bf-iframe';
        e.name = 'bf-iframe';
        e.src = page;
        e.width = '100%';
        e.style.borderStyle = "none";
        e.frameBorder = "0";

        // If the broswer supports HTML5 cross window messaging, we'll pass messages
        // back and forth to correctly size the iframe.  Otherwise, the iframe will have
        // a static size with scroll bars.
        if (this.supportsCrossWindowMessaging) {
            /* this.loadingImg = document.createElement('div');
            this.loadingImg.id = 'bf-iframe-loading';
            var tmpImg = document.createElement('img');
            tmpImg.src = "http://" + this.config.domain + "/img/loading.gif";
            this.loadingImg.appendChild(tmpImg);
            this.bfContainer.appendChild(this.loadingImg); */
            e.height = getViewportHeight() + 'px';
            e.scrolling = "no";
        }
        else {
            e.height = '600px';
        }

        this.bfContainer.style.border = "none";
        this.bfContainer.style.width = "100%";
        this.bfContainer.style.textAlign = "center";
        this.bfContainer.appendChild(e);
    };

    this.getQueryStringValue = function(_key) {
        var assoc = new Array();
        var queryString = location.search.substring(1);
        if (queryString == 'undefined' || queryString.length == 0)
            return "";
        var keyValues = queryString.split('&');
        for (var i in keyValues) {
            var keyVal = keyValues[i].split('=');
            if (keyVal[0] == _key)
                return keyVal[1];
        }
        return "";
    }


}

var getViewportHeight = function() {
    if (typeof (window.innerHeight) !== 'undefined') {
        return window.innerHeight;
    }
    else if (typeof (document.documentElement) !== 'undefined') {
        return document.documentElement.clientHeight;
    }
    else {
        return document.getElementsByTagName('body')[0].clientHeight;
    }
}

var jQueryNoConflict = function(onLoaded) {
    if (typeof (jQuery) == "undefined") {
        setTimeout(function() { jQueryNoConflict(onLoaded); }, 100);
        return;
    }
    jQuery.noConflict(false);
    if (typeof (onLoaded) == 'function') {
        onLoaded();
    }
}

function includeFacebox() {
    var fbcss = document.createElement('link');
    fbcss.href = 'http://theblogfrog.com/facebox/facebox-min.css';
    fbcss.rel = 'stylesheet';
    fbcss.type = 'text/css';
    document.getElementsByTagName('head')[0].appendChild(fbcss);

    var fbjs = document.createElement('script');
    fbjs.type = 'text/javascript';
    fbjs.src = 'http://theblogfrog.com/facebox/facebox-min.js';
    document.getElementsByTagName('head')[0].appendChild(fbjs);
}

// Safe console logging
window.log = function() {
    if (window.location.href.substring(0, 12) === 'http://local') {
        log.history = log.history || [];   // store logs to an array for reference
        log.history.push(arguments);
        if (this.console) {
            console.log(Array.prototype.slice.call(arguments));
        }
    }
};

