var Pages = {
	// get - fetch a page for a given app id.
	get: function(appid) {
		Ajax.get("data/apps/" + appid + ".json",{
			onSuccess: function(xhr) {
				//alert(typeof xhr.responseText);
				Pages.insert(jQuery.parseJSON(xhr.responseText));     
			},
			onFailure: function(xhr) {
				console.log("ERROR: Couldn't retrieve app json - " + appid);
				console.log(xhr);
			}
		});
	},
	
	// getForm
	getForm: function(formName){
		Ajax.get("data/forms/" + formName + ".html",{
			onSuccess: function(xhr){
				Pages.changeContent(xhr.responseText);
			},
			onFailure: function(xhr){
				console.log("ERROR: Couldn't retrieve form - " + formName);
				console.log(xhr);
			}
		});
	},
	
	// insert - create page from HTML template using app json file.
	insert: function(json) {
		var j = json;
		
		var parseLinks = function(linkArr){
			if(!linkArr || linkArr.length <= 0){
				return "BLAH";
			}
			
			var htmlStr = "<ul>";
			
			for(var i = 0; i < linkArr.length; i++){
				var l = linkArr[i] || null;
				if(l && l.label && l.url){
					htmlStr += "<li><a href=\""+l.url+"\">"+l.label+"</li>";
				}
			}
			
			htmlStr += "</ul>";
			
			return htmlStr;
		};
		
		//Fetch template and replace values.
		Pages.getTemplate("app",function(template){
			var screensText;
			
			var t = template
				.replace("#{ICON}", j.icon)
				.replace("#{TITLE}", j.name)
				.replace("#{DESC}", j.description)
				.replace("#{LINKS}", (j.links && parseLinks(j.links)))
			;
			Pages.changeContent(t, function(){
				// Insert screens
				if(j.screenshots && j.screenshots.length > 0) {
					var screens = document.createElement("div");
					var viewer = new ImageViewer({ images: j.screenshots });
					viewer.renderInto(document.getElementById("App-Screens"));
				} else {
					screensText = "NO SCREENSHOTS";
				}
			});
			
			//TODO: parse and display.
		});
	},
	
	// change
	changeContent: function(ct, cb){
		$content.hide(function(){
			$menu.slideUp(function(){
				
				$("#Content")[0].innerHTML = ct;
				$content.show();
				if(cb){
					cb();
				}
			}, true);
		});
	},
	
	getTemplate: function(name, cb){
		//alert("RESPONSE: " + JSON.stringify(xhr));
		Ajax.get("data/templates/"+name+".html", {
			onSuccess: function(xhr){
				//alert("RESPONSE: " + JSON.stringify(xhr));
				if(typeof cb === "function") {
					cb(xhr.responseText); //Callback if found.
				}
			},
			onFailure: function(xhr) {
				alert("ERROR: " + JSON.stringify(xhr));
			}
		});
		
	},

	getPage: function(name, cb){
		Ajax.get("data/pages/"+name+".html", {
			onSuccess: function(xhr){
				Pages.changeContent(xhr.responseText);
				if(typeof cb === "function") { cb(); }
			},
			onFailure: function(xhr){
				alert("ERROR: " + JSON.stringify(xhr));
			}
		});	
	}
};

