/*
 * Alternate Select Multiple (asmSelect) 1.0.4 beta - jQuery Plugin
 * http://www.ryancramer.com/projects/asmselect/
 * 
 * Copyright (c) 2008 by Ryan Cramer - http://www.ryancramer.com
 * 
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 */

(function($) {

	$.fn.asmSelect = function(customOptions) {

		var options = {

			listType: 'ol',						// Ordered list 'ol', or unordered list 'ul'
			sortable: false, 					// Should the list be sortable?
			highlight: false,					// Use the highlight feature? 
			animate: false,						// Animate the the adding/removing of items in the list?
			addItemTarget: 'bottom',				// Where to place new selected items in list: top or bottom
			hideWhenAdded: false,					// Hide the option when added to the list? works only in FF
			debugMode: false,					// Debug mode keeps original select visible 

			removeLabel: 'Effacer',					// Text used in the "remove" link
			highlightAddedLabel: 'Ajout&eacute;: ',				// Text that precedes highlight of added item
			highlightRemovedLabel: 'Effac&eacute;: ',			// Text that precedes highlight of removed item

			containerClass: 'asmContainer',				// Class for container that wraps this widget
			selectClass: 'asmSelect',				// Class for the newly created <select>
			optionDisabledClass: 'asmOptionDisabled',		// Class for items that are already selected / disabled
			listClass: 'asmList',					// Class for the list ($ol)
			listSortableClass: 'asmListSortable',			// Another class given to the list when it is sortable
			listItemClass: 'asmListItem',				// Class for the <li> list items
			listItemLabelClass: 'asmListItemLabel',			// Class for the label text that appears in list items
			removeClass: 'asmListItemRemove',			// Class given to the "remove" link
			highlightClass: 'asmHighlight'				// Class given to the highlight <span>

			};

		$.extend(options, customOptions); 

		return this.each(function(index) {

			var $original = $(this); 				// the original select multiple
			var $container; 					// a container that is wrapped around our widget
			var $select; 						// the new select we have created
			var $ol; 						// the list that we are manipulating
			var buildingSelect = false; 				// is the new select being constructed right now?
			var ieClick = false;					// in IE, has a click event occurred? ignore if not
			var ignoreOriginalChangeEvent = false;			// originalChangeEvent bypassed when this is true

			function init() {

				// initialize the alternate select multiple

				// this loop ensures uniqueness, in case of existing asmSelects placed by ajax (1.0.3)
				while($("#" + options.containerClass + index).size() > 0) index++; 

				$select = $("<select></select>")
					.addClass(options.selectClass)
					.attr('name', options.selectClass + index)
					.attr('id', options.selectClass + index); 

				$selectRemoved = $("<select></select>"); 

				$ol = $("<" + options.listType + "></" + options.listType + ">")
					.addClass(options.listClass)
					.attr('id', options.listClass + index); 

				$container = $("<div></div>")
					.addClass(options.containerClass) 
					.attr('id', options.containerClass + index); 

				buildSelect();

				$select.change(selectChangeEvent)
					.click(selectClickEvent); 

				$original.change(originalChangeEvent)
					.wrap($container).before($select).before($ol);

				if(options.sortable) makeSortable();

				if($.browser.msie) $ol.css('display', 'inline-block'); 
			}

			function makeSortable() {

				// make any items in the selected list sortable
				// requires jQuery UI sortables, draggables, droppables

				$ol.sortable({
					items: 'li.' + options.listItemClass,
					handle: '.' + options.listItemLabelClass,
					axis: 'y',
					update: function(e, data) {

						var updatedOptionId;

						$(this).children("li").each(function(n) {

							$option = $('#' + $(this).attr('rel')); 

							if($(this).is(".ui-sortable-helper")) {
								updatedOptionId = $option.attr('id'); 
								return;
							}

							$original.append($option); 
						}); 

						if(updatedOptionId) triggerOriginalChange(updatedOptionId, 'sort'); 
					}

				}).addClass(options.listSortableClass); 
			}

			function selectChangeEvent(e) {
				
				// an item has been selected on the regular select we created
				// check to make sure it's not an IE screwup, and add it to the list

				if($.browser.msie && $.browser.version < 7 && !ieClick) return;
				var id = $(this).children("option:selected").slice(0,1).attr('rel'); 
				addListItem(id); 	
				ieClick = false; 
				triggerOriginalChange(id, 'add'); // for use by user-defined callbacks
			}

			function selectClickEvent() {

				// IE6 lets you scroll around in a select without it being pulled down
				// making sure a click preceded the change() event reduces the chance
				// if unintended items being added. there may be a better solution?

				ieClick = true; 
			}

			function originalChangeEvent(e) {

				// select or option change event manually triggered
				// on the original <select multiple>, so rebuild ours

				if(ignoreOriginalChangeEvent) {
					ignoreOriginalChangeEvent = false; 
					return; 
				}

				$select.empty();
				$ol.empty();
				buildSelect();

				// opera has an issue where it needs a force redraw, otherwise
				// the items won't appear until something else forces a redraw
				if($.browser.opera) $ol.hide().fadeIn("fast");
			}

			function buildSelect() {

				// build or rebuild the new select that the user
				// will select items from

				buildingSelect = true; 

				// add a first option to be the home option / default selectLabel
				$select.prepend("<option>" + $original.attr('title') + "</option>"); 

				$original.children("option").each(function(n) {

					var $t = $(this); 
					var id; 

					if(!$t.attr('id')) $t.attr('id', 'asm' + index + 'option' + n); 
					id = $t.attr('id'); 

					if($t.is(":selected")) {
						addListItem(id); 
						addSelectOption(id, true); 						
					} else {
						addSelectOption(id); 
					}
				});

				if(!options.debugMode) $original.hide(); // IE6 requires this on every buildSelect()
				selectFirstItem();
				buildingSelect = false; 
			}

			function addSelectOption(optionId, disabled) {

				// add an <option> to the <select>
				// used only by buildSelect()

				if(disabled == undefined) var disabled = false; 

				var $O = $('#' + optionId); 
				var $option = $("<option>" + $O.text() + "</option>")
					.val($O.val())
					.attr('rel', optionId);

				if(disabled) disableSelectOption($option); 

				$select.append($option); 
			}

			function selectFirstItem() {

				// select the firm item from the regular select that we created

				$select.children(":eq(0)").attr("selected", true); 
			}

			function disableSelectOption($option) {

				// make an option disabled, indicating that it's already been selected
				// because safari is the only browser that makes disabled items look 'disabled'
				// we apply a class that reproduces the disabled look in other browsers

				$option.addClass(options.optionDisabledClass)
					.attr("selected", false)
					.attr("disabled", true);

				if(options.hideWhenAdded) $option.hide();
				if($.browser.msie) $select.hide().show(); // this forces IE to update display
			}

			function enableSelectOption($option) {

				// given an already disabled select option, enable it

				$option.removeClass(options.optionDisabledClass)
					.attr("disabled", false);

				if(options.hideWhenAdded) $option.show();
				if($.browser.msie) $select.hide().show(); // this forces IE to update display
			}

			function addListItem(optionId) {

				// add a new item to the html list
var test=new Array();
test['papOpt0']='';
function genChkBox(l,g,n,v){
	return '<label>'+l+'</label><input id="'+g+'B'+n+'" name="'+g+'B'+n+'" class="NIV3" type="checkbox" value="'+v+'" />';
}
function genChkBoxLabelDroite(l,g,n,v){
	return '<input id="'+g+'B'+n+'" name="'+g+'B'+n+'" class="NIV3" type="checkbox" value="'+v+'" /><label>'+l+'</label><br/>';
}
function genRadio(l,g,n,v){
	return '<label>'+l+'</label><input id="'+g+'R'+n+'" name="'+g+'R" class="NIV3" type="radio" value="'+v+'" />';
}
function genInpTxt(l,g,n,v){
	return '<label>'+l+'</label><input id="'+g+'T'+n+'" name="'+g+'T'+n+'" class="NIV3" type="text" value="'+v+'" />';
}
function genInpTxtCourt(l,g,n,v){
	return '<label>'+l+'</label><input id="'+g+'T'+n+'" name="'+g+'T'+n+'" class="NIV3 textCourt" type="text" value="'+v+'" />';
}
function genTextArea(l,g,n,v,r,c,m){
	return '<label>'+l+'</label><textarea id="'+g+'A'+n+'" name="'+g+'A'+n+'" class="NIV3" cols="'+c+'" rows="'+r+'" maxlength="'+m+'">'+v+'</textarea>';
}

test['G12O02']=genChkBox('28lb','G12O02','01','1')+genChkBox('32lb','G12O02','02','2');
test['G12O03']=genChkBox('100M','G12O02','01','1')+genChkBox('120M','G12O03','02','2')+genChkBox('140M','G12O03','03','3')+genChkBox('160M','G12O03','04','4')+genChkBox('200M','G12O03','05','5');
test['G12O04']=genChkBox('100M','G12O04','01','1')+genChkBox('120M','G12O04','02','2')+genChkBox('140M','G12O04','03','3')+genChkBox('160M','G12O04','04','4')+genChkBox('200M','G12O04','05','5');
test['G12O05']=genChkBox('100M','G12O05','01','1')+genChkBox('120M','G12O05','02','2')+genChkBox('140M','G12O05','03','3')+genChkBox('160M','G12O05','04','4');
test['G12O06']=genChkBox('140M','G12O06','01','1')+genChkBox('160M','G12O06','02','2')+genChkBox('180M','G12O06','03','3')+genChkBox('200M','G12O06','04','4')+genChkBox('230M','G12O06','05','5');
test['G12O07']=genChkBox('140M','G12O07','01','1')+genChkBox('160M','G12O07','02','2')+genChkBox('180M','G12O07','03','3')+genChkBox('200M','G12O07','04','4')+genChkBox('230M','G12O07','05','5');
test['G12O08']=genChkBox('130M (9pt)','G12O08','01','1')+genChkBox('160M (11 pt)','G12O08','02','2')+genChkBox('200M (13 pt)','G12O08','03','3');
test['G12O09']=genChkBox('200M (12pt)','G12O09','01','1')+genChkBox('260M (16 pt)','G12O09','02','2');
test['G12O10']=genChkBox('130M (9pt)','G12O10','01','1')+genChkBox('160M (11 pt)','G12O10','02','2')+genChkBox('200M (13 pt)','G12O10','03','3');
test['G12O11']=genChkBox('160M (11pt)','G12O11','01','1')+genChkBox('200M (13 pt)','G12O11','02','2');
test['G12O12']=genChkBox('8 pt','G12O12','01','1')+genChkBox('10 pt','G12O12','02','2')+genChkBox('12 pt','G12O12','03','3')+genChkBox('14 pt','G12O12','04','4')+genChkBox('16 pt','G12O12','05','5');
test['G12O13']=genChkBox('8 pt','G12O13','01','1')+genChkBox('10 pt','G12O13','02','2')+genChkBox('12 pt','G12O13','03','3')+genChkBox('14 pt','G12O13','04','4')+genChkBox('16 pt','G12O13','05','5');
test['G12O14']=genChkBox('8 pt','G12O14','01','1')+genChkBox('10 pt','G12O14','02','2')+genChkBox('12 pt','G12O14','03','3')+genChkBox('14 pt','G12O14','04','4');
test['G12O15']=genChkBox('30M','G12O15','01','1')+genChkBox('40M','G12O15','02','2');
test['G12O16']=''
test['G12O17']=genChkBox('Permanent','G12O17','01','1')+genChkBox('Amovible','G12O17','02','2')+genInpTxt('Application sur:','G12O17','03','');
test['G12O18']=genChkBox('Permanent','G12O18','01','1')+genChkBox('Amovible','G12O18','02','2')+genInpTxt('Application sur:','G12O18','03','');
test['G12O19']=genChkBox('Permanent','G12O19','01','1')+genChkBox('Amovible','G12O19','02','2')+genInpTxt('Application sur:','G12O19','03','');
test['G12O20']=genChkBox('Permanent','G12O20','01','1')+genInpTxt('Application sur:','G12O20','02','');
test['G12O21']=genChkBox('Permanent','G12O21','01','1')+genInpTxt('Application sur:','G12O21','02','');
test['G12O22']=genChkBox('Permanent','G12O22','01','1')+genInpTxt('Application sur:','G12O22','02','');
test['G12O23']=genChkBox('Permanent','G12O23','01','1')+genInpTxt('Application sur:','G12O23','02','');
test['G12O24']='';
test['G12O25']='';
test['G12O25']='';
test['G12O26']='';
test['G12O27']='';
test['G12O28']='';
test['G12O29']='';
test['G12O30']='';
test['G12O31']=genInpTxt('Ouverture sur le:','G12O31','01','');
test['G12O32']=genInpTxt('Ouverture sur le:','G12O32','01','');
test['G12O33']=genInpTxt('Ouverture sur le:','G12O33','01','');
test['G12O34']=genInpTxt('Ouverture sur le:','G12O34','01','');
test['G12O35']=genInpTxt('Format:','G12O35','01','');
test['G12O36']='';
test['G13O02']=genChkBox('Recto','G13O02','01','1')+genChkBox('Verso','G13O02','02','2')+genChkBox('avec marges perdues (bleed)','G13O02','03','3');
test['G13O03']=genChkBox('Recto','G13O03','01','1')+genChkBox('Verso','G13O03','02','2')+genChkBox('avec marges perdues (bleed)','G13O03','03','3');
test['G13O04']=genChkBox('Recto','G13O04','01','1')+genChkBox('Verso','G13O04','02','2')+genChkBox('avec marges perdues (bleed)','G13O04','03','3');
test['G13O05']=genChkBox('Recto','G13O05','01','1')+genChkBox('Verso','G13O05','02','2')+genChkBox('avec marges perdues (bleed)','G13O05','03','3');
test['G13O06']=genChkBox('Recto','G13O06','01','1')+genChkBox('Verso','G13O06','02','2')+genChkBox('avec marges perdues (bleed)','G13O06','03','3');
test['G13O07']=genChkBox('Recto','G13O07','01','1')+genChkBox('Verso','G13O07','02','2')+genChkBox('avec marges perdues (bleed)','G13O07','03','3');
test['G13O08']=genChkBox('Recto','G13O08','01','1')+genChkBox('Verso','G13O08','02','2')+genChkBox('avec marges perdues (bleed)','G13O08','03','3');
test['G13O09']=genChkBox('1','G13O09','01','1')+genChkBox('2','G13O09','02','2');
test['ReimpOpt0'] ='<textarea maxlength="300"></textarea>';
test['G17O02'] =genInpTxt('Longueur:','G17O02','01',''); 
test['G17O09'] =genInpTxt('Quantit&eacute; par livret','G17O09','01','');
test['G17O10'] =genInpTxt('Quantit&eacute; par tablette','G17O10','01','');
test['G17O12'] =genRadio('1','G17O12','01','1')+genRadio('2','G17O12','02','2')+genRadio('3','G17O12','03','3')+genRadio('4','G17O12','04','4');
test['G17O13'] =genRadio('1','G17O13','01','1')+genRadio('2','G17O13','02','2')+genRadio('3','G17O13','03','3')+genRadio('4','G17O13','04','4');
test['G17O17'] =genRadio('1','G17O17','01','1')+genRadio('2','G17O17','02','2')+genRadio('3','G17O17','03','3')+genRadio('4','G17O17','04','4')+genInpTxt('couleur d\'encre:','G17O17','05','');
test['G17O20'] =genInpTxt('couleur d\'encre:','G17O20','01','');
test['G17O21'] =genInpTxtCourt('Dimensions Largeur:','G17O21','01','')+genInpTxtCourt(' x Hauteur:','G17O21','02','')+genRadio('po','G17O21','03','po')+genRadio('cm','G17O21','04','cm')+genInpTxt('Couleur','G17O21','05',''); 
test['G17O22'] =genInpTxtCourt('Dimensions Largeur:','G17O22','01','')+genInpTxtCourt(' x Hauteur:','G17O22','02','')+genRadio('po','G17O22','03','po')+genRadio('cm','G17O22','04','cm'); 
test['G17O23'] =genRadio('1','G17O23','01','1')+genRadio('2','G17O23','02','2')+genRadio('3','G17O23','03','3')+genRadio('4','G17O23','04','4');
test['G17O25'] =genInpTxt('quantit&eacute; de kits &agrave; pr&eacute;parer','G17O25','01','');
test['G17O28'] =genRadio('1','G17O28','01','1')+genRadio('2','G17O28','02','2')+genRadio('3','G17O28','03','3')+genRadio('4','G17O28','04','4');
test['G17O38'] =genInpTxt('Longueur','G17O38','01','');
test['G17O39'] =genInpTxt('Longueur','G17O39','01','');
test['G17O41'] =genRadio('1','G17O41','01','1')+genRadio('2','G17O41','02','2')+genRadio('3','G17O41','03','3')+genRadio('4','G17O41','04','4');
test['G17O42'] =genInpTxt('Diam&egrave;tre','G17O42','01','')+genRadio('1','G17O42','02','1')+genRadio('2','G17O42','03','2')+genRadio('3','G17O42','04','3')+genRadio('4','G17O42','05','4');
test['G17O43'] =genInpTxt('Diam&egrave;tre','G17O43','01','');
test['G17O46']=genChkBox('Recto','G17O46','01','1')+genChkBox('Verso','G17O46','02','2');
test['G17O50'] =genInpTxt('Couleur','G17O50','01','');
test['G17O51'] =genInpTxt('Couleur','G17O51','01','');
test['G17O52'] =genInpTxt('Diam&egrave;tre','G17O52','01','')+genRadio('1','G17O52','02','1')+genRadio('2','G17O52','03','2')+genRadio('3','G17O52','04','3')+genRadio('4','G17O52','05','4');
test['G18O01'] =genInpTxt('&nbsp;','G18O01','01','');
test['G18O02'] =genInpTxt('&nbsp;','G18O02','01','');
test['G18O03'] =genInpTxt('&nbsp;','G18O03','01','');
test['G18O05'] =genInpTxt('&nbsp;','G18O05','01','');
test['G18O06'] =genInpTxt('&nbsp;','G18O06','01','');
test['G19O03'] =genTextArea('Adresse:','G19O03','01','','5','40','300');
test['G19O04'] =genInpTxtCourt('Quantit&eacute;','G19O04','01','');
test['G21O07'] =genChkBoxLabelDroite('Montage et r&eacute;vision des textes (inscrire les d&eacute;tails sous la rubrique NOTES)','G21O07','01','1')+genChkBoxLabelDroite('Faire l\'imposition des pages du document','G21O07','01','1')+genChkBoxLabelDroite('V&eacute;rifier le chevauchement des couleurs «trapping»','G21O07','03','1');

				var $O = $('#' + optionId); 

				if(!$O) return; // this is the first item, selectLabel

				var $removeLink = $("<a></a>")
					.attr("href", "#")
					.addClass(options.removeClass)
					.prepend(options.removeLabel)
					.click(function() { 
						dropListItem($(this).parent('li').attr('rel')); 
						return false; 
					}); 

				var $itemLabel = $("<span></span>")
					.addClass(options.listItemLabelClass)
					.html($O.html());
					
				var $item = $("<li></li>")
					.attr('rel', optionId)
					.addClass(options.listItemClass)					
					.append($itemLabel)					
//					.append('<INPUT type="radio" name="typedonnees" value="Interviews">Interviews')
//					.append('<input name="a" type="checkbox" value="a1" />A <input name="b" type="checkbox" value="b1" />B <input name="c" type="checkbox" value="c1" />C')
					.append(test[optionId])
					.append($removeLink)
					.hide();

				if(!buildingSelect) {
					if($O.is(":selected")) return; // already have it
					$O.attr('selected', true); 
				}

				if(options.addItemTarget == 'top' && !buildingSelect) {
					$ol.prepend($item); 
					if(options.sortable) $original.prepend($O); 
				} else {
					$ol.append($item); 
					if(options.sortable) $original.append($O); 
				}

				addListItemShow($item); 

				disableSelectOption($("[rel=" + optionId + "]", $select));

				if(!buildingSelect) {
					setHighlight($item, options.highlightAddedLabel); 
					selectFirstItem();
					if(options.sortable) $ol.sortable("refresh"); 	
				}

			}

			function addListItemShow($item) {

				// reveal the currently hidden item with optional animation
				// used only by addListItem()

				if(options.animate && !buildingSelect) {
					$item.animate({
						opacity: "show",
						height: "show"
					}, 100, "swing", function() { 
						$item.animate({
							height: "+=2px"
						}, 50, "swing", function() {
							$item.animate({
								height: "-=2px"
							}, 25, "swing"); 
						}); 
					}); 
				} else {
					$item.show();
				}
			}

			function dropListItem(optionId, highlightItem) {

				// remove an item from the html list

				if(highlightItem == undefined) var highlightItem = true; 
				var $O = $('#' + optionId); 

				$O.attr('selected', false); 
				$item = $ol.children("li[rel=" + optionId + "]");

				dropListItemHide($item); 
				enableSelectOption($("[rel=" + optionId + "]", options.removeWhenAdded ? $selectRemoved : $select));

				if(highlightItem) setHighlight($item, options.highlightRemovedLabel); 

				triggerOriginalChange(optionId, 'drop'); 
				
			}

			function dropListItemHide($item) {

				// remove the currently visible item with optional animation
				// used only by dropListItem()

				if(options.animate && !buildingSelect) {

					$prevItem = $item.prev("li");

					$item.animate({
						opacity: "hide",
						height: "hide"
					}, 100, "linear", function() {
						$prevItem.animate({
							height: "-=2px"
						}, 50, "swing", function() {
							$prevItem.animate({
								height: "+=2px"
							}, 100, "swing"); 
						}); 
						$item.remove(); 
					}); 
					
				} else {
					$item.remove(); 
				}
			}

			function setHighlight($item, label) {

				// set the contents of the highlight area that appears
				// directly after the <select> single
				// fade it in quickly, then fade it out

				if(!options.highlight) return; 

				$select.next("#" + options.highlightClass + index).remove();

				var $highlight = $("<span></span>")
					.hide()
					.addClass(options.highlightClass)
					.attr('id', options.highlightClass + index)
					.html(label + $item.children("." + options.listItemLabelClass).slice(0,1).text()); 
					
				$select.after($highlight); 

				$highlight.fadeIn("fast", function() {
					setTimeout(function() { $highlight.fadeOut("slow"); }, 50); 
				}); 
			}

			function triggerOriginalChange(optionId, type) {

				// trigger a change event on the original select multiple
				// so that other scripts can pick them up

				ignoreOriginalChangeEvent = true; 
				$option = $("#" + optionId); 

				$original.trigger('change', [{
					'option': $option,
					'value': $option.val(),
					'id': optionId,
					'item': $ol.children("[rel=" + optionId + "]"),
					'type': type
				}]); 
			}

			init();
		});
	};

})(jQuery); 

