jQuery(document).ready(function(){

	compubaseSelector.init();

        $("#help1, #help2").tooltip({
	    track: false,
	    delay: 100,
	    showBody: "::",
	    opacity: 0.9
	  });
//$(".group input[type='checkbox']").custCheckBox();
});

var compubaseSelector = {
	init: function() {
		this.handlePopup();
                this.handleTable();
		this.handleExtPopup();
                this.handleFiltersPopup();
                this.handleAddRubricPopup();
                $('.show-filters-pu').live('click', this.showFiltersPu);
                $('#save-selection').click(function(e) {
                	jQuery("#selection-action-type").val("saveAndUseSelection");                	
                	$('#filters-form').submit();
                });
                
	},

        removeRow: function(e) {
            e.preventDefault();
            $(this).parent().parent().animate({opacity: 'hide'}, 'slow', function() {
                $(this).remove();
            });
        },

        getFiltersRecursively: function(d) {
            
            if (typeof(d) == 'string') {
                d = $(d);
            }
            var children = d.children();
            var gchildren;
            var html = '<a href="#" class="orange load-filters" fid="'+d.attr('fid')+'">' + d.attr('desc') + '</a><ul>';
            var i = 0;
            for (i=0;i<children.length;i++) {
                    gchildren = children.eq(i).children();
                    if (gchildren.length == 0) {
                        html += '<li><input type="checkbox" name="'+children.eq(i).attr("title")+'"';
                        if (!$('a.filter[rel='+children.eq(i).attr("title")+']').hasClass("inactive") && $('a.filter[rel='+children.eq(i).attr("title")+']').is(":visible")) {html += ' checked="checked"';}
                        html += '/>'+children.eq(i).html()+'</li>';
                    }
            }
            for (i=0;i<children.length;i++) {
                gchildren = children.eq(i).children();
                if (gchildren.length > 0) {
                    html += '<li>' + compubaseSelector.getFiltersRecursively(children.eq(i).children().eq(0)) + '</li>';
                }
            }
            return html + '</ul>';
        },

        showFiltersPu: function(e) {
            e.preventDefault();
            $('#add-filter-type').val('#' + $(e.target).parents('table').attr('id'));
//#filters-data ul[title=restrictionGeographique]
            $('#filters-popup strong.filter-name').html($(this).parent().children(".name").html());
            var html = "";
            var restriction = /filter-row-(.*)/.exec($(this).parents("[id^=filter-row-]").attr("id"))[1];
            html = compubaseSelector.getFiltersRecursively('#filters-data ul[title='+restriction+']');

            $('#filters-popup .content .content-wrap').html(html);
            $('#filters-popup a.filter-name').attr("rel",restriction);

            //$('#filters-popup .content .content-wrap ul ul').css('display', 'none');

            if ($(this).parents("[id^=filter-row-]").hasClass("all-inactive")) {
                    $('#filters-popup .make-active').removeClass("active");
                    $('#filters-popup .make-inactive').addClass("active");
                    $('#filters-popup input:checkbox').attr("disabled","disabled");
                    $('#filters-popup td').addClass("inactive");
            } else {
                    $('#filters-popup .make-active').addClass("active");
                    $('#filters-popup .make-inactive').removeClass("active");
                    $('#filters-popup input:checkbox').removeAttr("disabled");
                    $('#filters-popup td').removeClass("inactive");
            }

            var pos = {
                    x: $(this).offset().left+Math.floor($(this).innerWidth()/2),
                    y: $(this).offset().top-$('#filters-popup').outerHeight()+8
            }

            
            //$('#filters-popup').css({top:pos.y+"px",left:pos.x+"px"}).show();
            //use fixed position instead of floating
            $('#filters-popup').show();
        },

        expandFilterByJson: function (json, fName) {
            filter = fName;
            $('#filters-popup .load-filters[fid=' + filter + ']').siblings('ul').hide();
            $.each(json.children, function(i, v){
                var html = "";
                html += '<li>';
                html += '<a href="#" class="orange load-filters" fid="' + i + '">' + v + '</a>';
                html += '<ul></ul>';
                html += '</li>';
                $('#filters-popup .load-filters[fid=' + filter + ']').siblings('ul').append(html);
            });
            $.each(json.filters, function(i, v){
                var html = "";
                html += '<li>';
                html += '<input type="checkbox" value="' + v + '" name="' + i + '" id="' + i + '-id"/>';
                html += '<label for="' + i + '">' + v + '</label>';
                html += '</li>';
                $('#filters-popup .load-filters[fid=' + filter + ']').siblings('ul').append(html);
            });
            $('#filters-popup .load-filters[fid=' + filter + ']').siblings('ul').slideToggle();
        },
        
        handleFiltersPopup: function() {

            $('.load-filters').live('click', function(e) {
                e.preventDefault();
                lfTarget = e.target;
                if ($(lfTarget).is('.expanded') || $(e.target).siblings('ul').children('li').length) {
                    $(lfTarget).siblings('ul').slideToggle('fast');
                }
                else {
                    var fid = $(e.target).attr('fid');
                    $(e.target).toggleClass('loading');
                    $.ajax({
                        url: 'filters-data2.php',
                        dataType: 'json',
                        data: {'filter' : fid},
                        success: function(data, msg) {
                            $.each(data, function(n, v) {
                                compubaseSelector.expandFilterByJson(v, n);
                            });
                                
                                 },
                        error: function() {alert('error');},
                        complete: function() { $(lfTarget).toggleClass('loading'); }
                    });
                }
                $(e.target).toggleClass('expanded');

            });

            $('#filters-popup .save img').click(function(e) {
                e.preventDefault();

                var inputFilterType = 'filter';
                if ($('#add-filter-type').val() == '#filters-exclusion') {inputFilterType = 'exclusion_filter'}

                var children = $('#filters-popup input:checkbox');
                var filtersSpan = $('#filter-row-'+$('#filters-popup a.filter-name').attr("rel")+' span[class=values]');
                $(filtersSpan).html('');
                for (var i=0;i<children.length;i++) {
                        if (children.eq(i).is(":checked")) {
                            var fName = children.eq(i).attr("name");
                            //alert(fName);
                            var fText = $('input[name='+fName+']').parent();//.siblings()[0];
                            var fHtml = '<span><a href="#" class="filter" rel="' + fName + '">' + $(fText).text() + '</a> -</span>';
                            fHtml += '<input type="hidden" name="' + inputFilterType + '[' + fName + ']" value="' + $(fText).text() + '"/>';
                            $(filtersSpan).append(fHtml);
                            $('a[rel='+fName+']', filtersSpan).css('display', 'inline');
                        }
                }
                for (i=0;i<children.length;i++) {
                        if (children.eq(i).is(":checked")) {
                                $('#filter-row-'+$('#filters-popup a.filter-name').attr("rel")+' a[rel='+children.eq(i).attr("name")+']').removeClass("inactive");
                                $('#filter-row-'+$('#filters-popup a.filter-name').attr("rel")+' a[rel='+children.eq(i).attr("name")+']').parent().show();

                                $('#filters-all #filter-'+$('#filters-popup a.filter-name').attr("rel")+'-'+children.eq(i).attr("name")+' .filterq').removeClass("inactive");
                                $('#filters-all #filter-'+$('#filters-popup a.filter-name').attr("rel")+'-'+children.eq(i).attr("name")).show();
                        } else {
                                $('#filter-row-'+$('#filters-popup a.filter-name').attr("rel")+' a[rel='+children.eq(i).attr("name")+']').parent().hide();
                                $('#filters-all #filter-'+$('#filters-popup a.filter-name').attr("rel")+'-'+children.eq(i).attr("name")).hide();
                        }
                }

                if (!$('#filters-all .filter').parent().filter(":visible").length) {
                        $('#filters-all .nofilters').show();
                } else {
                        $('#filters-all .nofilters').hide();
                }

                if ($('#filters-popup .filters-button.make-inactive').hasClass("active")) {
                        $('#filter-row-'+$('#filters-popup a.filter-name').attr("rel")).addClass("all-inactive");
                        $('#filters-all span[id^=filter-'+$('#filters-popup a.filter-name').attr("rel")+']').addClass("inactive");
                } else {
                        $('#filter-row-'+$('#filters-popup a.filter-name').attr("rel")).removeClass("all-inactive");
                        $('#filters-all span[id^=filter-'+$('#filters-popup a.filter-name').attr("rel")+']').removeClass("inactive");
                }

                if (children.not(":checked").length) {
                        $('#filter-row-'+$('#filters-popup a.filter-name').attr("rel")+' a.enlarge').show();
                        $('#filter-row-'+$('#filters-popup a.filter-name').attr("rel")+' a.reduce').hide();
                } else {
                        $('#filter-row-'+$('#filters-popup a.filter-name').attr("rel")+' a.enlarge').hide();
                        $('#filter-row-'+$('#filters-popup a.filter-name').attr("rel")+' a.reduce').show();
                }

                $('#filters-popup').hide();
                //sendHttpRequest();
        });
        },
        
	handlePopup: function() {
		$('#filters-popup-selector .icon-close').click(function(e) {
			e.preventDefault();
			$('#filters-popup-selector').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('');
                    $('#filters-popup-selector input:checkbox').each(function() {
                            if ($(this).is(":checked")) {
                                var text = $(this).parent().siblings()[0];
                                var id = $(this).parent().parent().attr('class');
                                if (isString(id) && id.length > 1) {id = ' id="' + id + '"';}
                                else {id ='';}
                                var aHtml = '<tr'+id+'><td><img src="img/icon-close3-i.gif" alt="" class="remove-row"/></td><td><span class="name">' + $(text).text() + ' :</span><span class="values"></span> - <a href="#" class="modify orange show-filters-pu">Modifier</a></td></tr>';
                                    $('#selection-detailed').append(aHtml);
                            }
                    });

                    if ($('#selection-detailed tr').length) {
                        $('#exclusion-block').show();
                    }
                    
                    $('#filters-popup-selector').hide();
                });
	},

        showExtPopup : function() {
            var target = $('#filter-type-id').val();
            if (target.length == 0) {target = '#selection-detailed';}
            $('#filters-popup-ext-selector input[type=checkbox]').removeAttr('checked');
            $(target + ' tr[id^=filter-row-]').each(function() {
                $('#filters-popup-ext-selector li.' + $(this).attr('id') + ' input').attr('checked', 'checked');
            });
            $('#filters-popup-ext-selector').show();
        },
        
	handleExtPopup: function() {
                $('#filters-popup-ext-selector .inactive input').attr('disabled', 'disabled');
		$('#filters-popup-ext-selector .icon-close').click(function(e) {
			e.preventDefault();
			$('#filters-popup-ext-selector').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://example.com/';
                        var msg = 'Désolé, cette rubrique de sélection ne fait pas partie de votre abonnement \u2013 <a href="' + infoURL + '">consulter nos offres</a>';
                        if ($(this).parent().is('.inactive')) {
                            jAlert(msg);
                        }
                        else {
                            $(this).toggleClass("act");
                        }
		});

		$('#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");
				}
			});

			$('#filters-popup-selector').show();
			$('#filters-popup-ext-selector').hide();
		});

                $('#filters-popup-ext-selector .save').click(function(e) {
                    var target = $('#filter-type-id').val();
                    if (target.length == 0) {target = '#selection-detailed';}
                    e.preventDefault();
                    $(target).html('');
                    $('#filters-popup-ext-selector input:checkbox').each(function() {
                            if ($(this).is(":checked")) {
                                var text = $(this).siblings(".rubric-name");
                                var id = $(this).parent().attr('class');
                                if (isString(id) && id.length > 1) {id = ' id="' + id + '"';}
                                else {id ='';}
                                var aHtml = '<tr'+id+'><td><img src="img/icon-close3-i.gif" alt="" class="remove-row"/></td><td><span class="name">' + $(text).text() + ' :</span><span class="values"></span> - <a href="#" class="modify orange show-filters-pu">Définir vos critéres</a></td></tr>';
                                    $(target).append(aHtml);
                            }
                    });

                    //save favorites to hidden
                    $("#selection-favotie-values-id").val('');
                    $('#filters-popup-ext-selector .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() + ';');
                        }
                    });

                    if ($('#selection-detailed tr').length) {
                        $('#exclusion-block').show();
                    }
                    
                    $('#filters-popup-ext-selector').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');
                        }
                    });
                });
	},

        showAddRubricPopup : function(target) {
            $('#filter-type-id').val(target);
            $('#popup-add-rubric').show();
        },
        
        handleAddRubricPopup: function() {
            $('#popup-add-rubric .icon-close').click(function(e) {
                e.preventDefault();
                $('#popup-add-rubric input').val('');
                $('#popup-add-rubric').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();
                    if ($('#popup-add-rubric input[type=radio]:checked').val() == '1') {
                        compubaseSelector.showExtPopup();
                    }
                }
            });
            
            $('#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);
            $('span.values a.filter').live('click', function(e) {
                    e.preventDefault();
                    $(this).toggleClass("inactive");
                    $(this).parent().animate({opacity: 'hide'}, 'slow', function() {
                        var fName = $(this).children('a').attr('rel');
                        $(this).siblings('input[name*=' + fName + ']').remove();
                        $(this).remove();
                    });
            });


            $('#remove-all').click(function() {
            	
            	var title =jQuery("#cpb_biz_selection_unsaved_alert_title").html();
				var content ="Voulez-vous tout effacer ?"				
				var ok_Button_label = "Effacer";
				
				jConfirm(content, title,ok_Button_label,
						function (r) { 
					res = r; 
					if(res){
						$('#selection-detailed').html('');
						$('#filters-exclusion').html('');
						if ($('#selection-detailed tr').length < 1) {
							$('#exclusion-block').hide();
						}
					}
				});
                    
            });


            $('#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();
				
				jConfirm(content, title,ok_Button_label,
					function (r) { 
						res = r; 
						if(res){
							jQuery("#selection-action-type").val("useSelection");                	
							$('#filters-form').submit();
						}
				});
				
            	/*var cMsg = cpb.biz.selection.unsaved.info;
                
                $.alerts.okButton = '&nbsp;Continuer&nbsp;';
                $.alerts.cancelButton = '&nbsp;Sauvegarder&nbsp;';
                jConfirm(cMsg, '', function(r) {
                    if (r) {
                        //FIXME: go to page Q
                        $('#selector-tab-selection form').submit();
                    }
                    else {
                        //FIXME: go to page M
                        $('#selector-tab-selection form').submit();
                    }
                });*/
                
            });
        }

}
