﻿var NEWS = {
	Load: function(renderCallback, failedCallback) {
		var resultSet = [];
		$.ajax({
			type: "POST",
			url: "/WS/SpotOn/SpotOn.Server/spoton.ws.iwebsite.asmx/SiteNameToID",
			data: "{ maxRowsToReturn: null, ticket: null, siteNameFilter: 'News' }",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			cws: false,
			success: function(response) {
				this.cws = true;		
				var sitehits = response.d;
				if (sitehits && sitehits.length == 1) {		
					$.ajax({
						type: "POST",
						url: "/WS/SpotOn/SpotOn.Server/spoton.ws.iwebsite.asmx/SiteTreeItems",
						data: "{ maxRowsToReturn: null, ticket: null, siteID: " + sitehits[0].ID.toString() + " }",
						contentType: "application/json; charset=utf-8",
						dataType: "json",
						cws: false,
						success: function(response) {
							this.cws = true;		
							var itemhits = response.d;
							var remaining = itemhits.length;
							for (var i=0; i<itemhits.length; i++) {	// these calls run in parallel				
								$.ajax({
									type: "POST",
									url: "/WS/SpotOn/SpotOn.Server/spoton.ws.iwebsite.asmx/ItemContent",
									data: "{ maxRowsToReturn: null, ticket: null, itemID: " + itemhits[i].ItemID.toString() + " }",
									contentType: "application/json; charset=utf-8",
									dataType: "json",
									cws: false,
									hitsIndex: i,
									success: function(response) {
										this.cws = true;		
										resultSet[this.hitsIndex] = response.d[0];										
									},
									failure: function(msg) {
										if (failedCallback) failedCallback(msg, this);
									},
									complete: function() {
										remaining--;
										if (!this.cws) {
											this.failure('failed to load news item #' + itemhits[this.hitsIndex].ItemID.toString() + '!');
										} else if (remaining==0 && renderCallback) {
											renderCallback(resultSet);
										}
									}
								});                													
							}	
						},
						failure: function(msg) {
							if (failedCallback) failedCallback(msg, this);
						},
						complete: function() { 
							if (!this.cws) {
								this.failure('failed to list content of News site!');
							} 
						}
					});                					
				}	
			},
			failure: function(msg) {
				if (failedCallback) failedCallback(msg, this);
			},
			complete: function() { 
				if (!this.cws) {
					this.failure('failed to find News site!');
				}
			}
		});                
	}
};