/***
 ***
 *** SITELIFE INTEGRATION & BUSINESS OBJECTS
 ***
 ***/
//document.domain = "discoveramerica.com";
//var sl_serverName = "sitelifestageuk";
var sl_fsArticle = "da_featuredstories";
var sl_fsDiv = "fs_container";
var noRequest = 0;

//var sl_daapiProxyServerUrl = "http://" + sl_serverName + "." + document.domain + "/ver1.0/Direct/DirectProxy";
//var sl_daapiServerUrl = "http://" + sl_serverName + "." + document.domain + "/ver1.0/Direct/Process";
//document.write("<scr" + "ipt type="text/javascript" src="" + sl_daapiProxyServerUrl + ""></sc" + "ript>n");

// SiteLife Integration Object
function SiteLifeIntegration() {
var GalleryArray = null;
	// receives an array of request objects along with a callback function where they
	// will be processed
	this.DoDAAPIRequest = function (requests, callback) {
		var requestBatch = new RequestBatch();
		//alert(requests.length);
		for (var i = 0; i < requests.length; i++) {
			requestBatch.AddToRequest(requests[i]);
		}
		//alert(callback);
		if (callback == null) {
			callback = this.ProcessResponse;
		}
		requestBatch.BeginRequest(serverUrl, callback);
	};
	this.ProcessResponse = function (responseBatch) {
		tools.DebugDir(responseBatch);
		var galleryResponse = false;
		if (responseBatch.Messages[0].Message == "ok") {
			pgp.GalleryArray = new Array();			
			for (var i = 0; i < responseBatch.Responses.length; i++) {
				if (responseBatch.Responses[i].Gallery != null) {
					galleryResponse = true;
					var gallery = responseBatch.Responses[i].Gallery;
					tools.DebugDir(gallery);
					pg = new PhotoGallery();
					pg.Title = gallery.Title;
					pg.Description = gallery.Description;
					pg.ImgSrc = gallery.GalleryPromo.Image.Small;
					pg.Permalink = gallery.Permalink;
					pgp.GalleryArray[i] = pg;						
				} else {
					if (responseBatch.Responses[i].Comment != null) {
						fsp.Stories[i] = responseBatch.Responses[i].Comment;
					} else {
						tools.DebugLog("Response [" + i + "] is not a supported object");
					}
				}
			}
			if (galleryResponse) {
				if (pgp.PhotoGalleryPageHandler != null) {
					pgp.PhotoGalleryPageHandler();
				} else {
					tools.DebugLog("PhotoGalleriesPageHandler is not defined!");
				}
			} else {
				if (fsp.FeaturedStoryPageHandler != null) {
					fsp.FeaturedStoryPageHandler();
				} else {
					tools.DebugLog("FeaturedStoryPageHandler is not defined!");
				}
			}
		} else {
			tools.DebugDir(responseBatch);
		}
	};
}
var sli = new SiteLifeIntegration();

// Generic tools object
function GenericTools() {
	this.getCookie = function (name) {
		var dc = document.cookie;// this returns/reads all cookies for the domain separated by a semicolon
		var prefix = name + "=";// creates "hd=" ("hd" is passed in to the function)
		var begin = dc.indexOf("; " + prefix);// returns a -1 or whole number for position of "; hd"
		if (begin == -1) { // "; hd" string does not exist - meaning that hd is the first cookie in the collection of cookies for the domain
			begin = dc.indexOf(prefix); //begin is 0 since prefix ("hd") is at the 0 position
			if (begin != 0) {
				return null;
			} //begin should be at index 0 - fail if not
		} else {
			begin += 2; // add 2 to current begin -- not sure why. perhaps this is useful if hd is not the first cookie for the domain
		}
		var end = document.cookie.indexOf(";", begin); // search the cookie collection for ";", start the search at begin
		if (end == -1) { // end does not exist so there is only one cookie for the domain
			end = dc.length; // only one cookie for the domain so the end is the length
		}
		return unescape(dc.substring(begin + prefix.length, end)); // return the values between the end of "hd=" and the end of the cookie
	};
	this.getUserKey = function () {
		var cookie = this.getCookie("HD");
		var userKey = null;
		if (cookie != null && cookie.length > 0) {
			userKey = unescape(cookie.split("|")[0]);
		}
		return userKey;
	};
	this.GetCity = function (entry) {
		return entry.split(",")[0];
	};
	this.GetGalleryId = function (entry) {
		if (entry != null) {
			return entry.split(",")[1];
		} else {
			return "";
		}
	};
	this.DebugLog = function (s) {
		if (typeof console != "undefined") {
			console.log(s);
		}
	};
	this.DebugDir = function (o) {
		if (typeof console != "undefined") {
			//console.dir(o);
		}
	};
}
var tools = new GenericTools();

// Photo Gallery object
function PhotoGallery() {
	this.Title = "";
	this.Description = "";
	this.ImgSrc = "";
	this.Permalink = "";
}

// Photo GalleryPage object
function PhotoGalleryPage() {
	this.GalleriesPerPage = 9;
	this.TotalGalleries = 0;
	this.OnPage = 1;
	this.TypeOfGallery = GALLERY_CITY;
	this.LetterOfGallery = A;
	this.Galleries = null;
	this.PhotoGalleryPageHandler = null;
	this.GalleryArray = null;
	
	//params: type of gallery (city/state), letter to get, page, callback handler, total galleries to retrieve
	this.LoadPage = function (galleryType, letter, pagenum, handler, totalToGet) {
		this.OnPage = pagenum;
		this.TypeOfGallery = galleryType;
		this.PhotoGalleryPageHandler = handler;
		this.LetterOfGallery = letter;
		this.GalleriesPerPage = totalToGet;
		this.CreateRequestNew();
	};
	this.NextPage = function () {
		this.OnPage++;
		this.CreateRequest();
	};
	this.PreviousPage = function () {
		this.OnPage--;
		this.CreateRequest();
	};
	this.TotalPages = function () {
		return Math.ceil(this.TotalGalleries / this.GalleriesPerPage);
	};
	this.StartAtGalleryIndex = function () {
		return (this.GalleriesPerPage * this.OnPage) - this.GalleriesPerPage;
	};
	this.StopAtGalleryIndex = function () {
		return (this.GalleriesPerPage * this.OnPage);
	};
	this.CreateRequest = function () {
		tools.DebugLog("OnPage: " + this.OnPage);
		tools.DebugLog("TypeOfGallery: " + this.TypeOfGallery);
		tools.DebugLog("PhotoGalleryPageHandler: " + this.PhotoGalleryPageHandler);
		this.Galleries = new Array();
		var keys = new Array();
		if (this.TypeOfGallery == GALLERY_CITY) {
			tools.DebugDir(city);
			this.TotalGalleries = city[this.LetterOfGallery].length;
			var startAt = this.StartAtGalleryIndex();
			var stopAt = this.StopAtGalleryIndex();
			for (var i = startAt; i < stopAt; i++) {
				if (city[this.LetterOfGallery][i] == null) {
					break;
				}		
				keys[i] = new GalleryKey(tools.GetGalleryId(city[this.LetterOfGallery][i]));		
			}
		} else {
			tools.DebugDir(state);
			this.TotalGalleries = state[this.LetterOfGallery].length;
			var startAt = this.StartAtGalleryIndex();
			var stopAt = this.StopAtGalleryIndex();
			for (var i = startAt; i < stopAt; i++) {
				if (state[this.LetterOfGallery][i] == null) {
					break;
				}
				keys[i] = new GalleryKey(tools.GetGalleryId(state[this.LetterOfGallery][i]));
			}
		}
		if (keys.length > 0) {
			sli.DoDAAPIRequest(keys);
		}
	};

	this.CreateRequestNew = function () {
		tools.DebugLog("OnPage: " + this.OnPage);
		tools.DebugLog("TypeOfGallery: " + this.TypeOfGallery);
		tools.DebugLog("PhotoGalleryPageHandler: " + this.PhotoGalleryPageHandler);
		var keys = new Array();
		if(this.TypeOfGallery == GALLERY_CITY) {
			var cityIndex = 0;
			tools.DebugDir(city);
			for(var alpha = 0; alpha < 26; alpha++){
				this.TotalGalleries = city[alpha].length;
				for (var i = 0; i < this.TotalGalleries; i++) {
					if (city[alpha][i] != null) {
						keys[cityIndex] = new GalleryKey(tools.GetGalleryId(city[alpha][i]));
						cityIndex++;
					}
				}
			}
		} else {
			var stateIndex = 0;
			tools.DebugDir(state);
			for(var alpha = 0; alpha < 26; alpha++){
				this.TotalGalleries = state[alpha].length;	
				for (var i = 0; i < this.TotalGalleries; i++) {
					if (state[alpha][i] != null) {
						keys[stateIndex] = new GalleryKey(tools.GetGalleryId(state[alpha][i]));
						stateIndex++;					
					}				
				}
			}
		}
		if (keys.length > 0) {
			var keyCount = 0;
			var keyLen = Math.floor(keys.length/10);
			
			if(keys.length % 10 > 0) {
				keyLen++;
			}
			noRequest = keyLen;
			
			while(keyLen > 0) {
				var tenKeys = new Array();
				for(var i = 0; i < 10; i++) {
					if(keyCount < keys.length) {
						tenKeys[i] = keys[keyCount];
						keyCount++;
					}
				}
				keyLen--;
				sli.DoDAAPIRequest(tenKeys);
			}
		}
	};
}
var pgp = new PhotoGalleryPage();

// Feature Stories Page object
function FeaturedStoryPage() {
	this.FeaturedStoryPageHandler = null;
	this.Stories = new Array();
	
	// params: callback handler
	this.LoadPage = function (handler) {
		this.FeaturedStoryPageHandler = handler;
		var commentKeys = new Array();
		for (var i = 0; i < featuredStories.length; i++) {
			commentKeys[i] = new CommentKey(featuredStories[i]);
		}
		sli.DoDAAPIRequest(commentKeys);
	};
}
var fsp = new FeaturedStoryPage();
function FeatureStory() {
	this.display = function () {
		var uid = tools.getUserKey();
		if (uid != null) {
			var key = new UserKey(uid);
			var requests = new Array();
			requests[0] = key;
			sli.DoDAAPIRequest(requests, slFeatureStory.processDisplay);
		}
	};
	this.processDisplay = function (responseBatch) {
		if (responseBatch.Messages[0].Message == "ok") {
			var user = responseBatch.Responses[0].User;
			if (user.UserTier == "Editor") {
				slFeatureStory.addLink();
			}
		}
	};
	this.addLink = function () {
		var cc = document.getElementById("Comments_Container");
		if (cc == null) {
			callmelater();
			return;
		}
		var tdDivs = cc.getElementsByTagName("td");
		for (var i = tdDivs.length - 1; i >= 0; i--) {
			if (tdDivs[i].className == "Comments_NestedRecommend") {
				var fsDiv = tdDivs[i].getElementsByTagName("div");
				// originaly there is only one div in this cell
				if (fsDiv.length == 1) {
					// Get comment key
					var s = fsDiv[0].id;
					var key = s.substring(10, s.length);
					// create new div
					var fsDiv = document.createElement("div");
					fsDiv.setAttribute("class", "plckFeatureStory");
					var a = document.createElement("a");
					a.href = "javascript:slFeatureStory.FeatureThis('" + key + "');";
					a.innerHTML = "Feature this Story";
					fsDiv.appendChild(a);
					tdDivs[i].appendChild(fsDiv);
				}
			}
		}

		//continue monitoring
		callmelater();
	};
	this.FeatureThis = function (key) {
		var title = "Featured story submitted";
		var body = "A featured story request was submitted for story key: " + key;
		var pro = key;
		var pageUrl = document.location.href;
		var pageTitle = document.title;
		// create and send request
		var articleKey = new ArticleKey(sl_fsArticle);
		var reviewAction = new ReviewAction(articleKey, pageUrl, pageTitle, title, 0, body, pro, "");
		var requests = new Array();
		requests[0] = reviewAction;
		sli.DoDAAPIRequest(requests, slFeatureStory.processFSRequest);
	};
	this.processFSRequest = function (responseBatch) {
		if (responseBatch.Messages[0].Message != "ok") {
			alert(responseBatch.Messages[0].Message);
		} else {
			alert("Feature story request has been submitted.");
		}
	};
	this.getFeaturedStories = function (parent) {
		var p = document.getElementById(parent);
		var d = document.createElement("div");
		d.id = sl_fsDiv;
		p.appendChild(d);
		var articleKey = new ArticleKey(sl_fsArticle);
		var reviewPage = new ReviewPage(articleKey, 3, 1, "TimeStampDescending");
		var requests = new Array();
		requests[0] = reviewPage;
		sli.DoDAAPIRequest(requests, slFeatureStory.processFeaturedStories);
	};
	this.processFeaturedStories = function (responseBatch) {
		if (responseBatch.Messages[0].Message == "ok") {
			var reviewPage = responseBatch.Responses[0].ReviewPage;
			var requests = new Array();
			for (var i = 0; i < reviewPage.Reviews.length; i++) {
				requests[i] = new CommentKey(reviewPage.Reviews[i].ReviewPros);
			}
			sli.DoDAAPIRequest(requests, slFeatureStory.DrawFeaturedStories);
		}
	};
	this.DrawFeaturedStories = function (responseBatch) {
		if (responseBatch.Messages[0].Message == "ok") {
			var d = document.createElement("div");
			d.setAttribute("class", "featured_stories");
			for (var i = 0; i < responseBatch.Responses.length; i++) {
				if (i == (responseBatch.Responses.length) - 1) {
					d.innerHTML += slFeatureStory.DrawFeaturedStory1(responseBatch.Responses[i].Comment);
				} else {
					d.innerHTML += slFeatureStory.DrawFeaturedStory(responseBatch.Responses[i].Comment);
				}
			}
			var container = document.getElementById(sl_fsDiv);
			container.appendChild(d);
		}
	};
	this.DrawFeaturedStory = function (story) {
		var html = "<div class='featured_story_border'>";
		html += "<div class='featured_story_user'>";
		html += "<div class='featured_story_user_avatar'>";
		html += "<img src='" + story.Author.AvatarPhotoUrl + "' />";
		html += "</div>";
		html += "<div class='featured_story_user_info'><a href='" + story.CommentUrl + "' class='blue-normal'>View Location</a></div>";
		html += "<div class='featured_story_user_info'>";
		html += "<a href='profile.html?UID=" + story.Author.UserKey.Key + "' class='blue-normal'>" + story.Author.DisplayName + "</a> wrote:";
		html += "</div>";
		html += "<div class='featured_story_time'>";
		html += story.PostedAtTime;
		html += "</div>";
		html += "</div>";
		html += "<div class='featured_story_body'>";
		html += story.CommentBody;
		html += "</div>";
		html += "</div>";
		return html;
	};
	this.DrawFeaturedStory1 = function (story) {
		var html = "<div class='featured_story'>";
		html += "<div class='featured_story_user'>";
		html += "<div class='featured_story_user_avatar'>";
		html += "<img src='" + story.Author.AvatarPhotoUrl + "' />";
		html += "</div>";
		html += "<div class='featured_story_user_info'><a href='" + story.CommentUrl + "' class='blue-normal'>View Location</a></div>";
		html += "<div class='featured_story_user_info'>";
		html += "<a href='profile.html?UID=" + story.Author.UserKey.Key + "' class='blue-normal'>" + story.Author.DisplayName + "</a> wrote:";
		html += "</div>";
		html += "<div class='featured_story_time'>";
		html += story.PostedAtTime;
		html += "</div>";
		html += "</div>";
		html += "<div class='featured_story_body'>";
		html += story.CommentBody;
		html += "</div>";
		html += "</div>";
		return html;
	};
}
var slFeatureStory = new FeatureStory();
callmelater = function () {
	window.setTimeout(slFeatureStory.addLink, 300);
};