$(document).ready(function () {

    // homepage quick start
    $('.quickstart #part').change(function(){
        var part = $('option:selected', this).text().toLowerCase().replace(' ',''),
            materials = parts.config.pages[part][0].text,
            materials = materials.split('|'),
            $menu = $('.quickstart #material');
        
        $menu.empty();
        $.each(materials, function(i, name){
            $('<option' + (i == 0 ? ' selected="selected"' : '') + ' value="' + name.replace(' ','') + '">' + name + '</option>').appendTo($menu);
        });        
    }).trigger('change');
    
    $('.quickstart button').click(function(){
        if ($('#material').val()){
            var url = '/parts-catalogue/' + $('#part').val() + '?material=' + $('#material').val();
            location.href = url;
        }
        return false;
    });

    // copy subnav to left panel
    if ($('#subnav').length && $('#nav > ul > li.selected').length) {
        $('#nav > ul > li.selected:first > ul').clone(true).appendTo($('#subnav'));
    }

    // search box
    $('#terms')
    .focus(function () {
        if ($(this).val() === 'Search the site') {
            $(this).val('');
        }
    })
    .blur(function () {
        if ($(this).val() === '') {
            $(this).val('Search the site');
        }
    });

    // init galleries and videos
    $("#gallery a").fancybox();

    $('#gf-video').mousedown(function () {
        $(this).fancybox({
            'width': 640,
            'height': 385,
            'padding': 10,
            'autoScale': false,
            'transitionIn': 'none',
            'transitionOut': 'none',
            'title': this.title,
            'href': this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
            'type': 'swf',
            'swf': {
                'wmode': 'transparent',
                'allowfullscreen': 'true'
            }
        });
        return false;
    });

    $('a#ta-video').fancybox({
        'width': 640,
        'height': 360,
        'padding': 10,
        'autoScale': false,
        'transitionIn': 'none',
        'transitionOut': 'none',
        'title': this.title
    });

    // homepage image rotation
    if ($('#banner.homepage').length) {
        setTimeout('nextImage()', 5000);
    }

    // create parts forms
    if (location.href.indexOf('parts-catalogue/') > 0 && location.href.indexOf('v-band') == -1) {

        var $c = $('#content'),
            page = location.href.split('/')[location.href.split('/').length - 1].split('.')[0].replace(/-/g, '');

        $c.append('<h2>Request a quote for this part</h2><p>Please use the form below to request information and costs for any items you are interested in. Note that the form will remember your query, so you can keep adding items from the catalogue until you are ready.</p><form id="partsRequest" method="post"><div id="unitsLabel">Choose:</div><div id="units"><a href="#" id="mm" class="on" title="Show units in milimeters">mm</a><a href="#" id="in" title="Show units in inches">in</a></div></form>');
        parts.init($('#partsRequest'), page);
        
        if (page == 'bends'){
            $('#partsRequest').append('<p><img src="/media/1232/diagram-bends.gif" alt="Bends diagram" /></p>');    
        }

        $('#addItem').live('click', function () {
            parts.add($('#partsRequest'));
            return false;
        });

        $('#sendQuery').live('click', function () {
            parts.send($('#partsRequest'));
            return false;
        });

        $('#partselector').live('change', function () {
            parts.showspec($(this));
            return false;
        }).change();

        $('.bends.changer').live('change', function () {
            parts.popMenu($(this));
            return false;
        }).eq(0).change();


        $('#partsRequest #units a').live('click', function () {
            $('#units a').toggleClass('on');
            parts.units.change($('#units a.on').text());
            return false;
        });

        $('#iQuery').blur(function () {
            if ($.cookie('query') && !$(this).val()) {
                if (confirm('Are you sure you wish to delete your query so far?')) {
                    $.cookie('query', null, { path: '/' });
                } else {
                    $(this).val(decodeURIComponent($.cookie('query')));
                }
            }
        });
      
        // copy user if they tick the box
        $('#iCopyUser').click(function(){
            var ccEmail = $(this).is(':checked') ? $('#iEmail').val() : '';
            $('#hRecipients2').val(ccEmail);
        });      

    } else if (location.href.indexOf('your-query-has-been-sent') > 0) {
        $.cookie('query', null, { path: '/' });
    }
    
});

// parts catalogue request form
var parts = {

    // form spec per page
    config: {
        pages: {
            tube: [
                { label: 'Material', format: 'menu', text: 'Inconel 625|Inconel 718|321 Stainless|Grade 2 Titanium' },
                { label: 'Outer diameter', format: 'text', css: 'length', units: 'mm' },
                { label: 'Length (max 500mm)', format: 'text', css: 'length', units: 'mm' },
                { label: 'Wall thickness', format: 'menu', text: '0.5|0.6|0.7|0.8|0.9|1.0|1.2', units:'mm', altunits: 'thous', css: 'length' }
            ],
            bends: [
                { label: 'Material', format: 'menu', text: 'Inconel|Titanium|321 Stainless|304 Stainless|Aluminium', id: 'material', css: 'bends changer' },
                { label: 'Outer diameter', format: 'menu', text: '', id: 'diameter', disabled: true, css: 'bends changer' },
                { label: 'Centre Line Radius', format: 'menu', text: '', id: 'clr', disabled: true, css: 'bends changer length', units: 'mm' },
                { label: 'Angle °', format: 'menu', text: '', id: 'angle', disabled: true, css: 'bends' },
                { label: 'Wall thickness', format: 'menu', text: '', id: 'wall', disabled: true, css: 'bends length', units:'mm', altunits: 'thous' },
                { label: 'Clamp length', format: 'text', id: 'clamp', text: '-', disabled: true, css: 'disabled bends length', units: 'mm' },
                { label: 'Tail length', format: 'text', units: 'mm', css: 'length' }
            ],
            collectors: [
                { label: 'Material', format: 'menu', text: 'Inconel 625|Inconel 718|321 Stainless|Grade 2 Titanium' },
                { label: 'Collector type', format: 'menu', text: '2-1|3-1|4-1|5-1|6-1' },
                { label: 'Wall thickness', format: 'menu', text: '0.5|0.6|0.7|0.8|0.9|1.0|1.2', units:'mm', altunits: 'thous', css: 'length' },
                { label: 'OD of Primary pipe', format: 'menu', text: '1|1.13|1.25|1.37|1.5|1.62|1.75|1.87|2|2.06|2.12|2.25|2.37|2.5|2.62|2.75|2.87|3|3.13|3.25|3.5', css: 'length', units: 'in' },
                { label: 'OD of Outlet pipe', format: 'menu', text: '1|1.13|1.25|1.37|1.5|1.62|1.75|1.87|2|2.06|2.12|2.25|2.37|2.5|2.62|2.75|2.87|3|3.13|3.25|3.5', css: 'length', units: 'in' }
            ],
            silencersmufflers: [
                { label: 'Material', format: 'menu', text: 'Stainless 304|Grade 2 Titanium' },
                { label: 'Muffler diameter', format: 'text', css: 'length', units: 'mm' },
                { label: 'Muffler length', format: 'text', css: 'length', units: 'mm' }
            ],
            steprings: [
                { label: 'Material', format: 'menu', text: 'Stainless 304|Inconel 625|Inconel 718' },
                { label: 'Inlet pipe OD', format: 'menu', text: '1|1.13|1.25|1.37|1.5|1.62|1.75|1.87|2|2.06|2.12|2.25|2.37|2.5|2.62|2.75|2.87|3|3.13|3.25|3.5', css: 'length', units: 'in' },
                { label: 'Outlet pipe OD', format: 'menu', text: '1|1.13|1.25|1.37|1.5|1.62|1.75|1.87|2|2.06|2.12|2.25|2.37|2.5|2.62|2.75|2.87|3|3.13|3.25|3.5', css: 'length', units: 'in' },
                { label: 'Wall thickness', format: 'menu', text: '0.5|0.6|0.7|0.8|0.9|1.0|1.2', units:'mm', altunits: 'thous', css: 'length' }
            ],
            /*vbandclampsrings: [
                { label: 'Part', format: 'menu', text: 'VBCR-50|VBCR-57|VBCR-60|VBCR-63|VBCR-69|VBCR-76|VBCR-88', id: 'partselector' },
                { label: 'Type', format: 'menu', text:'Male|Female|Clamp' }
            ],*/
            bosses: [
                { label: 'Part', format: 'menu', text: 'CAMB-1-101|CAMB-1-102|CAMB-2-101|CAMB-2-102', id: 'partselector' }
            ],
            flanges: [
                { label: 'Description', format: 'text' }
            ],
            common: [
                { label: 'Quantity', format: 'text', text: '1' },
                { label: '', format: 'button', id: 'addItem', text: 'Add this', css: 'common' },
                { label: 'Add/edit query', format: 'bigtext', id: 'iQuery', text: 'Please send me more information and costs for the items below.\n\n', css: 'common' },
                { label: 'Name', format: 'text', id: 'iName', css: 'common' },
                { label: 'Company', format: 'text', id: 'iOrg', css: 'common' },
                { label: 'Email', format: 'text', id: 'iEmail', css: 'common' },
                { label: 'Send me a copy', format: 'checkbox', id: 'iCopyUser', css: 'common' },
                { label: '', format: 'button', id: 'sendQuery', text: 'Send', css: 'common' },
                { label: '', format: 'hidden', id: 'hSenderEmail', text: 'info@goodfabs.com', css: 'common' },
                { label: '', format: 'hidden', id: 'hSenderName', text: 'GoodFabs website', css: 'common' },
                { label: '', format: 'hidden', id: 'hSubject', text: 'Website query', css: 'common' },
                { label: '', format: 'hidden', id: 'hRecipients', text: 'goodfabs@gmail.com; theo.paraskevopoulos@gmail.com', css: 'common' },
                { label: '', format: 'hidden', id: 'hRecipients2', text: '', css: 'common' },
                { label: '', format: 'hidden', id: 'hRedirect', text: 'http://www.goodfabs.com/your-query-has-been-sent.aspx', css: 'common' }
            ]
        },
        products: {
            'VBCR-50': 'Tube OD: 50.8mm (2in), V Band Ring: VBCR-50-M/F, V Band Ring: VBCR-50-C',
            'VBCR-57': 'Tube OD: 57.2mm (2.25in), V Band Ring: VBCR-57-M/F, V Band Ring: VBCR-57-C',
            'VBCR-60': 'Tube OD: 60.3mm (2.38in), V Band Ring: VBCR-60-M/F, V Band Ring: VBCR-60-C',
            'VBCR-63': 'Tube OD: 63.5mm (2.5in), V Band Ring: VBCR-63-M/F, V Band Ring: VBCR-63-C',
            'VBCR-69': 'Tube OD: 69.9mm (2.75in), V Band Ring: VBCR-69-M/F, V Band Ring: VBCR-69-C',
            'VBCR-76': 'Tube OD: 76.2mm (3in), V Band Ring: VBCR-76-M/F, V Band Ring: VBCR-76-C',
            'VBCR-88': 'Tube OD: 88mm (3.5in), V Band Ring: VBCR-88-M/F, V Band Ring: VBCR-88-C',

            'CAMB-1-101': 'Material: Inconel, Style: Cast Lambda/O2 (cast and then machined) flange style',
            'CAMB-1-102': 'Material: Stainless Steel, Style: Cast Lambda/O2 (cast and then machined) flange style',
            'CAMB-2-101': 'Material: Stainless Steel, Style: Machined Lambda/O2 (not flanged)',
            'CAMB-2-102': 'Material: Stainless Steel 1/8th NPT, Style: Thermo boss(cast and then machined) flange style'
        },
        bends: {
            options: [
                [25.4, true, 102, [28.575, 44.45, 50.8, 57.15, 101.6], [140, 140, 180, 180, 180], 'Aluminium;Inconel;Titanium;321 Stainless;304 Stainless;', [0.5, 1.2, 1.5]],
                [28.575, true, 102, [50.8], [180], 'Aluminium;Inconel;Titanium;321 Stainless;304 Stainless;', [1.2, 1.5]],
                [31.75, true, 102, [50.8, 101.6], [140, 180], 'Aluminium;Inconel;Titanium;321 Stainless;304 Stainless;', [0.7, 0.9, 1.2, 1.6, 2]],
                [34.92, true, 102, [50.8, 63.5], [180, 180], 'Aluminium;Inconel;Titanium;321 Stainless;304 Stainless;', [0.9, 1.2, 1.6]],
                [38.1, true, 127, [38.1, 44.45, 50.8, 57.15, 63.5, 82.55, 101.6, 127, 152.4], [135, 180, 160, 145, 180, 160, 180, 180, 180], 'Aluminium;Inconel;Titanium;321 Stainless;304 Stainless;', [0.9, 1.2, 1.6]],
                [41.27, true, 127, [41.275, 50.8, 57.15, 63.5, 69.85, 82.55, 101.6, 133.35], [140, 180, 180, 180, 180, 180, 180, 140], 'Aluminium;Inconel;Titanium;321 Stainless;304 Stainless;', [0.7, 0.9, 1.2, 1.6]],
                [44.45, true, 127, [44.45, 50.8, 57.15, 63.5, 76.2, 82.55, 101.6, 127, 152.4], [150, 140, 180, 180, 140, 180, 180, 180, 180], 'Aluminium;Inconel;Titanium;321 Stainless;304 Stainless;', [0.7, 0.9, 1.2, 1.5, 1.6]],
                [47.62, true, 127, [47.625, 50.8, 57.15, 63.5, 69.85, 76.2, 88.9, 101.6, 107.95, 127, 152.4], [130, 130, 150, 140, 155, 180, 180, 180, 180, 180, 180], 'Aluminium;Inconel;Titanium;321 Stainless;304 Stainless;', [0.6, 0.7, 0.9, 1.2, 1.6]],
                [49.8, false, 165, [49.8, 76.2], [130, 120], 'Inconel;321 Stainless;', [0.7, 0.9]],
                [50.8, true, 140, [50.8, 57.15, 61.4, 63.5, 69.85, 76.2, 88.9, 107.95, 127, 146], [130, 170, 140, 180, 140, 180, 180, 180, 180, 180], 'Aluminium;Inconel;Titanium;321 Stainless;304 Stainless;', [0.6, 0.7, 0.9, 1.2, 1.6]],
                [51.4, false, 140, [51.4, 63.5, 76.2, 88.9, 139.71, 200], [130, 130, 180, 180, 160, 180], 'Inconel;321 Stainless;', [0.5, 0.7, 0.9]], [52.37, true, 165, [63.5, 76.2, 88.9, 107.95, 146], [160, 160, 160, 170, 180], 'Inconel;Titanium;321 Stainless;', [0.7]],
                [53.97, true, 152, [53.97, 63.5, 69.85, 76.2, 88.9, 114.3, 127], [120, 140, 140, 180, 180, 180, 180], 'Aluminium;Inconel;Titanium;321 Stainless;', [0.5, 0.7, 0.8, 0.9, 1.2, 1.6]],
                [55.8, false, 150, [55.8, 63.5, 82.55], [135, 135, 160], 'Inconel;Titanium;321 Stainless;', [0.5, 0.7, 0.9, 1, 1.6]], [57.15, true, 178, [57.15, 61.4, 63.5, 69.85, 82.55, 101.6, 114.3, 139.71], [140, 140, 140, 160, 160, 160, 160, 160], 'Aluminium;Inconel;321 Stainless;304 Stainless;', [0.5, 0.6, 0.7, 0.9, 1.2, 1.6]],
                [58.6, false, 175, [58.6, 69.85], [160, 160], 'Inconel;Titanium;321 Stainless;', [0.5, 0.7]],
                [60.32, true, 165, [60.32, 69.85, 76.2, 101.6, 139.71], [160, 140, 140, 180, 180], 'Aluminium;Inconel;Titanium;321 Stainless;304 Stainless;', [0.5, 0.7, 0.9, 1.2, 1.6]],
                [61.4, false, 150, [61.4, 76.2, 82.55, 88.9, 100, 139.71, 200], [130, 150, 140, 180, 140, 180, 110], 'Inconel;Titanium;321 Stainless;', [0.5, 0.7, 0.9, 1.2, 1.6]],
                [62.4, false, 150, [63.5, 82.55, 105], [135, 135, 135], 'Inconel;Titanium;321 Stainless;', [0.5, 0.7, 1.6]], [63, false, 200, [63.5, 82.55, 90], [160, 160, 160], 'Inconel;321 Stainless;', [0.7, 0.9]],
                [63.5, true, 178, [63.5, 69.85, 76.2, 82.55, 88.9, 101.6, 139.71], [130, 130, 130, 160, 150, 130, 160], 'Aluminium;Inconel;Titanium;321 Stainless;304 Stainless;', [0.5, 0.6, 0.7, 0.8, 0.9, 1.2, 1.6]],
                [65.5, false, 175, [65.5, 76.2, 101.6], [160, 160, 160], 'Inconel;Titanium;321 Stainless;', [0.7, 0.9]], [66.67, true, 178, [66.675, 76.2, 88.9, 101.6], [160, 160, 100, 160], 'Inconel;321 Stainless;', [0.5, 0.7, 0.9, 1.2]],
                [69.85, true, 178, [76.2, 88.9], [160, 110], 'Aluminium;Inconel;Titanium;321 Stainless;304 Stainless;', [0.5, 0.7, 0.9, 1.2]],
                [71.4, false, 175, [90, 100], [180, 115], 'Inconel;Titanium;321 Stainless;', [0.5, 0.7, 1.2]], [73, true, 178, [76.2, 101.6], [135, 160], 'Inconel;321 Stainless;', [0.5, 0.7]],
                [76.2, true, 190, [76.2, 95.25, 114.3], [130, 140, 180], 'Aluminium;Inconel;Titanium;321 Stainless;304 Stainless;', [0.6, 0.7, 0.9, 1.2, 1.6]],
                [79.4, true, 190, [95.25], [160], 'Inconel;Titanium;321 Stainless;', [0.7, 0.9]],
                [82.55, true, 203, [101.6], [160], 'Inconel;Titanium;321 Stainless;', [0.5, 0.7, 0.9]],
                [86.4, false, 200, [86.4, 100], [150, 150], 'Inconel;Titanium;321 Stainless;', [0.5, 0.7, 0.9]],
                [88.9, true, 203, [114.3, 200], [180, 100], 'Aluminium;Inconel;Titanium;321 Stainless;304 Stainless;', [0.7, 0.9, 1.2, 1.6]]
            ],
            angles: [
                15, 20, 25, 30, 45, 60, 90, 100, 110, 115, 120, 135, 140, 150, 155, 160, 170, 180
            ]
        },
        ui: {
            text: function (id, text, css, disabled) {
                return '<input type="text" ' + (disabled ? 'disabled="disabled"' : '') + ' name="' + (id || '') + '" id="' + (id || '') + '" value="' + (text || '') + '" class="' + (css || '') + '" />';
            },
            bigtext: function (id, text, css, disabled) {
                return '<textarea ' + (disabled ? 'disabled="disabled"' : '') + ' name="' + (id || '') + '" id="' + (id || '') + '" class="' + (css || '') + '">' + (id == 'iQuery' && $.cookie('query') ? decodeURIComponent($.cookie('query')) : text) + '</textarea>';
            },
            menu: function (id, text, css, disabled, altunits) {
                var optionList = '';
                $.each(text.split('|'), function (i, option) {
                    optionList += '<option original="' + option + '">' + option + '</option>';
                });
                return '<select ' + (altunits ? 'altunits="' + altunits + '"' : '') + (disabled ? 'disabled="disabled"' : '') + ' name="' + (id || '') + '" id="' + (id || '') + '" class="' + (css || '') + '">' + optionList + '</select>';
            },
            button: function (id, text) {
                return '<button id="' + (id || '') + '">' + text + '</button>';
            },
            hidden: function (id, text, css) {
                return '<input type="hidden" name="' + (id || '') + '" id="' + (id || '') + '" value="' + (text || '') + '" class="' + (css || '') + '" />';
            },
            checkbox: function (id, text, css) {
                return '<input type="checkbox" name="' + (id || '') + '" id="' + (id || '') + '" class="checkbox ' + (css || '') + '" />';
            }
        }
    },

    // store and convert numbers for inches or mm
    units: {
        thous: [
            {mm: 0.5, thous: 0.022},
            {mm: 0.6, thous: 0.028},
            {mm: 0.7, thous: 0.028},
            {mm: 0.8, thous: 0.028},
            {mm: 0.9, thous: 0.035},
            {mm: 1, thous: 0.035},
            {mm: 1.2, thous: 0.048},
            {mm: 1.5, thous: 0.064},
            {mm: 1.6, thous: 0.064},
            {mm: 2, thous: 0.08}
        ],
        current: 'mm',
        convert: function (l, round, units) {
            var r = round ? round : 1000,
                u = units || this.current; 
            if (u === 'in') {
                return this.roundNumber(l / 25.4, r);
            }
            return l;
        },
        convertThous: function(num){
            var converted= num;
            if (this.current === 'in'){ 
                $.each(parts.units.thous, function(i,ref){
                    if (ref.mm == num){
                        converted = ref.thous;
                    }
                });
            }
            return converted;
        },
        roundNumber: function (num, dec) {
            return Math.round(num * 100) / 100;
        },
        change: function (u) {
            this.current = u;
            
            $('.length').each(function(){
                var unitName = $(this).attr('altunits') && u === 'in' ? $(this).attr('altunits') : u;
                $(this).next('.units').text(unitName);
            });
            
            $('#partsRequest select.length option').each(function () {
                if ($(this).val() != ''){
                    if ($(this).parent().attr('altunits') && u === 'in'){
                        $(this).text(parts.units.convertThous($(this).text()))
                    } else {
                        $(this).text(parts.units.convert(parseFloat($(this).attr('original')), 2))    
                    }
                }
                
                var optionText = $(this).text();
                if ($(this).siblings().filter(function(){ return $(this).text() == optionText }).length){
                    $(this).hide();
                } else {
                    $(this).show();
                }
            });
            $('#partsRequest input:disabled').each(function () {
                if ($(this).val() != ''){
                    $(this).val(parts.units.convert(parseFloat($(this).attr('original')), 2))
                }
            });
        }
    },

    // populate menus through selections
    popMenu: function ($menu) {

        var m = $menu.val(),
            o = parts.config.bends.options;

        $menu.nextAll('.bends').empty().val('').attr('disabled', 'disabled');
        if (!m) { return; }

        switch ($menu.attr('id')) {
            case 'material':
                $('#diameter').removeAttr('disabled').html('<option value="">Select diameter</option>');
                $.each(o, function (i, row) {
                    if (row[5].indexOf(m) != -1) {
                        $('#diameter').append('<option value="' + i + '">' + row[0] + 'mm&nbsp;(' + parts.units.convert(row[0], null,'in') + 'in)</option>');
                    }
                });
                break;

            case 'diameter':
                $('#clr').removeAttr('disabled').html('<option value="">Select CLR</option>');
                $.each(o[m][3], function (i, val) {
                    $('#clr').append('<option value="' + i + '" original="' + val + '">' + parts.units.convert(val) + '</option>');
                });
                break;

            case 'clr':
                var d = $('#diameter').val();

                $('#angle').removeAttr('disabled').html('<option value="">Select angle</option>');
                $.each(parts.config.bends.angles, function (i, angle) {
                    if (angle <= parseInt(o[d][4][m])) {
                        $('#angle').append('<option value="' + i + '">' + angle + '</option>');
                    }
                });

                $('#wall').removeAttr('disabled').html('<option value="">Select wall thickness</option>');
                $.each(o[d][6], function (i, val) {
                    $('#wall').append('<option value="' + i + '" original="' + val + '">' + parts.units.convertThous(val) + '</option>');
                });

                $('#clamp').attr('original', parts.units.convert(o[d][2], 10)).val(parts.units.convert(o[d][2], 10));
                break;
        }
    },

    // create forms
    init: function ($container, page) {
        var fields = this.config.pages[page].concat(this.config.pages.common);
        $.each(fields, function (i, field) {
            
            // convert all inches to mm
            if (field.units === 'in'){
                var converted = field.text.split('|');
                $.each(converted, function(i, option){
                converted[i] = parts.units.roundNumber(+option * 25.4, 2);
                });
                field.units = 'mm';
                field.text = converted.join('|');
            }
      
            // render control
      
            $container.append((field.format != 'hidden' ? '<label>' + field.label + '</label>' : '')
                + parts.config.ui[field.format](field.id, field.text, field.css, field.disabled, field.altunits)
                + (field.format === 'menu' || field.format === 'text' ? '<span class="units">' + (typeof field.units === 'undefined' ? '&nbsp;' : field.units )+ '</span>' : '' ) + (field.format != 'hidden' ? '<br />' : '')
                );      
        });
    
        // render parts table above the form
        if ($('#partselector').length){
            $('<table id="partsTable"><thead></thead><tbody></tbody></table>').insertBefore($container.prevAll('h2'));
            var header = '';
            $('#partselector option').each(function(i,$p){
                var product = parts.config.products[$(this).text()].split(','),
                row = '';
                $.each(product, function(k,detail){
                // add header items
                if (i === 0){
                    header += '<th>' + detail.split(':')[0] + '</th>';
                };
                row += '<td>' + detail.split(':')[1] + '</td>';
                });
                $('#partsTable tbody').append('<tr><td>' + $(this).text() + '</td>' + row + '</tr>');  
            });
            $('#partsTable thead').append('<tr><th>ID</th>' + header + '</tr>');          
        }
        
        // hide units toggle if not needed
        if (!$('.length').length){
            $('#units').remove();
        }
    
        // preselect material if given
        if (location.href.indexOf('?material=') != -1){
            var startMaterial = location.href.split('?material=')[1];
            $('#material option').filter(function(){ return $(this).text().replace(' ','') == startMaterial }).attr('selected','selected').parent().change();
        }
    },

    // show part details
    showspec: function ($menu) {
        if (!$menu.next().is('div')) {
            $menu.after('<div>' + parts.config.products[$menu.val()] + '</div>');
        } else {
            $menu.next().text(parts.config.products[$menu.val()]);
        }
    },

    // add item to list
    add: function ($container) {
        var query = $('#iQuery').val() + $('h1').text() + '\n';
        
        if ($container.find('input:not(.common), select:not(.common)').filter(function(){ return !$(this).val() }).length){
            alert('Please complete all form fields.');
            return false;
        }

        $container.find('input:not(.common), select:not(.common)').each(function (i) {
            query += $(this).prev('label').text() + ': ' + ($(this).is('select') ? $('option:selected', this).text() : $(this).val()) + $(this).next('.units').text() + ', ';
        });
        query += '\n--------\n';
        $('#iQuery').val(query);

        // remember the selection
        $.cookie('query', encodeURIComponent(query), { expires: 90, path: '/' });
    },

    // submit form
    send: function () {
        if ($('#iQuery').val().indexOf('--------') === -1) {
            alert('Please add at least one item to the query.');
        } else if (!$('#iName').val() || !$('#iEmail').val()) {
            alert('Please provide your name and email address.');
        } else {
            $.cookie('query', null);
            $('#partsRequest').submit().find('*').attr('disabled', 'disabled');
        }
    }
}

function nextImage() {
    $('#banner img:visible').next().fadeIn(1000, function () {
        $(this).prev().hide().insertAfter($('#banner img:last'));
    })
    setTimeout('nextImage()', 5000);
}
