/*
 * $Id: jquery.imagecheckbox.js 4534 2009-03-04 12:06:06Z 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
 */

/**
 * Checkbox replacement, creates a checkbox from images.
 * Grouping behaviour is also available (only one checkbox can be selected in a group, or none).<br/>
 * Example:<br/>
 * <img id="img1" name="group"><br/>
 * <img id="img2" name="group"><br/>
 * <input id="group"/>
 *
 * @param options<br/>
 * status: initial status of the box, optional, 0|1, default is 0<br/>
 * imgOn: image for selected status, required, any url<br/>
 * imgOff: image for deselected status, required, any url <br/>
 * groupMode: grouping on/off, optional, any value, default no grouping<br/>
 */
$.fn.imagecheckbox = function(args) {
  var options = args || {};

  // setting value to to a hidden field wich can be submitted
  var setHiddenValue = function(obj, status) {
    var name = obj.attr("name");
    var value = options.value;
    if (value == null) {
      value = obj.attr("id"); // take id if value not supplied in tag
    }
    $("#" + name).val(status == 1 ? value : "").attr("name", name);
  };

  return this.each(function() {

    var obj = $(this);
    var status = options.status == null ? 0 : options.status;

    // set the initial value to submit, 
    // in grouping mode only one hidden field exist and should have the evalue of the selected box
    if (options.groupMode == null || (options.groupMode != null && status == 1)) {
      setHiddenValue(obj, status);
    }

    obj.attr("status", status).attr("src", status == 0 ? options.imgOff : options.imgOn).click(function() {
      var obj = $(this);
      var name = obj.attr("name");
      var st = obj.attr("status") == 0 ? 1 : 0;
      if (options.groupMode != null && st == 1) {
        // group mode is on, if one is selected deselect others
        $("img[name=" + name + "]").attr("status", 0).attr("src", options.imgOff);
      }
      setHiddenValue(obj, st);

      // switching status and image
      obj.attr("status", st).attr("src", st == 0 ? options.imgOff : options.imgOn);
    });
  });
};
