

var seg = {};

seg.Load = function(data){
	seg.data = data;

    var tr = $(".manage-filters .table tbody .segment").clone(true);
    tr.removeClass("hidden");

    $(".manage-filters .table tbody").empty();

    $.each(data.Categories , function(c, filters ){
        $('.filters-form [name="category"]').append( "<option value='"+ c +"'>"+ c +"</option>" );
        $.each(filters , function(k, v ){
            var r = tr.clone(true);

            r.find(".name").html(v.sourcename);
            r.find(".cat").html(c);

            r.find(".edit-segment, .del-segment").attr("data-cat", c);
            r.find(".edit-segment, .del-segment").attr("data-source", k);

            if (ui.data.user.isAdmin != 1) {
                if (v.profileid==0 && v.userid!=ui.data.user.userid) {
                    // global segment belongs to someone else, no edit
                    r.find(".del-segment").remove();
                    r.find(".edit-segment").html("View");
                }
            } else {
                if (v.profileid==0 && v.userid!=0 && v.userid!=ui.data.user.userid) {
                    // global segment belongs to someone else, no edit
                    r.find(".edit-segment").html("View");
                }
            }
            $(".manage-filters .table tbody").append(r);
        });
    });

    $(".manage-segments").on("click", ".add" , function(e){
        e.preventDefault();

        var copy = $(this).parents("tr").first().clone(true);
        seg.NewRow(copy);
        $(".criteriatable").find("tbody").append(copy);
        $(copy).find("value");

        $(".manage-segments .remove").removeClass("disabled");
    });


    $(".manage-segments").on("click", ".remove" , function(e){
        e.preventDefault();
        if($(this).hasClass("disabled")){
            return;
        }

        if($(".criteriatable").find("tbody tr").length > 1){
            $(this).parents("tr").first().remove();
        }
        if($(".criteriatable").find("tbody tr").length == 1){
            $(".manage-segments .remove").addClass("disabled");
        }
    });

    seg.Help();

    seg.filterrow = $(".criteriatable .rowinput").clone(true);
    
    $(".manage-segments ").on("click", ".del-segment" , function(e){
        e.preventDefault();
        var segment = seg.data.Categories[ $(this).attr("data-cat") ][ $(this).attr("data-source") ];
        
        $.ajax({
            url: "app/model/ManangeSegmentFilters.php",
            data : { "conf" : conf, "del" : segment.id, "cat" : $(this).attr("data-cat") },
            type: 'POST',
            success: function(result) {
                var res = ui.ParseJSON(result);
                ui.Callout(res);
                if(res.Status == "Success"){
                    ui.HideWidget(".manage-segments");
                }
            }
        });

    });

    $(".manage-segments ").on("click", ".edit-segment" , function(e){
        e.preventDefault();

        $(".manage-filters, .filters-form").toggle();

        var segment = seg.data.Categories[ $(this).attr("data-cat") ][ $(this).attr("data-source") ];
        
        
        if (segment.profileid==0 && segment.userid!=ui.data.user.userid) {
            if (ui.data.user.isAdmin==1 && segment.userid==0) {
                // ok
            } else {
                // global segment belongs to someone else, no save edit
                $(".save-filter").val("Can't save. This global segment was created by another user");
                $(".save-filter").prop('disabled',true);
            }
        }

        $(".filters-form [name='name']").val(segment.sourcename);
        $(".filters-form [name='category']").val(segment.category);
        $(".filters-form [name='filterid']").val(segment.id);

        if (segment.userid!=0) {
            $(".filters-form [name='segment_access']").attr('checked', true);
        }

        if (segment.profileid==0) {
            $(".filters-form [name='segment_profile']").attr('checked', true);
        }

        /* Yay now decode the query string */        
        if(segment.sourcecondition.indexOf(" AND ") >= 0){
            var rows = segment.sourcecondition.split(" AND ");
            var andor = "AND";
        } else if(segment.sourcecondition.indexOf(" OR ") >= 0){
            var rows = segment.sourcecondition.split(" OR ");
            var andor = "OR";
        } else {
            var rows = [segment.sourcecondition];
            var andor = "AND";
        } 
        
        $(".filterradiooption [name='andor']").removeAttr("checked");
        $(".filterradiooption [name='andor'][value='"+ andor +"']").click();
        $(".criteriatable .rowinput").remove();
        
        $.each(rows, function(k,query){
            if(query == ""){ return; }

            if(query.indexOf(" NOT LIKE ") >= 0){   
                var rsplit = query.split(" NOT LIKE ");
                var field = rsplit[0];
                var condition = "nocontain";

                if(rsplit[1].slice(0,2) !="'%"){
                    var condition = "nostart";
                    var value = rsplit[1].slice(1,-2);
                } else {
                    var value = rsplit[1].slice(2,-2);
                }         
            
            } else if(query.indexOf(" LIKE ") >= 0){ 
                var rsplit = query.split(" LIKE ");
                var field = rsplit[0];
               
                if(rsplit[1].slice(0,2) == "'%"){
                    var condition = "end"; 
                    var value = rsplit[1].slice(2,-1);                   
                }
                if(rsplit[1].slice(-2) == "%'"){
                    if(condition == undefined){
                        var condition = "start";
                        var value = rsplit[1].slice(1,-2); 
                    } else {
                        var condition = "contains";
                        var value = rsplit[1].slice(2,-2); 
                    }
                }
            
            } else if(query.indexOf("!=") >= 0){
                var rsplit = query.split("!=");
                var condition = "isnot";
                var field = rsplit[0];
                var value = rsplit[1].slice(1,-1);

            } else if(query.indexOf("=") >= 0){ 
                var rsplit = query.indexOf("=");
                var condition = "is";
                var field = query.slice(0 , rsplit);
                var value = query.slice( (rsplit + 2),-1);
            } else{
                return;
            }

            var r = seg.filterrow.clone(true);
 
            $(".criteriatable tbody").append(r);

            r.find(".filter-field").attr("id", "field"+ k);
            r.find(".filter-field").attr("name", "field"+ k);
            r.find(".filter-field").val(field.trim());

            r.find(".filter-condition").attr("id", "condition"+ k);
            r.find(".filter-condition").attr("name", "condition"+ k);
            r.find(".filter-condition").val(condition);

            r.find(".filter-cvalue").attr("id", "cvalue"+ k);
            r.find(".filter-cvalue").attr("data-key", k);
            r.find(".filter-cvalue").attr("name", "cvalue"+ k);
            r.find(".filter-cvalue").val(value);
        });
    });

     $(".filters-form [name='segment_access']").on("click", function(e){
        if (ui.data.user.isAdmin!=1) {
            if ($(".filters-form [name='segment_access']").is(":checked") == false && $(".filters-form [name='segment_profile']").is(":checked") == true) {
                $(".filters-form [name='segment_profile']").prop("checked", false);
            }
        }        
    });
    $(".filters-form [name='segment_profile']").on("click", function(e){
        if (ui.data.user.isAdmin!=1) {            
            if ($(".filters-form [name='segment_profile']").is(":checked") == true) {                
                $(".filters-form [name='segment_access']").prop("checked", true);
            }
        }        
    });

    $(".new-segment-btn").on("click", function(e){
        $(".filters-form [name='filterid']").val("");
        $(".filters-form [name='name']").val("");

        if($(".manage-filters").is(":visible")){
            $(".manage-filters, .filters-form").toggle();
        }
    });

    $(".manage-segments-btn").on("click", function(e){ 
        e.preventDefault();
        if($(".manage-filters").is(":hidden")){
            $(".manage-filters, .filters-form").toggle();
        }
    });   

    $(".filters-form").on("click keyup",".filter-cvalue", function(e){
        var field = $("#field" + $(this).attr('data-key') ).val();
        var v = $(this).val(); 

        QBuilderHelpForms( field , e , v +'@'+ $(this).attr('id') +'@'+ field , 'forminput' );           
    });


    $(".filters-form .save-filter").on("click", function(e){
        
        e.preventDefault();
        
        if (ui.data.hl==false) {
            ui.LicenseUpgrade();
            return false;
        }

        var savedata = FormObjectToArray ( $(".manage-segments form[name='segment']") );
        savedata['save'] = 1;
        savedata['conf'] = conf;

        var btn = $(this);
        btn.button('loading');
        
        $.ajax({
            url: "app/model/ManangeSegmentFilters.php",
            data : savedata,
            type: 'POST',
            success: function(result) {
                var res = ui.ParseJSON(result);
                ui.Callout(res);
                if(res.Status == "Success"){
                    ui.HideWidget(".manage-segments");
                }
            }
        });
    });

    $(".manage-segments").on("click", ".addnewcat" , function(){
	    $('.filternewcatagory').toggle();
	});
}

seg.NewRow = function(newr){
    var count = $(".manage-segments .filter-field").length;

    newr.find(".filter-field").attr("name", "field"+ (count + 1) );
    newr.find(".filter-condition").attr("name", "condition"+ (count + 1) );
    newr.find(".filter-cvalue").attr("name", "cvalue"+ (count + 1) );

    newr.find(".filter-field").attr("id", "field"+ (count + 1) );
    newr.find(".filter-condition").attr("id", "condition"+ (count + 1) );
    newr.find(".filter-cvalue").attr("id", "cvalue"+ (count + 1) );

    newr.find(".filter-field").attr("data-key", (count + 1) );
    newr.find(".filter-condition").attr("data-key", (count + 1) );
    newr.find(".filter-cvalue").attr("data-key", (count + 1) );
}

seg.Help = function(){
	$(".help-segments").on("click" , function(){
	    $('.inner-info').toggle();
	});
}