$(document).ready(function() {
    setupMenu();
    setupTabs();
    setupSliders();
    setupPlaceholderFallBack();
    setupExpanders();
    setupAjaxPagination();
    setupSelects();
    setupShoppingBasket();
    setupDialog();
    setupUseBox();

    $(".navUp, .navTo").click(function() {
        var to = $(this).attr("href") != '#' ? $($(this).attr("href")).offset().top : 0;
        $("html,body").animate({ scrollTop: to}, "medium");
        return false;
    });

    $('.thumbGallery .thumbs a').live("mouseenter",
            function() {
                var hrefVal = $(this).prop('href');
                $("> img", $(this).closest(".thumbGallery")).prop({ src : hrefVal });
            }).live("click", function() {
                return false;
            });

    if ($.browser.msie && $.browser.version == 8) {
        $("html,body").scrollTop(1);
        setTimeout(function() {
            $("html,body").scrollTop(0)
        }, 1);
    }
    $("[data-href]").click(function() {
        document.location = $(this).data("href");
    });
    if ($('a[href$=".flv"]').size() > 0) {
        $('a[href$=".flv"]').flowplayer("/js/flowplayer/flowplayer-3.2.7.swf");
    }
    if ($("body.popup").size() == 1) {
        $("a.more, .boxInfo a, .activityDisplay a, .associatedBox a").live("click", function() {
            var href = $(this).attr("href");
            $(this).attr("href", appendArguments(href, "popup=true"));
        });
    }
});

function setupMenu() {
    $(".menuItem").hover(function() {
        $(this).addClass("hover");
        $("ul", this).css("z-index", 999).show();
    }, function() {
        $(this).removeClass("hover");
        $("ul", this).hide();
    });
    $(".menuItem > ul > li").hover(function() {
        $(this).addClass("hover");
    }, function() {
        $(this).removeClass("hover");
    });
}
function setupTabs() {
    $(".tabContainer").each(function() {
        var selected = $($(" ul > li.selected", this).length > 0 ? $(" ul > li.selected", this) : $("ul > li:first-child", this));
        $(selected).addClass("selected");
        var ajaxTabHandling = function(href) {
            var curId = getIdFromHref(href);
            var tabLoaded = $(curId).data("tabLoaded");
//            var tabLoaded = false;
            if (isAjaxTab(href) && !tabLoaded) {
                $(curId).append(getLoaderCode());
                $(curId).load(href, [], function() {
                    $(curId).data("tabLoaded", true);
                });
            }
        }

        var href = $("a", selected).attr("href");
        if (href.indexOf("#") > -1) {
            //If href doesn's contain a # it just reloads the page when clicking the tab (no ajax or tab activation required)
            var id = getIdFromHref(href);
            ajaxTabHandling(href);
            $(".tabContents > div", this).hide();
            $(id).show();
            $("> ul > li", this).click(function() {
                if (!$(this).hasClass("selected")) {
                    var selectedId = getIdFromHref($("li.selected a", $(this).parent()).attr("href"));
                    $(selectedId).hide();
                    $("li.selected", $(this).parent()).removeClass("selected");
                    $(this).addClass("selected")
                    var href = $("a", this).attr("href");
                    var curId = getIdFromHref(href);
                    ajaxTabHandling(href);
                    $(curId).show();
                    var event = jQuery.Event("tabChange");
                    event.href = href;
                    $(this).parent().parent().trigger(event);
                }
                return false;
            });
        }
    });
}
function getIdFromHref(href) {
    return href.indexOf("#") == 0 ? href : href.substr(href.indexOf("#"));
}
function appendArguments(href, arguments) {
    return href + (href.indexOf("?") == -1 ? '?' : '&') + arguments;
}
function isAjaxTab(href) {
    return href.indexOf("#") != 0;
}

function setupSliders() {
    setupHomeSlider();
    setupMultiSlider();
}
function setupHomeSlider() {
    if ($('.carousel').length == 1) {
        $('.carousel .slider').anythingSlider({animationTime : 500, delay: 8000, autoPlay:true});
        $('.thumbNav').wrap("<div class='thumbNavWrap'/>");
    }
}
function setupMultiSlider() {
    if ($('.multiSlider').length == 1) {
        $('.multiSlider .slider').anythingSlider({animationTime : 500, delay: 8000, autoPlay:false, buildStartStop:false, buildArrows:false,buildNavigation: false,
            onInitialized: function(e, slider) {
                $(".multiSlider .next").click(function() {
                    slider.goForward();
                    return false;
                });
                $(".multiSlider .previous").click(function() {
                    slider.goForward();
                    return false;
                });
            }});
        $('.multiSlider .mainImageSlider').anythingSlider({animationTime : 500, delay: 6000, autoPlay:false, buildStartStop:false, buildArrows:false,buildNavigation: false});
        $('.multiSlider .secondaryImageSlider').anythingSlider({animationTime : 500, delay: 6000, autoPlay:false, buildStartStop:false, buildArrows:false,buildNavigation: false});
        window.setTimeout(function() {
            try {
                $('.multiSlider .mainImageSlider').data('AnythingSlider').startStop(true);
            } catch(e) {
            }
        }, 1618);
        window.setTimeout(function() {
            try {
                $('.multiSlider .secondaryImageSlider').data('AnythingSlider').startStop(true);
            } catch(e) {
            }
        }, 2617);
    }
}

function initMap() {
    var zindexInfoWindow = 1;
    $(".map").each(function() {
                var mapOptions = { zoom: $(this).data("zoomLevel"), mapTypeId: google.maps.MapTypeId.ROADMAP, disableDefaultUI: true,
                    zoomControl: true,
                    mapTypeControl: true};

                var map = new google.maps.Map(this, mapOptions);

                var locationsSelector = "#" + $(this).data("locations") + " li";
                if ($(locationsSelector).size() == 0) {
                    $(this).hide();
                }
                $(locationsSelector).each(function(index, data) {
                    var geocoder = new google.maps.Geocoder();
                    var address = $(this).data("street") + " " + $(this).data("housenr") + " " + $(this).data("postalcode") + " " + $(this).data("muncipality");
                    geocoder.geocode({ 'address': address}, function(results, status) {
                        if (status == google.maps.GeocoderStatus.OK) {
                            if ($(data).data("center")) {
                                map.setCenter(results[0].geometry.location);
                            }
                            var marker = new google.maps.Marker({
                                map: map,
                                position: results[0].geometry.location,
                                title: $(data).text()
                            });
                            var contentValue = "<div class='mapInfo'>";
                            contentValue += $(data).html();
                            contentValue += "</div>";
                            var infowindow = new google.maps.InfoWindow({
                                content: contentValue
                            });
                            google.maps.event.addListener(marker, 'click', function() {
                                infowindow.open(map, marker);
                                infowindow.setZIndex(zindexInfoWindow++);
                            });
                        }
                    });

                });
            }
    );
}

function setCookie(name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = name + "=" + c_value;
}

function getCookie(name) {
    var i,x,y,ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == name) {
            return unescape(y);
        }
    }
}
function setupPlaceholderFallBack() {
    if (!supportsPlaceholderText()) {
        var isPassword = function(input) {
            return $(input).attr('realType') == 'password';
        }

        var valueIsPlaceholder = function(input) {
            return input.value == $(input).attr('placeholder');
        }

        var showPlaceholder = function(input, loading) {
            if (input.value == '' || (loading && valueIsPlaceholder(input))) {
                if (isPassword(input)) {
                    try {
                        input.setAttribute('type', 'input');
                    } catch (e) {
                    }
                }
                input.value = $(input).attr('placeholder');
                $(input).addClass('placeholder');
            }
        }

        var hidePlaceholder = function(input) {
            if (valueIsPlaceholder(input) && $(input).hasClass('placeholder')) {
                if (isPassword(input)) {
                    try {
                        $(input).attr("type", 'password');
                        input.focus();
                    } catch (e) {
                    }
                }
                $(input).val('');
                $(input).removeClass('placeholder');
            }
        }

        $('input[placeholder]').each(function(index) {
            if ($(this).attr('type') == 'password') {
                $(this).attr('realType', 'password');
            }

            showPlaceholder(this, true);

            $(this).focus(function() {
                hidePlaceholder(this)
            });
            $(this).blur(function() {
                showPlaceholder(this, false)
            });
        });
        $("form").submit(function() {
            $('input[placeholder]').each(function(index) {
                hidePlaceholder(this);
            });
        });
    }
}
function supportsPlaceholderText() {
    var i = document.createElement('input');
    return 'placeholder' in i;
}

function setupExpanders() {
    $("[data-expander-limit]").each(function(element) {
        var limit = $(this).data("expanderLimit");
        var labels = $(this).data("expanderLabels").split(",");
        $(this).expander({
            slicePoint : limit,
            expandText : labels[0],
            preserveWords: true,
            userCollapseText : labels[1]
        });
    });
}
function setupSelects() {
    $("select").live("change", function() {
        $(this).attr("title", $("option:selected", this).html());
    });
}

function setupAjaxPagination() {
    var History = window.History;
    if (!History.enabled) {
        return;
    }
    var contentId;

    History.Adapter.bind(window, 'statechange', function() {
        var state = History.getState();
        if (!contentId) {
            // Record the first div id that was updated
            contentId = state.data.id;
        }
        var id = state.data.id ? state.data.id : contentId;
        $("#" + id).append(getLoaderCode());
        //ajax=true is for ie only, it doesn't reload the first request
        $("#" + id).load(encodeURI(appendUrlParams(state.url, "ajax=true")));
    });

    $(".paginationBar a").live("click", function() {
        var href = $(this).attr("href");
        var form = $("form", findContainerNode(this));
        if (form) {
            href = appendUrlParams(href, serializeForm(form));
        }
        var node = findContentNode(this);
        History.pushState({id: node.attr("id")}, document.title, href);
        return false;
    });

    $(".toolbar select , .paginationBar select").live("change", function() {
        var form = $(this).closest("form");
        var formData = serializeForm(form);
        var action = form.attr("action");
        var href = appendUrlParams(action, formData);
        var nodeId = findContentNode(this).attr("id");
        History.pushState({id: nodeId}, document.title, href);
    });
}
function appendUrlParams(url, params) {
    if (params && params.length > 0) {
        url += (url.indexOf("?") != -1 ? "&" : "?") + params;
    }
    return url;
}
function serializeForm(form) {
    var value = "";
    var validIndex = 0;
    $.each(form.serializeArray(), function(index, item) {
        if (item.value != '') {
            value += (validIndex > 0 ? "&" : "") + item.name + "=" + encodeURI(item.value);
            validIndex++;
        }
    });
    return value;
}

function getLoaderCode() {
    return "<div class='loader'><div class='spinner'/></div>";
}
function findContentNode(element) {
    // Look for the dom node that should recieve the ajax updated content
    var tabContentDiv = $(element).closest(".pagingTarget");
    if (tabContentDiv.size() != 0) {
        return tabContentDiv;
    } else {
        var tabDiv = $(element).closest(".tabContents");
        if (tabDiv.size() != 0) {
            var parents = $(element).parentsUntil(".tabContents");
            return $(parents[parents.length - 1]);
        } else {
            //Not in tab but in simple container
            var node = $("> div:nth-child(2)", $(element).closest(".container"));
            if ($(node).hasClass("toolbar")) {
                node = $(node).next();
            }
            if (!$(node).attr("id")) {
                $(node).attr("id", new Date().getTime());
            }
            return $(node);
        }
    }
}
function findContainerNode(element) {
    var tabDiv = $(element).closest(".tabContents");
    if (tabDiv.size() != 0) {
        return tabDiv;
    } else {
        return $(element).closest(".container");
    }
}

function setupShoppingBasket() {
    $("#shoppingBasket .basketItems").css("visibility", "visible").hide();
    $("#shoppingBasket").hover(function() {
        $(this).addClass("hover");
        if ($.browser.msie && $.browser.version < 9) {
            $(".basketItems", this).stop(true, true).show();
        } else {
            $(".basketItems", this).stop(true, true).slideDown(100);
        }
    }, function() {
        $(this).removeClass("hover");
        if ($.browser.msie && $.browser.version < 9) {
            $(".basketItems", this).stop(true, true).hide();
        } else {
            $(".basketItems", this).stop(true, true).slideUp(100);
        }
    });
    $('.quantity .plus ,.quantity .minus').live("click", function() {
        var aantal = getMinPlusValue(this);
        updateQuantity(this, "action=update_item&aantal=" + aantal);
        return false;
    });
    $('.quantity .delete').live("click", function() {
        updateQuantity(this, "action=remove_item");
        return false;
    });
    setupQuantity('.quantity input');
    if ($("#basket").size() == 1) {
        $("#basket select").live("change", function() {
            var form = $(this).closest("form");
            var action = form.attr("action");
            var data = form.serializeArray();
            data.push("")
            $("#basket").load(action, data, function() {
                setupQuantity('#basket .quantity input');
            });
            if ($(this).attr("name") == "verzendingstype") {
                var shipmentType = $(this).val();
                if (shipmentType == "K") {
                    //Kiala shipment
                    $("#shipmentNonKialaForm").hide();
                    $("#shipmentKialaForm").show();
                } else {
                    // Non kiala shipment
                    $("#shipmentNonKialaForm").show();
                    $("#shipmentKialaForm").hide();
                }

            }
        });
        $("#shipment-address").click(function() {
            $('.shipment-adr').toggle();
        });
        $(".selectKialaPointAction, .changeKialaPointAction").live("click", function() {
            var baseUrl = $("#kialaFrame").data("baseUrl");
            var currentSrc = $("#kialaFrame").attr("src");
            var newSrc = baseUrl + "&zip=" + $("#postalcode").val() + "&street=" + $("#street").val() + "&city=" + $("#place").val();
            if (currentSrc != newSrc) {
                $("#kialaFrame").attr("src", newSrc);
            }
            var currentHeight = $('#kialaDialog .dialogContent').height() + 150;
            if (currentHeight > $(window).height()) {
                var newHeight = $(window).height() - 150;
                $('#kialaDialog .dialogContent,#kialaDialog .dialogContentWrapper').css("height", newHeight);
                $('#kialaDialog').css("margin-top", -((newHeight + 112) / 2));
            }

            $('#kialaDialog').jqmShow();
            return false;
        });

        $("#checkVoucher").live("click", function() {
            var form = $(this).closest("form");
            var data = form.serializeArray();
            var containQuestionMark = $(this).attr("href").indexOf("?") > 0;
            $("#paymentSelect").load($(this).attr("href") + (containQuestionMark ? '&' : '?') + "rand=" + Math.random(), data, function() {
            });
            return false;
        });
    }
}
function kialaCallback(content) {
    $(".selectKialaPointAction").hide();
    $(".changeKialaPointAction").show();
    $('#kialaDialog').jqmHide();
    $("#kialaFrame").attr("src", "");
    $("#selectedKialaPoint").html(content);
}

function updateQuantity(element, action) {
    var params = $(element).closest(".quantity").data("params");
    $.get("/mvc/updateBasket.jsp?" + action + "&" + params + "&rand=" + Math.random(), function (data) {
        var summaryContent = jQuery("<div>").append(data).find("#headerBasketSummary").html();
        var basketContent = jQuery("<div>").append(data).find("#headerBasket").html();
        $("#headerBasketSummary").html(summaryContent);
        $("#headerBasket").html(basketContent);
        setupQuantity('#headerBasket .quantity input');
        if ($("#basket").size() == 1) {
            $("#basket").load("/mvc/updateOrderForm.jsp?confirm=" + $('#basket').data('confirm') + "&rand=" + Math.random(), function() {
                setupQuantity('#basket .quantity input');
            });
            $("#paymentSelect").load("/mvc/updateWaardebonPayment.jsp?rand=" + Math.random());
        }
    });
}


function getMinPlusValue(element) {
    var input = $("input", $(element).parent());
    var minValue = parseInt($(element).closest(".quantity").data("min"));
    var currentVal = parseInt($(input).val());
    var amount = $(element).hasClass("minus") ? -1 : 1;
    if (currentVal == "NaN") currentVal = 0;
    return Math.max(currentVal + amount, minValue);
}
function setupQuantity(selector) {
    $(selector).
            before('<a href="#" class="minus"></a>').
            after('<a href="#" class="plus"></a>');
}
function limitText(limitFieldId, limitCountId, limitNum) {
    var limitField = $('#' + limitFieldId);
    var limitCount = $('#' + limitCountId);
    if (limitField.val().length > limitNum) {
        limitField.val(limitField.val().substring(0, limitNum));
    } else {
        limitCount.html(limitNum - limitField.val().length);
    }
}
function setupDialog() {
    $(".dialog.ajax").jqm({
        target: '.dialogContent',
        overlay: 50
    }).jqmAddClose('.dialog .close').jqmAddClose('.dialog .closeDialogBtn');
    $(".dialog.local").jqm({overlay: 50,
        onLoad: function() {

        }
    }).jqmAddClose('.dialog .close').jqmAddClose('.dialog .closeDialogBtn');

    $("a.inDialog").live("click", function() {
        var trigger = $(this);
        $(".dialog.ajax").jqm({ajax : $(this).attr("href"), onLoad :  function(hash) {
            if ($(trigger).data("contentHeight")) {
                $('.dialogContent', hash.w).css('height', $(trigger).data("contentHeight"));
                $('.dialogContentWrapper', hash.w).css('height', $(trigger).data("contentHeight"));
            }
            if ($(trigger).data("contentWidth")) {
                $(hash.w).css('width', $(trigger).data("contentWidth"));
                $(hash.w).css('margin-left', -$(trigger).data("contentWidth") / 2);
            }
            $(hash.w).css('margin-top', -$(hash.w).height() / 2);

            $(".title", hash.w).html($(trigger).attr("title"));
        }}).jqmShow();
        return false;
    });
}
function setupUseBox() {
    if ($(".usebox").size() > 0) {
        var activeSel = "#bookingCalendar .calendar .active";
        $(activeSel).live("click", function () {
            $(activeSel).removeClass("selected");
            $(this).addClass("selected");
            $(".calendarDateSelection .noDateSelected").hide();
            $(".calendarDateSelection .dateSelected").css('display', 'block');
            $(".calendarDateSelection .selectedBookingDate").html($(this).data("displayDate"));
            $(".calendarDateSelection .dateSelected input").val($(this).attr("data-date"));
            $("#bookingCalendar .shopButton").removeClass("disabled");
        });
        $(".calendar .prev, .calendar .next").live("click", function() {
            $("#bookingCalendar .calendars").append(getLoaderCode());
            $("#bookingCalendar .calendars").load($(this).attr("href"), function() {
                $(".active[data-date='" + $(".calendarDateSelection .dateSelected input").val() + "']", this).addClass("selected");
            });
            return false;
        });
        $(".usebox .shopButton").live("click", function () {
            if (!$(this).hasClass('disabled')) {
                $('#bookingForm').submit();
            }
            return false;
        });
    }
}

function openNewWindow(theURL, winName, features) { //v2.0
    window.open(theURL, winName, features);
}
