Array.prototype.contains = function(value)
{
    for(var i = 0; i < this.length; i++)
    {
        if(this[i] === value)
        {
            return true;
        }
    }
    
    return false;
}

Array.prototype.unique = function()
{
    var unique = [];
    for(var i = 0; i < this.length; i++)
    {
        if(unique.contains(this[i]) === false)
        {
            unique.push(this[i]);
        }
    }
    return unique;
}

var popUp = function(url, title, width, height)
{
    var w = window.open(url, title, 'width=' + width + ',height=' + height + ',dependent=yes,location=yes,menubar=yes,resizable=yes,scrollbars=yes,status=yes,toolbar=no');
    if(w)
    {
        w.focus();
    }
}

var showTripPlanner = function(url)
{
    popUp(url, 'TripPlanner', 700, 600);
}

var Polypex = {};

Polypex.ProductFinder = function()
{
    var dims = [];
    var lengthId;
    var lengthEl;
    var widthId;
    var widthEl;
    var depthId;
    var depthEl;
    var currentLength = null;
    var currentWidth = null;
    var currentDepth = null;
    
    var sorter = function(a, b)
    {
        return a - b;
    };
    
    var createOption = function(value, defaultSelected, selected)
    {
        var o = new Option(
            value,
            value,
            defaultSelected,
            selected
        );
        return o;
    };
    
    var onChange = function(evt)
    {
        if(! evt)
        {
            evt = window.event;
        }
        
        el = evt.target;
        if(! el)
        {
            el = evt.srcElement;
        }
        
        if(el.id === lengthId)
        {
            onLengthChange(parseFloat(el.options[el.selectedIndex].value));
        }
        else if(el.id === widthId)
        {
            onWidthChange(parseFloat(el.options[el.selectedIndex].value));
        }
        else if(el.id === depthId)
        {
            onDepthChange(parseFloat(el.options[el.selectedIndex].value));
        }
    };
    
    var onLengthChange = function(length)
    {
        var width = parseFloat(widthEl.options[widthEl.selectedIndex].value);
        var depth = parseFloat(depthEl.options[depthEl.selectedIndex].value);
        
        var widths = matchWidths(length, depth);
        var depths = matchDepths(length, width);
        
        updateOptions(widthEl, widths, width);
        updateOptions(depthEl, depths, depth);
    };
    
    var onWidthChange = function(width)
    {
        var length = parseFloat(lengthEl.options[lengthEl.selectedIndex].value);
        var depth = parseFloat(depthEl.options[depthEl.selectedIndex].value);
        
        var lengths = matchLengths(width, depth);
        var depths = matchDepths(length, width);
        
        updateOptions(lengthEl, lengths, length);
        updateOptions(depthEl, depths, depth);
    };
    
    var onDepthChange = function(depth)
    {
        var length = parseFloat(lengthEl.options[lengthEl.selectedIndex].value);
        var width = parseFloat(widthEl.options[widthEl.selectedIndex].value);
        
        var lengths = matchLengths(width, depth);
        var widths = matchWidths(length, depth);
        
        updateOptions(lengthEl, lengths, length);
        updateOptions(widthEl, widths, width);
    };
    
    var matchLengths = function(width, depth)
    {
        var values = [];
        
        for(var i = 0; i < dims.length; i++)
        {
            var dim = dims[i];
            if(    ((! width) || (width && dim.width.toString() === width.toString()))
                && ((! depth) || (depth && dim.depth.toString() === depth.toString())))
            {
                values.push(dim.length);
            }
        }
        
        values = values.unique();
        values.sort(sorter);
        return values;
    };
    
    var matchWidths = function(length, depth)
    {
        var values = [];
        
        for(var i = 0; i < dims.length; i++)
        {
            var dim = dims[i];
            if(    ((! length) || (length && dim.length.toString() === length.toString()))
                && ((! depth) || (depth && dim.depth.toString() === depth.toString())))
            {
                values.push(dim.width);
            }
        }
        
        values = values.unique();
        values.sort(sorter);
        return values;
    };
    
    var matchDepths = function(length, width)
    {
        var values = [];
        
        for(var i = 0; i < dims.length; i++)
        {
            var dim = dims[i];
            if(    ((! length) || (length && dim.length.toString() === length.toString()))
                && ((! width) || (width && dim.width.toString() === width.toString())))
            {
                values.push(dim.depth);
            }
        }
        
        values = values.unique();
        values.sort(sorter);
        return values;
    };
    
    var updateOptions = function(el, values, selectedValue)
    {
        el.options.length = 1;
        
        for(var i = 0; i < values.length; i++)
        {
            var value = values[i];
            
            var selected = false;
            if(    typeof(selectedValue) === 'number'
                && selectedValue.toString() === value.toString())
            {
                selected = true;
            }
            
            var o = createOption(value, false, selected);
            el.options[el.options.length] = o;
        }
    };
    
    return {
        setCurrentLength: function(v)
        {
            currentLength = v;
        },
        
        setCurrentWidth: function(v)
        {
            currentWidth = v;
        },
        
        setCurrentDepth: function(v)
        {
            currentDepth = v;
        },
    
        addDimension: function(length, width, depth)
        {
            dims.push({
                length: length,
                width: width,
                depth: depth
            });
        },
        
        applyTo: function(lengthElId, widthElId, depthElId)
        {
            lengthId = lengthElId;
            widthId = widthElId;
            depthId = depthElId;
            
            var dim;
            var i;
            
            lengthEl = document.getElementById(lengthElId);
            widthEl = document.getElementById(widthElId);
            depthEl = document.getElementById(depthElId);
            
            var lengths = [];
            var widths = [];
            var depths = [];
            
            for(i = 0; i < dims.length; i++)
            {
                dim = dims[i];
                lengths.push(dim.length);
                widths.push(dim.width);
                depths.push(dim.depth);
            }
            
            lengths = lengths.unique();
            widths = widths.unique();
            depths = depths.unique();
            
            lengths.sort(sorter);
            widths.sort(sorter);
            depths.sort(sorter);
            
            updateOptions(lengthEl, lengths, currentLength);
            updateOptions(widthEl, widths, currentWidth);
            updateOptions(depthEl, depths, currentDepth);
            
            $(lengthEl).change(onChange);
            $(widthEl).change(onChange);
            $(depthEl).change(onChange);
        }
    };
}();

Polypex.ProductSelector = function()
{
    var categories = [];
    var products = [];
    var categoryEl;
    var productEl;
    var categoryId;
    var productId;
    var url;
    var currentRootCategoryId = null;
    var currentProductId = null;
    
    var createOption = function(value, caption, defaultSelected, selected)
    {
        var o = new Option(
            caption,
            value,
            defaultSelected,
            selected
        );
        return o;
    };
    
    var onCategoryChange = function(evt)
    {
        if(! evt)
        {
            evt = window.event;
        }
        
        el = evt.target;
        if(! el)
        {
            el = evt.srcElement;
        }
        
        var categoryIdx = el.options[el.selectedIndex].value;
        updateProducts(categoryIdx);
    };
    
    var onProductChange = function(evt)
    {
        if(! evt)
        {
            evt = window.event;
        }
        
        el = evt.target;
        if(! el)
        {
            el = evt.srcElement;
        }
        
        var value = el.options[el.selectedIndex].value;
        url = null;
        if(value)
        {
            var toks = value.split('.');
            var categoryIdx = toks[0];
            var productIdx = toks[1];
            
            url = categories[categoryIdx].products[productIdx].url;
            window.location.href = url;
        }
    };
    
    var updateProducts = function(categoryIdx)
    {
        var category = categories[categoryIdx];
        var products = category.products;
        
        productEl.options.length = 0;
        for(var i = 0; i < products.length; i++)
        {
            var product = products[i];
            var selected = (product.id == currentProductId);
            var o = createOption(categoryIdx + '.' + i, product.caption, selected, selected);
            productEl.options[productEl.options.length] = o;
            
            if(i === 0)
            {
                url = product.url;
            }
        }
    };
    
    return {
        setCurrentRootCategoryId: function(v)
        {
            currentRootCategoryId = v;
        },
        
        setCurrentProductId: function(v)
        {
            currentProductId = v;
        },
        
        addCategory: function(id, caption)
        {
            categories.push({
                id: id,
                caption: caption,
                products: []
            });
            
            return categories.length - 1;
        },
        
        addProduct: function(categoryIdx, id, caption, url)
        {
            categories[categoryIdx].products.push({
                id: id,
                caption: caption,
                url: url
            });
        },
        
        getUrl: function()
        {
            return url;
        },
        
        applyTo: function(categoryElId, productElId)
        {
            categoryId = categoryElId;
            productId = productElId;
            
            categoryEl = document.getElementById(categoryElId);
            productEl = document.getElementById(productElId);
            
            categoryEl.options.length = 0;
            var selectedIdx = 0;
            for(var i = 0; i < categories.length; i++)
            {
                var category = categories[i];
                var selected = false;
                if(category.id == currentRootCategoryId)
                {
                    selected = true;
                    selectedIdx = i;
                }
                var o = createOption(i, category.caption, selected, selected);
                categoryEl.options[categoryEl.options.length] = o;
            }
            
            $(categoryEl).change(onCategoryChange);
            $(productEl).change(onProductChange);
            
            updateProducts(selectedIdx);
        }
    };
}();

$(document).ready(function() {
    $('a.cluetip').cluetip();
});