var daapiProcessUrl = "http://devsitelife.suntimes.com/ver1.0/Direct/Process";

/* STNG namespace */
var stng = function() {
    var _namespace = "stng";
    return { };
}();

/* SiteLife namespace */
stng.sitelife = function() {
    var _namespace = "stng.sitelife";
    return { };
}();

/**
 * Utility methods for future use.
 */
stng.sitelife.util = function() {
    var _namespace = "stng.sitelife.util";
    return {

		/**
		 * Convert newlines in a string to something that can be displayed in a browser.
		 */
		newlinesToHTML : function(text) {
			var result = text.replace(/\r\n/g,"\n");
			result = result.replace(/\n/g,"<br/>\n");
			return result;
		},

		/**
		 * Convert newlines in a string to something that can be displayed in a browser.
		 */
		htmlToNewlines : function(text) {
			var result = text.replace(/<[bB][rR][ ]*\/+>/g,""); // we are betting that a newline was put after the BR anyway
			return result;
		},

		escapeHTML : function(cmt) {
			var clean = "";
			if (cmt.length > 0) {
				var clean = cmt.replace(/</g,"&lt;");
				//clean=clean.replace(/>/g,"&gt;");
				clean = clean.replace(/\u2019/g,"&#8217;");
				clean = clean.replace(/\u201C/g,"&#8220;");
				clean = clean.replace(/\u201D/g,"&#8221;");
			}
			return clean;
		},

		/**
		 * Safe method for determining if a variable is available.
		 */
		isDefined : function(object, variable) {
			return (typeof(eval(object)[variable]) != "undefined");
		},

		/**
		 * Gets the value of a specified query parameter.
		 *
		 * name  Name of the value from the query string.
		 *
		 * Returns a string containing value of specified parameter, or null if it does not exist.
		 */
		getQueryParameter : function(parameterName) {
			var result = null;
			var key = parameterName + "=";
			var parameters = document.location.search.substring(1).split("&");
			for (var i = 0; i < parameters.length; i++) {
				if (parameters[i].indexOf(key) == 0) {
					result = parameters[i].substring(key.length);
					i = parameters.length;
				}
			}
			return result;
		},

		/**
		 * Get back the pathname with querystring, with the paramter we want updated to the value.
		 * Returns the whole query string with the value updated.
		 */
		updateQueryStringWithParam : function(url, param, value) {
			var regxp = /([^\?]+)\?{0,1}(.*)/;
			var parts = regxp.exec(url);
			var result = parts[1] + "?";
			var tqs = parts[2];
			var pvs = tqs.split("&");
			var added = false;
			var cnt = 0;
			for (var tt = 0; tt < pvs.length; tt++) {
				if (cnt > 0) {
					result += "&";
				}
				var eqL = pvs[tt].indexOf("=");
				var key = "";
				var val = null;
				if (eqL > 0) {
					key = pvs[tt].substring(0, eqL);
					val = pvs[tt].substring(eqL + 1, pvs[tt].length);
				} else {
					key = pvs[tt];
				}

				result += key;
				if (key == param) {
					result += "=";
					result += value;
					added = true;
				} else if (val != null) {
					result += "=" + val;
				}
				cnt++;
			}
			if (! added) {
				if (cnt > 0) {
					result += "&";
				}
				result += param + "=" + value;
				cnt++;
			}
			var pattern = /sl_CommentsInputAnchor/g;
			var clearAnchor = pattern.exec(result);
			if(clearAnchor != null) {
				result = result.replace(/#sl_CommentsInputAnchor/g,"");
			}
			return result;
		},

		/**
		 *
		 */
		mouseX : function(evt) {
            var result = null;
			if (evt.layerX) {
			    result = evt.layerX;
			} else if (evt.x) {
			    result = evt.x;
			} else if (evt.clientX) {
			    result = evt.clientX + (document.documentElement.scrollLeft ?
				  					    document.documentElement.scrollLeft :
									    document.body.scrollLeft);
			}
			return result;
		},
	
		/**
		 *
		 */
		mouseY : function(evt) {
			var result = null;
			if (evt.layerY) {
				result = evt.layerY;
			} else if (evt.y) {
				result = evt.y;
			} else if (evt.clientY) {
				result = evt.clientY + (document.documentElement.scrollTop ?
										document.documentElement.scrollTop :
										document.body.scrollTop);
			}
			return result;
		},

		/**
		 *
		 */
		hideElement : function(elementId) {
			var el = document.getElementById(elementId);
			if (el) {
				el.style.display = "none";
			}
		},

		/**
		 *
		 */
		showDivAtMouse : function(mouseEvent, elementId) {
			var el = document.getElementById(elementId);
			var posx = this.mouseX(mouseEvent) - 170; // REVISIT - I need to get this width from the el, not this made-up number
			var posy = this.mouseY(mouseEvent);
			//normalize to make sure we at least appear on the screen
			if (posx < 0) posx = 10;
			if (posy < 0) posy = 10;
			el.style.left = posx + "px";
			el.style.top = posy + "px";
			el.style.display = "block";
		},

		/**
		 * Accepts input as "8/29/2007 10:06:36 AM"
		 */
		formatDateNice : function(dateString) {
		    var months = new Array("","January","February","March","April","May","June","July","August","September","October","November","December");
		    //                       month      day        year      hour   min    sec      period
		    var prettyDateRegEx = /(\d{1,2})\/(\d{1,2})\/(\d{4})\s+(\d{1,2}):(\d\d):(\d\d)\s+([AaPp][Mm])/;
			var result = dateString;
			var doa = prettyDateRegEx.exec(dateString);
			if (doa != null && doa.length == 8) {
				result = "" + months[parseInt(doa[1])] + " " + parseInt(doa[2]) + ", " + doa[3] + " " + parseInt(doa[4]) + ":" + doa[5] + " " + doa[7]
			}
			return result;
		},

		/**
		 * Gets the value of the specified cookie.
		 *
		 * name  Name of the desired cookie.
		 *
		 * Returns a string containing value of specified cookie, or null if cookie does not exist.
		 */
		getCookie : function(name) {
			var dc = document.cookie;
			var prefix = name + "=";
			var begin = dc.toLowerCase().indexOf("; " + prefix.toLowerCase());
			if (begin == -1){
				begin = dc.toLowerCase().indexOf(prefix.toLowerCase());
				if (begin != 0) {
					return null; //begin should be at index 0 - fail if not
				}
			} else {
				begin += name.length;
			}
			var end = document.cookie.indexOf(";", begin);
			if (end == -1) {
				end = dc.length;
			}
			var result = unescape(dc.substring(begin + prefix.length, end));
			return result;
		},

		debug : function(s) {
			if (1 || SITELIFE_DEBUG) {
				if (this.isDefined(window, "console")) {
					console.log(s);
				} else {
					alert(s);
				}
			}
		},

		debugObj : function(obj) {
			if (1 || SITELIFE_DEBUG) {
				if (this.isDefined(window, "console") && navigator.userAgent.indexOf("Safari") < 0) {
					console.dir(obj);
				} else {
					alert(JSON.stringify(obj));
				}
			}
		}
	}; // close return
}();

/**
 * Utility methods for future use.
 */
stng.sitelife.integration = function() {
    var _namespace = "stng.sitelife.integration";
	var recEls = new Array();
	var comEls = new Array();
	var article = null;
    return {
		initArticle : function(articleId, title, url, section, catArray) {
			var articleKey = new ArticleKey(articleId);  
			var categories = new Array();
			for (var gg = 0 ; gg < catArray.length ; gg++) {
				categories[gg] = new Category(catArray[gg]);
			}
        
	        // create and send request  
		    var requestBatch = new RequestBatch();              
			var updateAction = new UpdateArticleAction(articleKey, url, title, new Section(section), categories);  
			requestBatch.AddToRequest(updateAction);
			requestBatch.AddToRequest(new ArticleKey(articleId));
			requestBatch.BeginRequest(daapiProcessUrl, __stng_sitelife_integration_initArticle_callback);   
        },
		RecommendationCount : function(elementId) {
			recEls.push(elementId);
		},
		placeRecommendationCounts : function() {
			for (var ff = 0 ; ff < recEls.length ; ff++) {
				var el = document.getElementById(recEls[ff]);
				if (el != null) {
					el.innerHTML = stng.sitelife.integration.article.Recommendations.NumberOfRecommendations;
				}
			}
		},
		CommentCount : function(elementId) {
			comEls.push(elementId);
		},
		placeCommentCounts : function() {
			for (var ff = 0 ; ff < comEls.length ; ff++) {
				var el = document.getElementById(comEls[ff]);
				if (el != null) {
					el.innerHTML = stng.sitelife.integration.article.Comments.NumberOfComments;
				}
			}
		}
    };
}();

function __stng_sitelife_integration_initArticle_callback(responseBatch) {  
	if (responseBatch.Messages[0].Message == 'ok') {  
		//alert('Article successfully updated');  
		stng.sitelife.integration.article = responseBatch.Responses[0].Article;
		stng.sitelife.integration.placeRecommendationCounts();
		stng.sitelife.integration.placeCommentCounts();
    } else {
		stng.sitelife.util.debug("__stng_sitelife_integration_initArticle_callback:  did not get a good response when trying to update an article and get article information.");
		stng.sitelife.util.debugObj(responseBatch);
    } 
}
         
