
$(function(){
    $.extend($.fn.disableTextSelect = function() {
        return this.each(function(){
            if($.browser.mozilla){//Firefox
                $(this).css('MozUserSelect','none');
            }else if($.browser.msie){//IE
                $(this).bind('selectstart',function(){
                    return false;
                });
            }else{//Opera, etc.
                $(this).mousedown(function(){
                    return false;
                });
            }
        });
    });

		/* Load product types map and series data array */
    var productId2TypeMap = 

[

        {
            "id": "type1",
            "type": "Application Processors"
        },

        {
            "id": "type2",
            "type": "Embedded Processors"
        },

        {
            "id": "type3",
            "type": "Ethernet Controllers"
        },

        {
            "id": "type4",
            "type": "Gateways"
        },

        {
            "id": "type5",
            "type": "PCI Bridges"
        },

        {
            "id": "type6",
            "type": "Power Management"
        },

        {
            "id": "type7",
            "type": "SAS\/SATA Storage"
        },

        {
            "id": "type8",
            "type": "SOHO Switching"
        },

        {
            "id": "type9",
            "type": "Switching"
        },

        {
            "id": "type10",
            "type": "System Controllers"
        },

        {
            "id": "type11",
            "type": "Transceivers"
        },

        {
            "id": "type12",
            "type": "Video Processors & Hybrid Demodulator"
        },

        {
            "id": "type13",
            "type": "Wireless"
        }

];

    var productTypesData = {
    "type1":[["series1","ARMADA&trade; Series"],["series2","PXA Series"]],
    "type2":[["series3","DISCOVERY INNOVATION Series"],["series4","KIRKWOOD&trade; DUO Series"],["series5","KIRKWOOD&trade; Series"],["series33","ARMADA&trade; Series"]],
    "type3":[["series6","YUKON&reg; Series"]],
    "type4":[["series7","LINK STREET&reg; Series"]],
    "type5":[["series8","PCI Express to PCI Bridges"]],
    "type6":[["series9","DC-DC REGULATORS Series"],["series10","DC-DC REGULATORS Series 2"],["series11","DC-DC REGULATORS Series 3"],["series34","DC-DC REGULATORS Series 4"]],
    "type7":[["series12","SATA Storage Controllers"],["series13","SAS/SATA Storage Controllers"],["series14","SATA Port Multiplier/Multiplexer"],["series15","SATA Bridge"],["series16","SAS to SATA Protocol Converter"]],
    "type8":[["series17","Link Street&reg; - Fast Ethernet Switches"],["series18","Link Street&reg; - Fast + Gigabit Ethernet Switches"],["series19","Link Street&reg; - Gigabit Ethernet Switches"]],
    "type9":[["series20","PRESTERA&reg; DX Series"],["series21","PRESTERA&reg; CX Series"],["series22","Intelligent Ethernet MAC"]],
    "type10":[["series23","DISCOVERY VI Series"],["series24","DISCOVERY V Series"],["series25","DISCOVERY III Series"]],
    "type11":[["series26","ALASKA&reg; Series"],["series27","Fast Ethernet (FE) PHY"],["series28","ALASKA&reg; X Series"]],
    "type12":[["series29","KYOTO Series"],["series30","BALI Series"]],
    "type13":[["series31","Wireless"],["series32","AVASTAR&trade; Series"]]
    };
    
    
    /* Check the URL to see if we're loading a type & series */
    var hash = location.hash;
    var productType = (hash) ? hash.split("-")[0].replace("#","") : "";
    var productSeries = (hash && hash.indexOf("-series") > 0) ? hash.split("-")[1] : "";

    $('.select-component, .select-component-multiple').disableTextSelect();
    
    $('#product-type-select').jScrollPane({
        showArrows:true,
        arrowSize: 17,
        scrollbarWidth:16,
        scrollbarMargin:0
    });
    
    $('#product-series-select').jScrollPane({
        showArrows:true,
        scrollbarWidth:16,
        arrowSize: 17,
        scrollbarMargin:0
    });

    $('#product-specifications-select').jScrollPane({
        showArrows:true,
        scrollbarWidth:16,
        arrowSize: 17,
        scrollbarMargin:0
    });


    $('.select-component > div, .select-component-multiple > div').click(function(){
        selectOption($(this));
    });

    columnsOrder = [];
    sorterObjects = [];
    currentSorter = null;

    function selectOption(obj, multiple) {
        if (multiple !== true) {
            obj.parent().children().removeClass('selected');
            obj.addClass('selected');
        } else {
            if (obj.hasClass('selected')) {
                obj.removeClass('selected');
                obj.children('.number').empty();
                for (var i=0; i<columnsOrder.length; i++) {
                    if (columnsOrder[i] == obj.text()) {
                        columnsOrder.splice(i, 1);
                        i--;
                    }
                }
                updateNumbers();
            } else {
                if (obj.parent().children('.selected').size() < 4) {
                    obj.addClass('selected');                    
                    columnsOrder.push(obj.text());
                    updateNumbers();
                }                
            }
        }
    }

    function updateNumbers() {
        $("#product-specifications-select > div").children(".number").empty();
        for (var i=0; i<columnsOrder.length; i++) {
            //$("#product-specifications-select > div:contains('" + columnsOrder[i] + "')").children(".number").html(i + 1);
            $("#product-specifications-select .mySpan").each(function(){
                if ($(this).text() == columnsOrder[i]) {
                    $(this).prev().html(i+1);
                }
            });
           
            col1 = currentSorter.findColumnByName(columnsOrder[i]);
            col2 = i;
            currentSorter.swapColumn(col1, col2);
        }
    }

    /* actions performed when the user selects a product type */
		$('#product-type-select > div').click( function() {
			selectType(this);
			productType = $(this).attr('code');
			(productType != "all") ? location.hash = productType : location.hash = "";
		});

		/* Fired when a type has been selected */
		function selectType(obj) {
			var productType = $(obj).attr('code');
			if (productType) {
				$('#product-series-select').empty();
				seriesArray = productTypesData[productType];
				if (seriesArray) {
					$('#product-series-select').append("<div id='all-series' code='all'>All Product Series</div>");
					for (var i=0; i < seriesArray.length; i++) {
						$('#product-series-select').append("<div code='" + seriesArray[i][0] + "-zone'>" + seriesArray[i][1] + "</div>");
					}
					loadCategory(productType);
					$('#product-series-select > div').click( function() {
						selectSeries(this);
						productSeries = $(this).attr('code').replace("-zone","");
						(productSeries != "all") ? location.hash = productType + "-" + productSeries : location.hash = productType;
					});
					selectSeries($('#all-series'));
				} else {
					/* we have an error or the "default" option is selected so we hide the div */
					$('#content-product-tables-box').hide();
				}
			}
		}

		/* Fired when a series has been selected */
		function selectSeries(obj) {
			selectOption($(obj));
			loadProductTable($(obj));
			loadProductSpecifications($(obj));
		} 
		

    /* actions performed when the user selects a product series */
    function loadProductSpecifications(obj) {
        $('#product-specifications-select').empty();
        if (obj.attr('code') != 'all') {

            //specsArray = getProductSpecification(obj);
            name = obj.attr('code').replace("-zone","");            
            specsArray = sorterObjects[name].getProductSpecifications();

            currentSorter = sorterObjects[name];
            
            for (var i = 0; i<specsArray.length; i++) {
                $('#product-specifications-select').append("<div><div class='number'></div><div class='mySpan'>" + specsArray[i] + "</div></div>");
            }
            
            $('#product-specifications-select').jScrollPane({
                showArrows:true,
                scrollbarWidth:16,
                arrowSize: 17,
                scrollbarMargin:0
            });

            $('#product-specifications-select > div').click(function(){
                selectOption($(this), true);
            });
        } else {
            
            $('#product-specifications-select').jScrollPane({
                showArrows:true,
                scrollbarWidth:16,
                arrowSize: 17,
                scrollbarMargin:0
            });
        }
        /* empty the columnsOrder array */
        columnsOrder = [];
    }

    function loadSeries(name) {
        
        $('#content-product-tables-box').append('<div class="zone-table-preloader" id="' + name + '-zone-table"><a href="series?id=' + name.replace("series","") + '"></a></div><div class="clear"></div>');

        $.ajax({
	          async: false,
            //url: 'series?id=' + name.replace("series","") + '',
            url: name + '.html',
            success: function(data) {
                $('#' + name + '-zone-table').removeClass('zone-table-preloader');
                $('#' + name + '-zone-table').addClass('zone-table-sorting');
                $('#' + name + '-zone-table').html(data);

                /* copy the AJAX loaded table into the DOM for later printing */
                $('#' + name + '-zone-table .content-table').clone().attr('id', 'printing-' + name).appendTo('BODY > #printing');

                s = new sorter('#' + name + '-zone-table', true);
                sorterObjects[name] = s;
                fixHeights('#' + name + '-zone-table');

                /* set the width of the table */
                width = s.scroller.getWidth() - 153 + 200;
                $('#printing-' + name).css('width', width);

                /* remove first column of the table */
                $('#printing-' + name + ' TH:first').remove();
                $('#printing-' + name + ' TR').each(function(){
                    $(this).find('TD:first').remove();
                    $(this).find('TD:first').addClass('products');
                });

                $('#printing-' + name + ' TH:first').width('200px').html($('#' + name + '-zone-table .products-table TH').html());
                $('#printing-' + name + ' TH:first A').remove();

                Cufon.refresh();
            }
        });
    }

    function loadCategory(name) {
        /* remove the current DOM content */
        $('#content-product-tables-box').empty();
        $('BODY > #printing').empty();
        $('#content-product-tables-box').show();
        
        series = productTypesData[name];
        for (var i=0; i<series.length; i++) {
            serie = series[i][0].replace("-zone", "");
            loadSeries(serie);
        }
    }

    function loadProductTable(obj) {
        name = obj.attr('code');
        if (name != 'all') {
            $('#content-product-tables-box .zone-table-sorting, #content-product-tables-box .zone-table-preloader, #content-product-tables-box .clear').hide();
            $('BODY > #printing > .content-table').addClass('myhidden');
            $('#' + name + '-table').show();
            $('BODY > #printing > #printing-' + name.replace('-zone', '')).removeClass('myhidden');
        } else {
            $('#content-product-tables-box .zone-table-sorting, #content-product-tables-box .zone-table-preloader, #content-product-tables-box .clear').show();
            $('BODY > #printing > .content-table').removeClass('myhidden');
        }
    }

		/* If the URL has a hash load the product & series from it */
		if(productType) {
			var type = $('#product-type-select div[code='+productType+']');
			selectType(type);
			selectOption($(type));
			$('#product-type-select')[0].scrollTo('.selected');
			if(productSeries) {
				selectSeries($('#product-series-select div[code='+productSeries+'-zone]'));
				$('#product-series-select')[0].scrollTo('.selected');
			} else {
				selectSeries($('#all-series'));
			}
		}
});

function resetNumbers() {
    $("#product-specifications-select > div").children(".number").empty();
    $("#product-specifications-select > div").removeClass('selected');
    columnsOrder = [];
}

