var p;
var t;
var s = null;
var global_placeholders;
$(document).ready(function() {
        /* scrollto() doesn't work in IE 8. Hide for now */
        if ($.browser.msie && $.browser.version == "8.0") {
           $("#index").hide();
        }
	global_placeholders = $('#tselected tbody tr:has(td.placeholder)').clone();
	$('#products tbody').load('cgi-bin/product.pl', {'q': '', 'market': market },
				     function (responseText, textStatus, XMLHttpRequest) {
					 $("#products_throbber").replaceWith(temp);
					 $("#products").css('visibility', 'visible');
					 $("#products thead").css('visibility', 'visible');
					 $("#products tfoot").css('visibility', 'visible');
					 p = new ScrollableTable($('#products')[0],  h);
				     });
	var h = $('#products').css('height');
	var w = 'auto'; /* FF won't use the whole width otherwise */
	var temp=$('#products').replaceWith($("<div id='products_throbber' style='margin: 0; padding: 0; height: "+h+"; width: "+w+";'></div>"));
	$.throbberShow({image: "images/throbber.gif", parent: $('#products_throbber')});
	/* $('#tselected thead').css('visibility', 'hidden'); */
	t = new ScrollableTable($('#tselected')[0],  h);
	$("#search").css('visibility','visible');
	$("#search").dialog({autoOpen: false, height: 300, width: 600, resizable: false});
	$("input[name='search']").click(search_click);
	$("input[name='product']").keyup(function(event) {
		if (event.keyCode == 13) { search_click(); return false; } else { return true; } });
	$("input[name='select']").click(select_click);
	$("input[name='checkall']").click(checkall_click);
	$("input[name='inquire']").click(inquire_click);
	$("input[name='remove']").click(remove_click);
	$("input[name='remove_all']").click(remove_all_click);
	$("input[name='addchecked']").click(addchecked_click);
	$("#product").autocomplete('cgi-bin/product.pl',
				   {delay:10,
				    extraParams:{ 'market': market },
				    minChars:2,
				    matchSubset:1,
				    matchContains:1,
				    cacheLength:10,
				    autoFill:true
				   });
    });

function search_click() {
    if (s) { $(s).empty(); }
    $('#search').dialog('open');
    var product = $("input[name='product']")[0].value;
    var cats = $("input[name='catsearch']").map(function () { if (this.checked) { return this.value } }).get();
    var apps = $("input[name='appsearch']").map(function () { if (this.checked) { return this.value } }).get();
    $('#tsearch tbody').load('cgi-bin/search.pl',
			     {'market': market, 'product': product, 'catsearch[]': cats, 'appsearch[]': apps },
			     function (responseText, textStatus, XMLHttpRequest) {
				 $("#search_throbber").replaceWith(temp);
				 $("#tsearch").css('visibility', 'visible');
				 $("#tsearch thead").css('visibility', 'visible');
				 $("#tsearch tfoot").css('visibility', 'visible');
				 $("#search input").css('visibility', 'visible');
				 $("#search h2").text(cats+' '+apps);
				 refill('#tsearch');
				 if (s == null) {
				     s = new ScrollableTable($('#tsearch')[0],  h);
				 }
			     });
    var h = $('#tsearch').css('height');
    var w = 'auto';  /* FF won't use the whole width otherwise */
    var temp=$('#tsearch').replaceWith($("<div id='search_throbber' style='margin: 0; padding: 0; height: "+h+"; width: "+w+";'></div>"));
    $.throbberShow({image: "images/throbber.gif", parent: $('#search_throbber')});
}

function select_click() {
    to_tselected_from('#products');
}

function addchecked_click () {
    to_tselected_from('#tsearch');
    $('#search').dialog('close');
    /*$('#tsearch tbody').empty();*/
}

function to_tselected_from (id) {
    var toadd = $(id+' tbody tr:has(input:checked)').clone();
    $('td:first-child input', toadd).attr('checked',1);
    $(id+' tbody tr td:first-child input:checked').removeAttr('checked');
    $('#tselected tbody tr:has(td.placeholder)').remove();
    var added=0;
    for (var i=0; i<toadd.length; i++) {
	/* add if the row is not already in the table */
	if ($('#tselected tbody tr td:nth-child(2):contains("'+$('td:nth-child(2)', toadd[i]).text()+'")').length == 0) {
	    $('#tselected tbody').append($(toadd[i]));
	    added = added+1;
	}
    }
    refill('#tselected');
}

function checkall_click() {
    $('#tsearch input:unchecked').attr('checked',1);
}

function inquire_click () {
    $('#tselected tbody tr :checkbox').each(function ()
						 { $('<input type="hidden" name="sel[]" value="'+this.value+'">').appendTo($("#inquiry_form")) });
    $('#inquiry_form').submit();
}

function remove_click () {
    $('#tselected tbody tr:has(td:first-child input:checked)').remove();
    refill('#tselected');
}

function remove_all_click () {
    $('#tselected tbody').empty();
    refill('#tselected');
}

function refill (id) {
    var count = $(id+' tbody tr').length;
    if (global_placeholders.length-count > 0) {
	$(id+' tbody').append(global_placeholders.clone().slice(0,global_placeholders.length-count));
    }
}

var a2z = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

function scrollto (index) {
  var a
  if (index == 'A') {
    a = $("#products tbody tr:first")
  } else {
    for(var i = a2z.indexOf(index); i < a2z.length; i++) {
      var a = $("#products tbody tr:has(td.prod:startswith('"+a2z.charAt(i)+"')):first")
      if (a.length>0) {
        break;
      }
    }
  }
  if (a.length > 0) {
    a[0].scrollIntoView();
    $('#products th.first').text(index);
    if (jQuery.browser.msie) {
      $('#products')[0].scrollTop=$('#products')[0].scrollTop-16;
      /*$('#products')[0].scrollLeft=0*/
    }
  }
}

function ScrollableTable (tableEl, tableHeight, tableWidth) {

    this.initIEengine = function () {

        this.containerEl.style.overflowY = 'auto';
        this.containerEl.style.overflowX = 'hidden';
        if (this.tableEl.parentElement.clientHeight - this.tableEl.offsetHeight < 0) {
            this.tableEl.style.width = this.newWidth - this.scrollWidth +'px';
        } else {
            this.containerEl.style.overflowY = 'hidden';
            this.tableEl.style.width = this.newWidth +'px';
        }

        if (this.thead) {
            var trs = this.thead.getElementsByTagName('tr');
            for (x=0; x<trs.length; x++) {
                trs[x].style.position ='relative';
                try {
                  trs[x].style.setExpression("top",  "this.parentElement.parentElement.parentElement.scrollTop + 'px'");
                } catch (e) {
                  /* does not work in IE 8. acceptable without it, pending workaround. */
                }
            }
        }

        if (this.tfoot) {
            var trs = this.tfoot.getElementsByTagName('tr');
            for (x=0; x<trs.length; x++) {
                trs[x].style.position ='relative';
                trs[x].style.setExpression("bottom",  "(this.parentElement.parentElement.offsetHeight - this.parentElement.parentElement.parentElement.clientHeight - this.parentElement.parentElement.parentElement.scrollTop) + 'px'");
            }
        }

        eval("window.attachEvent('onresize', function () { document.getElementById('" + this.tableEl.id + "').style.visibility = 'hidden'; document.getElementById('" + this.tableEl.id + "').style.visibility = 'visible'; } )");

    };


    this.initFFengine = function () {
        this.containerEl.style.overflow = 'hidden';
        this.tableEl.style.width = this.newWidth + 'px';

        var headHeight = (this.thead) ? this.thead.clientHeight : 0;
        var footHeight = (this.tfoot) ? this.tfoot.clientHeight : 0;
        var bodyHeight = this.tbody.clientHeight;
        var trs = this.tbody.getElementsByTagName('tr');
        if (bodyHeight >= (this.newHeight - (headHeight + footHeight))) {
            this.tbody.style.overflow = '-moz-scrollbars-vertical';
            for (x=0; x<trs.length; x++) {
                var tds = trs[x].getElementsByTagName('td');
                tds[tds.length-1].style.paddingRight += this.scrollWidth + 'px';
            }
        } else {
            this.tbody.style.overflow = '-moz-scrollbars-none';
        }

        var cellSpacing = (this.tableEl.offsetHeight - (this.tbody.clientHeight + headHeight + footHeight)) / 4;
        this.tbody.style.height = (this.newHeight - (headHeight + cellSpacing * 2) - (footHeight + cellSpacing * 2)) + 'px';

    };

    this.tableEl = tableEl;
    this.scrollWidth = 16;

    this.originalHeight = this.tableEl.clientHeight;
    this.originalWidth = this.tableEl.clientWidth;

    this.newHeight = parseInt(tableHeight);
    this.newWidth = tableWidth ? parseInt(tableWidth) : this.originalWidth;

    this.tableEl.style.height = 'auto';
    this.tableEl.removeAttribute('height');

    this.containerEl = this.tableEl.parentNode.insertBefore(document.createElement('div'), this.tableEl);
    this.containerEl.appendChild(this.tableEl);
    this.containerEl.style.height = this.newHeight + 'px';
    this.containerEl.style.width = this.newWidth + 'px';


    var thead = this.tableEl.getElementsByTagName('thead');
    this.thead = (thead[0]) ? thead[0] : null;

    var tfoot = this.tableEl.getElementsByTagName('tfoot');
    this.tfoot = (tfoot[0]) ? tfoot[0] : null;

    var tbody = this.tableEl.getElementsByTagName('tbody');
    this.tbody = (tbody[0]) ? tbody[0] : null;

    if (!this.tbody) return;

    if (document.all && document.getElementById && !window.opera) this.initIEengine();
    if (!document.all && document.getElementById && !window.opera) this.initFFengine();
}

