var isMobile = false;
var isIframe = false;
var hasGuidance = false;
var hasMoreLinks = false;
var nav;

var initMobileForm = function () {

    var formState = 0;// 0 | 1 | 2 | 3 (0 = none selected | 1 = form overview | 2 = my cases | 3 current form )

    if (document.body.querySelector(".overview.active")) {
        formState = 1;
    } else if (document.body.querySelector(".cases.active") && formState == 0) {
        formState = 2;
    } else if (document.body.querySelector(".pending.active") && formState == 0) {
        formState = 3;
    }

    transformInputs();

    console.log("GUIDANCE-START");

    var guidanceLi = document.querySelectorAll("ul#guidanceList li:not(.help):not(.error)");
    var moreLinksLi = document.querySelectorAll("ul.link-list li");

    var guidanceUl = document.createElement("ul");
    var moreUl = document.createElement("ul");


    if (guidanceLi !== null) {
        for (var gli = 0; gli < guidanceLi.length; gli++) {
            if (typeof guidanceLi[gli].textContent !== 'undefined' && guidanceLi[gli].textContent.trim().length > 0) {
                hasGuidance = true;
                guidanceUl.appendChild(guidanceLi[gli].cloneNode(true));
            }
        }
    }
    console.log(guidanceUl);

    console.log(moreLinksLi.innerText, moreLinksLi);
    if (moreLinksLi !== null) {
        for (var mli = 0; mli < moreLinksLi.length; mli++) {
            if (typeof moreLinksLi[mli].textContent !== 'undefined' && moreLinksLi[mli].textContent.trim().length > 0) {
                hasMoreLinks = true;
                moreUl.appendChild(moreLinksLi[mli].cloneNode(true));
            }
        }
    }
    console.log("g:", guidanceUl);
    console.log("m:", moreUl);

    if (hasGuidance || hasMoreLinks) {
        var moreButton;
        var guidanceButton;

        var guidanceContainer = document.createElement("div");
        guidanceContainer.classList.add("guidance-container");
        var domH2 = document.querySelector(".SkjemaContainer h2");
        insertAfter(guidanceContainer, domH2);

        if (hasGuidance) {
            guidanceButton = document.createElement("span");
            guidanceButton.classList.add("guidance-button");
            guidanceButton.innerHTML = "?";
            guidanceContainer.appendChild(guidanceButton);
        }
        if (hasMoreLinks) {
            moreButton = document.createElement("span");
            moreButton.classList.add("more-button");
            moreButton.innerHTML = "&hellip;";
            moreButton.title = getResource(resource, "Guidance");
            guidanceContainer.appendChild(moreButton);
        }

        var guidanceText = document.createElement("div");
        guidanceContainer.appendChild(guidanceText);

        if (hasGuidance) {
            guidanceButton.addEventListener("click", function (e) {
                var hasActive = false;
                if (guidanceButton.classList.contains("active")) {
                    hasActive = true;
                }
                if (!hasActive) {
                    guidanceButton.classList.add("active");
                    if (hasMoreLinks && moreButton.classList.contains("active")) {
                        moreButton.classList.remove("active");
                    }
                    guidanceText.innerHTML = "";
                    guidanceText.className = "";
                    guidanceText.classList.add("guidance-text");
                    guidanceText.classList.add("text");

                    guidanceText.appendChild(guidanceUl);
                }
            });
        }
        if (hasMoreLinks) {
            moreButton.addEventListener("click", function (e) {
                var hasActive = false;
                if (moreButton.classList.contains("active")) {
                    hasActive = true;
                }
                if (!hasActive) {
                    moreButton.classList.add("active");
                    if (hasGuidance && guidanceButton.classList.contains("active")) {
                        guidanceButton.classList.remove("active");
                    }
                    guidanceText.innerHTML = "";
                    guidanceText.className = "";
                    guidanceText.classList.add("more-text");
                    guidanceText.classList.add("text");

                    guidanceText.appendChild(moreUl);
                }
            });
        }

    }

    var errors = document.body.querySelectorAll(".error-link");

    for (index = 0; index < errors.length; ++index) {
        var id = errors[index].getAttribute("for");
        var input = document.getElementById(id);
        if (input !== null) {
            var parent = input.parentNode;
            console.log("tagName:", parent.tagName);
            if (parent.tagName !== "DIV") {
                parent = parent.parentNode.parentNode.parentNode.parentNode;
            }

            parent.appendChild(errors[index]);
        }

    }

    var k247img = document.querySelector("footer div#Footer ul li a img");
    if (k247img) {
        var k247dom = k247img.parentElement.cloneNode(true);
        k247dom.classList.add("k247-brand");
        var domBody = document.querySelector("body");
        domBody.insertBefore(k247dom, domBody.firstChild);
    }

    var header = document.querySelector("#Header");
    if (header == null) {

        header = document.createElement("div");
        var mainContentArea = document.querySelector("#MainContentArea");
        mainContentArea.insertBefore(header, mainContentArea.firstChild);
    }

    var menu = document.createElement("div");
    var span = document.createElement("span");

    span.classList.add("menu");
    menu.innerHTML = "&equiv;";
    menu.className = "mobile-menu";
    menu.title = getResource(resource, "Menu");
    var left = document.querySelector("#LeftContent");
    if (left !== null) {
        left.classList.add("mobile-menu-items");
    }

    if (formState == 3 || formState == 0) {
        nav = document.createElement("div");

        nav.className = "mobile-nav";
    }

    var help = document.createElement("div");
    help.innerHTML = "?";
    help.className = "mobile-help";
    help.title = "Hjelp"; // TODO: Replace with resource file
    var rightContent = document.querySelector("#RightContent");
    if (rightContent !== null) {
        rightContent.classList.add("mobile-menu-items");
    }

    var userFunctions = document.querySelector("#UserFunctions");
    if (userFunctions !== null) {
        var login = document.createElement("div");
        var loginUser = document.createElement("div");
        var loginUserUpper = document.createElement("div");
        var loginUserLower = document.createElement("div");

        loginUser.classList.add("loginUser");
        loginUserUpper.classList.add("loginUserUpper");
        loginUserLower.classList.add("loginUserLower");

        loginUser.appendChild(loginUserUpper);
        loginUser.appendChild(loginUserLower);
        login.appendChild(loginUser);

        login.className = "mobile-login";
        loginUser.title = getResource(resource,"UserInfo"); // TODO: Replace with resource file

        //test:
        //var ulList = document.querySelector("#UserFunctions ul");
        //var dom = "<li><span>hei</span></li>";
        //ulList.innerHTML = dom + ulList.innerHTML;

        // if first <li> element contains <span> with username - usercontext = logged-inn
        var userSpan = document.querySelector("#UserFunctions ul > li span");
        console.log(userSpan);
        if (userSpan !== null) {
            login.classList.add("logged-inn");
        }

        userFunctions.classList.add("mobile-menu-items");
        var userHeader = document.createElement("h3");
        userHeader.innerHTML = getResource(resource, "UserStatus");
        var userNud = document.createElement("span");
        userNud.classList.add("nud");
        userFunctions.insertBefore(userNud, userFunctions.firstChild);
        userFunctions.insertBefore(userHeader, userFunctions.firstChild);


        login.addEventListener("click", function (e) {
            var hasActive = false;
            if (userFunctions.classList.contains("active")) {
                hasActive = true;
            }
            remove();
            if (!hasActive) {
                userFunctions.classList.add("active");
                login.classList.add("active");
            }
        });

    }
    var remove = function (e) {
        if (left !== null) {
            left.classList.remove("active");
        }
        if (rightContent !== null) {
            rightContent.classList.remove("active");
        }
        if (userFunctions !== null) {
            userFunctions.classList.remove("active");
            login.classList.remove("active");
        }
        menu.classList.remove("active");
        help.classList.remove("active");

        //var activeItem = document.querySelector(".mobile-menu-items.active");
        //e.classList.remove("active");
    };

    var langList = document.querySelectorAll("#form_culture option");
    for (var ll = 0; ll < langList.length; ++ll) {
        langList[ll].text = langList[ll].value.substring(0, 2);
    }

    if (formState == 1) {
        var quick = document.querySelector(".QuickSearch");
        if (quick) {
            var main = document.querySelector("#MainContentArea");
            main.insertBefore(quick.parentElement, main.firstChild);
        }

        catlinks = document.body.querySelectorAll("ul.cat_list li a");
        for (var c = 0; c < catlinks.length; ++c) {
            catlinks[c].addEventListener("click", function (e) {
                if (left) {
                    remove();
                }
            });
        }

    }
    if (formState == 3 || formState == 0) {
        var choiceControls = document.body.querySelectorAll("input.ChoiceControl");
        for (var c = 0; c < choiceControls.length; ++c) {
            choiceControls[c].addEventListener("change", function (e) {
                var divs = document.body.querySelectorAll('div#skjema > div[style]');
                for (d = 0; d < divs.length; ++d) {
                    if (divs[d].style.display == "inline") {
                        divs[d].style.display = "block";
                        divs[d].classList.add("conditional-div");
                    }
                }
            });
        }

        var toggleGuidances = document.body.querySelectorAll(".toggleGuidance");
        for (var t = 0; t < toggleGuidances.length; ++t) {
            toggleGuidances[t].addEventListener("click", function (e) {
                var divs = document.body.querySelectorAll('div#skjema > div[style]');

                for (var d = 0; d < divs.length; ++d) {
                    if (divs[d].style.display !== "none") {
                        divs[d].style.display = "block";
                    }
                }
            });
        }


        //langList.classList.add("hidden");
        iframeResizePipeFix();
    }



    //var check = function (e) {
    //    if (e.srcElement.className == "active")) {
    //        remove();
    //        return;
    //    } else {
    //        remove();
    //    }
    //};

    menu.addEventListener("click", function (e) {
        var hasActive = false;
        if (left) {
            if (left.classList.contains("active")) {
                hasActive = true;
            }
            remove();
            if (!hasActive) {
                menu.classList.add("active");
                left.classList.add("active");
            }
        }
    });
    //help.addEventListener("click", function (e) {
    //    var hasActive = false;
    //    if (rightContent.classList.contains("active")) {
    //        hasActive = true;
    //    }
    //    remove();
    //    if (!hasActive) {
    //        rightContent.classList.add("active");
    //        help.classList.add("active");
    //    }
    //});



    menu.appendChild(span);
    var moveHelp = document.querySelector("#help");
    if (moveHelp !== null) {
        rightContent.appendChild(document.querySelector("#help"));
        moveHelp.innerHTML = '?';
        help.innerHTML = moveHelp.outerHTML;
    } else {
        help.innerHTML = "<a id=\"help\" href=\"" + consts.siteroot + "/" + consts.consumerUsername + "/hjelp/\" class=\"cboxElement\">?</a>";
    }
    var moveInfo = document.querySelector("#InfoContainer");
    if (moveInfo !== null) {
    	jquery("#InfoContainer").remove();
    }
    header.appendChild(menu);
    if (formState == 3 || formState == 0) {
        console.log("formstate = 3 or 0");
        setupSimpleMenu();
        header.appendChild(nav);
    }
    header.appendChild(help);
    if (userFunctions !== null) {
        header.appendChild(login);
    }
    if (left !== null) {
        header.appendChild(left);
    } else {
        menu.style.display = "none";
    }
    header.appendChild(rightContent);
    if (userFunctions !== null) {
        header.appendChild(userFunctions);
    }
    console.log("setupButtonNav");
    setupButtonNav();

    var skjemaDiv = document.querySelector("#skjema");
    var tdRelative = document.querySelectorAll("td.relativeTableTD");
    for (var x = 0; x < tdRelative.length; x++) {
        var childrenOfTdRelative = tdRelative[x].children;
        for (var y = 0; y < childrenOfTdRelative.length; y++) {
            if (childrenOfTdRelative[y].tagName === "DIV") {
                var tablesInDiv = childrenOfTdRelative[y].querySelectorAll("table");
                for (var t = 0; t < tablesInDiv.length; t++) {
                    if (hasClass(tablesInDiv[t], "input-list") || hasClass(tablesInDiv[t], "datagrid") || hasClass(tablesInDiv[t], "panelTable")) {
                        continue;
                    }
                    var tdsInDiv = tablesInDiv[t].querySelectorAll("td");
                    for (var w = 0; w < tdsInDiv.length; w++) {
                        for (var z = 0; z < tdsInDiv[w].children.length; z++) {
                            tdsInDiv[w].children[z].removeAttribute('style');
                            for (var q = 0; q < tdsInDiv[w].children[z].children.length; q++) {
                                tdsInDiv[w].children[z].children[q].removeAttribute('style');
                            }
                            childrenOfTdRelative[y].appendChild(tdsInDiv[w].children[z]);
                        }
                    }

                }
            }

        }
    }
    console.log("checking width");
    var screenwidth = (window.innerWidth > 0) ? window.innerWidth : screen.width;
    var grids = document.body.querySelectorAll("#skjema .datagrid");
    for (var gl = 0; gl < grids.length; gl++) {
        console.log("grid-width:", grids[gl].clientWidth, screenwidth);
        if (screenwidth < (grids[gl].clientWidth + 10)) {
            parentDivElement = grids[gl].parentNode;
            parentDivElement.style.overflow = "scroll";
            parentDivElement.style.width = (screenwidth - 10) + "px";
        }
    }

    var radios = document.querySelectorAll("#skjema input[onchange=\"javascript:refresh();\"]");
    for (var i = 0, max = radios.length; i < max; i++) {
        radios[i].setAttribute("onchange", "javascript:refresh(delayedSetupButtonNav);");
    }

    //jquery("#skjema input[onchange=\"javascript:refresh();\"]").on("refresh", function (a) {
    //    console.log("listening?");
    //    $(this).done(function() {
    //        delayedSetupButtonNav();
    //    });
    //});
    var textFields = document.querySelectorAll("#skjema input[type=\"text\"],#skjema input[type=\"textarea\"]");
    for (var i = 0, max = textFields.length; i < max; i++) {
        textFields[i].addEventListener("keydown", function (e) {
            jquery(".help-message").remove();
        });
    }
    objs = document.body.querySelectorAll("#skjema > div");
    for (index = 0; index < objs.length; ++index) {
        objs[index].style.width = "100%";
    }
};

function transformInputs() {
    var objs = document.body.querySelectorAll("#skjema input");
    for (index = 0; index < objs.length; ++index) {
        var type = objs[index].getAttribute("type");
        if (type == "text") {
            var width = getStyle(objs[index], "width").replace("px", "");
            if (width > 100) {
                objs[index].setAttribute("class", "mobile-input-full");
            } else {
                objs[index].setAttribute("class", "mobile-input-small");
            }
        }
        if (type == "date") {
            objs[index].style.width = "82px";
        }
    }
    objs = document.body.querySelectorAll("#skjema textarea");
    for (index = 0; index < objs.length; ++index) {
        objs[index].setAttribute("class", "mobile-input-full");
    }
    objs = document.body.querySelectorAll("#skjema select");
    for (index = 0; index < objs.length; ++index) {
        var width = getStyle(objs[index], "width").replace("px", "");
        if (width > 100) {
            objs[index].setAttribute("class", "mobile-input-full");
        } else {
            objs[index].setAttribute("class", "mobile-input-small");
        }
    }
}

function getStyle(el, styleProp) {
    var value, defaultView = (el.ownerDocument || document).defaultView;
    // W3C standard way:
    if (defaultView && defaultView.getComputedStyle) {
        // sanitize property name to css notation
        // (hypen separated words eg. font-Size)
        styleProp = styleProp.replace(/([A-Z])/g, "-$1").toLowerCase();
        return defaultView.getComputedStyle(el, null).getPropertyValue(styleProp);
    } else if (el.currentStyle) { // IE
        // sanitize property name to camelCase
        styleProp = styleProp.replace(/\-(\w)/g, function (str, letter) {
            return letter.toUpperCase();
        });
        value = el.currentStyle[styleProp];
        // convert other units to pixels on IE
        if (/^\d+(em|pt|%|ex)?$/i.test(value)) {
            return (function (value) {
                var oldLeft = el.style.left, oldRsLeft = el.runtimeStyle.left;
                el.runtimeStyle.left = el.currentStyle.left;
                el.style.left = value || 0;
                value = el.style.pixelLeft + "px";
                el.style.left = oldLeft;
                el.runtimeStyle.left = oldRsLeft;
                return value;
            })(value);
        }
        return value;
    }
    return "";
}

function delayedSetupButtonNav() {
    console.log("delayedSetupButtonNav");
    setupSimpleMenu();
    setupButtonNav();

}
function setupButtonNav() {
    //Remove text from bottomnav
    var buttonLists = document.querySelectorAll("ul.SkjemaBottomNav");
    for (var i = 0; i < buttonLists.length; i++) {
        var bottomBtns = buttonLists[i].querySelectorAll(".btn:not(.primary):not(.success):not(.disabled) input");
        for (var j = 0; j < bottomBtns.length; j++) {
            bottomBtns[j].value = "                     " + bottomBtns[j].value; // Lagt til space fordi input submit er avhengig av value, og enste måten å skjule value er på flytte teksten uten av knappen ved space-padding. 
        }
        console.log("bottomBtns", bottomBtns);
    }
    var prev = document.querySelector("ul.SkjemaBottomNav .btn.prev input");
    if (prev !== null) {
        prev.value = "";
    }

    // Kan nok slettes. Usikker på hva denne ble brukt til ettersom linjen over inkluderer denne eksluderingen...
    //var next = document.querySelector("ul.SkjemaBottomNav .btn.next:not(.primary):not(.success):not(.disabled) input");
    //if (next !== null) {
    //    next.value = "";
    //}
}
function setupSimpleMenu() {
    var ol = nav.querySelector("ol");
    if (ol != null) {
        ol.remove();
    }

    var links = document.body.querySelectorAll("#SkjemaNav .progress_list li");
    var navOL = document.createElement("ol");
    console.log(links);
    for (var l = 0; l < links.length; l++) {
        if (links[l].classList !== undefined && links[l].classList.contains("active")) {
            var activeNav = document.createElement("li");
            activeNav.classList.add("active");
            var dom = links[l].cloneNode(true);
            activeNav.title = dom.innerText;
            navOL.appendChild(activeNav);
        } else {
            var dom = links[l].cloneNode(true);
            dom.title = dom.children[0].innerText;
            dom.children[0].innerText = " ";
            navOL.appendChild(dom);
        }

        //if (links.childNodes[l].classList.contains("active")) {

        //} else {
        //    nav.appendChild(links.childNodes[l]);
        //}

    }
    if (links.length > 12) {
        navOL.classList.add("small-buttons");
    }
    if (links.length > 0) {
        nav.appendChild(navOL);
    }
}

function hasClass(elem, css) {
    return (" " + elem.className + " ").indexOf(" " + css + " ") > -1;
}
function insertAfter(newNode, referenceNode) {
    referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
function iframeResizePipeFix() {
    if (isIframe !== false) {
        console.log("iframeResizePipeFix");
        //update iframe height after slide complete
        var parameterFromUrl = getParameterFromUrl('iframeurl', '', true);
        if (parameterFromUrl !== false)
            iframeResizePipe(parameterFromUrl);
    }
}

// Check if mode = iframe
var isIframe = getParameterFromUrl('iframe', '', false);
console.log("isIFrame:", isIframe);

// Check screen width - if less than 950 - render mobile view
var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
console.log("width:", width, "window.innerWidth", window.innerWidth, "screen.width", screen.width);
if (width < 950) {
    isMobile = true;
    initMobileForm();
}


//Noe Kim greier?
//
//document.body.addEventListener("load", function() {
//    var copy = document.querySelector("body").innerHTML;
//    localStorage.setItem("body", copy);
//    var reset = function() {
//        document.body.innerHTML = localStorage.getItem("body");
//    };
//});

//var reset = function () {
//    document.body.innerHTML = localStorage.getItem("body");
//};

window.addEventListener('resize', function () {
    var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;

    var viewerForm = document.querySelector('form#viewer');
    var currentLocation = "0,0";

    if (viewerForm !== null) {
        currentLocation = document.querySelector('form#viewer').dataset.location;

        if (width < 950 && isMobile == false) {
            navigate(currentLocation);
        }
        else if (width > 950 && isMobile) {
            navigate(currentLocation);
        } else {
            iframeResizePipeFix();
        }
    }
}, true);

jQuery(document).ready(function () {
    jQuery(document).on('click', ".addPanelRow,.addRow", function (event) {
        console.log("addPanelRow clicked");
        setTimeout(function () {
            transformInputs();
        }, 700);
    });
});

