﻿/// <reference path="/Shared/Script/HTML.js" />


if (CloudUrl === undefined) {
    var CloudUrl = "";
}


$(function () {
    SharedCommonInit();
});


function SharedCommonInit() {
    $("body").on("click", ".GsExpandable .Summary", GsExpandableClick);
    $("body").on("click", ".GsCollapsable .Summary", GsExpandableClick);
}



function Noop() {
    return false;
}


if (typeof vex !== 'undefined') {
    vex.defaultOptions.className = "vex-theme-flat-attack";
}


function GetValueOrShake(selector, extraCheckCallback) {
    var field = $(selector);

    field.removeClass("Error");

    var value = field.val();

    if (value == null || value === "") {
        ErrorShake(selector);
        field.addClass("Error");
        value = "";
    }

    if (value !== "" && extraCheckCallback != null) {
        var valid = extraCheckCallback(value);
        if (!valid) {
            ErrorShake(selector);
            field.addClass("Error");
        }
    }

    value = value.replace(new RegExp("\"", 'g'), "\\\"");

    return value;
}



function IsNumeric(value) {

    if ((undefined === value) || (null === value)) {
        return false;
    }

    if (typeof value == "number") {
        return true;
    }

    return ((value - 0) == value) && value.length > 0;
}




function IsNullOrWhiteSpace(value) {
    if (IsNullOrEmpty(value)) {
        return true;
    }

    value = value.trim();

    if (value === "") {
        return true;
    }

    return false;
}

function IsNullOrEmpty(value) {
    if (IsNullOrUndefined(value)) {
        return true;
    }

    value = value.trim();
    if (value === "") {
        return true;
    }

    return false;
}

function IsSomething(value) {
    return !IsNullOrEmpty(value);
}


function IsMsgNull(msg) {
    return msg === null || msg === undefined || msg.d === null || msg.d === undefined;
}

function IsNullOrUndefined(val) {
    return val === null || val === undefined;
}


function DeselectText() {

    if (window.getSelection) {
        if (window.getSelection().empty) {  // Chrome
            window.getSelection().empty();
        } else if (window.getSelection().removeAllRanges) {  // Firefox
            window.getSelection().removeAllRanges();
        }
    } else if (document.selection) {  // IE?
        document.selection.empty();
    }
}

function ErrorShake(selector) {
    var input = $(selector);


    input.addClass("Error");
    input.shake2(10, 10, 1000);

    setTimeout(function () {

        input.removeClass("Error");
    }, 1000);
}

function ErrorShakeNew(selector) {
    ErrorShake(selector);
}


jQuery.fn.shake2 = function (intShakes, intDistance, intDuration) {
    this.each(function () {
        $(this).css("position", "relative");
        for (var x = 1; x <= intShakes; x++) {
            $(this).animate({ left: (intDistance * -1) }, (((intDuration / intShakes) / 4)))
                .animate({ left: intDistance }, ((intDuration / intShakes) / 2))
                .animate({ left: 0 }, (((intDuration / intShakes) / 4)));
        }
    });
    return this;
};


$.fn.enterKey = function (fnc, preventDefault) {
    return this.each(function () {
        $(this).keypress(function (ev) {
            return CallOnEnterKeyCode(ev, fnc, preventDefault);

        });
    });
};

function CallOnEnterKeyCode(ev, fnc, preventDefault) {
    var keycode = (ev.keyCode ? ev.keyCode : ev.which);
    if (keycode == "13") {

        if (preventDefault) {
            ev.preventDefault();
        }

        fnc.call(this, ev);

        return false;
    }

    return true;
}

$.fn.escKey = function (fnc) {
    return this.each(function () {
        $(this).keypress(function (ev) {
            var keycode = (ev.keyCode ? ev.keyCode : ev.which);
            if (keycode == '27') {
                fnc.call(this, ev);
            }
        });
    });
};

(function ($) {
    // VERTICALLY ALIGN FUNCTION
    $.fn.vAlign = function () {
        return this.each(function () {
            var ah = $(this).height();
            var ph = $(this).parent().height();
            var mh = Math.ceil((ph - ah) / 2);
            $(this).css('margin-top', mh);
        });
    };
})(jQuery);


function IsEmail(email) {
    if (IsNullOrWhiteSpace(email)) {
        return false;
    }
    var regex = /^([a-zA-Z0-9_.+-])+\@(([0-9a-zA-Z][-\w]*[0-9a-zA-Z])+\.)+([a-zA-Z0-9]{2,9})+$/;
    return regex.test(email);
}

function IsPhone(phone) {
    return IsNumeric(phone) && phone.length > 7;
}

function IsPhoneEx(phone) {
    var regex = /^\+?\d{8,12}$/;
    return regex.test(phone);
}

function IsVin(vin) {
    var regex = /^[a-zA-Z][a-zA-Z]\d{4,5}$/;
    return regex.test(vin);
}

function IsVin(vin, country) {
    // NO
    var regex = /^[a-zA-Z][a-zA-Z]\d{4,5}$/;

    switch (country) {
        case "SE":
            regex = /^[a-zA-Z]{3}\d{2}[a-zA-Z0-9]{1}$/;
            break;
        default:
    }

    return regex.test(vin);
}


function PrettyMobile(mobile) {

    if (mobile == null || mobile === "") {
        return "";
    }

    mobile = StringReplaceAll(mobile, " ", "");
    mobile = StringReplaceAll(mobile, "-", "");

    if (StringStartsWith(mobile, "+47")) {
        mobile = mobile.substring(3);
    }

    if (StringStartsWith(mobile, "0047")) {
        mobile = mobile.substring(4);
    }

    if (StringStartsWith(mobile, "+0047")) {
        mobile = mobile.substring(5);
    }

    return mobile;

}


function IsMobile(mobile) {
    if (mobile == null || mobile === "") {
        return false;
    }

    if (!IsNumeric(mobile) || mobile.length < 8) {
        return false;
    }


    var firstDigit = mobile.substring(0, 1);

    return firstDigit === "4" || firstDigit === "9";
}


function IsPrettyMobile(value) {
    value = PrettyMobile(value);
    return IsMobile(value);
}

function NumberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
}


function GetURLParameter(find) {
    var url = window.location.search.substring(1);
    var params = url.split("&");
    for (var i = 0; i < params.length; i++) {
        var param = params[i].split("=");
        if (param[0] === find) {
            return param[1];
        }
    }
    return null;
}


function StringStartsWith(value, search) {
    return value.indexOf(search) === 0;
}

function StringEndsWith(value, search) {
    return value.indexOf(search) === value.length - 1;
}

function StringTrim(value) {
    return value.replace(/^\s+|\s+$/g, "");
}

function StringReplaceAll(target, search, replacement) {
    return target.replace(new RegExp(search, "g"), replacement);
};



// ***** String function ******* //

if (typeof String.prototype.Float !== "function") {
    String.prototype.Float = function () {
        return parseFloat(this.replace(",", "."));
    };
}

if (typeof String.prototype.StartsWith !== 'function') {
    String.prototype.StartsWith = function (value) {
        return StringStartsWith(this, value);
    };
}

if (typeof String.prototype.EndsWith !== 'function') {
    String.prototype.EndsWith = function (suffix) {
        return this.indexOf(suffix, this.length - suffix.length) !== -1;
    };
}

if (typeof String.prototype.Contains !== 'function') {
    String.prototype.Contains = function (value) {
        return this.toUpperCase().indexOf(value.toUpperCase()) >= 0;
    };
}

if (typeof String.prototype.PadLeft !== 'function') {
    String.prototype.PadLeft = function (length, padding) {
        var output = this;
        if (!padding) {
            padding = '0';
        }
        while (output.length < length) {
            output = padding + output;
        }
        return output;
    };
}

if (typeof String.prototype.trim !== 'function') {
    String.prototype.trim = function () { return this.replace(/^\s+|\s+$/g, ''); };
}

if (typeof String.prototype.ltrim !== 'function') {
    String.prototype.ltrim = function () { return this.replace(/^\s+/, ''); };
}

if (typeof String.prototype.rtrim !== 'function') {
    String.prototype.rtrim = function () { return this.replace(/\s+$/, ''); };
}

function GsExpandableClick(e) {
    var content = $(this).next();
    if (content.length === 0) {
        return;
    }

    var parent = $(this).parents(".GsExpandable, .GsCollapsable");
    var deviceSpecific = parent.hasClass("OnlyCollapsableOnDesktop") || parent.hasClass("OnlyCollapsableOnMobile");

    if ($(content).hasClass("Active")) {
        $(content).removeClass("Active");
        this.innerHTML = this.innerHTML.replace(' mindre ', ' mer ');

        if (!deviceSpecific) {
            $(content).hide();
        }
    } else {
        $(content).addClass("Active");
        this.innerHTML = this.innerHTML.replace(' mer ', ' mindre ');

        if (!deviceSpecific) {
            $(content).show();
        }
    }
}


function BuildCommonTips() {
    $(".gstip, .commonTip").not(".tooltipstered").each(function () {
        var tip = $(this);
        var content = tip.find(".tipContent").html();

        if (IsNullOrUndefined(content)) {
            content = tip.find(".gstipcontent").html();
        }

        var pos = tip.attr("pos");
        if (pos == null || pos === "") {
            pos = 'left';
        }

        var interactive = tip.attr("interactive") === "true";

        tip.tooltipster({
            theme: 'tooltipster-shadow',
            position: pos,
            autoClose: true,
            interactive: interactive,
            content: $(content)
        });
    });
}


function FriendlyUrlFormat(value) {

    if (IsNullOrEmpty(value)) {
        return "";
    }

    value = value.toLowerCase();
    value = value.replace(/ø/g, "o");
    value = value.replace(/å/g, "a");
    value = value.replace(/æ/g, "ae");
    value = value.replace(/ä/g, "ae");
    value = value.replace(/ü/g, "u");
    value = value.replace(/ö/g, "o");
    value = value.replace(/ß/g, "ss");
    value = value.replace(/%/g, "");
    value = value.replace(/&/g, "_og_");
    value = value.replace(/\//g, "_");
    value = value.replace(/ /g, "_");
    value = value.replace(/ - /g, "_");
    value = value.replace(/ -/g, "_");
    value = value.replace(/- /g, "_");
    value = value.replace(/-/g, "_");
    value = value.replace(/\+/g, "_");
    value = value.replace(/\?/g, "_");
    value = value.replace(/\!/g, "_");
    value = value.replace(/#/g, "_");
    value = value.replace(/\*/g, "_");
    value = value.replace(/>/g, "_");
    value = value.replace(/</g, "_");
    value = value.replace(/:/g, "_");
    value = value.replace(/\./g, "_");
    value = value.replace(/\,/g, "_");
    value = value.replace(/\(/g, "_");
    value = value.replace(/\)/g, "_");
    value = value.replace(/\|/g, "_");
    value = value.replace(/\"/g, "_");
    value = value.replace(/\\/g, "_");
    value = value.replace(/™/g, "_");
    value = encodeURI(value);
    value = value.replace(/\+/g, "_");
    value = value.replace(/------/g, "_");
    value = value.replace(/-----/g, "_");
    value = value.replace(/----/g, "_");
    value = value.replace(/---/g, "_");
    value = value.replace(/--/g, "_");
    value = value.replace(/______/g, "_");
    value = value.replace(/_____/g, "_");
    value = value.replace(/____/g, "_");
    value = value.replace(/___/g, "_");
    value = value.replace(/__/g, "_");

    while (value.endsWith("_")) {
        value = value.substr(0, value.length - 2);
    }

    return value;
}


function Base64EncodeValue(value) {
    value = btoa(unescape(encodeURIComponent(value)));
    return value;
}


function WebPFallback() {
    /* IE doesnt handle webp image format */
    if (/MSIE \d|Trident.*rv:/.test(navigator.userAgent)) {
        var images = document.querySelectorAll('img');

        for (var i = 0; i < images.length; i++) {
            /*images[i].onerror = function () {
                this.src = this.src.replace('/webp', '');
            }*/
            images[i].src = images[i].src.replace('/webp/', '/');
        }
    }
}


function ToDbDate(date) {
    if (date == undefined) {
        return null;
    }

    if (!(date instanceof Date)) {
        return null;
    }

    var month = "" + (date.getMonth() + 1);
    var day = "" + date.getDate();
    var year = date.getFullYear();

    if (month.length < 2) 
        month = "0" + month;
    if (day.length < 2) 
        day = "0" + day;

    return [year, month, day].join("-");
}



function InitSwitchery() {

    
    $(".js-switch").not("[data-switchery='true']").each(function () {
        var temp = new Switchery(this);
    });
}


function AjaxCompleteSnack(msg) {
    if ($("#snackbar").length === 0) {
        return;
    }

    if (IsMsgNull(msg)) {
        return;
    }

    var isError = false;
    var message = "";

    if (typeof msg.d === "string") {
        message = msg.d;
    }

    if (typeof msg.d === "object") {
        isError = !msg.d.Success;
        message = msg.d.Message;
    }

    $("#snackbar").text(message);
    $("#snackbar").addClass("show");

    if (isError) {
        $("#snackbar").addClass("error");
    }

    setTimeout(function () {
        $("#snackbar").removeClass("show").removeClass("error");
    }, 3000);
}
