/*global require*/

// adds 'external' selector to jQuery, that finds external links, eg. $('a:external')
$.expr[':'].external = function (obj) {
    return !obj.href.match(/^mailto\:/)
            && (obj.hostname != location.hostname && obj.hostname != '');
};

function trackFormErrors(action) {
    Page_ClientValidate();

    if (!Page_IsValid) {
        var msg;

        for (var i = 0; i < Page_Validators.length; i++) {
            if (!Page_Validators[i].isvalid) {
                msg = $(Page_Validators[i]).text();
                break;
            }
        }
        googleTracker.trackEvent(googleTracker.categories.errorMessage, action, msg + '-' + location.pathname);
    }
}

// showrooms
function initialize_map(x, y) {
    var latlng = new google.maps.LatLng(x, y);
    var myOptions = {
        zoom: 15,
        center: latlng,
        disableDefaultUI: true,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    var marker = new google.maps.Marker({
        position: latlng,
        map: map,
        icon: '/Frontend/Images/chair_pin.png'
    });
}

function showSegment(strSegment) {
    var mapDiv = document.getElementById("showroomMap");
    var imageDiv = document.getElementById("showroomImage");
    var videoDiv = document.getElementById("showroomVideo");

    var mapLink = document.getElementById("showroomMapLink");
    var imageLink = document.getElementById("showroomImageLink");
    var videoLink = document.getElementById("showroomVideoLink");

    if (mapDiv != null) mapDiv.style.left = "3000px";
    if (imageDiv != null) imageDiv.style.left = "3000px";
    if (videoDiv != null) videoDiv.style.left = "3000px";
    if (mapDiv != null) mapDiv.style.top = "0px";
    if (imageDiv != null) imageDiv.style.top = "0px";
    if (videoDiv != null) videoDiv.style.top = "0px";


    if (mapLink != null) mapLink.setAttribute("class", "");
    if (imageLink != null) imageLink.setAttribute("class", "");
    if (videoLink != null) videoLink.setAttribute("class", "");

    var segment = document.getElementById(strSegment);
    segment.style.left = "0px";

    if (getVideoPlayer() != null) {
        if (strSegment == "showroomVideo") {
            if (typeof (getVideoPlayer().startPlayback) == "function") {
                getVideoPlayer().startPlayback();
            }
        } else {
            if (typeof (getVideoPlayer().pausePlayback) == "function") {
                getVideoPlayer().pausePlayback();
            }
        }
    }

    var segmentLink = document.getElementById(strSegment + "Link");
    if (segmentLink != null)
        segmentLink.setAttribute("class", "selected");
}
// end showrooms

//fix for font-face flicker
(function () {
    var d = document, e = d.documentElement, s = d.createElement('style');
    if (e.style.MozTransform === '') { // gecko 1.9.1 inference
         s.textContent = 'body{visibility:hidden}';
        //s.textContent = 'body{text-indent:-9999px}';
        e.firstChild.appendChild(s);
        function f() {
            var ffrendertime = setTimeout(function () { s.parentNode && s.parentNode.removeChild(s) }, 200);
        }
        addEventListener('load', f, false);
        setTimeout(f, 2000);
    }
})();

setTimeout(function () {
    var b = document.location.protocol == "https:" ? "https://ssl." : "http://", a = document.createElement("script");
    a.async = !0; 
    a.src = b + "229.site.ehavior.net/co/fr/bootstrap_229.js";
    document.getElementsByTagName("head")[0].appendChild(a);
    if (!document.readyState) window._onload = window.onload, window.onload = function () { 
document.readyState = "complete"; window._onload && window._onload() } }, 0);

require(['jquery', 'jquery.cycle.all.latest', 'fritzhansen.modal', 'jquery.cookie'], function ($) {

    /* frontpage image rotator */
    $(document).ready(function () {

        $('#languageSelectorBox a').click(function (e) {
            $.cookie('language', $(e.currentTarget).attr('data-culturename'), { expires: 365, path: '/' });
        });

        $('a:external').bind('click', function (e) {
            googleTracker.trackEvent(googleTracker.categories.exitLinks, googleTracker.actions.click, $(e.currentTarget).attr('href'));
        });

        $('a.popup').click(function (e) {
            var popup = $('<div>').addClass('wide');
            popup.load(this.href + ' .search_page', function () {
                popup.find('*').attr('id', null).attr('class', null);
                popup.modal();
            });
            e.preventDefault();
        });

        //preload bg image for submenu
        var preloadedBgImg = new Image().src = "/Frontend/images/submenu_fullbg_trans.png";

        $('#imgCycle').cycle({
            fx: 'fade'
        });

        var commerceMenu = $('.commercemenu');

        if (commerceMenu.size() > 0) {
            $(document).bind('basket', function () {
                var count = $.get('/WebServices/EcommerceService.svc/GetBasketCounts?' + Math.random(), function (data) {
                    commerceMenu.find('.basket .count').text(data.basket == 0 ? '' : '(' + data.basket + ')');
                    commerceMenu.find('.wishlist').toggle(data.wishlist > 0).find('.count').text('(' + data.wishlist + ')');
                });
            }).trigger('basket');
        }

        //Check if iOS, and disable link on menues with submenus
        if ((!navigator.userAgent.match(/iPhone/i)) && (!navigator.userAgent.match(/iPod/i)) && (!navigator.userAgent.match(/iPad/i))) {

            var alreadyOpen = null;

            $('.header_menu li').hover(function () {
                clearTimeout($.data(this, 'timer'));
                if ((alreadyOpen != null && $('ul', this).attr("id") != undefined) && alreadyOpen != $('ul', this).attr("id")) {
                    $("#" + alreadyOpen).hide();
                    $('ul', this).show();
                }
                else {
                    $('ul', this).stop(true, true).slideDown(500);
                }

                if ($('ul', this).attr("id") != undefined)
                    alreadyOpen = $('ul', this).attr("id");
            }, function () {
                $.data(this, 'timer', setTimeout($.proxy(function () {
                    $('ul', this).stop(true, true).slideUp(500);
                }, this), 500));
            });
        }

        // load the youtube js api if any iframed youtube players present

        var youtubeIframes = $('iframe[src*="youtube"]');
        if (youtubeIframes.length > 0) {
            loadYoutubePlayerApi();
        }

        function loadYoutubePlayerApi() {
            if (typeof (window.onYouTubePlayerAPIReady) !== "function") {
                window.onYouTubePlayerAPIReady = onYouTubePlayerAPIReady;
                $.getScript("http://www.youtube.com/player_api");
            }
        }

        function onYouTubePlayerAPIReady() {
            youtubeIframes.each(function (i, elm) {
                elm = $(elm);
                var player = new YT.Player(elm.attr('id'), {
                    events: {
                        'onStateChange': function (e) {
                            switch (e.data) {
                                case YT.PlayerState.PLAYING:
                                    googleTracker.trackEvent(googleTracker.categories.videos, googleTracker.actions.play, player.getVideoUrl());
                                    break;
                            }
                        }
                    }
                });
            });
        }

        $('div.imageTopWidgetMenu > ul li').mouseover(function () {
            moveunderline($(this));
        }).bind('touchstart', function () {
            location.href = $(this).children('a').attr('href');
        });

        $('div.imageTopWidgetMenu').mouseout(function () {
            $(".underline").hide();
        });
    });

    /* Menu on Designers and contact */
    window.moveunderline = function (liElement) {

        if ($('div.imageTopWidgetMenu > div.underline').length == 0) {
            $('div.imageTopWidgetMenu').append('<div class="underline"></div>');
        }

        $(".underline").show();

        var newPos = $(liElement).position().left;
        var newPosBtm = $(liElement).position().top + 22;

        $(".underline").stop().animate({ left: newPos }, 80);
        $(".underline").stop().animate({ top: newPosBtm }, 80);
    }

    function menuMouseOver(section) {
        showMouseOverImage(section);
        showNavigationSection(section);
    }

    function menuMouseOut(event, section) {
        showMouseOutImage(section);
        hideNavigation(event, this, section);
    }

    window.DoSearchOnEnter = function (e) {
        var keynum;
        var keychar;
        var numcheck;
        if (window.event) // IE
        {
            keynum = e.keyCode;
        }
        else if (e.which) // Netscape/Firefox/Opera
        {
            keynum = e.which;
        }
        if (keynum == 13) {
            DoSearch();
            return false;
        }
        return true;
    }

    window.imageClickCallback = function (url) {
        if (url != "") {
            window.location.href = url;
        }
    }

    window.gaTrackPageview = function (value) {
        try {
            value = value.toLowerCase().replace("_", "-");
            _gaq.push(['_trackPageview', value]);
        }
        catch (err) {
        }
    }

    window.gaTrackEvent = function (category, action, label, value) {
        try {
            _gaq.push(['_trackEvent', category, action, label, value]);
        }
        catch (err) {
        }
    }

    var currentlyPlayingVideo;

    window.activateVideo = function (videoId) {
        deactivateVideo();
        currentlyPlayingVideo = videoId;
        $("#videoContainer_" + videoId + " > #video").html("<iframe id='iframe_" + videoId + "' type=\"text/html\" width=\"100%\" height=\"100%\" src=\"http://www.youtube.com/embed/" + videoId + "?autoplay=1\" frameborder=\"0\"></iframe>");
        $("#videoContainer_" + videoId + " > .open").css({ display: "none" });
        $("#videoContainer_" + videoId + " > .close").css({ display: "inline" });
        $("#videoContainer_" + videoId).animate({
            width: "575",
            height: "300"
        }, 500, function () {
            $("#videoContainer_" + videoId + " > .video").css({ display: "inline" });
        });

        $("#videoContainer_" + videoId).parent().animate({
            height: 300
        });

        var player = new YT.Player('iframe_' + videoId, {
            events: {
                'onStateChange': function (e) {
                    switch (e.data) {
                        case YT.PlayerState.PLAYING:
                            googleTracker.trackEvent(googleTracker.categories.videos, googleTracker.actions.play, player.getVideoUrl());
                            break;
                    }
                }
            }
        });
    };

    window.deactivateVideo = function () {
        if (currentlyPlayingVideo == undefined) return;
        videoId = currentlyPlayingVideo;
        currentlyPlayingVideo = undefined;
        $("#videoContainer_" + videoId + " > .video").css({ display: "none" });
        $("#videoContainer_" + videoId).animate({
            width: "185",
            height: "111"
        }, 500, function () {
            $("#videoContainer_" + videoId + " > .open").css({ display: "inline" });
            $("#videoContainer_" + videoId + " > .close").css({ display: "none" });
            $("#videoContainer_" + videoId + " > #video").html("");
        });

        $("#videoContainer_" + videoId).parent().animate({
            height: 111
        }, 500);
    };

    window.toggleVideoShortcut = function () {
        if ($("#videos").is(':visible')) {
            $("#videoRightLink").css({ display: "block" });
        }
    };

    window.scrollToVideos = function () {
        $(document).scrollTo($("#videos"), 800);
    };

    window.getVideoPlayer = function (id) {
        var isIE = navigator.appName.indexOf("Microsoft") != -1;
        return (isIE) ? document.getElementById(id + "_ie") : document.getElementById(id + "_moz");
    };

    window.customerServiceCallback = function (param) {
        if (param.indexOf("/de/") > -1) {
            param = param.replace("/contact/CustomerService", "/Kontakt/Kundenservice");
        } else if (param.indexOf("/ja/") > -1) {
            param = param.replace("/ja/", "/jp/");
            param = param.replace("/CustomerService/", "/Customer-Service/");
        }
        window.location = param;
    };
});
