

if ( this.Concept == null )
	Concept = {};

Concept.Personalization = {};
Concept.Personalization = 
{

	/** The XML Callback passed back from asyncRequest **/
	xmlCallback:Object,
	
	/** The id of the DIV that we use for form rendering. **/
	divId:String,
	
	/** The callback object upon which we invoke update methods. **/
	formCallbackObject:Object,

	/** The name of the callback function that we invoke on a form change. **/
	formCallbackFunction:String,
	
	/** An array of TextPersonalization objects **/
	textPersonalizations:Array,
	
	/**
	 * Generate a form for personalization.
	 * @param divId The id of the DIV object that we insert our form into.
	 * @param configXMLURL The URL to the XML that we use for configuration information.
	 * @param formCallbackObject The object that receives callback events when the form values change.
	 * @param formCallbackFunction The function that we invoke on a callback.
	 */
	generateUI:function( divId, configXMLURL, formCallbackObject, formCallbackFunction )
	{

		this.divId = divId;
		this.formCallbackObject = formCallbackObject;
		this.formCallbackFunction = formCallbackFunction;
	
		
		// invoke the call to the Async request object.
		var callback =
		{
		  success:this.handleXMLSuccess,
		  failure:this.handleXMLFailure,
		  scope: this
		}
		this.xmlCallback = YAHOO.util.Connect.asyncRequest('GET', configXMLURL, callback, null);
		//Yahoo.util.Connect.abort(this.cObj);
	},

	/**
	 * Get the current state of the form as a Javascript object.
	 * @return An Array of objects. Each object has the following fields:
	 * 		- id:  The identifier of the text id whose properties are being described.
	 *      - text: The current text value.
	 *      - color: The current RGB color value as a number
	 *      - fontId: The identifier of the current font.
	 */
	getFormState:function( sDivId )
	{

		var oDIV = document.getElementById( sDivId );
		
		var cFIELDSET = oDIV.getElementsByTagName( 'FIELDSET' );
		
		var aResults = new Array();

		var sId;

		var sText;
		var oFont;
		var sFont;
		var sColor;

		for ( var i=0 ; i<cFIELDSET.length ; i++ )
		{
			if ( cFIELDSET[i].textId )
			{
				sId = cFIELDSET[i].textId;

				sText = document.getElementById( 'cr_' + sId + '_text' ).value;

				oFont = document.getElementById( 'cr_' + sId + '_font' );
				sFont = oFont.options[oFont.selectedIndex].value;

				sColor = document.getElementById( 'cr_' + sId + '_color' ).selectedColor;

				aResults.push(  { id:sId, text:sText, color:sColor, fontId:sFont } );
			}
		}
		//res.push(  { id:8, text:"Daniel", color:16750950, fontId:2 } );
		//res.push(  { id:10, text:"Brian", color:0, fontId:2 } );
		return aResults;
	},


	/**
	 * Callback indicating there was a failure in our XML request.
	 */ 
	handleXMLFailure:function()
	{
		// We silently fail as its possibly no personalization info was published.
		//alert("Call to personalization failed!");
	},

	/**
	 * Callback indicating we successfully received an XML message.
	 */
	handleXMLSuccess:function( params )
	{
		this.parseXML( params.responseXML.getElementsByTagName("personalization_config")[0] );
		this.generateForm();
	},


	/**
	 * Parse the personalization XML and generate the data model.
	 */
	parseXML:function( configNode )
	{
		this.textPersonalizations = new Array();
		
		var node;
		var cNode;
		for ( var i=0;i<configNode.childNodes.length;i++ )
		{
			try 
			{ 
				node = configNode.childNodes[i];
				if ( node.tagName == "text_personalization" )
				{
					// create the tp object.
					var tp = new Object();
					this.textPersonalizations.push( tp );
					
					tp.id = node.getAttribute("id");
					tp.displayName = node.getAttribute("display_name");
					tp.maxChars = Number( node.getAttribute("max_chars") );
					tp.defaultFontId = Number( node.getAttribute("default_font_id") );
					tp.availableColors = (node.getAttribute("available_colors")).split(",");
					tp.defaultText = node.getAttribute("default_text");
					var defaultColor = node.getAttribute("default_color");
					if ( defaultColor != null )
						tp.defaultColor = defaultColor;
					else
						tp.defaultColor = tp.availableColors[0];
					
					// add in the fonts
					tp.availableFonts = new Array();
					for ( var j=0;j<node.childNodes.length;j++ )
					{
						cNode = node.childNodes[j];
						if ( cNode.tagName == "font" )
						{
							tp.availableFonts.push( { id:cNode.getAttribute("id"), displayName:cNode.getAttribute("display_name") } );
						}
					}
				}
			}
			catch (e)
			{
				alert("parseXML exception: " + e);
			}
		}
	},

	generateForm:function()
	{
		//alert("creating form: " + this.config.textPersonalizations[0].availableFonts.length );
		try {
			var div = document.getElementById( this.divId );
			
			var form = document.createElement("form");
			form.className = "cr_personalization";
			div.appendChild( form );
			
			//var textElem;
			var tp;

			var fieldset;
			var legend;

			var inputLabel;
			var inputLabelMax;
			var input;

			var selectLabel;
			var select;
			var defaultFont;
			
			var colorsLabel;
			var colors;
			var colorsHTML;
			var defaultColor;

			for ( var i=0;i<this.textPersonalizations.length;i++ )
			{	
				tp = this.textPersonalizations[i];

				// FIELDSET wraps around text personalization options (text input, font selection, and color swatches)
				fieldset = document.createElement("fieldset");
				fieldset.textId = tp.id;
				form.appendChild( fieldset );

				// LEGEND appears on screen as label for fieldset
				legend = document.createElement("legend");
				legend.innerHTML = tp.displayName;
				fieldset.appendChild( legend );

				// INPUT LABEL
				inputLabel = document.createElement("label");
				inputLabel.setAttribute('for',"cr_" + tp.id + "_text");
				inputLabel.className = "label";
				inputLabel.innerHTML = "TEXT ";
				inputLabelMax = document.createElement("span");
				inputLabelMax.id = "cr_" + tp.id + "_textLabelMax";
				inputLabelMax.innerHTML =  "("+ tp.maxChars +" chars max)";
				
				// make sure to check that the default text isn't at the max already
				inputLabelMax.className = ( tp.defaultText.length >= tp.maxChars ) ? "maxReached" : "";
				
				inputLabel.appendChild( inputLabelMax );
				fieldset.appendChild( inputLabel );

				// INPUT captures text used to personalize display
				input = document.createElement("input");
				input.textId = tp.id;
				input.id = "cr_" + tp.id + "_text";
				input.setAttribute('autocomplete','off');
				input.maxLength = tp.maxChars;
				fieldset.appendChild( input );

				input.handler = this;
				input.value = tp.defaultText;
				input.onfocus = function() { this.onkeyup = this.handler.controlChanged; }
				input.onblur = function() { this.onkeyup = null; }

				// SELECT LABEL
				if (tp.availableFonts.length > 1)
				{
					selectLabel = document.createElement("label");
					selectLabel.setAttribute('for',"cr_" + tp.id + "_font");
					selectLabel.className = "label";
					selectLabel.innerHTML = "FONTS";
					fieldset.appendChild( selectLabel );
				}
				
				// SELECT box contains font selection options
				select = document.createElement("select");
				select.textId = tp.id;
				select.id = "cr_" + tp.id + "_font";
				select.handler = this;
				select.onchange = this.controlChanged;
				fieldset.appendChild( select );

				// if there is only one font, hide the font selection box
				if (tp.availableFonts.length <= 1) { select.style.display = "none"; }
				
				for ( var iOptions=0 ; iOptions<tp.availableFonts.length ; iOptions++ )
				{
					select.options[iOptions] = new Option( tp.availableFonts[iOptions].displayName , tp.availableFonts[iOptions].id );
					if (tp.availableFonts[iOptions].id == tp.defaultFontId) { select.options[iOptions].selected = true }
				}

				// COLORS LABEL
				if (tp.availableColors.length > 1)
				{
					colorsLabel = document.createElement("label");
					colorsLabel.setAttribute('for',"cr_" + tp.id + "_color");
					colorsLabel.className = "label";
					colorsLabel.innerHTML = "COLORS";
					fieldset.appendChild( colorsLabel );
				}

				// COLORS <div> contains color swatch options
				colors = document.createElement("div");
				colors.textId = tp.id;
				colors.id = "cr_" + tp.id + "_color";
				colors.selectedColor = tp.defaultColor;
				fieldset.appendChild( colors );

				// if there is only one color, hide the color swatches DIV
				if (tp.availableColors.length <= 1) { colors.style.display = "none"; }

				colorsHTML = '';
				
				for ( var iColors=0 ; iColors<tp.availableColors.length ; iColors++ )
				{
					defaultColor = '';
					if (tp.availableColors[iColors] == tp.defaultColor) { defaultColor = 'cr_selected'; }
					colorsHTML += '<a id="cr_'+ tp.id +'_color_'+tp.availableColors[iColors]+'" onclick="Concept.Personalization.selectColor(\''+colors.id+'\',\''+tp.availableColors[iColors]+'\');return false" onfocus="blur()" href="#" class="'+defaultColor+'"><span style="background-color:'+this.rgbValToHex(tp.availableColors[iColors])+'"></span></a>\n'
				}

				colorsHTML += '<br clear="all" />';
				colors.innerHTML = colorsHTML;
			}
			
		}
		catch (e)
		{
			alert("generateForm exception: " + e);
		}
	},
	
	
	/**
	 * Change selected swatch. Store changed value.
	 */
	selectColor:function( sParentId , sColorValue )
	{
		var oColor = document.getElementById( sParentId );

		var oPreviousSwatch = document.getElementById( sParentId + '_' + oColor.selectedColor );
		oPreviousSwatch.className = '';

		var oSelectedSwatch = document.getElementById( sParentId + '_' + sColorValue );
		oSelectedSwatch.className = 'cr_selected';
		
		oColor.selectedColor = sColorValue;
		
		// propogate the changes back to Flash
		this.onFormChanged( oColor.textId );
	},
	
	
	/**
	 * Callback from a form element. Note that "this" is the actual input control.
	 */
	controlChanged:function()
	{
		if (this.maxLength)
		{
			if (this.maxLength == this.value.length)
			{
				document.getElementById(this.id + "LabelMax").className = "maxReached";
			}
			else
			{
				document.getElementById(this.id + "LabelMax").className = "";
			}
		}
		this.handler.onFormChanged( this.textId );
	},
	
	onFormChanged:function( textId )
	{
		if ( this.formCallbackObject != null &&  this.formCallbackFunction != null )
		{
			this.formCallbackFunction.apply( this.formCallbackObject, [ textId ] );
		}
	}, 
      
     rgbValToHex:function( num )  
     {  
            var val = String( this.toHex( num ) ); 
            var len = 6 - val.length; 
            for ( var i=0;i<len;i++ ) 
            { 
                 val = "0" + val; 
            } 
          return "#" + val;  
     }, 
      
     toHex:function(d) { 
        var r = d % 16; 
        if(d-r==0) {return this.toChar(r);} 
        else {return this.toHex( (d-r)/16 )+this.toChar(r);} 
     }, 
      
     hexChars:"0123456789ABCDEF", 
 
     toChar:function(n) { 
             return this.hexChars.charAt(n); 
     }
	
}




