var refineCritLabel 		= "";
var modifyCritLabel 		= "";
var selectionCriteriaDelUrl = "jsp/compubase/selectionModule/Ajax/deleteCriteriaFromSelection.jsp";
var selectionCreateUrl 		= "jsp/compubase/selectionModule/Ajax/createOrUpdateSelection.jsp";
var selectionResetUrl 		= "jsp/compubase/selectionModule/Ajax/deleteAllSelections.jsp";
var selectionUri			= "jsp/compubase/selectionModule/Ajax/selectionContents.jsp";
var selectionShareTabUri	= "jsp/compubase/selectionModule/Ajax/selectionShareContents.jsp";
var selectionTreeUri		= "jsp/compubase/selectionModule/Ajax/selectionTreeContents.jsp";
var selectionStoredUri		= "jsp/compubase/selectionModule/Ajax/storedSelection.jsp";
var selectionProposedUri	= "jsp/compubase/selectionModule/Ajax/proposedSelection.jsp";
var selectionDeleteUri		= "jsp/compubase/selectionModule/Ajax/deleteSelection.jsp";
var staticContentUrl 		= 'img/';
jQuery(document).ready(function(){	
	compubaseSelector.init();	
	refineCritLabel = jQuery("#selection_module_content_criteria_link").html(); 
	modifyCritLabel = jQuery("#selection_module_content_modify_link").html();    
	$("#help1, #help2, #help3").tooltip({
	    track: false,
	    delay: 100,
	    showBody: "::",
	    opacity: 0.9
	  });	
	if(jQuery("#hide-overlay").length){
		jQuery("#overlay").hide();
	}
	if(jQuery("#show-exclusion-block").length){
		jQuery("#overlay").hide();
		jQuery("#exclusion-block").show();
	}
	
});

var compubaseSelector = {
        checkboxToProceed : null,
        lfTarget : null,
        elements: null,

        pushElement: function(id, element) {
            compubaseSelector.elements[id] = element;
        },
        getElement: function(id) {
            if (id in compubaseSelector.elements)
                return compubaseSelector.elements[id];
            else return null;
        },

        centerMe: function(popup) {
            var totalWidth = $(window).width();
            var totalHeight = $(window).height();
            var width = $(popup).width();
            var height = $(popup).height();
            var top = 100 + $(window).scrollTop();
			if($(popup).attr("id") == 'popup-save')
				top=300;
            $(popup).css('left', (totalWidth - width) / 2).css('top', top);
            //$(popup).css('left', (totalWidth - width) / 2).css('top', /*(totalHeight - height) / 2*/100 + $(window).scrollTop());
        },

	init: function() {
                this.checkboxToProceed = new Array();
                this.lfTarget = new Array();
                this.elements = new Array();
                
		this.handlePopup();
                this.handleTable();
		this.handleExtPopup();
                this.handleFiltersPopup();
                this.handleAddRubricPopup();
                $('.show-filters-pu').live('click', this.showFiltersPu);

                compubaseSelector.pushElement('popup-save', new SaveForm('popup-save'));
                $('#save-selection').click(function(e) {
                    compubaseSelector.setInput('filters-popup2-inc', true);
                    compubaseSelector.setInput('filters-popup2-exc', true);
                    $('table#filters-exclusion tr').length ? $('#tab-contents-detail #restricted-label').show() : $('#tab-contents-detail #restricted-label').hide();
                    compubaseSelector.getElement('popup-save').show();
                    $('html, body').animate({scrollTop: $('#popup-save').offset().top-7}, 0);
                });
                
                $('#save-selection-demo').click(function(e) {
                	userDemoPopupAlert();
                });
                
                compubaseSelector.pushElement('popup-stored', new StoredForm('popup-stored', selectionStoredUri, false));
                $('.selector-tabs a[rel=stored]').click(function(e) {
                    compubaseSelector.getElement('popup-stored').show();
                });                
                $('.resume-tabs a[rel=stored]').click(function(e) {
                    compubaseSelector.getElement('popup-stored').show();
                });
				
				$('#selection-delete-confirm-popup #selection-delete-confirm').click(function(e) {
					var currentId =  $('#selection-delete-confirm-popup span#selection-id').text();
					 compubaseSelector.removeSelectionById(selectionDeleteUri, {'idSelection':encodeURIComponent(currentId)});
					$('#selection-delete-confirm-popup').hide();                    
                });
                
                compubaseSelector.pushElement('popup-proposition', new StoredForm('popup-proposition', selectionProposedUri, true));
                $('.selector-tabs a[rel=proposition]').click(function(e) {
                    compubaseSelector.getElement('popup-proposition').show();
                });
                	
                compubaseSelector.pushElement('popup-quotation-save', new SaveForm('popup-quotation-save'));
                $('#selection-quotation').click(function(e) {
                	if($(this).hasClass("visitor")){
                		compubaseSelector.visitorAlert("quotation");
                	}else{
                		compubaseSelector.getElement('popup-quotation-save').show();
                		$('html, body').animate({scrollTop: $('#popup-quotation-save').offset().top-7}, 0);
                	}
                });
                
//                $('#filters-popup-selector .icon-close').click();
//                $('.selector-tabs a[rel=stored]').click();

                columnized = false;                
	},

        itemsDiff: function(str1, str2) {
            var a1 = str1.split(';');
            var a2 = str2.split(';');

            var a=[], diff=[];
            for(var i=0;i<a1.length;i++)
                a[a1[i]]=true;

            for(var i=0;i<a2.length;i++)
                if(a[a2[i]]) delete a[a2[i]];
                
            for(var k in a)
                diff.push(k);
            
            return diff.join(';');
        },
        
        removeRow: function(e) {
        	e.preventDefault();
			var targetId = $(this).closest('table').attr('id');
            $(this).parent().parent().animate({opacity: 'hide'}, 'slow', function() {
                var restriction = $(this).find('input').val();
                targetId = targetId == 'selection-detailed' ? 'filters-popup2-inc' : 'filters-popup2-exc';
                $('#' + targetId + ' .contents-' + restriction + ' :checkbox').attr('checked', '');

                var selection_id = targetId == 'filters-popup2-inc' ? 'selection-selected-values-id ': 'selection-restreted-values-id';
                var old_values = $('#' + selection_id).val();
                $(this).remove();
                compubaseSelector.setInput(targetId, false);
                var diff = restriction;
                var type = targetId == 'filters-popup2-inc' ? 'select' : 'restrict';
                var countId = targetId == 'filters-popup2-inc' ? '#count-select' : '#count-restrict';
                //alert("removeRow \n "+diff);
                 compubaseSelector.updateCount(
                		selectionCriteriaDelUrl,
                		{'type': type, 'itemsCriterias' : encodeURIComponent(diff)},
                		countId
                	);
                var restr= $(this).find('input').val();
                $('#filters-popup2-inc .contents-' + restr + ' :checkbox').attr('checked', '').attr('disabled', '');
            });
            $(this).parent().parent().next().animate({opacity: 'hide'}, 'slow', function() {
                $(this).remove();
            });
            $(this).closest('tr').animate({opacity: 'hide'}, 'slow', function() {
                $(this).remove();
            });          
        },

        showFiltersPu: function(e) {
            e.preventDefault();
            $('#add-filter-type').val('#' + $(e.target).parents('table').attr('id'));
            var targetId = '';
            if ($(e.target).closest('table').attr('id') == 'selection-detailed') {
                targetId = '-inc';
            }else{
                targetId = '-exc';
            }
            $('#filters-popup2' + targetId + ' strong.filter-name').html($(this).parent().children(".name").html());
            $('#filters-popup2'+targetId+' .content .content-wrap > div').css('display', 'none');
            var restriction = /filter-row-(.*)/.exec($(this).parents("[id^=filter-row-]").attr("id"))[1];
            
            if ($('#filters-popup2'+targetId+' .content-wrap .contents-'+ restriction +'').length) {
                if (!$('#filters-popup2'+targetId+' input[name=' + restriction + ']').attr('checked')) {
                    $('#filters-popup2'+targetId+' input[name=' + restriction + ']').attr('checked', 'checked');
                    compubaseSelector.proceedCheckBox($('#filters-popup2'+targetId+' input[name=' + restriction + ']'));
                }
                $('#filters-popup2'+targetId+' .content-wrap .contents-'+ restriction +'').css('display', 'block');
            }
            else {
                var html = '<div class="contents-' + restriction + '">';
                html += '<img src = "'+staticContentUrl+'leftmenu-icon-minus.gif"  class="load-filters expanded" name="'+restriction+'"/><div class="gray-checkbox"></div><input type="checkbox" rel="'+restriction+'" name="'+restriction+'"/><label>loading...</label><ul></ul>';
                html += '</div>';
                $('#filters-popup2'+targetId+' .content .content-wrap').append(html);
                $.ajax({
                            /*FIXME change
                             *           url: 'filters-data2.php'       -> url: 'myfile.jsp'
                             *           data: {'filter' : restriction} -> data: {'nodeCode' : restriction},
                             */
                            url: selectionUri,
                            type: 'get',
                            dataType: 'xml',
                            data: {'filter' : restriction},
                            success: function(data, msg) {
                                compubaseSelector.expandFilterFromXml(data, e);
                                $('#filters-popup2'+targetId+' input[name=' + restriction + ']').siblings('label').text($('root > title', data).text());
                                compubaseSelector.proceedCheckBox($('#filters-popup2'+targetId+' input[name=' + restriction + ']').click());
                            },
                            error: function() {jAlert('Requested filter isn\'t available');$('#filters-popup2'+targetId).hide();},
                            complete: function() {
                            	wait = false;
                            	$('#filters-popup2'+targetId+' .content-wrap .loading').removeClass('loading');
                            	
                            	/*************************************PARSING OF CURRENT MARKED CHECKBOXES******************************************************/
                            		var parentsArray = new Array();
                            		var childrensArray = new Array();
                            		var targetSelection = targetId=='-inc'?'selection-selected-values-id':'selection-restreted-values-id';
                            		var value = $('#'+targetSelection).val().split(';');////change for current exc inc/////////////////////////////////////////
                            		
                            		$(value).each(function(){
                            			if ($('#filters-popup2'+targetId+' .content-wrap input[name="'+this+'"]').length)//if such checkbox exist in popup list
		                            		{
                            					if ($('#filters-popup2'+targetId+' .content-wrap .contents-'+this).length){parentsArray.push(this)} else {childrensArray.push(this)}
		                            		}
                            		});
                            		if (parentsArray.length){
		                            		$(parentsArray).each(function(){
		                            			var currentParrent = this;
		                            			$(childrensArray).each(function(){
		                            				if($('.contents-'+currentParrent).find('input[name="'+this+'"]').length){//if curentparent have checked childes
		                            					if($('.contents-'+currentParrent).find('input[name="'+currentParrent+'"]:checked').length){
		                            						$('.contents-'+currentParrent).find('input[type="checkbox"]').attr('checked', '');//it uncheck default check
		                            						//$('.contents-'+currentParrent).find('input[name="'+currentParrent+'"]').click();//it uncheck default check
		                            					}
		                            					$('.contents-'+currentParrent).find('input[name="'+this+'"]').click();//it check needed items
		                            					
		                            				}
		                            			});
		                            		});
                            		}
                            		
                            		/************************************END PARSING OF CURRENT MARKED CHECKBOXES******************************************************/	
                            	}
                        });
                        
            } //filter not loaded yet .end
            $('#filters-popup2'+targetId+' a.filter-name').attr("rel",restriction);

            compubaseSelector.centerMe($('#filters-popup2' + targetId));
            $('#filters-popup2' + targetId).show();
            $('#overlay').show();
        },
     
        expandFilterFromXml: function (xml, e)
        {
            var targetId = '';
            if ($(e.target).get(0).tagName == 'IMG') {
                if($('#filters-popup2-inc').attr('id') == $(e.target).parents('#filters-popup2-inc').attr('id')) {
                    targetId = '-inc';
                } else if ($('#filters-popup2-exc').attr('id') == $(e.target).parents('#filters-popup2-exc').attr('id')){
                    targetId = '-exc';
                }
                
            } else {
                if ($(e.target).closest('table').attr('id') == 'selection-detailed') {
                    targetId = '-inc';
                }else if ($(e.target).closest('table').attr('id') == 'filters-exclusion') {
                    targetId = '-exc';
                }
            }
            filter = $('id', xml).text();

            $('#filters-popup2'+targetId+' .load-filters[name=' + filter + ']').siblings('ul').hide();
            $('contents > filter', xml).each(function() {
                var html = "";
                html += '<li>';

                var special = $(this).is('.special') ? ' special' : 'rubric-name';
                if($(this).attr('hasChildren') == 'yes')
                {
                        html += '<li class="children">';
                        html += '<img src = "'+staticContentUrl+'leftmenu-icon-plus.gif" align = "left"  class="load-filters" name="' + $(this).attr('id') + '" /><div class="gray-checkbox"></div><input type="checkbox" class="' + special + '" rel="' + $(this).attr('id') + '" name="' + $(this).attr('id') + '" /><label hasChildren = "yes" class="' + special + '">' + $(this).text() + '</label>';
                        html += '<ul></ul>';
                        html += '</li>';
                        $('#filters-popup2'+targetId+' .load-filters[name=' + filter + ']').siblings('ul').append(html);

                }
                else
                {
                        html += '<li class="single">';
                        html += '<input type="checkbox" class="' + special + '" rel="' + $(this).attr('id') + '" name="' + $(this).attr('id') + '"/><label class="' + special + '">' + $(this).text() + '</label>';
                        html += '<ul></ul>';
                        html += '</li>';
                        $('#filters-popup2'+targetId+' .load-filters[name=' + filter + ']').siblings('ul').append(html);
                }
            });

            var cbox = $('#filters-popup2'+targetId+' .load-filters[name=' + filter + ']').siblings(':checkbox');
            var chck = cbox.attr('checked') ? 'checked' : '';
            cbox.siblings('ul').find(':checkbox').not('.special').attr('checked', chck);
            
            $('#filters-popup2'+targetId+' .load-filters[name=' + filter + ']').siblings('ul').slideToggle('fast', compubaseSelector.repaintGrayBoxes);
        },

        updateFiltersInput: function() {},

        proceedCheckBox: function(me) {
            var childUl = me.siblings('ul');
            
            if (me.attr('checked')) {
                childUl.find('img.expanded').click();
                childUl.find('input:checkbox').not('.special').attr('checked', 'checked').attr('disabled', '');
            }

            if (!me.attr('checked')) {
                childUl.find('input:checkbox').attr('checked', '');
            }

            if (me.is('.special')) {
                me.parent().siblings('li').find('input:checkbox').attr('checked', '');
            }
            else {
                me.parent().siblings('li').find('input:checkbox.special').attr('checked', '');
            }

            var checked_count = me.parent().siblings('li').find('input:checked').length + me.attr('checked');
            var not_special_count = me.parent().siblings('li').find('input').not('.special').length + !me.is('.special');
            if (checked_count == not_special_count) {
                me.parent().parent().siblings('input').attr('checked', 'checked').attr('disabled', '');
                me.parent().parent().siblings('div.gray-checkbox').css('display', 'none');
            }
            else if (checked_count == 0) {
                me.parent().parent().siblings('input').attr('checked', '').attr('disabled', '');
                me.parent().parent().siblings('div.gray-checkbox').css('display', 'none');
            }
            else {
                me.parent().parent().siblings('input').attr('checked', 'checked').attr('disabled', 'disabled');
                var cb = me.parent().parent().siblings('input').get(0);
                var top = cb.offsetTop;
                var left = cb.offsetLeft;
                me.parent().parent().siblings('div.gray-checkbox').css('top', top).css('left', left).css('display', 'block');

            }
            var parent_box = me.parent().parent().siblings('input');
            if (parent_box.length) {
                compubaseSelector.updateCbState(parent_box);
            }
        },

        updateCbState: function(box) {

            var checked_count = box.siblings('ul').children('li').find('input:checked').length;
            var not_special_count = box.siblings('ul').children('li').find('input').not('.special').length;
            if (checked_count == not_special_count) {
                box.attr('checked', 'checked').attr('disabled', '');
                box.siblings('div.gray-checkbox').css('display', 'none');
            }
            else if (checked_count == 0) {
                box.attr('checked', '').attr('disabled', '');
                box.siblings('div.gray-checkbox').css('display', 'none');
            }
            else {
                box.attr('checked', 'checked').attr('disabled', 'disabled');
                var cb = box.get(0);
                var top = cb.offsetTop;
                var left = cb.offsetLeft;
                box.siblings('div.gray-checkbox').css('top', top).css('left', left).css('display', 'block');

            }
            
            var parent_box = box.parent().parent().siblings('input');
            if (parent_box.length) {
                compubaseSelector.updateCbState(parent_box);
            }
        },

        repaintGrayBoxes: function() {
            $(this).closest('div').find(':checkbox:disabled').each(function(){
                var cb = $(this).get(0);
                var top = cb.offsetTop;
                var left = cb.offsetLeft;
                $(this).siblings('div.gray-checkbox').css('top', top).css('left', left).css('display', 'block');
            });
        },

        handleFiltersPopup: function(e) {

            var targetId = '';

            $('.filters-popup2 .icon-close').click(function(e) {
                e.preventDefault();
                $('.filters-popup2').hide();
                $('#overlay').hide();
            });

            $('.gray-checkbox').live('click', function(e) {
                var me = $(e.target);
                var input = me.siblings('input');
                me.siblings('input').attr('disabled', '').attr('checked', '');
                compubaseSelector.proceedCheckBox(me.siblings('input'));
                me.hide();
            });

            //checkbox clicks
            $('.filters-popup2 input:checkbox').live('click', function (e) {
                var me = $(e.target);
                var targetId = me.closest('.filters-popup2').attr('id');

//                if (me.siblings('img').length && !me.siblings('ul').children().length) {
//                    compubaseSelector.checkboxToProceed.push(me);
//                    me.siblings('img').click();
//                }
//                else {
                    compubaseSelector.proceedCheckBox(me);
//                }
                
            });

            $('.load-filters').live('click', function(e) {
				
                //e.preventDefault();
                if ($('#filters-popup2'+targetId+' .loading').length) {return;}
                
                lfTarget = e.target;
                if ($(lfTarget).is('.expanded') || $(e.target).siblings('ul').children('li').length)
                {
                    $(lfTarget).siblings('ul').slideToggle('fast', compubaseSelector.repaintGrayBoxes);
                    var cb = $($(lfTarget).siblings('input'))
                    if (cb.is(':checked') && !cb.attr('disabled'))
                        cb.siblings('ul').find(':checkbox').not('.special').attr('checked', 'checked');
                }
                else
                 {
                    var name = $(e.target).attr('name');
                    $(lfTarget).parent().toggleClass('loading');
                    $.ajax({
                        //FIXME: replace this url
                        url: selectionUri,
                        dataType: 'xml',
                        data: {'filter' : name},
                        success: function(data, msg) {
                                    compubaseSelector.expandFilterFromXml(data, e);
                                    if (compubaseSelector.checkboxToProceed.length) {
                                        compubaseSelector.proceedCheckBox(
                                                    compubaseSelector.checkboxToProceed.pop()
                                                );
                                    }
                                 },
                        error: function() {alert('error');},
                        complete: function() {wait = false;$(lfTarget).parent().toggleClass('loading');}
                    });
                }
                $(e.target).toggleClass('expanded');
                if ($(lfTarget).is('.expanded')) {$(e.target).attr('src', staticContentUrl+'leftmenu-icon-minus.gif');}
                else {$(e.target).attr('src', staticContentUrl+'leftmenu-icon-plus.gif');}

            });


            $('.filters-popup2 .save img').click(function(e) {
                e.preventDefault();
                
                var me = $(e.target);
                var targetId = me.closest('.filters-popup2').attr('id');
                compubaseSelector.setInput(targetId, true);
                var restriction = $('#'+targetId+' a.filter-name').attr('rel');
                var destinationId = targetId == 'filters-popup2-inc' ? 'selection-detailed' : 'filters-exclusion';
                //for tree
                //var target = $('#'+destinationId);//+' tr.filter-row-' + restriction + ' > td');
                var target = $('#'+destinationId+' tr.filter-row-' + restriction + ' > td');
                var root = $('#' + targetId + ' .content-wrap div.contents-'+restriction);
                var type = targetId == 'filters-popup2-inc' ? 'select' : 'restrict';
                var selection_id = targetId == 'filters-popup2-inc' ? 'selection-selected-values-id ': 'selection-restreted-values-id';
                var countId = targetId == 'filters-popup2-inc' ? '#count-select' : '#count-restrict';

                var html = '';

               // html = compubaseSelector.getTreeFromAjax(target, type, encodeURIComponent(restriction), encodeURIComponent($('#' + selection_id).val()));
               var tree = compubaseSelector.getTreeHtml(root, 0, false);
                if (tree != '') {
                    if (tree == '<li> - Tout(e)</li>') {
                        $('#'+destinationId+' #filter-row-' + restriction + ' a.modify').text(refineCritLabel);
                        $('#'+destinationId+' #filter-row-' + restriction + ' span.values').text('Tout(e)');
                        html = '';
                        target.parent().hide();
                    }
                    else {
                        html = '<ul class="filter-result">' + tree + '</ul>';
                        target.parent().show();
                        $('#'+destinationId+' #filter-row-' + restriction + ' a.modify').text(modifyCritLabel);
                        $('#'+destinationId+' #filter-row-' + restriction + ' span.values').text('');
                    }
                    
                }
                else {
                    $('#'+destinationId+' #filter-row-' + restriction + ' a.modify').text(refineCritLabel);

                    //removes this filter from the table if all checkboxes are unselected
                    $('#'+destinationId+' #filter-row-' + restriction).remove();
                    $('#'+destinationId+' .filter-row-' + restriction).remove();
                    
                }
                target.html(html);
                //alert(restriction);
               //alert($('#' + selection_id).val());
               compubaseSelector.updateCount(
            		selectionCreateUrl,
                    {'type': type, 'parentNodecode':encodeURIComponent(restriction) ,'itemsCriterias' : encodeURIComponent($('#' + selection_id).val())},
                    countId
                );
                $('#'+targetId).hide();
                $('#overlay').hide();
            });
        },

        getTreeFromAjax: function(_target, type, restriction, items) {
            target = _target;
            $.ajax({
                            /*FIXME params
                             */
                            url: selectionTreeUri,
                            type: 'get',
                            dataType: 'xml',
                            data: {'type': type,'parentNodecode': restriction, 'itemsCriterias': items},
                            success: function(data, msg) {
                                target.parent().show();
                                target.html($('content', data).text());
                                $('#count-total').text($('total', data).text());
                            }
//                            error: function() {},
//                            complete: function() {}
                        });
        },

        fetchIds: function (cbox) {
            cbox = $(cbox);
            if (cbox.attr('checked') && !cbox.attr('disabled')) {
                return cbox.attr('rel') + ';';
            }
            else if (!cbox.attr('checked')) {
                return '';
            }
            else {
                var ids = '';
                var boxes = cbox.siblings('ul').find('> li > :checkbox');
                for (var i = 0; i < boxes.length; i++) {
                    ids += compubaseSelector.fetchIds(boxes[i]);
                }
            }
            return ids;
        },

        setInput: function (targetId, all) {
            var restriction = $('#'+targetId+' a.filter-name').attr('rel');

            var value = '';
            if (all) {
                var cboxes = $('#' + targetId + ' .content-wrap > div input:checked');
                for (var i = 0; i < cboxes.length; i++) {                    
                    value += $(cboxes[i]).attr('rel') + ';';
                }
            }
            else {
                var cboxes = $('#' + targetId + ' .content-wrap > div > :checkbox');
                for (var i = 0; i < cboxes.length; i++) {
                    value += compubaseSelector.fetchIds(cboxes[i]);
                }
            }
            
            var tableId = targetId == 'filters-popup2-inc' ? 'selection-detailed' : 'filters-exclusion';
            var rows = $('#'+tableId + ' tr[id^=filter]');
            for (var i = 0; i < rows.length; i++) {
                var id = /filter-row-(.*)/.exec(rows[i].id)[1];
                if ($('#'+targetId + ' .contents-'+id).length == 0) {
                    value += id + ';';
                }
            }
            
            if (targetId == 'filters-popup2-inc') {
                $('#selection-selected-values-id').val(value);
            }
            else {
                $('#selection-restreted-values-id').val(value);
            }
        },
        
        getTreeHtml: function(root, level, bare) {

            var html = '';
            if ($('>input:checkbox', root).attr('checked')) {
                //html += '<label>' + $('>label', root).text() + '</label>';
                //html += '<ul class="filter-result">';
                if (!$('>input:checkbox', root).attr('disabled')) {
                    html += '<li> - Tout(e)</li>'
                }
                else {
                    var cboxes = $('> ul > li > input:checked', root);
                    for (var i = 0; i < cboxes.length; i++) {
                        html += '<li class="'+$(cboxes[i]).attr('rel')+'"> - ' + $(cboxes[i]).next('label').text();
                        if (!bare)
                            html += ' <img class="remove-filter" src="'+staticContentUrl+'icon-close3-i.gif"/>';
                        if ($(cboxes[i]).parent().is('.children')) {
                            html += '<ul>';
                            html += compubaseSelector.getTreeHtml($(cboxes[i]).parent(), level +1, bare);
                            html += '</ul>';
                        }
                        html += '</li>';
                    }
                }
                //html += '</ul>';
            }
            
            return html;
        },
        
	handlePopup: function() {
		$('#filters-popup-selector .icon-close').click(function(e) {
			e.preventDefault();
			$('#filters-popup-selector').hide();
                        $('#overlay').hide();
		});
		
		$('#filters-popup-selector .toggle-checkboxes').click(function(e) {
			e.preventDefault();
			
			if ($('#filters-popup-selector .content input:checkbox:not(:checked)').length) {
				$('#filters-popup-selector .content input:checkbox').attr("checked","checked");
			} else {
				$('#filters-popup-selector .content input:checkbox').removeAttr("checked");
			}
		});

		$('#filters-popup-selector .show-ext').click(function(e) {
			e.preventDefault();

                        $('#filters-popup-selector input:checkbox').each(function() {
                        if ($(this).is(":checked")) {
                                $('#filters-popup-ext-selector input:checkbox[name='+$(this).attr("name")+']').attr("checked","checked");
                        } else {
                                $('#filters-popup-ext-selector input:checkbox[name='+$(this).attr("name")+']').removeAttr("checked");
                        }
                });

			$('#filters-popup-selector').hide();
			compubaseSelector.showExtPopup();
		});

                $('#filters-popup-selector .save').click(function(e) {
                    e.preventDefault();
                    //$('#selection-detailed').html('');
                    categories = '';
                    var target = $('#selection-detailed');
                    $('#filters-popup-selector input:checkbox').each(function() {
                            var id_ = $(this).parent().parent().attr('class');

                            if (!$(this).is(":checked")) { //remove unchecked
                                if ($('#'+id_, target).length){
                                    $('#'+id_ + ' img.remove-row', target).click();
                                }
                            }

                            if ($(this).is(":checked")) { //append checked
                                var text = $(this).parent().siblings()[0];
                                var id = '';
                                id = ' id="' + id_ + '"';
                                var cat = /^filter-row-(.*)/.exec(id_)[1];
                                categories += cat + ';';

                                if ($('#'+id_, target).length) return true; //do nothing if filter already exists

                                var aHtml = '<tr'+id+'><td><img src="'+staticContentUrl+'icon-close3-i.gif" alt="" class="remove-row"/>';
                                //name="selection-restreted-values[]"
                                    aHtml += '<input type="hidden" value="' + cat + '"/>';
                                    aHtml += '</td><td><span class="name">' + $(text).text() + ' :</span><span class="values">Tout(e) - </span> <a href="#" class="modify orange-bold show-filters-pu">' + refineCritLabel + '</a></td></tr>';
                                    aHtml += '<tr class="' + id_ + '" style="display: none;"><td colspan="2"></td></tr>';
                                    $(target).append(aHtml);
                            }
                    });

                    compubaseSelector.setInput('filters-popup2-inc', false);
                    //alert(categories);
					compubaseSelector.updateCount(
                    	selectionCreateUrl,
                        {'type': 'select', 'itemsCriterias' : encodeURIComponent(/*$('#selection-selected-values-id').val()*/categories)},//:encodeURIComponent($("#selection-favotie-values-id").val())},
                        '#count-select'
                    );
					//alert(categories);     
                    if ($('#selection-detailed tr').length) {
                        $('#exclusion-block').show();
                    }

                    compubaseSelector.setInput('filters-popup2-inc', false);
                    $('#filters-popup-selector').hide();

                    $('#overlay').hide();
                });
				
				$('#selection-new-link').live('click', function(e) {
					$('#overlay').show();
					$('#selection-new-confirm-popup').show();
				});
				
				$('#selection-save-update-confirm-popup #selection-replace, #selection-save-update-confirm-popup #selection-new').live('click', function(e) {
					var formId = $('#selection-save-update-confirm-popup span#selection-form-id').text();
					if(this.id =='selection-new'){
						jQuery("#selection-operation-type").val("save");
					}else{
						jQuery("#selection-operation-type").val("update");						
					}
					compubaseSelector.getElement(formId).submit();
				});
				
				$('#popup-quotation-save .icon-close').click(function(e) {
					e.preventDefault();
					$('#popup-quotation-save').hide();
		            $('#overlay').hide();
				});
				
	},

    showExtPopup : function() {
		var target = $('#filter-type-id').val();
	    if (target.length == 0) {target = '#selection-detailed';}
	    if (target == '#selection-detailed') {$('#filters-popup-ext-selector .reduce-popup').css('visibility', 'visible');}
	    else {$('#filters-popup-ext-selector .reduce-popup').css('visibility', 'hidden');}
	    $('#filters-popup-ext-selector input[type=checkbox]').removeAttr('checked');
	    compubaseSelector.centerMe($('#filters-popup-ext-selector'));
	    $('#filters-popup-ext-selector').show();
	    $('#overlay').show();
	    if (!columnized) {$('#columnize-me').columnize({columns: 3, target: '#columnize-target', buildOnce: true});}
	    columnized = true;
	    $(target + ' tr[id^=filter-row-]').each(function() {
	        $('#filters-popup-ext-selector span.' + $(this).attr('id') + ' input').attr('checked', 'checked');
	    });
    },
        
	handleExtPopup: function() {
        $('#filters-popup-ext-selector .inactive input').attr('disabled', 'disabled');
		$('#filters-popup-ext-selector .icon-close').click(function(e) {
			e.preventDefault();
			$('#msg-hints').hide();
			$('#filters-popup-ext-selector').hide();
            $('#overlay').hide();
		});

		$('#filters-popup-ext-selector .toggle-checkboxes').click(function(e) {
			e.preventDefault();
                        var notChecked = $('#filters-popup-ext-selector .content input:checkbox:not(:checked)').length;
                        var inactive = $('#filters-popup-ext-selector .content .inactive').length;
			if (notChecked - inactive > 0) {
				$('#filters-popup-ext-selector .content input:checkbox').each(function() {
                                    if (!$(this).parent().is('.inactive')) {
                                        $(this).attr("checked","checked");
                                    }
                                });
			} else {
				$('#filters-popup-ext-selector .content input:checkbox').removeAttr("checked");
			}
		});

		$('#filters-popup-ext-selector .set-fav').click(function(e) {
			e.preventDefault();
            //FIXME: replace with the correct URL
          /*  var infoURL 	= 'http://online.compubase.net/';
            var info 		= jQuery("#selection_module_rubric_restricted_info").html();
            var labelLink	= jQuery("#selection_module_rubric_restricted_link_label").html();
            var msg 		= info+'<a href="' + infoURL + '">'+labelLink+'</a>';
            $.alerts.okButton = "OK";
            
            if ($(this).parent().is('.inactive')) {
                jAlert(msg,'Information');
            }
            else {
                $(this).toggleClass("act");
            }*/
		});
		
		$('#filters-popup-ext-selector .set-fav.demo').click(function(e) {
			e.preventDefault();
			/*$(this).removeClass("act");
			userDemoPopupAlert();*/
		});
		
		$('#filters-popup-ext-selector .reduce-popup a').click(function(e) {
			e.preventDefault();

             $('#filters-popup-ext-selector input:checkbox').each(function() {
				if ($(this).is(":checked")) {
					$('#filters-popup-selector input:checkbox[name='+$(this).attr("name")+']').attr("checked","checked");
				} else {
					$('#filters-popup-selector input:checkbox[name='+$(this).attr("name")+']').removeAttr("checked");
				}
			});

            compubaseSelector.centerMe($('#filters-popup-ext-selector'));
			$('#filters-popup-selector').show();
			$('#filters-popup-ext-selector').hide();
			
		});

                $('#filters-popup-ext-selector .save').click(function(e) {
                    //var fps = (e.target == 'sadfsdf') ? $('#1') : $('#2');
                    var target = $('#filter-type-id').val();
                    if (target.length == 0) {target = '#selection-detailed';}
                    var exclusion = (target != '#selection-detailed') ? true : false;
                    var exclValue = '';
                    e.preventDefault();
                    //$(target).html('');
                    categories = '';
                    $('#filters-popup-ext-selector .rubrics-list input:checkbox').each(function() {
                            var id_ = $(this).parent().attr('class');
                            
                            if (!$(this).is(":checked")) { //remove unchecked
                                if ($('#'+id_, target).length){
                                    $('#'+id_ + ' img.remove-row', target).click();
                                }
                            }
                            
                            if ($(this).is(":checked")) { //append checked
                                var text = $(this).siblings(".rubric-name");
                                var id = '';
                                id = ' id="' + id_ + '"';
                                var cat = /^filter-row-(.*)/.exec(id_)[1];
                                categories += cat + ';';

                                if ($('#'+id_, target).length) return true; //do nothing if filter already exists
                                
                                var aHtml = '<tr'+id+'><td><img src="'+staticContentUrl+'icon-close3-i.gif" alt="" class="remove-row"/>';
                                //name="selection-restreted-values[]"
                                    aHtml += '<input type="hidden" value="' + cat + '"/>';
                                    aHtml += '</td><td><span class="name">' + $(text).text() + ' :</span><span class="values">Tout(e)</span> <a href="#" class="modify orange-bold show-filters-pu">'+refineCritLabel+'</a></td></tr>';
                                    aHtml += '<tr class="' + id_ + '" style="display: none;"><td colspan="2"></td></tr>';
                                    $(target).append(aHtml);
                                exclValue += id_ + ';';
                            }
                    });
                    var countId = target == '#selection-detailed' ? '#count-select' : '#count-restrict';
                    var type = target == '#selection-detailed' ? 'select' : 'restrict';
                    //if (exclusion) {$('#selection-restreted-values-id').val(exclValue);}
                    //save favorites to hidden
                    $("#selection-favotie-values-id").val('');
                    $('#filters-popup-ext-selector .rubrics-list .set-fav').each(function() {
                        if ($(this).is(".act")) {
                            var favText = $(this).siblings('.rubric-name');
                            var oldValue = $("#selection-favotie-values-id").val();
                            $("#selection-favotie-values-id").val(oldValue + $(favText).text() + ';');
                        }
                    });

                    var filtersPopup = target == '#selection-detailed' ? 'filters-popup2-inc' : 'filters-popup2-exc';
                    var inputIds = target == '#selection-detailed' ? '#selection-selected-values-id' : '#selection-restreted-values-id';

                    compubaseSelector.setInput(filtersPopup, false);
                    
                  //alert(categories);
                    compubaseSelector.updateCount(
                        	selectionCreateUrl,
                            {'type': type, 'itemsCriterias' : encodeURIComponent(/*$(inputIds).val()*/categories), 'favCodes' : encodeURIComponent($("#selection-favotie-values-id").val())},
                            countId
                        );

                    if ($('#selection-detailed tr').length) {
                        $('#exclusion-block').show();
                    }
                    
                    $('#msg-hints').hide();
                    $('#filters-popup-ext-selector').hide();
                    $('#overlay').hide();
                });

                $('#replace-with-fav').click(function(e) {
                    e.preventDefault();
                    $('#filters-popup-ext-selector .set-fav').each(function() {
                        if ($(this).is('.act')) {
                            $(this).siblings('input').attr('checked', 'checked');
                        }
                        else {
                            $(this).siblings('input').removeAttr('checked');
                        }
                    });
                });
                
                //added by msaad
       		 $('#filters-popup-ext-selector .rubric-name, #filters-popup2-inc .rubric-name').live("click", function(){
       			if (!$(this).parent().hasClass("inactive") ){
					$(this).addClass('checked');
					$(this).siblings(':checkbox').attr('checked', 'checked');
				}
       		});
       		$('#filters-popup-ext-selector .rubric-name.checked, #filters-popup2-inc .rubric-name.checked').live("click", function(){
       			if (!$(this).parent().hasClass("inactive") ){
					$(this).removeClass('checked');
					$(this).siblings(':checkbox').attr('checked', '');
				}
       		});
       		
       		jQuery('.subscription-popup #selection-reset').live("click", function() {				
    			var ref = $(this).closest('div.subscription-popup').attr('id');
    			if(!jQuery("#popup-save").is(":visible"))
    				jQuery("#overlay").hide();
    			$("#"+ref).hide();
    			return false;
    		});
	},

        showAddRubricPopup : function(target) {
            $('#filter-type-id').val(target);            
                        
             compubaseSelector.centerMe($('#popup-add-rubric'));            
             $('#popup-add-rubric').show();
           // compubaseSelector.centerMe($('#filters-popup-ext-selector'));
            //$('#filters-popup-ext-selector').show();
            
            $('#overlay').show();
        },
        
        handleAddRubricPopup: function() {
            $('#popup-add-rubric .icon-close').click(function(e) {
                e.preventDefault();
                $('#popup-add-rubric input').val('');
                $('#popup-add-rubric').hide();
                $('#overlay').hide();
            });

            $('#popup-add-rubric .save').click(function(e) {            	
                e.preventDefault();                
                if ($('#popup-add-rubric input[type=radio]:checked').val() == '3'
                        && !$('#popup-add-rubric input[name=agree]').attr('checked')) {
                        jAlert('You must agree.');
                }
                else {
                    $('#popup-add-rubric').hide();
                    $('#overlay').hide();
                   /* if ($('#popup-add-rubric input[type=radio]:checked').val() == '1') {
                        compubaseSelector.showExtPopup();
                    }*/
                    switch ( $('#popup-add-rubric input[type=radio]:checked').val() ){
                    case '1':
                    	compubaseSelector.showExtPopup();
                    	break;
                    case '2':
                    	compubaseSelector.getElement('popup-stored').show();
                    	break;
                    case '3':
                    	compubaseSelector.getElement('popup-proposition').show();
                    	break;
                    default: break;
                    }
                }
            });
            
            $('#popup-add-rubric .focus-border').mouseover(function(e) {
                $(this).css('border-top', '1px solid #B4B9BB').css('border-bottom', '1px solid #B4B9BB');
            });

            $('#popup-add-rubric .focus-border').mouseout(function(e) {
                $(this).css('border-top', '1px solid white').css('border-bottom', '1px solid white');
            });

            $('#popup-add-rubric input[type=radio]').click(function(e) {
                if ($(this).val() == '3') {
                    $('#popup-add-rubric .agreement').show();
                }
                else {
                    $('#popup-add-rubric .agreement').hide();
                }
            });
        },

        handleTable: function() {
            $('#add-rubric').click(function(e) {
                e.preventDefault();
                compubaseSelector.showAddRubricPopup('#selection-detailed');
            });

            $('#add-exclusion').click(function(e) {
                e.preventDefault();
                compubaseSelector.showAddRubricPopup('#filters-exclusion');
            });

            $('.remove-row').live('click', this.removeRow);
            $('.remove-filter').live('click', function(e) {
            	e.preventDefault();
	            var countId = $(this).closest('table').attr('id') == 'selection-detailed' ? '#count-select' : '#count-restrict';
	            var type = $(this).closest('table').attr('id') == 'selection-detailed' ? 'select' : 'restrict';
	            var current=$(this).parent('li').attr('class');
	            if (current==undefined){alert('undefined');return; }
	            var siblings = $(e.target).parent().siblings();
	            $(this).parent().animate({opacity: 'hide'}, 'slow', function() {
	                var fName = $(this).attr('class');
	                var holder = $(this).closest('.filter-result');
	                var restriction = /filter-row-(.*)/.exec($(this).closest('tr').attr('class'))[1];
	                var cbox = $('.filters-popup2 .content-wrap > div.contents-' + restriction + ' input[rel='+fName + ']');
	                cbox.attr('checked', '');
	                cbox.siblings('ul').find('input').attr('checked', '');
	                var targetId = $(this).closest('table').attr('id') == 'selection-detailed' ? 'filters-popup2-inc' : 'filters-popup2-exc';
	
	                var selection_id = $(this).closest('table').attr('id') == 'selection-detailed' ? 'selection-selected-values-id' : 'selection-restreted-values-id';
	                var old_values = $('#' + selection_id).val();
	                var diff = '';
	                diff = current + ';';
	                
	                //alert("unique criteria \n "+diff);                        
	                compubaseSelector.updateCount(selectionCriteriaDelUrl, {'type': type, 'itemsCriterias': encodeURIComponent(diff)}, countId);
	                $(this).remove();
	               // alert($(holder).children('li').length);
	                if (!$(holder).children('li').length) {
	                	var restr= holder.parent().parent().hide().prev().find('input').val();
	                    $('#' + targetId + ' .contents-' + restr + ' :checkbox').attr('checked', '');
	                    holder.closest("tr").animate({opacity: 'hide'}, 'slow', function() {$(this).remove();});
	                    $("#"+holder.closest("tr").attr('class')).animate({opacity: 'hide'}, 'slow', function() {$(this).remove();});
	                }
	            });
	            var parentRemover = function(parentImg){
	                var currentP=$(parentImg).parent('li').attr('class');
	                    if (currentP!=undefined){ 
	                            var siblings = $(parentImg).parent().siblings();
	                            $(parentImg).parent().animate({opacity: 'hide'}, 'slow', function() {
	                                var fName = $(parentImg).attr('class');
	                                var holder = $(parentImg).closest('.filter-result');
	                                var restriction = /filter-row-(.*)/.exec($(parentImg).closest('tr').attr('class'))[1];
	                                var cbox = $('.filters-popup2 .content-wrap > div.contents-' + restriction + ' input[rel='+fName + ']');
	                                cbox.attr('checked', '');
	                                cbox.siblings('ul').find('input').attr('checked', '');
	                                var targetId = $(parentImg).closest('table').attr('id') == 'selection-detailed' ? 'filters-popup2-inc' : 'filters-popup2-exc';
	                                var selection_id = $(parentImg).closest('table').attr('id') == 'selection-detailed' ? 'selection-selected-values-id' : 'selection-restreted-values-id';
	                                $(parentImg).parent().remove();
	                               // alert("rec "+$(holder).children('li').length);
	                                if (!$(holder).children('li').length) {
	                                	var restr= holder.parent().parent().hide().prev().find('input').val();
	                                    $('#' + targetId + ' .contents-' + restr + ' :checkbox').attr('checked', '');
	                                    holder.closest("tr").animate({opacity: 'hide'}, 'slow', function() {$(this).remove();});
	                                    $("#"+holder.closest("tr").attr('class')).animate({opacity: 'hide'}, 'slow', function() {$(this).remove();});
	                                }
	                            });
	                            var siblings = $(parentImg).parent().siblings();
	                            if (siblings.length == 0) {
	                                var parentPar = $(parentImg).parent().parent().siblings('img');
	                                if (parentPar.length) parentRemover(parentPar);		                                
	                                return;
	                            }
			                  }
			                
			            }
		            var siblings = $(this).parent().siblings();
		            
		            if (siblings.length == 0) {
		                var parentCur = $(this).parent().parent().siblings('img');
		                parentRemover(parentCur);
		                return;
		            }            	
                    
            });
            
            $('#remove-all').click(function() {
            	var title 			=jQuery("#cpb_biz_selection_unsaved_alert_title").html();
				var content 		=jQuery("#selection_module_content_criteria_deleteAll_info").html();			
				var ok_Button_label = "OK"; //jQuery("#selection.module.content.criteria.delete.label").html();
				
				jConfirm(content, title,ok_Button_label,function (r) { 
					res = r; 
					if(res){
                        compubaseSelector.updateCount(selectionResetUrl, {'type': 'select'}, '#count-select');
                        $('#count-restrict').text('0');
						$('#selection-detailed').html('');
						$('#filters-exclusion').html('');
						if ($('#selection-detailed tr').length < 1) {
							$('#exclusion-block').hide();
						}
						$('.filters-popup2 .content-wrap').html('');
					}
				});                    
            });

            $('#continue').click(function(e) {
            	var title 			= jQuery("#cpb_biz_selection_unsaved_alert_title").html();
				var content 		= jQuery("#cpb_biz_selection_unsaved_alert_info").html();				
				var ok_Button_label = jQuery("#popup_alert_selection_button_ok").html();
				$.alerts.cancelButton = '&nbsp;Sauvegarder&nbsp;';			
				//to be removed
				jQuery("#selection-action-type").val("useSelection");                	
				$('#selector-tab-selection form').submit();
				/*jConfirm(content, title,ok_Button_label,
					function (r) { 
						res = r; 
						if(res){
							//FIXME: go to page Q
							jQuery("#selection-action-type").val("useSelection");                	
							$('#selector-tab-selection form').submit();
						}
						else {
							//FIXME: go to page M
							compubaseSelector.getElement('popup-save').show();
						}
				});
				*/
            });
            
            $('#continue-update').click(function(e) {
				jQuery("#selection-action-type").val("useSelection");            	
				$('#selector-tab-selection form').submit();
            });

            $('#subscription-demo').click(function(e) {
            	var title 	= jQuery("#cpb_biz_popup_alert_info_title").html();
				var info 	= jQuery("#cpb_biz_subscription_Open_Access_info").html();
				jAlert(info, title);
				return false;
            });
        },

        updateCount: function(url, data, targetId) {
        	var modeSelection = jQuery("#mode-selection-value").val(); 
        	var oldPotentialValue 	= jQuery("#old-potential-AMB").val();
        		$.ajax({
                            url: url,
                            type: 'get',
                            dataType: 'xml',
                            data: data,
                            cache : false,
                            beforeSend : function(){
        						$('#count-total').text('');
        					},
                            success: function(data, msg) {
			        			var errorMessage = $('errorMessage', data).val();
									if(typeof errorMessage != "undefined")
										location.reload();
								
        						var nbCount = ($('count', data).text() < 0)? 0 : $('count', data).text();
                                $(targetId).text(nbCount);                                
                                var total = ($('total', data).text() < 0)? 0 : $('total', data).text();        							
                                $('#count-total').text(total);   
                                $('#author-fname').text($('authorFirstName', data).text());   
                                $('#author-sname').text($('authorSurName', data).text());   
                                $('#date-last-modification').text($('dateLastModification', data).text());   
                                if(modeSelection == "update"){                             	   
                             	   if(typeof oldPotentialValue != "undefined"){
	                             	   var total = $('total', data).text();
	                             	   if(total != oldPotentialValue){
	                             		  $('#save-selection').removeClass('disable-button');
	                             		  $('#save-selection').removeAttr("disabled");	                             		  
	                             	   }
                             	   }
                                }                                
                            }
                            //error: function() {},
                            //complete: function() {}
                        });
        		},
				
				removeSelectionById: function(url, data) {      
					$.ajax({
						url: url,
						type: 'get',
						dataType: 'xml',
						data: data,
						cache : false,
						success: function(data, msg) {		
							if($('.selector-tabs a[rel=stored]').length)
								$('.selector-tabs a[rel=stored]').click();
							if($('.resume-tabs a[rel=stored]').length);
								$('.resume-tabs a[rel=stored]').click();
							
							var errorMessage = $('errorMessage', data).text();							
							if((typeof errorMessage != "undefined") && (errorMessage.length))
								resetPageContent();
							
						}
						//error: function() {},
						//complete: function() {}
					});
        		},
        		
        		visitorAlert: function(contextParam){        			
        			var title =jQuery("#features_popup_alert_header_title").html();
        			var content =jQuery("#features_popup_alert_content_text").html();
        			var isConfirm = jQuery("#features_popup_alert_type_confirm").html();
        			var href = "identification.do?selectionMode="+contextParam
        			var ok_Button_label = jQuery("#features_popup_alert_button_ok").html();
        			
        			if(isConfirm == "false"){
        				jAlert(""+content, ""+title);
        			}else{
        				jConfirm(content, title,ok_Button_label,
        					function (r) { 
        						res = r; 
        						if(res){
        							location.href = href;
        						}
        					});
        			}
        		}
       }

function resetPageContent() {
	var selectionName = jQuery("#selection_module_content_header_name").html();
	$('#header-selection-name').text(selectionName);
	$('#header-selection-name').text();
	$('#count-restrict').text('0');
	$('#selection-detailed').html('');
	$('#filters-exclusion').html('');
	if ($('#selection-detailed tr').length < 1) {
		$('#exclusion-block').hide();
	}
	$('.filters-popup2 .content-wrap').html('');
	if($('#resume-tab').length)
		$('#resume-tab').html('');
}
        
function SaveForm(id) {
    this.id = id;

    $('#'+this.id + ' .icon-close').click(function(e) {
        e.preventDefault();
        $(this).closest('.popup-window').hide();
        $('#overlay').hide();
    });

    $('#save-name .clear').click(function(e) {
        e.preventDefault();
        var id = $(this).closest('.popup-window').attr('id');
        compubaseSelector.getElement(id).clearName();
		if($('#save-name-input').hasClass("field-error-border")){
			$('#save-name-input').removeClass("field-error-border")
		}
    });

    $('#save-tabs .tab').click(function(e) {
        e.preventDefault();
        var id = $(this).closest('.popup-window').attr('id');
        var tab = /^tab-(.*)$/.exec($(this).attr('id'))[1];
        compubaseSelector.getElement(id).switchTab(tab);
    });

    $('#save-add-tag-add').click(function(e) {
        e.preventDefault();
        var id = $(this).closest('.popup-window').attr('id');
        var tag = $(this).siblings('input').val();
        compubaseSelector.getElement(id).addTag(tag);
    });

    $('#save-add-tag-input').keypress(function(event) {
  	  if (event.keyCode == '13') {
  		var id = $(this).closest('.popup-window').attr('id');
        var tag = $(this).val();
        compubaseSelector.getElement(id).addTag(tag);
  	  }
  	});
    
    $('#tags .remove-tag').live('click', function(e) {
        e.preventDefault();
        var id = $(this).closest('.popup-window').attr('id');
        var tag = $(this).parent().attr('rel');
        compubaseSelector.getElement(id).removeTag(tag);
    });

    $('#' + this.id + ' .set-fav').click(function(e) {
        e.preventDefault();
        var id = $(this).closest('.popup-window').attr('id');
        compubaseSelector.getElement(id).toggleFavorite();
    });

    $('#'+this.id+' .save').click(function(e) {
        e.preventDefault();
        var id = $(this).closest('.popup-window').attr('id');
        compubaseSelector.getElement(id).submit();
    });

    $('#'+this.id+' #popup-save-button').click(function(e) {
        e.preventDefault();
        var id = $(this).closest('.popup-window').attr('id');
        jQuery("#selection-action-type").val("saveAndUseSelection");
        
        if($(this).hasClass("demo")){       
        	userDemoPopupAlert();
        }else{
        	if($("#quote-request-type-other").attr('checked')){
    			if($("#quote-request-type-other-text").val().length < 1){
    				var title =jQuery("#cpb_biz_popup_alert_info_title").html();
    				jAlert("Veuillez remplir le champ Autre.", title);
    			}
    		}
        	
	        if($('#save-add-tag-input').val().length>0){			
	        	var tag = $('#save-add-tag-input').val();
	        	compubaseSelector.getElement(id).addTag(tag);
	        }
	        
	        if($(this).hasClass("created")){
				$('#selection-save-update-confirm-popup span#selection-form-id').text(id);			
	        	$('#selection-save-update-confirm-popup').show();
	        	$('html, body').animate({scrollTop: $('#selection-save-update-confirm-popup').offset().top-7}, 0);
	        }else{	        
	        	compubaseSelector.getElement(id).submit();
	        }
        }
    });
    
    $('#'+this.id + ' input, #'+this.id + ' textarea').live('click', function(e) {
        var id = $(this).closest('.popup-window').attr('id');
        compubaseSelector.getElement(id).removeWarnings();
    } );
    
    $('#'+this.id+' #popup-quotation-button').click(function(e) {
        e.preventDefault();
        var id = $(this).closest('.popup-window').attr('id');
        jQuery("#selection-action-type").val("selectionQuoteRequest");
	    compubaseSelector.getElement(id).submit();
	  
    });
}

with (SaveForm) {
    prototype.id ='';
    prototype.tags = [];
    prototype.isfav = false;
    prototype.partageLoaded = false;

    prototype.email_sp = new RegExp(' +|;+|,+', 'g');

    prototype.clearName = function() {
        $('#save-name-input').val('');
    }

    prototype.switchTab = function(tab) {
        $('#' + this.id + ' .tab').removeClass('active');
        $('#' + this.id + ' .tab-contents').hide();

        if (tab == 'partage' && !this.partageLoaded) {
            $('#tab-contents-partage').load(selectionShareTabUri);
            this.partageLoaded = true;
        }
        $('#tab-' + tab ).addClass('active');
        $('#tab-contents-' + tab).show();
    }

    prototype.addTag = function(tag) {
        if (tag == '') return false;
        if (tag.indexOf(';') != -1) {
            jAlert("';' isn't allowed in keywords!");
            return false;
        }
        for (var key in this.tags) {
            if (this.tags[key] == tag) {
                jAlert('Duplicate item');
                return false;
            }
        }
        this.tags.push(tag);
        
        this.repaint();
        $('#save-add-tag-input').val('');
    }

    prototype.removeTag = function(tag) {
        var index = this.tags.indexOf(tag);
        if (index != -1) {
            this.tags.splice(index, 1);
            this.repaint();
        }

    }

    prototype.repaint = function() {
        /* TAGS */
        $('#tags').html('');

        var html = '';
        var tags_string = '';
        for (var key in this.tags) {
            if (key == 'indexOf') continue;
            html += '<div rel="'+this.tags[key]+'"><span>'+this.tags[key]+'</span><img alt="clear" class="remove-tag" src="'+staticContentUrl+'icon-close3-i.gif"/></div>';
            tags_string += this.tags[key] + ';';
        }
        $('#save-add-tag-hidden').val(tags_string);
        if (html != '') {
            $('#tags').html(html);
            $('#tags').parent().show();
        }
        else $('#tags').parent().hide();

        /* FAVORITE */
        if (this.isfav) {
            $('#'+this.id+' .set-fav').addClass('act');
            $('#save-isfav').val('yes');
        }
        else {
            $('#'+this.id+' .set-fav').removeClass('act');
            $('#save-isfav').val('no');
        }

        /* EMAIL */
        if (this.partageLoaded) {
            var email = $('#visibility-email-input').val();
            if(typeof email != "undefined"){
            	email = email.replace(this.email_sp, ";");
            	$('#visibility-email-input').val(email);
            }
        }

        $('#'+this.id+' .volume').text($('#count-total').text());
        $('#selection-volume').val($('#count-total').text());
    }

    prototype.show = function() {
        $('#overlay').show();
        compubaseSelector.centerMe($('#' + this.id));
        $('#' + this.id).show();

        var reg = RegExp('<img[^>]+>', 'gi');
        var details = '';
        var rows = $('#selection-detailed tr');
        for (var i = 0; i < rows.length; i++) {
            var id = $(rows[i]).attr('id');
            if (id != '') {
                id = /^filter-row-(.*)$/.exec(id)[1];
                details += '<ul class="root"><li>' + $('span.name', rows[i]).text() + '<ul>';
                var root = $('#filters-popup2-inc .content-wrap div.contents-'+id);
                //var tree = compubaseSelector.getTreeHtml(root, 0, true);
                var tree = $('#selection-detailed tr.filter-row-' + id + ' > td > ul').html();
                if (tree) {
                    tree = tree.replace(reg, '');
                    details += tree;
                }
                else {details += '<li>- Tout(e)</li>';}
                details += '</ul></li>';
                details += '</ul>';
            }
        }
        $('#tab-contents-detail .selected').html(details);

        var details = '';
        var rows = $('#filters-exclusion tr');
        for (var i = 0; i < rows.length; i++) {

            var id = $(rows[i]).attr('id');
            if (id != '') {
                id = /^filter-row-(.*)$/.exec(id)[1];
                details += '<ul class="root"><li>' + $('span.name', rows[i]).text() + '<ul>';
                var root = $('#filters-popup2-exc .content-wrap div.contents-'+id);
                //var tree = compubaseSelector.getTreeHtml(root, 0, true);
                var tree = $('#filters-exclusion tr.filter-row-' + id + ' > td > ul').html();
                if (tree) {
                    tree = tree.replace(reg, '');
                    details += tree;
                }
                else {details += '<li>- Tout(e)</li>';}
                details += '</ul></li>';
                details += '</ul>';
            }
        }
        $('#tab-contents-detail .restricted').html(details);

        this.repaint();
    }

    prototype.toggleFavorite = function() {
        this.isfav = !this.isfav;
        this.repaint();
    }

    prototype.submit = function() {
        this.repaint();

        if (!this.validate()) {
            return false;
        }
		//jQuery("#selection-action-type").val("saveAndUseSelection");
		/*
		 suffix = $('#visibility-suffix-input').val();
        var reg = new RegExp('\r?\n', 'g');
        suffix = suffix.replace(reg, ';');
        $('#visibility-suffix-input').val(suffix);
		*/		
		
        $('#' + this.id).closest('form').submit();
    }

    prototype.validate = function() {

        var error =false;
        /* TITLE */
        if ($('#save-name-input').val() == '') {
            $('#'+this.id+ ' .ident-check-error.error-name').show();
            $('#save-name-input').css('border-color', 'red');
            error = true;
        }

        if (this.partageLoaded) {
            /* EMAIL */
            if ($('#visibility-email').attr('checked')) {
                var reg = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);


                var raw = $('#visibility-email-input').val();
                var emails = raw.split(';');
                var wrong = '';
                var count = 0;
                for (var i = 0; i < emails.length; i++) {
                    if (emails[i] == '') continue;
                    count++;
                    if (!reg.test(emails[i])) {
                        wrong += emails[i] + '<br/>';
                    }
                }
                if (wrong != '' || !count) {
                    $('#'+this.id+ ' .ident-check-error.error-email .mails').html(wrong);
                    $('#'+this.id+ ' .ident-check-error.error-email').show();
                    $('#visibility-email-input').css('border-color', 'red');

                    error = true;
                    $('#tab-partage').click();
                }
            }

            /* DOMAIN */
            if ($('#visibility-suffix').attr('checked')) {
                var reg = new RegExp(/^(\w+\.?)*\.\w+$/i);

                var domains = $('#visibility-suffix-input').val();
                var domains = domains.split("\n");
                var wrong = '';
                for (var i = 0; i < domains.length; i++) {
                    if (!reg.test(domains[i])) {
                        wrong += domains[i] + '<br/>';
                    }
                }
                if (wrong != '') {
                    $('#'+this.id+ ' .ident-check-error.error-domain .domains').html(wrong);
                    $('#'+this.id+ ' .ident-check-error.error-domain').show();
                    $('#visibility-suffix-input').css('border-color', 'red');

                    error = true;
                    $('#tab-partage').click();
                }
            }
        }

        return !error;
    }

    prototype.removeWarnings = function() {
        $('#'+this.id+ ' .text').css('border-color', '');
        $('#'+this.id+ ' .ident-check-error').hide();
    }
    
}

function StoredForm(id, datasource, readonly) {
    this.id = id;
    this.datasource = datasource;
    this.readonly = readonly;
    
    $('#'+this.id + ' .icon-close').click(function(e) {
        e.preventDefault();
        $(this).closest('.popup-window').hide();
        $('#overlay').hide();
    });
    
    $('#' + this.id + ' .show-filter').live("click", function(e) {
        e.preventDefault();
        var id = $(this).closest('.popup-window').attr('id');
        compubaseSelector.getElement(id).showFilter();
    });

    $('#' + this.id + ' .hide-filter').click(function(e) {
        e.preventDefault();
        var id = $(this).closest('.popup-window').attr('id');
        compubaseSelector.getElement(id).hideFilter();
    });
    
    $('#' + this.id + ' > .wrap > .head > .stared').live("click", function(e) {
        e.preventDefault();
        $(this).toggleClass('act');
        var id = $(this).closest('.popup-window').attr('id');
        compubaseSelector.getElement(id).filterFavorites($(this).is('.act'));
    });

    $('#' + this.id + ' .stored-filter button.green2').click(function(e) {
        e.preventDefault();
        var id = $(this).closest('.popup-window').attr('id');
        compubaseSelector.getElement(id).filterByKeyword($(this).siblings('input').val());
    });

}

with (StoredForm) {
    prototype.id = '';
    prototype.selections = [];
    prototype.selection_events_initialized = false;
    prototype.readonly = false;
    prototype.datasource = '';
    
    prototype.fetchSelections = function() {
    	$('#popup-stored .content .selections .selection').not('#selection-source').remove();
    	$('#popup-stored .head a.stared').remove();
    	$('#popup-stored .head a.show-filte').remove();

        $.ajax({

            url: this.datasource,
            type: 'get',
            dataType: 'xml',
            context: this,
            success: this.proceedSelections,
            cache:false
        });
    }

    prototype.proceedSelections = function(data, msg) {
        var selections = $('selections', data).children('selection');
        for (var i = 0; i < selections.length; i++) {
            var s = $(selections[i]);
            var id = s.attr('id');
            var options = {
                title:      s.children('title').text(),
                isfav:      s.children('favorite').text() == '1',
                count:      parseInt(s.children('count').text()),
                tags:       s.children('tags').text()/*,
                selected:   s.children('selected').text(),
                restricted: s.children('restricted').text()*/
            };
            this.selections[id] = new Selection(id, this);
            this.selections[id].set(options);
            compubaseSelector.pushElement(this.selections[id].getId(), this.selections[id]);
        }
        var fav = $('selections', data).children('header').children('favorite').text();
        var filter = $('selections', data).children('header').children('filter').text();
        $('#popup-stored .head p').after(fav+filter);
    }
    
    prototype.show = function() {
        this.fetchSelections();
        compubaseSelector.centerMe($('#' + this.id));
        $('#overlay').show();
        $('#' + this.id).show();
    }

    prototype.showFilter = function() {
        $('#' + this.id + ' .show-filter').hide();
        $('#' + this.id + ' .stored-filter').show();
    }

    prototype.hideFilter = function() {
        this.filterByKeyword('');
        $('#' + this.id + ' .show-filter').show();
        $('#' + this.id + ' .stored-filter').hide();
    }

    prototype.getId = function() {
        return this.id;
    }

    prototype.filterFavorites = function(filter) {
        for (var key in this.selections) {
            if (key == 'indexOf') continue;
            if (filter && !this.selections[key].isfav)
                this.selections[key].hide();
            else
                this.selections[key].show()
        }
    }

    prototype.filterByKeyword = function(keyword) {
        for (var key in this.selections) {
            if (key == 'indexOf') continue;
            this.selections[key].show();
            continue;
        }
        if (keyword == '') return true;
        for (var key in this.selections) {
            if (key == 'indexOf') continue;
            if (keyword == '') {
                this.selections[key].show();
                continue;
            }
            //alert(this.selections[key].tags.indexOf(keyword));
            if (this.selections[key].title.indexOf(keyword) == -1
                    && this.selections[key].tags.indexOf(keyword) == -1)
            {
                this.selections[key].hide();
            }
        }
    }

}





function Selection(id, parent) {
    this.id = parent.getId() + '-selection-'+id;
    this.parent = parent;
    
    var s = $('#selection-source').clone();
    if (this.parent.readonly) {
        s.find('thead .controls span').remove();
        s.find('thead .title img').remove();
    }
    s.attr('id', this.id);
   // $('thead .count', s).html(this.count);
    var idSelection=this.getId().replace("popup-stored-selection-","");
    $('thead .controls a#selection-modify', s).attr('href', 'restoreSelection.do?idSelection=' + encodeURIComponent(idSelection));
	$('thead .controls a#selection-use', s).attr('href', 'selectionDetailAndResult.do?idSelection=' + encodeURIComponent(idSelection));
    s.appendTo('#'+this.parent.getId()+' .selections');

    if (!this.parent.selection_events_initialized) {
        this.initEvents();
    }
}

with (Selection ) {
    prototype.id = '';
    prototype.parent = null;

    prototype.title = '';
    prototype.isfav = false;
    prototype.ischecked = false;
    prototype.count = 0;
    prototype.hidden = false;
    prototype.tags = '';

    prototype.selected = '';
    prototype.restricted = '';

    prototype.loadSelectedbyAjax = function(){
    	var curId=this.id.replace("popup-stored-selection-","");
		var curContaineer = this.id;
        $.ajax({
            url: selectionStoredUri+'?idSelection='+curId,
            type	: 'get',
            dataType: 'xml',
            cache 	: false,
            success	: function(data){
        	   var selection = $('selections', data).find('#'+curId);
        	   var selected = $(selection).children('selected').text();
        	   var restricted = $(selection).children('restricted').text();
        	   var potential = $(selection).children('count').text();
        	   $("#"+curContaineer).find('span.count').empty().append(potential);
        	   $("#"+curContaineer).find('td.inc').empty().append(selected);
        	   if(restricted.length > 0)
        		   $("#"+curContaineer).find('td.exc').empty().append('<span style="color: red">Sauf</span>').append(restricted);
           }
        });
    }
    
	prototype.loadPotentialbyAjax = function(){
    	var curId=this.id.replace("popup-stored-selection-","");
		var curContaineer = this.id;
        $.ajax({
            url: selectionStoredUri+'?idSelection='+curId,
            type	: 'get',
            dataType: 'xml',
            cache 	: false,
            success	: function(data){ 
				var selection = $('selections', data).find('#'+curId);
        	   var potential = $(selection).children('count').text();
        	   $("#"+curContaineer).find('span.count').empty().append(potential);      	   
           }
        });
    }
	
    prototype.initEvents = function() {
        $('#'+this.parent.getId()+' .selections .minimize').live('click', function(e) {
            var id = $(this).closest('table.selection').attr('id');
            compubaseSelector.getElement(id).minimize();
        });

        $('#'+this.parent.getId()+' .selections thead .title :checkbox').live('click', function(e) {
            var id = $(this).closest('table.selection').attr('id');
            var checked = $(this).attr('checked');
            compubaseSelector.getElement(id).set({ischecked: checked}, true);
        });

        $('#'+this.parent.getId()+' .selections .hide-selection').live('click', function(e) {
            var id = $(this).closest('table.selection').attr('id');
            compubaseSelector.getElement(id).hide();
        });
        
		$('#'+this.parent.getId()+' .selections .remove-selection').live('click', function(e) {
            var id = $(this).closest('table.selection').attr('id');
			var curId=id.replace("popup-stored-selection-","");			
			$('#selection-delete-confirm-popup .selection-name').text($("#"+id +" .label").html());
			$('#selection-delete-confirm-popup #selection-id').text(curId);
			pos = {
					x: $(this).offset().left-310,
					y: $(this).offset().top + 25
				}
			$('#selection-delete-confirm-popup').css({top:pos.y+"px",left:pos.x+"px"}).show();
			//$('#overlay').show();
			//$('#selection-delete-confirm-popup').show();
            //compubaseSelector.getElement(id).hide();
        });
		
		$('#'+this.parent.getId()+' .selections .potential').live('click', function(e) {
            var id = $(this).closest('table.selection').attr('id');
            compubaseSelector.getElement(id).potentialUpdate();
        });
		
        this.parent.selection_events_initialized = true;
    }

    prototype.getId = function() {
        return this.id;
    }
   
    prototype.minimize = function() {

        $('#'+this.id+' tbody').slideToggle(function() {
            if ($(this).css('display') != 'none') $(this).css('display', 'table-row-group');
        });

        if ($('#'+this.id+' thead .minimize').is('.minimized')) {
            $('#'+this.id+' thead .minimize').attr('src', staticContentUrl+'icon-close.gif');
            this.loadSelectedbyAjax();
        }
        else {
            $('#'+this.id+' thead .minimize').attr('src', staticContentUrl+'icon-close-b.gif');
        }
        $('#'+this.id+' thead .minimize').toggleClass('minimized');
    }

    prototype.hide = function() {
        this.hidden = true;
        $('#'+this.id).hide();
        //$('#'+this.id).animate({opacity: 'hide'}, 'fast');
    }

    prototype.show = function() {
        this.hidden = false;
        $('#'+this.id).show();
        //$('#'+this.id).animate({opacity: 'show'}, 'slow');
    }

    prototype.set = function(options, lazy) {

        this.title      = typeof(options.title) == 'undefined'      ? this.title : options.title;
        this.isfav      = typeof(options.isfav) == 'undefined'      ? this.isfav : options.isfav;
        this.ischecked  = typeof(options.ischecked) == 'undefined'  ? this.ischecked : options.ischecked;
        this.count      = typeof(options.count) == 'undefined'      ? this.count : options.count;
        this.tags       = typeof(options.tags) == 'undefined'       ? this.tags : options.tags;
        this.selected   = typeof(options.selected) == 'undefined'   ? this.selected : options.selected;
        this.restricted = typeof(options.restricted) == 'undefined' ? this.restricted : options.restricted;

        if (!lazy) this.repaint();
    }

    prototype.repaint = function() {
        $('#'+this.id+ ' thead .label').html(this.title);
        //
        if (this.isfav)
            $('#'+this.id+' thead .favorite').attr('src', staticContentUrl+'selector-fav.png');
        else
            $('#'+this.id+' thead .favorite').attr('src', staticContentUrl+'selector-fav-inact.png');
        //
        $('#'+this.id+' thead input:checkbox').attr('checked', this.ischecked);
        //
       // $('#'+this.id + ' thead .count').html(this.count);
        //
        $('#'+this.id + ' tbody .inc').html(this.selected);
        //
        if(this.restricted.length >0){
        	html = '<span style="color: red">Sauf</span>' + this.restricted;
        	$('#'+this.id + ' tbody .exc').html(html);
        }
    }
	
	prototype.potentialUpdate = function() {
        
        if ($('#'+this.id+' thead .potential').is('.active')) {
            $('#'+this.id+' thead .potential').attr('src', staticContentUrl+'icone-update-inactive.gif');
			$('#'+this.id+' thead .potential').removeClass('active');
			$('#'+this.id+' thead .potential').toggleClass('inactive');
            this.loadPotentialbyAjax();
        }
		
        /*else {
            $('#'+this.id+' thead .potential').attr('src', staticContentUrl+'icone-update-actif.gif');
        }*/
       
    }

}


function userDemoPopupAlert() {
	var title =jQuery("#features_popup_alert_header_title").html();
	var content =jQuery("#features_popup_alert_content_text").html();
	var isConfirm = jQuery("#features_popup_alert_type_confirm").html();
	var href = "identification.do?selectionMode=save"
	var ok_Button_label = jQuery("#features_popup_alert_button_ok").html();
	
	if(isConfirm == "false"){
		jAlert(""+content, ""+title+"/"+contextParam);
	}else{
		jConfirm(content, title,ok_Button_label,
			function (r) { 
				res = r; 
				if(res){
					location.href = href;
				}
			});
	}
};
