/*
*
* Carnegie Fabrics
*
* Common JS
* file: common.js 
* dev: www.theatomgroup.com
* Provides universal event handling and shared functionality.
*
*/

// Default ready handler
// @Param $: (jQuery) object
jQuery(function ($) {

    // get the page request manager
    var pageRequestManager = Sys.WebForms.PageRequestManager.getInstance();

    function onUpdatePanelStart() {
        Sys.Debug.trace("onUpdatePanelStart");
        // update panel is loading -- add spinner class
        $(document.body).addClass("showSpinner");
    }
    pageRequestManager.add_beginRequest(onUpdatePanelStart);
    //Sys.Application.add_unload(onUpdatePanelStart);
    $(window).bind('beforeunload', onUpdatePanelStart);


    function onUpdatePanelFinish() {
        // update panel has finished -- remove spinner class
        $(document.body).removeClass("showSpinner");
    }
    pageRequestManager.add_pageLoaded(onUpdatePanelFinish);



    $(".shows-spinner").live("click", onUpdatePanelStart);

    // This is the object to clear
    $.fn.clear = function (who, not, when, what) {
        var that = this;

        // Bind to each selector
        $(who).each(function (i, e) {
            // Default to click
            e = (e === "document") ? document : e;
            $(e).bind((when || "click"), function (evt) {
                if (typeof what === "function")
                    what.call(that, evt);
                else
                    that.hide();
            });
        });

        // Prevent the object from closing
        $(not).bind(when || "click", function (evt) {
            evt.stopPropagation();
        });

        return that;
    }

    // Primary navigation
    var $primary_nav = $("#primary-nav > ul > li").hover(
        function (evt) {
            var $this = $(this);
            $this.addClass("focus");
            $this.find("ul").addClass("show");

            setMenuHeight.call(this);
        },
        function () {
            var $this = $(this);
            $this.removeClass("focus");
            $this.find("ul").removeClass("show");
            $this.find("ul ul").hide();

            setMenuHeight.call(this);
        }
    );

    // Carnegie Home Image Rollover
    $("#primary-nav > ul > li").hover(function () {
        //location.hash = "bg-"+ $(this).index();
        //$("body").prepend("<span>" + $(this).index() + "</span>");
        $("#carnegie div").removeClass().addClass("bg-" + $(this).index());
    }, function () {
        // do nothing
    });

    // breacrumb lowercase
    if ($('.breadcrumb').length) {
        (function () {
            var crumbGroup = $(".CMSBreadCrumbsLink, .CMSBreadCrumbsCurrentItem"),
				text = crumbGroup.text();
            if (text != "surface iQ") crumbGroup.css("text-transform", "lowercase");
        })();
    };

    (function () {
        var ul = $('ul.products');
        if (!ul.children('li').length) ul.css('display', 'none');
    })();

    // remove last dash from product detail page swatch views
    //$(".img-actions > a").filter(":visible").filter(":last").remove("span.dash");

    // Set Height for Nav Columns
    function setMenuHeight() {
        var $this = $(this),
            $window = $(window),
            height = $window.height() - ($this.offset().top + $this.height() + parseFloat($this.children("ul").css("padding-top")));

        $("#navsecond > li > ul").css("height", height + "px");
    }

    // show sub menu ul in primary nav on click
    $("#primary-nav ul ul li .CMSListMenuLink").click(
        function () {
            $(this).next("ul").is(":visible") ? $(this).next("ul").hide() : $(this).next("ul").show();
            if ($(this).next("ul").length > 0) return false;
        }
    );

    // what's new margin on last column
    $(".whats-new-column:first").addClass("first");

    // DOM Window
    $('.defaultDOMWindow').openDOMWindow({
        eventType: 'click',
        loader: 1,
        loaderHeight: 16,
        loaderWidth: 17,
        borderSize: 0,
        windowPadding: 0,
        overlayOpacity: 50,
        width: 600,
        windowBGColor: '#000',
        height: 500
    });

    // no margin on 5th product
    $("ul.products li").filter(":nth-child(5n)").css("margin-right", "0");

    // no border on first filter nav item
    $("#filterlist li:first-child").addClass("first-child");

    // no margin on 4th product in sample cart
    $(".CartTable ul.products li").filter(":nth-child(4n)").css("margin-right", "0");
    $(".CartTable ul.products li").filter(":nth-child(5n)").css("margin-right", "5px");

    // zig zag on first li in my projects 
    $("#favs-cart-products .products li:nth-child(4n+1) .image-link").prepend("<span class='zig-zag'>zig zag</span>");

    // toggle value
    $('input[placeholder]').placeholder({
        placeholderCSS: {
            'font': '11px Arial',
            'color': '#A7A9AD',
            'position': 'absolute',
            'left': '5px',
            'top': '3px',
            'overflow-x': 'hidden'
        }
    });

    // display inline block on placeholder spans in ecart
    $(".Zip,.City,.txt-city,.txt-zip").parent("span").css("display", "inline-block");


    // hover affect on input buttons
    $('.search input.btn, .FormButton,.search-nav input.filter-btn,#favs-cart-details input.btn, #favs-cart-products input.btn, .btn').hover(
        function () {
            $(this).css({
                'color': "#333",
                'cursor': "pointer"
            });
        },
        function () {
            $(this).css({
                'color': "#6D6E71",
                'cursor': "pointer"
            });
        }
    );

    $(".txtTopSearch").keypress(function (e) {
        var EnterKey = 13;
        if (e.keyCode == EnterKey) {
            e.preventDefault();
            onTopSearchSubmit();
        }
    });
});



// handler for the top "fuzzy" search button
function onTopSearchSubmit() {
    // get search terms
    var searchTerms = $(".txtTopSearch").val();

    // encode
    var searchTermsEncoded = searchTerms.replace(/ /g, '%2B').replace(/-/g, ';');

    if (typeof (siteRoot) == "undefined")
        siteRoot = "/";

    // send to search
    window.location = siteRoot + 'productsearch.aspx#v={-f-.{-Usage-.[0]}_-p-.1_-s-.-' + searchTermsEncoded + '-}';
}


function setVisible(element, isVisible) {
    if (isVisible)
        $(element).show();
    else
        $(element).hide();
}

function imageError(img, size) {
    img.onerror = null;
    img.src = "carnegie/includes/img/content/product.png";
}
