/*extern window, document, dhtmlHistory, ort, console */
/*
 * URL fragment handler ajax handler
 * 
 * Usage:
 *
 * This code will hijack any internal URL's on the page when they receive a click
 * event; convert the href to a sensible hash value and then, via ajax, insert
 * the html contained in a particular file into the designated content area.
 *
 * The regular expression run on hrefs is /[^a-z\/_-]/. All other characters
 * are removed. In addition, standard file extensions html|htm|php|asp|jsp|cfm
 * will be removed. This means that the location of your resources will be a
 * transform of the URL that is clicked on. For example, this URL:
 *
 * /this/is/a/url.php
 *
 * will correspond to a hash value of:
 *
 * #/this/is/a/url
 *
 * Using other file extensions will mean that the extension (without a dot) will
 * be lef on the end of the hash unless you edit the regex in the frg.jack function.
 *
 * The function "frg.handler" is the interaction point. If calling from flash
 * you can either call frg.handler directly with the url or set the url # and wait
 * for the listener to poll the hash and call it for you. 
 *
 * Note that if you are setting the hash directly then you need to call
 * it with a value that correctly translates into a resource location.
 * The resource location is determined by the config. For example, if the config
 * has resourceExtension set to ".html" and the resourcePath set to "/my/files/"
 * then setting the hash to #/this-is-a-resource/ will attempt to fetch the content
 * from a file at /my/files/this-is-a-resource.html
 * 
 */



/*
 * This version 26th February 2009
 * patrick@horologe.com.au
 * 
 */


frg = window.frg || {};



/* BEGIN configurable section --------------------------------------------------
 *
 * Config options:
 * 
 * domain:            The domain of the site. This is used to determine
 *                    internal vs external URL's as only internal URL's are hijacked.
 *                    The document.domain is also used for this but you should set
 *                    the domain anyway. This can be a string or a regex. If it's
 *                    a regex be careful to escape /'s.
 *                    
 * contentId:         Determines which element the content is dumped into.
 *
 * fadeClass:         Determines the class of the element which is faded
 * resourceExtension: If resources are in files you can set this extension to be
 *                    appended to the ajax requests.
 *
 * resourcePath:      Determines where content framents are found.
 *
 * defaultFragment:   The fragment to load if there's no # on the url... use this with caution!
 *                    Leave blank to not use a default fragment
 *
 * Note: If you have resources served from a single file you can just set the
 * resourcePath to something like "resources.php?"
 *
 */

frg.config = {  
    "domain": /http:\/\/www.zspace.com.au|http:\/\/www.horologe.com.au|http:\/\/10.68.203.177/, 
    "contentId": "content",
    "fadeClass": "heroCol",
    "resourceExtension": ".html",
    "resourcePath": "fragments",
    "defaultFragment": "",
    "rootFragment": "/home",
    "analytics": "google"
};

/* END configurable section ---------------------------------------------------- */


/* This handles page setup and onload */
(function () {
    
    /*window.dhtmlHistory.create({
        toJSON: function(o) {
                return JSON.stringify(o);
        },
        fromJSON: function(s) {
            return JSON.parse(s);
        }
    });*/
            
    var old = window.onload || function () {};
    window.onload = function(e) {
        var shim;
        frg.jack();
        frg.history();
        frg.loader.setup();
        

        
        if (window.location.hash.length > 0) {
            frg.fetch(window.location.hash.replace("#", ""));
        } else if (!!frg.config.defaultFragment) {
            frg.fetch(frg.config.defaultFragment);
        }
        

        shim = window.swfobject.embedSWF;
        window.swfobject.embedSWF = function (swf, id, w, h, v, ei, fv, parms, attrs) {
            var tw, el, elp;
            
            el = document.getElementById(id);
            el.style.visibility = "hidden";
            el.style.height = "0px";
            elp = el.parentNode;
            elp.style.height = "0px";
            
            tw = new ort.Tween(elp.style, "height", ort.fns.easeInOutQuad, 0, h, 0.6, "px"); 
            tw.start();
            tw.onMotionFinished = function () {
                shim(swf, id, w, h, v, ei, fv, parms, attrs);
                elp.style.visibility = "visible";
                elp.style.height = h + "px";
                
                ort.initAccordion();
                
            };

   
        };
        
        
    };

}());

/* This is the loading animation */
frg.loader = {
    setup: function () {
        frg.loader.img = document.createElement("img");
        frg.loader.img.id = "frg-loader-image";
        frg.loader.img.src = "loading.gif";
        frg.loader.img.style.display = "block";
        frg.loader.hide();
        frg.loader.img.style.position = "absolute";
        frg.loader.img.style.zIndex = "9999";
        //frg.loader.img.style.top = "10px";
        //frg.loader.img.style.left = "220px";
        document.getElementsByTagName("body")[0].appendChild(frg.loader.img);
    },
    show: function () {
        if (typeof frg.loader.img !== "undefined") {
            //frg.loader.img.style.top = (ort.getPageScroll()[1] + 26) + "px";
            frg.loader.img.style.display = "block";
        }
    },
    hide: function () {
        if (!!frg.loader.img) {
            frg.loader.img.style.display = "none";
        }
    }
};


/* Handle URL changes and link clicks. Adds to the history manager
 * if handling a click call from frg.jack */
frg.handler = function (destination, push) {
    var to = ("/" + destination.replace("http://" + document.domain, "").replace(window.location.pathname, "")).replace(/\/\//gi, "/");
    to = to.replace(/\/\//gi, "/");

    frg.fetch(to);
    
};

frg.curl = "";

/* Called by the history + hash manager when change occurs */
frg.listener = function (newLocation, historyData) {
    frg.handler(newLocation, false);
};


/* Instantiates the history manager */
frg.history = function () {
    SWFAddress.onChange = function() {
        frg.listener(SWFAddress.getValue()); 
    }
};

/* Fetch content page fragments and innerHTML's them into content area form config */
frg.fetch = function (resource) {
    var fadeOut,
        fadeIn,
        contentElem = document.getElementById(frg.config.contentId),
        oldContent = contentElem.innerHTML,
        fadeElem = ort.getElementsByClassName(frg.config.fadeClass, contentElem)[0],
        rsr = resource;
        
    frg.injectorCleaner();
        
    document.body.className = document.body.className.replace(/fragger-fl/gi, "");
    if (resource === "/") {
        resource = frg.config.rootFragment;
    }
    // hide content
    if (fadeElem) {
        fadeOut = new ort.OpacityTween(fadeElem, ort.fns.easeInOutQuad, 100, 0, 1);
        frg.loader.show();
        fadeOut.start();
    }
    

    ort.xhr("GET", (frg.config.resourcePath + resource + frg.config.resourceExtension).replace("/.", "."), function (res) {
        
        
        var pageFragment = res.responseText,
            pageScripts = res.responseText.match(/<script[^>]*>[^<]*<\/script>/gi) || [];
            
        // track
        if (!!frg.config.analytics) {
            if (frg.config.analytics === "google" && pageTracker && typeof pageTracker._trackPageview === "function") {
                pageTracker._trackPageview((frg.config.resourcePath + rsr + frg.config.resourceExtension).replace("/.", "."));
            }
        }
            
        pageFragment = pageFragment.replace(/<script[^>]*>[\s\S]*<\/script>/gi, "");
             
        
        if (fadeElem) {
            fadeOut.fforward();
        }
        
        
        contentElem.innerHTML = res.responseText;

        document.body.className = document.body.className.replace(/frg-[^\s]*/gi, "");
        document.body.className += " frg-" + resource.replace(/[^a-z0-9_-]/gi, "") + " ";
        fadeElem = ort.getElementsByClassName(frg.config.fadeClass, contentElem)[0];
        if (fadeElem) {
            fadeIn = new ort.OpacityTween(fadeElem, ort.fns.easeInOutQuad, 0, 100, 1);
            fadeIn.start(); 
        }
        
        (function () {
            var jj, scriptToEval;
            for (jj = 0; jj != pageScripts.length; jj++) {
                scriptToEval = pageScripts[jj].replace(/<[\/]*script[^>]*>/gi, "");
                if (window.execScript) {
                    window.execScript(scriptToEval);
                } else {
                    eval.call(window, scriptToEval);
                }
            }
        }());

        frg.loader.hide();
            
        window.scrollTo(0,0);
    }, "", function () {
        document.body.className = document.body.className.replace(/fragger-fl/gi, "");
        contentElem.innerHTML = oldContent;
        if (typeof console !== "undefined") { console.log("Error fetching fragment"); }
        fadeElem = ort.getElementsByClassName(frg.config.fadeClass, contentElem)[0];
        if (fadeElem) {
            fadeOut.fforward();
            fadeIn = new ort.OpacityTween(fadeElem, ort.fns.easeInOutQuad, 0, 100, 1);
            fadeIn.start();
        }
        frg.loader.hide();
        
    });
};

/* Intercept the onclick event when the target is an "a" element with an internal URL */
frg.jack = function () {
    var old = document.onclick || function () {};
    document.onclick = function (e) {
        var ev = e || window.event,
            target = ev.target || ev.srcElement;
            if (ev.button && ev.button === 2) {
                return;
            }
            if (target && target.nodeName.toLowerCase() == "a") {
                if (target.href.indexOf("mailto:") >= 0) {
                    return;
                }
                if (target.href && (frg.config.domain.test(target.href) || !/^http/.test(target.href))) {
                    SWFAddress.setValue(target.href.replace(frg.config.domain, "").replace(/[^a-z0-9\/_-]/gi, "").replace(/(html|htm|php|asp|jsp|cfm)$/, ""));
                    if (typeof ev.PreventDefault == "function" && typeof ev.stopPropagation == "function") {
                        ev.preventDefault();
                        ev.stopPropagation();
                    }
                    ev.cancelBubble = true;
                    ev.returnValue = false;
                    old(e);
                    return false;
                } else {
                    // external link
                    old(e);
                    return true;
                }
            
            }    
    };
};

frg.lastInjected = null;

frg.inject = function (parenId, fragmentConfig) {
    var paren = document.getElementById(parenId),
        newElem = document.createElement(fragmentConfig.elem),
        oldElem = document.getElementById(fragmentConfig.id),
        oldF = window.onload || function () {};
        
        if (oldElem && oldElem.parentNode) {
            oldElem.parentNode.removeChild(oldElem);
        }
        
        newElem.className = fragmentConfig.klass;
        newElem.innerHTML = fragmentConfig.text;
        newElem.id = fragmentConfig.id;
        
        frg.lastInjected = newElem;
        
        if (paren) {
            paren.appendChild(newElem);
        }
};

frg.injectorCleaner = function () {
    if (frg.lastInjected && frg.lastInjected.parentNode) {
        frg.lastInjected.innerHTML = "";
        frg.lastInjected.parentNode.removeChild(frg.lastInjected);
        frg.lastInjected = null;
    }
};
