function validateLogin() {
	var username = document.login_form.username.value;
	var password = document.login_form.password.value;
	
	if (username == "") {
		alert("You must enter a username.");
		document.login_form.username.focus();
		return false;
	}
	if (password == "") {
		alert("You must enter a password.");
		document.login_form.password.focus();
		return false;
	}
	
	encodePassword(password);
}

function validateEmail(email) {
	// E-mail Validation by Henrik Petersen / NetKontoret
	// Explained at www.echoecho.com/jsforms.htm
	// Please do not remove this line and the two lines above.
	apos=email.indexOf("@"); 
	dotpos=email.lastIndexOf(".");
	lastpos=email.length-1;
	if (apos<1 || dotpos-apos<2 || lastpos-dotpos>3 || lastpos-dotpos<2) {
		return false;
	} else {
		return true;
	}
}

function encodePassword(password) {
    var hash = hex_md5(password);
	document.login_form.password.value = hash;
	return true;
}

function cancelAdmin(section) {
	document.forms[0].action = baseUrl+"/"+section;
	document.forms[0].submit();	
}

function replaceChars(entry) {
	out = "\\"; // replace this
	add = "/";  // with this
	temp = "" + entry; // temporary holder

	while (temp.indexOf(out)>-1) {
		pos= temp.indexOf(out);
		temp = "" + (temp.substring(0, pos) + add + 
		temp.substring((pos + out.length), temp.length));
	}
	return temp;
}

function isNumeric(strString) {
	var strValidChars = "0123456789";
	var strChar;
	var blnResult = true;

	if (strString.length == 0) return false;
	//  test strString consists of valid characters listed above
	for (i = 0; i < strString.length && blnResult == true; i++) {
		strChar = strString.charAt(i);
		if (strValidChars.indexOf(strChar) == -1) {
			blnResult = false;
		}
	}
	return blnResult;
}

function isPhone(strString) {
	var strValidChars = "0123456789()+- ";
	var strChar;
	var blnResult = true;

	if (strString.length == 0) return false;
	//  test strString consists of valid characters listed above
	for (i = 0; i < strString.length && blnResult == true; i++) {
		strChar = strString.charAt(i);
		if (strValidChars.indexOf(strChar) == -1) {
			blnResult = false;
		}
	}
	return blnResult;
}

function confirmDelete(path) {
	if (confirm("Are you sure want to delete this entry from the database?")) {
		window.location = baseUrl+path;
	}
}


function addLeadNotes(type) {
	new Ajax.Updater('notes_div', baseUrl+'/lead/ajaxAddNotes', { 
        method:'post', postBody:'lead_id='+$F('lead_id')+'&lead_notes='+$F('lead_notes'), 
        onComplete: function() {
            document.getElementById('lead_notes').value = "";
        }
    });
}

function addAction(type) {
	document.edit_form.action = baseUrl+"/"+type+"/addAction";
	document.edit_form.submit();	
}

function resetLeadFilter() {
    document.filter_form.product_id.value = -1;
    document.filter_form.status_id.value = -1;
    document.filter_form.owner_id.value = -1;
    document.filter_form.source_id.value = -1;
    document.filter_form.priority_id.value = -1;
    document.filter_form.submit();
}

function showNewSource(sourceId) {
    if (sourceId == '0') {
        document.getElementById('new_source_div').style.display = 'block';
        document.getElementById('new_source').focus();
    } else {
        document.getElementById('new_source_div').style.display = 'none';
    }
}

function toggleContactDate() {
    toggleField = document.getElementById('toggle_contact_date');

    if (toggleField.checked) {
        showBlock('contact_date_div');
    } else {
        hideBlock('contact_date_div');
    }
}

function toggleLastContactDate() {
    toggleField = document.getElementById('toggle_last_contact_date');

    if (toggleField.checked) {
        showBlock('last_contact_date_div');
    } else {
        hideBlock('last_contact_date_div');
    }
}

function toggleFollowupDate() {
    toggleField = document.getElementById('toggle_followup_date');

    if (toggleField.checked) {
        showBlock('followup_date_div');
    } else {
        hideBlock('followup_date_div');
    }
}

function hideBlock(divId) {
	document.getElementById(divId).style.display = "none";
}

function showBlock(divId) {
	document.getElementById(divId).style.display = "block";
}

function validateProductForm() {
    productName = document.getElementById('product_name');
    if (productName.value == "") {
    	alert ('You must provide a product name.');
    	productName.focus();
    	return false;
    }
    
    var priceType = document.edit_form.price_type;
    for (i=0; i<priceType.length; i++) {
    	if (priceType[i].checked) {
    		priceTypeSelection = priceType[i].value;
    	}
    }
    price = document.getElementById('price');
    if (priceTypeSelection == 1 && price.value == "") {
    	alert ('You must provide a fixed price.');
    	return false;
    }
    
    return true;
}

function finishUpdate() {
    document.edit_form.complete.value = "true";
    document.edit_form.submit();
}

function toggleNewContact(state) {
    if (state == 1) {
        showBlock('hide_new_contact_div');
        hideBlock('show_new_contact_div');
        
        showBlock('new_contact_div');
        document.getElementById('contact_name').focus();
        
        document.getElementById('show_new_contact').value = "Y";
    } else {
        showBlock('show_new_contact_div');
        hideBlock('hide_new_contact_div');
        
        hideBlock('new_contact_div');
        
        document.getElementById('show_new_contact').value = "N";
    }
}

function toggleContacts(state) {
    if (state == 1) {
        showBlock('hide_contacts_div');
        hideBlock('show_contacts_div');
        
        showBlock('contacts_div');
        
        document.getElementById('show_contacts').value = "Y";
    } else {
        showBlock('show_contacts_div');
        hideBlock('hide_contacts_div');
        
        hideBlock('contacts_div');
        
        document.getElementById('show_contacts').value = "N";
    }
}

function addNewContact() {
    var contactName = document.getElementById('contact_name').value;
	var phone = document.getElementById('contact_phone').value;
	var mobile = document.getElementById('contact_mobile').value;
	var email = document.getElementById('contact_email').value;
	if (contactName.value == "") {
		alert("You must enter a contact name.");
		document.getElementById('contact_name').focus();
		return;
	}
	if (phone != "" && !isPhone(phone)) {
		alert("Your phone number contains invalid characters");
		document.getElementById('contact_phone').focus();
		return;
	}
	if (mobile != "" && !isPhone(mobile)) {
		alert("Your mobile number contains invalid characters");
		document.getElementById('contact_mobile').focus();
		return;
	}
	if (email != "" && !validateEmail(email)) {	    
		alert("You must enter a valid email address");
		document.getElementById('contact_email').focus();
		return;
	}
	
	document.getElementById('add_contact').value = "Y";
	document.edit_form.submit();
}

function validateUserForm() {
	var username = document.getElementById('username');
	var password = document.getElementById('password');
	var verifyPassword = document.getElementById('verify_password');
	
	if (username.value == "") {
		alert("You must enter either a username.");
		username.focus();
		return false;
	}
	if (password.value == "") {
	    alert("You must provide a password.");
	    password.focus();
		return false;
	}
	if (verifyPassword.value == "") {
	    alert("You must retype the password.");
	    verifyPassword.focus();
		return false;
	}
	if (verifyPassword.value != password.value) {
	    alert("Your passwords do not match - please retype.");
	    verifyPassword.select();
		return false;
	}
	
	return true;
}

function validateUpdateUserForm() {
	var password = document.getElementById('password');
	var verifyPassword = document.getElementById('verify_password');
	
	if (password.value != "") {
    	if (verifyPassword.value == "") {
    	    alert("You must retype the password.");
    	    verifyPassword.focus();
    		return false;
    	}
    	if (verifyPassword.value != password.value) {
    	    alert("Your passwords do not match - please retype.");
    	    verifyPassword.select();
    		return false;
    	}
	}
	return true;
}

function adminForm(type) {
    document.filter_form.action = baseUrl+"/broker/add"+type;
	document.filter_form.submit();	
}

function valButton(btn) {
    var cnt = -1;
    for (var i=btn.length-1; i > -1; i--) {
        if (btn[i].checked) {cnt = i; i = -1;}
    }
    if (cnt > -1) {
		return btn[cnt].value;
	}  else {
		return null;
	}
}

function showNewCategory() {
    categoryId = document.getElementById('category_id').value;
    
    if (categoryId == '0') {
        document.getElementById('new_category_div').style.display = 'block';
        document.getElementById('new_category').focus();
    } else {
        document.getElementById('new_category_div').style.display = 'none';
    }
}

function toggleNewLeadContact() {
    contactDiv = document.getElementById('contact_div');
    if (contactDiv.style.display == "display") {
        document.getElementById('contact_full_name').value = "";
    }
    new Effect.toggle(contactDiv, 'slide');
}

function toggleNewClientContact() {
    contactDiv = document.getElementById('contact_div');
    if (contactDiv.style.display == "display") {
        document.getElementById('contact_full_name').focus();
    }
    new Effect.toggle(contactDiv, 'slide');
}

function addLeadContact() {
    new Ajax.Updater('lead_contacts', baseUrl+'/lead/ajaxAddContact', { 
        method:'post', postBody:'lead_id='+$F('lead_id')+'&contact_full_name='+$F('contact_full_name')+
        	'&contact_role='+$F('contact_role')+'&contact_phone='+$F('contact_phone')+'&contact_mobile='+$F('contact_mobile')+
        	'&contact_email='+$F('contact_email'), 
        onComplete: function() {
            newContactDiv = document.getElementById('lead_contact_div');
            contactsDiv = document.getElementById('lead_contacts');
            clearLeadContactForm();
            new Effect.toggle(newContactDiv, 'slide');
            new Effect.Highlight(contactsDiv, 'slide');
        }
    });
}

function addClientContact() {
    new Ajax.Updater('client_contacts', baseUrl+'/client/ajaxAddContact', { 
        method:'post', postBody:'client_id='+$F('client_id')+'&admin_name='+$F('admin_name')+'&admin_role='+$F('admin_role')+'&admin_phone='+$F('admin_phone')+'&admin_mobile='+$F('admin_mobile')+'&admin_email='+$F('admin_email'), 
        onComplete: function() {
            newContactDiv = document.getElementById('client_contact_div');
            contactsDiv = document.getElementById('client_contacts');
            clearClientContactForm();
            new Effect.toggle(newContactDiv, 'slide');
            new Effect.Highlight(contactsDiv, 'slide');
        }
    });
}

function clearLeadContactForm() {
    document.getElementById('contact_full_name').value = "";
    document.getElementById('contact_role').value = "";
    document.getElementById('contact_phone').value = "";
    document.getElementById('contact_mobile').value = "";
    document.getElementById('contact_email').value = "";
}

function toggleProductSet() {
    productsDiv = document.getElementById('product_set');
    new Effect.toggle(productsDiv, 'slide');
}

function reloadBrokerProducts() {
    new Ajax.Updater('broker_products', baseUrl+'/broker/ajaxGetBrokerProducts', { 
        method:'post', postBody:'broker_id='+$F('broker_id')
        });
}

function toggleAppointment() {
    appointmentDiv = document.getElementById('appointment_div');
    if (appointmentDiv.style.display == "none") {
        new Effect.toggle(appointmentDiv, 'slide');
        hideBlock('toggle_appointment');
    } else {
        new Effect.toggle(appointmentDiv, 'slide');
        document.getElementById('toggle_appointment').style.display = "inline";
    }
}

function addAppointment() {
    new Ajax.Updater('next_appointment', baseUrl+'/broker/ajaxAddAppointment', { 
        method:'post', parameters:Form.serialize(document.edit_form), 
        onComplete: function() {
            newAppointmentDiv = document.getElementById('appointment_div');
            appointmentsDiv = document.getElementById('next_appointment');
            clearAppointmentForm();
            new Effect.toggle(newAppointmentDiv, 'slide');
            new Effect.Highlight(appointmentsDiv, 'slide');
            showBlock('edit_appointment');
        }
    });
}

function clearAppointmentForm() {
    document.getElementById('appointment_notes').value = "";
}

function deleteAppointment() {
    appointmentId = document.getElementById('appointment_id').value;
    
	if (confirm("Are you sure want to delete this appointment "+appointmentId+"?")) {
		new Ajax.Updater('next_appointment', baseUrl+'/broker/ajaxDeleteAppointment', { 
            method:'post', postBody:'appointment_id='+$F('appointment_id'), 
            onComplete: function() {
                hideBlock('edit_appointment');
                showBlock('schedule_appointment');
                showBlock('next_appointment');
                document.getElementById('next_appointment').innerHTML = "None scheduled";
            }
        });
	}
}

function resetAppointmentFilter() {
    document.getElementById('broker_id').value = -1;
    document.getElementById('user_id').value = -1;
    document.filter_form.submit();
}

function toggleLeadDetails() {
    detailsDiv = document.getElementById('lead_details');
    new Effect.toggle(detailsDiv, 'slide');
}

function toggleStatusUnchanged() {
    toggleField = document.getElementById('status_unchanged');
    statusField = document.getElementById('status_id');

    if (toggleField.checked) {
        statusField.disabled = true;
    } else {
        statusField.disabled = false;
    }
}

function toggleOwnerUnchanged() {
    toggleField = document.getElementById('owner_unchanged');
    ownerField = document.getElementById('owner_id');

    if (toggleField.checked) {
        ownerField.disabled = true;
    } else {
        ownerField.disabled = false;
    }
}

function toggleRecurPeriod() {
    toggleField = document.getElementById('recurring');

    if (toggleField.checked) {
        document.getElementById('recur_div').style.display = 'inline';
    } else {
        hideBlock('recur_div');
    }
}

function toggleFixedPrice() {
    var priceType = document.edit_form.price_type;
    for (i=0; i<priceType.length; i++) {
    	if (priceType[i].checked) {
    		priceTypeSelection = priceType[i].value;
    	}
    }

    if (priceTypeSelection == 1) {
        showBlock('price_div');
    } else {
        hideBlock('price_div');
    }
}

function toggleFollowUpDate() {
    var followUpSelection = document.getElementById('follow_up').selectedIndex;
    var followUpId = document.getElementById('follow_up').options[followUpSelection].value;

    if (followUpId == 0) {
        document.getElementById('follow_up_div').style.display = 'inline';
    } else {
        hideBlock('follow_up_div');
    }
}

function validateProjectForm() {
    title = document.getElementById('title');
    summary = document.getElementById('summary');
    var categorySelection = document.getElementById('category_id').selectedIndex;
    var categoryId = document.getElementById('category_id').options[categorySelection].value;
    
    if (title.value == "") {
    	alert ('You must provide a project title.');
    	title.focus();
    	return false;
    }
    if (summary.value == "") {
    	alert ('You must provide a project summary.');
    	summary.focus();
    	return false;
    }
    if (categoryId == -1) {
    	alert ('You must select a project category.');
    	document.getElementById('category_id').focus();
    	return false;
    }
     if (categoryId == 0 && newCategory.value) {
    	alert ('You must select a project category.');
    	document.getElementById('category_id').focus();
    	return false;
    }
    return true;
}

function addProject() {
    document.filter_form.action = baseUrl+"/project/add";
	document.filter_form.submit();
}

function confirmMigrate(leadId) {
	if (confirm("Are you sure want to migrate this lead to a client?")) {
		window.location = baseUrl+'/lead/migrate/'+leadId;
	}
}

function showNewCategory(categoryId) {
    if (categoryId == '0') {
        showBlock('new_category_div');
        document.getElementById('new_category').focus();
    } else {
        hideBlock('new_category_div');
    }
}

function addProjectImage() {
    imageName = document.getElementById('image_name');
    if (imageName.value == "") {
        alert("You must specify an image file. Click Browse...");
		imageName.focus();
		return;
    }
    
    new Ajax.Updater('images_div', baseUrl+'/project/ajaxAddImage', { 
        method:'post', parameters:Form.serialize(document.edit_form), 
        onComplete: function() {
            document.getElementById('image_name').value = "";
            document.getElementById('caption').value = "";
        }
    });
}

function deleteProjectImage(imageId) {
    if (confirm("Are you sure want to delete this image?")) {
		new Ajax.Updater('images_div', baseUrl+'/project/ajaxDeleteImage', { 
            method:'post', postBody:'image_id='+imageId+'&project_id='+$F('project_id')
        });
	}
}

function projectImagesTab() {
    if (validateProjectForm()) {
        document.getElementById('add_images').value = "Y";
        document.edit_form.submit();
    }
}

function toggleResults(section) {
    var divName = section + "_results";
    resultsDiv = document.getElementById(divName);
    new Effect.toggle(resultsDiv, 'slide');
}


function validateContactForm() {
	var fullName = document.getElementById('full_name');
	var email = document.getElementById('email');
	var phone = document.getElementById('phone');
	var query = document.getElementById('query');
	
	if (fullName.value == "") {
		alert("You must enter your full name.");
		fullName.focus();
		return false;
	}
	if (email.value == "" && phone.value == "") {
		alert("You must enter either a phone number or email address.");
		email.focus();
		return false;
	}
	if (email.value != "") {
		if (!validateEmail(email.value)) {
    		alert("You must enter a valid email address");
    	    email.focus();
    		return false;
    	}
	}
	if (phone.value != "" && !isPhone(phone.value)) {
		alert("The phone number contains invalid characters.");
		email.focus();
		return false;
	}
	if (query.value == "") {
		alert("You must enter a query.");
		query.focus();
		return false;
	}
	return true;
}