/**
 * customDrop javascript for nice Dropdowns with Multiselect
 * 
 * @todo OO version
 * 
 */

/**
 * Avoide text marking
 * 
 */
function nomark(e)
{
	return false;
}
function cnomark()
{
	return true;
}

var selectTimeout = false;

/**
 * Search all select items with rel attribut "customDrop".
 * First call generateDropdown then bind the mousedown event.
 * Use mousedown instead of click because click isn't working in Safari 4
 * 
 */
$(document).ready(function() {
	// Not for IE 6
	if((navigator.appVersion).search(/MSIE 6/) > 0) {
		return true;
	}

	initCustomdrop();
});

function initCustomdrop()
{
	$('select[rel*="customDrop"]').each(function() {
		generateDropdown($(this));

		$('.option').each(function(i) {
			if ($(this).attr('rel') != '' && $(this).attr('rel') != 'undefined') {
				$(this).css(eval('(' + $(this).attr('rel') + ')'));
			}
		});
		$('.options').each(function(i) {
			if ($(this).attr('rel') != '' && $(this).attr('rel') != 'undefined') {
				$(this).css(eval('(' + $(this).attr('rel') + ')'));
			}
		});
		$('.dropdown').each(function(i) {
			if ($(this).attr('value') != '' && $(this).attr('value') != 'undefined') {
				$(this).css(eval('(' + $(this).attr('value') + ')'));
			}
		});
	}).bind('mousedown', function() {
		// first show all select that might be hidden
		$('select').show(0);

		// then blur/hide current select
		$(this).blur();
		$(this).hide(0);

		// toggle visibility of dropdown list. Close all open first
		$('.dropdown:visible').hide(0);

		var strDropSelector = 'drop' + $(this).attr('name').replace(/fe_/, '');

		$('#' + strDropSelector).toggle();

		// avoid text marking
		document.getElementById(strDropSelector).onselectstart = new Function ("return false");
		if (window.sidebar){
			document.getElementById(strDropSelector).onmousedown	= nomark;
			document.getElementById(strDropSelector).onclick		= cnomark;
		}

		// bind event on the body when we leave the drop down and unbind when we enter it
		$('#' + strDropSelector).bind('mouseleave', function() {
			$('body').bind('click', function() {
				$('select').show(0);
				// hide dropdown and unbind click event.
				$('.dropdown').hide(0, function() {
					$('body').unbind('click');
				});
			});
		}).bind('mouseenter', function() {
			$('body').unbind('click');
		});
	});

	/**
	 * Bind event to the opntions. On mousedown we also bind the mouseenter event
	 * to mark more than only one option by moveing the mouse over other entries
	 * un mouseup we unbind mouseenter and trigger the updateFormField funtion with
	 * a Timeout of one sec.
	 */
	$('.option').bind('mousedown', function() {
		$(this).toggleClass('active');
		$('.option').bind('mouseenter', function() {
			$(this).toggleClass('active');
		});
		$('.options').bind('mouseleave', function() {
			$('.option').trigger('mouseup');
		});
	}).bind('mouseup', function() {
		$('.option').unbind('mouseenter');
		$('.options').unbind('mouseleave');

		if(selectTimeout !== false) {
			window.clearTimeout(selectTimeout);
		}

		//get id for one and two row dropdowns.
		if($(this).parent().parent().attr('id') == '') {
			var id = $(this).parent().parent().parent().attr('id');
		} else {
			var id = $(this).parent().parent().attr('id');
		}

		selectTimeout = window.setTimeout("updateFormField('" + id + "')", 1000);
	});
}

/**
 * Update the form field für a customDropdown.
 * Fill frontend field with displayed value and
 * backend field with the backend value.
 * 
 * @param {Object} dropDown
 */
function updateFormField(dropDown)
{
	// setup variables
	var tworow		= false;
	var $dropDown	= $('#' + dropDown);
	var $be_Field	= $('input[name="' + $dropDown.attr('rel') + '"]');
	var $fe_Field	= $('[name="' + $be_Field.attr('rel') + '"]');
	
	// check if we have one or two rows
	if($fe_Field.attr('rel').search(/tworow/) > 0) {
		tworow = true;
	}
	
	var fe_value	= '';
	var be_value	= '';
	
	// get options element
	if (tworow) {
		var $options = $dropDown.children().children();
	} else {
		var $options = $dropDown.children();
	}

	// get all options with class active and generate the front and backend string
	$options.children('.active').each(function(i){
		fe_value += $(this).html() + ', ';
		be_value += $(this).attr('value') + ':';
	});
	
	// write strings after last manipulation
	$fe_Field.children().html(fe_value.replace(/, $/, '').replace(/^$/, '--- ' + translation.GLOBAL.selection + ' ---'));
	$be_Field.val(be_value.replace(/:$/, ''));
}

/**
 * Generate a custom Dropdown list from a given select item.
 * Every option creates one div in the list. If there is the tworow argument
 * found in the rel attribute we create a dropDown with two rows.
 * 
 * @param {Object} $ell
 */
function generateDropdown($ell)
{
	var $parent = $ell.parent();
	var tworow	= false;
	var invert	= false;
	var invertF = 'removeClass';
	var cssMaps	= new Array();
	
	// create left and right element if we have to make two rows
	if(($ell.attr('rel')).search(/tworow/) > 0) {
		tworow = true;
		var leftrow = '<div class="leftrow">';
		var rightrow = '<div class="rightrow">';
		var breakingPoint = Math.ceil(($ell.children().length / 2));
		
		cssMaps['drop'] = '';
		cssMaps['opt'] = '';
		cssMaps['optl'] = '';
	} else {
		//get style changes for dropdown
		if(($ell.attr('rel')).search(/drop:/) > 0) {
			var result = ($ell.attr('rel')).match(/drop:(\{[^;]*\})/);
			cssMaps['drop'] = result[1];
		} else {
			cssMaps['drop'] = '';
		}
		//get style changes for option container options
		if(($ell.attr('rel')).search(/optl:/) > 0) {
			var result = ($ell.attr('rel')).match(/optl:(\{[^;]*\})/);
			cssMaps['optl'] = result[1];
		} else {
			cssMaps['optl'] = '';
		}
		//get style changes for option
		if(($ell.attr('rel')).search(/opt:/) > 0) {
			var result = ($ell.attr('rel')).match(/opt:(\{[^;]*\})/);
			cssMaps['opt'] = result[1];
		} else {
			cssMaps['opt'] = '';
		}
	}
	
	if(($ell.attr('rel')).search(/invert/) > 0) {
		invert	= true;
		invertF = 'addClass';
	}
	
	var dd = '<div class="dropdown" id="drop' + $ell.attr('name').replace(/\[\]/, '') + '" value="' + cssMaps['drop'] + '" rel="' + $ell.attr('name') + '"><div class="options" rel="' + cssMaps['optl'] + '">';
	
	// create options. only options with a value are considert
	$ell.children().each(function(i) {
		var active = '';
		if ($(this).val() != '') {
			if($(this).attr('selected')) {
				active = ' active';
			}
			
			if (tworow) {
				if (i + 1 <= breakingPoint) {
					leftrow = leftrow + '<div class="option' + active + '" rel="' + cssMaps['opt'] + '" value="' + $(this).val() + '">' + $(this).html() + '</div>';
				} else {
					rightrow = rightrow + '<div class="option' + active + '" rel="' + cssMaps['opt'] + '" value="' + $(this).val() + '">' + $(this).html() + '</div>';
				}
			} else {
				dd = dd + '<div class="option' + active + '" rel="' + cssMaps['opt'] + '" value="' + $(this).val() + '">' + $(this).html() + '</div>';
			}
		}
	});
	
	// foot für den dropdown falls er kommen soll.
	if(tworow) {
		dd = dd + leftrow + '</div>' + rightrow + '</div><br clear="all" /></div><div class="foot"><div style="float: left; cursor: pointer;" onclick="$(\'#drop' + $ell.attr('name').replace(/\[\]/, '') + ' > .options > div > .option\').' + invertF + '(\'active\'); updateFormField(\'drop' + $ell.attr('name').replace(/\[\]/, '') + '\');">' + translation.GLOBAL.any + '</div><div style="float: right;"><img src="/gfx/' + translation.GLOBAL.lang + '/btn_select_orange_small.png" border="0" style="cursor: pointer;" onclick="$(\'select\').show(0);$(\'#drop' + $ell.attr('name').replace(/\[\]/, '') + '\').toggle()" /></div></div></div><input type="hidden" name="' + $ell.attr('name') + '" value="" rel="' + 'fe_' + $ell.attr('name').replace(/\[\]/, '') + '" />'
	} else {
		dd = dd + '</div><div class="foot"><div style="float: left; cursor: pointer;" onclick="$(\'#drop' + $ell.attr('name').replace(/\[\]/, '') + ' > .options > .option\').' + invertF + '(\'active\'); updateFormField(\'drop' + $ell.attr('name').replace(/\[\]/, '') + '\');">' + translation.GLOBAL.any + '</div><div style="float: right;"><img src="/gfx/' + translation.GLOBAL.lang + '/btn_select_orange_small.png" border="0" style="cursor: pointer;" onclick="$(\'select\').show(0);$(\'#drop' + $ell.attr('name').replace(/\[\]/, '') + '\').toggle()" /></div></div></div><input type="hidden" name="' + $ell.attr('name') + '" value="" rel="' + 'fe_' + $ell.attr('name').replace(/\[\]/, '') + '" />';
	}

	$ell.attr('name', 'fe_' + $ell.attr('name').replace(/\[\]/, '')).html('<option value="">--- ' + translation.GLOBAL.selection + ' ---</option>').css({
		'width': '222px'
	}).bind('focusin', function() {
		$(this).blur();
	});
	
	$parent.append(dd);
	
	updateFormField('drop' + $ell.attr('name').replace(/fe_/, ''));
}
