(function($) {
  $.fn.emptySelect = function() {
    return this.each(function(){
      if (this.tagName=='SELECT') this.options.length = 0;
    });
  }

  $.fn.loadSelect = function(optionsDataArray) {
    return this.emptySelect().each(function(){
      if (this.tagName=='SELECT') {
        var selectElement = this;
        $.each(optionsDataArray,function(index,optionData){
          var option = new Option(optionData.caption,
                                  optionData.value);
          if ($.browser.msie) {
            selectElement.add(option);
          }
          else {
            selectElement.add(option,null);
          }
        });
      }
    });
  }
})(jQuery);


function updateFormats(product) {
	list = {};
	fl = formats.length;
	for (i=0; i<fl; i++) {
		if (formats[i]['product_code'] == product) {
			list[i] = {value:formats[i]['code'],caption:formats[i]['format']};
		}
	}
	$("#format").loadSelect(list);
	$("#format").attr("disabled", false);
	$("#quantity").attr("disabled", false);
	$("#quantity :first-child").attr("selected","selected");
	$("#add").attr("disabled", false);
}

function resetForm() {
	$("#product :first-child").attr("selected","selected");
	$("#format").attr("disabled", true);
	$("#format").emptySelect();
	$("#quantity").attr("disabled", true);
	$("#quantity :first-child").attr("selected","selected");
	$("#add").attr("disabled", true);
}

function addRecord() {
	rnum = recordId;
	pc = $("#product").val();
	pn = $("#product option:selected").text();
	fc = $("#format").val();
	fn = $("#format option:selected").text();
	qt = $("#quantity").val();
	records[rnum] = {productcode:pc, productname:pn, formatcode:fc, formatname:fn, quantity:qt};
	$.cookie('records', JSON.stringify(records));
	recordId++;
	
	updateRow(rnum, pn, fn, qt);
	
	resetForm();
	$("#selectedlist").show();
	$("#checkout").show();
}

function updateOrderTable() {
	for (i in records) {
		rnum = recordId;
		pn = records[i].productname;
		fn = records[i].formatname;
		qt = records[i].quantity;
		recordId++;
		
		updateRow(rnum, pn, fn, qt);
		
		$("#selectedlist").show();
		$("#checkout").show();
	}
}

function updateRow(rnum, pn, fn, qt) {
	deleteimg = '<a href="#" onclick="deleteRecord('+rnum+'); return false;"><img src="/img/delete.png" alt="" /></a>';
	newrow = "<tr class=\"record\"><td>" + pn + "</td><td>" + fn + "</td><td class=\"qty\">" + qt + "</td><td class=\"delete\">" + deleteimg + "</td></tr>";
	$("#selectedlist").append(newrow);
}

function deleteRecord(id) {
	records.splice(id,1);
	$.cookie('records', JSON.stringify(records));
	$(".record").remove();
	recordId = 0;
	if (recordsIsEmpty()) {
		$("#selectedlist").hide();
		$("#checkout").hide();
	} else {
		updateOrderTable();
	}
}

function transferData() {
	// convert records object to JSON. Needs json2.js
	$("#selectedItems").val(JSON.stringify(records));
	return true;
}

function recordsIsEmpty() {
	if (typeof(records)=="undefined") return true;
	var count = 0;
	for (var i in records) {
		if (typeof(this[i])!='function') count++;
	}
	return (count==0);
}

var recordId = 0;
var records = new Array();


$(document).ready(function(){

	$("#selectedlist").hide();
	$("#checkout").hide();
	
	// check for cookie value
	if ($.cookie('records')) records = eval($.cookie('records'));
	if (!recordsIsEmpty()) updateOrderTable();

	$("#product").change(function() {
		if (this.value) {
			updateFormats(this.value);
		} else {
			resetForm();
		}
	});

	$("#add").click(function() {
		addRecord();
	});

	$("#productChooser").submit(function() {
		return transferData();
	});

	$("#confirm").submit(function() {
		// erase cookie if set
		if ($.cookie('records')) $.cookie('records', null);
	});

});


