﻿

//Move the contact list along with the user as they scroll down the document.
function updateContactListPosition() {    
    var mainDivOffset = (mainDiv.cumulativeOffset())[1];
    var topOffset = (body.cumulativeScrollOffset())[1] - mainDivOffset + 20;
    topOffset = (topOffset < 100) ? 100 : topOffset;
    topOffset = (topOffset > 464) ? 464 : topOffset;
    //alert(topOffset + " " + mainDivOffset);
    //contactListDiv.setStyle({top: topOffset+'px'});
    if(!editWindowOpen){
        new Effect.Move(contactListDiv, {x: 20, y: topOffset, mode: 'absolute', duration: 0.2});
    }
    setTimeout('updateContactListPosition()', 250);
}

function showInstructions(linkelem){
    var linkelem = $(linkelem);
    var offset = linkelem.cumulativeOffset();
    $('instructions').setStyle( {left: (offset[0] - 420)+"px",
                                 top: (offset[1]-120)+"px",
                                 visibility: 'visible'});
}
function hideInstructions(){
    $('instructions').setStyle( {visibility: 'hidden'} );
}

function ordainedContactClick(){
    alert("Clergy automatically receive a printed subscription.");
}

function waitingOnAjax(){
    return (waiting_on_ajax == true);
}

function setWaitingOnAjax(val){
    waiting_on_ajax = val;
}


//Old function used in development for highlighting records
function highlightOnlyContactDiv(thediv){
    thediv = $(thediv);
    var siblings = thediv.siblings();
    for (var i=0; i<siblings.length; i++){
        unhighlightContactDiv(siblings[i]);
    }
    highlightContactDiv(thediv);
}
//Old function used in development for highlighting records
function highlightContactDiv(thediv){
    $(thediv).removeClassName('contactrec').addClassName('contactrec_hi');
}
//Old function used in development for highlighting records
function unhighlightContactDiv(thediv){
    $(thediv).removeClassName('contactrec_hi').addClassName('contactrec');
}

//Return true if the element specified by container_elem contains an item
//with the given id.
function hasChildElementWithAttributeEqualing(container_elem, attr, value) {
    var elems = $(container_elem).childElements();
    for(var i=0; i < elems.length; i++){
        if(elems[i].getAttribute(attr) == value){
           return true;
        }
    }
    return false;
}





//---------------Contact Edit Window Functions-----------------------------

//Use an ajax call to retrieve a form for editing the contact specified by contactGuid and
//show that form in the edit window using showEdit()
function editContact(contactGuid) {
    if (waitingOnAjax() == true) {
        return;
    }
    
    setWaitingOnAjax(true);
    
    var scrollOffset = body.cumulativeScrollOffset();
    new Ajax.Request('editcontact.aspx',
        {
            method: 'get',
            parameters: { guid: contactGuid,
                          rand: Math.random() },
            onSuccess: function (transport) {
                var response = transport.responseText;  
                showEdit(response, 100, scrollOffset[1]+140);
                Event.observe('editContactForm', 'submit', SaveContactInEditWindow);
                $('ContactNameFirstName').select();
                setWaitingOnAjax(false);
            },
            onFailure: function() { alert("There was a problem retrieving the edit form"); 
                                    setWaitingOnAjax(false); }
    });
    return false;
}

//Use an ajax call to retrieve a form for editing the subscription specified by subtype and 
//subguid and show that form in the edit window using showEdit()
function editSubscription(subtype, subguid) {
    if (waitingOnAjax() == true) {
        return;
    }
    setWaitingOnAjax(true);

    var scrollOffset = body.cumulativeScrollOffset();
    /*var params = $H({type: subtype,
                          guid: subguid,
                          rand: Math.random() });
    alert(params.toQueryString());*/
    new Ajax.Request('editsubscription.aspx',
        {
            method: 'get',
            parameters: { type: subtype, 
                          guid: subguid, 
                          rand: Math.random() },
            onSuccess: function (transport) {
                var response = transport.responseText;
                showEdit(response, 250, scrollOffset[1]+200);
                Event.observe('editSubscriptionForm', 'submit', SaveSubscriptionInEditWindow);
                $('laityselect1').focus();
                setWaitingOnAjax(false);
            },
            onFailure: function() { alert("There was a problem retrieving the edit form"); 
                                    setWaitingOnAjax(false); }
    });
}

function addContact(churchnum){
    if (waitingOnAjax() == true) {
        return;
    }
    setWaitingOnAjax(true);
    
    var scrollOffset = body.cumulativeScrollOffset();
    new Ajax.Request('addcontact.aspx',
        {
            method: 'get',
            parameters: { churchnum: churchnum,
                          rand: Math.random() },
            onSuccess: function (transport) {
                var response = transport.responseText;
                showEdit(response, 250, scrollOffset[1]+200);
                $('ContactNameFirstName').focus();
                Event.observe('addContactForm', 'submit', addContactNextStep);
                setWaitingOnAjax(false);
            },
            onFailure: function() { alert("There was a problem retrieving the add form"); 
                                    setWaitingOnAjax(false); }
    });
}

function validateAddContact()
{
    var AddStep = parseInt($F('AddStep'));

    if (AddStep == 2){
        var valid = validateEditContact();
        if (!valid) return false;
    }
    else if (AddStep == 3) {
        var createorupdate = $F('CreateOrUpdate');
        var radioval = $RF('addContactForm', 'contactradio');
        if(trim(createorupdate) == "update" && isEmpty(radioval)){
            alert("Please select a contact to use.");
            return false;
        }
    }
    return true;
}

/**
* Returns the value of the selected radio button in the radio group, null if
* none are selected, and false if the button group doesn't exist
*
* @param {radio Object} or {radio id} el
* OR
* @param {form Object} or {form id} el
* @param {radio group name} radioGroup
*/
function $RF(el, radioGroup) {
    if($(el).type && $(el).type.toLowerCase() == 'radio') {
        var radioGroup = $(el).name;
        var el = $(el).form;
    } else if ($(el).tagName.toLowerCase() != 'form') {
        return false;
    }
 
    var checked = $(el).getInputs('radio', radioGroup).find(
        function(re) {return re.checked;}
    );
    return (checked) ? $F(checked) : null;
}

function addContactNextStep(evt){
    Event.stop(evt);
    
    var valid = validateAddContact();
    if (!valid) return;
    
    if (waitingOnAjax() == true) {
        return;
    }
    setWaitingOnAjax(true);
    
    var addContactForm = $('addContactForm');
    //alert($H(addContactForm.serialize(true)).toQueryString());
    new Ajax.Request('addcontact.aspx',
        {
            parameters: addContactForm.serialize(true),
            onSuccess: function (transport) {
                var response = transport.responseText;
                $('editMenu').update(response);
                Event.observe('addContactForm', 'submit', addContactNextStep);
                setWaitingOnAjax(false);
            },
            onFailure: function() { alert("There was an error in retrieving the form"); 
                                    setWaitingOnAjax(false); }
     });
}  

function finishAddContact()
{
    hideEdit();
    refreshLists(); 
}
     

//Add subscription of the given subscription type for the church specified by
//churchnum and contact specified by contactid using an Ajax call. Fill the
//element fillelement with the contents of the response.
function addSubscription(subtype, year, churchnum, contactid, prevsubid, fillelement) {
    /*var params = $H({type: subtype,
                          year: year,
                          churchnum: churchnum,
                          contactid: contactid,
                          prevsubid: prevsubid,
                          rand: Math.random() });
    alert(params.toQueryString());*/
    
    if (fillelement) {
        var spinner = new Element('img', {'src': 'static/images/ajax-loader.gif', 
                                          'class': 'ajaxloader'});
        $(fillelement).appendChild(spinner);
    }
    new Ajax.Request('addnewsub.aspx',
        {
            method: 'get',
            parameters: { type: subtype,
                          year: year,
                          churchnum: churchnum,
                          contactid: contactid,
                          prevsubid: prevsubid,
                          rand: Math.random() },
            onSuccess: function (transport) {
                var response = transport.responseText;
                if (fillelement && !response.startsWith("error: ")){
                    $(fillelement).replace(response);
                }else {
                    alert("There was a problem in creating the new subscription. \n" +
                          response.substring(7));
                    if(fillelement){
                        $(fillelement).remove();
                    }
                }
            },
            onFailure: function() { 
                alert("There was a problem creating the new subscription"); 
                if (fillelement) {
                    $(fillelement).remove();
                }
            }
    });
}

function removeContactFromChurch(contactid, churchnum, contactrecord) 
{
    if(global_internal_user == "false"){
        var answer = confirm("Are you sure you want to remove this contact from your church membership?");
        if (!answer) return;
    }
    
    new Ajax.Request('removecontact.aspx',
        {
            method: 'get',
            parameters: { contactid: contactid,
                          churchnum: churchnum,
                          rand: Math.random() },
            onSuccess: function (transport) {
                var response = transport.responseText;
                if (response == "error"){
                    alert("There was an error performing the operation");
                    return;
                }
                if (contactrecord) {
                    $(contactrecord).remove();
                    refreshLists();
                }
            },
            onFailure: function() {
                alert("There was a problem perfoming the requested operation"); 
            }
    });
} 

function removeSubscription(subtype, subguid, subrecord)
{
    /*var params = $H({type: subtype,
                          subguid: subguid,
                          rand: Math.random()});
    alert(params.toQueryString());*/
    
    if(global_internal_user == "false"){
        var answer = confirm("Are you sure you want to delete this subscription?");
        if (!answer) return;
    }
    
    new Ajax.Request('removesubscription.aspx',
        {
            method: 'get',
            parameters: { subtype: subtype,
                          subguid: subguid,
                          rand: Math.random() },
            onSuccess: function (transport) {
                var response = transport.responseText;
                if (response == "error"){
                    alert("There was an error performing the operation");
                    return;
                }
                if (subrecord) {
                    $(subrecord).remove();
                }
            },
            onFailure: function() {
                alert("There was a problem perfoming the requested operation"); 
            }
    });
    
    return false;                 
}               
            

//Used in the edit contact window to update editable address fields with the currently selected
//address, selected in the "AddressSelect" select element.
function FillAddressFields(){
    var AddressSelect = $('AddressSelect');
    
    if (AddressSelect.value == "NewAddress"){
        $('AddressAddr1').value = "";
        $('AddressAddr2').value = "";
        //$('AddressCity').value = "";
        //$('StateSelect').selectedIndex = 0;
        $('AddressZip').value = "";
    } else {
        var SelectedAddr = Addresses[AddressSelect.value];    
        $('AddressAddr1').value = SelectedAddr.Addr1;
        $('AddressAddr2').value = SelectedAddr.Addr2;
        //$('AddressCity').value = SelectedAddr.City;
        //$('StateSelect').selectedIndex = GetIndexFromValue('StateSelect', SelectedAddr.StateGuid);
        $('AddressZip').value = SelectedAddr.Zip;
    }
}

function FillEmailField() {
    var EmailSelect = $('EmailSelect');
    if (EmailSelect.value == "NewEmail") {
        $('EmailAddress').value = "";
	document.getElementById("EmailAddress").style.color = "#000000";
    } else {
	var email = EmailSelect.options[EmailSelect.selectedIndex].text;
        $('EmailAddress').value = email;
	new Ajax.Request('checkbademail.aspx',
        {
            method: 'get',
            parameters: { email: email, 
                          rand: Math.random() },
            onSuccess: function (transport) {
                var response = transport.responseText;
		if (response == "True") {
		    document.getElementById("EmailAddress").style.color = "red";
		} else {
		    document.getElementById("EmailAddress").style.color = "#000000";
		}

            },
            onFailure: function() { alert("There was a problem checking for a bad email address.");}
	});

    }
}
    
//Get the numerical index of the option in the select element specified by selectname with value
//val. Will return the first number with the specified value.
function GetIndexFromValue(selectname, val) {
    var SelectElem = $(selectname);
    for(var i = 0; i < SelectElem.length; i++) {
        var cur = SelectElem.options[i];
        if(cur.value == val){
            return i;
        }
    }
}


//Save the information using an Ajax call for the contact being edited in the edit window.
function SaveContactInEditWindow(evt) {
    Event.stop(evt);
    
    //If the user hit cancel instead.
    if($('editContactForm') == null){
        return;
    }
    
    var valid = validateEditContact();
    if (!valid) return;
    
    var editContactForm = $('editContactForm');
    //Do validation
    //Show spinning thingy...
    new Ajax.Request('savecontact.aspx',
            {
            parameters: editContactForm.serialize(true),
            onSuccess: function (transport) {
                var response = transport.responseText;  
                if (response.startsWith("error: ")){
                    alert("There was a problem saving the contact. \n" + response.substring(7));
                    return;
                }
                hideEdit();
                refreshLists();
            },
            onFailure: function() { alert("The contact could not be saved."); }
    });
}

function SaveSubscriptionInEditWindow(evt) {
    Event.stop(evt);
    
    var valid = validateEditSubscription();
    if (!valid) return;
    
    var editSubscriptionForm = $('editSubscriptionForm');
    //Do validation
    //Show spinning thingy...
    new Ajax.Request('savesubscription.aspx',
            {
            parameters: editSubscriptionForm.serialize(true),
            onSuccess: function (transport) {
                var response = transport.responseText;  
                if (response.startsWith("error: ")){
                    alert("The subscription could not be saved. \n" + response.substring(7));
                }
                hideEdit();
                refreshLists();
            },
            onFailure: function() { alert("There was an error saving this subscription"); }
    });
}

//Hide the edit window.
function hideEdit(){
    editWindowOpen = false;
    $('editMenu').update('');
    $('editMenu').remove();
    $('mask').remove();
    //$('mask').setStyle( {'visibility':'hidden'} );
}

//Show the edit window and update it's contents with the text in editContents,
//also place the window according to the position and size given. The edit window
//will function as a dialog, disallowing further clicking until the window is 
//dismissed.
function showEdit(editContents, pos_left, pos_top) {
    editWindowOpen = true;
    var edit = new Element('div', {'id': 'editMenu'});
    var left = (document.viewport.getWidth() - 200) / 2;

    var mask = new Element('div', {'id': 'mask'});
    var w = body.getWidth();
    var h = body.getHeight();
    body.appendChild(mask);
    $('mask').setStyle( {'visibility':'visible', 'top':'0px', 'left':'0px', 'width':w+"px", 'height':h+"px"} );
    new Effect.Opacity('mask', { from: 1.0, to: 0.7, duration: 0});
    
    edit.update(editContents);
    body.appendChild(edit);
    edit.setStyle({'left': pos_left+'px', 'top': pos_top+'px'});
}


//Old function for creating a dummy record used during development.
function createCurrentSubElement(source) {
   	//var member = new Element('div', {'id': source.id + '_currentsub', 'class': 'cursubrec'});
   	var member = new Element('div');
    $(member).update('Church Member 1<br />');
	
    var address = new Element('div', {'class': 'subbox address'});
    $(address).update('Address Line 1<br />Address Line 2<br />City, State Zip');

    var subs = new Element('div', {'class': 'subs'});
    $(subs).update('<b>Subscription Period:</b> 1/08 - 12/08<br /><b>Laity Codes:</b><br />5 - Administration<br />10 - Lay Leadership Committee Chair');

    member.appendChild(address);
    member.appendChild(subs);

    return member; 
}


//--------------Validation Routines-----------------------

function validateExternalLogin()
{
    var custnum = $F('custnum');
    var passwd = $F('passwd');
    var name = $F('name');
    var phone = $F('phone');
    var email = $F('email');
    
    if(!isNumeric(trim(custnum)) || trim(custnum).length != 8){
        alert("Customer number must be 8 digits.");
        return false;
    }
    
    if(!isAlphaNum(trim(passwd))){
        alert("Password cannot be null and must be only letters and numbers.");
        return false;
    }
    
    if(!isAlpha(name)){
        alert("Name cannot be null and must be only letters.");
        return false;
    }
    
    if(!isPhoneNumber(phone)){
        alert("Phone number incorrect or in wrong format.");
        return false;
    }
    
    if(!isEmail(email)){
        alert("Email address not in valid format.");
        return false;
    }
    
    return true;    
}

function validateInternalLogin()
{
    var username = $F('username');
    var password = $F('password');
    
    if(!isAlphaNum(trim(username))){
        alert("Username cannot be null and must be only letters and numbers.");
        return false;
    }
    
    if(!isAlphaNum(trim(password))){
        alert("Password cannot be null and must be only letters and numbers.");
        return false;
    }
    
    return true;
}

function validateEditContact()
{   
    var title = $F('NameTitle');
    var firstname = $F('ContactNameFirstName');
    var lastname = $F('ContactNameLastName');
    var addressselect = ($('AddressSelect') == null) ? null : $F('AddressSelect');
    var address1 = $F('AddressAddr1');
    var address2 = $F('AddressAddr2');
    //var city = $F('AddressCity');
    //var stateselect = $F('StateSelect');
    var zip = $F('AddressZip');
    var emailselect = ($('EmailSelect') == null) ? null : $F('EmailSelect');
    var emailaddress = $F('EmailAddress');
    
    if (!isAlpha(firstname)){
        alert("First Name cannot be blank and must be only letters.");
        return false;
    }
    if (!isAlpha(lastname)){
        alert("Last Name cannot be blank and must be only letters.");
        return false;
    }
    if (!isAddress(address1)){
        alert("Address Line 1 cannot be blank and must be only letters and numbers.");
        return false;
    }
    if (!isEmpty(address2) && !isAddress(address2)){
        alert("Address Line 2 must be only letters and numbers.");
        return false;
    }
    /*if (!isAlpha(city)){
        alert("City cannot be blank and must be only letters and numbers.");
        return false;
    }
    if (isEmpty(stateselect)) {
        alert("Please select a state.");
        return false;
    }*/
    if (!isZip(zip)){
        alert("Zip cannot be blank and must be in the correct format.");
        return false;
    }
    if (!isEmpty(emailaddress) && !isEmail(emailaddress)){
        alert("Email cannot be blank and must be in the correct format.");
        return false;
    }
    return true;
}

function validateEditSubscription()
{
    var laity1 = $F('laityselect1');
    var laity2 = $F('laityselect2');
    
    if (isEmpty(laity1)) {
        alert("Please specify the first laity code.");
        return false;
    }
    return true;
}

function validateChooseChurchForm()
{
    var churchnum = $F('churchnumber');
    var batch = $F('batchnumber');
    
    if(!isAlphaNum(churchnum)){
        alert("Church number cannot be blank and must be only letters and numbers.");
        return false;
    }
    if(!isNumeric(batch)){
        alert("Batch number cannot be blank and must be only numbers.");
        return false;
    }
    return true;
}

function trim(val) { 
        if(val != null && val != "")
            return val.replace(/^\s+|\s+$/g, ''); 
        return val;
}

function isEmpty(val)
{
    return (val == null || trim(val) == "");
}

function isAlphaNum(val)
{
    return (!isEmpty(val) && val.match(/^([a-zA-Z_0-9]|\s)*$/) != null);
}

function isAlpha(val)
{
    return (!isEmpty(val) && val.match(/^([a-zA-Z.&]|\s)*$/) != null);
}

function isAddress(val) 
{
    return (!isEmpty(val) && val.match(/^([-a-zA-Z_.:&/#0-9]|\s)*$/) != null);
}

function isNumeric(val)
{
    return (!isEmpty(val) && val.match(/^\d+$/) != null);
}

function isPhoneNumber(val)
{
    return (!isEmpty(val) && val.match(/^(\()?\d{3}(\))?([-.]|\s)*\d{3}([-.]|\s)?\d{4}$/) != null);
}

function isEmail(val)
{
    return (!isEmpty(val) && val.match(/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*([,;]\s*\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)*/) != null);
}

function isZip(val)
{
    return (!isEmpty(val) && val.match(/^\d{5}(-\d{4})?$/) != null);
}





//--------------Drag and Drop Functions-------------------

//Function that is executed when an item is dropped in the "Current Subscriptions" list
function currentSubDropped (draggable, droppable, evt) {
    if (subtype == "freeprint"|| subtype == "freedigital") {
        var subid = draggable.getAttribute("subid");
        var contactid = draggable.getAttribute("contactid");
        var churchnum = draggable.getAttribute("churchnum");
	var bademail = draggable.getAttribute("bademail");
        
        if (hasChildElementWithAttributeEqualing(droppable, "contactid", contactid)) {
            alert("The contact you tried to add is already receiving a subscription. Please select another contact.");
            return;
        }
        
        if (droppable.childElements().length >= 5) {
            alert('Only five current subscriptions are allowed at this time.');
            return;
        }

	if (subtype == "freedigital"){
	    if (bademail == "True"){
		alert("This contact has an undeliverable email address.  Please edit the contact before adding a digital subscription");
		return;
	    }
	}

	new Ajax.Request('checkexistingsubscriptions.aspx',
        {
            method: 'get',
            parameters: { type: subtype,
                          year: (global_year-1),
                          churchnum: churchnum,
                          contactid: contactid,
                          prevsubid: subid,
                          rand: Math.random() },
            onSuccess: function (transport) {
                var response = transport.responseText;
                if (!response.startsWith("error: ")){
		    var answer = confirm(response);
		    if (!answer) return;
		}
		var newSub = new Element('div', {'class': 'newsubrec'});
		droppable.appendChild(newSub);
		addSubscription(subtype, (global_year-1), churchnum, contactid, subid, newSub);
		new Draggable (newSub, {revert: true});
            },
            onFailure: function() { 
                alert("There was a problem checking for existing subscriptions."); 
            }
    });
    }
}
           
//Function that is executed when an item is dropped in the "New Subscriptions" list
//This retrieves any information it can from attributes of the dropped item, and then
//makes a call to create the subscription based on those parameters.
function newSubDropped (draggable, droppable, evt) {
    
    var subid = draggable.getAttribute("subid");
    var contactid = draggable.getAttribute("contactid");
    var churchnum = draggable.getAttribute("churchnum");
    var bademail = draggable.getAttribute("bademail");
    
    if (hasChildElementWithAttributeEqualing(droppable, "contactid", contactid)) {
        alert("The contact you tried to add is already receiving a subscription. Please select another contact.");
        return;
    }
    
    if (subtype != "paidprint" && subtype != "paiddigital"){
        if (droppable.childElements().length >= 5) {
            alert('Only five digital subscriptions are allowed for renewal.');
            return;
        }
    }

    if (subtype == "freedigital" || subtype == "paiddigital"){
	if (bademail == "True"){
	    alert("This contact has an undeliverable email address.  Please edit the contact before adding a digital subscription");
	    return;
	}
    }

    new Ajax.Request('checkexistingsubscriptions.aspx',
        {
            method: 'get',
            parameters: { type: subtype,
                          year: global_year,
                          churchnum: churchnum,
                          contactid: contactid,
                          prevsubid: subid,
                          rand: Math.random() },
            onSuccess: function (transport) {
                var response = transport.responseText;
                if (!response.startsWith("error: ")){
		    var answer = confirm(response);
		    if (!answer) return;
		}
		var newSub = new Element('div', {'class': 'newsubrec'});
		droppable.appendChild(newSub);
		addSubscription(subtype, global_year, churchnum, contactid, subid, newSub);
		new Draggable (newSub, {revert: true});
            },
            onFailure: function() { 
                alert("There was a problem checking for existing subscriptions."); 
            }
    });
}                       


//Initialize the various components for the dragging and dropping system, i.e.
//set up the scriptaculous Draggables and Droppables.
function initDragAndDrop(){
    initDraggables($('contactlist'), 'contactrec');
    initDraggables($('currentsubs'));

    Droppables.add('currentsubs',{
                    accept:['contactrec'], 
                    onDrop: currentSubDropped
                });   

    Droppables.add('newsubs',{
                    accept:['contactrec', 'cursubrec'], 
                    onDrop: newSubDropped
                }); 

    /*Droppables.add('main', {
                    accept:['cursubrec', 'newsubrec'],
                    onDrop: function (element) {
                        $(element).remove();
                    }
                });*/
} 

function initDraggables(parentDiv, classname){
    if (parentDiv) {
        var items = $(parentDiv).childElements();
        items.each( function(item) {
            if(classname == null || item.hasClassName(classname)){
                new Draggable(item, {
                                revert:true,
                                detached: true
                              });
            }
        });
    }
}
                                

function refreshLists()
{
    new Ajax.Request('datafeeder.aspx',
            {
            method: 'get',
            parameters: { churchnum: global_churchnum,
                          data: 'contacts',
                          year: global_year,
                          rand: Math.random() },
            onSuccess: function (transport) {
                var response = transport.responseText;  
                $('contactlist').update(response);
                initDraggables($('contactlist'), 'contactrec');
            },
            onFailure: function() { alert("There was an error refreshing the data"); }
    });
    
    
    
    if (subtype == "freeprint" || subtype == "freedigital") {
        var data = subtype;
        //Current year subs
        new Ajax.Request('datafeeder.aspx',
            {
            method: 'get',
            parameters: { churchnum: global_churchnum,
                          data: subtype,
                          year: String(parseInt(global_year) - 1),
                          rand: Math.random() },
            onSuccess: function (transport) {
                var response = transport.responseText;  
                $('currentsubs').update(response);
                initDraggables($('currentsubs'));
            },
            onFailure: function() { alert("There was an error refreshing the data"); }
        });
        
        //Next years subs (Enroll year subs)
        new Ajax.Request('datafeeder.aspx',
            {
            method: 'get',
            parameters: { churchnum: global_churchnum,
                          data: subtype,
                          year: global_year,
                          rand: Math.random() },
            onSuccess: function (transport) {
                var response = transport.responseText;  
                $('newsubs').update(response);
            },
            onFailure: function() { alert("There was an error refreshing the data"); }
        });
    }
    
    else if (subtype == "paidprint" || subtype == "paiddigital") {
        new Ajax.Request('datafeeder.aspx',
            {
            method: 'get',
            parameters: { churchnum: global_churchnum,
                          data: subtype,
                          year: global_year,
                          rand: Math.random() },
            onSuccess: function (transport) {
                var response = transport.responseText;  
                $('currentsubs').update(response);
                $('newsubs').update('');
                initDraggables($('currentsubs'));
            },
            onFailure: function() { alert("There was an error refreshing the data"); }
        });
    }    
}


//---------------Onload events...-----------------

function pageInit(){
    body = $(document.getElementsByTagName("body").item(0))
    contactListDiv = $('contactlistdiv');
    mainDiv = $('main');
    
    var queryStringHash = $H(window.location.search.toQueryParams());
    subtype = queryStringHash.get("subtype");
    
    waiting_on_ajax = false;
    
    //Event.observe('addcontactbutton', 'click', addContact);
    
    if(contactListDiv){
        editWindowOpen = false;
        initDragAndDrop();
        updateContactListPosition();
        
        //If sub type is paid, make div titles a color (red) to signify working with paid subs
        if(subtype == "paidprint" || subtype == "paiddigital"){
           $('currentsubstitle').addClassName("paidsubstitle");
           $('newsubstitle').addClassName("paidsubstitle");
        } 

    }
}


Event.observe(window, 'load', pageInit);
