// FIXME: make this into a js file and FIX THE OTHER FORMS.

/**
 * Sets up areas to be visible/invisible depending on value of select
 */
function addToggleSelect( field, valueToArea ) {
	field.onchange = function() {
		for ( var ifThisValue in valueToArea ) {
			var area = valueToArea[ifThisValue];
			
			if ( this.value == ifThisValue ) {
				// Value is for me.
				toggleClass( area, "invisible", "off" );
			} else {
				// Value isn't for me
				toggleClass( area, "invisible", "on" );
			}
		}
	};
	
	// Make sure things are as they need to be.
	field.onchange();
}



// ==================================================================
/**
 * Sets up areas to be visible/invisible depending on value of radio / checkbox
 */
function addToggleRadio( fieldList, valueToArea ) {
	for ( var i=0; i < fieldList.length; i++ ) {
		var field = fieldList.item(i);
		
		field.onclick = function() {
			var currentValue = getCurrentValueOfRadio(fieldList);
			selectRadio(currentValue, valueToArea);
		};
	}
	
	var currentValue = getCurrentValueOfRadio(fieldList);
	selectRadio(currentValue, valueToArea);
}
function getCurrentValueOfRadio(fieldList) {
	var value = null;
	for ( var i=0; i < fieldList.length; i++ ) {
		var field = fieldList.item(i);
		if ( field.checked ) {
			value = field.value;
			// break; // commented out so it works with selectManyCheckbox
		}
	}
	return value;
}
function selectRadio(valueWant, valueToArea) {
	for ( var value in valueToArea ) {
		var area = valueToArea[value];
		if ( value == valueWant) {
			// Visible
			toggleClass( area, "invisible", "off" );
		} else {
			toggleClass( area, "invisible", "on" );
		}
	}
}
// ==================================================================

/* ==========================================================================================
 * Tomahawk's inputDate component can ouput in any timezone you specify... but you can't have
 * it be the user's. This JS class will switch the output to take input in the users
 * timezone.
 * It REQUIRES the inputDate to be in GMT to work. Eg
 *
 * <h:form id="test">
 *	 <t:inputDate id="availableFrom"
 *					value="#{viewProvider.provider.availableFrom}"
 *					timeZone="GMT"
 *					/>
 * </h:form>
 *
 * To use the class then do
 *   new TomahawkInputDateConvertFromGMTToLocal("test:availableFrom");
 * NOTE: The arguement must be the full id.
 *
 * What this does is create new input fields, and adds the CSS class 'gmtField' to the existing ones. With CSS you should hide the existing ones.
 * Users use the new ones we create, and onchange we update the original. This way what comes and is sent to the server is always GMT.
 *
 * NOTE: If improve on.. you should make it grab document.getElementById(this.name) which contains everything.. duplicate that..
 *			that way everything isn't mix together...
 * NOTE: Currently does NOT work with the popup calendar...
 *
 */
function TomahawkInputDateConvertFromGMTToLocal(name, defaultDate) {
	this.name = name;
	this.init(defaultDate);
}
TomahawkInputDateConvertFromGMTToLocal.prototype = {
	init : function(defaultDate) {
		var span = document.getElementById(this.name);
		if ( span == undefined ) {
			alert("Can not convert GMT to local. Field name given doesn't seem to exist: "+ this.name);
			return false;
		}
		
		// Creates references to the fields. NOTE: That not all of these will exists
		this.gmt = {
			day			: document.getElementById(this.name+".day"),
			month		: document.getElementById(this.name+".month"),
			year		: document.getElementById(this.name+".year"),
			hours		: document.getElementById(this.name+".hours"),
			minutes		: document.getElementById(this.name+".minutes"),
			seconds		: document.getElementById(this.name+".seconds"),
			ampm		: document.getElementById(this.name+".ampm")		// -1 = "", 0 = AM, 1 = PM
		};
		
		
		// =======================================================================
		// Create date object
		if ( defaultDate != undefined ) {
			this.date = defaultDate;
		} else {
			this.date = new Date();
			this.date.setUTCMonth(0);
			this.date.setUTCDate(1);
			this.date.setUTCFullYear(1970);
			this.date.setUTCHours(0);
			this.date.setUTCMinutes(0);
			this.date.setUTCSeconds(0);
		}
		
		// Month
		if ( this.gmt.month != undefined && this.gmt.month.value != "" && this.gmt.month.value != -1 ) {
			this.date.setUTCMonth(parseInt(this.gmt.month.options[this.gmt.month.selectedIndex].value) - 1, 10);
		}
		// Day
		if ( this.gmt.day != undefined && this.gmt.day.value != "" ) {
			this.date.setUTCDate(parseInt(this.gmt.day.value, 10));
		}
		// Year
		if ( this.gmt.year != undefined && this.gmt.year.value != "" ) {
			this.date.setUTCFullYear(parseInt(this.gmt.year.value, 10));
		}
		
		// Hours
		if ( this.gmt.hours != undefined && this.gmt.hours.value != "" ) {
			var hoursValue = 0;
			hoursValue = parseInt(this.gmt.hours.value, 10);
			if ( this.gmt.ampm != undefined && this.gmt.ampm.options[this.gmt.ampm.selectedIndex].value == 1 && hoursValue <= 12 /*Just in case someoen enters millitary...*/ ) {
				hoursValue += 12;
			}
			this.date.setUTCHours(hoursValue);
		}
		// Minutes
		if ( this.gmt.minutes != undefined && this.gmt.minutes.value != "" ) {
			this.date.setUTCMinutes(parseInt(this.gmt.minutes.value, 10));
		}
		// Seconds
		if ( this.gmt.seconds != undefined && this.gmt.seconds.value != "" ) {
			this.date.setUTCSeconds(parseInt(this.gmt.seconds.value, 10));
		}
		// Milliseconds
		// No fields.
		this.date.setUTCMilliseconds(0);
		
		// =======================================================================
		// Create local version of fields
		this.local = {};
		if ( this.gmt.month != undefined ) {
			this.local.month = this.createLocalClone(this.gmt.month, "Month");
		}
		if ( this.gmt.day != undefined ) {
			this.local.day = this.createLocalClone(this.gmt.day, "Date");
		}
		if ( this.gmt.year != undefined ) {
			this.local.year = this.createLocalClone(this.gmt.year, "Year");
		}
		if ( this.gmt.hours != undefined ) {
			this.local.hours = this.createLocalClone(this.gmt.hours, "Hours");
		}
		if ( this.gmt.minutes != undefined ) {
			this.local.minutes = this.createLocalClone(this.gmt.minutes, "Minutes");
		}
		if ( this.gmt.seconds != undefined ) {
			this.local.seconds = this.createLocalClone(this.gmt.seconds, "Seconds");
		}
		if ( this.gmt.ampm != undefined ) {
			this.local.ampm = this.createLocalClone(this.gmt.ampm, "ampm");
		}
		
		// =======================================================================
		// Sync values
		this.sync();
	}
	,
	createLocalClone : function(element, whatFor) {
		// Create clone and put in document.
		var clone = element.cloneNode(true);
		clone.id = "LOCAL-" + clone.id;
		clone.name = "LOCAL-" + clone.name;

		element.parentNode.insertBefore( clone, element );
		
		// This specifies what this edits. (Eg 'month', 'year', etc.)
		clone.whatFor = whatFor;
		
		// Add class and disable current field.
		element.className = element.className + ", gmtField";
		//Cannot be donig this. With them disabled the value isn't sent to the server. element.disabled = true;
		
		// Put on change on clone that will update the gmt version
		var thisRef = this;
		clone.onchange = function() { thisRef.localOnchange(this); };
		
		return clone;
	}
	,
	localOnchange : function (element) {
		// ===============================================
		// Determine value
		var value;
		var whatFor = element.whatFor;
		if ( element.options != undefined ) {
			value = parseInt( element.options[element.selectedIndex].value, 10 );
		} else {
			value = parseInt(element.value, 10);
		}
		if ( whatFor == "Month" ) {
			value = value - 1;
		} else if ( whatFor == "Hours" ) {
			if ( this.local.ampm != undefined ) {
				if ( this.local.ampm.options[this.local.ampm.selectedIndex].value == 1 /*PM*/
					&& value >= 1 && value <= 11
					) {
					// PM and its past 
					value = value + 12;
				} else if ( this.local.ampm.options[this.local.ampm.selectedIndex].value == 0 /*AM*/
					&& value == 12
				) {
					// AM and 12... so we go up to 24 which will cause the code below to set the time to 11:59 PM
					value = value + 12;
				}
			}
			
			if ( value >= 24 ) {
				// We don't let them enter a value that will cause the day to rollover. One reason we don't is because if we are only displaying
				// time fields..and not date (day,month,year) we don't want the user to accidently change which day it is.
				value = 23;
				
				// We also need to update the other fields.
				if ( this.local.minutes != undefined )
					this.date.setMinutes(59);
				if ( this.local.seconds != undefined )
					this.date.setSeconds(59);
			}
			
			whatFor = "Hours";
		} else if ( whatFor == "ampm" ) {
			/*
			var hours = this.date.getHours();
			if ( value == 1 ) {
				// PM
				if ( hours < 12 ) {
					this.date.setHours( hours + 12 );
				}
			} else {
				// AM
				if ( hours > 12 ) {
					this.date.setHours( hours - 12 );
				} else if ( hours == 12 ) {
					this.date.setHours( 24 );
				}
			}
			*/
			this.local.hours.onchange();	// We cause onchange to be called..which triggers updating.
			whatFor = undefined;
		}
		
		// ===============================================
		if (whatFor != undefined) {
			// Determine value
			
			var func = eval("this.date.set"+ whatFor);
			func.call(this.date, value);
			
			this.sync();
		}
		
	}
	, 
	/**
	 * Sets the local and GMT field valued based on this.date
	 */
	sync : function() {
		if ( this.gmt.month != undefined ) {
			this._setDropDownValue(this.gmt.month, this.date.getUTCMonth()+1);
			this._setDropDownValue(this.local.month, this.date.getMonth()+1);
		}
		if ( this.gmt.day != undefined ) {
			this.gmt.day.value = this.date.getUTCDate();
			this.local.day.value = this.date.getDate();
		}
		if ( this.gmt.year != undefined ) {
			this.gmt.year.value = this.date.getUTCFullYear();
			this.local.year.value = this.date.getFullYear();
		}
		
		
		if ( this.gmt.hours != undefined ) {
			var value = this.date.getUTCHours();
			if ( this.gmt.ampm != undefined ) {
				if ( value == 12 ) {
					// "Noon"
					this._setDropDownValue(this.gmt.ampm, 1);
				} else if ( value > 12 ) {
					// PM
					value = value - 12;
					this._setDropDownValue(this.gmt.ampm, 1);
				} else {
					// AM
					this._setDropDownValue(this.gmt.ampm, 0);
				}
			}
			this.gmt.hours.value = value;
			
			var value = this.date.getHours();
			if ( this.local.ampm != undefined ) {
				if ( value == 12 ) {
					// "Noon"
					this._setDropDownValue(this.local.ampm, 1);
				} else if ( value > 12 ) {
					// PM
					value = value - 12;
					this._setDropDownValue(this.local.ampm, 1);
				} else {
					// AM
					this._setDropDownValue(this.local.ampm, 0);
				}
			}

			this.local.hours.value = value;
		}
		
		if ( this.gmt.minutes != undefined ) {
			this.gmt.minutes.value = this.date.getUTCMinutes();
			this.local.minutes.value = this.date.getMinutes();
		}
		if ( this.gmt.seconds != undefined ) {
			this.gmt.seconds.value = this.date.getUTCSeconds();
			this.local.seconds.value = this.date.getSeconds();
		}
	}
	,
	_setDropDownValue : function(dropdown, value) {
		for ( var i=0; i < dropdown.options.length; i++ ) {
			if ( dropdown.options[i].value == value ) {
				dropdown.selectedIndex = i;
				break;
			}
		}
	}
}

function onEnterClickFirstButton(e, input) {
	var r = true;
	
	var keynum;
	if(window.event) { // IE
		keynum = e.keyCode
	} else if(e.which) { // Netscape/Firefox/Opera
		keynum = e.which
	}

	if (keynum == 13) {
		for ( var i=0; i < input.form.elements.length; i++ ) {
			var element = input.form.elements[i];
			
			if ( element.type == 'submit' ) {
				// First button
				element.click();
				r = false;
				break;
			}
		}
		
	}
	
	return r;
}


