﻿function Filter(s, maxWidth) {
    var result = s;

    //script
    var scr = /<script*./;
    if (scr.test(s)) throw "script detected";

    //profanity
    result = result.replace(/fuck/gi, "f***");
    result = result.replace(/shit/gi, "sh**");
    result = result.replace(/cunt/gi, "c***");

    //remove height attributes
    result = result.replace(/height=".*?"/gi, "height=259");

    //urls

    result = parseUrl2(result);


    //replace width attributes with the max width
    if ((maxWidth != null) && (maxWidth > 0)) {
        result = result.replace(/width=".*?"/gi, "width=\"" + maxWidth + "\"");
    }
    return result;

}


function parseUrl2(data) {
    // var e = /(?:http:\/\/)?(?:[\w-]+\.)+[a-z]{2,6}$/gi;
    var e = /(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)(?:\([-A-Z0-9+&@#\/%=~_|$?!:;,.]*\)|[-A-Z0-9+&@#\/%=~_|$?!:;,.])*(?:\([-A-Z0-9+&@#\/%=~_|$?!:;,.]*\)|[A-Z0-9+&@#\/%=~_|$])/gi;
    var str = data.split(/\s/g);
    str = removeDuplicateElement(str);
    for (i = 0; i < str.length; i++) {

        if (str[i].match(e)) {
            if (str[i].indexOf("src") == -1) {
                anchortag = "<a href=\"http://" + str[i] + "\" style=\"float:none\">" + str[i] + "</a>";
                data = data.replace(str[i], anchortag);
                data = data.replace("http://http://", "http://");
            }
        }
    }
    return data;
}

function removeDuplicateElement(arrayName) {
    var newArray = new Array();
    label: for (var i = 0; i < arrayName.length; i++) {
        for (var j = 0; j < newArray.length; j++) {
            if (newArray[j] == arrayName[i])
                continue label;
        }
        newArray[newArray.length] = arrayName[i];
    }
    return newArray;
}
