﻿function LoadFaneblade() {
    jQuery(document).ready(function () {
        var qs = getQueryString("fane");
        if (qs != undefined && qs != "") {
            var object = jQuery("#" + qs);
            if (object != undefined) {
                object.click();
                jQuery('html,body').scrollTop(object.offset().top);
            }
        }
    });
}
// GOOGLE MAPS: 
var infowindow;
var currentStore;

function generateGoogleMaps() {
    jQuery(document).ready(function () {
        IncludeGoogleMapsScript("initializeBallMaps");
    });
}
function initializeBallMaps() {
    var lat = jQuery("#countryLat").val();
    var lng = jQuery("#countryLng").val();
    var zoom = jQuery("#countryZoom").val();

    infowindow = new google.maps.InfoWindow({ content: "", maxWidth: 180 });
    var myLatlng = new google.maps.LatLng(lat, lng);
    initGoogleComponents(myLatlng, "googleMap");
    map.setZoom(Number(zoom));
    GetStoresFromID(jQuery("#StoreIds").val(), map);
}

function GetStoresFromID(ids) {
    jQuery.ajax({
        type: "POST",
        url: "/layouts/Chainbizz/Webservice/Service.asmx/GetStoresFromids",
        data: "{'afdelingsider':'" + ids + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        error: function (err, st) { alert("Webservicen er desværre nede. Prøv igen senere") },
        success: function (msg) {

            jQuery(msg.d).each(function () {
                var value = this.split(";");
                if (value[0] + "" + value[1] == "") {
                    FindAndSaveStoreLatLng(value[3], value[2]);
                }
                else
                    presentBallStore(value);
            });

        }
    });
}

function saveCords(kode, position) {
    jQuery.ajax({
        type: "POST",
        url: "/layouts/Chainbizz/Webservice/Service.asmx/SaveStoreCords",
        data: "{afdelingsShortId:'" + kode + "', lat:'" + position.lat() + "', lng :'" + position.lng() + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            var value = msg.d.split(";");
            presentBallStore(value);
        },
        error: function (a, b) { alert(a + b + "Webservicen er desværre nede. Prøv igen senere"); }
    });
}

function showBallStreetView() {
    if (currentPosition != null) {
        SwitchToStreetView(currentPosition);
        jQuery(".streetview-button").show();
        jQuery(".streetview-button").click(function () {
            jQuery(this).hide();
            initializeBallMaps();
        });

    }
}
function presentBallStore(value) {
    var StorePosition = new google.maps.LatLng(parseFloat(value[0]), parseFloat(value[1]));
    var image = "/layouts/Chainbizz/images/system/google_marker_small.png";
    AddMarkerToMap(StorePosition, image);
    google.maps.event.addListener(marker, 'click', function (e) {

        var contentValue = value[4];
        contentValue = contentValue.replace("(Gåtilbutik)", gotoStoreText);
        var content = "<div class=\"google-infobox\">" + contentValue + "";

        if (value[5] == "False")
            content += "<div class='link'><a href='#' onclick=\"showBallStreetView();\">" + streetviewText + "</a></div>";

        content += "</div>";
        currentPosition = this.position;
        currentStore = value[2];
        infowindow.setContent(content);
        infowindow.setPosition(this.position);
        infowindow.open(map, this);
    });

    if (value[2] == currentStore) {
        var content = "<div class=\"google-infobox\">" + contentValue + "<div class='link'><a href='#' onclick=\"showBallStreetView();\">" + streetviewText + "</a></div></div>";
        infowindow.setContent(content);
        infowindow.setPosition(StorePosition);
        infowindow.open(map, marker);
    }

}
function FindAndSaveStoreLatLng(address, kode) {
    if (address != "" && kode != "") {
        GoogleLookupAddress(address, kode, saveCords);

    }
}
// GOOGLE MAPS END

//Faneblade:
function ShowFaneblad(obj, active, wrapClas, sharedclass) {

    jQuery("." + sharedclass).hide();
    if (active.indexOf('#') != -1)
        jQuery("" + active).show();
    else
        jQuery("." + active).show();
    jQuery("." + wrapClas).children().each(function () { jQuery(this).removeClass("selected"); });
    jQuery(obj).addClass("selected");
}
//Faneblade end
//StyleSheet settings:

function FindStyleCookie() {
    var val = readCookie(cssStyleCookie);
    if (val != undefined)
        changeStyle(val);
}
var cssStyleCookie = "cssStyle";
function changeStyle(title) {
    if (title == "color-1")
        eraseCookie(cssStyleCookie);
    else
        createCookie(cssStyleCookie, title, 99);
    var lnks = document.getElementsByTagName('link');
    for (var i = lnks.length - 1; i >= 0; i--) {
        if (lnks[i].getAttribute('rel').indexOf('style') > -1 && lnks[i].getAttribute('title')) {
            lnks[i].disabled = true;
            if (lnks[i].getAttribute('title') == title) lnks[i].disabled = false;
        }
    }
}
//styleSheetSettings end





//Client side validering

function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;

    return true;
}

//slut Client side validering

//ProduktZoomfunktioner:
var options;
var container;
var aktuelFarve;
function VisGalleri() {

    jQuery('#zoom-product').show();
    container.find(".zoom-navigator").each(function () {
        var styling = jQuery(this).attr("style");
        var found = false;
        if (styling == undefined) {
            found = true;
        }
        else if (styling != undefined) {
            if (styling.indexOf("display:none") != -1) {
                found = true;
            }
        }
        if (found) {
            aktuelFarve = jQuery(this).find("a").attr("rel").replace("galleri", "");
            jQuery(this).find("a").jqzoom(options);
        }
    });

    var currentIndex = getQueryString("billede");
    if (currentIndex != null) {
        var counter = 0;
        var current;
        var All = new Array();
        jQuery("#thumbs" + aktuelFarve).children().each(function () {

            var LoopItem = jQuery(this).clone();
            if (LoopItem != null) {
                if (LoopItem.hasClass("selected"))
                    current = LoopItem;
                else {
                    All[counter++] = LoopItem;
                }
                if (counter == currentIndex) {
                    All[counter++] = current;
                }
            }
        });

        jQuery("#thumbs" + aktuelFarve).empty();
        for (var i = 0; i < All.length; i++)
            jQuery("#thumbs" + aktuelFarve).append(jQuery(All[i]));

    }

    klikthumbnail();
}
function klikthumbnail() {
    jQuery("#thumbs" + aktuelFarve).find("a:first").removeClass("zoomThumbActive");
    jQuery("#thumbs" + aktuelFarve).find("a:first").click();
}
function SkjulGalleri() {
    jQuery('#zoom-product').hide();
}
function visNytGalleri(obj, nyFarve) {
    //lav valgte farve "selected" 
    container.find(".clothing-color").find("a").removeClass("selected");
    jQuery(obj).addClass("selected");
    container.find(".thumbs").hide();
    container.find(".zoom-navigator").hide();

    container.find("#thumbs" + nyFarve).show();
    container.find("#zoom" + nyFarve).show();
    jQuery("#zoomer" + nyFarve).jqzoom(options);
    klikthumbnail();
}
function LoadZoomFunktioner(synlig, farve) {
    jQuery(document).ready(function () {
        container = jQuery("#zoom-product .product-details .wrap-zoom");
        options = {
            zoomType: 'drag',
            lens: true,
            preloadImages: true,
            alwaysOn: true,
            zoomWidth: 254,
            zoomHeight: 330,
            title: false,
            position: 'right'
        };

        if (synlig) {
            aktuelFarve = farve;
            VisGalleri();
        }
    });
}

//Slup ProduktZoomfunktioner

//popups checkoutflow hide
function bindHideLayer(theLayer) {
    jQuery(theLayer).focus();
    jQuery(theLayer).keydown(function (event) {
        if (event.keyCode == '27') {
            jQuery('#bg-popup').hide();
            jQuery(theLayer).hide();
        }
    });
}
//slut popups checkoutflow hide

//topmenu funktioner:

function kollektionDropDownVis(displayControl) {

    jQuery("#" + displayControl).css("visibility", "visible");
    jQuery('#bg-layer-menu').show();

} function kollektionDropDownSkjul(displayControl) {

    jQuery("#" + displayControl).css("visibility", "hidden");
    jQuery('#bg-layer-menu').hide();
}

//Stylisten Anbefaler:
var StylingIndex = 0;
var StylistCount = 0;
var StylistFading = false;
var stylistenAnbefaler;
function LoadStylistenAnbefaler() {
    jQuery(document).ready(function () {
        stylistenAnbefaler = jQuery(".wrap-carousel-elements");
        StylistCount = stylistenAnbefaler.find(".hProduct").length;
        stylistenAnbefaler.find(".left").click(function () {
            if (!StylistFading) {
                StylistFading = true;
                var oldIndex = StylingIndex;
                if (StylingIndex == 0)
                    StylingIndex = StylistCount - 1;
                else
                    StylingIndex--;
                VisNytItem(oldIndex, StylingIndex);
            }
        });
        stylistenAnbefaler.find(".right").click(function () {
            if (!StylistFading) {
                StylistFading = true;
                var oldIndex = StylingIndex;
                if ((StylingIndex + 1) == StylistCount)
                    StylingIndex = 0;
                else
                    StylingIndex++;
                VisNytItem(oldIndex, StylingIndex);
            }
        });
    });
}
function VisNytItem(oldIndex, newIndex) {
    jQuery("#stylespot" + oldIndex).fadeOut(250,
                function () {
                    jQuery("#stylespot" + newIndex).fadeIn(250,
                            function () {
                                StylistFading = false;
                            });
                });

}
//Stylisten anbefaler slut:

//checkout script
var addToShoppingCartIsProcessing = false;
function buyProduct() {
    var kode = jQuery("#productCode").attr("content");
    AddToShoppingCart(kode);
}
function AddToShoppingCart(productCode) {
    if (!addToShoppingCartIsProcessing) {
        addToShoppingCartIsProcessing = true;
        setTimeout(function () {
            addToShoppingCartIsProcessing = false;
        }, 500);
        jQuery.ajax({
            type: "POST",
            url: "/layouts/Chainbizz/Webservice/Service.asmx/BuyProduct",
            data: "{productCode:'" + productCode + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                var popup = jQuery("#productBoughtPopup");
                var boxwidth = popup.html().length * 10;
                popup.css("top", ((jQuery(window).height() - popup.outerHeight()) / 2) + jQuery(window).scrollTop() + "px");
                popup.css("left", ((816 - boxwidth) / 2) + jQuery(window).scrollLeft() + "px");
                popup.show();
                setTimeout(function () {
                    jQuery("#productBoughtPopup").hide();
                }, 1500);
                LoadSublayout("CHAINTRALayouts/Core/BasketMini", null, function (msg) {
                    jQuery("#basket").animate({ opacity: 0.3 }, 500, function (id) {
                        jQuery(this).replaceWith(msg.d);
                        jQuery(this).css({ opacity: 0.3 });
                        jQuery(this).animate({ opacity: 1 }, 600);
                    });
                });
            }
        });
    }
    return false;
}
function LoadSublayout(sublayout, placeholder, callback) {
    var id = jQuery("#scID").attr("content");
    jQuery.ajax({
        type: "POST",
        url: "/layouts/Chainbizz/Webservice/Service.asmx/LoadSublayout",
        data: "{sublayout:'" + sublayout + "', id : '" + id + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: (callback) ? callback : function (msg) {
            placeholder.html(msg.d);
        }
    });
}
