/** 
 *	When the window finishes loading, get all
 *	fields with css class 'text' and set their
 *	onfocus and onblur events to change the
 *	field's background and border color.
*/
function textFieldColorHandler(window) {
	Event.observe(window, 'load', function () {
		var text_fields = $$('.text');
		text_fields.each(function(field, index) {
			field.onfocus = function() { this.className += ' focused';}
			field.onblur = function() { this.className = this.className.replace('focused', ''); }
		});
	});
}


//changes the target of a form (usually for a popup window)
function changeFormTarget(targetName) {
	document.forms[0].target = targetName;
}


//submit current form
function submitForm() {
	document.forms[0].submit();
}


function imposeMaxLength(obj, maxLen) {
	return (obj.value.length <= maxLen);
}


function setSelectedId(id, versionId) {
	$('selectedId').value = id;
	if (versionId) {
		$('selectedVersionId').value = versionId;
	}
}


function setSelectedPriority(priorityFieldName) {
	$('selectedPriority').value = $(priorityFieldName).value;
}


function popupWindow(url, windowName) {
	window.open(url, windowName);
}


function toggleDisabled(obj, toggleCheck) {

	if ($(toggleCheck)) {

		var tc = $(toggleCheck);
		if (getCheckedValue(tc) == "true") {
			$(obj).disabled = true;
		} else {
			$(obj).disabled = false;
		}

	} else {
		$(obj).disabled = !document.getElementById(obj).disabled;
	}
}


function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}


/**
 * This class watches a form who's ID is used as an argument
 * in the constructor. The intial form values are serialized
 * and compared to the values at the time of the window's
 * unload event to see if any changes have occured and still
 * need to be saved.
 * 
 * = Usage
 * <script type="text/javascript>
 *         new FormChangeWatcher('my_form_id');
 * </script>
 */
var FormChangeWatcher = Class.create({
    initialize: function(form_id) {
        this.form = $(form_id);
        this.initial_fields = $(form_id).serialize();
        this.submitted = false;
        this.handler = this.alertOnExit.bindAsEventListener(this);
        
        Event.observe(window, 'beforeunload', this.handler);
        Event.observe(this.form, 'submit', function() { this.submitted = true }.bind(this));
    },

	stopWatching: function() {
		Event.stopObserving(window, 'beforeunload', this.handler);
        	Event.stopObserving(this.form, 'submit', function() { this.submitted = true }.bind(this));	
	},

    alertOnExit: function(evt) {
        this.current_fields = this.form.serialize()
        if ((this.initial_fields != this.current_fields) && !this.submitted) {
            evt.returnValue = "Your changes will not be saved."
        }
    }   
}); 


/**
  * Given the id of a select element on the page, the function
  * will enumerate through that element's option elements
  * and if any of them match option_id, it will be selected.
  */
function selectOption(option_id, select_id) {
	var opts = $(select_id).getElementsByTagName('option');
	
	$A(opts).each(function(opt) {
		if (opt.value == option_id) {
			opt.selected = true;
		}
	});	
}


/**
 * Returns the value of the url parameter specified in the argument
 */
function getUrlParam(name) {
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );
	
	if (results == null) {
		return "";
	} else {
		return results[1];
	}
}


function disableElement(obj){
	$(obj).disabled = true;	
}


function enableElement(obj){
	$(obj).disabled = false;	
}


function getInnerHtmlOfOption(select_id) {
	var option_content = '';
	
	$A($(select_id).getElementsByTagName('option')).each(function(opt) {
		if (opt.value == $(select_id).value) {
			option_content = opt.innerHTML;
		}
	});

	return option_content;
}


function setFieldFromOption(field_id, select_id) {
	$(field_id).value = getInnerHtmlOfOption(select_id);
}


/**
  * Checks to see whenever a benefit is published by comparing
  * the publish and active flags.
  */
function isPublished(status) {
	return (status.publishFlag == true && status.activeFlag == true);
}


/**
  * Submit the action Form after changing the Action path dynamically
  */
function submitFormDynamically(formStyleId, path, selectStyleId) {
	//if (selectStyleId) {
		//if($(selectStyleId).value!=0){
			//$(formStyleId).action=path;
			//document.forms[0].submit();
		//}else{
			//$(contentStyleId).value=0;
			
		//}
	//}else{
		
		$(formStyleId).action=path;	
		document.forms[0].submit();
	//}
	
}


/**
  * Change the Action path dynamically
  */
function changeFormDynamically(formStyleId, path){
	$(formStyleId).action=path;	
}


/**
  * Check the limit of the characters entered in the textarea/textbox 
  */
function limitText(obj, maxLen){
	if($(obj).value.length>maxLen){
		// Reached the Maximum length so trim the textarea
		$(obj).value = $(obj).value.substring(0, maxLen);
	}	
}


/**
  * Given the id of a select element, retrieve the contents of
  * the option tag that is currently selected.
  */
function getInnerHtmlOfOption(select_id) {
	var option_content = '';
	
	$A($(select_id).getElementsByTagName('option')).each(function(opt) {
		if (opt.value == $(select_id).value) {
			option_content = opt.innerHTML;
		}
	});

	return option_content;
}


/**
  * Set the value of the form element with field_id to the
  * currently selected value of select_id.
  */
function setFieldFromOption(field_id, select_id) {
	$(field_id).value = getInnerHtmlOfOption(select_id);
}


function confirmNotLoggedState(class1,class2,class3,id4,id5){
	
	var agreed =confirm("Selecting \"Not Logged In State\" will disable all Content Rules. Updating/Publishing the record will not save any existing Content Rules. Are you sure you want to continue?");
	if (agreed) {
		disableMultiInput(class1,class2,class3,id4,id5);
		
	} else{
		if($('logInSelected').value=="Y"){
			$('loggedInYes').checked=true;
		}else if($('logInSelected').value=="B"){
			$('loggedInBoth').checked=true;
		}
		
	}
}

function disableMultiInput(class1,class2,class3,id4,id5){
	$$(class1).each(function(x) {
					x.disabled = true;
				 });
				
	$$(class2).each(function(x) {
					x.disabled = true;
				});
	$$(class3).each(function(x) {
					x.disabled = true;
				 });
	disableElement(id4);
	disableElement(id5);			
	
}

function enableMultiInput(class1,class2,class3,id4,id5){
	$$(class1).each(function(x) {
					x.disabled = false;
				});
	$$(class2).each(function(x) {
					x.disabled = false;
				});
	$$(class3).each(function(x) {
					x.disabled = false;
				});			
	enableElement(id4);
	enableElement(id5);		
				
}

function setCurrentCheckedValue(obj){
	$('logInSelected').value=obj;

}


/**
  * Loads the entire list of specified benefit and puts the results
  * in the specified select element on the page.
  */
function loadLookupList(ajax_url, element_type, select_id, benefit_attr) {
	new Ajax.Request(ajax_url, {
   		parameters: {'actionType':'GET_ALL', 'elementType':element_type, 'excludeChildren':'true'},
   		
   		onSuccess: function(transport) {
   			var benefits = transport.responseText.evalJSON();
			
			benefits.each(function(b) {
				$(select_id).insert({'bottom':Builder.node('option', {'value':b.id}, b.name)});
			});

			selectOption(benefit_attr, select_id);	   		
   		}
	});
}

function openPreviewWindow(url) {
	window.open(url, 'previewWindnow');
}

function disableFormBeforeDelete(form_id, buttons_hash, buttons_container, confirm_fn, benefit_name, urls) {
	var form = $(form_id);
	buttons_hash = $H(buttons_hash);
	urls = $H(urls);
	
	// disable all form inputs
	var inputs = form.getElements();
	inputs.invoke('disable');
	
	// enable all the buttons in this list
	$H(buttons_hash).values().each(function(v) {
		$(v).enable();
	});
	
	// clear the buttons' previous event listeners so we can attach new ones
	$H(buttons_hash).values().each(function(v) {
		$(v).stopObserving();
	});
	
	// The cancel button in this state should revert the form to its default
	// state when clicked.
	Event.observe(buttons_hash.get('cancel'), 'click', function(e) {
		inputs.invoke('enable');
		defaultButtonBehaviors(form_id, buttons_hash, buttons_container, confirm_fn, benefit_name, urls);
	});
	
	// The delete button in this state should show a confirmation dialog.
	Event.observe(buttons_hash.get('delete'), 'click', function(e) {
		// Event.stop(e);
		var agreed = confirm_fn(benefit_name);
		if (agreed) {
			inputs.invoke('enable');
			var actionType = new Element('input', { 'type': 'hidden', 'name': 'actionType', 'value':'Delete'});
			$(buttons_container).insert({'bottom':actionType});
			
			if (watcher) {			
				watcher.stopWatching();
			}
			 	
			form.action = urls.get('delete'); 		
			form.submit();
		}
	});
	
	// The preview button in this state should open the preview for the parent layer.
	Event.observe('previewButton', 'click', function(e) {
		openPreviewWindow(urls.get('previewDelete'));
	});
}


function defaultButtonBehaviors(form_id, buttons_hash, buttons_container, confirm_fn, benefit_name, urls) {
	buttons_hash = $H(buttons_hash);
	urls = $H(urls);
	
	// clear the buttons' previous event listeners so we can attach new ones
	$H(buttons_hash).values().each(function(v) {
		$(v).stopObserving();
	});

	Event.observe(buttons_hash.get('cancel'), 'click', function(e) {
		forward(urls.get('cancel'));
	});
	
	Event.observe(buttons_hash.get('delete'), 'click', function(e) {
		Event.stop(e);
		disableFormBeforeDelete(form_id, buttons_hash, buttons_container, confirm_fn, benefit_name, urls);
	});
	
	Event.observe('previewButton', 'click', function(e) {
		openPreviewWindow(urls.get('preview'));
	});	
}

function forward(url) {
	try {
		location.href = url;
	} catch (err) {
		// Do nothing, this is to handle IE
	}
}

function isBenefitPublished(status) {
	return (status.publishFlag == true && status.activeFlag == true);
}

function checkRadioButton(obj){
	$(obj).checked = true;
}

function checkRadioButton(obj, index){
	document.getElementsByName(obj)[index].checked = true;
}


 var BenefitAjaxParams = Class.create({
                       
  initialize: function(_id, _version_id, _action_type) {
  
    // private instance variables
    var id = _id;
    var version_id = _version_id;
    var action_type = _action_type;
    var params = $H({'id':id, 'versionId':version_id, 'actionType':action_type});
  
    // privelged accessor methods
    this.id = function() { return id; }    	    
    this.version_id = function() { return version_id; }
    this.action_type = function() { return action_type; }
    this.params = function() { return params; }
  },
  
  paramsHash: function() {
    return this.params();
  },
  
  queryString: function() {
  	return this.params().toQueryString();
  }
});


var AdminBenefitAjaxParams = Class.create(BenefitAjaxParams, {
  
  initialize: function($super, _id, _version_id, _action_type, _excluded_child_id) {
    $super(_id, _version_id, _action_type);

     // private instance variable
    var excluded_child_id = _excluded_child_id || 0;
    
    // add the new attribute to the hash
    this.params().set('excludedChildId', excluded_child_id);
    
    // priveleged accessor method
    this.excluded_child_id = function() { return excluded_child_id; }
  }
});

var FormUtils = {
	imposeMaxLength: function(evt, obj, max_len) {
	    if (obj.value.length >= max_len) {
	    	
	    	if (!this.validTextareaKeys(evt.keyCode)) {
		    	evt.stop();
	 			obj.value = obj.value.substring(0, max_len);	    	
	    	}

    	} 		
	},
	
	validTextareaKeys: function(key_code) {
		return (key_code == Event.KEY_BACKSPACE
					|| key_code == Event.KEY_DELETE
					|| key_code == Event.KEY_LEFT
					|| key_code == Event.KEY_UP
					|| key_code == Event.KEY_RIGHT
					|| key_code == Event.KEY_DOWN);
	},
	
	confirmResetMsg: function() {
		return confirm("This record is not yet saved. Do you want to continue to reset the data on this form?");
	},
	
	clearValues: function(form_id) {
		
		if (this.confirmResetMsg()) {
			this.form = $(form_id);
			this.form.reset();
			
			var text_inputs = this.form.getInputs('text');
			var text_area = this.form.select('textarea');
			var drop_downs = this.form.select('select');
			
			drop_downs.each(function(f) {
				f.getElementsByTagName('option')[0].selected = true;
			});
			
			text_inputs.each(function(f) {
				f.value = "";
			});
			
			text_area.each(function(f) {
				f.value = "";
			});		
			
			var errors = $('errors');
			if (errors != null) {
				errors.update(''); 
			}				
		}
	},
	
	setFieldsFromParamsHash: function(params_hash) {
		params_hash = $H(params_hash);
		params_hash.keys().each(function(key) {
			var field = $(key);
			if (field != null) field.value = params_hash.get(key);
		});
	}	
};

var DateUtils = {
	firstBeforeSecond: function(first_dt, second_dt) {
		return first_dt.getTime() < second_dt.getTime();
	},
	
	firstAfterSecond: function(first_dt, second_dt) {
		return first_dt.getTime() > second_dt.getTime();
	},
	
	dateInBetweenStartAndEnd: function(start_dt, end_dt, date_obj) {
		var startBeforeDate = DateUtils.firstBeforeSecond(start_dt, date_obj);
		var endAfterDate = DateUtils.firstAfterSecond(end_dt, date_obj);
		return (startBeforeDate && endAfterDate);
	}
};