/*
 * $Id: jquery.imageselectbox.js 3122 2008-12-04 16:21:53Z tkrauss $
 *
 * This document contains trade secret data which is the property of
 * markt.de GmbH & Co KG. Information contained herein may not be used,
 * copied or disclosed in whole or part except as permitted by written
 * agreement from markt.de GmbH & Co KG.
 *
 * Copyright (C) 2008 markt.de GmbH & Co KG / Munich / Germany
 *
 * author:tkrauss
 */

/**
 * Select box  replacement
 */
$.fn.imageselectbox = function(options) {
  options = options || {};
  return this.each(function() {
    var width = options.width;
    var height = options.height;
    var bgUrl = options.backgroundUrl;
    var maxSize = options.maxSize;
    var displayStyleOpt = options.style;

    var boxStyle = "display:none;position:absolute;top:" + height + "px;left:0;width:" + width + "px;";
    var wrapperStyle = "position:relative;padding:0;margin:0;height:" + height + "px;width:"
        + width + "px";
    var displayStyle = "position: absolute;top:0;left:0;border:0;height:" + height + "px;width:" + width
        + "px;background: no-repeat url(" + bgUrl + ");" + displayStyleOpt;

    var box = $(this);
    var boxId = box.attr("id");
    var opts = box.children("option");

    // get the current selected value
    var value = opts.length > 0 ? $(opts[0]).text() : "";
    for (var i = 0; i < opts.length; i++) {
      var o = $(opts[i]);
      if (o.attr("selected")) {
        value = o.text();
      }
      if (opts.length == 1) {
        o.attr("selected", "selected");
      }
    }

    // "expand" the select box
    box.attr("size", opts.length > maxSize ? maxSize : opts.length).attr("style", boxStyle);

    // wrap the original select box
    box.wrap("<div id='isb_wrapper'></div>");
    box.before("<div id='isb_display'/>");
    $("#isb_wrapper").attr("style", wrapperStyle);
    $("#isb_display").attr("style", displayStyle).text(value);
    if (opts.length >= 2) {
      $("#isb_display").click(function() {
        $("#" + boxId).show();
      });
    }

    // bind on change event to capture mouse clicks
    box.change(function() {
      $('#isb_display').text(this.options[this.selectedIndex].text);
      $(this).hide();
    });

    // todo: hide box also when no selection !
    /*$("html").click(function(){
     setTimeout("if($('#s1').css('display') == 'block') $('#s1').hide()", 0)
     });*/
  });
};
