var Time = {
  noExistingEdit: function() {
    if ($$('.edit_panel').length > 0) { 
      alert('Another edit is already open.'); 
      return false; 
    } else {
      return true;
    }
  }
}

var HoursSummary = {
  setup: function() {
    this.updateSelect();
    $('type').observe('change', this.updateSelect);
  }, 
  
  updateSelect: function() {
    var type = $F('type');
    if (type == 'Month') {
      $$('p.date label')[0].update('Year'); 
      $('date_month').hide();
    } else {
      $$('p.date label')[0].update('Month'); 
      $('date_month').show();      
    }
  }
};

var Report = {
  updateDateSelect: function(element) {
    var selection = $(element).value
    if (selection == 'custom') {
      $('custom').show();
      $('choose_month').hide();
    } else if (selection == 'choose_month') {
      $('custom').hide();
      $('choose_month').show();
    } else {
      $('custom').hide();
      $('choose_month').hide();
    }
  }, 
  
  toggleWeeklySummary: function(element) {
    var summary = $$('table.weekly_summary')[0]; 
    if (!summary.visible()) {
      element.update('Hide weekly summary');
    } else {
      element.update('Show weekly summary');
    }
    summary.toggle();
  }
}

function addAttachmentField() {
	tbl = document.getElementById('attachments-tbody');
	count = document.getElementById('attachmentCount');
	n = ++count.value;
		
	newRow1 = document.createElement('tr');
	newRow1.id = 'attachmentTR'+n;
	  newCell1a = document.createElement('td');
	  innerText1a = 'Attachment';
	  newCell1a.innerHTML = innerText1a;
	  newCell1b = document.createElement('td');
	  innerText1b = '&nbsp;';
	  newCell1b.innerHTML = innerText1b;
	  newCell1c = document.createElement('td');
	  innerText1c = '<input id="uploaded_data['+n+']" name="uploaded_data['+n+']" type="file" /> &nbsp; &nbsp; (<a href="javascript:removeAttachmentField('+n+')">remove</a>)';
	  newCell1c.innerHTML = innerText1c;
    newRow1.appendChild(newCell1a);
	newRow1.appendChild(newCell1b);
	newRow1.appendChild(newCell1c);
	tbl.appendChild(newRow1);

	count.value=n;
	return;
}

var OffDay = {
  showAdd: function(element) {
    var link = $(element); 
    var panel = link.next('.day_panel')

    panel.show();
    link.hide();
    
    panel.select('form').each(function(form) {
      form.reset();
    });
  }, 
  
  hideAdd: function(element) {
    var link = $(element); 
    var panel = link.up('.day_panel')
    var add_link = panel.previous('a.add_another'); 
    panel.hide();
    add_link.show();
  }, 
  
  selectTab: function(element, tab) {
    var link = $(element);
    var dayPanel = link.up('div.day_panel');
    var multiTab = dayPanel.down('li.multi');
    var singleTab = dayPanel.down('li.single');
    var multiBody = dayPanel.down('div.multi_day'); 
    var singleBody = dayPanel.down('div.single_day'); 

    if (tab == 'multi') {
      if (!multiTab.hasClassName('active')) multiTab.addClassName('active');
      singleTab.removeClassName('active');
      singleBody.hide(); 
      multiBody.show();
    } else if (tab == 'single') {
      if (!singleTab.hasClassName('active')) singleTab.addClassName('active');
      multiTab.removeClassName('active');
      multiBody.hide(); 
      singleBody.show();      
    }
  }, 
  
  showControl: function(tr) {
    $(tr).down('a.delete').show();
  },  
  
  hideControl: function(tr) {
    $(tr).down('a.delete').hide();    
  }, 
  
  resetForms: function() {
    $$('.day_panel form').each(function(form) {
      OffDay.hideAdd(form);
      form.reset();
    });
  }
};

function removeAttachmentField(x) {
  tbl = document.getElementById('attachments-tbody');
  tr = document.getElementById('attachmentTR'+x);
  tbl.removeChild(tr);

  return;
}



var UploadProgress = {
  statusBar: null,
  statusText: null,
  
  monitor: function(upid) {          
    this.periodicExecuter = new PeriodicalExecuter(function() {
      new Ajax.Request('/sow/progress?upload_id=' + upid);
    }, 1);

    this.createStatusBar();
    $$('div.submit')[0].hide();
    $('progress-bar').show(); 
  },

  update: function(total, current) {            
    var status     = current / total;
    var totalWidth = $('progress-bar').getWidth();
    
    this.statusText.innerHTML = status.toPercentage();
    this.statusBar.style.width = Math.floor(totalWidth * status) + 'px';
  },
  
  finish: function() {
    this.periodicExecuter.stop();
    this.statusText.innerHTML  = '100%';
    this.statusBar.style.width = '100%';
  },
    
  createStatusBar: function() {
    this.statusBar  = this._createStatus('status-bar');
    this.statusText = this._createStatus('status-text');
    this.statusText.innerHTML  = '0%';
    this.statusBar.style.width = '0';
  },
    
  _createStatus: function(id) {
    el = $(id);
    if(!el) {
      el = document.createElement('span');
      el.setAttribute('id', id);
      $('progress-bar').appendChild(el);
    }
    return el;
  }
}


Number.prototype.toPrecision = function() {
  var precision = arguments[0] || 2;
  var s         = Math.round(this * Math.pow(10, precision)).toString();
  var pos       = s.length - precision;
  var last      = s.substr(pos, precision);
  return s.substr(0, pos) + (last.match("^0{" + precision + "}$") ? '' : '.' + last);
}

// (1/10).toPercentage() # => '10%'
Number.prototype.toPercentage = function() {
  return (this * 100).toPrecision() + '%';
}


function toggleDeliverables(n){
  var del = document.getElementById('deliverables-'+n);
  var arw = document.getElementById('arw-'+n);
  var toggle = (del.style.display == "none");

  del.style.display = (toggle) ? "block" : "none";
  arw.className = (toggle) ? "arw-dn" : "arw-rt";
  
  return;
}

// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
function addIdToUrl(id, value) {
    link = document.getElementById(id)
    if (value.length > 0) {
        href = link.href
        last_slash = href.lastIndexOf('/')
        if (isNaN(href.substr(last_slash + 1))) {
            link.href = href + '/' + value
        } else {
            link.href = href.substr(0, last_slash + 1) + value
        }
        link.style.display = 'inline'
    } else {
        link.style.display = 'none'
    }
}

var Validation = {
	setup: function() {
		for (var fieldID in Validation.rules) {
			// Install event handlers
			var field = $(fieldID);
			if (!field) break; 
			
			var eventsToObserve = Validation.Config.initialEvents[field.type];
			eventsToObserve.each(function(eventType) {
				Event.observe(field, eventType, Validation.validateField);				
			})
			
			// Install structures
			var errorMessage = document.createElement('span');
			errorMessage.className = 'error-message'; 
			errorMessage.style.display = 'none';			
			if (!Validation.showMessageOnBottom(fieldID)) {
				errorMessage.style.marginLeft = '9px'; 
				errorMessage.style.marginTop = '1px';
				errorMessage.style.verticalAlign = 'top';
			}
			
			var checkmark = document.createElement('img');
			checkmark.src = "/images/icn-checkmark.gif"; 
			checkmark.className = "checkmark";
			checkmark.style.display = 'none';			
			checkmark.style.marginLeft = '9px'; 
			checkmark.style.marginTop = '1px';
			checkmark.style.verticalAlign = 'top';

			field.parentNode.appendChild(checkmark);			

			if (Validation.showMessageOnBottom(fieldID)) {
				var messageContainer = document.createElement('div');
				messageContainer.style.height = '1em'; 
				messageContainer.appendChild(errorMessage);
				field.parentNode.appendChild(messageContainer);						
			} else {
				field.parentNode.appendChild(errorMessage);						
			}

		}
	}, 
	
	validateField: function(e) {
		var field = Event.element(e);
		var rules = Validation.rules[field.id];
		var row = $(field.parentNode.parentNode); 
		var errorMessage = document.getElementsByClassName('error-message', row)[0];
		var checkmark = document.getElementsByClassName('checkmark', row)[0];
		var isValid = true; 
		
		// Abort all validation if required is false and field is empty
		if (!rules['required'] && $F(field).match(/^\s*$/)) {
			return; 
		} 																													
														
		for (var rule in rules) {
			var arg = rules[rule];
			var validator = Validation.Validators[rule]; 

			if (!validator.validate($F(field), arg)) {
				isValid = false; 
				field.addClassName('invalid');
				checkmark.hide();
				errorMessage.show();
				if (Validation.showMessageOnBottom(field.id)) {
					errorMessage.innerHTML = validator.defaultMessage(arg);
				} else {
					errorMessage.innerHTML = '&laquo; ' + validator.defaultMessage(arg);
				}
			
				break;
			}
		} 
		
		if (isValid) {
			field.removeClassName('invalid');			
			errorMessage.hide();
			
			if (Validation.shouldShowCheckMark(field.type, e.type)
			    && field.value != field.lastValidValue) {
				checkmark.show();
				Effect.Fade(checkmark, { delay:1.5 } );
				
				field.lastValidValue = field.value;
			}				
		}
		
		var eventsToObserve = Validation.Config.subsequentEvents[field.type] || [];
		eventsToObserve.each(function(eventType) {
			Event.observe(field, eventType, Validation.validateField);				
		})
	}, 
	
	shouldShowCheckMark: function(fieldType, eventType) {
		return Validation.Config.showCheckMarkOn[fieldType].include(eventType);
	}, 
	
	showMessageOnBottom: function(fieldID) {
		return Validation.messagePosition && Validation.messagePosition[fieldID] == 'bottom'; 
	},
	
	Validators: {
		length: {
			validate: function(value, range) {
				return value.length >= range[0] && value.length <= range[1];
			}, 
			defaultMessage: function(range) {
				return 'The length must be between ' + range[0] + ' and ' + range[1] + ' characters';
			}  
		},
		required: {
			validate: function(value, isRequired) {
				return !isRequired || !value.match(/^\s*$/)
			}, 
			defaultMessage: function() {
				return 'This field is required'; 
			}
		}, 
		format: {
			validate: function(value, format) {
				return value.match(format);
			},
			defaultMessage: function() {
				return 'The format is invalid'; 
			}
		}
	}, 
	
	Config: {
		initialEvents: {
			'select-one': [ 'blur', 'change', 'keyup' ],
			'text': 	    [ 'blur' ], 
			'textarea':   [ 'blur' ],
			'password':   [ 'blur' ]
		},

		subsequentEvents: {
			'text': 	    [ 'keyup' ], 
			'textarea':   [ 'keyup' ],		
			'password':   [ 'keyup' ]
		},

		showCheckMarkOn: {
			'select-one': [ 'blur', 'change', 'keyup' ],
			'text': 	    [ 'blur' ], 
			'textarea':   [ 'blur' ],
			'password':   [ 'blur' ]	
		}		
	}
}
Event.observe(window, 'load', Validation.setup);





/*function getProjectsDD(cid) {
  var wrap = document.getElementById('projects-wrap');
  wrap.innerHTML = '<%= select_tag("pid", "<option value=\'\'>- project -</option>\n" + options_for_select(get_projects_associated_with('+cid+').collect{|p| [ p.name, p.id]})) %>';
  //document.write('<%= select_tag("pid", "<option value=\'\'>- project -</option>\n" + options_for_select(get_projects_associated_with('+cid+').collect{|p| [ p.name, p.id]})) %>');
  wrap.style.display = (!empty(cid)) ? 'inline' : 'none';
}

function toggleAddFeature() {
  var cli = document.getElementById();
  var pro = document.getElementById();
  var wrap = document.getElementById();
}*/