
function sorter(elementId, withSwapableColumns) {
    var myTable = null;
    var options = new Array();
    var originalOptions = new Array();

    this.init = function() {
        var myInstance = this;
        myTable = $(elementId + ' .content-table').dataTable({
            "bPaginate": false,
            "bLengthChange": false,
            "bFilter": false,
            "bSort": true,
            "bInfo": false,
            "bAutoWidth": false,
            "asStripClasses": [ 'even', 'odd' ],
            "fnDrawCallback": function() {
                myInstance.copyProducts();
                myInstance.copyArrows();
            }
        });

        $(elementId + ' .content-table TH').unbind('click');

        myTable.fnSetColumnVis( 0, false );
        myTable.fnSetColumnVis( 1, false );

        $(elementId + ' .content-div').append("<div class=\"floating-header-wrapper\" style=\"position: absolute; top: 0px; left: 0; \"><table class=\"floating-header\"></table></div>");
        $(elementId + ' .content-table THEAD').clone(true).appendTo($(elementId + ' .floating-header'));
        
        /* if the window is scrolled, move the table header in the right position */
        $(window).scroll(function(){

            windowWidth = $(window).width();
            windowHeight = $(window).height();

            tableHeight = $(elementId + ' .content-table').height();

            if ((tableHeight > 0) && (tableHeight > windowHeight)) {

                documentWidth = $(document).width();
                documentHeight = $(document).height();

                y1 = $(window).scrollTop();
                y2 = y1 + windowHeight;

                tableOffset = $(elementId + ' .content-table').offset();

                if (tableOffset) {
                    y1Table = tableOffset.top;
                    y2Table = y1Table + tableHeight;

                    floatingHeaderHeight = $(elementId + ' .floating-header').height();

                    if ( (y1Table < y1) && (y2Table - floatingHeaderHeight > y1 )) {
                        $(elementId + ' .floating-header-wrapper').css('top', (y1-y1Table) + 'px');
                    } else {
                        $(elementId + ' .floating-header-wrapper').css('top', '0px');
                    }
                }
            } else {
                $(elementId + ' .floating-header-wrapper').css('top', '0px');
            }
        })
        
        $(elementId + ' .floating-header TH A').each(function(index){
            myTable.fnSortListener($(this), index + 2); /* + 2 because we remove the first two columns from the table */
        })

        /* this is only related to swapable columns */
        if (withSwapableColumns == true) {

            $(elementId + ' .floating-header TH > A').each(function(index){
                options[index] = $(this).text();
                originalOptions[index] = $(this).text();
            })
                    
            optionsString = "";
            for (var i = 0; i< options.length; i++) {
                optionsString += "<option value='" + options[i] + "'>" + options[i] + "</option>";
            }

            $(elementId + ' .floating-header TH').each(function(index){
                var currentColumn = index;
                link = $(this).children();
                link.wrap('<div class="sorter-wrapper"><div class="sorter"></div></div>');
                $(this).append('<div class="selector"><select id="col-' + index +'">' + optionsString + '</select></div>');
                $(this).find("SELECT OPTION[value='" + link.text() + "']").attr('selected', 'selected');

                $(this).find("SELECT").change(function(){
                    newColumn = $(this).find("OPTION:selected").text();
                    newColIndex = myInstance.findColumnByName(newColumn);
                    
                    if (newColIndex >= 0) {
                        myInstance.swapColumn(currentColumn, newColIndex);
                        resetNumbers();
                    }
                })
            })        
        }
        /* end swapable columns */

        myInstance.copyProducts();
    }

    /* this method is a getter for the table columns / specs */
    this.getProductSpecifications = function () {
        return originalOptions;
    }

    this.copyProducts = function () {
        if (myTable) {
            productsList = myTable.fnGetColumnData(1, false, false, false);
            var i = 0;
            $(elementId + ' .products-table td').each(function(){
                $(this).html(productsList[i++]);
            })

            $('.show-popup').unbind('click');
                
            $('.show-popup').click(function(){
                showPopup($(this));
                return false;
            })
        }
    }

    this.copyArrows = function () {
        if (myTable) {
            $(elementId + ' .content-table TH').each(function(index){
                $(elementId + ' .floating-header TH:nth-child(' + (index + 1) + ')').attr('class', $(this).attr('class'));
            })
        }
    }

    this.findColumnByName = function(name) {
        index = -1;
        for (i = 0; i < options.length; i++) {
            if (options[i] == name) {
                index = i;
                break;
            }
        }
        return index;
    }

    this.swapColumn = function(col1, col2) {

        if ((myTable) && (col1 != col2)) {
            column1Data = myTable.fnGetColumnData(col1 + 2, false, false, false);
            column2Data = myTable.fnGetColumnData(col2 + 2, false, false, false);

            for (var i = 0; i < column1Data.length; i++) {
                myTable.fnUpdate( column2Data[i], i, col1 + 2 );
                myTable.fnUpdate( column1Data[i], i, col2 + 2 );
            }

            contentCol1 = $(elementId + ' .floating-header TH:nth-child(' + (col1 + 1) + ') A').html();
            contentCol2 = $(elementId + ' .floating-header TH:nth-child(' + (col2 + 1) + ') A').html();

            $(elementId + ' .floating-header TH:nth-child(' + (col2 + 1) + ') A').html(contentCol1);
            $(elementId + ' .floating-header TH:nth-child(' + (col1 + 1) + ') A').html(contentCol2);

            /* copy the sorting arrow */
            classCol1 = $(elementId + ' .floating-header TH:nth-child(' + (col1 + 1) + ')').attr('class');
            classCol2 = $(elementId + ' .floating-header TH:nth-child(' + (col2 + 1) + ')').attr('class');

            $(elementId + ' .floating-header TH:nth-child(' + (col1 + 1) + ')').attr('class', classCol2);
            $(elementId + ' .floating-header TH:nth-child(' + (col2 + 1) + ')').attr('class', classCol1);

            $(elementId + ' .floating-header TH').each(function(index){
                link = $(this).find('A');
                $(this).find("SELECT OPTION[value='" + link.text() + "']").attr('selected', 'selected');
            })

            /* re-arrange the order in the options array */
            temp = options[col1];
            options[col1] = options[col2];
            options[col2] = temp;
        }
        
    }

    this.init();
    /* create the scroller for the element */
    this.scroller = new scroller(elementId);
}




function scroller(elementId) {

    var containerWidth = 360; /* width of the container that contains the scroller control - the value is in pixels */
    var columnsPerPage = 4; /* the number of columns displayed on one page */
    var currentPage = 1; /* initialize the current page variable to 1 */
    var columnWidth = 153; /* value in pixels and includes the border (151 + 2) */

    //var columnsCount = $(elementId + ' .content-table > thead > tr > th').length - 2;
    var columnsCount = $(elementId + ' .content-table > thead > tr > th').length ;
    var numberOfPages = Math.ceil(columnsCount / columnsPerPage);
    var barWidth = Math.round(containerWidth / numberOfPages);
        
    /**
     * Constructor method (builds the actual scroller)
     */
    this.initScroller =  function () {
        var dragDiv = $(elementId + ' .dragBar');
        var myInstance = this;

        dragDiv.css('width', barWidth + "px");
        if (numberOfPages == 1) {
            $('#page_slider_right').css('background-position', 'top left');
            $(elementId + ' .next-big').hide();
        }

        dragDiv.append('<img src="/assets/images/product-selector/page_slider_separator_blue.gif" alt="" style="float: left; display: none;" />');
        dragDiv.append('<img src="/assets/images/product-selector/page_slider_separator_blue.gif" alt="" style="float: right" />');

        $(elementId + ' .slider-wrapper').prepend('<div class="page_slider_separators_wrapper"></div>');
        var separatorsDiv = $(elementId + ' .page_slider_separators_wrapper');
            
        for (i = 0; i< numberOfPages-1; i++) {
            separatorsDiv.append('<div class="page_slider_separators" style="width:' + barWidth + 'px;"></div>');
        }

        $(elementId + ' .slider-wrapper').append('<div class="page_slider_left"></div>');
        $(elementId + ' .slider-wrapper').append('<div class="page_slider_right"></div>');

        dragDiv.draggable({
            axis: 'x',
            containment: 'parent',
            grid: [barWidth, 0],
            opacity: 1.0,
            zIndex: 1000,
            drag: function(event, ui) {
                return myInstance.selectPageByPx(dragDiv.css("left").replace("px",""),0);
            },
            stop: function(event, ui) {
                return myInstance.selectPageByPx(dragDiv.css("left").replace("px",""),0);
            }
        });

        /* start listeners for the prev next buttons */
        $(elementId + ' .prev').click(function () {
            myInstance.prevPage();
            return false;
        })
            
        $(elementId + ' .next').click(function () {
            myInstance.nextPage();
            return false;
        })

        $(elementId + ' .prev-big').click(function () {
            myInstance.prevPage();
            return false;
        })

        $(elementId + ' .next-big').click(function() {
            myInstance.nextPage();
            return false;
        })

        $(elementId + ' .prev-big').hide();
        $(elementId + ' .pagination').text("Viewing specifications 1-4 of " + columnsCount);
    }

        

    /**
     *  Select Page method (works with pixels)
     */
    this.selectPageByPx = function (x, y) {

        var leftRounded = $(elementId + ' .page_slider_left');
        var rightRounded = $(elementId + ' .page_slider_right');
        currentPage = Math.round(x / barWidth) + 1;

        if (x > 0) {
            //we are not on the first page
            leftRounded.css('background-position', 'bottom left');
            $(elementId + ' .dragBar img:first-child').show();
            $(elementId + ' .prev-big').show();
        }

        if (x == 0) {
            //we are on the first page
            leftRounded.css('background-position', 'top left');
            $(elementId + ' .dragBar img:first-child').hide();
            $(elementId + ' .prev-big').hide();
        }

        if (x < containerWidth - barWidth) {
            //we are not on the last page
            rightRounded.css('background-position', 'bottom left');
            $(elementId + ' .dragBar img:last-child').show();
            $(elementId + ' .next-big').show();
            $(elementId + ' .right-blue-border').show();
        }

        if (x >= containerWidth - barWidth) {
            //we are on the last page
            rightRounded.css('background-position', 'top left');
            $(elementId + ' .dragBar img:last-child').hide();
            $(elementId + ' .next-big').hide();

            /* hide the right blue border if we are on last page and number of columns on last page < 4*/
            if (columnsCount % columnsPerPage != 0) {
                $(elementId + ' .right-blue-border').hide();
            }

        }


        scrollerContent = $(elementId + ' .content-div');
        //scrollerContent = $(elementId + ' .dataTables_wrapper');
        scw = scrollerContent.width();
        scp = Math.round(scw / numberOfPages);

        if(x>=0 && x<(containerWidth))
        {
            var width = $(elementId + ' .content-table').width();

            var pagePixels = width / columnsCount * columnsPerPage;

            scrollerContent.css('left', (- (currentPage - 1) * pagePixels ) + "px" );

            var columnStart = (currentPage-1) * columnsPerPage +1;
            var columnEnd = (currentPage * columnsPerPage);
            if (columnEnd > columnsCount) {
                columnEnd = columnsCount;
            }

            $(elementId + ' .pagination').text("Viewing specifications " + columnStart + "-" + columnEnd + " of " + columnsCount);
        }

        return {
            x: x,
            y: y
        }

    }

    this.selectPage = function (page) {
        if (page > numberOfPages) {
            page = numberOfPages;
        }

        if (page < 1) {
            page = 1;
        }

        var pixels = (page - 1) * barWidth;
        $(elementId + ' .dragBar').css('left', pixels + 'px');
        this.selectPageByPx(pixels, 0);
    }

    this.nextPage = function () {
        this.selectPage (currentPage + 1);
    }

    this.prevPage = function () {
        this.selectPage (currentPage - 1);
    }

    this.alternateRow = function() {
        $(elementId + ' .products-table > tbody > tr:even').addClass("even");
        $(elementId + ' .products-table > tbody > tr:odd').addClass("odd");
    }

    this.computeTableWidth = function() {
        var width = columnsCount * columnWidth;
        $(elementId + ' .content-table').css('width', width + 'px');
        $(elementId + ' .floating-header').css('width', width + 'px');
    }

    this.getWidth = function() {
        return columnsCount * columnWidth;
    }

    this.initScroller();
    this.alternateRow();
    this.computeTableWidth();
}
   
function fixHeights(elementId) {
    $(elementId + ' .content-mask').height($(elementId + ' .products-table').height());
    /* position the big prev and next buttons at the middle of the layer */
    headerHeight = $(elementId + ' .products-table TH').height() + 2;
    cellHeight = $(elementId + ' .products-table TD').height();
    /* oh yeah */
    tempHeight = ($(elementId + ' .products-table').height() - 43) / 2 + 17 + (headerHeight - 43) * 0.45;
    $(elementId + ' .next-big').css('top', tempHeight + "px");
    $(elementId + ' .prev-big').css('top', tempHeight + "px");
}


function tabbing(elementId) {
    //create listeners
    $(elementId + ' .category-tab').each(function() {
        $(this).click(function(){

            $(elementId + ' .category-tab').parent().removeClass('selected');
            $(this).parent().addClass('selected');
            $(elementId + ' .zone-table').hide();

            /* printing div */
            $(elementId + ' .zone-table').each(function(){
                $( 'BODY > #printing > #printing-' + $(this).attr('id').replace('-zone-table', '')).addClass('myhidden');
            })
            $('BODY > #printing > #printing-' + $(this).attr('id').replace('-zone','')).removeClass('myhidden');
            /* end of printing div */

            var tabId = $(this).attr('id');
                
            $("#" + tabId + "-table").show();
            fixHeights("#" + tabId + "-table");

            Cufon.refresh();
            return false;
        })
    })

    //select the first category tab every time
    $(elementId + ' .category-tab:first').click();
}


function openLink(productId) {
  console.log('here');
  
    if (productId.length > 0) {
        var productTypesData = {
          "type1":{"series1":["88AP162-B0-BJD2C004","88AP166-B0-BJD2C008","88AP168-B0-BJD2C010","88AP510-A1-BJV2C008","88AP510-A1-BJV2C010","88AP610-A1-BKF2C008-TUNV","88AP610-A1-BLO2C008-TUNV","88AP610-A1-BLO2C010-TUNV","88AP610-A1-BLT2A008-TUNV","88AP610-A1-BLT2C008-TUNV","88AP610-A1-BLT2C010-TUNV"],"series2":["88AP300-A1-BGK2C208-T164","88AP300-A1-BGK2C624-T161","88AP300-A1-BGK2C624-T162","88AP300-A1-BGK2C624-T163","88AP303-A1-BGF2C208-TN22","88AP303-A1-BGF2C208-TN32","88AP303-A1-BGF2C624-TN12","88AP303-A1-BGF2C624-TN22","88AP303-A1-BGF2C624-TN32","88AP310-B1-BGK2C624-TN02","88AP310-B1-BGK2C624-TS02","88AP310-B1-BGK2C806-TN02","88AP320-C0-BGR2C624-TN10","88AP320-C0-BGR2C624-TN20","88AP320-C0-BGR2C624-TN21","88AP320-C0-BGR2C624-TN30","88AP320-C0-BGR2C806-TN10","88AP320-C0-BGR2C806-TN11","88AP320-C0-BGR2C806-TN21","88AP320-C0-BGR2C806-TN30","88AP320-C0-BGR2C806-TN31","88AP320-C0-BGR2E806-TN21","88AP270MA2-BGO2C312","88AP270MA2-BGO2C416","88AP270MA2-BGO2C520","88AP270MA2-BGO2C624","88AP270MA2-BHE1C312","88AP270MA2-BHE1C416","88AP270MA2-BHE1C520","88AP270MA2-BHE1C624","88AP270MA2-BHE1E312 (Extended Temp)","88AP270MA2-BHE1E416 (Extended Temp)"]},
          "type2":{"series3":["MV76100","MV78100","MV78200"],"series4":["88F6321","88F6322","88F6323"],"series5":["88F6180","88F6192","88F6280","88F6281"],"series33":["88F6282","88F6283"]},
          "type3":{"series6":["Yukon FE+ 88E8040","Yukon FE+ 88E8040","Yukon Optima 88E8059","Yukon Optima 88E8059","Yukon Ultra II 88E8057","Yukon Ultra II 88E8057","Yukon Ultra II 88E8057"]},
          "type4":{"series7":["Link Street 88E6218","Link Street 88E6218R","Link Street 88E7251","Link Street 88E7251F"]},
          "type5":{"series8":["88SB2211"]},
          "type6":{"series9":["88PG839","88PG877","88PH8101","88PH845","MVPG16","MVPG31"],"series10":["88PG8111","88PG817x","88PG8218","88PG827x","88PG8318 (2 LDO)","88PG837x","88PG847x","88PG849E","88PW889","MVPG15x","MVPG30x"],"series11":["88PG8211 (2 Buck + LDO)","88PG8216","88PG8226","88PG8227","88PG8237","88PW886 (3 buck + 3 LDO)"],"series34":["88EM8080","88EM8081"]},
          "type7":{"series12":["88SE6101","88SE6121","88SE6145","88SE9120","88SE9125","88SE9130"],"series13":["88SE6320","88SE6340","88SE6440","88SE6445","88SE6480","88SE6485","88SE9485","88SE9445"],"series14":["88SM4021","88SM4140"],"series15":["88SA8052"],"series16":["88SF6210B1"]},
          "type8":{"series17":["88E6020","88E6031","88E6035","88E6060","88E6061/B","88E6063","88E6065/B","88E6070","88E6071","88E6083","88E6085"],"series18":["88E6045","88E6046","88E6092/95","88E6095F","88E6096/97","88E6097F"],"series19":["88E6121","88E6122","88E6123","88E6131","88E6152/55","88E6161","88E6165","88E6171","88E6172","88E6171R","88E6175","88E6176","88E6175R","88E6182/85","88E6350","88E6350R","88E6351","88E6352"]},
          "type9":{"series20":["Prestera-DX107","Prestera-DX160","Prestera-DX167","Prestera-DX240","Prestera-DX249","Prestera-DX253","Prestera-DX269","Prestera-DX273","Prestera-DX5128","Prestera-DX8110","Prestera-DXx24","Prestera-DXx16","Prestera-DXx08"],"series21":["Prestera-CX8234","Prestera-CX8248"],"series22":["Prestera-MV82104-Cx","Prestera-MV82110-Cx","Prestera-MV82210-Cx","Prestera X2220"]},
          "type10":{"series23":["Discovery VI MV64660"],"series24":["Discovery V MV64560"],"series25":["Discovery III MV64440","Discovery III MV64441","Discovery III MV64442","Discovery III MV64460","Discovery III MV64461","Discovery III MV64462"]},
          "type11":{"series26":["Alaska 88E1111","Alaska 88E1112","Alaska 88E1113","Alaska 88E1114","Alaska 88E1116R","Alaska 88E1118R","Alaska 88E1119R","Alaska 88E1310","Alaska 88E1318", "Alaska 88E1310S","Alaska 88E1318S","Alaska 88E1121R","Alaska 88E1322","Alaska 88E1143","Alaska 88E1145","Alaska 88E1240","Alaska 88E1340","Alaska 88E1340S"],"series27":["88E3015","88E3016","88E3018","88E3019","88E3082","88E3083"],"series28":["Alaska X 88X2010","Alaska X 88X2011","Alaska X 88X2012","Alaska X 88X2013","Alaska X 88X2040","Alaska X 88X2080"]},
          "type12":{"series29":["88DE2710","88DE2750","88DE2755"],"series30":["88DE8010","88DE8020","88DE8500"]},
          "type13":{"series31":["88W8366/88W8063","88W8786"],"series32":["88W8764","88W8782","88W8787","88W8790"]}
        };
        found = false;
        myModule = "";
        mySection = "";
        for (ptype in productTypesData) {
            //alert(ptype);
            ptypeArray = productTypesData[ptype]
            for (pserie in ptypeArray) {
                pserieArray = ptypeArray[pserie];
                for (var i = 0; i < pserieArray.length; i++) {
                    if (pserieArray[i] == productId) {
                        myModule = ptype;
                        mySection = pserie + "-zone";
                        found = true;
                        break;
                    }
                }
                if (found) break;
            }
        }

        if (found) {
            if ($('#' + myModule).hasClass('tab-plus')) {
                $('#' + myModule).click();
            }

            $('#' + mySection).click();

            setTimeout("window.scroll(0,$('#' + myModule).offset().top)",500);
        }
    }

}

function showPopup(link)  {
    console.log('here');
  
    url = link.attr("href");

		if($('#popup').length) { //Does it exist? If so, trash it and get a new one
			$('#popup').remove();
		}

    $.ajax({
        url: url,
        success: function(data) {
            $('body').append(data);
            Cufon.refresh();

            var position = link.offset();
            
            $('#popup').show();

            $('#popup').css({
                top: position.top - 65,
                left: position.left + link.width() + 20
            });

            $('#popup').stop(true, true).animate({
                left: position.left + link.width()
            } , "slow");

            $('#popup .close').click(function(){
                $('#popup').remove();
                return false;
            })

            /* tabbing for the popup */
            $('#ptabs > UL > LI > A').click(function(){
                $('#ptabs > UL > LI > A').removeClass('selected');
                $(this).addClass('selected');

                $('#ptabs .content-tab').hide();
                $('#ptabs #'+ $(this).attr('id') + '-content').show();

                return false;
            })

            /* select first tab of the popup */
            $('#tab-briefs').click();
        }
    });
    
}

function init_popup() {

    $('.show-popup').click(function(){
        showPopup($(this));
        return false;
    })
}


function init_allproducts() {

    tabbing('#type1-content');

    tabbing('#type2-content');

    tabbing('#type3-content');

    tabbing('#type4-content');

    tabbing('#type5-content');

    tabbing('#type6-content');

    tabbing('#type7-content');

    tabbing('#type8-content');

    tabbing('#type9-content');

    tabbing('#type10-content');

    tabbing('#type11-content');

    tabbing('#type12-content');

    tabbing('#type13-content');

    if (window.location.hash) {
        hash = window.location.hash.substr(1);
        openLink(hash);
    }

    $("#toc-content A").click(function(){
        productId = $(this).attr('href').substr(1);
        openLink(productId);
    })

    init_popup();
}


function extractProducts(name){
    var productsList = new Array();
    $("#" + name + "-zone-table .products-table a").each(function(){
        if ($(this).text() != "More Info") {
            productsList.push($(this).text());            
        }
    })
       
    mystring ="var " + name + " = new Array (";
    for (i = 1; i< productsList.length; i++) {
        mystring += " \"" + productsList[i] + "\" , ";
    }
    mystring += "<br/><br/>"
    
    $('#myproducts').append(mystring);

}

