/* VALIDATION STARTS WITH NO ERRORS */
var hasError = 0;

/* IF ERRORS DISPLAYS MESSAGE OTHERWISE SUBMITS FORM */
function processValidation(form, errorMsg) {
if (hasError) { errorMsg.style.display = "block"; } 
else { 
  errorMsg.style.display = "none";
  form.submit(); }
}


/* RETURNS TRUE IF ID IS BLANK */
function isBlank(x) {
  if (x.value.length === 0 || x.value === null || x.value === "") { return true; }
  else { return false; }
}


/* RETURNS TRUE IF ID IS NUMERIC */
function isNumeric(x) {
  if (x.value !== null && x.value.toString().match(/^[-]?\d*\.?\d*$/)) { return true; }
  else { return false; }
}


/* RETURNS INDEX OF ERROR IN CLASSNAME OTHERWISE FALSE */
function isErrorIndex(x) {
  //if (!x) { alert(x + " is undefined!"); }
  var i = x.className.indexOf(" error");
  if (i > -1) { return i; }
  else { return false; }
}



/*-- NUMERIC INPUTS */
function validateNumeric(num) {
  var i = isErrorIndex(num);
	
	if (isBlank(num)) {
		if (!i) { num.className += " error"; } hasError = 1;
	} else if (isNumeric(num)) {
		if (i) { num.className = num.className.substring(0, i); }
	} else {
		if (!i) { num.className += " error"; } hasError = 1;
	}
}

/*-- TEXT INPUTS */
function validateText(txt) {
	var i = isErrorIndex(txt);

	if (isBlank(txt)) { 
		if (!i) { txt.className += " error"; } hasError = 1;
	} else if (i) { txt.className = txt.className.substring(0, i); }
}


function validatePasswords(pw1, pw2) {
	var i = isErrorIndex(pw1);
  
    if (pw1.value.length < 5) { 
		if (!i) { 
			pw1.className += " error"; 
			pw2.className += " error"; 
		} 
		hasError = 1; 
		document.getElementById("errorMsg").innerHTML = "Passwords must be at least 5 characters long!";
	}
	else if (pw1.value != pw2.value) {
		if (!i) { 
			pw1.className += " error"; 
			pw2.className += " error"; 
		} 
		hasError = 1; 
		document.getElementById("errorMsg").innerHTML = "Your passwords do not match!";
	}
    else { 
      if (i) {
        pw1.className = pw1.className.substring(0, i); 
        pw2.className = pw1.className.substring(0, i);
      }
    }
}


/*-- TEXT AREAS */
function validateTextArea(txtArea) {
  var i = isErrorIndex(txtArea);
  if (txtArea.value.length === 0) { 
	if (!i) { txtArea.className += " error"; } 
	hasError = 1;
  } 
  else if (i) { 
	txtArea.className = txtArea.className.substring(0, i); 
  }
}



/*-- SEARCH AHEADS */
function validateSearchAhead(name) {
  if ($('#'+name+'Id').val() > 0) {
    $('#'+name+'Search').removeClass('error')
  } 
  else {
    $('#'+name+'Search').addClass("error"); 
    hasError = 1;
  }
}



/*-- SELECTS */
function validateSelect(select, emptyAllowed) {
	var i = isErrorIndex(select);
	if ((select === null) ||
	   ((select.selectedIndex === -1) && (!emptyAllowed)) || 
	   (select.options[select.selectedIndex].value==-1))
	{ 
		if (!i) { select.className += " error"; }
		hasError = 1; 
	} 
	else if (i) { select.className = select.className.substring(0, i); }
}
/*---------------------------------------------------------------------------*/



// validate item form
function validateItem() {
  hasError = 0;
  var placeId = document.getElementById("placeId");
  validateText(document.itemForm.itemName);
  if (placeId === null) { 
    validateSearchAhead('company');
  }
  validateSearchAhead('itemCategory');
  processValidation(document.itemForm, document.getElementById("errorMsg"));
}



/*-- ITEM SIZE FORM */
function validateItemSize() {
	hasError = 0;
	var soldByWeight = document.getElementById('soldByWeight');
	var soldIndv = document.getElementById('soldIndividually');
	var packagedItem = document.getElementById('packagedEntry');
	
	/* If it's a packaged item (i.e, 6x12oz) */
	if ((packagedItem !== null) && 
		(packagedItem.checked === true)) { 
	  validateText(document.sizeForm.quantity); 
	}
	/* If it's not sold in bulk */
	else if ((soldByWeight.checked === false) && 
			(soldIndv===null || !soldIndv.checked))
	{
	  validateText(document.sizeForm.size); 
	  validateSelect(document.sizeForm.unitsId, 0); 
	}
	processValidation(document.sizeForm, document.getElementById("sizeErrorMsg"));
}


function validateItemSizeName() {
  hasError = 0;
  validateText(document.itemSizeForm.sizeName);
  processValidation(document.itemSizeForm, 
                    document.getElementById('errorMsg'));
}



/*-- ITEM NUTRITION */
function validateNutrition() {
  hasError = 0; 
  validateText(document.nutritionForm.calories);
  validateText(document.nutritionForm.fat);
  validateText(document.nutritionForm.totalCarb);
  validateText(document.nutritionForm.sodium);
  validateText(document.nutritionForm.protein);
  processValidation(document.nutritionForm, document.getElementById("nutErrorMsg"));
}



/*-- PLACE FORM */
function validatePlace() {
  hasError = 0;
  validateText(document.placeForm.placeName);
  validateText(document.placeForm.address);
  processValidation(document.placeForm, document.getElementById("errorMsg"));
}



/*-- FOOD TYPE FORM */
function validateType() {
	hasError = 0;
	validateText(document.typeForm.typeName);
	processValidation(document.typeForm, document.getElementById("errorMsg"));
}



/*-- COMPANY FORM */
function validateCompany() {
  hasError = 0;
  validateText(document.companyForm.companyInput);
  processValidation(document.companyForm, document.getElementById("errorMsg"));
}



/*-- BRAND FORM */
function validateBrand() {
  hasError = 0;
  validateText(document.brandForm.brandInput);
  validateSearchAhead('company');
  validateSearchAhead('brandCategory');
  processValidation(document.brandForm, document.getElementById("errorMsg"));
}

/*-- ADD LINK FORM */
function validateLink() {
	hasError = 0;
	validateText(document.linkForm.url);
	validateText(document.linkForm.title);
	validateText(document.linkForm.title);
	processValidation(document.linkForm, document.getElementById("errorMsg"));
}

/*-- AVAILABILITY FORM */
function validateAvailability() {
  hasError = 0;
  validateSelect(document.availForm.placeId, 0); 
  validateText(document.availForm.itemCost);
  processValidation(document.availForm, 
                    document.getElementById("availErrorMsg"));
}



// place/show add availability
function validateAvailabilityFromPlace() { 
  hasError = 0;
  if (document.availForm.itemId === "0") { hasError = 1; }
  validateSelect(document.availForm.sizeId); 
  validateText(document.availForm.itemCost);
  if (hasError) { $('#errorMsg').show(); }
  else { processAvailabilityFromPlace(); }
}


/*-- RATING FORM */
function validateRating() {
	hasError = 0;
	validateTextArea(document.ratingForm.rReviewTxt);
	processValidation(document.ratingForm, document.getElementById("ratingErrorMsg"));
}

/*-- BLOG OPTIONS FORM */
function validateBlogOptions() {
	hasError = 0;
	validateText(document.blogOptionsForm.title);
	processValidation(document.blogOptionsForm, document.getElementById("errorMsg"));
}

/*-- BLOG POST FORM */
function validateBlogPost() {
  hasError = 0;
  validateText(document.blogPostForm.title);
  validateText(document.blogPostForm.blogPost);
  processValidation(document.blogPostForm, document.getElementById("blogPostEditErrorMsg"));
}

/*-- CITY ADD FORM */
function validateCity() {
  hasError = 0;
  validateSearchAhead('country');
  //validateSearchAhead('region');
  validateText(document.cityForm.city);
  processValidation(document.cityForm, document.getElementById("errorMsg"));
}


/*-- MEAL VALIDATION */
function validateMeal() {
  hasError = 0;
  validateText(document.mealForm.mealName);
  if (document.mealForm.ingredStr.value.length === 0) { hasError = 1; }
  processValidation(document.mealForm, document.getElementById("errorMsg"));
}


/*-- ALCOHOL NUTRITION VALIDATION */
function validateAlcoholNutrition() {
  hasError = 0;
  validateText(document.nutritionForm.abv);
  processValidation(document.nutritionForm, document.getElementById("errorMsg"));
 }

/*-- NEW USER VALIDATION */
function validateUser() {
	hasError = 0;
	
	validateText(document.userForm.username);
	validateText(document.userForm.email);
	validateText(document.userForm.userCode);
	
	if (hasError) { 
	  document.getElementById("errorMsg").innerHTML = "You must enter the highlighted values!";
	}
	
	validatePasswords(document.userForm.password, document.userForm.password2);
	processValidation(document.userForm, document.getElementById("errorMsg"));
}


/*---------------------------------------------------------------------------*/

/* RETURNS TRUE IF ID IS NOT BLANK */
function checkBlank(id) {
	var x = document.getElementById(id);
	var blank = isBlank(x);
	if (blank) { x.focus(); }
	return !blank;
}



function confirmCompanyDelete(id) { 
  if (confirm("Are you sure you want to delete this company?")) { 
    window.location = '/company/delete?id='+id;
  }
}



function confirmItemDelete(id) { 
  if (confirm("Are you sure you want to delete this item?")) { 
    window.location = '/item/delete?id='+id;
  }
}


function confirmItemSizeDelete(sizeId) {
  if (confirm("Are you sure you want to delete this item size?")) { 
    var url = '/item/sizeDelete?id='+$('#id').val()+'&sizeId='+sizeId;
    $.ajax({
      url: url, 
      success: function(data) { 
        $('#itemSize'+sizeId).fadeOut(300);
        $('#itemSizeComma'+sizeId).fadeOut(300);
      }
    });
  }
}



function confirmPlaceDelete(id) { 
  if (confirm("Are you sure you want to delete this place?")) { 
    window.location = '/places/delete?id='+id;
  }
}


function confirmTypeDelete(id) {
  if (confirm("Are you sure you want to delete this type?")) {
    window.location = '/type/delete?id='+id;
  }
}

