﻿var Dynamo = function () { }
var cache = {};
(function () {
    if (typeof window.CustomEvent === "function") return false; //If not IE

    function CustomEvent(event, params) {
        params = params || { bubbles: false, cancelable: false, detail: undefined };
        var evt = document.createEvent('CustomEvent');
        evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
        return evt;
    }

    CustomEvent.prototype = window.Event.prototype;

    window.CustomEvent = CustomEvent;
})();

Dynamo.prototype.UpdateQuantityUp = function (el) {
    jQuery(function () {
        var spinner = $(el).closest('.customQuantity');
        var input = spinner.find('input[type="number"]');
        var btnUp = spinner.find('.quantity-up');
        var btnDown = spinner.find('.quantity-down');
        var min = input.attr('min');
        var max = input.attr('max');

        var oldValue = parseFloat(input.val());
        if (oldValue < max) {
            input.val(oldValue + 1);
        }
    });
}
//Dynamo.prototype.TitleRestict = function (el) {
//    jQuery(function () {
//        $('.customTooltip').each(function (i) {
//            var group = $(this);
//            var groupchild = group.find(".product-list-item__name");
//            var linkchild = group.find(".read-more");
//            if (groupchild.height() > 35) {
//                groupchild.css({
//                    'overflow': 'hidden',
//                    'width': '170px',
//                    'height': '35px'

//                })
//                linkchild.removeClass('hidden').css({
//                    'display:': 'inline-block'
//                })
//            }
//        });
//    });
//}
Dynamo.prototype.UpdateQuantityDown = function (el) {
    jQuery(function () {
        var spinner = $(el).closest('.customQuantity');
        var input = spinner.find('input[type="number"]');
        var btnUp = spinner.find('.quantity-up');
        var btnDown = spinner.find('.quantity-down');
        var min = input.attr('min');
        var max = input.attr('max');

        var oldValue = parseFloat(input.val());
        if (oldValue > min) {
            input.val(oldValue - 1);
        }
    });
}

//Update the template on the chosen element
Dynamo.prototype.UpdateTemplate = function (id, tmpl) {
    var data = Dynamo.FindDataInCache(id);
    var ajaxContainerElement = document.getElementById(id);

    ajaxContainerElement.setAttribute("data-template", tmpl);

    if (ajaxContainerElement.hasAttribute('data-save-cookie')) {
        document.cookie = id + "Template=" + tmpl;
    }

    Dynamo.CreateItemsFromJson(data, ajaxContainerElement);
}

//Find the temporaily saved data for the selected element
Dynamo.prototype.FindDataInCache = function (id) {
    for (property in cache) {
        if (property == id) {
            return cache[property];
        }
    }
}

//Create data in the cache object (Must be validated Json)
Dynamo.prototype.SetDataInCache = function (id, data) {
    cache[id] = data;
}

//Update the content on the chosen element + subelements (New data request by url)
Dynamo.prototype.UpdateContent = function (containerId, url, updateUrl) {
    var ajaxContainerElement = document.getElementById(containerId);
    ajaxContainerElement.setAttribute('data-json-feed', url);

    //Update the browser url
    if (updateUrl == true) {
        history.pushState(null, null, url);
    }
    Dynamo.GetContentFromJson(ajaxContainerElement)
}

//Call the Json provider, and show a preloader if it is chosen
Dynamo.prototype.GetContentFromJson = function (container) {
    var feed = container.getAttribute('data-json-feed');

    if (!container.hasAttribute('data-preloader') || container.getAttribute('data-preloader') == "minimal") {
        while (container.firstChild) container.removeChild(container.firstChild);

        container.classList.remove("hidden");

        var preloaderElement = document.createElement('i');
        preloaderElement.className = "fa fa-circle-o-notch fa-spin preloader";
        preloaderElement.setAttribute('id', (container.getAttribute('id') + "_preloader"));
        container.appendChild(preloaderElement);
    } else if (container.getAttribute('data-preloader') == "overlay") {
        var overlayElement = document.createElement('div');
        overlayElement.className = "preloader-overlay";
        overlayElement.setAttribute('id', "overlay");
        document.getElementById('content').parentNode.insertBefore(overlayElement, document.getElementById('content'));
    } else if (container.getAttribute('data-preloader') == "overlay-minimal") {
        var overlayElement = document.createElement('div');
        overlayElement.className = "preloader-overlay minimal";
        overlayElement.setAttribute('id', "overlay");
        document.getElementById('content-minimal').appendChild(overlayElement);
    }

    var xhr = new XMLHttpRequest();
    xhr.open('GET', feed, true);
    xhr.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            var data;

            if (xhr.responseType === 'json') {
                data = xhr.response.message;
            } else {
                if (this.response.trim().length > 0) {
                    try {
                        data = JSON.parse(this.response);
                    }
                     catch (error) {
                            data = "";
                        }   
                }
                else {
                    data = "";
                }
            }
            if (data.length) {
            cache[container.getAttribute('id')] = data;

            Dynamo.CreateItemsFromJson(data, container);
            document.dispatchEvent(new CustomEvent("Dynamo.GetContentFromJson", { "detail": container }));
            $(".product-list-item__name").dotdotdot({
               
            });
            }
        } else {
            Dynamo.CleanContainer(container);
        }
    };
    xhr.send(null);
}

//Create visual elements from the data provided and with the chosen template
Dynamo.prototype.CreateItemsFromJson = function (data, container, count) {
    Dynamo.CleanContainer(container);

    if (!count) {
        count = 0;
    }

    if (document.body.contains(container)) {
        for (var i = 0; i < data.length; i++) {
            var templateId;

            //Get template from either the data attribute or a 'template' property in the JSON feed
            if (container.hasAttribute('data-template')) {
                templateId = container.getAttribute('data-template');
            } else {
                for (property in data[i]) {
                    if (property == "template") {
                        templateId = data[i][property];
                        container.setAttribute('data-template', templateId);
                    }
                }
            }

            //If a template setting is found in a cookie, then use that one insted af the above
            if (container.hasAttribute('data-save-cookie')) {
                if (Dynamo.GetCookie(container.getAttribute("id") + "Template")) {
                    templateId = Dynamo.GetCookie(container.getAttribute("id") + "Template");
                }
                document.cookie = container.getAttribute("id") + "Template=" + templateId;
            }

            //Create a temporary container to contain the parsed element before rendering
            var temporaryElementType = container.tagName;
            var temporaryElement = document.createElement(temporaryElementType);

            temporaryElement.innerHTML = Dynamo.RenderItem(data[i], templateId);

            var newElementNodes = temporaryElement.childNodes;
            for (var item = 1; item < newElementNodes.length; item++) {
                container.appendChild(newElementNodes[item]);
            }

            //Check to see if there is a sub nodelists in the data provided, if so then render new items 
            for (property in data[i]) {
                if (typeof data[i][property] == 'object') {
                    var subContainer = document.getElementById(property);
                    //Make the ID unique for each sub object
                    var uniqueId = data[i].id ? property + data[i].id : count == 0 ? property : property + count;

                    cache[uniqueId] = data[i][property];

                    if (subContainer) {
                        subContainer.setAttribute('id', uniqueId);
                        subContainer = document.getElementById(uniqueId);

                        Dynamo.CreateItemsFromJson(data[i][property], subContainer, count);
                    }

                    count++;
                }
            }
        }

        container.classList.remove("hidden");
    }
}

//Clean the container for either all the elements or the preloader
Dynamo.prototype.CleanContainer = function (container) {
    if (document.body.contains(container)) {
        if (container.getAttribute('data-preloader') == "minimal") {
            container.removeChild(document.getElementById(container.getAttribute('id') + "_preloader"));
        } else if (document.getElementById('overlay')) {
            document.getElementById('overlay').parentNode.removeChild(document.getElementById('overlay'));
        } else {
            while (container.firstChild) container.removeChild(container.firstChild);
            container.classList.add("hidden");
        }
    }
}

//Parse the data properties into the element
Dynamo.prototype.RenderItem = function (data, templateId) {
    var template = Dynamo.LoadTemplate(templateId);

    if (template != null) {
        for (property in data) {
            var item = data[property];
            var nameKey = "data." + property;

            template = template.replace(new RegExp(nameKey, "gi"), item);
        }
    }

    return template;
}

//Load the chosen template
Dynamo.prototype.LoadTemplate = function (templateId) {
    if (document.getElementById(templateId)) {
        return document.getElementById(templateId).innerHTML;
    } else {
        console.log("Dynamo: Template element not found - " + templateId);
        return null;
    }
}

//Parse to finde the chosen cookie
Dynamo.prototype.GetCookie = function (name) {
    var pattern = RegExp(name + "=.[^;]*")
    matched = document.cookie.match(pattern)

    if (matched) {
        var cookie = matched[0].split('=')
        return cookie[1]
    }
    return false
}

//Auto initialization
var Dynamo = new Dynamo();

document.addEventListener("DOMContentLoaded", function (event) {
    var ajaxContainer = document.getElementsByClassName("js-ajax-container");

    for (var i = 0; i < ajaxContainer.length; i++) {
        var ajaxContainerElement = ajaxContainer[i];

        if (!ajaxContainerElement.getAttribute('data-json-feed')) {
            console.log("Ajax element: Please specify json feed via data attribute: data-json-feed");
        }

        if (!ajaxContainerElement.hasAttribute('data-init-onload') || ajaxContainerElement.getAttribute('data-init-onload') == false) {
            Dynamo.GetContentFromJson(ajaxContainerElement);
        } else {
            ajaxContainerElement.classList.add("hidden");
        }
    }
});

jQuery('.customQuantity').each(function () {
    var spinner = jQuery(this),
        input = spinner.find('input[type="number"]'),
        btnUp = spinner.find('.quantity-up'),
        btnDown = spinner.find('.quantity-down'),
        min = input.attr('min'),
        max = input.attr('max');

    btnUp.click(function () {
        var oldValue = parseFloat(input.val());
        if (oldValue >= max) {
            var newVal = oldValue;
        } else {
            var newVal = oldValue + 1;
        }
        spinner.find("input").val(newVal);
        spinner.find("input").trigger("change");
    });

    btnDown.click(function () {
        var oldValue = parseFloat(input.val());
        if (oldValue <= min) {
            var newVal = oldValue;
        } else {
            var newVal = oldValue - 1;
        }
        spinner.find("input").val(newVal);
        spinner.find("input").trigger("change");
    });

});