document.observe("dom:loaded", function()
{
    // handle program selection with URL redirect
    var program = $('program');
    if ( program )
    {
        Event.observe(program, 'change', function()
        {
            var value, newUrl;
            // is valid value?
            value = program.value;
            if (!value.empty())
            {
                var loc = document.location;
                var rfiPath = "/request-info/";
                var fsPath = "/school/";
                var rfiControllerIndex = loc.pathname.indexOf(rfiPath);
                if (0 <= rfiControllerIndex)
                {
                    var pathPrefix = loc.pathname.substring(0, rfiControllerIndex);
                    newUrl = loc.protocol + '//' + loc.host + pathPrefix + rfiPath + value;
                }
                else if (0 == loc.pathname.indexOf(fsPath))
                {
                    newUrl = loc.protocol + '//' + loc.host + fsPath + value;
                }

                // See if we have any existing pre-filled data
                if ( $('command') )
                {
                    var cmdElements = $A(Form.getElements('command'));

                    // Get rid of all elements that are empty, or values we don't care to propagate. 
                    var filteredElements = cmdElements.reject(function(formElement) {
                        var formValue = formElement.getValue();
                        if ( formValue != null && !formValue.blank() )
                        {
                            if ( formElement.name != 'draft'
                                    && formElement.name != 'program'
                                    && formElement.name != 'submit'
                                    && !formElement.name.startsWith('_') )
                            {
                                return false;
                            }
                        }
                        return true;
                    });

                    var serialized = Form.serializeElements(filteredElements);
                    if ( !serialized.blank() )
                    {
                        newUrl += "?" + serialized;
                    }
                }

                document.location = newUrl;
            }
        });

    }

    if ($("errorSearchSubmit"))
    {
        Event.observe($("errorSearchSubmit"), 'click', function(event)
        {
            $('mini-rfi-error-search').submit();
        });
    }

    // toggle show more suggested schools
    var suggestedAll = $('suggestedAll');
    var suggestedMore = $('suggestedMore');
    var showSchools = "See All Schools";
    var hideSchools = "Reduce List of Schools";
    if (suggestedMore)
    {
        Element.setStyle(suggestedMore, {
            display: 'none'
        });
        suggestedAll.removeChild(suggestedAll.firstChild);
        suggestedAll.appendChild(document.createTextNode(showSchools));

        Event.observe(suggestedAll, 'click', function(event)
        {
            Event.stop(event);
            if (Element.visible(suggestedMore))
            {
                Element.setStyle(suggestedMore, {
                    display: 'none'
                });
                suggestedAll.removeChild(suggestedAll.firstChild);
                suggestedAll.appendChild(document.createTextNode(showSchools));
            }
            else
            {
                Element.setStyle(suggestedMore, {
                    display: 'block'
                });
                suggestedAll.removeChild(suggestedAll.firstChild);
                suggestedAll.appendChild(document.createTextNode(hideSchools));
            }
        });
    }

    ASD.generateFormErrorTooltips();

    // events and modal dialog for international questions
    var elementInternationalWrap = $('internationalWrap');
    if (elementInternationalWrap)
    {
        var submitButton = $('submitButton');
        if (submitButton)
        {
            Event.observe(submitButton, 'click', function(event)
            {
                var country = $('country');
                // do not show for 'blank' value
                var regex = /USA|CAN|ASM|FSM|GUM|MHL|MNP|PRI|UMI|VIR|--/g;
                if (!regex.test(country.value))
                {
                    Event.stop(event);
                    Modalbox.show($(elementInternationalWrap), {
                        height: 450,
                        overlayClose: false,
                        title: "International Information",
                        transitions: false,
                        width: 600,
                        afterLoad: function()
                        {
                    		if( Prototype.Browser.IE6)
                    		{
                    			// US3953 Nimret: IE specific setting of the date fields cuz IE sux
	                    		$('toeflDate.monthOfYear').selectedIndex = $('command')['toeflDate.monthOfYear'].selectedIndex;
	                    		$('toeflDate.dayOfMonth').selectedIndex = $('command')['toeflDate.dayOfMonth'].selectedIndex;
	                    		$('toeflDate.year').selectedIndex = $('command')['toeflDate.year'].selectedIndex;
                    		}
                    	
                            var intlSubmitButton = $('intlSubmitButton');
                            Event.observe(intlSubmitButton, 'click', function(event)
                            {
                            	// US3953 Nimret: The popup modal box actually displays the fields 
                            	// in a new form and we need to save off the old values here so 
                            	// that we can set them in the original form in the handler below
                            	var els = $('internationalBlock').select("input","select");
                            	
                                Modalbox.hide({
                                    afterHide: function()
                                    {
                                        // submit form
                                    	var command = $('command');
                                    
                                    	// US3953 Nimret: copy the values from the lightbox to the main form and submit it
	                                	for( i = 0; i < els.size(); i++)
	                                	{
	                                		if( els[i].type == 'checkbox' || els[i].type == 'radio')
	                                		{
	                                			command[els[i].id].checked = els[i].checked;
	                                		}
	                                		else if( els[i].type == 'text')
	                                		{
	                                			command[els[i].id].value = els[i].value;
	                                		}
	                                		else if( els[i].type.substr(0,6) == 'select')
	                                		{
	                                			command[els[i].id].selectedIndex = els[i].selectedIndex;
	                                		}
	                                	}
                                	
                                        command.submit();
                                    }
                                })
                            });
                        }
                    });
                }
            });
        }
    }

    // suggested instruction location list
    var elementsSuggestedLocations = $$('#rfiMini .location');
    if (elementsSuggestedLocations)
    {
        elementsSuggestedLocations.each(function(each)
        {
            var id = each.id.split('_');
            var location = id[1] + '/' + id[2];
            var baseParams = {};
            if ( id[3] ) {
                baseParams['decorator'] = id[3];
            }

            Event.observe(each, 'mouseover', function(event)
            {
                if (each.id != selectedItemId.id)
                {
                    each.addClassName('over');
                }
            });
            Event.observe(each, 'mouseout', function(event)
            {
                if (each.id != selectedItemId)
                {
                    each.removeClassName('over');
                }
            });
            Event.observe(each, 'click', function(event)
            {
                Event.stop(event);
                // when clicked on an instruction location
                if (!ASD.getInstructionLocationClickable())
                {
                    // if the state is in processing, do not allow click
                    return;
                }
                
                ASD.setSelectedMiniRfiItem(each);
                var content = $('content');
                new Ajax.Updater(content, '/ajax/rfi/programs', {
                    method: 'post',
                    parameters: Object.extend({location: location}, baseParams),
                    onSuccess: function(transport)
                    {
                        ASD.setInstructionLocationClickable(false);
                    },

                    onComplete: function(transport)
                    {
                        // program changed
                    	var selectedSdpo = $('sdpo');
                        Event.observe(selectedSdpo, 'change', function(event)
                        {
                            selectedSdpo.fire("ajax:triggered");
                        });
                        selectedSdpo.observe("ajax:triggered", function(event)
                        {
                            var contentSdpo = $('contentSdpo');
                            var ajaxProcessing = $('ajaxProcessing');
                            contentSdpo.hide();
                            ajaxProcessing.show();
                            new Ajax.Updater('contentSdpo', '/ajax/rfi/form', {
                                method: 'get',
                                parameters: Object.extend({program: selectedSdpo.value}, baseParams),
                                onComplete: function(transport)
                                {
                                    ASD.setupMiniRFISubmitButtons();
                                    ASD.setInstructionLocationClickable(true);
                                    ASD.setUpEditContactInfo();

                                    contentSdpo.show();
                                    ajaxProcessing.hide();
                                    
                                    /* change class of selected school to selected-program so the user doesn't have to mouseout to change the style */
                                    each.removeClassName('over');
                                    each.addClassName('selected-program');
                                },
                                onFailure: function(transportResponse)
                                {
                                    alert("Could not load your form");
                                }
                            });
                        });
                        selectedSdpo.fire("ajax:triggered");

                        // fact sheet popup
                        var elementsPopup = $$('#selectedLocation .popup');
                        if (elementsPopup)
                        {
                            elementsPopup.each(function(each)
                            {
                                Event.observe(each, 'click', function(event)
                                {
                                    Event.stop(event);
                                    // new window
                                    ASD.Window.open({
                                        'url' : each.href
                                    });
                                });
                            });
                        }
                    }
                });
            });
        });
    }

    var elementsSuggestedLocations = $$('#rfiMini .location');
    if (elementsSuggestedLocations)
    {
    	var elem = elementsSuggestedLocations[0];
    	if(elem) {
    		ASD.fireEvent(elem,'click');
    	}
    	
    }
});

ASD.handleEditClick = function(event)
{
    Event.stop(event);
    $('answeredItems').show();
    $('contactInfo').hide();
};

ASD.setUpEditContactInfo = function()
{
    var editContact = $('editContact');
    editContact.observe('click', function(event)
    {
        ASD.handleEditClick(event);
    });
};

ASD.setupMiniRFISubmitButtons = function()
{
    var hoverLinks = $$('.minirfi-submit-button');
    if ( hoverLinks )
    {
        hoverLinks.each(function(each) {
            if ( !each.hasClassName("no-hover") )
            {
                Event.observe(each, 'mouseover', function(event) {
                    each.src = each.src.replace(".png","-hover.png");
                });
                Event.observe(each, 'mouseout', function(event) {
                    each.src = each.src.replace("-hover.png",".png");
                });
            }

            // Clickers!
            each.observe('click', function(event) {
                ASD.handleSubmitButton(event);
            });
        });
    }
};

/**
 * Handles submission for submit button on AJAX found form
 */
ASD.handleSubmitButton = function(event)
{
    Event.stop(event);
    var contentSdpo = $("contentSdpo");
    var ajaxProcessing = $('ajaxProcessing');
    // stop if currently processing a submit
    if (!ASD.getRfiSubmitClickable())
    {
        return;
    }

    // set the currently processing to true
    ASD.setRfiSubmitClickable(false);
    var formCommand = $('formCommand');
    var params = formCommand.serialize(true);
    var randomnumber = Math.floor(Math.random() * 11);

    contentSdpo.hide();
    ajaxProcessing.show();
    scroll(0, 0);
    
    new Ajax.Request('/ajax/rfi/form?cache=' + randomnumber, {
        method: 'post',
        parameters: params,

        onSuccess: function(transportResponse)
        {
            // submit successful, reset main content
            if (transportResponse.responseText != "")
            {
                contentSdpo.update(transportResponse.responseText);
                var validationErrors = $("validationErrors");
                if (validationErrors)
                {
                    // re-register the click event because new form exist (existing button wiped out)
                    try
                    {
                        ASD.generateFormErrorTooltips();
                        if($('rfi-validation-error')) {
                            // if there is an error on the page, then show the contact
                            // info as though they clicked the "edit" button
                            ASD.handleEditClick(event);
                        }
                    }
                    catch (e)
                    {/* do not do anything when there's an exception */
                    }

                    ASD.setupMiniRFISubmitButtons();

                    var editContact = $('editContact');
                    Event.observe(editContact, 'click', function(event)
                    {
                        ASD.handleEditClick(event);
                    });

                    contentSdpo.show();
                    ajaxProcessing.hide();
                }
            }
        },
        onFailure: function(transportResponse)
        {
            alert("The form submission was not successful. Please try again.");
        },
        onException: function(requester, exception)
        {
            alert("Exception " + exception);
        },
        onComplete: function(transportResponse)
        {
            ASD.setRfiSubmitClickable(true);
        }
    });
};

// Holds currently selected instruction location ID
var selectedItemId = false;
// variable representing state of clickable for InstructionLocation list
var rfiClickable = true;
// variable representing state of clickable for InstructionLocation list
var iLClickable = true;


ASD.getSelectedMiniRfiLocation = function()
{
    return selectedItemId;
};
/**
 *   Sets the active instruction location in the list with CSS class
 */
ASD.setSelectedMiniRfiItem = function (itemId)
{
    if ($(selectedItemId))
    {
        $(selectedItemId).removeClassName("selected-program");
    }
    $(itemId).addClassName("selected-program");
    selectedItemId = $(itemId);
};

ASD.setSubmitButtonState = function (state)
{
    var btn = $("submitButton");
    if (!btn)
    {
        return;
    }
    if (!state)
    {
        btn.src = btn.src.replace("rfi_submit.gif", "rfi_submit_disabled.gif");
    }
    else
    {
        btn.src = btn.src.replace("rfi_submit_disabled.gif", "rfi_submit.gif");
    }
};

/**
 *  Sets current state of RFI submit
 */
ASD.setRfiSubmitClickable = function(isClickable)
{
    ASD.setSubmitButtonState(isClickable);
    rfiClickable = isClickable;
};

/**
 * returns current state of instruction location list
 */
ASD.getRfiSubmitClickable = function()
{
    return rfiClickable;
};

/**
 * Setups a function to set the current state of the instruction location list
 */
ASD.setInstructionLocationClickable = function (isClickable)
{
    iLClickable = isClickable;
};

/**
 * returns current state of instruction location list
 */
ASD.getInstructionLocationClickable = function()
{
    return iLClickable;
};


///********************************
var active = 0;
ASD.updateClickCounter = function (state)
{
    /*
     * uncomment this and take out the return to show status of ajax calls in progress
     *
     var msg = "ACTIVE AJAX CALLS " + active + "<br>";
     msg += "in " + state;
     $("messageResponse").innerHTML = msg;
     /**/
    return;
};

Ajax.Responders.register({
    onCreate: function()
    {
        active++;
        ASD.updateClickCounter("onCreate");
    },
    onFailure: function()
    {
        ASD.updateClickCounter("onFailure");
    },
    onException: function()
    {
        ASD.updateClickCounter("onException");
    },
    on205: function()
    {
        ASD.updateClickCounter("on205");
        alert("205");
    },
    onComplete: function()
    {
        active--;
        ASD.updateClickCounter("onComplete");
    }
});
