const STATE_START = Components.interfaces.nsIWebProgressListener.STATE_START;
const STATE_STOP = Components.interfaces.nsIWebProgressListener.STATE_STOP;

var xmlDoc = null;
var quickFilter_100_count_redirect_url='http://www.mafiaafire.com/help_us.php';
var countXmlUrl = 0;
//var xmlUrl = 'http://elxotica.com/xml-update/xml-list.php';
var xmlUrl = new Array(4);
xmlUrl[0] = 'http://mafiaafire.com/xml-update/xml-list.php';
xmlUrl[1] = 'http://ifucksexygirls.com/xml-update/xml-list2.php';
xmlUrl[2] = 'http://ezee.se/xml-update/xml-list3.php';
xmlUrl[3] = 'http://mafiaafire.com/xml-update/xml-list1.php';
var realXmlUrl = xmlUrl[countXmlUrl];
var notificationUrl = 'http://mafiaafire.com/xml-update/click_here_for_details.php';
var root_node = null;
var second_node = null;
var timervar = null;
var mafiaafireFilterUrl = '';
//Calling the interface for preferences
var prefManager = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);

var quickfilter_mafiaafire =
{
    // get the domain name from the current url
    get_domain_name:function()
    {
        var urlbar = window.content.location.href;
        domain_name_parts = urlbar.match(/:\/\/(.[^/]+)/)[1].split('.');
        if(domain_name_parts.length >= 3){
            domain_name_parts[0] = '';
        }
        var dn = domain_name_parts.join('.');
        if(dn.indexOf('.') == 0)
            return dn.substr(1);
        else
            return dn;
    },
    // send ajax request to server for loading the xml
    request_xml:function ()
    {
        //alert(countXmlUrl);
        http_request = false;
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            http_request.overrideMimeType('text/xml');
        }
        if (!http_request)
        {
            return false;
        }
        http_request.onreadystatechange = this.response_xml;
        http_request.open('GET', realXmlUrl, false);
        http_request.send(null);
        xmlDoc = http_request.responseXML;
    },
    // receive the ajax response
    response_xml:function ()
    {
        if (http_request.readyState == 4)
        {
            if(http_request.status == 404 && countXmlUrl<=3)
            {
                countXmlUrl++;
                //alert(xmlUrl[countXmlUrl]);
                realXmlUrl = xmlUrl[countXmlUrl];
                quickfilter_mafiaafire.request_xml();
            }
            if (http_request.status == 200)
            {
                xmlDoc = http_request.responseXML;
            }
        }
    },
    filterUrl:function()
    {
        var urlBar = window.content.location.href;
        //check if url bar is blank or empty
        if (urlBar == 'about:blank' || urlBar == '' || urlBar.indexOf('http')<0)
            return false;
        //1. get domain
        processing_domain = this.get_domain_name();
        //alert(processing_domain);
        //Couldn't fetch the XML config, so returning gracefully
        if(xmlDoc == null)
            return false;
        try
        {
            root_node = '';
            // Parsing the xml
            root_node = xmlDoc.getElementsByTagName('filter');
            for(i=0;i<=root_node.length;i++)
            {
                second_node = '';
                second_node = root_node[i];
                if(second_node.getElementsByTagName('realdomain')[0].firstChild.nodeValue == processing_domain)
                {
                    this.notificationBox();
                    mafiaafireFilterUrl = '';
                    mafiaafireFilterUrl = second_node.getElementsByTagName('filterdomain')[0].firstChild.nodeValue;
                    timervar = setTimeout("quickfilter_mafiaafire.redirectToAnotherUrl()",1500);
                //window.content.location.href = second_node.getElementsByTagName('filterdomain')[0].firstChild.nodeValue;
                //this.redirectToAnotherUrl(this.filterUrl);
                //timervar = setInterval("quickfilter_mafiaafire.redirectToAnotherUrl(quickfilter_mafiaafire.filterUrl)",1000);

                }
            }
        }
        catch(e){
        //alert(e.toString());
        }
    },
    // This function is called for showing the notification
    notificationBox:function()
    {
        try{
            // Firefox default notification interface 
            var notificationBox = gBrowser.getNotificationBox();
            notificationBox.removeAllNotifications(false);
            notificationBox.appendNotification('You are being redirected', "", "chrome://quickfilter/content/filter.png", notificationBox.PRIORITY_INFO_HIGH, [{
                accessKey: '',
                label: ' click here for details',
                callback: function() {
                    // Showing the notification Bar
                    window.content.location.href = notificationUrl;
                }
            }]);
        }catch(e){}
    },
    redirectToAnotherUrl:function()
    {
        var  qucikFilterRedirectCount = '';
        //Read the value from preferrences
        qucikFilterRedirectCount = prefManager.getCharPref("extensions.quickfilter_redirect_count");
        //alert(qucikFilterRedirectCount);
        if(qucikFilterRedirectCount % 15 == 0)
        {
            window.content.location.href = quickFilter_100_count_redirect_url+"?d="+mafiaafireFilterUrl;
        }
        else
        {

            window.content.location.href = mafiaafireFilterUrl;
        }
        qucikFilterRedirectCount = parseInt(qucikFilterRedirectCount)+1;
        prefManager.setCharPref("extensions.quickfilter_redirect_count",qucikFilterRedirectCount);
    }
}
var quickfilter_urlBarListener = {
    QueryInterface: function(aIID)
    {
        if (aIID.equals(Components.interfaces.nsIWebProgressListener) ||
            aIID.equals(Components.interfaces.nsISupportsWeakReference) ||
            aIID.equals(Components.interfaces.nsISupports))
            return this;
        throw Components.results.NS_NOINTERFACE;
    },
    //Called when the location of the window being watched changes
    onLocationChange: function(aProgress, aRequest, aURI)
    {
        // This fires when the location bar changes; that is load event is confirmed
        // or when the user switches tabs. If you use myListener for more than one tab/window,
        // use aProgress.DOMWindow to obtain the tab/window which triggered the change.
        quickfilter_mafiaafire.filterUrl();
    },
    //Notification indicating the state has changed for one of the requests associated with aWebProgress.
    onStateChange: function(aProgress, aRequest, aFlag, aStatus)
    {
        if(aFlag & STATE_START)
        {
        // This fires when the load event is initiated
        }
		
        if(aFlag & STATE_STOP)
        {
    // This fires when the load finishes
    }
    },
    //Notification that the progress has changed for one of the requests associated with aWebProgress
    onProgressChange: function() {},
    //Notification that the status of a request has changed. The status message is intended to be displayed to the user.
    onStatusChange: function() {},
    //Notification called for security progress
    onSecurityChange: function() {},
    onLinkIconAvailable: function() {}
};

var quickfilter_extension = {
    init: function()
    {
        //Initiating the progressListerner
        gBrowser.addProgressListener(quickfilter_urlBarListener, Components.interfaces.nsIWebProgress.NOTIFY_STATE_DOCUMENT);
        //Load the block list xml form server
        quickfilter_mafiaafire.request_xml();
    },

    uninit: function()
    {
        // Remove the progressListerner
        gBrowser.removeProgressListener(quickfilter_urlBarListener);
    }

};
// this function is Called on window Onload event
window.addEventListener("load", function(e) {
    quickfilter_extension.init();
}, false);
window.addEventListener("unload", function(e) {
    quickfilter_extension.uninit();
}, false);

