/*
 * Javascript class to handle department functions
 *
 * Author: Lucas Pedley
 * Copyright Me
 */
var Dept = new function() {
	this.department = null;
	
	//----------------------
	this.init = function() {
		var self = Dept;
		//alert('inited');
		self.swapLinkFile();
		
		//check if on ballot page
		self.ballotCheck();
	};
	//----------------------
	this.doDeleteItemConfirm = function() {
		var self = Dept;
		
		if(confirm('Are you sure you wish to delete this department?')){
			document.forms[0].submit();
		}else{
			return false;
		}
	};
	//----------------------
	this.doDeleteStaffConfirm = function() {
		var self = Dept;
		
		if(confirm('Are you sure you wish to delete this staff member?')){
			document.forms[0].submit();
		}else{
			return false;
		}
	};
	//----------------------
	this.doDeleteConfirm = function(txt,formId) {
		var self = Dept;
		var curForm = document.forms[0];
		var provided = false;
		if(typeof(arguments[1]) != 'undefined'){
			//alert('provided id: '+formId);
			curForm = document.getElementById(formId);
			provided = true;
		}
		if(confirm('Are you sure you wish to delete this '+txt+'?')){
			if(txt == 'committee' || provided){
				if(curForm.actionType){
					curForm.actionType.value = 'delete';
				}
			}
			//alert(curForm.actionType.value);
			if($('hidMode')){
				$('hidMode').value = 'D';	
			}
			curForm.submit();
		}else{
			
			return false;
		}
	};
	//---------------------
	this.toggleElectedForm = function(){
		var self = Dept;
		var electedDiv = $('electedElements');
		if(electedDiv){
			electedDiv.toggle();	
		}
		//alert('toggleing');
	}
	//--------------------
	this.delStaffImg = function(){
		var self = Dept;
		var hidStaffId = $('hidStaffId');
		var ImgDelButn = $('staffImgDel');
		if(hidStaffId){
			if(confirm('Are you sure you wish to delete this image?')){
				var options = {
					method		: 'post',
					parameters  : 'action=delOffImg&staffId='+hidStaffId.value,
					onSuccess   : Dept.deleteStaffSuccess,
					onFailure   : Dept.deleteStaffFailure
				};
				//alert('/county/ajaxDelImg');
				ImgDelButn.value = 'Please Wait';
				new Ajax.Request('/county/ajaxDelImg', options);
				//new Ajax.Updater ('electedImgHldr', site_url+'county/ajaxDelImg', options );
				
			}
			else{
				return false;	
			}
		}
	}
	//--------------------
	this.deleteStaffSuccess = function(transport){
		var self     = Dept;
		//alert(transport.responseText);
		var respArr  = transport.responseText.split('|');
		var respType = respArr[0].toLowerCase();	//sucess | error | newPass
		var respMsg  = respArr[1];		
		if(respType == 'error'){
			alert(respMsg);
		}else{
			new Effect.SwitchOff('staffImgHldr');
		}
	}
	//--------------------
	this.deleteStaffFailure = function(transport){
		var self = Dept;
		alert(transport.responseText);
	}
	//--------------------
	this.swapLinkFile = function(){
		var self = Dept;
		var linkDiv      = $('linkInput');
		var link_ext_url = $('link_ext_url');
		var link_int_url = $('link_int_url');
		var fileDiv      = $('fileInput');
		var extraTypeObj = $('extra_type');

		if(linkDiv && fileDiv && extraTypeObj){
		
			if(typeof(extraTypeObj.selectedIndex) == 'undefined'){
				extraTypeObj.selectedIndex = 0;
			}
			//alert(extraTypeObj.selectedIndex);
			//alert(extraTypeObj.options[].value );
			//alert(extraTypeObj.options[].text); 
			var selIndex = extraTypeObj.selectedIndex;	
			if(extraTypeObj.options[selIndex].value == 'link'){
				linkDiv.show();	
				fileDiv.hide();
				link_ext_url.show();
				link_int_url.hide();
			}
			if(extraTypeObj.options[selIndex].value == 'iLink'){
				linkDiv.show();
				fileDiv.hide();
				link_ext_url.hide();
				link_int_url.show();
			}
			if(extraTypeObj.options[selIndex].value == 'file'){
				linkDiv.hide();	
				fileDiv.show();
			}
			
		}		
	};
	//--------------------
	this.delDeptFile = function(){
		var self = Dept;
		var hidExtraId = $('hidStaffId');
		var hidExtraLabel = $('hidFileName');
		var fileDelButn = $('delFileButn');
		if(hidExtraId && hidExtraLabel){
			if(confirm('Are you sure you wish to delete this file?')){
				var options = {
					method		: 'post',
					parameters  : 'action=delFile&extraId='+hidExtraId.value+'&fileName='+hidExtraLabel.value,
					onSuccess   : Dept.deleteFileSuccess
				};
				fileDelButn.value = 'Please Wait';
				new Ajax.Request(site_url+'county/ajaxDelFile', options);
				//new Ajax.Updater ('electedImgHldr', site_url+'county/ajaxDelImg', options );			
			}
			else{
				return false;	
			}
		}
	};
	//--------------------
	this.deleteFileSuccess = function(transport){
		var self = Dept;
		//alert(transport.responseText);
		new Effect.SwitchOff('fileLinkHldr');
	}	
	
	this.ballotCheck = function(){
		var self = Dept;
		if(typeof(window.adminBallot) == 'undefined'){
			return;
		}
		Ballot.init();
	};
	/**
	 * Handles the click action when administering a committee
	 * @param integer, comm_id
	 * @param string, action
	 * @return null
	 */
	this.commAction = function(comm_id,action){
		if($('comm_id')){
			if(comm_id != ''){
				$('comm_id').value = comm_id;
			}else{
				alert('Error: Unable to determine id. Edit will not continue.');
				return;
			}
			if($('actionType')){
				$('actionType').value = action;
			}
			if(action == 'delete'){
				if(confirm('Are you sure you wish to delete this committee?')){
					$('adminForm').submit();
				}else{
					return;
				}
			}
			$('adminForm').submit();
		}
	};
	/**
	 * Updates selected committe list in staff form
	 * @return null
	 */
	this.toggleCommittee = function(){
		var self = Dept;
		$$('#fullCommList input[type=checkbox]').each(
			function(s){
				var elem = s.name.split('_');
				var rowId = elem[1];
				if(s.checked && elem[0] == 'comm'){
					//alert('showing: '+s.value);
					$('row_'+rowId).show();
				}else if(elem[0] == 'comm'){
					//alert('hiding: '+s.value);
					$('row_'+rowId).hide();
				}
				if(s.checked && elem[0] == 'type'){
					//alert(s.name);
					$(s.name+'_span').show();
				}else if(elem[0] == 'type'){
					$(s.name+'_span').hide();
				}
			}
		);
		//var commList    = $('committee[]').value.evalJSON();
		//var commOptions = $('comOptions').value.evalJSON();
 		//get all selected committees
		/*
		var i=0;
		var selComArr = new Array();
		$$('#fullCommList checkbox').each(
			function(s){
				if(s.value != ''){
					selComArr[i] = {
									'name' : s.name,
									'value': s.value
									};
				}
				alert(s.name);
			}
		);
		*/
	};
	this.clearLike = function(obj,cnt){
		var elem = obj.name.split('_');
		var curElem = '';
		for(var i=0; i<cnt; i++){
			curElem = elem[0]+'_'+elem[1]+'_'+i;
			//alert('curelem:'+curElem+', objNm:'+obj.name);
			if($(curElem).checked && obj.name != curElem){
				$(curElem).checked = false;
			}
		}
	};
};	

Event.observe(window,'load', Dept.init);

//-------------------
// ballot Class
//-------------------
var Ballot = new function() {
	this.ballotId  = null;
	this.ballotCat = null;
	this.curMsgObj = null;
	this.tempHold = '';
	this.settings = {
        statusSuccessColor  : '#99ff99',
		statusSuccessBGColor: '#dffed9',
        statusErrorColor    : '#ffff99',
		statusErrorBGColor  : '#fed9d9',
		statusStatColor     : '#4c3111',
		statusStatBGColor   : '#dcfdff',
        statusEndColor      : '#ff9966',
		statusOrigColor     : '#ffffff'
    };
	/**
	 * Load the admin buttons on the ballot page and get ids
	 * @return null
	 */
	this.init = function(){
		var self = Ballot;
		//alert('here');
		self.ballotId  = $('ballot_id');
		self.ballotCat = $('catCount');
		//alert('ballot: '+self.ballotId.value+'\nCatCount: '+self.ballotCat.value);
	};
	/**
	 * Prepares to delete a category or option
	 * @param id, integer. Id of 'cat' or 'opt'
	 * @param type, string. 'cat' | 'item'
	 * @return null
	 */
	this.ballotItemDelete = function(id,type){
		var self = Ballot;
		var adlMsg = '';
		
		switch(type){
			case 'cat':
				var optContainer = $('optionContainer_'+id);
				if(optContainer){
					if(optContainer.innerHTML != ''){
						adlMsg = '\nAll associated options will also be deleted.';	
					}
				}
				if(confirm('Are you sure you want to delete this ballot category/item? '+adlMsg )){
					self.doCategoryDelete(id);
				}
			break;
			case 'opt':
				if(confirm('Are you sure you want to delete this ballot option? '+adlMsg )){
					self.doOptionDelete(id);
				}
			break;
			default:
				alert('Invalid Option');
		}
	};
	/**
	 * Prepares a ajax request to delete a category/item
	 * @param catId
	 * @return null
	 */
	this.doCategoryDelete = function(catId){
		var self = Ballot;		 
		self.curMsgObj = 'editCatMsg_'+catId;
		var options = {
			method      : 'post',
			parameters  : 'action=deleteCat&id='+catId,
			onSuccess   : self.ballotAjaxSuccess,
			onFailure   : self.ballotAjaxFailure
		};
		
		self.setStatus('Please Wait',self.curMsgObj,'stat');
		$('deleteCat_'+catId).disabled = true;
		new Ajax.Request(site_url+'/county/ajaxBallotDelete', options);
	 };
	/**
     * Sets a status message 
     * provides user with useful information about their interactions
	 * @param msg, string 
	 * @param msgLocDiv, string: name of div we are changing
	 * @param msgType, string: 'error' | 'success' | 'stat'
     * @return null
     */
    this.setStatus = function(msg,msgLocDiv,msgType){
        var self = Ballot;
        var color     = '';
		var bgColor   = '';
        var endColor  = self.settings.statusEndColor;
		var origColor = self.settings.statusOrigColor;
		
		switch(msgType){
			case 'error':
				color   = self.settings.statusErrorColor;
            	bgColor = self.settings.statusErrorBGColor
			break;
			case 'success':
				color   = self.settings.statusSuccessColor;
            	bgColor = self.settings.statusSuccessBGColor;
			break;
			default:
				color   = self.settings.statusStatColor;
            	bgColor = self.settings.statusStatBGColor;
		}
		
		var msgLoc = $(msgLocDiv);
		var options = {
			startcolor  :   color,
			afterFinish : 	function(){ 
								this.update(''); 
							}.bind(msgLoc)
		};
		//alert('about to update');
    	//msgLoc.update(msg);
		//alert('about to highlight');
    	new Effect.Highlight(msgLoc, options);
		
	};
	/**
	 * Logic to do what needs to be done when ajax request successful
	 * @param transport, string
	 * @return null
	 */
	 this.ballotAjaxSuccess = function(transport){
		var self     = Ballot;
		//alert('in ballotAjaxSuccess \n'+transport.responseText);
		var json   = transport.responseText.evalJSON();
		var msg    = json.message.txt;
		var type   = json.message.type;
		var action = json.action;
		var attrib = json.attrib;
		if(typeof(type) == 'undefined' || typeof(action) == 'undefined'){
			this.ballotAjaxError(msg);
		}else{
			//valid data returned 
			switch(action){
				case 'deleteCat':
					//remove category section				
					self.ballotCat.value = self.ballotCat.value-1;
					var currCat = $('cat_'+attrib.key);	
					Effect.DropOut(currCat);
					//alert('should of dropped out');
					self.setStatus(msg,self.curMsgObj,type);
				break;
				case 'deleteOpt':
					var optRow = $('optInput_'+attrib.key);
					//alert('in deleteOpt for id: '+attrib.key);
					Effect.DropOut(optRow);
					self.setStatus(msg,self.curMsgObj,type);
				break;
				case 'cat_add':
					//alert('in cat add, type: '+type+', key: '+attrib.key);
					if(type=='error'){
						var errMsgDiv = $('msg_'+attrib.key);
						if(errMsgDiv){
							errMsgDiv.innerHTML = msg;
						}
					}else{
						//build new category
						//alert('about to: buildCatDisp');
						var newCatObj = self.ballotBuildCatDisp(attrib,true);
						//alert('built CatDisp, about to insert it');
						$('catAdd').insert({'before' : newCatObj});
						self.tempHold = '';
						self.ballotCatAddCancel(0);
						self.ballotCat.value = self.ballotCat.value+1;
					}
				break;
				case 'cat_edit':
					//alert('in cat edit, type: '+type+', key: '+attrib.key);
					if(type=='error'){
						$('msg_'+attrib.key).innerHTML=msg;	
					}else{
						//alert('about to remove old');
						//remove old cat div
						var curCatSect = 'catInput_'+attrib.key;
						if($(curCatSect)){
							$(curCatSect).remove(curCatSect);
							//alert('removed old category');
						}
						//alert('about to build category display');
						var newCatObj = self.ballotBuildCatDisp(attrib,false);
						//alert('built CatDisp, about to insert it before forms fieldset');
						$('fldSet_'+attrib.key).insert({'before' : newCatObj});
							
						self.tempHold = '';
						self.ballotCatAddCancel(attrib.key);
					}
				break;
				case 'opt_add':
					//alert('in opt_add, type:'+type+',optId:'+attrib.opt);
					if(type=='error'){
						var errMsgDiv = $('msg_'+attrib.opt);
						if(errMsgDiv){
							alert('err div exists, loading: '+msg);
							errMsgDiv.innerHTML = msg;
							$('canidate_submit').disabled = false;
							$('canidate_submit').value = 'Submit';
						}
					}else{
						//build new canidate
						var optId = attrib.opt;
						var catId = attrib.cat;
						var addOptButn = $('addOpt_'+catId);
						var newOptObj  = self.ballotBuildOptDisp(attrib);
						//alert('built option, about to insert it');
						$('optionContainer_'+catId).appendChild(newOptObj);
						self.tempHold = '';
						//alert('about to hide form, opt: '+optId+', cat: '+catId);
						self.ballotOptAddCancel(0,catId);
						
					}
				break;
				case 'opt_edit':
					//alert('in opt_edit');
					if(type=='error'){
						$('msg_'+attrib.opt).innerHTML=msg;	
					}else{
						//alert('edit successful');
						//remove old opt div
						var fldSet = 'opt_'+attrib.opt;
						if($(fldSet)){
							$(fldSet).remove(fldSet);
							//alert('removed old fieldset, opt_'+attrib.opt);
						 }
						var newOptObj = self.ballotBuildOptDisp(attrib);
						//alert('built CatDisp, about to insert it');
						var curForm = 'fldSet_'+attrib.opt+'_'+attrib.cat;				
						$(curForm).insert({'before' : newOptObj});
						self.tempHold = '';
						//alert('about to hide form');
						self.ballotOptAddCancel(attrib.opt,attrib.cat);		
					}
				break;
				default:
					alert('No action set for: '+action);
			}
		}
	 };
	/**
	 * Logic to do what needs to be done when ajax request errors out
	 * @param transport, string
	 * @return null
	 */
	 this.ballotAjaxError = function(transport){
		 if(transport != ''){
			alert('Error: '+transport);
		 }else{
			alert('An error occured during this request.'); 
		 }
	 };
	/**
	 * Builds a category section to be placed on document for display
	 * via ajax
	 * @param catData
	 * @return object
	 */
	this.ballotBuildCatDisp = function(catData,isAdd){
		var self = Ballot;
		var catId   = catData.key;
		var catName = catData.name;
		var catDesc = catData.desc;
		var catPrec = catData.prec;
		if(catPrec != ''){
			catPrec =  'Precincts Reporting: '+catData.prec;
		}
		
		if(isAdd){
			//alert('build for add');
			var elt = 	Builder.node('div', { id: 'cat_'+ catId, className: 'infoSection' }, [
							Builder.node('div', { id: 'catInput_'+ catId }, [
								Builder.node('p', { id: 'catTitle_'+ catId, className: 'listTitle' }, [catName, 
									Builder.node('span', { id: 'precinct_'+ catId, className: 'precinct' }, [catPrec]),
								]),	
								Builder.node('p', { id: 'catDetail_'+ catId, className: 'listDetail' }, [catDesc]),
								Builder.node('div',{ id: 'catEdit_'+catId, className: 'pageAdmin' }, [
									Builder.node('span', { id: 'editCatMsg_'+catId }, []),																  
									Builder.node('input',{ type: 'button', name: 'editCat_'+catId, id: 'editCat_'+catId, value: 'Edit Category', className: 'btn', onclick: 'Ballot.ballotCatEdit('+catId+')', onmouseover: "this.className='btn btnhov'", onmouseout: "this.className='btn'" }, []),	
									Builder.node('input',{ type: 'button', name: 'deleteCat_'+catId, id: 'deleteCat_'+catId, value: 'Delete Category', className: 'btn', onclick: 'Ballot.ballotItemDelete('+catId+',\'cat\')', onmouseover: "this.className='btn btnhov'", onmouseout: "this.className='btn'" }, []),														  
									Builder.node('div', { className:'clear' }, []),
								]),																	  
							]),	
							Builder.node('div', { id: 'optionContainer_'+catId }, [
								Builder.node('div', { id: 'opt_'+catId, className: 'catSection' }, []),
							]),
							Builder.node('div',{ id: 'optAdd_'+catId, className: 'smallFormB' }, [
								Builder.node('input',{ type: 'button', name: 'addOpt_'+catId, id: 'addOpt_'+catId, value: 'Add Option', className: 'btn', onclick: 'Ballot.ballotOptAdd('+catId+')', onmouseover: "this.className='btn btnhov'", onmouseout: "this.className='btn'" }, []),		
							]),
							Builder.node('div',{ className: 'clear'}, []),
						]);
		}else{
			//alert('build for edit');
			var elt = 	Builder.node('div', { id: 'catInput_'+ catId }, [
							Builder.node('p', { id: 'catTitle_'+ catId, className: 'listTitle' }, [catName, 
								Builder.node('span', { id: 'precinct_'+ catId, className: 'precinct' }, [catPrec]),
							]),	
							Builder.node('p', { id: 'catDetail_'+ catId, className: 'listDetail' }, [catDesc]),
							Builder.node('div',{ id: 'catEdit_'+catId, className: 'pageAdmin' }, [
								Builder.node('span', { id: 'editCatMsg_'+catId }, []),																  
								Builder.node('input',{ type: 'button', name: 'editCat_'+catId, id: 'editCat_'+catId, value: 'Edit Category', className: 'btn', onclick: 'Ballot.ballotCatEdit('+catId+')', onmouseover: "this.className='btn btnhov'", onmouseout: "this.className='btn'" }, []),	
								Builder.node('input',{ type: 'button', name: 'deleteCat_'+catId, id: 'deleteCat_'+catId, value: 'Delete Category', className: 'btn', onclick: 'Ballot.ballotItemDelete('+catId+')', onmouseover: "this.className='btn btnhov'", onmouseout: "this.className='btn'" }, []),														  
								Builder.node('div', { className:'clear' }, []),
							]),																	  
						]);
		}
			 
		return elt; 
	 };
	/**
	 * Prepares to build a category input form
	 * @return null
	 */
	 this.ballotCatAdd = function(){
		 var self = Ballot;
		 var fldSet = $('fldSet_0');
		 //check if we already built the form
		 if($(fldSet)){
		 	$(fldSet).remove(fldSet);
		 }	 
		 //alert('here');
		 var formObj = self.buildCategoryForm(0);
		 $('ballotContainer').insertBefore(formObj, $('catAdd'));
		 var fldSet = $('fldSet_0');	 
		 $('addCat').disabled = true;

		if(fldSet){
			var opt = {
				duration:  1.5
		 	};
		 	Effect.SlideDown(fldSet, opt);
		}
	};
	/**
	 * Prepares to build a category input form for edit
	 * @param catid, integer
	 * @return null
	 */
	 this.ballotCatEdit = function(catId){
		 var self = Ballot;
		 var fldSet = $('fldSet_'+catId);
		 //check if we already built the form
		 if($(fldSet)){
		 	$(fldSet).remove(fldSet);
		 }	 
		//get existing data
		var options = {
			method		: 'post',
			parameters  : 'catId='+catId+'&action=getCategoryData',
			onSuccess   : Ballot.ajaxCatEdit,
			onFailure   : Ballot.ajaxCatEdit
		};
		self.curMsgObj = $('catEditMsg');
		$('editCat_'+catId).value = 'Please Wait';
		$('editCat_'+catId).disabled = true;
		new Ajax.Request(site_url+'/county/ajaxGetCategory', options);
	 };
	/**
	 * Ajax result that finishes the edit action of a category
	 * @param transport, json object
	 * @return null
	 */
	this.ajaxCatEdit = function(transport){
		var self = Ballot;
		//alert('in ajaxCatEdit \n'+transport.responseText);
		var json   = transport.responseText.evalJSON();
		var msg    = json.message.txt;
		var type   = json.message.type;
		var action = json.action;
		var attrib = json.attrib;
		if(typeof(type) == 'undefined' || typeof(action) == 'undefined'){
			alert('An error occured while retrieving ballot data.');
		}else if(type == 'error'){
			self.curMsgObj = $('editCatMsg_'+attrib.key);
			self.setStatus(msg,self.curMsgObj,type);
		}else{
			//alert('about to buildCategoryForm');
			var curCatDiv = $('catInput_'+attrib.key);
			var formObj   = self.buildCategoryForm(attrib.key,attrib);
			$('cat_'+attrib.key).insertBefore(formObj, curCatDiv);
			var fldSet = $('fldSet_'+attrib.key);	 
			$('addCat').disabled = true;
			$('addOpt_'+attrib.key).style.display = 'none';
			var options = {
				duration:  1.5
			};
			Effect.SlideDown(formObj, options); 
			//clear current content being edited
			//hold onto current content in case cancel
			self.tempHold = curCatDiv.innerHTML;
			curCatDiv.innerHTML = '';
		}
	};
	 /**
	 * Called to create the category form
	 * @param formId, integer
	 * @param formElement, array
	 * @ return form object
	 */
	 this.buildCategoryForm = function(formId,formElement){
		var self = Ballot;
		var setAction = '';
		var legend    = '';
		var catName   = '';
		var catDesc   = '';
		var catReport = '';
		if(formId > 0){
			//edit
			//alert('building form for edit');
			setAction = 'edit';
			legendTxt = 'Editing Ballot Item/Category';
			if(typeof(formElement != 'undefined')){
				catName   = formElement.name;
				catDesc   = formElement.desc;
				catReport = formElement.prec;
			}
		}else{
			//add
			setAction = 'add';
			legendTxt = 'Add a Ballot Item/Category';
		}
		
		var elt = 	Builder.node('fieldset', { id: 'fldSet_'+ formId, style: 'display:none' }, [
						Builder.node('legend',{ }, [legendTxt]),
						Builder.node('form', { id: 'catForm_'+ formId, method: 'post', className: 'horizontal', onsubmit: 'Ballot.ballotCatSubmit('+formId+');return false' }, [
							Builder.node('input',{ type: 'hidden', name: 'categoryId', value: formId }, []),
							Builder.node('input',{ type: 'hidden', name: 'action', value: setAction }, []),
							Builder.node('div',{ id: 'msg_'+formId }, []),
							Builder.node('div',{ className: 'field' }, [
								Builder.node('label',{ htmlFor: 'category_name' }, ['Category Name:']),
								Builder.node('input',{ type: 'text', name: 'category_name', id: 'category_name', size: '25', maxlength: '250', onblur: 'mand(this)', value: catName }, []),
							]),
							Builder.node('div',{ className: 'field' }, [
								Builder.node('label',{ htmlFor: 'category_desc' }, ['Category Description:']),
								Builder.node('textarea',{ name: 'category_desc', id: 'category_desc', rows: '5', cols: '45' }, [catDesc]),
								Builder.node('span',{ }, ['Optional']),
							]),
							Builder.node('div',{ className: 'field' }, [
								Builder.node('label',{ htmlFor: 'category_precinct' }, ['Precincts Reporting:']),
								Builder.node('input',{ type: 'text', name: 'category_precinct', id: 'category_precinct', size: '25', maxlength: '250', value: catReport }, []),
								Builder.node('span',{ }, ['Optional']),
							]),
							Builder.node('div',{ id: 'button_'+formId, style: 'text-align:right' }, [
								Builder.node('input',{ type: 'submit', name: 'category_submit', id: 'category_submit', value: 'Submit' }, []),	
								Builder.node('input',{ type: 'button', name: 'category_cancel', onclick: 'Ballot.ballotCatAddCancel('+formId+')', value: 'Cancel' }, []),
							]),
						])
				  	]);
		return elt;
	 };
	 /**
	 * Cancels a babllot category addition by
	 * removing the form and restoreing the add category button
	 * @param formId
	 * @return null
	 */
	 this.ballotCatAddCancel = function(formId){
		var self = Ballot;
		//alert('in ballotCatAddCancel, catId: '+formId);	
		Effect.SlideUp('fldSet_'+formId);
		
		//restore edisting category info
		if(self.tempHold != ''){
			$('catInput_'+formId).innerHTML = self.tempHold;
			self.tempHold = '';
		}
		//restore buttons
		if($('editCat_'+formId)){
			if($('editCat_'+formId).disabled){
				$('editCat_'+formId).disabled = false;
			}

			$('editCat_'+formId).value = 'Edit Category';
		}
		$('addCat').disabled = false;
		if($('addOpt_'+formId)){
			$('addOpt_'+formId).style.display = 'inline-block';
		}
	};
	/**
	 * Submits the ballot category to ajax
	 * @param
	 * @ return null
	 */
	this.ballotCatSubmit = function(id){
		 var self = Ballot;
		 var serializedForm = Form.serialize('catForm_'+id);
		 //alert(serializedForm);
		 var options = {
			method		: 'post',
			parameters  : 'ballotId='+self.ballotId.value+'&'+serializedForm,
			onSuccess   : Ballot.ballotAjaxSuccess,
			onFailure   : Ballot.ballotAjaxError
		};
		self.curMsgObj = $('catAddMsg');
		$('category_submit').value = 'Please Wait';
		$('category_submit').disabled = true;
		new Ajax.Request(site_url+'/county/ajaxBallotCatSave', options);
	 };
	//--------------------------------------------------------------------------------------------
	/**
	 * Prepares to build a option input form
	 * @return null
	 */
	this.ballotOptAdd = function(catId){
		var self = Ballot;
		//check if there is already a add/edit form open bu scanning entire document for fieldsets, 
		// if fieldsets found close the old and open the new	
		$$('fieldset').each(
			function(s){
				s.remove(s);
			}
		);	
		//alert('cleared fieldsets, catId is: '+catId);
		//var optSet = $('optSet_0');
		//if($(optSet)){
		//	$(optSet).remove(optSet);
		//}	 
		var addOptButn = $('addOpt_'+catId);
		var formObj = self.buildOptionForm(0,catId,'');
		//alert('form created'); 
		$('optionContainer_'+catId).appendChild(formObj);
		addOptButn.style.display = 'none';
		
		//alert('show the form'+ formObj.innerHTML);
		var fldSet = $('fldSet_0_'+catId);
		if(!fldSet){
			alert('Error creating option form');	
		}
		//fldSet.show();
		var options = {
			duration:  1.5
		};
		Effect.SlideDown(fldSet, options);	
	};
	/**
	 * Called to create the options form
	 * @param optId, integer
	 * @param catId, integer
	 * @param formElement, array
	 * @ return form object
	 */
	 this.buildOptionForm = function(optId,catId, formElement){
		var self = Ballot;
		var setAction = '';
		var legend    = '';
		var optName   = '';
		var optParty   = '';
		var optVotes = '';
		var optWinner = '';
		var checkBox = null;
		
		if(catId == ''){
			alert('error: Unknown category.');	
		}
		if(optId > 0){
			//edit
			//alert('Edit Form');
			setAction = 'edit';
			legendTxt = 'Editing Ballot Option';
			if(typeof(formElement != 'undefined')){
				optName   = formElement.name;
				optParty  = formElement.party;
				optVotes  = formElement.votes;
				optWinner = formElement.winner;
			}
		}else{
			//add
			//alert('Add Form');
			setAction = 'add';
			legendTxt = 'Add a Ballot Option';
		}
		
		if(optWinner == 1){
			checkBox = Builder.node('input',{ type: 'checkbox', name: 'canidate_winner', id: 'canidate_winner', checked: 'checked', value: 'winner' }, []);
		}else{
			checkBox = Builder.node('input',{ type: 'checkbox', name: 'canidate_winner', id: 'canidate_winner', value: 'winner' }, []);
		}
		
		var elt = 	Builder.node('fieldset', { id: 'fldSet_'+optId+'_'+catId, style: 'display:none' }, [
						Builder.node('legend',{ }, [legendTxt]),
						Builder.node('form', { id: 'optForm_'+ optId, method: 'post', className: 'horizontal', onsubmit: 'Ballot.ballotOptSubmit('+optId+');return false' }, [
							Builder.node('input',{ type: 'hidden', name: 'canidateId', value: optId }, []),																																		 
							Builder.node('input',{ type: 'hidden', name: 'categoryId', value: catId }, []),
							Builder.node('input',{ type: 'hidden', name: 'action', value: setAction }, []),
							Builder.node('div',{ id: 'msg_'+optId }, []),
							Builder.node('div',{ className: 'field' }, [
								Builder.node('label',{ htmlFor: 'canidate_name' }, ['Option/Canidate Name:']),
								Builder.node('input',{ type: 'text', name: 'canidate_name', id: 'canidate_name', size: '25', maxlength: '250', onblur: 'mand(this)', value: optName }, []),
							]),
							Builder.node('div',{ className: 'field' }, [
								Builder.node('label',{ htmlFor: 'canidate_party' }, ['Canidate Party:']),
								Builder.node('input',{ type: 'text', name: 'canidate_party', id: 'canidate_party', size: '20', maxlength: '20', value: optParty }, []),
								Builder.node('span',{ }, ['Optional']),
							]),
							Builder.node('div',{ className: 'field' }, [
								Builder.node('label',{ htmlFor: 'canidate_votes' }, ['Votes Received:']),
								Builder.node('input',{ type: 'text', name: 'canidate_votes', id: 'canidate_votes', size: '10', maxlength: '10', value: optVotes }, []),
								Builder.node('span',{ }, ['Optional']),
							]),
							Builder.node('div',{ className: 'field' }, [
								Builder.node('label',{ htmlFor: 'canidate_winner' }, ['Winner:']),
								checkBox,
								Builder.node('span',{ }, ['Optional, (Check to indicate winner)']),
							]),
							Builder.node('div',{ id: 'button_'+optId, style: 'text-align:right' }, [
								Builder.node('input',{ type: 'submit', name: 'canidate_submit', id: 'canidate_submit', value: 'Submit' }, []),	
								Builder.node('input',{ type: 'button', name: 'canidate_cancel', onclick: 'Ballot.ballotOptAddCancel('+optId+','+catId+')', value: 'Cancel' }, []),
							]),
						]),
				  	]);
		return elt;
	 };
	/**
	 * Cancels a ballot option addition by
	 * removing the form and restoreing the option buttons
	 * @param optId
	 * @param catId
	 * @return null
	 */
	this.ballotOptAddCancel = function(optId,catId){
		var self = Ballot;
	
		//alert('in ballotOptAddCancel');
		var frmId = 'fldSet_'+optId+'_'+catId;
		//alert(frmId);
		var fldSet = $(frmId);
		if(fldSet){
			//alert('found form, about to remove');
			Effect.SlideUp(fldSet);
		}
		
		//restore existing option info
		if(self.tempHold != ''){
			$('opt_'+optId).innerHTML = self.tempHold;
			self.tempHold = '';
		}
		//alert('restoreing buttons');
		//restore option butn
		if($('editOpt_'+optId)){
			$('editOpt_'+optId).value = 'Edit Option';	
		}
		var addOptButn = $('addOpt_'+catId);
		if(addOptButn){
			addOptButn.style.display = 'inline-block';
		}
	};
	/**
	 * Submits the ballot option to ajax
	 * @param
	 * @ return null
	 */
	this.ballotOptSubmit = function(id){
		var self = Ballot;		
		if(id==''){
			id = '0'; 
		}
		var optForm = $('optForm_'+id);
		//if(optForm){
		//	alert(optForm.innerHTML);
		//}else{
		//	alert('ballotOptSubmit, no dice:(');
		//}		
		var serializedForm = Form.serialize(optForm);
		//alert(serializedForm);
		var options = {
			method		: 'post',
			parameters  : serializedForm,
			onSuccess   : Ballot.ballotAjaxSuccess,
			onFailure   : Ballot.ballotAjaxError
		};
		self.curMsgObj = $('msg_'+id);
		new Ajax.Request(site_url+'/county/ajaxBallotOptSave', options);
		$('canidate_submit').value = 'Please Wait';
		$('canidate_submit').disabled = true;
	};
	/*
	 * Creates the option display
	 * @param opts, object
	 * @return object
	 */
	 this.ballotBuildOptDisp = function(opts){
		 //alert('in ballotBuildOptDisp');
		 var catId 		= opts.cat;
		 var optId 		= opts.opt;
		 var optName 	= opts.name;
		 var optParty 	= opts.party!='' ? '['+opts.party+']' : '';
		 var optVotes 	= opts.votes!='' ? '('+opts.votes+' Votes)' : '';
		 optVotes 	    = opts.votes!='0' ? optVotes : '';
		 var optWinner 	= opts.winner;
		 var winAttrib  = { className: 'infoLabel2', style: 'color:#009900;', id: 'optName'+optId };
		 if(optWinner == ''){
			 winAttrib  = { className: 'infoLabel2', id: 'optName'+optId };
		 }
		 
		 var elt = 	Builder.node('div', { id: 'opt_'+ optId, className: 'catSection' }, [
						Builder.node('div', { id: 'optInput_'+ optId }, [
							Builder.node('div', { className: 'field' }, [
								Builder.node('div', winAttrib, [optName]),	
								Builder.node('p', { className: 'infoValue', id: 'optVote'+optId }, [optVotes,
									Builder.node('span', {}, [optParty]),	
									Builder.node('div', { className: 'smallForm', id: 'optEdit'+optId }, [
										Builder.node('span', {id: 'editOptMsg_'+optId}, []),
										Builder.node('input',{ type: 'button', name: 'deleteOpt_'+optId, id: 'deleteOpt_'+optId, value: 'Delete Option', className: 'btn', onclick: 'Ballot.ballotItemDelete(\''+optId+'\',\'opt\')', onmouseover: "this.className='btn btnhov'", onmouseout: "this.className='btn'" }, []),' ',
										Builder.node('input',{ type: 'button', name: 'editOpt_'+optId, id: 'editOpt_'+optId, value: 'Edit Option', className: 'btn', onclick: 'Ballot.ballotOptEdit('+optId+','+catId+')', onmouseover: "this.className='btn btnhov'", onmouseout: "this.className='btn'" }, []),										
									]),
								]),
							]),											 												 
						]),																 
		 			]);
		return elt;
	 };
	 /**
	 * Prepares to build a option/canidate input form for edit
	 * @param optId, integer
	 * @param catId, integer
	 * @return null
	 */
	 this.ballotOptEdit = function(optId,catId){
		 var self = Ballot;
		 var fldSet = $('fldSet_'+optId+'_'+catId);
		 //check if we already built the form
		 if($(fldSet)){
		 	$(fldSet).remove(fldSet);
		 }	 
		//get existing data
		var options = {
			method		: 'post',
			parameters  : 'optId='+optId+'&action=getCanidateData',
			onSuccess   : Ballot.ajaxOptEdit,
			onFailure   : Ballot.ajaxOptEdit
		};

		$('editOpt_'+optId).value = 'Please Wait';
		new Ajax.Request(site_url+'/county/ajaxGetCanidate', options);
	 };
	/**
	 * Ajax result that finishes the edit action of a category
	 * @param transport, json object
	 * @return null
	 */
	this.ajaxOptEdit = function(transport){
		var self = Ballot;
		//alert('in ajaxOptEdit \n'+transport.responseText);
		var json   = transport.responseText.evalJSON();
		var msg    = json.message.txt;
		var type   = json.message.type;
		var action = json.action;
		var attrib = json.attrib;
		if(typeof(type) == 'undefined' || typeof(action) == 'undefined'){
			alert('An error occured while retrieving canidate/option data.');
		}else if(type == 'error'){
			self.curMsgObj = $('msg_'+attrib.opt);
			self.setStatus(msg,self.curMsgObj,type);
		}else{
			//alert('sucessful data grab');
			var curOptDiv = $('opt_'+attrib.opt);
			//alert('about to store and clear div content');
			self.tempHold = curOptDiv.innerHTML;
			curOptDiv.innerHTML = '';
			//alert('about to buildCanidateForm');
			var formObj = self.buildOptionForm(attrib.opt,attrib.cat,attrib);
			//alert('about to insert form');
			$('optionContainer_'+attrib.cat).insertBefore(formObj, curOptDiv);
			//var fldSet = $('fldSet_'+attrib.key);	 
			//$('addCat').disabled = true;
			var options = {
			duration:  1.5
			};
			Effect.SlideDown(formObj, options); 
		}
	};
	/**
	 * Prepares a ajax request to delete a ballot option
	 * @param optId
	 * @return null
	 */
	 this.doOptionDelete = function(optId){
		 var self = Ballot;
		 self.curMsgObj = 'editOptMsg_'+optId;		 
		 var options = {
			method      : 'post',
			parameters  : 'action=deleteOpt&id='+optId,
			onSuccess   : self.ballotAjaxSuccess,
			onFailure   : self.ballotAjaxFailure
		};
		
		self.setStatus('Please Wait',self.curMsgObj,'stat');
		$('deleteOpt_'+optId).style.display = 'none';
		new Ajax.Request(site_url+'/county/ajaxBallotDelete', options);
	 }; 
};
