
/*
 * jQuery Styled File Input Field plugin
 */

(function($) {
	$.fn.StyledCheckboxField = function(options) {

    var opts = $.extend({}, $.fn.StyledCheckboxField.defaults, options);

    $.fn.StyledCheckboxField.defaults = {
        width:11,
        height:11
    }

    $.fn.StyledCheckboxField.settings = {
        checkboxID : null,
        checkboxName : null,
        wrapperID : null,
        newCheckboxID : null,
        newLabelID : null,
        newCheckbox : null,
		checked: false
    }

    var $this = $.fn.StyledCheckboxField.settings;
    
    var toggle = function(el){
        if (el.checked) {
            unCheck(el);
        } else {
            check(el);
        }
    };
    var check = function(el){
		if (!$this.checked) {
            $this.newCheckbox.css('background-position', 'left -'+opts.height+'px');
            jQuery('#' + $this.checkboxID).attr('checked', true);
            $this.checked = true;
        }
    };
    var unCheck = function(el){
        if ($this.checked) {
            $this.newCheckbox.css('background-position', 'left 0px');
            jQuery('#' + $this.checkboxID).attr('checked', false);
            $this.checked = false;
        }
    };
    var addEventHandlers = function(el){
        $this.newCheckbox.click(function() {
            toggle(el);
        });
        $this.label.click(function(event) {
			event.preventDefault();
            toggle(el);
        });
    };
    var setInitialStyles = function(){
        $this.newCheckbox.css({
            height: parseInt(opts.width)+'px',
            width: parseInt(opts.height)+'px',
            cursor: 'pointer'
        });

        $this.label.css({
            cursor: 'pointer'
        });
    };

    return this.each(function() {
        //set ID & Name
        $this.checkboxID = $(this).attr("id");
        $this.checkboxName = $(this).attr("name");
		
		// attempt to find a valid label for this checkbox
		$this.label = $('label[for=' + $this.checkboxID + ']');
		
		$this.wrapperID = "#" + $this.checkboxName + '_' + $this.checkboxID;

        // using the name from the old check box create new id
        $this.newCheckboxID = "#" + $this.checkboxID + 'Pretty';
        
        if (!$this.label.length) {
            //alert("No label on checkbox: " + $this.checkboxID);
        }
        // hide the old ugly checkbox
        $(this).css('display', 'none');

        // create and store the new pretty checkbox
        var newCheck = $('<div></div>').attr({
            'id': $this.newCheckboxID,
            'className': 'newCheckbox'
        });
        $this.newCheckbox = newCheck;

        $(this).after($this.newCheckbox);

        setInitialStyles();

        // get checkboxHolder and insert pretty checkbox
        $($this.wrapperID).prepend($this.newCheckbox);

        $this.checked = false;
        if ($(this).attr('checked') == true) {
			check(this);
        }
        addEventHandlers(this);
    });
  }
})(jQuery);
