/*
 * jQuery selectRelation plugin
 * Version: 0.1.0
 *
 * Copyright (c) 2008 Alexander Smalle
 *
 * Dual licensed under the MIT and GPL licenses 
 *
 *
 * Changelog: 
 * v 0.1.0 - 2008-04-28
 *
 * Todo:
 * - handle special chars ',".. in value
 */
 

(function($) {
  jQuery.fn.selectRelation = function(settings) {
    settings = jQuery.extend({
    version: "0.1.0"
    }, settings);
    var selectRelationContainterList=this;
    return selectRelationContainterList.each(function(){
      var selectRelationContainterDomElem = this;
      jQuery('.parent').each(function() {
        var parent=jQuery(this).attr('id');
        var childDomElem = jQuery('.child_' + parent, selectRelationContainterDomElem);
        var child=childDomElem.attr('id');
        var relationMap = {};
        var childSelectedValue=$('#'+child).attr('value');
        childSelectedValue = (typeof childSelectedValue == "undefined")? "" : childSelectedValue;
        jQuery("#"+child+" option").each( function(i) {
            var myKey=jQuery(this).attr('alt');
            var myValue=jQuery(this).attr('value');
            var myLabel=jQuery(this).html();
            myValue = (typeof myValue == "undefined")? "" : myValue;
            myLabel = (typeof myLabel == "undefined")? "" : myLabel;
            if (relationMap[myKey] == undefined) {
              relationMap[myKey]= [{value:myValue, label:myLabel}]; // new array
            } else {
              relationMap[myKey].push( {value:myValue, label:myLabel} );
            }
          }
        );
        var parentValue = jQuery('#'+parent).attr('value');
        $('#'+child).html(''); //empty
        if (relationMap['selectRelation_'+parentValue] != undefined) {
          for(var i = 0; i < relationMap['selectRelation_'+parentValue].length; i++) {
            $('#'+child).append('<option value=\''+relationMap['selectRelation_'+parentValue][i].value+'\'>'+relationMap['selectRelation_'+parentValue][i].label+'</option>');
          }
          $("#"+child+' option[@value="'+ childSelectedValue +'"]').attr('selected','selected');
        }
        var childValue = $('#'+child).attr('value');
        $('#'+parent).change(
          function() {
            var parentValue = $('#'+parent).attr('value');
            $('#'+child).html(''); //empty
            if (relationMap['selectRelation_'+parentValue] != undefined) {
              for(var i = 0; i < relationMap['selectRelation_'+parentValue].length; i++) {
                $('#'+child).append('<option value=\''+relationMap['selectRelation_'+parentValue][i].value+'\'>'+relationMap['selectRelation_'+parentValue][i].label+'</option>');
              }
              $("#"+child+' option[@value="'+ childSelectedValue +'"]').attr('selected','selected');
            }
            $('#'+child).trigger("change");
            $('#'+child).focus();
        });
      });
    });
  };
})(jQuery);
