/*
 *
 * jqTransform
 * by mathieu vilaplana mvilaplana@dfc-e.com
 * Designer ghyslain armand garmand@dfc-e.com
 *
 *
 * Version 1.0 25.09.08
 * Version 1.1 06.08.09
 * Add event click on Checkbox and Radio
 * Auto calculate the size of a select element
 * Can now, disabled the elements
 * Correct bug in ff if click on select (overflow=hidden)
 * No need any more preloading !!
 * 
 ******************************************** */
 
(function ($) {
    var defaultOptions = { preloadImg: true };
    var jqTransformImgPreloaded = false;

    var jqTransformPreloadHoverFocusImg = function (strImgUrl) {
        //guillemets to remove for ie
        strImgUrl = strImgUrl.replace(/^url\((.*)\)/, '$1').replace(/^\"(.*)\"$/, '$1');
        var imgHover = new Image();
        imgHover.src = strImgUrl.replace(/\.([a-zA-Z]*)$/, '-hover.$1');
        var imgFocus = new Image();
        imgFocus.src = strImgUrl.replace(/\.([a-zA-Z]*)$/, '-focus.$1');
    };


    /***************************
    Labels
    ***************************/
    var jqTransformGetLabel = function (objfield) {
        var selfForm = $(objfield.get(0).form);
        var oLabel = objfield.next();
        if (!oLabel.is('label')) {
            oLabel = objfield.prev();
            if (oLabel.is('label')) {
                var inputname = objfield.attr('id');
                if (inputname) {
                    oLabel = selfForm.find('label[for="' + inputname + '"]');
                }
            }
        }
        if (oLabel.is('label')) { return oLabel.css('cursor', 'pointer'); }
        return false;
    };

    /* Hide all open selects */
    var jqTransformHideSelect = function (oTarget) {
        var ulVisible = $('.jqTransformSelectWrapper ul:visible');
        ulVisible.each(function () {
            var oSelect = $(this).parents(".jqTransformSelectWrapper:first").find("select").get(0);
            //do not hide if click on the label object associated to the select
            if (!(oTarget && oSelect.oLabel && oSelect.oLabel.get(0) == oTarget.get(0))) { $(this).hide(); }
        });
    };
    /* Check for an external click */
    var jqTransformCheckExternalClick = function (event) {
        if ($(event.target).parents('.jqTransformSelectWrapper').length === 0) { jqTransformHideSelect($(event.target)); }
    };

    /* Apply document listener */
    var jqTransformAddDocumentListener = function () {
        $(document).mousedown(jqTransformCheckExternalClick);
    };

    /* Add a new handler for the reset action */
    var jqTransformReset = function (f) {
        var sel;
        $('.jqTransformSelectWrapper select', f).each(function () { sel = (this.selectedIndex < 0) ? 0 : this.selectedIndex; $('ul', $(this).parent()).each(function () { $('a:eq(' + sel + ')', this).click(); }); });
        $('a.jqTransformCheckbox, a.jqTransformRadio', f).removeClass('jqTransformChecked');
        $('input:checkbox, input:radio', f).each(function () { if (this.checked) { $('a', $(this).parent()).addClass('jqTransformChecked'); } });
    };

    /***************************
    Buttons - REMOVED
    ***************************/

    /***************************
    Text Fields - REMOVED
    ***************************/

    /***************************
    Check Boxes  - removed
    ***************************/

    /***************************
    Radio Buttons  - REMOVED
    ***************************/

    /***************************
    TextArea  - REMOVED
    ***************************/

    /***************************
    Select 
    ***************************/
    $.fn.jqTransSelect = function () {
        var objLen = this.length * 10;
        return this.each(function (index) {
            var $select = $(this);
            if ($select.width() > 2) {
                if ($select.hasClass('jqTransformHidden')) { return; }
                if ($select.attr('multiple')) { return; }
                var oLabel = jqTransformGetLabel($select);
                /* First thing we do is Wrap it */
                var $wrapper = $select
					.addClass('jqTransformHidden')
					.wrap('<div class="jqTransformSelectWrapper"></div>')
					.parent()
                    .css({ zIndex: objLen - index });
                if ($select.attr('disabled')) {
                    $wrapper.addClass('selectDisabled');
                }
                /* Now add the html for the select */
                $wrapper.prepend('<span></span><a class="jqTransformSelectOpen"><span></span></a><ul></ul>');
                var $ul = $('ul', $wrapper).css('width', $select.width()).hide();
                /* Now we add the options */
                $('option', this).each(function (i) {
                    var oLi = $('<li><a index="' + i + '">' + $(this).html() + '</a></li>');
                    $ul.append(oLi);
                });
                /* Add click handler to the a */
                var f = 1;
                $ul.find('a').click(function () {
                    $('a.selected', $wrapper).removeClass('selected');
                    $(this).addClass('selected');
                    /* Fire the onchange event */
                    if ($select[0].selectedIndex != $(this).attr('index') && $select[0].onchange) { $select[0].selectedIndex = $(this).attr('index'); $select[0].onchange(); }
                    $select[0].selectedIndex = $(this).attr('index');
                    if (!f == 1) {
                        $($select[0]).blur();
                    }
                    $('span:eq(0)', $wrapper).html($(this).html());
                    $ul.hide();
                    f = 0;
                    return false;
                });
                /* Set the default */
                $('a:eq(' + this.selectedIndex + ')', $ul).click();
                /* activate CLICK events if not set as disabled */
                if (!$select.attr('disabled')) {
                    $('span:first', $wrapper).click(function () { $("a.jqTransformSelectOpen", $wrapper).trigger('click'); });
                    oLabel && oLabel.click(function () { $("a.jqTransformSelectOpen", $wrapper).trigger('click'); });
                    this.oLabel = oLabel;
                    /* Apply the click handler to the Open */
                    var oLinkOpen = $('a.jqTransformSelectOpen', $wrapper).click(function () {
                        //Check if box is already open to still allow toggle, but close all other selects
                        if ($ul.css('display') == 'none') { jqTransformHideSelect(); }
                        if ($select.attr('disabled')) { return false; }
                        $ul.slideToggle('fast', function () {
                            var offSet = ($('a.selected', $ul).offset().top - $ul.offset().top);
                            $ul.animate({ scrollTop: offSet });
                        });
                        return true;
                    });
                }
                // Set the new width
                var iSelectWidth = $select.outerWidth();
                var oSpan = $('span:first', $wrapper);
                var newWidth = (iSelectWidth > oSpan.innerWidth()) ? iSelectWidth : $wrapper.width();
                //$wrapper.css('width',newWidth);
                $ul.css('width', newWidth + 26);
                oSpan.css({ width: iSelectWidth + 4, marginRight: 20 });

                // Calculate the height if necessary, less elements that the default height
                //show the ul to calculate the block, if ul is not displayed li height value is 0
                $ul.css({ display: 'block', visibility: 'hidden' });
                var iSelectHeight = ($('li', $ul).length) * ($('li:first', $ul).height()); //+1 else bug ff
                (iSelectHeight < $ul.height()) && $ul.css({ height: iSelectHeight, 'overflow': 'hidden' }); //hidden else bug with ff
                $ul.css({ display: 'none', visibility: 'visible' });
            };
        });
    };
    $.fn.jqTransform = function (options) {
        var opt = $.extend({}, defaultOptions, options);
        /* each form */
        return this.each(function () {
            var selfForm = $(this);

            if (selfForm.children('.jqTransformSelectOpen').length < 1) {
                selfForm.removeClass('jqtransformdone');
            }
            if (selfForm.hasClass('jqtransformdone')) { return; }

            // Disabled as initally not needed as only styling the SELECT input
            //$('input:submit, input:reset, input[type="button"]', this).jqTransInputButton();			
            //$('input:text, input:password', this).jqTransInputText();			
            //$('input:checkbox', this).jqTransCheckBox();
            //$('input:radio', this).jqTransRadio();
            //$('textarea', this).jqTransTextarea();

            if ($('select', this).jqTransSelect().length > 0) { jqTransformAddDocumentListener(); }
            selfForm.bind('reset', function () { var action = function () { jqTransformReset(this); }; window.setTimeout(action, 10); });

        }); /* End Form each */

    }; /* End the Plugin */

    $.fn.jqTransformUpdateSelect = function (options) {
        return this.each(function () {
            var $sel = $(this);
            $sel.each(function () {
                //alert($(this).width());
                var $wrapper = $(this).parent();
                var $select = $(this);
                var $ul = $sel.prev('ul').empty();
                $('option', $sel).each(function (i) {
                    var oLi = $('<li><a index="' + i + '">' + $(this).html() + '</a></li>');
                    $ul.append(oLi);
                });
                $ul.find('a').click(function () {
                    $('a.selected', $wrapper).removeClass('selected');
                    $(this).addClass('selected');
                    /* Fire the onchange event */
                    if ($select[0].selectedIndex != $(this).attr('index') && $select[0].onchange) { $select[0].selectedIndex = $(this).attr('index'); $select[0].onchange(); }
                    $select[0].selectedIndex = $(this).attr('index');
                    $('span:eq(0)', $wrapper).html($(this).html());
                    $ul.hide();
                    return false;
                });
                var $chk = $('a.selected', $wrapper);
                if ($chk.length < 1) {
                    $ul.find('li:first-child a').addClass('selected');
                }
            });
        }); /* End Form each */
    }; /* End the Updater */

    $.fn.jqTransformEnableSelect = function (options) {
        var opt = $.extend({}, defaultOptions, options);
        var $wrapper = $(this).parent();
        var $select = $(this);
        var $ul = $select.prev('ul');
        var oLabel = jqTransformGetLabel($select);
        //alert(opt.showSel);
        if (opt.showSel) {
            $wrapper.removeClass('selectDisabled');
            $('span:first', $wrapper).unbind('click');
            $('a.jqTransformSelectOpen', $wrapper).unbind('click');
            $('span:first', $wrapper).click(function () { $("a.jqTransformSelectOpen", $wrapper).trigger('click'); });
            oLabel && oLabel.click(function () { $("a.jqTransformSelectOpen", $wrapper).trigger('click'); });
            this.oLabel = oLabel;
            /* Apply the click handler to the Open */
            var oLinkOpen = $('a.jqTransformSelectOpen', $wrapper).click(function () {
                // Check if box is already open to still allow toggle, but close all other selects
                if ($ul.css('display') == 'none') { jqTransformHideSelect(); }
                if ($select.attr('disabled')) { return false; }
                $ul.slideToggle('fast', function () {
                    var offSet = ($('a.selected', $ul).offset().top - $ul.offset().top);
                    $ul.animate({ scrollTop: offSet });
                });
                return false;
            });
            $ul.css({ display: 'block', visibility: 'visible' });

            if ($('li', $ul).length > 7) {
                var iSelectHeight = (7 * $('li:first', $ul).height()); //+1 else bug ff
            } else {
                var iSelectHeight = ($('li', $ul).length) * ($('li:first', $ul).height()); //+1 else bug ff
            }
            $ul.css({ height: iSelectHeight, overflow: 'auto' });
            $ul.css({ display: 'none', visibility: 'visible' });
        } else {
            $wrapper.addClass('selectDisabled');
            $('span:first', $wrapper).unbind('click');
            $('a.jqTransformSelectOpen', $wrapper).unbind('click');
        }
    };

})(jQuery);
				   
