/*
	skanska.js
*/

Skanska = {
    Ext: {
        /*
        show/hide country/language select
        */
        InitUtilityMenu: function () {
            $(".show-utility-menu").bind("click", function () {
                var h = $(document).height();

                if ($("#CoverLayer").size() == 0) {
                    var coverLayer = $("<div id=\"CoverLayer\"></div>");
                    $("body").append(coverLayer);
                }
                $("#CoverLayer").height(h);
                $("#CoverLayer").show();
                $("#UtilityMenu").slideDown(500);

                $("#CoverLayer").bind("click", function () {
                    $("#UtilityMenu").slideUp(500, function () {
                        $("#CoverLayer").hide();
                    });
                });
            });

            $(".hide-utility-menu").bind("click", function () {
                $("#UtilityMenu").slideUp(500, function () {
                    $("#CoverLayer").hide();
                });
            });
        },
        /*
        quick search
        */
        InitQuickSearch: function () {
            $(".v2-quick-search input[type=image]").bind("click", function () {
                location.href = $(this).prev("input[type=text]").attr("data-url") + "&q=" + $(this).prev("input[type=text]").attr("value");
                return false;
            });
            $(".v2-quick-search input[type=text]").bind("keypress", function (e) {
                if (e.which == 13) {
                    location.href = $(this).attr("data-url") + "&q=" + $(this).attr("value");
                    return false;
                }
            });
        },
        /*
        add border colors to dynamic content/highlighters (for IE, other browsers handle it in CSS)
        */
        AddBorderColors: function () {
            var featureSupported = $(".v2-dynamic-content > div:first-child").css("border-left-color") != "transparent";

            if (!featureSupported) {
                $(".v2-dynamic-content > div:nth-child(4n+1)").addClass("border-1st-child");
                $(".v2-dynamic-content > div:nth-child(4n+2)").addClass("border-2nd-child");
                $(".v2-dynamic-content > div:nth-child(4n+3)").addClass("border-3rd-child");
                $(".v2-dynamic-content > div:nth-child(4n+4)").addClass("border-4th-child");
            }
        },
        /*
        fix event bubbling on media slider element (IE 8- handles it wrong)
        */
        FixEventBubbling: function () {
            if (!$.support.changeBubbles) {
                $("#v2-MediaSlider").bind("mouseover", function (e) {
                    $(this).addClass("hover");
                }).bind("mouseout", function (e) {
                    $(this).removeClass("hover");
                });
            }
        },
        /*
        add fade overlay layer for image scroller
        */
        AddFadeOverlay: function () {
            $("#v2-MediaSlider .items > div").each(function () {
                if ($(this).attr("class").indexOf("no-overlay") == -1) {
                    $(this).append("<div class=\"fade-overlay\"></div>");
                }
            });
        },
        /* 
        add support for placeholder attribute
        */
        AddPlaceholderSupport: function () {
            $("input.placeholder").each(function () {
                var elm = $(this);

                elm.attr("data-placeholder", elm.attr("title"));

                if (elm.attr("value").length == 0 || elm.attr("value") == elm.attr("data-placeholder")) {
                    elm.attr("value", elm.attr("title"));
                    elm.attr("title", "");
                    elm.addClass("placeholder-text-active");
                }
            }).bind("focus blur", function () {
                var elm = $(this);
                elm.toggleClass("placeholder-text-active");

                if (elm.attr("value") == elm.attr("data-placeholder")) {
                    elm.attr("value", "");
                } else if (elm.attr("value").length == 0) {
                    elm.attr("value", elm.attr("data-placeholder"));
                } else {
                    elm.removeClass("placeholder-text-active");
                }
            });
        },
        Paging: {
            /*
            paging for lists
            */
            Apply: function () {
                $(".apply-paging").each(function () {
                    var items = $(this).find("ul").children("li").length;
                    var pages = Math.ceil(items / parseInt($(this).attr("data-items-per-page")));

                    if (pages > 1) {
                        // create paging element
                        var pagingElm = $("<div class=\"paging\"></div>");

                        // add list elements for paging
                        var arr = new Array(pages + 1);
                        var x = arr.join("<a href=\"javascript:void(0)\" onclick=\"Skanska.Ext.Paging.TurnPage(this)\"></a>");
                        pagingElm.append(x);
                        $(this).append(pagingElm);
                        pagingElm.find("a:first").click();
                    }

                    $("a.bottom-link + div.paging", $(this)).each(function () {
                        $(this).prev().addClass("before-paging");
                    });
                });
            },
            /*
            turn page
            */
            TurnPage: function (elm) {
                var parentElm = $(elm).parent();
                var listContainer = $(elm).parents("div.apply-paging");
                var pageSize = parseInt(listContainer.attr("data-items-per-page"));
                var indexClicked = parseInt($("a", parentElm).index($(elm)));
                var itemStart = indexClicked * pageSize;
                var itemEnd = itemStart + pageSize - 1;

                // mark current page
                $("a", parentElm).removeClass("current");
                parentElm.find("a").eq(indexClicked).addClass("current");

                for (var i = 0; i < $("li", listContainer).length; i++) {
                    $("li", listContainer).eq(i).removeClass("first-visible");

                    if (i >= itemStart && i <= itemEnd) {
                        $("li", listContainer).eq(i).fadeIn();
                        if (i == itemStart) {
                            $("li", listContainer).eq(i).addClass("first-visible");
                        }
                    } else {
                        $("li", listContainer).eq(i).hide();
                    }
                }
            }
        },
        /*
        scrollable (media slider)
        */
        InitMediaScroller: function () {
            if ($(".scrollable").length > 0) {
                var _s = $(".scrollable").scrollable({ "circular": true })
                scrollableApi = $(".scrollable").data("scrollable");

                if (scrollableApi.getItems().length > 1) {
                    _s.autoscroll({ "autoplay": true, "interval": 8000 });
                    _s.navigator();

                    $(".navi").bind("mouseover", function () {
                        scrollableApi.stop();
                    });
                }
            }
        },
        /*
        overlay
        */
        ShowOverlay: function () {
            if ($(".overlay").length > 0) {
                $(".overlay").overlay({
                    "mask": "rgba(0, 0, 0, .5)",
                    "load": true
                });
                overlayApi = $(".overlay").data("overlay");
            }
        },
        HideOverlay: function () {
            if (typeof (overlayApi) != "undefined") {
                overlayApi.close();
            }
        },
        /*
        equal column height for dynamic content/highlighters
        */
        FixEqualColumnHeight: function () {
            var h, m = 0;
            $(".v2-dynamic-content > div").each(function () {
                h = $(this).height();
                m = h > m ? h : m;
            });
            $(".v2-dynamic-content").css("height", m);
        },
        Print: function () {
            $(".print-link").bind("click", function () {
                window.print();
            });
        },
        MegaDrop: function () {
            var limits = {
                left: 190,
                right: 950
            }

            $("#v2-TopNav li > div").each(function (i) {
                // get parent element properties
                var p = {};
                p.element = $(this).parent();
                p.offset = p.element.position().left + 20;
                p.width = p.element.width();

                // get menu properties
                var m = {};
                m.element = $(this);
                m.width = m.element.innerWidth();
                m.left = parseInt(p.offset - (m.width - p.width) / 2) + 12;
                //m.left += 24;

                // background properties
                var bg = {};
                bg.offset = parseInt(p.width / 2);

                // check if dropdown would go off-limits
                if (m.left < limits.left) {
                    m.left = limits.left;
                } else if (m.left + m.width > limits.right) {
                    m.left = limits.right - m.width;
                }

                // calculate where to position dropdown arrow and do it
                bg.left = (p.offset - m.left + bg.offset) + "px";
                $(this).css("background-position", bg.left + " 2px");

                // set position of dropdown
                $(this).css("left", m.left);
            });

            // $("#v2-TopNav > ul").addClass("script-enhanced");

            $("#v2-TopNav > ul > li").bind("mouseenter", function () {
                $("div", this).show();
            }).bind("mouseleave", function () {
                $("div", this).hide();
            });
        },
        AddDropShadow: function () {
            var elm = $("#v2-TopNav li > div > div");

            if (typeof (elm.css("box-shadow")) == "undefined" && typeof (elm.css("-moz-box-shadow")) == "undefined") {
                $(elm).after("<span class=\"drop-shadow left\"></span><span class=\"drop-shadow right\"></span>");
            }
        },
        AdjustCampaignAreaHeight: function () {
            var h = $("#v2-Footer .cols").height();
            $("#v2-Footer .v2-share-price").css("height", h + 18);
        },
        MediaSlider: function () {
            $(".media-slider").each(function () {
                var root = $(this);

                // if thumbnails element is present then it's an 'advanced' slider
                if (root.find(".thumbnails").length > 0) {
                    var itemGroupSize = $(this).find('.item-group:first').children().length;
                    var prevItemIndex = -1;
                    var currentItemIndex;
                    // top scroller
                    var elmTop = root.find(".large-object-wrapper");
                    var elmTabContent = elmTop.parent();
                    if (elmTabContent.find(".thumbnails .item-group").length <= 1) {
                        elmTabContent.find(".thumbnails").next(".navigate").addClass("disabled");
                    }
                    if (elmTop.find(".items > div").length == 1) {
                        elmTop.find(".prev").addClass("disabled");
                        elmTop.find(".next").addClass("disabled");
                    }
                    if (elmTop.length > 0) {
                        elmTop.scrollable({
                            easing: "linear",
                            speed: 400,
                            next: ".large-object-wrapper .next",
                            prev: ".large-object-wrapper .prev",
                            circular: false,
                            onSeek: function () {
                                // get index of current item
                                currentItemIndex = apiTop.getIndex();
                                // move lower scroller to match correct item group
                                apiBottom.seekTo(Math.floor(currentItemIndex / itemGroupSize));
                                // add class to corresponding thumbnail in lower scroll
                                elmBottom.find("img").eq(currentItemIndex).parents("div:first").addClass("selected");
                                // remove class from previous item
                                if (prevItemIndex >= 0 && prevItemIndex != currentItemIndex) {
                                    elmBottom.find("img").eq(prevItemIndex).parents("div:first").removeClass("selected");
                                }
                                prevItemIndex = currentItemIndex;
                            }
                        });
                        var apiTop = elmTop.data("scrollable");
                        apiTop.begin();
                        // bottom scroller
                        // get number of item groups
                        var itemGroups = root.find(".item-group").size();

                        var elmBottom = root.children(".thumbnails").scrollable({
                            easing: "linear",
                            speed: 300,
                            next: ".thumbnails .next",
                            prev: ".thumbnails .prev"
                        }).navigator(".navigate");

                        var apiBottom = elmBottom.data("scrollable");
                        // handle clicking on thumbnails
                        elmBottom.find("div").bind("click", function () {
                            itemGroupIndex = $(this).parent("div.item-group").index();
                            itemIndex = $(this).index();
                            apiTop.seekTo(itemGroupIndex * itemGroupSize + itemIndex);
                        });
                        // if only one, hide navigation
                        if (itemGroups <= 1) {
                            elmBottom.parent().find(".navigate").hide();
                        }
                    }
                } else {
                    var scroller = root.children(".large-object-wrapper");
                    var circular = scroller.find(".items > div").length > 1;
                    if (!circular) {
                        scroller.find(".prev").addClass("disabled");
                        scroller.find(".next").addClass("disabled");
                        scroller.find(".navigate").addClass("disabled");
                    }
                    if (scroller.length > 0) {
                        scroller.scrollable({
                            "easing": "linear",
                            "speed": 400,
                            "circular": circular
                        }).autoscroll({
                            "interval": 5000,
                            "autoplay": false,
                            "autopause": false
                        }).navigator(".navigate");
                        var api = scroller.data("scrollable");
                        api.play();
                        scroller.bind("mouseenter", function () {
                            api.stop();
                        });
                    }
                }
                // overlay text
                root.find(".large-object-wrapper .items div img").each(function () {
                    var _title = $(this).attr("title");
                    $(this).attr("title", "");

                    if (_title != "") {
                        var c = "<div class=\"mediaslider-overlay\">";
                        c += _title ? "<p>" + _title + "</p>" : "";
                        c += "</div>";
                        $(this).after(c);
                    }
                });
            });
        },
        Tabs: function () {
            jQuery(".v2-tabs").tabs();
        },
        ImageList: function (id, propertyName, width, height, imageids) {
            window.open("/Views/Static/ImageListDisplay.aspx?id=" + id + "&imageids="+imageids+"&propertyName=" + propertyName, "ImageWindow", "resizable=yes,scrollbars=yes,width=" + width + ",height=" + height);
        },
        Lightbox: function () {
            $("a.lightbox").each(function () {
                var h = 600; // $(window).height();
                var w = 540;

                if ($(this).attr("data-width") != null) {
                    w = parseInt($(this).attr("data-width"));
                }
                if ($(this).attr("data-height") != null) {
                    h = parseInt($(this).attr("data-height"));
                }
                $(this).fancybox({
                    "width": w,
                    "height": h,
                    "centerOnScroll": true,
                    "padding": 0,
                    "overlayOpacity": .9,
                    "overlayColor": "#333",
                    "disableNavButtons": true,
                    "showNavArrows": false,
                    "autoScale": false,
                    "transitionIn": "none",
                    "transitionOut": "none",
                    "type": "iframe",
                    "titleShow": false,
                    "onClosed": function () {

                    }
                });
            });
        },
        ImageLightbox: function () {
            $("a.imagelightbox").each(function () {
                var h = 600; // $(window).height();
                var w = 540;

                if ($(this).attr("data-width") != null) {
                    w = parseInt($(this).attr("data-width"));
                }
                if ($(this).attr("data-height") != null) {
                    h = parseInt($(this).attr("data-height"));
                }
                $(this).fancybox({
                    "width": w,
                    "height": h,
                    "centerOnScroll": true,
                    "padding": 0,
                    "overlayOpacity": .9,
                    "overlayColor": "#333",
                    "disableNavButtons": true,
                    "showNavArrows": false,
                    "autoScale": true,
                    "transitionIn": "none",
                    "transitionOut": "none",
                    "type": "iframe",
                    "titleShow": false,
                    "onClosed": function () {

                    }
                });
            });
        }
    }
}

/**
* Cookie plugin
*
* Copyright (c) 2006 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/

/**
* Create a cookie with the given name and value and other optional parameters.
*
* @example $.cookie('the_cookie', 'the_value');
* @desc Set the value of a cookie.
* @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
* @desc Create a cookie with all available options.
* @example $.cookie('the_cookie', 'the_value');
* @desc Create a session cookie.
* @example $.cookie('the_cookie', null);
* @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
*       used when the cookie was set.
*
* @param String name The name of the cookie.
* @param String value The value of the cookie.
* @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
* @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
*                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
*                             If set to null or omitted, the cookie will be a session cookie and will not be retained
*                             when the the browser exits.
* @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
* @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
* @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
*                        require a secure protocol (like HTTPS).
* @type undefined
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/

/**
* Get the value of a cookie with the given name.
*
* @example $.cookie('the_cookie');
* @desc Get the value of a cookie.
*
* @param String name The name of the cookie.
* @return The value of the cookie.
* @type String
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
jQuery.cookie = function (name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

$(document).ready(function () {
    Skanska.Ext.InitUtilityMenu();
    Skanska.Ext.InitQuickSearch();
    Skanska.Ext.AddBorderColors();
    Skanska.Ext.AddPlaceholderSupport();
    Skanska.Ext.FixEventBubbling();
    Skanska.Ext.Paging.Apply();
    Skanska.Ext.InitMediaScroller();
    Skanska.Ext.Print();
    Skanska.Ext.AddFadeOverlay()
    Skanska.Ext.MediaSlider();
    Skanska.Ext.Tabs();
    Skanska.Ext.Lightbox();
    Skanska.Ext.ImageLightbox();
    $(".sbutton").makeButton();
    $(".smediabutton").makeButton();
    $(".nationalsearchbutton").makeButton(); 
});

$(window).load(function() {
	Skanska.Ext.FixEqualColumnHeight();
	Skanska.Ext.AdjustCampaignAreaHeight();
	Skanska.Ext.MegaDrop();
	Skanska.Ext.AddDropShadow();
});

