//handles the AIM registration and receipt of incoming stories
AIM.params.callbacks.listener.dataIM = ["newsBoxWidget.acceptIncomingNews"];
AIM.params.callbacks.startSession = ["newsBoxWidget.startSession"];
AIM.params.callbacks.endSession = ["newsBoxWidget.endSession"];
AIM.params.assertCaps = ["dfa00f982b1048f7b40c3d73945104e6"];
//var subscriptionTopic = "";

var relegenceTopics = "";
var subscriptionTopic = new Array();
var tickersloaded = false;

// Define our widget object
var newsBoxWidget = {
	// The entry point for the application. Called from the windows load event.
	init: function() {
		// if you'd like to see the data stream, set this to true.
		AIM.params.DEBUG = false;
		AIM.params.wimKey = "rt1VyNQdqA79rdfn";
		if (typeof LIVE_NEWS_ENABLED == "undefined" || LIVE_NEWS_ENABLED) {
		    AIM.util.addEvent(window,newsBoxWidget.cleanUp,"beforeunload");
	        newsBoxWidget.connectSession("dataIM");
	    }
	},
	cleanUp: function() {
		AIM.util.currentState = 1;
		if(AIM.core.activeSession) {
			AIM.transactions.endSession();
			AIM.core.debug(AIM.params.text.autoLogOut);
		}
		AIM.params.token = null;
		AIM.params.sessionId = null;
	},
	/**
	*	Accepts an incoming instant mesage and routes it to the appropriate window.
	*	@param { Object } response The JSON response from the host.
	*/
	acceptIncomingNews:function(response) {
	AIM.core.debug("<b>newsBoxWidget.acceptIncomingNews:</b><br />" + response.source.aimId);
        var winID = response.source.aimId;
        // This will have to move into the populateNewsModule function once there are more than 1 topics on a page
        var isWinID = false;
        for (var i=0; i < subscriptionTopic.length; i++)
         {
          if (winID == subscriptionTopic[i]) { // Find WindID is in array
            isWinID = true;
            break;
           }
         }
        if (!isWinID) return;
        
		var message = response.dataIM;
		var tmp = "{ \"alert\": { \"as";
		var indx = message.indexOf(tmp);
		//TODO: this is in order to try prevent JavaScript holes. Need to look into this more
		if (indx == -1) {
		   // The format of the message is not as expected so rejecting it
		   return;
		}
		var jsn_msg = eval("("+message+")");
		if (typeof jsn_msg != "undefined") {
		    var title = jsn_msg.alert.headline;
            if (typeof title != 'undefined') {
                var lang = jsn_msg.alert.language;
                if (lang.toLowerCase() != "en") {
                 // we only want to display english stories for now
                    return;
                }
			var newsObject = new RelegenceNews(title);
			newsObject.winID = winID;
		        newsObject.source = jsn_msg.alert.source;
		        newsObject.newsDate = jsn_msg.alert.publishDate;
		        newsObject.mediaType = jsn_msg.alert.mediaType;
			newsObject.setStoryURL(encodeURIComponent(jsn_msg.alert.url));
			newsObject.sourceGroup = jsn_msg.alert.sourceGroup;
			var firstline = "";
			if (typeof jsn_msg.alert.snippet != "undefined") {
                    if(jsn_msg.alert.snippet.match(/<a ([^>]*)>([^<]*)<\/a>/g))  
                        jsn_msg.alert.snippet = jsn_msg.alert.snippet.replace(/href/gi,"target=\"_blank\" href");
                    if(jsn_msg.alert.snippet.match(/<img ([^>]*)>/g))  {
                        jsn_msg.alert.snippet = jsn_msg.alert.snippet.replace(/</g,"&lt;");
                        jsn_msg.alert.snippet = jsn_msg.alert.snippet.replace(/>/g,"&gt;");
                    }
				    firstline = encodeURIComponent(jsn_msg.alert.snippet);
				    if(firstline.match(/'/g))  {
				        firstline = firstline.replace(/'/g,"%27");
				    }
                    if(firstline.match(/ /g))  {
				        firstline = firstline.replace(/ /g,"+");
				    }
				}
				//debugger;
                newsObject.firstLine = firstline;
		        newsObject.parseRelatedCount(jsn_msg.alert.topicCounts);
			    newsObject.relevancy = jsn_msg.alert.relevance;
			    newsObject.assetID = jsn_msg.alert.assetId;
			    newsObject.topicID = jsn_msg.alert.topicID;
			    newsObject.related = jsn_msg.alert.relatedExist.toLowerCase();
			    newsObject.parseAllRelated(jsn_msg.alert.allTopicCounts);
		        populateNewsModule(newsObject);
				var heat = jsn_msg.alert.heat;
				//debugger;
				//updateHeat(heat);
            }
		}
	},
    connectSession: function(eventList) {
        var ses = AIM.params.sessionId?"&aimsid=" + AIM.params.sessionId:"";
		var tObj = {
			dataURI:AIM.params.baseTransactionURI + AIM.params.transactions.startSession + "?k=" + AIM.params.wimKey + ses +"&events="+eventList+"&assertCaps=" + AIM.params.assertCaps +"&f=json&anonymous=1&c=AIM%2Ecore%2EacceptData",
			type:"startSession"
		}
        newsBoxWidget.requestData(tObj);
	},
    acceptData:function(json) {
		var requestId = parseInt(json.response.requestId);
		var code = parseInt(json.response.statusCode);
		if(code != 200) {
			AIM.core.debug("newsBoxWidget.acceptData: Response Error! Code is " + code + "(" + AIM.params.text.errors.serverErrors[code] + "), transaction was " + AIM.core.AIMData[requestId].objData.type);
			if(code == 401) { 
				var t = AIM.core.AIMData[requestId].objData.type;
				// only these transactions expect a 401 - if we get it on any other, kill the session
				if(t != "getToken" && t != "startSession" && t != "endSession") {
					AIM.params.sessionId = null;
					AIM.params.token = null;
					AIM.transactions.endSession();
					AIM.transactions.getToken(AIM.core.subscriptions);
				}
			}
		}
		try{ 
			AIM.core.debug("<b>AIM.core.acceptData:</b><br />" + json.response.toSource());
		} catch(err) { }
		// Until we have an aim api with the addTempBuddy callback we need to use this acceptData function.
		try {
			if(AIM.core.AIMData[requestId]) {
				if(AIM.core.AIMData[requestId].oScript) {
					// Following line will cause IE to crash on a reload of the page and a relaunch of the app...go figure.
					if(!AIM.params.MSIE) AIM.core.AIMData[requestId].oScript.parentNode.removeChild(AIM.core.AIMData[requestId].oScript);
				}
			}
		} catch(err) {
			AIM.core.debug("newsBoxWidget.acceptData: Unable to remove AIM.core.AIMData[" + requestId + "] -- " + err.message);
		}
	},
    endSession:function(json) {
	    var fetchEvent = json.response.data.fetchBaseURL + "&f=json";
        var tObj = {
            dataURI:fetchEvent,
            type:"endSession"
        }
        newsBoxWidget.requestData(tObj);
		AIM.core.destroyDataObject(json.response.requestId);
		AIM.core.destroyListenerObject(false);
		AIM.core.activeSession = false;
		newsBoxWidget.cleanUp();
	},
    updateSubscription: function(sub) {
	    // temp blocking of sub while news is not returning it all the time
		if (sub == "") {
		    subscriptionTopic[subscriptionTopic.length] = "empty";
		} else {
			subscriptionTopic[subscriptionTopic.length] = sub;
    	 }
	},
	    /**
    *   Sends a request to the host, i.e, an instant message, status update, etc.
    *   @param { Object } transactionObject An object defined by the AIM.transactions.* methods with properties required by the transaction
    */
    requestData: function(transactionObject) {
        var len = AIM.core.AIMData.length;
        transactionObject.timestamp = Date.parse(new Date());
        AIM.core.AIMData[len] = {};
        AIM.core.AIMData[len].oScript = document.createElement("script");
        AIM.core.AIMData[len].oScript.setAttribute("id","AIMBuddyList-AIMData-" + len);
        AIM.core.AIMData[len].oScript.setAttribute("type","text/javascript");
        AIM.core.AIMData[len].objData = transactionObject;
        if (transactionObject.dataURI != "	") {
            if(transactionObject.dataURI.indexOf("?") == -1) {
                transactionObject.dataURI+="?r=" + len + "&nocache=" + Date.parse(new Date());
            } else {
                transactionObject.dataURI+="&r=" + len + "&nocache=" + Date.parse(new Date());
            }
            AIM.core.debug("requestData: " + transactionObject.dataURI);
            AIM.core.AIMData[len].oScript.setAttribute("src",transactionObject.dataURI);
            document.getElementsByTagName("head")[0].appendChild(AIM.core.AIMData[len].oScript);
        }
    },
	
    subscriptionTopicUpdate: function() {
    	var topics = "";
        if (subscriptionTopic.length > 0 && tickersloaded == true) {
            for (var i=0; i<subscriptionTopic.length; i++)
             {
              if (subscriptionTopic[i].toLowerCase() == "disconnect") {
              	 topics = "disconnect";
              } else {
                  topics = topics + "&t=" + subscriptionTopic[i];
              }
             }
             
             if (topics.toLowerCase() == "disconnect") {
                newsBoxWidget.cleanUp();
              } else {
                var tObj = {
                	
                    dataURI:AIM.params.baseTransactionURI + "aim/addTempBuddy?f=json&k="+AIM.params.wimKey + "&c=newsBoxWidget%2EacceptData&aimsid="+AIM.params.sessionId+topics,
                    type:"addTempBuddy"
                }
                newsBoxWidget.requestData(tObj);
              }
            
        } else {
	        window.setTimeout("newsBoxWidget.subscriptionTopicUpdate()", 10000);        
        }
    },


	/**
	*	Starts a new session on a succesful startSession request. Creates the listener object for the session.
	*	@param { Object } json The JSON response from the host.
	*/
	startSession: function(json) {
		if(json.response.statusCode == 200) {
			AIM.params.user = json.response.data.myInfo.displayId;
			AIM.params.sessionId = json.response.data.aimsid;
			AIM.params.listenerURI = json.response.data.fetchBaseURL + "&f=json&c=AIM%2Ecore%2Elisten&timeout=" + AIM.params.REQUEST_TIMEOUT;
			AIM.core.destroyListenerObject(true);
			AIM.core.activeSession = true;
			
		    newsBoxWidget.subscriptionTopicUpdate();
			
		} else if(json.response.statusCode == 450) {
			AIM.core.createAuthWindow(json.response.data.redirectURL + "&k=" + AIM.params.wimKey);
		} else if (json.response.statusCode == 451) {
			AIM.transactions.endSession();
			AIM.core.debug(AIM.params.text.permissionDenied);
			return;
		} else {
			AIM.core.debug("Unable to start a session. Code is " + json.response.statusCode);
			//alert(AIM.params.text.startSessionFailed);
		}
		AIM.core.destroyDataObject(json.response.requestId);
	}
	
		
}
// attach the presenceBoxWidget.init function to the window's load event
window.addEventListener?window.addEventListener("load",newsBoxWidget.init,false):window.attachEvent("onload",newsBoxWidget.init);
