var YI = {
    registry: {
    },

    images_to_preload: [],

    set: function(key, value) {
        YI.registry[key] = value;
    },

    get: function(key) {
        return YI.registry[key];
    },

    generateRandomNumber: function() {
        return (("" + Math.random()).substring(2));
    },

    staticContent: function(url) {
        if (YI.get('static_content_url')) {
            if (url.indexOf('http://') !== -1) {
                return url;
            }

            if (url.indexOf('/') === 0) {
                url = url.substring(1);
            }

            return YI.get('static_content_url') + url;
        }

        YI.logger.debug("static_content_url not set - returning URL [" + url + "]");

        return url;
    },

    relativePath: function (path, sslAllowed) {
        if (!YI.get('relative_path')) {
            YI.logger.debug("relative_path not set - returning path [" + path + "]");
            return path;
        }

        if (path.indexOf('/') === 0) {
            path = path.substring(1);
        }

        var sslPath = YI.get('relative_path_ssl');
        
        return (sslAllowed && sslPath ? sslPath : YI.get('relative_path')) + path;
    },

    addFrameworkParameters: function(url) {
        var parameters = 0;

        $.each(['langId', 'partnerId', 'geoip', 'mc', 'wt_cc1'], function(index, value) {
            if ($.url.param(value)) {
                url += (parameters ? '&' : '?') + value + '=' + $.url.param(value);
                parameters++;
            }
        });

        return url;
    },

    partners: {
        /**
         * Check if current user comes from partner
         *
         * @param {string|number} partnerId e.g. 501 or 'gtw' (numeric partner IDs must be in 'number' type)
         */
        isFromPartner: function(partnerId) {
            if (!$.url.param('partnerId')) {
                return false;
            }

            if (typeof partnerId == 'number') {
                return $.url.param('partnerId') == partnerId;
            }

            if (typeof partnerId == 'string') {
                return $.url.param('partnerId').indexOf(partnerId) === 0;
            }

            return false;
        }
    },

    flash: {
        load: function(path, container_id, width, height, flash_variables, flash_parameters, callback) {
            if (flash_variables == undefined) {
                flash_variables = {};
            }

            if (flash_parameters == undefined) {
                flash_parameters = {};
                
                flash_parameters.scale = "noscale";
                flash_parameters.quality = "best";
                flash_parameters.salign = "TL";
                flash_parameters.menu = "false";
                flash_parameters.wmode = "transparent";
                flash_parameters.allowScriptAccess = "always";
            }

	        swfobject.embedSWF(path, container_id, width, height, "9.0.0", false, flash_variables, flash_parameters, {}, callback ? function(e) {
                callback(e.success);
            } : undefined);
        }
    },

    image: {
        /**
         * Preload element background image
         *
         * @param element
         */
        preloadBackground: function(element) {
            $(element).each(function() {
                var background_image = $(this).css('background-image');

                if (background_image && background_image != 'none') {
                    YI.image._preload(YI.image._getBackgroundImageFromStyleValue(background_image));
                }
            });
        },

        /**
         * Preload element mouseover background image by specifing element
         *
         * @param element
         * @param hover_suffix specify suffix for hover image. It will be added to current background image before extension
         * @param new_extension Optional. Specify if mouseover image has different extension that original background
         */
        preloadBackgroundHover: function(element, hover_suffix, new_extension) {
            $(element).each(function() {
                var background_image = $(this).css('background-image');

                if (background_image && background_image != 'none') {
                    if (hover_suffix == undefined) {
                        hover_suffix = '_over';
                    }

                    background_image = YI.image._getBackgroundImageFromStyleValue(background_image);
                    background_image = YI.image._addSuffixToFilename(background_image, hover_suffix, new_extension);

                    YI.image._preload(background_image);
                }
            });
        },

        /**
         * Preload image by specifying path
         *
         * @param path Image URL
         */
        preloadImage: function(path) {
            YI.image._preload(YI.staticContent(path));
        },

        /**
         * Helper method for taking URL from CSS value for background.
         * e.g. For url("http://path") it will return http://path.
         *
         * @param style_value e.g. url("http://path")
         */
        _getBackgroundImageFromStyleValue: function(style_value) {
            return style_value.replace(/url\(["']?([^"']*)["']?\)/, '$1');
        },

        /**
         * Add suffix to filename.
         * E.g. for file.jpg and suffix '_test' it will return file_test.jpg.
         * This function will also work with URLs.
         *
         * @param filename
         * @param suffix
         * @param new_extension Optional. Specify if you want to change extension for returned value.
         */
        _addSuffixToFilename: function(filename, suffix, new_extension) {
            var last_dot = filename.lastIndexOf('.');
            var begin = filename.substring(0, last_dot);
            var end = filename.substring(last_dot);

            return begin + suffix + (new_extension ? '.' + new_extension : end);
        },

        /**
         * Add URL to preload queue.
         *
         * @param url
         */
        _preload: function(url) {
            if ($.inArray(url, YI.images_to_preload) == -1) {
                YI.logger.debug("Adding image to be preloaded: " + url);
                YI.images_to_preload.push(url);
            }
        },

        /**
         * Preloads all images in preload queue.
         * Before preloading this method triggers event 'preload.before'.
         */
        _processPreloading: function() {
            YI.logger.switchGroup('Processing preloading');
            
            $(document).trigger('preload.before');

            for (var i in YI.images_to_preload) {
                if (typeof YI.images_to_preload[i] != 'string') {
                    continue;
                }
                
                YI.logger.debug("Preloading image: " + YI.images_to_preload[i]);

                var image = document.createElement('img');
                image.src = YI.images_to_preload[i];
            }

            YI.logger.switchGroup();
        }
    },

    logger: {
        currentGroup: undefined,

        /**
         * Group logs
         *
         * @param {string=} group Leave empty if you want to switch to general group
         */
        switchGroup: function(group) {
            try {
                if (group != YI.logger.currentGroup) {
                    if (YI.logger.currentGroup != undefined) {
                        console.groupEnd();
                    }

                    if (group != undefined) {
                        YI.logger.currentGroup = group;
                        console.group(group);
                    }
                }
            } catch(e) {
            }
        },

        isDebugEnabled: function() {
            return YI.get('debug') === true;
        },

        debug: function(message) {
            if (YI.logger.isDebugEnabled()) {
                try {
                    console.log(message);
                } catch (e) {
                }
            }
        },

        debugWithGroup: function(group, message) {
            YI.logger.switchGroup(group);

            if (YI.logger.isDebugEnabled()) {
                try {
                    console.log(message);
                } catch (e) {
                }
            }
        },

        debugWithObject: function(message, object) {
            if (YI.logger.isDebugEnabled()) {
                try {
                    console.log(message);

                    if (object != undefined) {
                        console.dir(object);
                    }
                } catch (e) {
                }
            }
        },
    
        error: function(message) {
            try {
                console.error(message);
            } catch (e) {
            }
        }
    },

    /**
     * @deprecated
     */
    isDebugEnabled: function() {
        return YI.logger.isDebugEnabled();
    },

    /**
     * @deprecated
     */
    debug: function(message) {
        YI.logger.debug(message);
    },

    /**
     * @deprecated
     */
    error: function(message) {
        YI.logger.error(message);
    }
};

