/*
 * UPDATED: 12.19.07
 *
 * jNice
 * by Sean Mooney (sean@whitespace-creative.com) 
 *
 * To Use: place in the head 
 *  <link href="inc/style/jNice.css" rel="stylesheet" type="text/css" />
 *  <script type="text/javascript" src="inc/js/jquery.jNice.js"></script>
 *
 * And apply the jNice class the form you want to style
 *
 * To Do: Add textareas, Add File upload
 *
 ******************************************** */
 
var jNiceSavedZIndex = 1;
 
(function($){
    $.fn.jNice = function(options){
        var self = this;
        var safari = $.browser.safari; /* We need to check for safari to fix the input:text problem */
    
        /* each form */
        this.each(function(){
            /***************************
              Buttons
             ***************************/
            var setButton = function(){
                $(this).replaceWith('<button id="'+ this.id +'" name="'+ this.name +'" type="'+ this.type +'" class="'+ this.className +'"><span><span>'+ $(this).attr('value') +'</span></span>');
            };
            $('input:submit, input:reset', this).each(setButton);
            
            /***************************
              Text Fields 
             ***************************/
            var setText = function(){
                var $input = $(this);
                $input.addClass("jNiceInput").wrap('<div class="jNiceInputWrapper"><div class="jNiceInputInner"><div></div></div></div>');
                var $wrapper = $input.parents('div.jNiceInputWrapper');
                $wrapper.css("width", $(this).width()+10);
                $input.focus(function(){
                    $wrapper.addClass("jNiceInputWrapper_hover");
                }).blur(function(){
                    $wrapper.removeClass("jNiceInputWrapper_hover");
                });
            };
            $('input:text:visible, input:password', this).each(setText);
            /* If this is safari we need to add an extra class */
            if (safari){$('.jNiceInputWrapper').each(function(){$(this).addClass('jNiceSafari').find('input').css('width', $(this).width()+11);});}
            
                        var CheckAdd = function(){
                            var $input = $(this).addClass('jNiceHidden').wrap('<span class="jNiceWrapper"></span>');
                            var $wrapper = $input.parent().append('<span class="jNiceCheckbox"></span>');

                            /* Click Handler */
                            var clickHandler = function($a) {
                                    var input = $a.siblings('input')[0];
                                    if ($(input).attr('checked')){
                                        input.checked = false;
                                        $a.removeClass('jNiceChecked');
                                    }
                                    else {
                                        input.checked = true;
                                        $a.addClass('jNiceChecked');
                                    }
                                    if ($a.siblings('input')[0].onclick) { typeof $a.siblings('input')[0].onclick == "function" ? $a.siblings('input')[0].onclick() : eval($a.siblings('input')[0].onclick); }
                                    $(input).trigger('change');
                                    return false;
                            }

                            var $a = $wrapper.find('.jNiceCheckbox').click(function(){
                                    return clickHandler($(this));
                            });

                            if ($.browser.msie || $.browser.opera)
                                $('label[for=' + $(this).attr('id') + ']').click(function() {
                                        clickHandler($a);
                                        return false;
                                });

                            $input.click(function(){
                                if(this.checked){ $a.addClass('jNiceChecked');  }
                                else { $a.removeClass('jNiceChecked'); }
                            }).focus(function(){ $a.addClass('jNiceFocus'); }).blur(function(){ $a.removeClass('jNiceFocus'); });
                            
                            /* set the default state */
                            if (this.checked){$('.jNiceCheckbox', $wrapper).addClass('jNiceChecked');}
                        }; 
            /***************************
              Check Boxes 
             ***************************/
            $('input:checkbox', this).each(CheckAdd);

            
            /***************************
              Radios 
             ***************************/
            $('input:radio', this).each(function(){
                $input = $(this);
                $input.addClass('jNiceHidden').wrap('<span class="jRadioWrapper"></span>');
                var $wrapper = $input.parent();
                $wrapper.prepend('<a href="#" class="jNiceRadio" rel="'+ this.name +'"></a>');
                /* Click Handler */
                var clickHandler = function($a){
                        var nameSel = 'input[name=' + $($a.siblings('input')[0]).attr('name') + ']'; 
                        var inpSel = nameSel + ':checked';
                        var prevVal = $(inpSel).val();

                        $a.siblings('input')[0].checked = true;
                        $($a.siblings('input')[0])
                            .attr('checked', 'checked')
                            .attr('selected', 'selected');
                        $a.addClass('jNiceChecked');
                        /* uncheck all others of same name */
                        $('a[rel="'+ $a.attr('rel') +'"]').not($a).each(function(){
                            $(this).removeClass('jNiceChecked').siblings('input')[0].checked=false;
                            $($(this).siblings('input')[0])
                                .removeAttr('checked')
                                .removeAttr('selected');
                        });
                        if ($a.siblings('input')[0].onclick) { typeof $a.siblings('input')[0].onclick == "function" ? $a.siblings('input')[0].onclick() : eval($a.siblings('input')[0].onclick); }

                        if ($(inpSel).val() != prevVal) {
                            $(nameSel).trigger('change');
                        }
                        return false;
                };
                
                $('a.jNiceRadio', $wrapper).click(function() { return clickHandler($(this)); });

                /* set the default state */
                if ($(this).attr('checked') || $(this).attr('selected')){
                        $('a.jNiceRadio', $wrapper).addClass('jNiceChecked');
                        $('a.jNiceChecked input')
                            .attr('checked', 'checked')
                            .attr('selected', 'selected');
                    }

                // if ($.browser.msie || $.browser.opera)
                var $a = $wrapper.find('.jNiceRadio');
                  $('label[for=' + $(this).attr('id') + ']').click(function() {
                  clickHandler($a);
                  return false;
                });
            });
    
            
            /***************************
              Selects 
             ***************************/
            $('select', this).each(function(index){
                var $select = $(this);
                /* First thing we do is Wrap it */
                $(this).addClass('jNiceHidden').wrap('<div class="jNiceSelectWrapper"></div>');
                var $wrapper = $(this).parent();//.css({zIndex: 100-index});
                /* Now add the html for the select */
                $wrapper.prepend('<div><span></span><a href="#" class="jNiceSelectOpen"></a></div><p><ul></ul></p>');
                var $ul = $('ul', $wrapper);
                /* Now we add the options */
                $('option', this).each(function(i){
                    $ul.append('<li><a href="#" index="'+ i +'">'+ this.text +'</a></li>');
                });
                /* Hide the ul and add click handler to the a */
                $ul.hide().find('a').click(function(){
                        $('a.selected', $wrapper).removeClass('selected');
                        $(this).addClass('selected');   
                        /* Fire the onchange event */

                        var raiseChange = $select[0].selectedIndex != $(this).attr('index');
                        /* if ($select[0].selectedIndex != $(this).attr('index') && $select[0].onchange) { 
                        	$select[0].selectedIndex = $(this).attr('index'); 
                        	typeof $select[0].onchange == "function" ? $select[0].onchange() : eval($select[0].onchange); 
                        } */

                        $('li', $ul).show();

                        $select[0].selectedIndex = $(this).attr('index');
                        $(this).parent().hide();
                        $('span:eq(0)', $wrapper).html($(this).html());
                        $ul.hide();
                        $ul.parent().removeClass("opened");

                        if (raiseChange) {
                          $select.trigger('change');
                        }
                        return false;
                });
                /* Set the defalut */
                $('a:eq('+ this.selectedIndex +')', $ul).click();
                $('a:eq('+ this.selectedIndex +')', $ul).parent().hide();
            });/* End select each */
            
            /* Apply the click handler to the Open */
            $('a.jNiceSelectOpen, .jNiceSelectWrapper div').css({'cursor':'pointer'});
            $('a.jNiceSelectOpen, .jNiceSelectWrapper div', this).click(function(){
                                                        if (this.tagName.toUpperCase() == 'DIV')
                                                            var $ul = $(this).siblings('ul');
                                                        else
                                                            var $ul = $(this).parent().siblings('ul');
                                                        if ($ul.css('display')=='none'){hideSelect();} /* Check if box is already open to still allow toggle, but close all other selects */
                                                         $ul.css({zIndex: 100 + (++jNiceSavedZIndex)}); $ul.parent().css({zIndex: 100 + jNiceSavedZIndex});
                                                        if ($ul.css('display')=='none'){
                                                            $ul.parent().addClass("opened");
                                                        $ul.slideToggle("fast");
                                                        }
                                                        else{
                                                            $ul.parent().removeClass("opened");
                                                        $ul.slideToggle("fast");
                                                        }
                                                        
                                                        if ($.browser.opera) {
                                                            var offSet = ($('a.selected', $ul).offset().top - $ul.offset().top);
                                                            $ul.animate({scrollTop: offSet});
                                                        }
                                                        return false;
                                                });
        
        }); /* End Form each */


        /* Hide all open selects */
        var hideSelect = function(){
            $('.jNiceSelectWrapper').removeClass("opened");
//          $('.jNiceSelectWrapper p').hide();
            $('.jNiceSelectWrapper ul:visible').hide();
        };
        
        /* Check for an external click */
        var checkExternalClick = function(event) {
            if ($(event.target).parents('.jNiceSelectWrapper').length === 0) { hideSelect(); }
        };

        /* Apply document listener */
        $(document).mousedown(checkExternalClick);
        
            
        /* Add a new handler for the reset action */
        var jReset = function(f){
            var sel;
            $('.jNiceSelectWrapper select', f).each(function(){sel = (this.selectedIndex<0) ? 0 : this.selectedIndex; $('ul', $(this).parent()).each(function(){$('a:eq('+ sel +')', this).click();});});
            $('a.jNiceCheckbox, a.jNiceRadio', f).removeClass('jNiceChecked');
            $('input:checkbox, input:radio', f).each(function(){if(this.checked){$('a', $(this).parent()).addClass('jNiceChecked');}});
        };
        this.bind('reset',function(){var action = function(){jReset(this);}; window.setTimeout(action, 10);});
        
    };/* End the Plugin */

    /* Automatically apply to any forms with class jNice */
    $(function(){$('form.jNice').jNice();   });

})(jQuery);
                   
