/**
 * Tosi jQuery Value cloner
 *
 * @since 317
 * @require jQuery 1.3
 * @require Tosi Translator
 */

$.fn.tCloner = function( options ) {
	 // fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
    if (!this.length) {
        return this;
    }
	var $inputs = this;
	var O = $.extend({
		tabsSelect: '',
		baseClass: 'showhelp address_icon ',

		cloneSrc: 'page_go.png',
		cloneAlt: t('Clone to empty'),
		cloneClass: 'clone_value',

		copySrc: 'page_paste.png',
		copyAlt: t('Copy value'),
		copyClass: 'copy_value',

		dialogTitle: t('Choose existing value')
	}, options || {});
	var tabsSelect = O.tabsSelect;

	var getValues = function( exclude ){
		var values = [];
		var els = $inputs;
		els.each(function(){
			var V = $(this).val();
			if ( V != '' && 0 > $.inArray( V, values ) ) {
				values.push( V );
			}
		});
		return values;
	};
	var getClone = function() {
		var C = this;
		return $(
			'<img '+
				'src="'+O.cloneSrc+'" '+	
				'class="'+O.baseClass+' '+O.cloneClass+'" '+
				'alt="'+O.cloneAlt+'" '+
				'title="'+O.cloneAlt+'" '+
				'style="display:inline"'+
			'/>'
			);
	};
	var getCopy = function() {
		var C = this;
		return $(
			'<img '+
				'src="'+O.copySrc+'" '+	
				'class="'+O.baseClass+' '+O.copyClass+'" '+
				'alt="'+O.copyAlt+'" '+
				'title="'+O.copyAlt+'" '+
				'style="display:inline"'+
			'/>'
			);
	};

	var C = this;
	$inputs.each(function(i,el){
		var $this = $(this);
		var $clone = getClone().hide().click(function(){
			if ( ! $(this).hasClass( 'disabled' ) && $this.val() != '' ) {
				$inputs.each(function(){
					if ( $(this).val() == '' ) {
						$(this).val( $this.val() ).change();	
					}
				});
			}
		});
		var $copy = getCopy().hide().click(function(){
			var values = getValues( '#'+$this.attr('id') );
			if ( ! $(this).hasClass( 'disabled' ) && $this.val() == '' && values.length > 0 ) {
				var $list = $('<div class="value_list"><ul><li>'+values.join('</li><li>')+'</li></ul></div>');
				$list.dialog({
					draggable: false, resizable: false, modal: true,
					title: O.dialogTitle
				});
				$list.find('li').hover(
					function(){ $(this).addClass('hover');},
					function(){ $(this).removeClass('hover');}
				).click(function(){
					$this.val( $(this).html() ).keyup();
					$list.dialog('close');
				});
				$this.keyup();
			}
		});
		$this.parent()
			.prepend( $clone )
			.prepend( $copy )
		;

		$this.keyup(function(){
				if ( $this.val() == '' ) {
					// Copy from existing
					$clone.hide();
					$copy.show().css('display','inline');
				}
				else {
					// Clone to empty
					$clone.show().css('display','inline');
					$copy.hide();
				}

				if ( getValues().length < 1 ) {
					$( tabsSelect + ' .'+O.copyClass )
						.addClass('disabled').css({opacity: .5});
				} 
				else {
					$( tabsSelect + ' .'+O.copyClass )
						.removeClass('disabled').css({opacity: 1 });
				}
			})
			.change(function(){$(this).keyup();})
			.keyup();
	});
};

/* end */

