function setCookie(name, value) {
    document.cookie = name + "=" + escape(value) + "; path=/;";
    //alert(name+" ==> "+value); 
}

function expireCookie(name) {
	thisCookie = document.cookie.split("; ")
	for (i=0; i<thisCookie.length; i++) {
		if (name == thisCookie[i].split("=")[0]) { expireDate = new Date
			expireDate.setDate(expireDate.getDate()-1)
			document.cookie = name + "=;expires=" + expireTime.toGMTString()
		}
	}
}

function getRawCookie(name) {
	thisCookie = document.cookie.split("; ")
	for (i=0; i<thisCookie.length; i++) {
		if (name == thisCookie[i].split("=")[0]) {
			return thisCookie[i].split("=")[1]
		}
	}
}
function getCookie(name) {
    rawval = getRawCookie(name);
    if(rawval) {
        return unescape(rawval);
    }
} 

/* Note that the following code uses the ntrim() function defined in util.js */

function getFormInputValue( form, name ) {
    var element = form.elements[name];
    if(! element) return null;
    return ntrim(element.value);
}

function getFormRadioValue( form, name ) {
    var elements = form.elements[name];
    if(! elements) return null;
    for(j=0; j<elements.length;j++) {
        element = elements[j];
        if(element.checked) {
           return ntrim(element.value); 
        }
    }
    return null;
}

function getFormCheckboxValue( form, name ) {
    var element = form.elements[name];
    if(element && element.checked) return "Yes";
    return "No";
}

// DEPRECATED: remove eventually...
function setNoteCookies( form ) {
    var tmp = null;
    tmp = getFormInputValue( form, 'notenames' );
    if(tmp == null) tmp = "";
    else tmp += ";";
    tmp += "giftname;giftaddress1;giftaddress2;giftcity;giftstate;giftzip1;giftzip2";
    if(tmp) {
        notenames = tmp.split(";");
        for (i=0;i<notenames.length;i++) {
            notename = notenames[i];
            var val = getFormInputValue( form, notename );
            if(! val) continue;
            setCookie(notename, val);
        }
    }
    tmp = getFormInputValue( form, 'notenames_radio' );
    if(tmp) {
        notenames = tmp.split(";");
        for (i=0;i<notenames.length;i++) {
            notename = notenames[i];
            var val = getFormRadioValue(form, notename);
            if(! val) continue;
            setCookie(notename, val);
        }
    }
    tmp = getFormInputValue( form, 'notenames_checkbox' );
    if(tmp) {
        notenames = tmp.split(";");
        for (i=0;i<notenames.length;i++) {
            notename = notenames[i];
            var val = getFormCheckboxValue(form, notename);
            setCookie(notename, val);
        }
    }
}


function setBillingAddressCookie( form ) {
    var data = "";
    var names = new Array('billname', 'billaddress1', 'billaddress2', 'billcity', 'billstate', 'billzip1', 'billzip2', 'billcountry', 'homeareacode', 'homephone1', 'homephone2', 'areacode', 'phone1', 'phone2', 'email');
    for (i=0;i<names.length;i++) {
        name = names[i];
        var val = getFormInputValue( form, name );
        if(val == null) val = "";
        if(data) data += "\t";
        data += name;
        data += ":";
        data += val;

    }
    setCookie("billingAddressData",data);
}

function setShippingFields( form ) {
    var mail_to = getFormRadioValue( form, "mail to" );
    if(mail_to == null) return;
    var names = new Array('name', 'address1', 'address2', 'city', 'state', 'zip1', 'zip2', 'country');
    for (i=0;i<names.length;i++) {
        name = names[i];
        if(mail_to == "recipient") {
            var val = getFormInputValue( form, "gift"+name );
            if(val == null) val = "";
            form.elements["ship"+name].value = val;
        } else if(mail_to == "buyer"){
            form.elements["ship"+name].value = "";
        }
    }
}

/*
This function assumes that the data about required fields
is passed as a hidden input named "required", whose value
is a semicolon-delimited list of strings where each string
is a colon-delimited list of 3 strings: "name:type:title".
name is the name of the form field.
type is one of "radio", "checkbox", "text".
title is a label of the field for the generated error message.
*/
function validateRequiredFields( form ) {
    var missing = new Array();
    var tmp = getFormInputValue( form, 'required' );
    if(tmp) {
        requirednamestitles = tmp.split(";");
        for (i=0;i<requirednamestitles.length;i++) {
            requirednametitle = requirednamestitles[i];
            var tmpary = requirednametitle.split(":");
            requiredname = tmpary[0];
            requiredtype = tmpary[1];
            requiredtitle = tmpary[2];
            var val = null;
            if(requiredtype == 'radio') {
                val = getFormRadioValue( form, requiredname );
            } else if(requiredtype == 'checkbox') {
                val = getFormCheckboxValue( form, requiredname );
            } else {
                val = getFormInputValue( form, requiredname );
            }
            if(val == null) {
                missing[missing.length] = requiredtitle;
            }
        }
        if(missing.length > 0) {
            var message = "The following information is required:\n\n";
            for (var i=0;i<missing.length;i++) {
                message += " - "+missing[i]+"\n";
            }
            alert(message);
            return false;
        }
    }
    return true;
}

function handleFormSubmit( form ) {
    if( validateRequiredFields(form) ) {
        setBillingAddressCookie( form );
        setShippingFields( form );
        //setNoteCookies( form );
        return true;
    }
    return false;
}


function handleDonationFormSubmit( form ) {
    var priceString = getFormInputValue( form, 'price' );
    if(priceString == null) {
        alert("Please enter your donation amount.");
        return false;
    }
    var price = parseInt(priceString, 10);
    if(isNaN(price) || price < 0) {
        alert("Please enter your donation amount.");
        return false;
    }
    var tmp = getFormInputValue( form, 'minimum_price' );
    if(tmp) {
      var min = parseInt(tmp, 10);
      var max = parseInt( getFormInputValue( form, 'maximum_price' ), 10 );
      if(price < min || price > max) {
        alert("Please enter a donation amount between $"+min+" and $"+max+".");
        return false;
      }
    }
    return true;
}


function handleAdoptionFormSubmit( form ) {
    var portion_to_area = getFormRadioValue(form, 'portion to area');
    var portion_to_programs = getFormRadioValue(form, 'portion to programs');
    if (
         (portion_to_area == 'all' && portion_to_programs == 'half')
         ||
         (portion_to_area == 'half' && portion_to_programs == 'none')
       ) {
        alert("Please make selections to distribute all of your donation amount.");
        return false;
    }
    return true;
}


function handleIndividualMembershipFormSubmit( form ) {
    var children = getFormInputValue(form, 'children');
    var grandchildren = getFormInputValue(form, 'grandchildren');
    if (children && grandchildren) {
        alert("Please enter only children or grandchildren -- not both.");
        return false;
    }
    return true;
}

