/**
 *  SMT Translate to CWindow Copyright Torge Mönch @ Connectoor.com.
 */

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Dom Ready Function
 * Must be the first
 */
(function(){

    var DomReady = window.DomReady = {};

// Everything that has to do with properly supporting our document ready event. Brought over from the most awesome jQuery.

    var userAgent = navigator.userAgent.toLowerCase();

// Figure out what browser is being used
    var browser = {
        version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1],
        safari: /webkit/.test(userAgent),
        opera: /opera/.test(userAgent),
        msie: (/msie/.test(userAgent)) && (!/opera/.test( userAgent )),
        mozilla: (/mozilla/.test(userAgent)) && (!/(compatible|webkit)/.test(userAgent))
    };
//alert(browser.msie);
    var readyBound = false;
    var isReady = false;
    var readyList = [];

// Handle when the DOM is ready
    function domReady() {
// Make sure that the DOM is not already loaded
        if(!isReady) {
// Remember that the DOM is ready
            isReady = true;

            if(readyList) {
                for(var fn = 0; fn < readyList.length; fn++) {
                    readyList[fn].call(window, []);
                }

                readyList = [];
            }
        }
    };

// From Simon Willison. A safe way to fire onload w/o screwing up everyone else.
    function addLoadEvent(func) {
        var oldonload = window.onload;
        if (typeof window.onload != 'function') {
            window.onload = func;
        } else {
            window.onload = function() {
                if (oldonload) {
                    oldonload();
                }
                func();
            }
        }
    };

// does the heavy work of working through the browsers idiosyncracies (let's call them that) to hook onload.
    function bindReady() {
        if(readyBound) {
            return;
        }

        readyBound = true;

// Mozilla, Opera (see further below for it) and webkit nightlies currently support this event
        if (document.addEventListener && !browser.opera) {
// Use the handy event callback
            document.addEventListener("DOMContentLoaded", domReady, false);
        }

// If IE is used and is not in a frame
// Continually check to see if the document is ready
        if (browser.msie && window == top) (function(){
            if (isReady) return;
            try {
// If IE is used, use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
                document.documentElement.doScroll("left");
            } catch(error) {
                setTimeout(arguments.callee, 0);
                return;
            }
// and execute any waiting functions
            domReady();
        })();

        if(browser.opera) {
            document.addEventListener( "DOMContentLoaded", function () {
                if (isReady) return;
                for (var i = 0; i < document.styleSheets.length; i++)
                    if (document.styleSheets[i].disabled) {
                        setTimeout( arguments.callee, 0 );
                        return;
                    }
// and execute any waiting functions
                domReady();
            }, false);
        }

        if(browser.safari) {
            var numStyles;
            (function(){
                if (isReady) return;
                if (document.readyState != "loaded" && document.readyState != "complete") {
                    setTimeout( arguments.callee, 0 );
                    return;
                }
                if (numStyles === undefined) {
                    var links = document.getElementsByTagName("link");
                    for (var i=0; i < links.length; i++) {
                        if(links[i].getAttribute('rel') == 'stylesheet') {
                            numStyles++;
                        }
                    }
                    var styles = document.getElementsByTagName("style");
                    numStyles += styles.length;
                }
                if (document.styleSheets.length != numStyles) {
                    setTimeout( arguments.callee, 0 );
                    return;
                }

// and execute any waiting functions
                domReady();
            })();
        }

// A fallback to window.onload, that will always work
        addLoadEvent(domReady);
    };

// This is the public function that people can use to hook up ready.
    DomReady.ready = function(fn, args) {
// Attach the listeners
        bindReady();

// If the DOM is already ready
        if (isReady) {
// Execute the function immediately
            fn.call(window, []);
        } else {
// Add the function to the wait list
            readyList.push( function() { return fn.call(window, []); } );
        }
    };

    bindReady();

})();
// DOMREADY END

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * TESTREQUEST
 */
// @method XRequest: Object constructor. As this implements a singleton, the object can't be created calling the constructor, GetInstance should be called instead
function XRequest()
{
    this.XHR = XRequest.CreateXHR();
}

XRequest.instance = null;


// @method static GetInstance: Creates a singleton object of type XRequest. Should be called whenever an object of that type is required.
// @return: an instance of a XRequest object
XRequest.GetInstance = function()
{
    if(XRequest.instance == null)
    {
        XRequest.instance = new XRequest();
    }

    return XRequest.instance;
}

// @method static CreateXHR: Implments a basic factory method for creating a XMLHttpRequest object
// @return: XMLHttp object or null
XRequest.CreateXHR = function()
{
    var xhr = null;
    var factory = [
        function() { return new XMLHttpRequest(); },
        function() { return new ActiveXObject("Msxml2.XMLHTTP"); },
        function() { return new ActiveXObject("Microsoft.XMLHTTP"); }
    ];

    for(var i = 0; i < factory.length; ++i)
    {
        var f = factory[i];
        xhr = f();
        if(xhr)
            return xhr;
    }

    return null;
}

XRequest.prototype.SetRequestHeader = function(name, value)
{
    if(this.XHR)
    {
//alert(name+'|||'+value);
        this.XHR.setRequestHeader(name, value);
    }
}

XRequest.prototype.SendRequest = function(args)
{
    var async = false;
    var type = "";
    var url = "";
    var username = "";
    var password = "";
    var body = null;
    var success = null;
    var failure = null;

    for(e in args)
    {
        switch(e)
        {
            case "async":
                async = args[e];
                break;

            case "type":
                type = args[e];
                break;

            case "success":
                success = args[e];
                break;
            case "failure":
                failure = args[e];
                break;

            case "url":
                url = args[e];
                break;

            case "username":
                username = args[e];
                break;

            case "password":
                password = args[e];
                break;

            case "body":
                body = args[e];
                break;
        }
    }

    var that = this;
    this.XHR.onreadystatechange = function()
    {
//alert("readyState == " + that.XHR.readyState + "  status == " + that.XHR.status);
        if(that.XHR.readyState == 4)
        {
            if(that.XHR.status == 200 || that.XHR.status == 0)
            {
                if(success)
                    success(that.XHR);
            }
            else
            {
                if(failure)
                    failure();
            }
        }
    };

    this.XHR.open(type, url, async, username, password);
    for(e in args)
    {
        switch(e)
        {
            case "setHeader":
                var h = args[e].toString().split(":");
                if(h.length == 2)
                {
                    this.SetRequestHeader(h[0], h[1]);
                }
                break;
        }
    }
    this.XHR.send(body);
}
// TESTREQUEST END


DomReady.ready(function() {

    var nfo = "https://app.connectoor.de/smt/translate/";
    var cwurl = "";

    var je_stellenmarkt = document.getElementsByClassName("je_stellenmarkt");

    var i;
    for (i = 0; i < je_stellenmarkt.length; i++) {

        var embed_id = je_stellenmarkt[i].id;
        var embed_element = je_stellenmarkt[i];

        var x = XRequest.GetInstance();
        x.SendRequest({type:"GET",
            setHeader:"Accept:text/html, image/png, image/!*, *!/!*",
            overrideMimeType:"application/json",
            url: nfo+embed_id+"/",
            success:isSuccess, failure:onFail
        });
    }

    function isSuccess(obj) {
        console.log(obj.responseText);
        embed_element.id = obj.responseText;

        var script = document.createElement('script');
        script.setAttribute('src',cwurl);
        script.setAttribute('type',"application/javascript");
        script.setAttribute('id',"connectoorinit");
        script.setAttribute('defer', '');
        script.setAttribute('async', '');

        var Obj = document.getElementById('je_script');

        Obj.appendChild(script);

    }

    function onSuccess(obj) {
        console.log(obj.responseText);

    }


    function onFail() {
        alert("Leider konnte der Stellenmarkt nicht eingebunden werden. Bitte kontaktieren Sie support@connectoor.com.");
    }



});