var gz = (function()
{
    function labelIfBlank( element, label, color ) {
        if( element.get('value').match(/^\s*$/) )
        {
            element.set('value', label);
            if( color )
            {
                element.setStyle('color', color);
            }
        }
    };

    function blankIfLabel( element, label, color ) {
        if( element.get('value') == label )
        {
            element.set('value', '');
            if( color )
            {
                element.setStyle('color', color);
            }
        }
    };

    function labeling( selector, label )
    {
        YUI().use('node', 'event', function( Y )
        {
            Y.on('available', function( e )
            {
                labelIfBlank(this, label);
            }, selector);

            Y.on('focus', function( e )
            {
                blankIfLabel(this, label);
            }, selector);

            Y.on('blur', function( e )
            {
                labelIfBlank(this, label);
            }, selector);
        });
    };

    function autolabel( selector, options )
    {
        YUI().use('node', 'event', function( Y )
        {
            Y.all(selector).each(function( item, index, list )
            {
                var label = item.get('value');
                var color = item.getStyle('color');

                item.on('focus', function( e )
                {
                    if( options && options['focusColor'] )
                    {
                        blankIfLabel(this, label, options['focusColor']);
                    }
                    else
                    {
                        blankIfLabel(this, label);
                    }
                });

                item.on('blur', function( e )
                {
                    if( options && options['blurColor'] )
                    {
                        labelIfBlank(this, label, options['blurColor']);
                    }
                    else
                    {
                        labelIfBlank(this, label, color);
                    }
                });
            });
        });
    };

    function loadwin( eventFunction )
    {
        YUI().use('node', function( Y )
        {
            Y.on("load", eventFunction, Y.config.win);
        });
    };

    function unloadwin( eventFunction )
    {
        YUI().use('node', function( Y )
        {
            Y.on("unload", eventFunction, Y.config.win);
        });
    };

    function value( element )
    {
        var value;
        if(element)
        {
            value = element.get('value');
        }
        return value;
    };

    function rewrite( alink, callback )
    {
        YUI().use("io-base", "node", function( Y ) {
            var getURL = function ( alink )
            {
                if( !alink )
                {
                    return '';
                }

                if( Y.Lang.isString(alink) )
                {
                    return alink;
                }
                else if( alink.href )
                {
                    return alink.href;
                }
                else
                {
                    return alink.toString();
                }
            };

            //A function handler to use for successful requests:
            var onSuccess = function( ioId, o )
            {
                if( o.responseText !== undefined )
                {
                    callback(o);
                }
            };

            //A function handler to use for failed requests:
            var onFailure = function( ioId, o )
            {
                alert('Failed refresh.');
            };

            //Subscribe our handlers to IO's global custom events:
            Y.on('io:success', onSuccess);
            Y.on('io:failure', onFailure);

            /* Configuration object for POST transaction */
            var cfg = {
                method: 'POST'
            };

            //Handler to make our XHR request
            Y.io(getURL(alink), cfg);
        });
    };

    return {
        labeling: labeling,
        autolabel: autolabel,
        loadwin: loadwin,
        unloadwin: unloadwin,
        value: value,
        rewrite: rewrite
    };
})();

var Expire = (function()
{
    function inDays( days )
    {
        return inMillis(days * 24 * 60 * 60 * 1000);
    }

    function inHours( hours )
    {
        return inMillis(hours * 60 * 60 * 1000);
    }

    function inMinutes( minutes )
    {
        return inMillis(minutes * 60 * 1000);
    }

    function inSeconds( seconds )
    {
        return inMillis(seconds * 1000);
    }

    function inMillis( period )
    {
        var date = new Date();
        date.setTime(date.getTime() + ( period || 0 ));
        return date.toUTCString();
    }

    return {
        inDays :inDays,
        inHours :inHours,
        inMinutes :inMinutes,
        inSeconds :inSeconds,
        inMillis :inMillis
    };
})();

function linkPopup( e )
{
    e.preventDefault();
    popup(e.currentTarget.get('href'));
}

function popup( alink, windowname )
{
    if( !windowname )
    {
        windowname = 'MooresPopup';
    }

    return windower( alink, windowname, 'height=600,width=690,location=no,top=40,left=40,scrollbars=yes,menubar=no,toolbar=no,resizable=no,directories=no,status=no');
}

function windower( alink, windowname, specs )
{
    if( !window.focus )
    {
        return true;
    }

    var url;
    if( typeof(alink) == 'string' )
    {
        url = alink;
    }
    else
    {
        url = alink.href;
    }

    if( !windowname )
    {
        windowname = 'Moores';
    }

    if( navigator.userAgent.indexOf('Chrome/') > -1 )
    {
        if( window[windowname] )
        {
            window[windowname].close();
            window[windowname] = null;
        }
    }

    window[windowname] = window.open(url, windowname, specs);
    if( window[windowname] && window[windowname].focus )
    {
        window[windowname].focus();
    }

    return false;
}

YUI().use('node', 'cookie', 'event-mouseenter', 'dump', function( Y )
{
    Y.on('click', linkPopup, 'a.popup');

    function getItems( prefix, search )
    {
        var items = Y.Array([]);
        var count = Y.Cookie.get(prefix);
        if( search )
        {
            items.push(search);
        }
        for( var index = 0, limit = ( count ? count : 0 ); index < limit; index++ )
        {
            var key = prefix + "-" + ( index + 1 );
            var value = Y.Cookie.get(key);
            if( !search || value != search )
            {
                items.push(value);
            }
        }

        return items;
    }

    function setItems( prefix, items )
    {
        Y.Array.each(items || Y.Array([]), function( value, index, fa ) {
            var key = prefix + "-" + ( index + 1 );
            Y.Cookie.set(key, value, { path: '/' });
        });
    }

    function addToList( item, tool )
    {
        var prefix = Y.Array(['colorsViewed', 'datesViewed', 'itemsViewed'])[tool];

        setItems(prefix, getItems(prefix, item));

        showItemsViewed();
    }

    function showItemsViewed()
    {
        var items = getItems('itemsViewed');
        if( items.length > 0 )
        {
            var root = '<br />';
            var linkTemplate
                    = '<a id="{item}" href="/mor/itemDetail.jsp?product={item}">'
                    + '<img src="/mor/images/60x60/{item}_main_60x60.jpg" style="width: {width}px;" alt="" />'
                    + '</a>';

            var limit = 5;
            if( items.length > limit )
            {
                items = items.slice(0, limit);
            }
            
            Y.Array.each(items, function( value, index, fa ) {
                var thumbSize = ( index == 0 ? 60 : 37 );
                if( navigator.appName.indexOf("Microsoft ") >= 0 )
                {
                    thumbSize--;
                }

                var params = {
                    item: value,
                    width: thumbSize
                };

                var link = Y.Lang.sub(linkTemplate, params);
                root += link;
            });

            var detail = Y.one('#itemsViewedDetail');
            if( detail )
            {
                detail.purge(true);
                detail.setContent(root);
                var links = detail.all('a');
                if( links && !links.isEmpty() )
                {
                    links.on('click', function( e )
                    {
                        var target = e.currentTarget;
                        addToList(target.get('id'), 2);
                    });
                }
            }
            var viewAll = Y.one('#viewAll');
            if(viewAll)
            {
                viewAll.show();
            }
        }
    }

    function switchTool( tool )
    {
        var lastTool;
        if( tool && Y.Lang.isString(tool) )
        {
            lastTool = tool;
        }
        else
        {
            lastTool = Y.Cookie.get('last_tool');
        }

        if( !lastTool )
        {
            lastTool = 'colorTool';
        }

        if( 'itemsViewed' == lastTool )
        {
            showItemsViewed();
        }

        var parameters = {
            attr:'id',
            value:lastTool
        };

        var tab = Y.all(Y.Lang.sub('#toolsMenu > [{attr}={value}Tab]', parameters));
        if(!tab)
        {
            parameters.value = 'colorTool';
            tab = Y.all(Y.Lang.sub('#toolsMenu > [{attr}={value}Tab]', parameters));
        }

        if(tab)
        {
            Y.all('#toolsMenu > .toolsTab').removeClass('active');
            tab.addClass('active');
            var content = Y.all(Y.Lang.sub('#toolsMenu > [{attr}={value}]', parameters));
            if(content)
            {
                Y.all('#toolsMenu > .toolsContent').hide();
                content.show();
            }
        }

        Y.Cookie.set('last_tool', lastTool, { path: '/' });

        return false;
    };

    Y.on('contentready', switchTool, '#toolsMenu');

    Y.on('click', function( e )
    {
        e.preventDefault();
        var target = e.currentTarget;
        var parent = target.get('parentNode');
        var tool = parent.get('id').replace(/Tab$/, '');
        switchTool( tool, target.get('href') );
    }, '#toolsMenu > .toolsTab > a');

    Y.on('focus', function( e )
    {
        var target = e.currentTarget;
        target.blur();
    }, '#toolsMenu > .toolsTab > a');

    function hoverString( source, re, value )
    {
        if (source.search(re) != -1)
        {
            source = source.replace(re, value);
        }

        return source;
    }

    Y.on('mouseenter', function (e) {
        var source = this.get('src');
        source = hoverString( source, /_up\./, '_over.' );
        source = hoverString( source, /-up\./, '-over.' );
        this.set('src', source);
    }, 'img.hover');

    Y.on('mouseleave', function (e) {
        var source = this.get('src');
        source = hoverString( source, /_over\./, '_up.' );
        source = hoverString( source, /-over\./, '-up.' );
        this.set('src', source);
    }, 'img.hover');
});

function isEmpty(value) {
    return !value || value.length <= 0;
}

function isValidEmail(value) {
    var LEGAL_ASCII_PATTERN = /^[\x00-\x7F]+$/;
    var STRUCTURE_PATTERN = /^[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z_+])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9}$/;

    // Check the whole email address structure
    return value && LEGAL_ASCII_PATTERN.test(value) && STRUCTURE_PATTERN.test(value);
}

function isValidPostal(value) {
    var STRUCTURE_PATTERN = /^[a-z]\d[a-z] ?\d[a-z]\d$/i;

    // Check the postal code structure
    return value && STRUCTURE_PATTERN.test(value);
}

