	/*
		UpdateArticleWidget by Erik Noble
		version 0.3 Last modified on 02/14/2009
	
		Maybe: Improve input validation
		Maybe: Handle the server being down?
		Maybe: Allow input of categories as an array OR string

		Q: What's up with serverUrl and scope?
	*/
	function UpdateArticleWidget(serverUrl) {
		this.debug = false;
		this.isUrl = function(s) {
			var regexp = /https?:\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
			return regexp.test(s);
		}
		if (serverUrl != null && serverUrl != "" && this.isUrl(serverUrl)) {
			this.serverUrl = serverUrl;
		} else if (typeof gSiteLife != "undefined") { //Check for the existence of SiteLifeProxy so we can build it ourself.
			this.serverUrl = gSiteLife.__baseUrl + "/Direct/Process";
		} else {
			var siteLifeServer = "sitelife"; //the best we can do is guess now.
			var tld = document.domain.replace(/[^\.]*\.([^\.]+\.[^\.]{2,3})/g,"$1");
			this.serverUrl = "http://" + siteLifeServer + "." + tld + "/" + "ver1.0/Direct/Process";
		}
	}
	
	UpdateArticleWidget.prototype.HandleCheckResponse = function(paramBag, responseBatch) {
		if (typeof(console) != 'undefined' && navigator.userAgent.indexOf("Safari") < 0 && this.debug) {		//Firebug debug
		    console.group("Response: HandleCheckResponse - " + paramBag.articleKey + " (" + paramBag.state + ")");
		    console.dir(paramBag);
		    console.dir(responseBatch);
		    console.groupEnd();
		}
		//We need to compare what we returned with what we're trying to input.
		var article = responseBatch.Responses[0].Article;
		if (article.PageUrl != paramBag.onPageUrl) {
			if (typeof(console) != 'undefined' && navigator.userAgent.indexOf("Safari") < 0 && this.debug) {		//Firebug debug
			    console.log("Debug: HandleCheckResponse - PageUrl needs updating. article.PageUrl:\"" + article.PageUrl + "\" !=  paramBag.onPageUrl:\"" + paramBag.onPageUrl + "\"");
			}
			paramBag.state = "update";
			return this.Core(paramBag);
		} else {
			if (typeof(console) != 'undefined' && navigator.userAgent.indexOf("Safari") < 0 && this.debug) {		//Firebug debug
			    console.log("Debug: HandleCheckResponse - PageUrl NOT updating. article.PageUrl:\"" + article.PageUrl + "\" ==  paramBag.onPageUrl:\"" + paramBag.onPageUrl + "\"");
			}
		}
		if (article.PageTitle != paramBag.onPageTitle) {
			if (typeof(console) != 'undefined' && navigator.userAgent.indexOf("Safari") < 0 && this.debug) {		//Firebug debug
			    console.log("Debug: HandleCheckResponse - PageTitle needs updating. article.PageTitle:\"" + article.PageTitle + "\" !=  paramBag.onPageTitle:\"" + paramBag.onPageTitle + "\"");
			}
			paramBag.state = "update";
			return this.Core(paramBag);
		} else {
			if (typeof(console) != 'undefined' && navigator.userAgent.indexOf("Safari") < 0 && this.debug) {		//Firebug debug
			    console.log("Debug: HandleCheckResponse - PageTitle NOT updating. article.PageTitle:\"" + article.PageTitle + "\" ==  paramBag.onPageTitle:\"" + paramBag.onPageTitle + "\"");
			}
		}
		if (paramBag.section == null) { //If paramBag.categories is null, String functions won't work
			if (article.Section != null) {
				if (typeof(console) != 'undefined' && navigator.userAgent.indexOf("Safari") < 0 && this.debug) {		//Firebug debug
				    console.log("Debug: HandleCheckResponse - Section needs updating. article.Section:\"" + article.Section.Name.toLowerCase()  + "\" !=  paramBag.section:\"" + paramBag.section  + "\"");
				}
				paramBag.state = "update";
				return this.Core(paramBag);
			} else {
				if (typeof(console) != 'undefined' && navigator.userAgent.indexOf("Safari") < 0 && this.debug) {		//Firebug debug
				    console.log("Debug: HandleCheckResponse - Section NOT updating. article.Section:\"" + article.Section + "\" ==  paramBag.section:\"" + paramBag.section + "\"");
				}
			}
		} else {
			if (article.Section.Name.toLowerCase()  != paramBag.section.toLowerCase() ) {
				if (typeof(console) != 'undefined' && navigator.userAgent.indexOf("Safari") < 0 && this.debug) {		//Firebug debug
				    console.log("Debug: HandleCheckResponse - Section needs updating. article.Section:\"" + article.Section.Name.toLowerCase()  + "\" !=  paramBag.section:\"" + paramBag.section.toLowerCase()  + "\"");
				}
				paramBag.state = "update";
				return this.Core(paramBag);
			} else {
				if (typeof(console) != 'undefined' && navigator.userAgent.indexOf("Safari") < 0 && this.debug) {		//Firebug debug
				    console.log("Debug: HandleCheckResponse - Section NOT updating. article.Section:\"" + article.Section.Name.toLowerCase() + "\" ==  paramBag.section:\"" + paramBag.section.toLowerCase() + "\"");
				}
			}
		}
		if (paramBag.categories == null) { //If paramBag.categories is null, String functions won't work
			if (article.Categories.join("") != "") {
				if (typeof(console) != 'undefined' && navigator.userAgent.indexOf("Safari") < 0 && this.debug) {		//Firebug debug
				    console.log("Debug: HandleCheckResponse - Categories needs updating. article.Categories:\"" + article.Categories.join("") + "\" !=  paramBag.categories:\"" + paramBag.categories + "\"");
				}
				paramBag.state = "update";
				return this.Core(paramBag);
			} else {
				if (typeof(console) != 'undefined' && navigator.userAgent.indexOf("Safari") < 0 && this.debug) {		//Firebug debug
					console.log("Debug: HandleCheckResponse - Categories NOT updating. article.Categories:\"" + article.Categories.join("") + "\" ==  paramBag.categories:\"" + paramBag.categories + "\"");
				}
			}
		} else {
			var articleCategories = "";
			for (var i = 0; i < article.Categories.length; i++) {
				articleCategories += article.Categories[i].Name;
				if (i < article.Categories.length-1) {articleCategories += " ";} //Don't add a space to the end.
			}
			if (articleCategories.toLowerCase() != paramBag.categories.replace(/,/gi," ").replace(/\s+/gi," ").split(" ").join(" ").toLowerCase()) {
				if (typeof(console) != 'undefined' && navigator.userAgent.indexOf("Safari") < 0 && this.debug) {		//Firebug debug
				    console.log("Debug: HandleCheckResponse - Categories needs updating. article.Categories:\"" + articleCategories.toLowerCase() + "\" !=  paramBag.categories:\"" + paramBag.categories.replace(/,/gi," ").replace(/\s+/gi," ").split(" ").join(" ").toLowerCase() + "\"");
				}
				paramBag.state = "update";
				return this.Core(paramBag);
			} else {
				if (typeof(console) != 'undefined' && navigator.userAgent.indexOf("Safari") < 0 && this.debug) {		//Firebug debug
					console.log("Debug: HandleCheckResponse - Categories NOT updating. article.Categories:\"" + articleCategories.toLowerCase() + "\" ==  paramBag.categories:\"" + paramBag.categories.replace(/,/gi," ").replace(/\s+/gi," ").split(" ").join(" ").toLowerCase() + "\"");
				}
			}
		}
		if (typeof(console) != 'undefined' && navigator.userAgent.indexOf("Safari") < 0 && this.debug) {		//Firebug debug
			console.log("Debug: HandleCheckResponse - No updates necessary.");
		}
		return false;
	}

	UpdateArticleWidget.prototype.HandleUpdateResponse = function(paramBag, responseBatch) {
		if (responseBatch.Messages[0].Message == "ok") {
			if (typeof(console) != 'undefined' && navigator.userAgent.indexOf("Safari") < 0 && this.debug) {		//Firebug debug
			    console.group("Response: HandleUpdateResponse - " + paramBag.articleKey + " (" + paramBag.state + ")");
			    console.dir(paramBag);
			    console.dir(responseBatch);
			    console.groupEnd();
			}
		} else {
			alert("Error: "  + responseBatch.Messages[0].Message);
			if (typeof(console) != 'undefined' && navigator.userAgent.indexOf("Safari") < 0 && this.debug) { //Firebug debug
				console.group("Error: HandleUpdateResponse - UNKNOWN ERROR");
			    console.dir(paramBag);
			    console.dir(responseBatch);
				console.groupEnd();
			}
		}
	}

	UpdateArticleWidget.prototype.Core = function(paramBag) {
		paramBag				= paramBag				|| {};
		paramBag.articleKey		= paramBag.articleKey	|| null;
		paramBag.onPageUrl		= paramBag.onPageUrl	|| window.location.href;
		paramBag.onPageTitle	= paramBag.onPageTitle	|| document.title;
		paramBag.section		= paramBag.section		|| null;
		paramBag.categories		= paramBag.categories	|| null;
		paramBag.state			= paramBag.state		|| "check";
		
		if (typeof(console) != 'undefined' && navigator.userAgent.indexOf("Safari") < 0 && this.debug) {		//Firebug debug
			console.group("Debug: Core - " + paramBag.articleKey + " (" + paramBag.state + ")");
			console.dir(paramBag);
			console.groupEnd();
		}

		if (this.ValidateInput(paramBag)) {

			var requestBatch =  new RequestBatch();
			var UAA_ArticleKey = new ArticleKey(paramBag.articleKey);

			if (paramBag.state == "check") {
				requestBatch.AddToRequest(UAA_ArticleKey); 
				//Check what's already in the system.
				var ProcessCheckResponse = (function(paramBag, self) { //We make this an embedded function so that we still have the paramBag for reference. Phred is awesome.
					return function(responseBatch) {
						if (responseBatch.Messages[0].Message == "ok") {
							self.HandleCheckResponse(paramBag, responseBatch);
						} else if (responseBatch.Messages[0].Message.indexOf("Unable to find data on request") > -1) { //Article doesn't exist
							paramBag.state = "new";
							self.Core(paramBag);
						} else {
							alert("Error: "  + responseBatch.Messages[0].Message);
							if (typeof(console) != 'undefined' && navigator.userAgent.indexOf("Safari") < 0 && this.debug) { //Firebug debug
							    console.group("Error: ProcessCheckResponse - " + responseBatch.Messages[0].Message);
							    console.dir(responseBatch);
							    console.groupEnd();
							}
						}
					}
				})(paramBag, this);
				serverUrl = serverUrl || this.serverUrl
				if (this.isUrl(serverUrl)) {
			        requestBatch.BeginRequest(serverUrl, ProcessCheckResponse);
				} else {
					throw("UpdateArticleWidget: Invalid Process URL.");
				}
			} else if (paramBag.state == "new" || paramBag.state == "update") {
				var UAA_OnPageUrl = paramBag.onPageUrl;
				var UAA_OnPageTitle = paramBag.onPageTitle;
				var UAA_Section = new Section(paramBag.section);
				var UAA_Categories = (paramBag.categories == null) ? new Array() : this.BuildArray(paramBag.categories);
		        
		        requestBatch.AddToRequest(new UpdateArticleAction(UAA_ArticleKey, UAA_OnPageUrl, UAA_OnPageTitle, UAA_Section, UAA_Categories));
				var ProcessUpdateResponse = (function(paramBag, self) { //We make this an embedded function so that we still have the paramBag for reference. Phred is awesome.
					return function(responseBatch) {
						if (responseBatch.Messages[0].Message == "ok") {
							self.HandleUpdateResponse(paramBag, responseBatch);
						} else {
							alert("Error: "  + responseBatch.Messages[0].Message);
							if (typeof(console) != 'undefined' && navigator.userAgent.indexOf("Safari") < 0 && this.debug) { //Firebug debug
							    console.group("Error: ProcessUpdateResponse - UNKNOWN ERROR");
							    console.dir(responseBatch);
							    console.groupEnd();
							}
						}
					}
				})(paramBag, this);
				serverUrl = this.serverUrl || serverUrl;
				if (this.isUrl(serverUrl)) {
			        requestBatch.BeginRequest(serverUrl, ProcessUpdateResponse);
				} else {
					throw("UpdateArticleWidget: Invalid Process URL.");
				}
			} else {
				//unknown state. Error?
				if (typeof(console) != 'undefined' && navigator.userAgent.indexOf("Safari") < 0 && this.debug) { //Firebug debug
					console.group("Unknown state in Core - " + paramBag.articleKey + " (" + paramBag.state + ")");
					console.dir(paramBag);
					console.groupEnd();
				}
			}
		} else {
			if (typeof(console) != 'undefined' && navigator.userAgent.indexOf("Safari") < 0 && this.debug) { //Firebug debug
				console.group("Validation Failed (" + this.Core.validationOutput.length + ") for articleKey: " + paramBag.articleKey + " (" + paramBag.state + ")");
				console.dir(this.Core.validationOutput);
				console.groupEnd();
			}
			return this.validationOutput;
		}
	}
	
	UpdateArticleWidget.prototype.ValidateInput = function(paramBag) {
		paramBag			= paramBag				|| {};
		var articleKey		= paramBag.articleKey	|| null;
		var onPageUrl		= paramBag.onPageUrl	|| null;
		var onPageTitle		= paramBag.onPageTitle	|| null;
		var section			= paramBag.section		|| null;
		var categories		= paramBag.categories	|| null;

		this.validationOutput = new Array();
		var isValid = true;

		if (typeof(console) != 'undefined' && navigator.userAgent.indexOf("Safari") < 0 && this.debug) { //Firebug debug
			console.group("Debug: ValidateInput");
			console.dir(paramBag);
			console.groupEnd();
		}
		
		if (articleKey == "" || articleKey == null) {
			this.validationOutput[this.validationOutput.length] = "Invalid articleKey: \"" + articleKey + "\"";
			isValid = false;
		}
		if (onPageUrl == "" || onPageUrl == null || !this.isUrl(onPageUrl)) {
			this.validationOutput[this.validationOutput.length] = "Invalid onPageUrl: \"" + onPageUrl + "\"";
			isValid = false;
		}
		if (onPageTitle == "" || onPageTitle == null) {
			this.validationOutput[this.validationOutput.length] = "Invalid onPageTitle: \"" + onPageTitle + "\"";
			isValid = false;
		}
		return isValid;
	}

	UpdateArticleWidget.prototype.BuildArray = function(inputString) {
		var inputArray = inputString.replace(/,/gi," ").replace(/\s+/gi," ").split(" ");
		var outputArray = new Array();
		
		for (var i=0; i < inputArray.length; i++) {
			outputArray[i] = new Category(inputArray[i]);
		}
		if (typeof(console) != 'undefined' && navigator.userAgent.indexOf("Safari") < 0 && this.debug) { //Firebug debug
			console.group("Debug: BuildArray - " + inputString);
			console.dir(outputArray);
			console.groupEnd();
		}
		return outputArray;
	}

	UpdateArticleWidget.prototype.UpdateArticle = function(articleKey, categories, section, onPageTitle, onPageUrl) {
		return this.Core({"articleKey":articleKey,"onPageUrl":onPageUrl,"onPageTitle":onPageTitle,"section":section,"categories":categories}); 
	}

	/* THE END */

	var plck_DW_UAW = new UpdateArticleWidget(serverUrl);
