/*
 * Cellblock general-purpose management console, a component of
 * the Gloto Platform.  See www.gloto.com for more information,
 * terms, and licensing.
 *
 * Copyright (C) 2005-2010, Gloto Corp.
 * http://www.cellblock.com/terms.htm
 */

function Config()
{
	var config = this;

	// Support context override via URL parameter "context", defaults to ugc.gloto.com
	var defaultContext = "smp.gloto.com"; // "ugc.gloto.com"
	var context = ( getUrlParameter("context") ? getUrlParameter("context") : defaultContext );

	var initObj = {
	 	context: "http://" + context,
	 	apiKey: "http://smp.gloto.com",
		realm: getUrlParameter("realm"),
		id: getUrlParameter("cb"),
		frame: getUrlParameter("frame"),
		adminMode: false, // Will be auto-filled on login
		user: null, // Will be auto-filled on login,
		spamId: null, // Will be auto-filled as needed by util.initCellblockNavigation
		receiptEnabled: false, // Receipts enabled by default for new cellblocks? Boolean: true or false
		receiptSubject: "Default Subject", // Edit this to your liking
		receiptMessage: "Default response message.", // Edit this to your liking
		attributes: {},
		feeds: {}
	};

	function getUrlParameter( name )
	{
		name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
		var regexS = "[\\?&]"+name+"=([^&#]*)";
		var regex = new RegExp( regexS );
		var results = regex.exec( window.location.href );
		if( results === null )
			return null;
		else
			return results[1];
	}

	this.isAdmin = function(){
		return config.get("adminMode");
	};

	// Getter Methods

	this.get = function( key )
	{
		return initObj[key];
	};

	this.getInit = function()
	{
		var foo = initObj;
		foo.publicUrl = config.getPublicUrl();
		return foo;
	};

	this.getContext = function()
	{
		return config.get("context");
	};

	this.getPublicUrl = function( suffix ){
		var base = (config.getContext().indexOf('dev')<0)?"ugc.gloto.com":"10.4.48.128:8080/gloto";
		suffix = (suffix != null ) ? "/" + suffix : "";
		return "http://" + base + suffix;
	};

	this.getContextDisplay = function( clean )
	{
		var context = config.get("context");
		if( clean != null && clean ){
			return context.substring( 7, context.length );
		}else{
			if( context.indexOf(defaultContext) ){
				return "";
			}

			return " (" + context.substring( 7, context.length ) + ")";
		}
	};

	this.getApiKey = function()
	{
		return config.get("apiKey");
	};

	this.getRealm = function()
	{
		return config.get("realm");
	};

	this.getId = function()
	{
		return config.get("id");
	};

	this.getFeeds = function(){
		return config.get("feeds")[config.getId()];
	};

	this.hasFeeds = function( aka ){
		var feeds = config.get("feeds");
		aka = aka || config.getId();
		return (feeds != null && feeds[aka] != null && feeds[aka].length > 0 );
	};

	this.isFeed = function( aka ){
		var feeds = config.get("feeds");
		for( var key in feeds ){
			if( util.indexOf( feeds[key], aka ) >= 0 ){
				return true;
			}
		}
		return false;
	};

	// Generic Setter

	this.set = function( key, value )
	{
		initObj[key] = value;
	};

	this.getCellblockServiceUrl = function(){
		var context = config.getContextDisplay(true);
		return "http://" + context + "/ugc/api/rest";
	};

	this.getGeoServiceUrl = function(){
		var context = config.getContextDisplay(true);
		return "http://" + context + "/geo/api/rest";
	};

	this.init = function(){
		config.getRealmAttributes();
		api.getRealmCellblocks(0, 10, config.setFeedInfo);
	};

	this.setRealmAttributes = function( data ){
		if( util.valid( data ) ){
			var attributeList = data.attributes;
			var attributeMap = {};
			for( var i = 0; i < attributeList.length; i++ ){
				for( var key in attributeList[i] ){
					var name = attributeList[i].name;
					var value = attributeList[i].value;
					attributeMap[name] = value;
				}
			}

			config.set( "attributes", attributeMap );
			config.initConfigForm();
		}else{
			util.error( data );
		}
	};

	this.setFeedInfo = function( data ){
		if( util.valid( data ) ){
			var cellblocks = data.cellblocks;
			var feedInfo = util.getElement("feedInfo");
			util.clear( feedInfo );
			for( var i = 0; i < cellblocks.length; i++ ){
				var cellblock = cellblocks[i];
				feedInfo.innerHTML += "<p>" + cellblock.name + ": " + cellblock.id + "</p>";
			}
		}else{
			util.error( data );
		}
	};

	this.getRealmAttributes = function( ){
		api.getRealmAttributeValues( config.setRealmAttributes );
	};

	this.initConfigForm = function(){
		var form = document.configForm;
		var attributes = config.get("attributes");
		for( var key in attributes ){
			if( form[key] != null ){
				form[key].value = attributes[key];
			}
		}
	};

	this.saveConfig = function( form ){
		for( var i = 0; i < form.length; i++ ){
			var input = form[i];
			var type = input.type.toLowerCase();
			if( type != "submit" && type != "hidden" && type != "button" ){
				api.setRealmAttribute( input.name, input.value, function( data ){
					if( util.valid( data ) ){
						util.console.println("Saved: Annotation Settings");
					}else{
						util.error( data );
					}
				});
			}
		}
	};

	this.setSkinMap = function( map, callback ){
		api.setRealmAttribute( "skinMap", map, function( data ){
			if( util.valid( data ) ){
				util.console.println("Skin binding saved");
				if( callback ){
					callback();
				}
			}else{
				util.error( data );
			}
		});
	};

	this.updateSkinMap = function( id, skins ){
		api.getRealmAttributeValue("skinMap", function(data){
			if( util.valid( data ) ){
				var value = data.value;
				if( value == "" ){
					value = "{}";
				}
				var skinMap = util.stringToObject( value ); // Convert to object
				skinMap[id] = skins; // Update object
				skinMap = config.mapToString( skinMap ); // Revert to string for save
				config.setSkinMap( skinMap );
			}else{
				if( data.errorCode == "305" ){
					// Attribute definition not found
					config.setSkinMap( "" );
				}else{
					util.error( data );
				}
			}
		});
	};

	this.setSiteMap = function( map, callback ){
		api.setRealmAttribute( "siteMap", map, function( data ){
			if( util.valid( data ) ){
				util.console.println("Sites binding saved");
				if( callback ){
					callback();
				}
			}else{
				util.error( data );
			}
		});
	};

	this.updateSiteMap = function( id, sites ){
		api.getRealmAttributeValue("siteMap", function(data){
			if( util.valid( data ) ){
				var value = data.value;
				if( value == "" ){
					value = "{}";
				}
				var siteMap = util.stringToObject( value ); // Convert to object
				siteMap[id] = sites; // Update object
				siteMap = config.mapToString( siteMap ); // Revert to string for save
				config.setSiteMap( siteMap );
			}else{
				if( data.errorCode == "305" ){
					// Attribute definition not found
					config.setSiteMap( "" );
				}else{
					util.error( data );
				}
			}
		});
	};

	this.mapToString = function( map ){
		var str = "{";
		var keyCount = 0;
		for( var key in map ){
			var items = map[key];
			if( keyCount > 0){
				str += ",";
			}

			keyCount++;

			str += "\"" + key + "\":[";
			for( var i = 0; i < items.length; i++ ){
				str += "\"" + items[i] + "\"";
				if( i+1 < items.length ){
					str += ",";
				}
			}
			str += "]";
		}
		str += "}";
		return str;
	};
}

// Create config
var config = new Config();
