var rule_id = 0;

var robots = {
    "All" : { name: "*", description: "", pattern_matching: false },
    // Google bots: http://www.google.com/support/webmasters/bin/answer.py?answer=40364
    "Googlebot" : { name : "Googlebot", description: "crawl pages from web index and news index", pattern_matching : true },
    "Googlebot-Mobile" : { name : "Googlebot-Mobile", description: "crawls pages for mobile index", pattern_matching : true },
    "Googlebot-Image" : { name : "Googlebot-Image", description: "crawls pages for image index", pattern_matching : true },
    "Mediapartners-Google" : { name : "Mediapartners-Google", description: "crawls pages to determine AdSense content", pattern_matching : true },
    "Adsbot-Google" : { name : "Adsbot-Google", description: "crawls pages to measure AdWords landing page quality", pattern_matching : true },
    // Yahoo: http://help.yahoo.com/l/us/yahoo/search/webcrawler/slurp-02.html
    "Slurp" : { name : "Slurp", description: "The URL of a disallowed page might be included in Yahoo! Search as a \"thin\" document with no text content.", pattern_matching : true },
    // MSN
    "msnbot" : { name : "msnbot", description: "", pattern_matching : true },
    "msnbot-media" : { name : "msnbot-media", description: "", pattern_matching : true },
    // Teoma: http://about.ask.com/en/docs/about/webmasters.shtml
    "Teoma" : { name : "Teoma", description: "", pattern_matching : false }    
};

function robot_rule (action, robot, url) {
    this.id      = rule_id;
    this.action = action;
    this.robot   = robot;
    this.url     = url;
    this.has_errors = false;
    rule_id++;
}

var rules = [];

function get_robot_options(r) {
    var opt = "";   
    for (var i in robots) {
        if (r == robots[i].name) {
            opt += '<option value="'+robots[i].name+'" selected="selected" >'+i+'</option>';
        }
        else {
            opt += '<option value="'+robots[i].name+'">'+i+'</option>';
        }
    }
    return opt;
}

function get_rule_html(id, a, r, u) {

    var html = "";
    html += '<tr id="rule_'+id+'">';
    html += '<td>'
         html += '<input type="radio" name="edit_action_'+id+'" id="edit_disallow_'+id+'" value="Disallow"';
         if (a == "Disallow") html += ' checked="checked"';
         html += ' /><label for="edit_disallow_'+id+'">Disallow</label>';
         html += '<input type="radio" name="edit_action_'+id+'" id="edit_allow_'+id+'" value="Allow"';
         if (a == "Allow") html += ' checked="checked"';
         html += ' /><label for="edit_allow_'+id+'">Allow</label>';
    html += '</td>';
    
    html += '<td><select id="edit_robot_'+id+'">'+get_robot_options(r)+'</select></td>';
    html += '<td><input type="text" name="edit_url_'+id+'" id="edit_url_'+id+'" class="input-url" value="'+u+'">';
    html += '<input type="button" id="copy_rule_'+id+'" value="Copy" class="right-label"/>';
    html += '<input type="button" id="delete_rule_'+id+'" value="Delete" class="right-label"/>';
    html += '<div id="edit_err_'+id+'" class="error"></div>';
    html += '</td>';
    html += '</tr>';

    return html;    
}

function copy_rule(id) {
    var aa = $("input[name=edit_action_"+id+"]:checked").val();
    if (!aa) return;
    
    var rr = $("#edit_robot_"+id).val();
    if (!rr) return;
    
    var uu = $("#edit_url_"+id).val();
    if (!uu) { $("#edit_url_"+id).focus(); return; }
    
    var new_rule = new robot_rule(aa, rr, uu);
    rules.push(new_rule);
    
    $("#robot-rules tbody").append(get_rule_html(new_rule.id, aa, rr, uu));
    
    if ($.browser.msie) {
        $("#edit_disallow_"+new_rule.id).click(function() { update_rule_action(new_rule.id); });
        $("#edit_allow_"+new_rule.id).click(function() { update_rule_action(new_rule.id); });        
    }
    else {
        $("#edit_disallow_"+new_rule.id).change(function() { update_rule_action(new_rule.id); });
        $("#edit_allow_"+new_rule.id).change(function() { update_rule_action(new_rule.id); });

    }
        
    $("#edit_robot_"+new_rule.id).change(function() {
       update_rule_robot(new_rule.id);
    });
    
    $("#edit_url_"+new_rule.id).keyup(function() {
        update_rule_url(new_rule.id);
    });

    $("#copy_rule_"+new_rule.id).click(function() {
       copy_rule(new_rule.id);
    });
    
    $("#delete_rule_"+new_rule.id).click(function() {
       delete_rule(new_rule.id);
    });
    
    update_robots_txt();
}

function update_rule_action(id) {
    var aa = $("input[name=edit_action_"+id+"]:checked").val();
    for (var i in rules) {
        if (rules[i].id == id) {
            rules[i].action = aa;
            break;
        }
    }
    
    update_robots_txt();
}

function delete_rule(id) {
    for (var i in rules) {
      if (rules[i].id == id) {
          rules.splice(i,1);
          $("#rule_"+id).remove();
          break;
      }
    }
    
    update_robots_txt();
}

function update_rule_robot(id) {
    var rr = $("#edit_robot_"+id).val();
    
    for (var i in rules) {
        if (rules[i].id == id) {
            rules[i].robot = rr;
            break;
        }
    }
    
    update_robots_txt();
    
}

function update_rule_url(id) {
    var uu = $("#edit_url_"+id).val();
    // if (!uu) { $("#edit_url_"+id).focus(); return; }

    for (var i in rules) {
        if (rules[i].id == id) {
            rules[i].url = uu;
            break;
        }
    }
    
    update_robots_txt();
    
}

function update_robots_txt() {
    check_errors();
    
    var nl = "\n";
    if ($.browser.msie) nl = "\n\r";
    
    var html = "";
    html += "User-Agent: *"+nl;;
    var def = "";
    
    if ($("input[name=default_action]:checked").val() == "Disallow") {
        def = "Disallow: /"+nl;;    
    }
    else {
        def = "Disallow: "+nl;;    
    }
    
    // var def = $("input[name=default_action]:checked").val() + ": /"+nl;;
    html += def;
    
    for (var i in robots) {
        var found = false;
        for (var j in rules) {
            if (rules[j].robot == robots[i].name && !rules[j].has_errors) {
                if (!found) { found = true; if (rules[j].robot != "*") { html += nl + "User-Agent: "+rules[j].robot+nl; } }
                html += rules[j].action + ": " + rules[j].url + nl;
            }
        }
    }
    
    var sitemap_url = $("#sitemap_url").val();
    if ( (sitemap_url != "") && (sitemap_url.match(/^http(s)?\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S+)+$/i)) ) {
        html += nl + "Sitemap: " + $("#sitemap_url").val() + nl;
    }
    $("#robots_txt").text(html);
        
}

function check_errors() {
    
    var ar = $("#add_robot").val();
    var au = $("#add_url").val();
    
    var r = get_robot(ar);
    
    var err = "";
    if ((!r.pattern_matching) && ((au.indexOf("*") != -1) || (au.indexOf("$") != -1))) {
        err += "This robot doesn't support pattern matching!<br />"
    }
    
    if (!au.match(/^\//)) {
        err += "You should start url with / <br />";
    }
    
    if (is_duplicate_rule(-1,ar,au)) {
        err += "This is duplicate rule <br />";
    }
    
    
    if (err) {
        $("#add_err").html(err);
        if ($("#add_err").is(":hidden")) $("#add_err").show("fast");
    }
    else {
        if (!$("#add_err").is(":hidden")) $("#add_err").hide("fast");
    }
    
    for (var i in rules) {
        err = "";
        ar = $("#edit_robot_"+rules[i].id).val();
        au = $("#edit_url_"+rules[i].id).val();
        r = get_robot(ar);
        
        if ((!r.pattern_matching) && ((au.indexOf("*") != -1) || (au.indexOf("$") != -1))) {
            err += "This robot doesn't support pattern matching!<br />"
        }

        if (!au.match(/^\//)) {
            err += "You should start url with / <br />";
        }
        
        //if (au == "/") {
        //    err += "This is the same as the default rule <br />";
        //}
        
        if (is_duplicate_rule(rules[i].id,ar,au)) {
            err += "This is duplicate rule <br />";
        }
        
        if (err) {
            $("#edit_err_"+rules[i].id).html(err);
            if ($("#edit_err_"+rules[i].id).is(":hidden")) $("#edit_err_"+rules[i].id).show("fast");
            rules[i].has_errors = true;
        }
        else {
            if (!$("#edit_err_"+rules[i].id).is(":hidden")) $("#edit_err_"+rules[i].id).hide("fast");
            rules[i].has_errors = false;
        }
        
    }
    
    if ($("#sitemap_url").val() != "") {
        var sitemap_url = $("#sitemap_url").val();
        if (sitemap_url.match(/^http(s)?\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S+)+$/i)) {
            if (!$("#sitemap_err").is(":hidden")) $("#sitemap_err").hide("fast");
        }
        else {
            $("#sitemap_err").html("You should enter full url to your sitemap");
            if ($("#sitemap_err").is(":hidden")) $("#sitemap_err").show("fast");
        };
    }
    else {
        if (!$("#sitemap_err").is(":hidden")) $("#sitemap_err").hide("fast");
    }
    
    
        
}

function is_duplicate_rule(id, robot, url) {
    for (var i in rules) {
        if ((rules[i].id != id) && (rules[i].robot == robot) && (rules[i].url.toLowerCase() == url.toLowerCase())) {
            return true;
        }
    }
    return false;
}

function get_robot(name) {
    for (var i in robots) {
        if (robots[i].name == name) return robots[i];
    }
    return 0;
}

$(document).ready(function() {

    update_robots_txt();
    
    $("#add_robot").append(get_robot_options('*'));

    if ($.browser.msie) {
        $("#default_disallow").click(function() { update_robots_txt(); });
        $("#default_allow").click(function() { update_robots_txt(); });               
    }
    else {
        $("#default_disallow").change(function() { update_robots_txt(); });
        $("#default_allow").change(function() { update_robots_txt(); });        
    }    
    
    $("#add_robot").change(function() {
        check_errors();
    });
    
    $("#add_url").keyup(function() {
        check_errors();        
    });
    
    $("#sitemap_url").keyup(function() {
        update_robots_txt();    
    });
    
    $("#add_rule").click(function() {

       var a = $("input[name=add_action]:checked").val();
       if (!a) return;
       
       var r = $("#add_robot").val();
       if (!r) return;
       
       var u = $("#add_url").val();
       if (!u) { $("#add_url").focus(); return; }
       
       if (is_duplicate_rule(-1,r,u)) { $("#add_url").focus(); return; }
       
       var rule = new robot_rule(a,r,u);
       rules.push(rule);
        
       $("#robot-rules tbody").append(get_rule_html(rule.id, a, r, u));

       if ($.browser.msie) {
            $("#edit_disallow_"+rule.id).click(function() { update_rule_action(rule.id); });
            $("#edit_allow_"+rule.id).click(function() { update_rule_action(rule.id); });        
       }
       else {
            $("#edit_disallow_"+rule.id).change(function() { update_rule_action(rule.id); });
            $("#edit_allow_"+rule.id).change(function() { update_rule_action(rule.id); });        
       }
       
       $("#edit_robot_"+rule.id).change(function() {
            update_rule_robot(rule.id); 
       });
       
       $("#edit_url_"+rule.id).keyup(function() {
            update_rule_url(rule.id);
       });
       
       $("#copy_rule_"+rule.id).click(function() {
          copy_rule(rule.id);
       });
       
       $("#delete_rule_"+rule.id).click(function() {
          delete_rule(rule.id);
       });
       
       $("#add_robot").val("*");
       $("#add_url").val("");
       
       update_robots_txt();
    });

});
