/**
 * Put label values into input fields, and replace password fields
 * Usage: jQuery('.myForm').formFieldHelper();
 */
jQuery.fn.formFieldHelper = function() {
	window.inputValues = [];

	jQuery('input', this).each(function(n, input) {
		input = jQuery(input);
		// Clone password fields (type may not and cannot be changed!)
		if (input.attr('type')=='password') {
			var dummy = input.parent().clone();
			var dummyInput = jQuery('<input type="text" id="'+input.attr('id')+'_dummy" clone="yes"/>');
			input.parent().hide();
			jQuery('input', dummy).replaceWith(dummyInput.val(jQuery('label', input.prev()).html()));
			dummy.insertAfter(input.parent());
		}
		// Text fields
		else {
			if (input.val()=='' && input.attr('type')=='text') {
				input.val(jQuery('label', input.prev()).html());
			}
		}
	});

	// Bind focus and blur events
	jQuery('input', this).each(function(n, input) {
		input = jQuery(input);
		input.focus(function(){
				var me = jQuery(this);

				if (me.attr('type')=='password') {
					return;
				}

				if (!window.inputValues[me.attr('id')]) {
					window.inputValues[me.attr('id')] = jQuery('label', me.prev()).html();
				}

				if (me.attr('clone')=='yes') {
					jQuery('input', me.parent().hide().prev().show()).focus();
				}
				else if (me.val()==window.inputValues[me.attr('id')]) {
					me.val('');
				}
			})

		input.blur(function(){
				var me = jQuery(this);

				if (me.attr('type')=='password' && me.val()=='') {
					me.parent().hide().next().show();
				}
				else {
					if (!window.inputValues[me.attr('id')]) {window.inputValues[me.attr('id')] = jQuery('label', me.prev()).html();}
					if (me.val()=='') {
						me.val( window.inputValues[me.attr('id')] );
					}
				}
			});
	});
};


/**
 * Show a modal window with help.
 * Currently only usable with div#framenumber_help
 */
jQuery.fn.formHelp = function ()
{
	jQuery('input', this).each(function(n, input){
		input = jQuery(input);
		if (input.prev().attr('class')!='help') {return;}

		var helpFrame = jQuery('#framenumber_help');
		if (helpFrame.length==0) {return;}
		var helpFrameHeight = helpFrame.height();
		helpFrame.hide();

		var box = input.parents('.box-content:eq(0)');
		if (helpFrameHeight > input.parents('form:eq(0)').height()) {
			box.css({height:box.height() + (helpFrameHeight - input.parents('form:eq(0)').height())});
		}


		var closeButton = jQuery('<span class="close"><!-- IE --><\/span>')
			.click(function(){helpFrame.fadeOut('fast');})
			.appendTo(jQuery('h1:first', helpFrame));

		var closeLink = jQuery('<a href="javascript:;" class="close">Close</a>')
			.click(function(){helpFrame.fadeOut('fast');})
			.wrap('<p></p>')
			.appendTo(helpFrame);

		jQuery('label', input.prev().prev()).css({'float':'left'});
		input.prev()
			.appendTo(input.prev().prev())
			.click(function(){
				var parentOffset = box.offset();
				var pos = input.offset();
				helpFrame.css({left:pos.left-parentOffset.left, top:pos.top-parentOffset.top}).fadeIn('fast');
			})
			.show();
	});
};


/**
 * Replace checkboxes with styled checkboxes.
 */
jQuery.fn.replaceCheckboxes = function(){
	jQuery(this).each(function(n, me){
		me = jQuery(me);
		var checkbox = jQuery('<span class="checkbox'+(me.is(':checked') ? ' checked' : '')+'"><!-- IE --><\/span>')

		me.toggleCheckbox = function (e)
		{
			if (jQuery(e.target).attr('for') == me.attr('id') || e.target == checkbox.get(0))
			{
				if (me.is(':checked')) {
					me.removeAttr('checked');
					checkbox.removeClass('checked');
					return false;
				}

				me.attr('checked', 'checked');
				checkbox.addClass('checked');
				return false;
			}
		}

		checkbox.click(me.toggleCheckbox);
		me.hide();
		jQuery('label[for='+ me.attr('id') +']').click(me.toggleCheckbox).prepend(checkbox);
	});
};


/**
 * Replace radio buttons with styled radio buttons.
 */
jQuery.fn.replaceRadios = function(){
	jQuery(this).each(function(n, me){
		me = jQuery(me);
		var checkbox = jQuery('<span class="checkbox'+(me.is(':checked') ? ' checked' : '')+'"><!-- IE --><\/span>')

		me.toggleCheckbox = function ()
		{
			if (me.is(':selected')) {
				//me.removeAttr('checked');
				//checkbox.removeClass('checked');
				return false;
			}

			// clear all radios in this range
			jQuery('input[name=' + me.attr('name') + ']').each(function() {
				jQuery(this).removeAttr('checked');
				jQuery('.checkbox', jQuery(this).parent()).removeClass('checked');
			});

			me.attr('checked', 'checked');
			checkbox.addClass('checked');
			return false;
		}

		checkbox.click(me.toggleCheckbox);
		me.hide();
		jQuery('label[for='+ me.attr('id') +']').click(me.toggleCheckbox).prepend(checkbox);
	});
};

/**
 * Execute on document.onReady
 */
jQuery(document).ready(function(){
	jQuery('input[type=checkbox]').replaceCheckboxes();
	jQuery('input[type=radio]').replaceRadios();
	jQuery('.w30').formFieldHelper();

        jQuery('.bike-list').each(function() {

            $(this).bind('change', function() {
                var idData = $(this).attr('id').split('-');
                var id = idData[0].substr(4);

                var colorId = 'bike' + id + '-color' + id;
                var colorSelect = $('#' + colorId);

                colorSelect.trigger('empty');

                jQuery.post('/ajax/warranty', {bike: $(this).val()}, function(data) {
                    if (data.length == 1) {
						colorSelect.append(
							jQuery('<option></option>').attr('value', data[0].id).html(data[0].colorname)
						);
                        colorSelect.trigger('select', $('option:first', colorSelect));
                    }
                    else {
                        colorSelect.append('<option value=""></option>');
                        for(i = 0; i < data.length; i ++) {
							colorSelect.append(
								jQuery('<option></option>').attr('value', data[i].id).html(data[i].colorname)
							);
                        }
                    }
                }, 'json');

            });
        });
});
jQuery(window).load(function(){
	jQuery('form').formHelp();
});

