﻿//plugin readyOrAjax
(function ($) {
    $.fn.readyOrAjax = function (f) {
        return this.each(function () {
            var $this = $(this);

            $(function () {
                f();

                if (typeof Sys != "undefined" && Sys && Sys.WebForms && Sys.WebForms.PageRequestManager) {
                    var prm = Sys.WebForms.PageRequestManager.getInstance();
                    if (prm) {
                        prm.remove_endRequest(f);
                        prm.add_endRequest(f);
                    }
                }
            });
        });
    };
})(jQuery);


//async nvtrack
$(document).ready(
    function () {
        setTimeout(function () {
            var protocol = 'https:' == document.location.protocol ? 'https' : 'http';
            var url = $(location).attr('href');

        }, 500);
    }
);

//Optional parameter includeMargin is used when calculating outer dimensions
(function ($) {
    $.fn.getHiddenDimensions = function (includeMargin) {
        var $item = this,
        props = { position: 'absolute', visibility: 'hidden', display: 'block' },
        dim = { width: 0, height: 0, innerWidth: 0, innerHeight: 0, outerWidth: 0, outerHeight: 0 },
        $hiddenParents = $item.parents().andSelf().not(':visible'),
        includeMargin = (includeMargin == null) ? false : includeMargin;

        var oldProps = [];
        $hiddenParents.each(function () {
            var old = {};

            for (var name in props) {
                old[name] = this.style[name];
                this.style[name] = props[name];
            }

            oldProps.push(old);
        });

        dim.width = $item.width();
        dim.outerWidth = $item.outerWidth(includeMargin);
        dim.innerWidth = $item.innerWidth();
        dim.height = $item.height();
        dim.innerHeight = $item.innerHeight();
        dim.outerHeight = $item.outerHeight(includeMargin);

        $hiddenParents.each(function (i) {
            var old = oldProps[i];
            for (var name in props) {
                this.style[name] = old[name];
            }
        });

        return dim;
    }
} (jQuery));

$(document).ready(function () {
    $('.divClick').click(function (e) {
        var $target = $(e.target);

        var launch = $('a', this);
        if (launch.size() > 0) {
            //document.getElementById(launch[0].id).click();
            var id = document.getElementById(launch[0].id);
            window.location.href = $(id).attr('href');
        }
    });
    $(".trim300").text()    // get the text within the div
    .trim()    // remove leading and trailing spaces
    .substring(0, 300)    // get first 300 characters
    .split(".") // separate characters into an array of words, separated by fullstop
    .slice(0, -1)    // remove the last full or partial sentence
    .join(" ") + "..."; // combine into a single string and append "..."

});

var slidingNav = {
    show: true,
    init: function (outercontrol, innercontrol, barcontrol, btncontrol) {
        var height = $(innercontrol).height();

        var outerMinHeight = parseInt($(outercontrol).css("min-height"));
        var barMinHeight = parseInt($(outercontrol).css("min-height"));

        $(outercontrol).height(outerMinHeight > height ? outerMinHeight : height);
        $(barcontrol).height(barMinHeight > height ? barMinHeight : height);
    },
    toggleLeftNav: function () {
        if (this.show) {
            $(".sliding-main").animate({ left: "+=185" }, 500, "swing");
            $(".sliding-leftnav").animate({ width: "+=185" }, 500, "swing");
            $(".sliding-reveal.reveal").hide();
            $(".sliding-reveal.hide").show();
        } else {
            $(".sliding-main").animate({ left: "-=185" }, 500, "swing");
            $(".sliding-leftnav").animate({ width: "-=185" }, 500, "swing");
            $(".sliding-reveal.reveal").show();
            $(".sliding-reveal.hide").hide();
        }

        this.show = !this.show;
    }
};

var sportsMenu = {
    control: null,
    innerControl: null,
    showMoreBtn: null,
    showingPage: 0,
    controlWidth: 0,
    btnWidth: 0,
    visibleWidth: 0,
    hiddenWidth: 0,
    lock: true,
    loadDelay: 500,
    animationTime: 1000,
    btnMargin: 10,
    initialize: function (control, inner, showMoreBtn) {
        var that = this;

        $(control).find("li").css("visibility", "hidden");

        var callback = function () {
            $(that.control).find("li").css("visibility", '');
        }

        setTimeout(function () { that.init(control, inner, showMoreBtn, callback); }, that.loadDelay);
    },
    init: function (control, inner, showMoreBtn, callback) {
        var that = this;

        this.control = control;
        this.innerControl = inner;
        this.showMoreBtn = showMoreBtn;

        this.controlWidth = $(this.control).width();
        this.btnWidth = $(this.showMoreBtn).width();

        var data = this.getVisibility($(this.control).find("li"), 0);

        this.visibleWidth = data[0];
        this.hiddenWidth = data[1];

        var visibleElements = data[2];
        var hiddenElements = data[3];

        if (hiddenElements.length > 0) {
            data = this.getVisibility($(this.control).find("li"), that.btnWidth + that.btnMargin);

            this.visibleWidth = data[0];
            this.hiddenWidth = data[1];

            visibleElements = data[2];
            hiddenElements = data[3];

            $(showMoreBtn).css("visibility", 'visible');
        }

        var dummyLiLength = this.controlWidth - this.visibleWidth + this.btnWidth / 2;

        var dummyLi = '<li style="width: ' + dummyLiLength + 'px; display:block; height:30px;"></li>';

        $(visibleElements).last().after(dummyLi);

        this.innerControl.width(this.visibleWidth + this.hiddenWidth + dummyLiLength + this.btnWidth);

        this.lock = false;

        if ($(hiddenElements).find("div.selected").length > 0) {
            this.showMore();
        }

        if (typeof callback == "function") {
            callback();
        }
    },
    getVisibility: function (coll, buttonOffset) {
        var runningLength = 0;
        var remainingLength = 0;
        var visibleLength = 0;

        var that = this;

        var visibleElements = $();
        var hiddenElements = $();

        $(coll).each(function () {
            var liLength = $(this).width();

            if (runningLength + liLength < that.controlWidth - buttonOffset) {
                visibleLength += liLength;
                visibleElements = $(visibleElements).add($(this));
            } else {
                remainingLength += liLength;
                hiddenElements = $(hiddenElements).add($(this));
            }

            runningLength += liLength;
        });

        return [visibleLength, remainingLength, visibleElements, hiddenElements];
    },
    showMore: function () {
        if (!this.lock) {
            var that = this;

            var slideLeft = (this.showingPage == 0);

            var callback = function () {
                if (slideLeft) {
                    that.showingPage = 1;
                } else {
                    that.showingPage = 0;
                }
                that.lock = false;
            }

            var length = this.controlWidth - this.btnWidth;

            if (slideLeft) {
                $(this.innerControl).animate({ left: "-=" + length }, this.animationTime, "swing", callback);
                $(this.showMoreBtn).animate({ left: "-=" + length }, this.animationTime, "swing");
                setTimeout(function () { $(that.showMoreBtn).addClass("showMore-rotated"); }, this.animationTime / 2);
            } else {
                $(this.innerControl).animate({ left: "+=" + length }, this.animationTime, "swing", callback);
                $(this.showMoreBtn).animate({ left: "+=" + length }, this.animationTime, "swing");
                setTimeout(function () { $(that.showMoreBtn).removeClass("showMore-rotated"); }, this.animationTime / 2);
            }
        }
    }
};

var carousel = {
    control: null,
    currentIndex: 0,
    totalItems: 0,
    interval: 0,
    animate: true,
    items: $(),
    buttons: $(),
    init: function (control, buttons, interval) {
        this.control = control;
        this.interval = interval;

        this.items = $(control).find(".module-item");
        this.buttons = $(buttons).find(".button");

        this.totalItems = $(this.items).length;

        this.showIndex(this.currentIndex);

        if (this.totalItems > 1) {
            this.startAnimation();
        }
    },
    startAnimation: function () {
        this.animate = true;

        var that = this;
        
        setInterval(function () {
            if (that.animate) {
                var nextIndex = that.currentIndex + 1;
                if (nextIndex >= that.totalItems) {
                    nextIndex = 0;
                }

                that.showIndex(nextIndex);
            }
        }, this.interval);
    },
    stopAnimation: function () {
        this.animate = false;
    },
    showIndex: function (index) {
        var itemToShow = $(this.items)[index];

        $(itemToShow).siblings(".module-item").fadeOut();
        $(itemToShow).fadeIn();

        this.currentIndex = index;

        var button = $(this.buttons)[index];
        $(button).siblings().removeClass("selected");
        $(button).addClass("selected");
    },
    selectItem: function (index) {
        this.stopAnimation();
        this.showIndex(index);
        return false;
    },
    goToDetails: function (control) {
        var link = $(control).find("a[id$='lnkBuyNow']").attr("href");

        if (link !== undefined && link !== null && link !== "") {
            window.location.href = link;
        }
    }
};

function loadSelectBoxes() {
    $(".selectBox").find("option").filter(function () {
        return ($(this).val().indexOf("function(") == 0);
    }).remove();

    $(".selectBox").selectBox("create", { autoWidth: true });

    $(".selectBox-options").each(function () {
        setSelectBoxWidth($(this));
    });
}

function setSelectBoxWidth(selectbox) {
    var maxWidth = 0;

    $(selectbox).css('width', '');

    $(selectbox).find('li a').each(function () {
        $(this).css('width', 'auto');

        var width = $(this).getHiddenDimensions(false).width;

        if (width > maxWidth) {
            maxWidth = width;
        }

        $(this).css('width', '');
        $(this).addClass('ellipsis');
    });

    if (maxWidth > 155){
        $(selectbox).addClass("selectBox-wide");
    }
}

function reloadSelectBoxes() {
    var boxes = $(".selectBox")

    $(boxes).selectBox("destroy");
    $(boxes).addClass("selectBox");

    loadSelectBoxes();
}

function validatePassword(control) {
    var pass = $(control).parents(".row").find("input[id$='txtNewPassword']").val();
    var confpass = $(control).parents(".row").find("input[id$='txtNewPasswordConfirm']").val();

    if (pass.length < 6){
        alert("Password should be six characters or longer.");
        return false;
    }

    if (pass != confpass) {
        alert("Passwords don't match. Please retype passwords.");
        return false;
    }

    return true;
}

(function ($) {
    $.fn.tag = function (divClass) {
        var $elem = this;

        if ($elem.children('div.' + divClass).length == 0){
            var position = $elem.css('position');

            if (position !== 'relative' && position !== 'absolute') {
                $elem.css('position', 'relative');
            }
            
            $elem.append('<div class="' + divClass + '"></div>');    
        }

        return $elem;
    }
})(jQuery);

function setCookie(name, value, expiresMinutes, path, domain, secure) {
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime(today.getTime());

    if (expiresMinutes) {
        expiresMinutes = expiresMinutes * 1000 * 60;
    }
    var expires_date = new Date(today.getTime() + (expiresMinutes));

    document.cookie = name + "=" + escape(value) +
((expiresMinutes) ? ";expires=" + expires_date.toGMTString() : "") +
((path) ? ";path=" + path : "") +
((domain) ? ";domain=" + domain : "") +
((secure) ? ";secure" : "");
}

$(document).ready(function () {

    var ua = navigator.userAgent.toLowerCase();

    if (ua.indexOf("safari") != -1 && ua.indexOf("chrome") == -1) {
        $('select.safariFix').css('background', 'url("../images/safariArrow.png") no-repeat scroll right center #2D2D37');
    }

    $('input[type="text"],textarea').live('mouseleave blur', function () {
        if (/(<([^>]+)>)/ig.test($(this).val())) {
            var msg = $(this).parent().find('#scriptWarn');
            if (!msg.length)
                $(this).parent().append('<div id="scriptWarn">Please don\'t use HTML tags</div>');
        }
    });
});

function setCaptchaImage() {
    $('div.captchaImage img').attr('src', $('div.captchaImage img').attr('alt'));
}
