/* ----------------------------------------------------------------------
	MAIN
	$Id: forms.js,v 1.9 2009-03-13 16:27:50 mmozdyniewicz Exp $
---------------------------------------------------------------------- */

function checkSearchForm(form, inputId) {
	if (inputId == null || inputId == '')
		inputId = "search-clause";

	var input = document.getElementById(inputId);
	if (!input) {
		alert("Input " + inputId + " not found!");
		return false;
	}

	if (input.value == "" || input.value == 'Wyszukiwana fraza')
		return focusFailedInput(inputId, "Podaj szukane wyra\u017Cenie");

	return true;
}

function checkAdvancedSearchForm() {
	return checkInput("search-clause-adv", "Podaj szukane wyra\u017Cenie");
}

function checkContactForm() {
	return checkEmail("contact_email", "Podaj prawid\u0142owy adres email!")
			&& checkTextarea("contact_message",
					"Podaj tre\u015B\u0107 wiadomo\u015Bci!");
}

function checkOpinionForm() {
	return checkTextarea("opinion_message",
			"Podaj tre\u015B\u0107 wiadomo\u015Bci!");
}

/*
 * ----------------------------------------------------------------------
 * DEFAULT VALIDATION FORMS
 * ----------------------------------------------------------------------
 */
function getFormElementValue(inputId) {
	var input = document.getElementById(inputId);
	if (!input) {
		alert("Input " + inputId + " not found!");
		return null;
	}

	return input.value;
}

function checkInput(inputId, errorMessage) {
	var input = document.getElementById(inputId);
	if (!input) {
		alert("Input " + inputId + " not found!");
		return false;
	}

	if (input.value == "")
		return focusFailedInput(inputId, errorMessage);

	return true;
}

function compareFields(fieldId1, fieldId2, errorMessage) {
	var field1 = document.getElementById(fieldId1);
	if (!field1) {
		alert("Element " + fieldId1 + " not found!");
		return false;
	}

	var field2 = document.getElementById(fieldId2);
	if (!field2) {
		alert("Element " + fieldId2 + " not found!");
		return false;
	}

	if (field1.value != field2.value)
		return focusFailedInput(fieldId2, errorMessage);

	return true;
}

function checkTextarea(inputId, errorMessage) {
	var input = document.getElementById(inputId);
	if (!input) {
		alert("Textarea " + inputId + " not found!");
		return false;
	}

	if (input.value.length <= 3)
		return focusFailedInput(inputId, errorMessage);

	return true;
}

function checkEmail(inputId, errorMessage) {
	var input = document.getElementById(inputId);
	if (!input) {
		alert("Input " + inputId + " not found!");
		return false;
	}

	if (!isValidEmail(input.value)) {
		focusFailedInput(inputId, errorMessage);
		return false;
	}
	return true;
}

function checkZIP(countryInputId, inputId, errorMessage) {
	var zip = document.getElementById(inputId);
	var country = document.getElementById(countryInputId);

	if (!zip) {
		alert("Input " + inputId + " not found!");
		return false;
	}
	if (!country) {
		alert("Input " + countryInputId + " not found!");
		return false;
	}

	if (country[country.selectedIndex].value == "PL" && !isValidZIP(zip.value)) {
		focusFailedInput(inputId, errorMessage);
		return false;
	}
	return true;
}

function isValidZIP(zip) {
	var pattern = new RegExp('^\\d{2}-\\d{3}$');
	var patternStop = new RegExp('^00-000$');
	return (pattern.test(zip) && !patternStop.test(zip));
}

function isValidEmail(email) {
	var template = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,6})+$/;
	if (template.test(email) == false)
		return false;
	return true;
}

function clearError() {
	var labels = document.getElementsByTagName("label");

	for ( var i = 0; i < labels.length; i++) {
		var label = labels[i];
		removeClassName(label, "error");
	}
	return true;
}

function focusFailedInput(inputId, errorMessage) {
	var labels = document.getElementsByTagName("label");

	var tmplabel;
	// set error class to correct label and remove error class from others
	for ( var i = 0; i < labels.length; i++) {
		var label = labels[i];
		removeClassName(label, "error");
		// if anything will be wrong, remove break statement
		// KCI -> KCI i think it is wrong 'couse it coulnd not loop to the end
		if (label.htmlFor == inputId) {
			addClassName(label, "error");
			break;
		}
	}

	// TODO: $ all getElementById should use this pattern
	var element;
	if (typeof inputId == "string")
		element = document.getElementById(inputId);
	else
		element = inputId;

	if (errorMessage) {
		alert(errorMessage);
		element.focus();
	}

	return false;
}

function checkRadio(form, input, errorMessage, inputId) {
	var tmpForm = document.getElementById(form);
	if (tmpForm)
		form = tmpForm;

	if (!form[input]) {
		alert("Element " + input + " not found!");
		return false;
	}

	if (!form[input].length) // 1 input
	{
		if (form[input].checked)
			return true;
		return focusFailedInput(inputId, errorMessage);
	}

	var i = 0;
	for (i; i < form[input].length; i++)
		if (form[input][i].checked == true)
			break;

	if (i == form[input].length)
		return focusFailedInput(inputId, errorMessage);

	return true;
}

function groupFields(name, id, cnt, message) {
	var count = parseInt(cnt);
	for ( var i = 1; i <= count; i++)
		if (document.getElementById(id + "_" + i, message).value == "")
			return true;
	return focusFailedInput(id + "_1", message);
}

function groupEmails(name, id, cnt, message) {
	var template = /^[0-9a-z]+[0-9a-z._-]*\@[0-9a-z]+[0-9a-z._-]*\.[0-9a-z]{2,}$/i;
	var count = parseInt(cnt);
	for ( var i = 1; i <= count; i++)
		if (template.test(document.getElementById(id + "_" + i, message).value) == true)
			return true;
	return focusFailedInput(id + "_1", message);
}

function checkPESEL(inputId, errorMessage) {
	var input = document.getElementById(inputId);
	if (!input) {
		alert("Input " + inputId + " not found!");
		return false;
	}

	if (!validatePESEL(input.value))
		return focusFailedInput(inputId, errorMessage);
	return true;
}

function validatePESEL(pesel) {
	// basic check
	if (pesel.length != 11)
		return false;

	// check date
	var month = parseInt(pesel.slice(2, 4), 10);
	if (month == 0 || month > 12)
		return false;
	var day = parseInt(pesel.slice(4, 6), 10);
	if (day == 0 || day > 31)
		return false;
	var year = parseInt(pesel.slice(0, 2), 10) + 1900;

	if (month > 20 && month < 40) {
		year += 100;
	} else if (month > 80) {
		year -= 100;
	} else if (month > 60) {
		year += 300;
	} else if (month > 40) {
		year += 200;
	}

	var bornString = ((month < 10 ? "0" : "") + month) + "/"
			+ ((day < 10 ? "0" : "") + day) + "/" + ("" + year);
	// nice regexp ;)
	var RegExPattern = /^(?=\d)(?:(?:(?:(?:(?:0?[13578]|1[02])(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})|(?:0?2(\/|-|\.)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))|(?:(?:0?[1-9])|(?:1[0-2]))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2}))($|\ (?=\d)))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;
	if (!bornString.match(RegExPattern))
		return false;

	// calculate crc
	var steps = new Array(1, 3, 7, 9);
	var crc = 0;
	for ( var i = 0; i < 10; i++)
		crc += steps[i % 4] * parseInt(pesel[i]);
	crc = 10 - (crc % 10);
	if (crc == 10)
		crc = 0;

	return crc == parseInt(pesel[10]);
}

function toggleDisplay(objId, display) {

	var obj = document.getElementById(objId);
	if (display == true || display == 1) {
		obj.style.display = 'block';
	} else {
		obj.style.display = 'none';
	}
}

function verifyAttributes(obj) {
	var sels = obj.form.getElementsByTagName('select');

	for (i = 0; i < sels.length; i++) {
		if (isAttribute(sels[i].name) && sels[i].selectedIndex == 0) {
			alert('Proszę podać ' + sels[i].title + ' dla : '
					+ sels[i].id.substring(0, sels[i].id.length - 5));
			sels[i].focus();
			return false;
		}
	}
	obj.form.submit();
	return true;
}

function isAttribute(txt) {

	if (txt.indexOf('color') == 0 || txt.indexOf('size') == 0) {
		return true;
	}

	return false;
}

function sort(field, formId, order) {

	var f = document.getElementById(formId);
	var s = document.getElementById('sort_hidden')
	if (s != null) {
		s.value = order + field;
	}
	var o = document.getElementById('order_hidden')
	if (o != null) {
		o.value = order;
	}

	f.submit();
}

function checkFormChangepassword(aForm) {

	if (aForm['form_changepassword_password1'].value != aForm['form_changepassword_password2'].value) {
		alert("Powtórzone hasło ma inną wartość.");
		aForm['form_changepassword_password2'].focus();
		return false;
	}
	return true;
}

/* clear all fields and fade/unfade reset link - product front list view */

function clearInit() {
	var form = $('#reset_link').parents().find("form#filter_form");
	$('input[type=reset]').addClass('hidden');
	$('#reset_link').removeClass('hidden');
	$('#reset_link').click(function() {
		clearForm(form);
		setDefault(form);
		$(this).addClass('faded');
		return false;
	});
}

function clearForm(form) {
	$(':input', form).each( function() {
		var type = this.type;
		var tag = this.tagName.toLowerCase();
		//alert(type+', '+tag);
		if (type == 'text' || type == 'password' || tag == 'textarea')
			this.value = "";
		else if (type == 'checkbox' || type == 'radio')
			this.checked = false;
		else if (tag == 'select')
			this.selectedIndex = 0;
	}).change( function() { $('#reset_link').removeClass('faded'); });
};

function setDefault(form) {
	$(':input', form).each( function() {
		var id = this.getAttribute('id');
		if(id != null && id.indexOf('all')!=-1)
			this.checked = true;
	});
}