   
    var loginFlag       = 0;
    var formSubmitted   = false;
    var clickedSubscribe= false;
    var isNewUser       = false;
    
    function checkMailList(){
        $('#mailSubscribeAll').removeAttr('checked');
        subscribeMarkProfile();
    }
    
    function checkMailListAll(){
        $('.mailingCheckbox').attr('checked','checked');
    }
    
    function buildPage(setup,email,zip){
        loginFlag = setup;
        switch(setup){
            /* user is not auth, show email & zip fields */
            case 1  :   $('#nextButton').attr('src','/images/continue.png'); toggleLayer('profileLoginDiv'); break;
            
            /* user is authed, show profile display & specific form */
            case 2  :   do_userProfile(); break;
            
            /* user is authed & has completed the specific form is session, show profile & specific form result content */ 
            case 3  :   do_userProfile(); break;
            
            /* open login */
            default :   toggleLayer('profileLoginDiv'); 
        }
            
    }

    //=================//
    //     SESSION     //
    //=================//
    function do_session_cb(result){
        $('#debug_area').html(result);
    }
    
    function do_session(){
        var sess = $('#debug_area').html();
        
        if(sess == ''){ x_session(do_session_cb); }
        else { $('#debug_area').html(''); }
    }
    
    //======================//
    //     USER PROFILE     //
    //======================//
    function do_userProfile_cb(result){
        $('#profileWorkerDiv').html(result);
        
        hideLayer('profileLoginDiv'); // close login
        showLayer('profileWorkerDiv'); // show profile
        
        if(loginFlag < 3){
            showLayer('specificFormDiv'); // show form
            window.setTimeout('resetFormSize()',500);
        } else {
            window.setTimeout('resetProfileSize()',500);
        }
        
        if(loginFlag == 3 ){ showLayer('specificFormDoneDiv'); } // show thanks
    }
    
    function do_userProfile(){
        x_userProfile(do_userProfile_cb);
    }
    
    function resetProfileSize(){
        /* The resizing can be done using .height() and .animate() */
    
        // Reset the bottom of the form to just below the continue button
        if(skipResize == '' && $('#continue_button_profile')){
            var isNav = (navigator.appName.indexOf("Netscape") !=-1);
            var formBtn = document.getElementById('continue_button_profile').offsetTop;
            var formTop = document.getElementById('profileEntryDiv').offsetTop;
        
            //var contPos = formBtn - formTop + 30;
            if(isNav){
                var contPos = formBtn - formTop + 270;
            } else {
                var contPos = formBtn + 270;
            }

            $('#profileEntryDiv').height(contPos+'px');
        }
    }
    //======================//
    //     PROFILE FORM     //
    //======================//
    function do_buildProfileForm_cb(result){
        $('#profileEntryDiv').html(result);
        
            
        $('#subMailingList').is(':checked')     ? $('#mailingList').attr('checked','checked')   : '';
        $('#subMailSales').is(':checked')       ? $('#mailSales').attr('checked','checked')     : '';
        $('#subMailRoad').is(':checked')        ? $('#mailRoad').attr('checked','checked')      : '';
        $('#subMailProduct').is(':checked')     ? $('#mailProduct').attr('checked','checked')   : '';
        $('#subMailHealth').is(':checked')      ? $('#mailHealth').attr('checked','checked')    : '';
        $('#subMailCooking').is(':checked')     ? $('#mailCooking').attr('checked','checked')   : '';
        $('#subMailNewsAlerts').is(':checked')  ? $('#mailNewsAlerts').attr('checked','checked'): '';
        
        $('#checkAllMail').is(':checked')       ? $('#mailSubscribeAll').click() : '';
        $('#mailCatalog').is(':checked')        ? $('#catalog').click() : '';        


        showLayer('profileEntryDiv');  /* show profile entry */
        hideLayer('profileWorkerDiv'); /* hide profile summary*/
        hideLayer('specificFormDiv');  /* hide form */
        hideLayer('profileLoginDiv');  /* hide login */
        
        window.setTimeout('resetProfileSize()', 1000);
    }
    
    
    function do_buildProfileForm(event){
        var login_email = $('#login_email').val();
        var login_zip   = $('#login_zip').val();
        x_buildProfileForm(login_email,login_zip,do_buildProfileForm_cb);
    }
    //
    
    //=========================//
    //     PROCESS PROFILE     //
    //=========================//
    function do_processProfile_cb(result){
        $('#profileWorkerDiv').html(result);
        
        hideLayer('profileEntryDiv');  // close profile entry
        hideLayer('profileRequiredFields');  // any error message areas
        
        // show subscribe message
        if(mailStatusChanged){
            subscribed = 0;
            
            if($('#mailingList').attr('checked')){ subscribed = 1; }
            if($('#mailSales').attr('checked')){   subscribed = 1; }
            if($('#mailRoad').attr('checked')){    subscribed = 1; }
            if($('#mailProduct').attr('checked')){ subscribed = 1; }
            if($('#mailHealth').attr('checked')){  subscribed = 1; }
            if($('#mailCooking').attr('checked')){  subscribed = 1; }
            if($('#mailNewsAlerts').attr('checked')){  subscribed = 1; }
            
            
            if(subscribed){ $('#profile_message_area').html(''); }
            else { $('#profile_message_area').html("<b>You've been unsubscribed from Cabot's Mailings.</b>"); }
        } else {
            $('#profile_message_area').html('');
        }

        showLayer('profileWorkerDiv'); // close profile
        showLayer('specificFormDiv');  // show form
        window.setTimeout('resetFormSize()',500);
        mailStatusChanged = false;
    }
    
    function do_processProfile(event){
        var title               = $('#title').val();
        var firstName           = $('#firstName').val();
        var lastName            = $('#lastName').val();
        var birthYear           = $('#birthYear').val();
        var profile_zip         = $('#profile_zip').val();
        var profile_email       = $('#profile_email').val();
        var profile_address1    = $('#profile_address1').val();
        var profile_address2    = $('#profile_address2').val();
        var profile_city        = $('#profile_city').val();
        var profile_state       = $('#profile_state').val();
        
        var catalog             = 0;
        var mailingList         = 0;
        var mailSales           = 0;
        var mailRoad            = 0;
        var mailHealth          = 0;
        var mailProduct         = 0;
        var mailCooking         = 0;
        var mailNewsAlerts      = 0;
        
        
        if($('#mailingList').attr('checked')){ mailingList = 1; }
        if($('#mailSales').attr('checked')){   mailSales   = 1; }
        if($('#mailRoad').attr('checked')){    mailRoad    = 1; }
        if($('#mailProduct').attr('checked')){ mailProduct = 1; }
        if($('#mailHealth').attr('checked')){  mailHealth  = 1; }
        
        if($('#mailCooking').attr('checked')){  mailCooking  = 1; }
        if($('#mailNewsAlerts').attr('checked')){  mailNewsAlerts  = 1; }
                

        ok = true;
        
        if(!isNotEmpty('firstName')){ $('#firstName').addClass('badInputClass'); ok = false; }
        else { $('#firstName').addClass('goodInputClass'); }
        
        if(!isNotEmpty('lastName')){ $('#lastName').addClass('badInputClass'); ok = false; }
        else { $('#lastName').addClass('goodInputClass'); }
        
        if(!isNotEmpty('profile_email')){ $('#profile_email').addClass('badInputClass'); ok = false; }
        else { $('#profile_email').addClass('goodInputClass'); }
        
        if(birthYear != '' && !isYear('birthYear')){ $('#birthYear').addClass('badInputClass'); ok = false; }
        else { $('#birthYear').addClass('goodInputClass'); }
        
        if(profile_email != '' && !isEmail('profile_email')){ $('#profile_email').addClass('badInputClass'); ok = false; }
        else { $('#profile_email').addClass('goodInputClass'); }
        
        if(profile_zip != '' && !isZip('profile_zip')){ $('#profile_zip').addClass('badInputClass'); ok = false; }
        else { $('#profile_zip').addClass('goodInputClass'); }
        
        if($('[name=catalog]').is(':checked')){
            catalog             = $('#catalog').val();
        
            if(profile_address1 == ''){ $('#profile_address_1').addClass('badInputClass'); ok = false; }
            else { $('#profile_address1').addClass('goodInputClass'); }
            
            if(profile_state == ''){ $('#profile_state').addClass('badInputClass'); ok = false; }
            else { $('#profile_state').addClass('goodInputClass'); }
            
            if(profile_city == ''){ $('#profile_city').addClass('badInputClass'); ok = false; }
            else { $('#profile_city').addClass('goodInputClass'); }
        }

        if(ok){
            $('#profile_update').attr('src','images/profileUpdateDim.gif');
            subscribeWarningProfile();
            x_processProfile(title, firstName, lastName, birthYear, profile_email, profile_zip, profile_address1, profile_address2, profile_city, profile_state, catalog, mailingList, mailSales, mailRoad, mailProduct, mailHealth, mailCooking ,mailNewsAlerts, subscribeProfileMarked, do_processProfile_cb);
        } else {
        	showLayer('profileRequiredFields');
        }
        
        $('#checkAllMail').is(':checked')       ? $('#mailSubscribeAll').click() : '';
        $('#mailCatalog').is(':checked')        ? $('#catalog').click() : ''; 
    }
    
    //======================//
    //     USER LOOK UP     //
    //======================//
    function do_userLookUp_cb(result){
        if(result == 'authed'){
            isNewUser       = false;
            clickedSubscribe= false;
            do_userProfile();
        }
        if(result == 'emailOnFile'){
            isNewUser       = false;
            failureMsg      = '<span style="color:#C00">That email address is already on file. <br />However, it is listed under a different zip code.<br><br></span>If you created this profile while living in a different area please enter the zip code you would have used when you created the profile. An email address may only be used once to create a Cabot Profile.</i><br><br>';
            $('#login_prompt_area').html(failureMsg);
        }
        if(result == 'profileNotFound'){
            isNewUser = true;
            do_buildProfileForm();
        }
    }
    
    function do_userLookUp(fld){
        $('#nextButton').attr('src','/images/continueDisabled.png');
        
        var emailOK     = true;
        var zipOK       = true;
        var login_email = $('#login_email').val();
        var login_zip   = $('#login_zip').val();
        var action      = "neither";
               
        
        $('#zipAlertDiv').html('');
        $('#emailAlertDiv').html('');
        
        if((login_zip == '' || login_zip.length > 15 || login_zip.length < 5)){
            $('#zipAlertDiv').html('Invalid Zip');
            emailOK = false;
        }
        
        if(login_email == ''){
            $('#emailAlertDiv').html('Invalid Email');
            emailOK = false;
        }
        
        if(zipOK && emailOK){
            x_userLookUp(login_email, login_zip, action, do_userLookUp_cb);
        }
    }
    
    //======================//
    //     PROCESS FORM     //
    //======================//
    function do_processSpecificForm_cb(result) {
        if(result.length > 5){ $('#specificFormDoneDiv').html(result); }
        
        hideLayer('specificFormDiv'); 
        showLayer('specificFormDoneDiv'); 
    }
    
    function processSpecificForm(event){
        if(formSubmitted == true){ return false; }

        $('#specificFormErrorDiv').hide();
        
        var requiredFieldStr    = $('#form_required_fields').val();
        var requiredFields      = requiredFieldStr.split(',');
        
        var failedFields        = '';
        var failedFieldCount    = 0;
        var stopAt              = requiredFields.length;
        
        var i=0;
        for(i=0; i<stopAt; i++){
            fld = requiredFields[i];
            lbl = fld;

            if($('#'+fld).attr('type') == 'text' || $('#'+fld).attr('type') == 'select-one'){
                if(isNotEmpty(fld)){
                    $('#'+fld+'_label').removeClass();                 
                    $('#'+fld+'_label').addClass('goodInputClass');
                } else {
                    $('#'+fld+'_label').removeClass();                   
                    $('#'+fld+'_label').addClass('badInputClass');
                    
                    failedFields += ','+fld;
                    failedFieldCount++;
                }
            } else {
                lbl = fld + '_label';
                if(isNotEmpty(fld)){
                    $('#'+lbl).removeClass();
                } else {
                    $('#'+lbl).removeClass();                
                    $('#'+lbl).addClass('badInputClass');
                    
                    failedFields += ',' + fld;
                    failedFieldCount++;
                }
            }
        }
        
        var requiredTypeStr = $('#form_required_types').val();
        if(requiredTypeStr != ''){
            var requiredTypes = requiredTypeStr.split(',');
            
            for(i=0; i<requiredTypes.length; i++){
                specStr = requiredTypes[i];
                spec    = specStr.split(':');
                fld     = spec[0];
                func    = spec[1];
                val     = $('#'+fld).val();
                
                if(val != ''){
                    ok = true;

                    if(func == 'isYear'){       if(!isYear(fld)){       ok = false; } }
                    if(func == 'isPhone'){      if(!isPhone(fld)){      ok = false; } }
                    if(func == 'isZip'){        if(!isZip(fld)){        ok = false; } }
                    if(func == 'isEmail'){      if(!isEmail(fld)){      ok = false; } }
                    if(func == 'isDate'){       if(!isDate(fld)){       ok = false; } }
                    if(func == 'isCabotDate'){  if(!isCabotDate(fld)){  ok = false; } }
                    if(func == 'isSSN'){        if(!isSSN(fld)){        ok = false; } }
                    if(func == 'isNumeric'){    if(!isNumeric(fld)){    ok = false; } }

                    if(!ok){
                        $('#'+fld).addClass('badInputClass');
                        $('#'+fld+'_info').addClass('addInfoBad');
                        
                        failedFields += ',' + fld;
                        failedFieldCount++;
                    } else {
                        $('#'+fld).addClass('goodInputClass');
                        $('#'+fld+'_info').addClass('addInfo');
                    }
                }
            }
        }
        
        var fieldNameStr    = $('#form_field_names').val();
        var fieldNames      = fieldNameStr.split(',');

        if(failedFields == ''){
            formSubmitted = true;
            $('#nextButton').attr('src','/images/continueDisabled.png');
            
            if($('#continue_button').attr('src') == '/images/submit-green.gif' ){
                $('#continue_button').attr('src','/images/submit-gray.gif');
            }
            
            hideLayer('specificFormErrorDiv');

            var data = '';
            for(i=0; i<fieldNames.length; i++){
                if(data != ''){ data += '&'; }
                fld = fieldNames[i];
                if($('#'+fld).attr('type') == 'checkbox'){
                    if($('#'+fld).attr('checked')){ val = '1'; }
                    else { val = '0'; }
                } else if($('#'+fld).attr('type') == 'radio' && (! $('#'+fld).is(':checked')) ){
                    continue; // skip this radio button
                } else if($('#'+fld).attr('type') == 'radio' && $('#'+fld).is(':checked')){
                                       
                    val = $('#'+fld).val();
                    fld = $('#'+fld).attr('name');
                } else {
                    val = escape($('#'+fld).val());
                }
                
                itm = fld + '=' + val;
                data += itm;
            }
            
            saveDataPieces(data);                                    
        } else {
            $('#specificFormErrorDiv').html('Oops! There are errors with your submission.<br>Please check the indicated fields below:');
            
            error_message = "You've missed " + failedFieldCount + " required field";
            if(failedFieldCount > 1){ error_message = error_message + 's'; }
            $('#failed_fields_message_area').html(error_message);
            
            showLayer('specificFormErrorDiv');
            
            window.setTimeout('resetFormSize()',500);
        }
    }
    
    var dataIndex   = 0;
    var bufferData  = '';
    var bufferLimit = 1000;
    
    function saveDataPieces(all_data){
        var i       = dataIndex;
        
        if(bufferData == ''){ bufferData = all_data; }
        
        var blocks  = bufferData.length / bufferLimit;
        blocks = Math.floor(blocks);
        
        var send    = '';
        
        if(i == blocks){ send = bufferData.substring(bufferLimit * i,bufferData.length); }
        else if(i < blocks){ send = bufferData.substring(0 + (bufferLimit * i), bufferLimit + (bufferLimit * i)); }
        
        if(send != ''){ do_buffer_form_chunk(send); }       
        else { x_processSpecificForm(do_processSpecificForm_cb); }
    }
    
    function do_buffer_form_chunk(data){
        x_buffer_form_chunk(data,do_buffer_form_chunk_cb);            
    }
    
    function do_buffer_form_chunk_cb(phpRet){
        if(phpRet != 0){ alert("error code: " + phpRet); }
        else { dataIndex++; saveDataPieces('next'); }
    }
    
    //=========================//
    //     PROFILE OPTIONS     //
    //=========================//
    function returnToLogin(event){
        $('#nextButton').attr('src','/images/continue.png');
        
        showLayer('profileLoginDiv');
        hideLayer('profileWorkerDiv'); 
        hideLayer('specificFormDiv');  
        hideLayer('profileRequiredFields'); 
        hideLayer('profileEntryDiv'); 
    }
    
    
    function loadUpdateProfileForm(event){
        do_buildProfileForm('profileEntryDiv');
    }

    //========================//
    //     SHOW THANK YOU     //
    //========================//
    function do_thankYou_cb(result){
        $('#specificFormDoneDiv').html(result);
    }
    
    function do_thankYou(event){
        x_thankYou(do_thankYou_cb);
    }

    //=========================//
    //     SLIDEY GOODNESS     //
    //=========================//
    var slideInUse = new Array();
    
    function Slide(objId,options){
        this.obj = document.getElementById(objId);
        this.duration = 0.5;
        this.height = parseInt(this.obj.style.height);
    
        if(typeof options != 'undefined') { this.options = options; } else { this.options = {}; }
        if(this.options.duration) { this.duration = this.options.duration; }
            
        this.up = function(event){
            this.curHeight = this.height;
            this.newHeight = '1';
            if(slideInUse[objId] != true) {
                var finishTime = this.slide();
                window.setTimeout("Slide('"+objId+"').finishup("+this.height+");",finishTime);
            }
        }
        
        this.down = function(event){
            this.newHeight = this.height;
            this.curHeight = '1';
            if(slideInUse[objId] != true) {
                this.obj.style.height = '1px';
                this.obj.style.display = 'block';
                this.slide();
            }
        }
        
        this.slide = function(event){
            slideInUse[objId] = true;
            var frames = 30 * duration; /* Running at 30 fps */
    
            var tIncrement = (duration*1000) / frames;
            tIncrement = Math.round(tIncrement);
            var sIncrement = (this.curHeight-this.newHeight) / frames;
    
            var frameSizes = new Array();
            for(var i=0; i < frames; i++) {
                if(i < frames/2) {
                    frameSizes[i] = (sIncrement * (i/frames))*4;
                } else {
                    frameSizes[i] = (sIncrement * (1-(i/frames)))*4;
                }
            }
            
            for(var i=0; i < frames; i++) {
                this.curHeight = this.curHeight - frameSizes[i];
                window.setTimeout("document.getElementById('"+objId+"').style.height='"+Math.round(this.curHeight)+"px';",tIncrement * i);
            }
            
            window.setTimeout("delete(slideInUse['"+objId+"']);",tIncrement * i);
            
            if(this.options.onComplete) {
                window.setTimeout(this.options.onComplete, tIncrement * (i-2));
            }
            
            return tIncrement * i;
        }
        
        this.finishup = function(height){
            this.obj.style.display = 'none';
            this.obj.style.height = height + 'px';
        }
        
        return this;
    }
    
    
    function toggleLayer(objName,setHeight){            
        if(setHeight > 0){ $('#'+objName).height(setHeight + "px"); }
        
        if($('#'+objName).is(':visible')){ Slide(objName,'').up(); }
        else { Slide(objName,'').down(); }
    }
    
    function hideLayer(objName){        
        if($('#'+objName).is(':visible')){ Slide(objName,'').up(); }
    }
    
    function showLayer(objName,setHeight){            
        if(setHeight > 0){ $('#'+objName).height(setHeight + "px"); }

        if($('#'+objName).is(':hidden')){ Slide(objName,'').down(); }
    }
    
    function showImg(id,delay){
        var obj     = $('#'+id);
        var doIt    = setTimeout(function(event){ obj.show(); },delay);
    }

    
    function profileEmailChecked(event){
        subscribed = 0;
        
        if($('#mailingList').attr('checked')){  subscribed = 1; }
        if($('#mailSales').attr('checked')){    subscribed = 1; }
        if($('#mailRoad').attr('checked')){     subscribed = 1; }
        if($('#mailProduct').attr('checked')){  subscribed = 1; }
        if($('#mailHealth').attr('checked')){   subscribed = 1; }
        
        if(subscribed){ alert('Yes'); }
        else { alert('No'); }
    }

    function resetFormSize(){
        if(skipResize == '' && $('#continue_button')){            
            var $adjusted_height = 0;
            $('#specificFormDiv > table').each(function(event){
                $adjusted_height += $(this).height();
            });
            
            $adjusted_height += ($('#continue_button').height() + 150);
            
            if($('#specificFormErrorDiv').is(':visible')){
                $adjusted_height += $('#failed_fields_message_area').height();
                $adjusted_height += $('#specificFormErrorDiv').height();
            }
            
            $('#specificFormDiv').height($adjusted_height + 'px'); 
        }
    }

    function subscribeWarningLogin(event){
        // obj = $('#radioSubscribe');
        // if(obj.attr('checked')){
        //      alert("In order to receive our newsletters, sales offers, and delicious recipes, we need you to confirm your account with us. Please click on the link we sent to your email address and you'll be all set.");
        // }
    }

    var subscribeProfileMarked = false;
    var mailStatusChanged = false;
    
    function subscribeMarkProfile(event){
        subscribeProfileMarked  = true;
        mailStatusChanged       = true;
    }

    function subscribeWarningProfile(event){
        subscribed = 0;
        
        if($('#mailingList').attr('checked')){  subscribed = 1; if(isNewUser){mailStatusChanged=1;} }
        if($('#mailSales').attr('checked')){    subscribed = 1; if(isNewUser){mailStatusChanged=1;} }
        if($('#mailRoad').attr('checked')){     subscribed = 1; if(isNewUser){mailStatusChanged=1;} }
        if($('#mailProduct').attr('checked')){  subscribed = 1; if(isNewUser){mailStatusChanged=1;} }
        if($('#mailHealth').attr('checked')){   subscribed = 1; if(isNewUser){mailStatusChanged=1;} }
        if($('#mailCooking').attr('checked')){  subscribed = 1; if(isNewUser){mailStatusChanged=1;} }
        if($('#mailNewsAlerts').attr('checked')){   subscribed = 1; if(isNewUser){mailStatusChanged=1;} }
        
        
        if(mailStatusChanged && isNewUser && subscribed){
            alert("To complete the newsletter registration process, please click the link in the email we'll be sending to your email address shortly and you'll be all set.");
            isNewUser = false;
        }
    }
    