﻿var ZARTIS;
if (ZARTIS == undefined) {
    ZARTIS = {};
}

if (!ZARTIS.initialized) {

    ZARTIS.initialized = true;
}

function foo(data) {
    var jobs = data;
    var jobsHTML = [];
    ZARTIS.functions.forEach(jobs.results, function (item, i) {
        jobsHTML.push(ZARTIS.functions.complileTemplate(ZARTIS.functions.options.jobTemplate, item));
    });

    var html = jobsHTML.join('');

    html = "<div id='jobs_iframe' class='hh-list'>" + html + "</div>";

    // Client wants an in page iframe
    if (ZARTIS.functions.options.container) {
        // They have passed in an id, insert content here...
        var container_el = document.getElementById(ZARTIS.functions.options.container);
        container_el.innerHTML = html;
    } else if (document.getElementById("hh-widget") != null) {
        var scriptTag = document.getElementById("hh-widget");
        scriptTag.insertAdjacentHTML('afterend', html);
    }
    else {
        // no id given, find the script tag and add it after
        var scriptTag = document.querySelector('script[src$="/getwidget"]');

        if (scriptTag == null)
            scriptTag = document.querySelector('script[src*="/getwidget"]');

        scriptTag.insertAdjacentHTML('afterend', html);
    }
}

ZARTIS.jobs_widget = function (options) {

    // Create the <style> tag
    var style = document.createElement("style");
    // WebKit hack :(
    try {
        style.appendChild(document.createTextNode(""));
        // Add the <style> element to the page
        document.head.appendChild(style);
    }
    catch (ex) {
        document.getElementsByTagName('head')[0].appendChild(style);
    }

    var sheet = style.sheet || style.styleSheet;

    ZARTIS.functions.addCSSRule(sheet, ".hh-list-row", "float: left; display: block; border-bottom: 1px solid #ccc; padding: 15px 0 15px 0; width: 100%; text-align: left;");
    ZARTIS.functions.addCSSRule(sheet, ".hh-list-row:first-child", "border-top: 1px solid #ccc;");

    ZARTIS.functions.addCSSRule(sheet, ".hh-list-title", "float:left; width: 50%; font-weight: bold;");
    ZARTIS.functions.addCSSRule(sheet, ".hh-list-location", "float: left; width: 30%; margin-left: 2.5%;");
    ZARTIS.functions.addCSSRule(sheet, ".hh-list-type", "float: right; width: 15%; margin-left: 2.5%;text-align:right;");
    // Create option defaults
    options = options ? options : {};

    options.jobTemplate = options.jobTemplateSelector ? document.querySelectorAll(options.jobTemplateSelector)[0].innerHTML.trim() : '<a class="hh-list-row" href="{{Link}}" target="{{Target}}"><span class="hh-list-title">{{Title}}</span> <span class="hh-list-location">{{Location}}, {{StateCode}}{{Country}}</span> <span class="hh-list-type">{{Type}}</span></a>';

    ZARTIS.functions.options = options;

    var request = new XMLHttpRequest();
    try {
        request.open('GET', encodeURI("https://my.hirehive.io/api/public/search?cname=" + options.company), true);
    }
    catch (ex) {
        var script = document.createElement('script');
        script.src = "https://my.hirehive.io/api/public/search?cname=" + options.company + "&callback=foo";

        document.getElementsByTagName('head')[0].appendChild(script);
    }

    request.onreadystatechange = function () {
        if (this.readyState === 4) {
            if (this.status >= 200 && this.status < 400) {
                // Success!
                var jobs = JSON.parse(this.responseText);
                var jobsHTML = [];
                ZARTIS.functions.forEach(jobs.results, function (item, i) {
                    jobsHTML.push(ZARTIS.functions.complileTemplate(options.jobTemplate, item));
                });

                var html = jobsHTML.join('');

                html = "<div id='jobs_iframe' class='hh-list'>" + html + "</div>";

                // Client wants an in page iframe
                if (options.container) {
                    // They have passed in an id, insert content here...
                    var container_el = document.getElementById(options.container);
                    container_el.innerHTML = html;
                } else if (document.getElementById("hh-widget") != null) {
                    var scriptTag = document.getElementById("hh-widget");
                    scriptTag.insertAdjacentHTML('afterend', html);
                }
                else {
                    // no id given, find the script tag and add it after
                    var scriptTag = document.querySelector('script[src$="/getwidget"]');
                    if (scriptTag == null)
                        scriptTag = document.querySelector('script[src*="/getwidget"]');
                    scriptTag.insertAdjacentHTML('afterend', html);
                }

            } else {
                console.log('Request failed.  Returned status of ' + this.status);
                console.log('Using jsonp fallback');
                var script = document.createElement('script');
                script.src = "https://my.hirehive.io/api/public/search?cname=" + options.company + "&callback=foo";

                document.getElementsByTagName('head')[0].appendChild(script);
            }
        }
    };

    request.onerror = function () {
        //do what you want on error
        console.log("error");
    };

    request.send();
    request = null;

};

ZARTIS.functions = {
    options: {},

    complileTemplate: function (template, job) {
        template = template.replace(/{{Title}}/g, job.title);
        template = template.replace(/{{Link}}/g, job.jobUrl);
        template = template.replace(/{{Location}}/g, job.location);
        template = template.replace(/{{Country}}/g, job.countryName);
        template = template.replace(/{{Type}}/g, job.type);

        if (job.stateCode && job.stateCode.length > 0) {
            template = template.replace(/{{StateCode}}/g, job.stateCode + ", ");
        }
        else {
            template = template.replace(/{{StateCode}}/g, '');
        }

        if (this.options.newTab) {
            template = template.replace(/{{Target}}/g, '_blank');
        }
        else {
            template = template.replace(/{{Target}}/g, '_self');
        }

        return template;
    },

    addCSSRule: function (sheet, selector, rules, index) {
        if ("insertRule" in sheet) {
            sheet.insertRule(selector + "{" + rules + "}", index);
        }
        else if ("addRule" in sheet) {
            sheet.addRule(selector, rules, index);
        }
    },

    forEach: function (array, fn) {
        for (i = 0; i < array.length; i++)
            fn(array[i], i);
    },

    hide: function () {
        if (ZARTIS.getId('jobs_iframe').addEventListener) {
            ZARTIS.getId('jobs_iframe').removeEventListener("load", this.loaded, false);
        } else if (ZARTIS.getId('jobs_iframe').attachEvent) {
            ZARTIS.getId('jobs_iframe').detachEvent("onload", this.loaded);
        }

        ZARTIS.getId('jobs_overlay').style.display = "none";
        ZARTIS.getId('jobs_iframe').removeAttribute("src");
        ZARTIS.getId('jobs_iframe').className = "loading";

        ZARTIS.removeClassName(document.getElementsByTagName('html')[0], 'jobs_tab_on');
    },

    loaded: function () {
        ZARTIS.getId('jobs_iframe').className = "loaded";
    }
}

if (!Array.prototype.forEach) {
    Array.prototype.forEach = function (fun /*, thisArg */) {
        "use strict";
        if (this === void 0 || this === null || typeof fun !== "function") throw new TypeError();

        var
            t = Object(this),
            len = t.length >>> 0,
            thisArg = arguments.length >= 2 ? arguments[1] : void 0;

        for (var i = 0; i < len; i++)
            if (i in t)
                fun.call(thisArg, t[i], i, t);
    };
}