/* This script sends a mesage to Notifixious to check if a user is conencted or not*/

/* If the user is not connected, let's show him the subscription form*/

/* If he is connected, let's display links for each of his channels*/
var notifixious = "notifixio.us";

var i, a;
var feed; 

/* What do we do if we have several feeds? */
/* Hum, let's display several times the widget, once for each feed? But what if they're different format of the same thing? */
/* Interesting : */
/* Only care about RSS Feeds and if they're none, look at the ATOM feeds : looks good! (risk = we lose some specific ATOM feeds if they're RSS as well)*/
var rss_feeds = new Array();
var atom_feeds = new Array();
var feeds = new Array();
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("alternate") != -1) {
        if(a.getAttribute("type") == "application/rss+xml") {
            rss_feeds[rss_feeds.length] = a;
        }
        else if(a.getAttribute("type") == "application/atom+xml") {
            atom_feeds[atom_feeds.length] = a;
        }
    }
}
/* Ok, now, let's find out the results! How many RSS/ATOM feeds to we have? */
if(atom_feeds.length == 0)
{
    if(rss_feeds.length == 0)
    {
        /* Let's show an error message!*/
        document.getElementById('notifixious_widget_errors').innerHTML = 'Sorry, this page doesn\'t support subscription.';
        document.getElementById('notifixious_widget_errors').style.display = 'block';
    }
    else
    {
        feeds = rss_feeds;
    }
}
else
{
    feeds = atom_feeds;
}

document.write('<div id="notifixious_widget">');
document.write('<span id="notifixious_widget_debug"></span>');

document.write('<p id="notifixious_widget_errors" style="display:none;" ></p>');

document.write('<div id="subscription_form" style="display:none">');
document.write('<p id="notifixious_instructions">Receive messages as soon as a new entry is published on this blog. Choose your channel:</p>');
document.write('<select id="feed" name="feed" style="display:none;">');
for(i=0; (feed = feeds[i]); i++) {
    if(i==1)
    {
        document.getElementById("feed").style.display = 'inline';
    }
    title = feed.getAttribute("title");
    title = title.replace(/rss|atom/ig, document.title);
    document.write('<option value="'+feed.href+'">'+title+'</option>'); /* Here, we must check that the url of the feed is absolute!*/
}
document.write('</select>');
document.write('<select id="channel_type" name="channel_type" onchange="change_partial()"><option value="MsnAccount">With Live! Messenger</option><option value="IcqAccount">With ICQ</option><option value="JabberAccount">With Jabber</option><option value="GtalkAccount" selected="selected">With GoogleTalk</option><option value="AimAccount">With AIM</option><option value="YahooMessengerAccount">With Yahoo!</option><option value="EmailAccount">By Email</option></select>');
document.write('<span id="new_account_form">')
document.write('<input onclick="erase_input_field(this)" id="GtalkAccount_to" name="GtalkAccount[to]" size="30" value="Your Gmail username" style="color:#808080; background: 0% 50% #fff url(http://'+notifixious+'/images/gtalk_small.png?1226113078) no-repeat; padding-left:35px; width:120px;" type="text" />');
document.write('</span>')
document.write('<input onclick="subscribe();" type="button" value="Subscribe" />');
document.write('</div>');

document.write('<div id="confirmation_form" style="display:none;">');
document.write('<input name="_method" type="hidden" value="put" />');
document.write('<input id="subscription_id" type="hidden" value = ""  >');
document.write('<label for="subscription_confirmation_phrase">Code :</label>');
document.write('<input id="subscription_confirmation_phrase" name="subscription[confirmation_phrase]" type="text" />');
document.write('<input onclick="confirm();" type="button" value="Confirm" />');
document.write('<input type="hidden" id="send_confirmation_url" value = "" >'); 
document.write('<a href="#" onclick="resend_confirmation_code()">Resend it</a>');
document.write('</div>');

document.write('<p id="subscribed_message" style="display:none;">You will now receive udpates from this site. Please, <a href="http://'+notifixious+'/login">sign up to Notifixious</a>, to manage your subscriptions in one-click, add channels, and so much more!</p>');

document.write('<ul id="subscription_list" style="padding-left:0px;display:none">')
document.write('</ul>');

function erase_input_field(obj)
{
    obj.value = "";
    obj.style.color = "black";
}

/* Returns the class name of the argument or undefined if it's not a valid JavaScript object.*/  
function getObjectClass(obj) {  
    if (obj && obj.constructor && obj.constructor.toString) {  
        var arr = obj.constructor.toString().match(  
            /function\s*(\w+)/);  
        if (arr && arr.length == 2) {  
            return arr[1];  
        }  
    }  
    return undefined;  
}

/* JSONscriptRequest */
function JSONscriptRequest(fullUrl) {
    // REST request path
    this.fullUrl = fullUrl; 
    // Keep IE from caching requests
    this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
    // Get the DOM location to put the script tag
    this.headLoc = document.getElementsByTagName("head").item(0);
    // Generate a unique script tag id
    this.scriptId = 'JscriptId' + JSONscriptRequest.scriptCounter++;
}

// Static script ID counter
JSONscriptRequest.scriptCounter = 1;

// buildScriptTag method
JSONscriptRequest.prototype.buildScriptTag = function () {
    // Create the script tag
    this.scriptObj = document.createElement("script");
    // Add script object attributes
    this.scriptObj.setAttribute("type", "text/javascript");
    this.scriptObj.setAttribute("charset", "utf-8");
    this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
    this.scriptObj.setAttribute("id", this.scriptId);
}

// removeScriptTag method
JSONscriptRequest.prototype.removeScriptTag = function () {
    // Destroy the script tag
    this.headLoc.removeChild(this.scriptObj);  
}

// addScriptTag method
JSONscriptRequest.prototype.addScriptTag = function () {
    // Create the script tag
    this.headLoc.appendChild(this.scriptObj);
}

/* End of JSONscriptRequest */
function change_partial() {
    var partials = new Array();
    var value = document.getElementById('channel_type').value;
    partials['MsnAccount'] = '<input id=\"MsnAccount_to\" onclick=\"erase_input_field(this)\" value=\"Your MSN Live! \" name=\"MsnAccount[to]\" size=\"30\" style=\"color: #808080; background: 0% 50% #fff url(http://'+notifixious+'/images/msn_small.png?1226113078) no-repeat; padding-left:35px; width:120px;\" type=\"text\" />';
    partials['IcqAccount'] = '<input id=\"IcqAccount_to\" onclick=\"erase_input_field(this)\" value=\"Your ICQ number\" name=\"IcqAccount[to]\" size=\"30\" style=\"color: #808080; background: 0% 50% #fff url(http://'+notifixious+'/images/icq_small.png?1226113078) no-repeat; padding-left:35px; width:120px; width:120px;\" type=\"text\" />';
    partials['JabberAccount'] = '<input id=\"JabberAccount_to\" onclick=\"erase_input_field(this)\" value=\"Your Jabber ID\" name=\"JabberAccount[to]\" size=\"30\" style=\"color: #808080; background: 0% 50% #fff url(http://'+notifixious+'/images/jabber_small.png?1226113078) no-repeat; padding-left:35px; width:120px;\" type=\"text\" />\n';
    partials['GtalkAccount'] = '<input id=\"GtalkAccount_to\" onclick=\"erase_input_field(this)\" value=\"Your Gmail username\" name=\"GtalkAccount[to]\" size=\"30\" style=\"color: #808080; background: 0% 50% #fff url(http://'+notifixious+'/images/gtalk_small.png?1226113078) no-repeat; padding-left:35px; width:120px;\" type=\"text\" />';
    partials['AimAccount'] = '<input id=\"AimAccount_to\" onclick=\"erase_input_field(this)\" value=\"Your AIM username\" name=\"AimAccount[to]\" size=\"30\" style=\"color: #808080; background: 0% 50% #fff url(http://'+notifixious+'/images/aim_small.png?1226113078) no-repeat; padding-left:35px; width:120px;\" type=\"text\" />';
    partials['YahooMessengerAccount'] = '<input id=\"YahooMessengerAccount_to\" onclick=\"erase_input_field(this)\" value=\"Your Yahoo! ID\" name=\"YahooMessengerAccount[to]\" size=\"30\" style=\"color: #808080; background: 0% 50% #fff url(http://'+notifixious+'/images/yahoo_small.png?1226113078) no-repeat; padding-left:35px; width:120px;\" type=\"text\" />';        
    partials['EmailAccount'] = '<input id=\"EmailAccount_to\" onclick=\"erase_input_field(this)\" value=\"Your Email address\" name=\"EmailAccount[to]\" size=\"30\" style=\"color: #808080; background: 0% 50% #fff url(http://'+notifixious+'/images/email_small.png?1226113078) no-repeat; padding-left:35px; width:120px;\" type=\"text\" />';
    document.getElementById('new_account_form').innerHTML = partials[value];
}
    
function subscribe_channel_to_source(channel_id, source_id) {
    document.getElementById('notifixious_loading').style.display = 'inline';
    // The web service call
    var req  = 'http://'+notifixious+'/channels/'+channel_id+'/sources/'+source_id+'/subscription.json?perform=create&callback=updateSubscription'; 
    // Create a new request object
    bObj = new JSONscriptRequest(req); 
    // Build the dynamic script tag
    bObj.buildScriptTag(); 
    // Add the script tag to the page
    bObj.addScriptTag();
}

function unsubscribe_channel_to_source(channel_id, source_id) {
    document.getElementById('notifixious_loading').style.display = 'inline';
    // The web service call
    var req  = 'http://'+notifixious+'/channels/'+channel_id+'/sources/'+source_id+'/subscription.json?perform=destroy&callback=updateSubscription'; 
    // Create a new request object
    bObj = new JSONscriptRequest(req); 
    // Build the dynamic script tag
    bObj.buildScriptTag(); 
    // Add the script tag to the page
    bObj.addScriptTag();
}

function formatted_user_subscription(subscription) {
    li = document.createElement('li');
    li.setAttribute('style', 'list-style-type:none; margin:0px; min-height:20px; line-height:20px; background: url('+subscription.channel.icon+') no-repeat 0% 50%; padding-left: 40px;');
    li.setAttribute('id', 'subscription-'+subscription.channel.id+'-'+subscription.source.permalink);
    link = document.createElement('a');
    // link.setAttribute('href', '#');
    if(subscription.id)
    {
        link.setAttribute('onclick', 'unsubscribe_channel_to_source('+subscription.channel.id+', \''+subscription.source.permalink+'\');');
        link.innerHTML = 'Unsubscribe '+subscription.channel.display_name;
    }
    else
    {
        link.setAttribute('onclick', 'subscribe_channel_to_source('+subscription.channel.id+', \''+subscription.source.permalink+'\');');
        link.innerHTML = "Subscribe "+subscription.channel.display_name;
    }
    li.appendChild(link);
    return li;
}

function display_widget(json) {
    if(json.subscriptions == null) {
        // No user is logged in
        document.getElementById('subscription_form').style.display = 'block';
    }
    else
    {
        subscriptions = json.subscriptions.subscription;
        if(subscriptions[0])
        {
            first_subscription = subscriptions[0];
        }
        else
        {
            first_subscription = subscriptions;
        }
        if(!document.getElementById(first_subscription.source.permalink))
        {
            li_source = document.createElement('li');
            li_source.setAttribute('style', 'list-style-type:none; margin-left:0px;');
            li_source.setAttribute('id', first_subscription.source.permalink);
            li_source.innerHTML = first_subscription.source.name;
            ul = document.createElement('ul');
            ul.setAttribute('style', 'padding:0px')
            li_source.appendChild(ul);
            
            if(subscriptions[0])
            {
                for(i=0; (subscription = subscriptions[i]); i++) {
                    // For each of the subscriptions, let's create a <li>
                    li = formatted_user_subscription(subscription);
                    ul.appendChild(li);
                }// So we have a list of channels!
            }
            else
            {
                li = formatted_user_subscription(subscriptions);
                ul.appendChild(li);
            }
            document.getElementById('subscription_list').appendChild(li_source);
            document.getElementById('subscription_list').style.display = 'block';
        }
    }
}

function updateSubscription(json) {
    document.getElementById('subscription-'+json.subscription.channel.id+'-'+json.subscription.source.permalink).innerHTML = "";

    link = document.createElement('a');
    // link.setAttribute('href', '#');
    if(json.subscription.id)
    {
        link.setAttribute('onclick', 'unsubscribe_channel_to_source('+json.subscription.channel.id+', \''+json.subscription.source.permalink+'\');');
        link.innerHTML = 'Unsubscribe '+json.subscription.channel.display_name;
    }
    else
    {
        link.setAttribute('onclick', 'subscribe_channel_to_source('+json.subscription.channel.id+', \''+json.subscription.source.permalink+'\');');
        link.innerHTML = "Subscribe "+json.subscription.channel.display_name;
    }
    document.getElementById('subscription-'+json.subscription.channel.id+'-'+json.subscription.source.permalink).appendChild(link);
    document.getElementById('notifixious_loading').style.display = 'none';
}

function subscribe() {
    document.getElementById('notifixious_loading').style.display = 'inline';
    var channel_type = document.getElementById('channel_type').value;
    var feed = document.getElementById('feed').value;
    var channel_to_field = channel_type+'_to';
    var channel_to = document.getElementById(channel_to_field).value;
    if(channel_type != "" && channel_to != "")
    {
        var params = 'channel_type='+channel_type+'&'+channel_type+'[to]='+channel_to+'&feed='+feed;
        // The web service call
        var req  = 'http://'+notifixious+'/subscriptions.json?perform=create&callback=show_confirmation_or_error&'+params; 
        // Create a new request object
        bObj = new JSONscriptRequest(req); 
        // Build the dynamic script tag
        bObj.buildScriptTag(); 
        // Add the script tag to the page
        bObj.addScriptTag();
    }
    else
    {
        alert('Please, make sure to fill the text field(s)!');
        document.getElementById('notifixious_loading').style.display = 'none';
    }
}

function show_confirmation_or_error(json) {
    document.getElementById('notifixious_loading').style.display = 'none';
    if(!json.subscription.id)
    {
        if(json.subscription.channel.errors)
        {
            if(json.subscription.channel.errors.gtalk_username)
            {
                alert("There are problems with your subscription. Your Google ID "+json.subscription.channel.errors.gtalk_username);
            }
            else if(json.subscription.channel.errors.msn_username)
            {
                alert("There are problems with your subscription. Your MSN Live! ID "+json.subscription.channel.errors.gtalk_username);
            }
            else if(json.subscription.channel.errors.aim_username)
            {
                alert("There are problems with your subscription. Your AIM "+json.subscription.channel.errors.aim_username);
            }
            else if(json.subscription.channel.errors.icq_number)
            {
                alert("There are problems with your subscription. Your ICQ number "+json.subscription.channel.errors.icq_number);
            }
            else if(json.subscription.channel.errors.full_jid)
            {
                alert("There are problems with your subscription. Your Jabber ID "+json.subscription.channel.errors.full_jid);
            }
            else if(json.subscription.channel.errors.yahoo_messenger_username)
            {
                alert("There are problems with your subscription. Your Yahoo! ID "+json.subscription.channel.errors.yahoo_messenger_username);
            }
            else if(json.subscription.channel.errors.email_address)
            {
                alert("There are problems with your subscription. Please check your email address.");
            }
            else
            {
                alert("There are problems with your subscription. Please check your channel.");
            }
        }
        else if(json.subscription.errors.channel)
        {
            document.getElementById('notifixious_widget_errors').innerHTML = 'This channel already belongs to someone. Please <a href="http://'+notifixious+'/login">login</a> if this is yours.';
            document.getElementById('notifixious_widget_errors').style.display= "block";
        }
        else
        {
            // Catch all.
            alert("Sorry, there was an error with your subscription.");
        }
    }
    else
    {
        subscription_id = json.subscription.id;
        confirmed =  json.subscription.confirmed;
        if(confirmed == "true") {
            // Replace this with a confirmation form!
            display_subscribed_message();
        }
        else {
            alert('We sent you a confirmation code on this channel, please enter it to make sure you want to subscribe');
            display_confirmation_form(subscription_id);
        }
    }
}

function display_confirmation_form(subscription_id) {
    var confirmation_url = 'http://'+notifixious+'/subscriptions/'+subscription_id+'.json';
    var send_confirmation_url = 'http://'+notifixious+'/subscriptions/'+subscription_id+'/send_confirmation.json';    
    document.getElementById('send_confirmation_url').value = send_confirmation_url;
    document.getElementById('confirmation_form').action = confirmation_url;
    document.getElementById('subscription_id').value = subscription_id;
    document.getElementById('subscription_form').style.display = "none";
    document.getElementById('subscribed_message').style.display = "none";
    document.getElementById('notifixious_widget_errors').style.display = "none";
    document.getElementById('confirmation_form').style.display = "block";
}

function display_subscribed_message() {
    document.getElementById('subscription_form').style.display = "none";
    document.getElementById('confirmation_form').style.display = "none";
    document.getElementById('notifixious_widget_errors').style.display = "none";
    document.getElementById('subscribed_message').style.display = "block";
}

function resend_confirmation_code() {
    document.getElementById('notifixious_loading').style.display = 'inline';
    var confirmation_url = document.getElementById('send_confirmation_url').value;
    var req  = confirmation_url + '?perform=send_confirmation&callback=confirmation_code_sent'; 
    // Create a new request object
    bObj = new JSONscriptRequest(req); 
    // Build the dynamic script tag
    bObj.buildScriptTag(); 
    // Add the script tag to the page
    bObj.addScriptTag();
}

function confirmation_code_sent(json) {
    document.getElementById('notifixious_loading').style.display = 'none';
    alert(json.subscription.channel.confirmation_message);
}

function confirmation_sent(json) {
    confirmed =  json.subscription.confirmed
    if(confirmed == "true") {
        // Replace this with a confirmation form!
        display_subscribed_message(confirmed);
    }
    else {
        display_confirmation_form(subscription_id);
        alert('Sorry, this is not the right confirmation code... Please, try again.');
        document.getElementById('subscription_confirmation_phrase').value = "";
    }
    document.getElementById('notifixious_loading').style.display = 'none';
}

function confirm() {
    document.getElementById('notifixious_loading').style.display = 'inline';
    var url = document.getElementById('confirmation_form').action
    var confirmation_phrase = document.getElementById('subscription_confirmation_phrase').value;
    if(confirmation_phrase!= "")
    {
        var req = url+'?perform=confirm&callback=confirmation_sent&subscription[confirmation_phrase]='+confirmation_phrase;
        // Create a new request object
        bObj = new JSONscriptRequest(req); 
        // Build the dynamic script tag
        bObj.buildScriptTag(); 
        // Add the script tag to the page
        bObj.addScriptTag();
    }
    else
    {
        alert('Please enter the confirmation code!');
        document.getElementById('notifixious_loading').style.display = 'none';
    }
}

/*Widget Body*/
for(i=0; (feed = feeds[i]); i++) {
    // The web service call to get all subscriptions for the current user and ssource
    var req  = 'http://'+notifixious+'/subscriptions.json?callback=display_widget&perform=source&feed='+feed.href; 
    // Create a new request object
    bObj = new JSONscriptRequest(req); 
    // Build the dynamic script tag
    bObj.buildScriptTag(); 
    // Add the script tag to the page
    bObj.addScriptTag();
}

document.write('<div id="notifixious_signature" style="margin-top:0px;font-size:0.8em">');
document.write('<img src="https://s3.amazonaws.com/notifixious_assets/ajax-loader.gif" id="notifixious_loading" style="display:none;" />');
document.write('<a href = "http://notifixio.us"><img src="https://s3.amazonaws.com/notifixious_assets/notifixious_widget.png" style="border:none;"></a>');
document.write('<br /><a href="http://notifixio.us/sources/widgets">Powered by Notifixious</a>');
document.write('</div>');
document.write('</div>');
