/*
 * Authored by Aaron Reynolds 2011 
 * 
 * 
 * 
 */
var FunkyControls = {};


FunkyControls.DefaultText = Class.create({

	initialize: function()
	{
		this.arControlIds = [];
		this.arValues = [];
	},

	add: function(ctrlId, defText)
	{
		// Add to our arrays and then setup events
		this.arControlIds.push(ctrlId);
		this.arValues.push(defText);

		$(ctrlId).observe( 'focus', this.onFocus.bindAsEventListener(this) );
		$(ctrlId).observe( 'blur', this.onBlur.bindAsEventListener(this) );
	},

	addRange: function (arCtrls, arVals)
	{
		arCtrls.each
		(
	    	function(s, index) 
	    	{ 
    	    	if ($(s)) 
    	    	{ 
    	    		this.arControlIds.push(s);
    	    		$(s).observe( 'focus', this.onFocus.bindAsEventListener(this) );
    	    		$(s).observe( 'blur', this.onBlur.bindAsEventListener(this) );

    	    		this.arValues.push(arVals[index]);
    	    	}
	    	}, this
	    );		
	},

	onFocus: function(eventArgs)
	{
		var elm = Event.element(eventArgs);
		var ap = this.getArrayPosition(this.arControlIds, elm.id);
		if (ap == -1) return;
		
		if ($(elm.id).value == this.arValues[ap])
			$(elm.id).value = '';
	},

	onBlur: function(eventArgs)
	{
		var elm = Event.element(eventArgs);
		var ap = this.getArrayPosition(this.arControlIds, elm.id);
		if (ap == -1) return;
		
		if ($(elm.id).value == '')
			$(elm.id).value = this.arValues[ap];
	},

	getArrayPosition: function(array, value)
	{
		var result = -1;
		array.each(function (item, index) { if (item == value) { result = index; throw $break; }});
		return result;
	}
});


FunkyControls.FileUpload = Class.create({

	initialize: function(optionsIn)
	{
		this.options = Object.extend(
		{
			controlId:				null

		}, 
		optionsIn || {});
		
		if ( $(this.options.controlId) == undefined )
    		return;

		this.controlNewId = "fc_" + this.options.controlId;
		this.recreateOverlay();
		this.setupEvents();
	},

	recreateOverlay: function()
	{
		// Create Replacement Html for Overlay Control
		var fc_upload_template_overlay = 
			"<div id=\"" + this.controlNewId + "\" class=\"fc_upload_container\">" + 
				"<div class=\"fc_upload_standard_control_container\">" + 
				"</div>" + 
				"<div class=\"fc_upload_revised_control_container\">" + 
					"<input name=\"" + this.controlNewId + "_lblFileName\" class=\"fc_upload_label\" readonly=\"readonly\" value=\"&nbsp;\" type=\"text\">" + 
					"<div class=\"fc_upload_browse_btn\">" + 
						"<a name=\"" + this.controlNewId + "_btn\"></a>" + 
					"</div>" + 
				"</div>" + 
			"</div>";

		// Add the Overlay to the Html
		$(this.options.controlId).insert ( { 'after': fc_upload_template_overlay } );

		// Get the original control
		var tempCtrl = $(this.options.controlId).remove();
		
		// Move the original control into position
		$(this.controlNewId).down('div.fc_upload_standard_control_container').insert 
			( { 'top': tempCtrl } );

		// Set styles on original control
		$( this.options.controlId ).addClassName('fc_upload_standard_control');

		if ( ! $(this.options.controlId).visible() )
			$(this.controlNewId).hide();
	},

	setupEvents: function()
	{
		$(this.options.controlId).observe
			( 'change', this.onFUPChange.bindAsEventListener(this) );

		//$(this.controlNewId).down('div.fc_upload_browse_btn').observe
		$(this.options.controlId).observe
			( 'mouseover', this.onFUPMouseOver.bindAsEventListener(this) );

		//$(this.controlNewId).down('div.fc_upload_browse_btn').observe
		$(this.options.controlId).observe
			( 'mouseout', this.onFUPMouseOut.bindAsEventListener(this) );
	},

	onFUPMouseOver: function(eventArgs)
    {
		var ctrlUpload = Event.element(eventArgs);
		var btn = 
        	$(this.controlNewId).down('div.fc_upload_revised_control_container').down('div').className = 'fc_upload_browse_btn_active';
    },
    
	onFUPMouseOut: function(eventArgs)
    {
		var ctrlUpload = Event.element(eventArgs);
		var btn = 
        	$(this.controlNewId).down('div.fc_upload_revised_control_container').down('div').className = 'fc_upload_browse_btn';
    },
    
    onFUPChange: function(eventArgs)
    {
    	var ctrlUpload = Event.element(eventArgs);
        var lblFileName = 
        	$(this.controlNewId).down('div.fc_upload_revised_control_container').down('input');

        var file_path = ctrlUpload.value;
        if (file_path != null && file_path != '')
		{
			var i = file_path.lastIndexOf('/');
			if (i == -1) { i = file_path.lastIndexOf('\\'); }
			i++;
			
			if (i > 0 && i < file_path.length)
			{
				file_path = file_path.substr(i);
			}
		}
		$(lblFileName).value = file_path;
    }
});


FunkyControls.DropDowns = [];

FunkyControls.DropDown = Class.create({

	initialize: function(optionsIn)
	{
		this.options = Object.extend(
		{
			controlId:				null
		}, 
		optionsIn || {});
		
		if ( $(this.options.controlId) == undefined )
    		return;

		this.controlNewId = "fc_" + this.options.controlId;
		this.recreateOverlay();			
		this.setupEvents();
		
		var selectedValue = this.getSelectedValue();
		this.showSelectedValue(selectedValue);
		
		FunkyControls.DropDowns.push ( this );
	},
	
	getSelectedValue: function()
	{
		var options = $( this.options.controlId ).select('option');
		var selectedValue = null;
		
		if (options.size() > 0)
		{
			options.each(
				function (ctrl, idx)
				{
					if ( $( ctrl ).selected )
						selectedValue = $( ctrl ).value;						
				}, this);
			
			if (selectedValue == null)
				selectedValue = $(options[0]).value;
		}
		
		return selectedValue;
	},
	
	showSelectedValue: function(selectedValue)
	{
		$( this.options.controlId ).descendants().each
		(
				function (tag, idx)
				{					
					if ( $(tag).readAttribute('value') == selectedValue )
					{
						// Select on original control
						$(tag).selected = true;
						
						// Set label on overlay
						$( this.controlNewId ).down('div.fc_dropdown_overlayMiddle')
							.update( $(tag).innerHTML );
					}
				}, this
		);
		
		// Remove selection class from the overlay
		$( this.controlNewId + "__dropdown_container" ).childElements().each(
			function (ctrl, idx)
			{
				ctrl.removeClassName ('selected');						
			});
		
		// Add selection class to the overlay
		if (selectedValue != null)
			$( this.controlNewId + "__dropdown_element_" + selectedValue ).addClassName ('selected');
	},
	
	recreateOverlay: function()
	{       	   		
    	// Hide the Original Control
    	$(this.options.controlId).hide();
    	
		// Create Replacement Html for Overlay Control
		var fc_dropdown_template_overlay = 
			"<div id=\"" + this.controlNewId + "\" class=\"fc_dropdown_overlayContainer\">" + 
			"<div class=\"fc_dropdown_overlayLeft\"></div>" + 
			"<div class=\"fc_dropdown_overlayMiddle\"></div>" + 
			"<div class=\"fc_dropdown_overlayButton\"></div>" + 
			"</div>";

		// Create Html for drop-down part of control
		var fc_dropdown_template_elementContainer = 
    		"<div id=\"" + this.controlNewId + "__dropdown_container\" class=\"fc_dropdown_elements_container\">" + 
    		"\r\n--INNER--" + 
    		"</div>";
		

		// Create Html for each option
		var options = this.renderChildElementsOf( $( this.options.controlId ), 0 );
		var iCount = $( this.options.controlId ).descendants().size();
		
		// Put into the template
		options = fc_dropdown_template_elementContainer.replace('--INNER--', options);


		// If not already defined in DOM
		if ( $(this.options.controlNewId) == undefined )
		{
    		// Add the Overlay to the Html
    		$(this.options.controlId).insert ( { 'after': fc_dropdown_template_overlay } );
		}
		else
		{
			// Update the LABEL shown
		}

		// Remove the old Drop-Down section
		if ( $( this.controlNewId + "__dropdown_container" ) != undefined )
			$( this.controlNewId + "__dropdown_container" ).remove();
		
		// Add the new Drop-Down section
		$(this.controlNewId).insert ( { 'bottom': options } );

		// If less than 5 options then limit height of drop-down
		var dd_height = iCount < 5 ? iCount * 25 : 125;
		
		// Set styles on options container
		$( this.controlNewId + "__dropdown_container" ).setStyle(
				{
    				position: 'absolute', 
    				top: 0,
    				left: 0,
    				height: dd_height + 'px'
				});

		// Hide, once created - could be rendered hidden
		$( this.controlNewId + "__dropdown_container" ).hide();
	},
	
	renderChildElementsOf: function(elmParent, depth)
	{		
		var result = "";
		var fc_dropdown_template_element_group = 
    		"<div class=\"\" title=\"--TITLE--\">" + 
    		"--INNER--" + 
    		"</div>\r\n";
		var fc_dropdown_template_element = 
    		"<div id=\"" + this.controlNewId + "__dropdown_element_--INDEX--\" class=\"\" title=\"--TITLE--\">" + 
    		"--INNER--" + 
    		"</div>\r\n";
		
		var children = $( elmParent ).childElements();
		
		children.each
		(
			function (tag, idx)
			{
				var strTagName = $(tag).tagName.toLowerCase();
				
				if ( strTagName == 'optgroup' )
				{
					var lblOptGroup = $(tag).readAttribute('label');
					
					result += 
						fc_dropdown_template_element_group
							.replace('--TITLE--', lblOptGroup)
							.replace('--INNER--', "  ".times(depth) + '<b>' + lblOptGroup + '</b>');
					
					result += this.renderChildElementsOf( $(tag), depth + 1 );
				}
				else if ( strTagName == 'option' )
				{
					var val = $(tag).readAttribute('value');
					var label = $(tag).innerHTML;
				
					result += 
						fc_dropdown_template_element.replace('--INDEX--', val)
							.replace('--TITLE--', label)
							.replace('--INNER--', "    ".times(depth) + label);	
				}
				else alert ( strTagName );
			}, this
		);
		
		return result;
	},

	setupEvents: function()
	{
		$(this.controlNewId).down('div.fc_dropdown_overlayButton').observe( 'click', this.onButtonClick.bindAsEventListener(this) );
		var subItems = $( this.controlNewId + "__dropdown_container" ).descendants();

		// Observe all clicks on the options container
		$( this.controlNewId + "__dropdown_container" ).observe( 'click', this.onOptionClick.bindAsEventListener(this) );
	},
	
	hide: function()
	{
		$( this.controlNewId + "__dropdown_container" ).hide();
	},
	
	show: function()
	{
		// Hide all others
		FunkyControls.DropDowns.each
		(
				function (item, idx)
				{
					$( item.controlNewId + "__dropdown_container" ).hide();
				}
		);
		
		$( this.controlNewId + "__dropdown_container" ).show();
	},

	onButtonClick: function()
	{
    	if ( $( this.controlNewId + "__dropdown_container" ).visible() )
    		this.hide();
    	else
    		this.show();
	},

	onOptionClick: function(evt)
	{
		var ctrl = Event.element(evt);

		if ( ctrl.id == undefined || ctrl.id == '' )
			return;
		
		var selectedValue = ctrl.id.replace( this.controlNewId + "__dropdown_element_", "" );
				
		this.showSelectedValue(selectedValue);
		
		// Hide the drop-down elements of the overlay
		this.hide();
	},
	
	invalidationMarker: function(isInvalid, className)
	{
		if ( isInvalid )
			$( this.controlNewId ).addClassName( className );
		else
			$( this.controlNewId ).removeClassName( className );
	}
});


// For Live:

var fc_defaultText = new FunkyControls.DefaultText();

