var ph_container_id;
var ph_url;
var ph_sourcematch;
var ph_familymatch;
var ph_sourceweb;
var ph_catrestrict;
var ph_pcode;
var ph_params;
var ph_debug;
var ph_rcount;
var ph_force;

function topix_ajax(opt) {
    var t;
    try {
        var ua = navigator.userAgent;
        if (ua.indexOf("MSIE") > -1)
            t = new ActiveXObject("Microsoft.XMLHTTP");
        else
            t = new XMLHttpRequest();
    }
    catch (e) { return null; }
    if (t == null) return null;
    if (opt.callback)
        t.onreadystatechange = function() { if (t.readyState == 4) opt.callback(t) };
    t.open("POST", opt.url, !opt.sync);
    t.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    if (opt.headers)
        for (var hname in headers)
            t.setRequestHeader(hname, headers[hname]);
    t.send(opt.body);

    if (opt.sync && t.overrideMimeType)
        opt.callback(t);

}

function topix_get_headlines()
{
    if (window.location.href.match("ph_debug=1"))
        ph_debug = 1;
 
    if (ph_container_id == null)
    {
        if (ph_debug)
            alert('You must set "container_id" to the id of the div that will contain the widget"');
        return null;
    }
    
    if (ph_url != null && ph_url != '')
        art_url = ph_url;
    else
        art_url = window.location.href;
    
    if (art_url.match("force=1") || window.location.href.match("force=1"))
        ph_force = 1;
   
    if (!art_url.match("^http://"))
    {
        if (ph_debug)
            alert("URL must start with http://");
        return null;
    }

    if (ph_sourcematch == null)
        ph_sourcematch = 0;

    if (ph_familymatch == null)
        ph_familymatch = 0;

    if (ph_sourceweb == null)
        ph_sourceweb = 0;
    
    if (ph_catrestrict == null)
        ph_catrestrict = 0;

    if (ph_pcode == null && ph_debug)
        alert("PCODE not set");
        
    
    var req_url = "http://api.topix.com/ajax/relinx-widget";
    req_url += "?surl=" + escape(art_url) + "&ssrc=" + escape(ph_sourcematch) + "&ssrcweb=" + escape(ph_sourceweb) + "&sscatsearch=" + escape(ph_catrestrict) + "&sspropmatch=" + escape(ph_familymatch) + "&ssjswidget=1";

    if (ph_pcode != null)
        req_url += "&sspcode=" + escape(ph_pcode);
    if (ph_params)
        req_url += "&ssurlparams=" + escape(ph_params);
    if (ph_rcount)
        req_url += "&sscount=" + escape(ph_rcount);
    if (ph_force)
        req_url += "&force=1";
    
    document.write('<script type="text/javascript" defer="defer" src="' + req_url + '"></script>');
}

function topix_validate_attrib()
{
    var attrib = document.getElementById("topix_attrib");

    if (attrib == null)
        return 0;
    if (attrib.nodeName.toLowerCase() != 'a')
        return 0;
    if (attrib.href.indexOf('http://www.topix.com') != 0)
        return 0;
    
    return 1;
}

if (topix_validate_attrib())
    topix_get_headlines();
