var Util = function () {

    var path = "/";
    var search_path = null;
    var search_id = null;
    var return_url = null;

    return {

        InArray: function (what, where) {

            for (var i = 0; i < where.length; i++)
                if (what == where[i])
                    return true;

            return false;
        },

        AliveOptionsMenu: function () {
            $('div.b-options').live('click', function () {
                var is_visible = $(this).next().is(':visible');
                $(this).closest('tbody').find('div.b-options-flyout').hide();
                if (!is_visible) $(this).next().show();
                return false;
            });
        },

        AliveSearchSnippet: function () {
            $('#cat-search').click(function () {
                $(this).toggleClass('m-active');
                $('#cat-search-flyout').toggle();
                return false;
            });
        },

        AliveFakeDropDowns: function () {

            $('div.b-options').live('click', function () {
                $(this).parent().find('div.b-options-flyout').toggle();
                return false;
            });

            $('div.b-options-flyout > div.b-options-flyout-item > span.m-pseudo-link').live('click', function () {
                $(this).parent().parent().prev().html($(this).html());
            });

            $('div.b-options-flyout > div.b-options-flyout-item > span.m-pseudo-link').live('mouseover', function () {
                $(this).addClass('m-over');
            });

            $('div.b-options-flyout > div.b-options-flyout-item > span.m-pseudo-link').live('mouseout', function () {
                $(this).removeClass('m-over');
            });
        },

        GenerateRandomID: function (max_range) {
            return parseInt(Math.random() * max_range);
        },

        ToUpperFirstLetter: function (str) {
            return str.substr(0, 1).toUpperCase() + str.substr(1);
        },

        IsNumber: function (str) {

            if (!/^\d+$/.test(str)) return false;

            return true;
        },

        IsNullOrEmpty: function (str) {

            if (str == null) return true;

            if (str.replace(/^\s+/, '').replace(/$\s+/, '') == '') return true;

            return false
        },

        ShowRemoveLightbox: function (lightbox, title, text, func) {
            $('#overlay').show();
            lightbox.find('img[name="remove-button"]').unbind('click').click(function () { func(); });
            lightbox.find('span[name="title"]').html(title);
            lightbox.find('p[name="text"]').html(text);
            lightbox.show();
        },

        HideLightBox: function (elt) {
            $('#overlay').hide();
            $(elt).closest('div.h-lightbox').hide();
        },

        ShowLightBox: function (selector) {
            $('#overlay').show();
            $(selector).show();
        },

        AliveImagesOver: function (selector) {
            $(selector).mouseover(function () {
                $(this).attr('src', $(this).attr('src').replace('-ico.png', '-over-ico.png'));
            }).mouseout(function () {
                $(this).attr('src', $(this).attr('src').replace('-over-ico.png', '-ico.png'));
            });
        },

        // binding all "label" elements to their parents
        AliveLabels: function () {
            $('label').each(function () {
                var id = 'l' + Util.GenerateRandomID(10000);
                $(this).prev().attr('id', id);
                $(this).attr('for', id);
            });
        },

        ShowOnPasswordEnter: function (inputPassword, elementid) {
            if ($.trim($(inputPassword).val()) != '') {
                $(elementid).show();
            } else {
                $(elementid).hide();
            }
        },

        AdjustIframeHeight: function (iframe, shift) {

            $(iframe).prev().hide().end().show(0, function () {
                if ($(iframe).contents().find('div.b-content').html() != null) {
                    $(iframe).height($(iframe).contents().find('div.b-content').height() + (shift ? shift : 0));
                } else {
                    $(iframe).height($(iframe).contents().find('body').height() + (shift ? shift : 0));
                }
            })
        },

        AdjustIframeHeightIfNeeded: function (iframe, shift) {

            $(iframe).prev().hide().end().show(0, function () {

                var contentHeight = null;

                if ($(iframe).contents().find('div.b-content').html() != null) {
                    var contentHeight = $(iframe).contents().find('div.b-content').height() + (shift ? shift : 0);
                } else {
                    var contentHeight = $(iframe).contents().find('body').height() + (shift ? shift : 0);
                }

                if ($(iframe).height() < contentHeight) {
                    $(iframe).height(contentHeight);
                }
            })
        },

        RefreshImage: function (img) {
            var now = new Date();
            $(img).prev().attr('src', $(img).prev().attr('src') + '?' + now.getTime());
        },

        isSecurityCodeValid: function (type, code) {
            if (type == "AmEx") {
                // American Express: cvv code - 4 digits
                if (!/^\d{4}$/.test(code)) return false;
            } else {
                // All others: cvv code - 3 digits
                if (!/^\d{3}$/.test(code)) return false;
            }

            return true;
        },

        isCreditCardNumberValid: function (type, ccnum) {

            if (type == "Visa") {
                // Visa: length 16, prefix 4, dashes optional.
                var re = /^4\d{3}-?\d{4}-?\d{4}-?\d{4}$/;
            } else if (type == "MasterCard") {
                // Mastercard: length 16, prefix 51-55, dashes optional.
                var re = /^5[1-5]\d{2}-?\d{4}-?\d{4}-?\d{4}$/;
            } else if (type == "Discover") {
                // Discover: length 16, prefix 6011, dashes optional.
                var re = /^6011-?\d{4}-?\d{4}-?\d{4}$/;
            } else if (type == "AmEx") {
                // American Express: length 15, prefix 34 or 37.
                var re = /^3[4,7]\d{13}$/;
            } else if (type == "Diners") {
                // Diners: length 14, prefix 30, 36, or 38.
                var re = /^3[0,6,8]\d{12}$/;
            }


            if (!re.test(ccnum)) return false;
            // Remove all dashes for the checksum checks to eliminate negative numbers
            ccnum = ccnum.split("-").join("");
            // Checksum ("Mod 10")
            // Add even digits in even length strings or odd digits in odd length strings.
            var checksum = 0;
            for (var i = (2 - (ccnum.length % 2)); i <= ccnum.length; i += 2) {
                checksum += parseInt(ccnum.charAt(i - 1));
            }
            // Analyze odd digits in even length strings or even digits in odd length strings.
            for (var i = (ccnum.length % 2) + 1; i < ccnum.length; i += 2) {
                var digit = parseInt(ccnum.charAt(i - 1)) * 2;
                if (digit < 10) { checksum += digit; } else { checksum += (digit - 9); }
            }

            return ((checksum % 10) == 0) ? true : false;
        },

        AddLoader: function () {

            var doc = parent.document != document ? parent.document : document;

            $(doc).find('div.b-overlay').show();
            $(doc.body).prepend('<div id="loader" style="text-align:center;"><img alt="Loader" src="' + Util.Path() + 'res/default/images/ico/loader-ico.gif" /></div>');
        },

        RemoveLoader: function () {

            var doc = parent.document != document ? parent.document : document;

            $(doc).find('div.b-overlay').hide();
            $(doc.body).children('div:first').remove();
        },


        ShowLicenses: function (img, item_id) {
            $.ajax(
			{
			    url: Util.Path() + 'catalog/get-licenses',
			    data: "id=" + item_id,
			    success: function (r) {
			        var body = $(parent.document).find('body');
			        body.find('#licenses').remove();
			        body.find('div.b-overlay').show();
			        body.prepend(r.html).find('#licenses').show();
			    }
			});
        },

        AddSingleToCart: function (img) {

            $(img).unbind();

            $.ajax(
			{
			    type: "POST",
			    url: Util.Path() + 'ecom/sc/checkout/add-to-cart',
			    data: "id=" + $(img).parent().prev().find('input:checked').attr('id'),
			    success: function (r) {
			        parent.window.location.href = Util.Path() + 'ecom/sc/checkout'
			    }
			});
        },

        ShowNextError: function (control, msg) {
            $(control).parent().next().html(msg).show();
            return false;
        },

        HideNextError: function (control) {
            $(control).parent().next().hide();
            return false;
        },

        AdjustIframe: function (iframe) {
            $(iframe).prev().hide().end().show();
        },

        GoToSearchPage: function (category, q) {
            q = q.replace(/\+/g, "%252B");
            var path = search_path + "?tags=" + category + "&search=" + (q == 'Search' ? '' : q);

            if (Util.IsInIframe()) {
                parent.window.location.href = path;
            } else {
                window.location.href = path;
            }

            return false;
        },

        SearchPath: function (p) {
            if (p) {
                search_path = p;
            }
            else {
                return search_path;
            }
        },

        SearchResultsPath: function (p) {
            search_results_path = p;
        },

        Path: function (p) {
            if (p) {
                path = p + (!/\/$/.test(p) ? "/" : "");
            }
            else {
                return path;
            }
        },

        Return_Url: function (url) {
            if (url) {
                return_url = url;
            }
            else {
                return return_url;
            }
        },

        Encode: function (text) {
            return $('<div/>').text(text).html();
        },

        GoHome: function (path) {
            window.location.href = path ? Util.Path() + path : Util.Path();
        },

        GoToPreviousPage: function () {
            window.location.href = Util.Return_Url();
        },

        GoToPage: function (path) {

            if (path.substr(0, 1) == "/") {
                window.location.href = path;
            }
            else {
                window.location.href = Util.Path() + path;
            }
        },

        PreloadImages: function (images, path) {
            if (images instanceof Array) {
                for (var i in images) {
                    $("<img>").attr("src", (path ? path : '') + images[i]);
                }
            }
            else {
                images.each(function () {

                    $("<img>").attr("src", $(this).attr('src').replace(/-btn\.png/, '-over-btn.png').replace(/-ico\.png/, '-over-ico.png'));

                });
            }
        },

        IsPasswordValid: function (password) {

            var len = password.length;

            if (len < 8 || len > 20) return false;

            if (!/[a-z]/i.test(password) || !/\d/.test(password)) return false;

            return true;
        },

        IsEmailValid: function (email) {
            if (!/^[a-zA-Z0-9._\-'\+\$]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/.test(email)) return false;

            return true;
        },

        HideConfirmation: function (span) {
            $(span).parent().parent().parent().parent().hide();
            $('#overlay').hide();

            return true;
        },

        ShowConfirmation: function (text, func) {

            $('#confirmation').find('p:first').html(text).end().find('p:last > img:last').unbind().click(function () { $(this).parent().parent().parent().parent().hide(); $('#overlay').hide(); func(); }).end().show();
            $('#overlay').show();

            return false;
        },

        ShowAlert: function (title, text, not_in_iframe) {

            if (not_in_iframe) {
                $('#alert').find('p:first').html(text).end().find('span:first').html(title).end().show();
                $('#overlay').show();
            }
            else {
                $(parent.document).find('#alert').find('p:first').html(text).end().find('span:first').html(title).end().show();
                $(parent.document).find('#overlay').show();
            }

            return false;
        },

        ShowProcessing: function (title, text, not_in_iframe) {

            if (not_in_iframe) {

                $('#processing').find('p:first').next().html(text).end().end().find('span:first').html(title).end().show();
                $('#overlay').show();
            }
            else {
                $(parent.document).find('#processing').find('p:first').next().html(text).end().end().find('span:first').html(title).end().show();
                $(parent.document).find('#overlay').show();
            }

            return false;
        },

        HideProcessing: function (not_in_iframe) {

            if (not_in_iframe) {
                $('#processing').hide()
                $('#overlay').hide();
            }
            else {
                $(parent.document).find('#processing').hide();
                $(parent.document).find('#overlay').hide();
            }

            return false;
        },

        WhatShouldHappen: function () {
            alert('What should happen by clicking this?');
            return false;
        },

        NotImplemented: function () {
            alert('Sorry, not implemented yet');
            return false;
        },

        IsValidEmail: function (email) {
            return /^[a-zA-Z0-9._\-'\+\$]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/.test(email);
        },

        IsInIframe: function () {
            return document != parent.document;
        }

    }
} ();
