﻿String.prototype.trim = function() 
{
	var x = this;
	x = x.replace(/^\s*(.*)/, '$1');
	x = x.replace(/(.*?)\s*$/, '$1');
	return x;
};

String.prototype.startsWith = function(s) 
{
    if (s == this.substring(0, s.length))
    {
        return true;
    }
    else
    {
        return false;
    }
};

String.prototype.fixLB = function()
{
	var x = this;
	x = x.replace(/\r/g, '').replace(/\n/g, '<br/>');
	return x;
};

String.prototype.isInteger = function()
{
    return this.match(/^\d+$/)
};

var Popup = {

    callback: null,

    //
    // Positions the message box centered horizontally and top-weighted vertically
    //
    position: function()
    {
        var msg = $('__p_msg');
        if (msg)
        {
            var paneSize = document.viewport.getDimensions();
            var paneScroll = document.viewport.getScrollOffsets();
            var msgSize = msg.getDimensions();
            msg.style.top = (paneScroll.top + ((paneSize.height - msgSize.height) / 2) - (0.05 * paneSize.height)) + 'px';
            msg.style.left = ((paneSize.width - msgSize.width) / 2) + 'px';
            var tbl = $('__p_body_table');
            if (tbl)
            {
                msg.style.width = Element.getWidth(tbl) + 'px';
            }
        }
    },

    //
    // Displays an overlay mask over the entire viewport
    //
    showOverlay: function()
    {
        // Get or create the mask element
        var mask = $('__p_mask');
        if (!mask)
        {
            // Create the mask and add it to the document
            mask = document.createElement('div');
            mask.id = '__p_mask';
            mask.style.display = 'none';
            (document.body || document.documentElement).appendChild(mask);
        }

        // Hide certain elements that would show through the mask on some browsers
        $$('select', 'object', 'embed').each(function(node) { node.style.visibility = 'hidden'; });

        // Fade the mask in
        Effect.Appear(mask, { duration: 0.25, from: 0, to: 0.5 });
    },

    //
    // Hides the overlay mask
    //
    hideOverlay: function()
    {
        // Fade the mask out if it exists
        var mask = $('__p_mask');
        if (mask)
        {
            Effect.Fade(mask, { duration: 0.25, from: 0.5, to: 0 });
        }

        // Restore objects
        setTimeout(function()
        {
            $$('select', 'object', 'embed').each(
                function(node)
                {
                    node.style.visibility = 'visible';
                });
        }, 350);
    },

    //
    // Shows the specified content in the popup
    //
    show: function(html, callback)
    {
        // Remember the callback
        Popup.callback = callback;

        // Show the pane mask
        Popup.showOverlay();

        // Create the popup content    
        var msg = $('__p_msg');
        if (!msg)
        {
            // Create the message box
            msg = document.createElement('div');
            msg.id = '__p_msg';

            // Add it to the document
            (document.body || document.documentElement).appendChild(msg);
        }

        // Have it consume space so we can get its dimensions
        msg.style.display = 'block';
        msg.style.visibility = 'hidden';

        // Construct the table for the popup
        msg.innerHTML =
            '<table id="__p_body_table" cellpadding="0" cellspacing="0" width="100%" border="0">' +
            '<tr>' +
                '<td id="__p_ul"></td>' +
                '<td id="__p_uc"></td>' +
                '<td id="__p_ur"></td>' +
            '</tr>' +
            '<tr>' +
                '<td id="__p_l"></td>' +
                '<td id="__p_body"><div id="__p_body_inner">' + html + '</div></td>' +
                '<td id="__p_r"></td>' +
            '</tr>' +
            '<tr>' +
                '<td id="__p_ll"></td>' +
                '<td id="__p_lc"></td>' +
                '<td id="__p_lr"></td>' +
            '</tr>' +
            '</table>' +
            '<div id="__p_close" onclick="Popup.hide()"></div>';

        // Position it
        Popup.position();

        // Scroll the content and reposition if it's too tall
        var maxHeight = document.viewport.getDimensions().height * 0.75;
        if ($('__p_body_inner').clientHeight > maxHeight)
        {
            $('__p_body_inner').style.height = (maxHeight + 'px');
            $('__p_body_inner').style.overflowY = 'scroll';
            Popup.position();
        }
        else
        {
            $('__p_body_inner').style.height = '';
            $('__p_body_inner').style.overflowY = 'visible';
        }

        // Display the popup
        msg.style.visibility = 'visible';
        Element.show(msg);

        // Keep the popup in the center as the window resizes
        Event.observe(window, 'resize', Popup.position);
    },

    //
    // Hides the popup and overlay mask
    //
    hide: function()
    {
        // Hide the box and remove it from the DOM
        var msg = $('__p_msg');
        if (msg)
        {
            Element.hide(msg);
            setTimeout(function() { Element.remove('__p_msg'); }, 500);
        }

        // Hide the overlay
        Popup.hideOverlay();

        // Detach
        Event.stopObserving(window, 'resize', Popup.position);

        // Notify subscriber
        if (Popup.callback)
        {
            Popup.callback();
        }
    },

    //
    // Intended to be used to set the content of an already-displayed popup
    //
    setHTML: function(html)
    {
        var o = $('__p_body_inner');
        if (o)
        {
            o.update(html);
            Popup.position();
        }
    },

    //
    // Displays a "loading"-type message.  Intended to be used when the popup
    // contents cannot be immediately rendered.
    //
    showLoader: function(msg)
    {
        var html = '<div class="busy"></div>';
        if (msg)
        {
            html = msg + '<br/><br/>' + html;
        }
        Popup.show(html);
    }
};


//
// G is a variable for scoping global functions
//

var G = {

    //
    // Returns a standardized AJAX error message for transport issues
    //
    getAjaxErrorHTML: function(transport)
    {
        var html = '<b>An unexpected problem occurred while attempting to contact the server.</b><br/>' +
            'If the problem continues, please contact technical support.' +
            '<div style="margin-top:4px;color:#999">';
        if (transport)
        {
            html += '(Status ' + transport.status + ': ' + transport.statusText + ')';
        }
        else
        {
            html += '(Transport information unavailable)';
        }
        html += '</div>';
        return html;
    },

    showMessage: function(container, msg, callback, timeout)
    {
        // Display the error message
        $(container).update(msg);
        Element.show(container);

        if (callback)
        {
            // Default timeout to 3 seconds
            if (!timeout)
            {
                timeout = 3000;
            }

            // Set the container to fade out, then set the callback to execute 50ms after it has disappeared
            setTimeout(function() { Effect.Fade(container, { duration: 0.5 }); }, timeout);
            setTimeout(callback, timeout + 550);
        }
    },

    //
    // Outputs the specified error information to the user.  If 'container' is specified,
    // the message will be rendered there, otherwise it will be shown in a popup.  If
    // using a container and a callback is specified, the container will be set to fade
    // out after the specified timeout period, after which the callback will be executed.
    //
    error: function(obj, container, callback, timeout)
    {
        // Get the message text
        var msg;
        if (obj)
        {
            if (obj.substring) // String
            {
                msg = obj;
            }
            else if (obj.message) // Error
            {
                msg = obj.message;
            }
            else if (obj.responseText) // AJAX response
            {
                try
                {
                    // Check for expected error
                    msg = obj.responseText.evalJSON().message;
                }
                catch (e)
                {
                    // A generic AJAX error occurred
                    msg = G.getAjaxErrorHTML(obj);
                }
            }
        }

        if (!msg)
        {
            msg = 'An unknown error has occurred.';
        }

        msg = '<div class="error">' + msg + '</div>';

        // Show in the container or in a popup
        if (container)
        {
            G.showMessage(container, msg, callback, timeout);
        }
        else
        {
            Popup.show(msg);
        }
    },

    //
    // Returns the absolute X/Y position and width/height of the
    // specified object.
    //
    getRect: function(o)
    {
        o = $(o);
        var dims = o.getDimensions();
        var pos = o.cumulativeOffset();
        return {
            x: pos.left,
            y: pos.top,
            w: dims.width,
            h: dims.height
        };
    },

    emptyList: function(list)
    {
        list = $(list);
        for (var i = list.options.length - 1; i >= 0; i--)
        {
            list.options[i] = null;
        }
    },

    addListItem: function(list, val, text)
    {
        var opt = document.createElement('option');
        opt.value = val;
        opt.text = text;
        list = $(list);
        list.options[list.options.length] = opt;
        return opt;
    },

    setList: function(list, val, matchText)
    {
        list = $(list);
        for (var i = 0; i < list.options.length; i++)
        {
            if (!matchText && list.options[i].value == val)
            {
                list.selectedIndex = i;
                return true;
            }
            else if (matchText && list.options[i].text == val)
            {
                list.selectedIndex = i;
                return true;
            }
        }
        return false;
    },

    S4: function()
    {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    },

    newGuid: function()
    {
        return (G.S4() + G.S4() + '-' + G.S4() + '-' + G.S4() + '-' + G.S4() + '-' + G.S4() + G.S4() + G.S4()).toUpperCase();
    },

    swapMenu: function(img, on)
    {
        if (on)
        {
            img.style.backgroundColor = '#000';
        }
        else
        {
            img.style.backgroundColor = '';
        }
    },

    addToCart: function()
    {
        try
        {
            var ary = $$('input[class=buy_qty]');
            var serialized = '';
            var num = 0;
            for (var i = 0; i < ary.length; i++)
            {
                var v = ary[i].value;
                if (v.isInteger())
                {
                    serialized += i + '=' + v + '&';
                    num += parseInt(v);
                }
            }

            if (1 > num)
            {
                throw 'Please enter the number of items you would like to add to your cart.';
            }

            Element.hide('buy_button');
            Element.show('buy_busy');
            new Ajax.Request('/Ajax/AddToCart.ashx',
            {
                parameters:
                {
                    serialized: serialized,
                    options: $('buy_info').value
                },
                onSuccess: function(t)
                {
                    document.location.href = '/Cart.aspx';
                },
                onFailure: function(t)
                {
                    G.error(t, 'buy_error', function() { Element.show('buy_button'); });
                },
                onComplete: function(t)
                {
                    Element.hide('buy_busy');
                }
            });
        }
        catch (e)
        {
            ['buy_button', 'buy_busy'].each(Element.hide);
            G.error(e, 'buy_error', function() { Element.show('buy_button'); });
        }
    }
};