var formValidator;
var expandPanels = false;

window.addEvent('domready', init);

function init() {

	if(window.ie) $('prefPanels').removeClass('none');

    // ryiTabs = new mootabs('prefPanels', {
        // changeTransition: 'none',
        // mouseOverClass: 'over' ,
        // activateOnLoad:	'none'
    // });

    // $$('.mootabs_panel', '#prefPanels').setStyles({
        // 'width' 	: 'auto',
        // 'height'	: 'auto'
    // });

    $$('#land_pref', '#aprt_pref').addEvent('click', function(){
        var group;
 
        var tabName = this.getParent();
 
        switch (tabName.title)
        {
            case "landPrefs":
                group = "land";
                break;
            case "aprtPrefs":
                group = "apartments";
                break;
        }
        
       
        if(this.checked){
			$$('ul.mootabs_title', '#prefPanels').removeClass('none');
            $$('#prefPanels div.mootabs_panel').removeClass('active').addClass('none');
            $$('ul.mootabs_title li').removeClass('active');

            $(tabName.title + '_tab').removeClass('none').addClass('active');
            $(tabName.title).removeClass('none').addClass('active showing');
			
            formValidator.setGroupState(group, com.thenextspark.lib.sparktools.Validation.ON);
        } else {
            $$('#prefPanels div.mootabs_panel').addClass('active').removeClass('none');
            $(tabName.title + '_tab').addClass('none');
            $(tabName.title).addClass('none').removeClass('active').removeClass('showing');
            formValidator.setGroupState(group, com.thenextspark.lib.sparktools.Validation.OFF);
        };
        if($$('#prefPanels div.showing').length == 0) {
				$$('ul.mootabs_title', '#prefPanels').addClass('none');
				
			}
    });

    var PrefPanels = new Array();

    $$('div#prefPanels div.prefs').each(function(el){
        this.push(new Fx.Slide(el).hide());
    }.bind(PrefPanels));

    var prefH4Images = $$('div#prefPanels h4 img');

    $$('div#prefPanels h4').each(function(el, n) {
        el.addEvent('click', function(){
            el.toggleClass('minus');
            if(el.hasClass('minus'))
            {
	            if(window.ie) PrefPanels[n]['element'].setStyle('display','block');
	            PrefPanels[n].slideIn();
    	        prefH4Images[n].src = 'ryi/bkgd-ryiPreference_h4-minus.gif';
            }
            else
            {
	            PrefPanels[n].slideOut().chain(function(){ if(window.ie) { PrefPanels[n]['element'].setStyle('display','none'); } });                
	            prefH4Images[n].src = 'ryi/bkgd-ryiPreference_h4.gif';
            };
			//console.log('hello there dofus')
        });
    });

    //If the user is logged in the we need to set up step 2 panel to be colapsable.
    if($('expandableProfilePanel')) {
        var expandPanels 	= new Fx.Slide($$('div.expandable')[0]).hide();

        var panelTrigger01 	= $$('div.expand span.ryiPanelNotifier')[0];
        var panelTrigger02 	= $$('div.expand h3')[0];
        var triggerGraphic 	= $$('div.expand h3 img')[0];

        if (window.ie) panelTrigger01.getNext().getNext().getFirst().addClass('none');

        $$([panelTrigger01,panelTrigger02]).addEvent('click', function(){
            openProfile();
        });

        function openProfile(){
            triggerGraphic.toggleClass('minus');
            //Hiding the expandable slider so that it hides properly in IE
            if (window.ie) expandPanels['element'].toggleClass('none');
			
            expandPanels.toggle().chain(function(){
                if (triggerGraphic.hasClass('minus')) {
                    expandPanels['wrapper'].setStyle('height', 'auto');
                };
            });
            if(triggerGraphic.hasClass('minus')) {
                triggerGraphic.src = 'ryi/bkgd-div_loggedIn_contract-h3.gif';
            }
            else {
                triggerGraphic.src = 'ryi/bkgd-div_loggedIn_expand-h3.gif';
            };
			
        }

    }

    formValidator =
    new com.thenextspark.lib.sparktools.Validation (
        $('ryiForm'),
        {
            onSuccess: function() {

				/* HACK FOR GETTING AROUND LEFT BEHIND REQUIRED STATES IN PROJECT INTEREST */
				$('ProjectInterest').getElements('span.interestLabel span')[0].setText(' ');
				
				var agree = $$('span.Agree input');
				var canSubmit = false;
				
				agree.each(function(el,n){ if(el.checked) canSubmit = true; });

					
				if (!canSubmit) 
				{
					$$('.formMessage')
									.setStyle('display', 'block')
									.addClass('error')
									.empty()
									.setHTML('You need to agree to the Terms and Conditions to proceed');
				} 
				else 
				{
					$$('.formMessage')
									.setStyle('display', 'block')
									.removeClass('error')
									.empty()
									.setHTML('');
					$('ryiForm').submit();
				}
           },
           onFailure: function() {
			
                var profileRequired = !!($$('#expandableProfilePanel span.required').length);
			
                if($('expandableProfilePanel')) {
                    triggerGraphic.toggleClass('minus');
                    if (window.ie) expandPanels['element'].toggleClass('none');
								
                    if(profileRequired)
                    {
                        expandPanels.slideIn().chain(function(){
                            if (triggerGraphic.hasClass('minus')) {
                                expandPanels['wrapper'].setStyle('height', 'auto');
                            };
                        });
                    } else
                    {
                        expandPanels.slideOut().chain(function(){
                            if (triggerGraphic.hasClass('minus')) {
                                expandPanels['wrapper'].setStyle('height', 'auto');
                            };
                        });
                    }
                }

				//
				//Testing to see if any of the Projects have been selected
				//If not show the required text next to "Project(s) of Interest:"
				//
				if($('ProjectInterest')) {
					var el = $('ProjectInterest');	
					var messageBox = el.getElements('span.interestLabel span')[0].setText(' '); //Assume this exists...
					messageBox.empty().removeClass('required'); //empty and remove class as not to break the next bit

					var requiredSpan = el.getElements('span.required');

					if(requiredSpan.length > 0)
					{
						var requiredMessage = requiredSpan[0].innerHTML;
						messageBox.setText(requiredMessage).addClass('required');
					}
				}

                //
                // For each preference panel:
                // Check if there are any required items and if there are,
                // add a message box with the required text.
                //
                $$('div.ryiPreference').each(
                    function (el)
                    {
						var requiredSpans = el.getElements('div.prefs span.required');
                        var messageBox = el.getElements('h4 span')[0]; // Assume this exists...
                        if (requiredSpans.length > 0)
                        {
                            var requiredMessage = requiredSpans[0].innerHTML;
                            messageBox.setText(requiredMessage).addClass('required');
                        }
                        else if (messageBox.hasClass('required'))
                        {
                            messageBox.removeClass('required');
                            messageBox.empty();
                        }
                    }
                    );

                //
                // For each tab:
                // Clear any existing spans (used to show required messages)
                // Go through the tabPanel & check for span.required(s)
                // If any exist on that tabPanel, then set an error message
                // in a span in the tab's li.
                //
                $$('ul.mootabs_title li').each(
                    function (tabElement)
                    {
                        tabElement.getElements('span').each(
                            function(el)
                            {
                                el.empty();
                            }
                            );
                        $$('div#' + tabElement.title).each(
                            function (tabPanelElement)
                            {
                                var requiredSpans = tabPanelElement.getElements('span.required');
                                if (requiredSpans.length > 0)
                                {
                                    // We have required elements missing in this tab panel
                                    var messageSpan = tabElement.getElements('span');
                                    if (messageSpan.length <= 0)
                                    {
                                        messageSpan = new Element('span')
                                        .addClass('required')
                                        .injectInside(tabElement);
                                    }
                                    else
                                    {
                                        messageSpan = messageSpan[0];
                                    }
                                    messageSpan.setHTML(" * Required items");
                                }
                            }
                            );
                    }
                    );

                $$('.formMessage')
								.setStyle('display', 'block')
								.addClass('error')
								.empty()
								.setHTML('You have missed some required fields. Please check and resubmit the form');
            }
        }
        );

    // if($('email') || $('phone')) {
    //     $$('#email', '#phone').each(function(input){
    //         input.addEvent('blur', function(){
    //             $('contactMethod').getChildren().each(function(option){
    //                 if(input.id == option.value) {
    //                     option.setHTML(input.name.capitalize() + ': ' + input.value);
    //                 //option.value = input.value;
    //                 }
    //             });
    //         });
    //     });
    // }

 
    var otherPrefs = [];

    $$('div#otherPrefs div.prefs').each(
        function(el) {
            this.push(new Fx.Slide(el).hide());
        } .bind(otherPrefs)
        );

    $$('div#otherPrefs h4').each(function(el, n) {
        el.addEvent('click', function() {
            otherPrefs[n].toggle();
            el.toggleClass('minus');
        });
    });

    $$('#prefPanels input[type="checkbox"]',
        '#prefPanels input[type="radio"]',
        '#prefPanels input[type="text"]').each(
        function(input, n)
        {

            var prefContainer =
            input.getParent().getParent().getParent().getParent();

            var event = input.type == "text" ? 'keyup' : (window.ie ? 'click' : 'change');
            input.addEvent(event, function(){
                populateResults(prefContainer);
            });
        });
    $$(".ryiPreference").each(populateResults);

    $('countrySubscribe').addEvent('change', checkCountry).value = "";
    checkCountry();

	$('livingClubSubscription').addEvent('click', showSubscribe);
	showSubscribe();
}

function showSubscribe() {
	if($('livingClubSubscription').checked) {
		$('subscriptionDetails').removeClass('none');
		formValidator.setGroupState("subscription", com.thenextspark.lib.sparktools.Validation.ON);
	} else {
		$('subscriptionDetails').addClass('none');
		formValidator.setGroupState("subscription", com.thenextspark.lib.sparktools.Validation.OFF);
	}
}


function populateResults(prefContainer) {
    var prefSummaryItems = [];
    var inputs = $$('#' + prefContainer.id + ' div.prefs input');
    inputs.each(
        function (input, n)
        {
            if(input.type == "text")
            {
                // if input.type == "text" we get the value of the text box
                prefSummaryItems.push(input.getValue());
            }
            else
            {
                // if input.type != "text", assume checkbox or radio button,
                // and get the value from the input's label.

                // only add to the list if the checkbox or radion is checked
                if(input.checked)
                {
                    // Assume label follows the input element.
                    // The text we're interested in for the summary is
                    // the text of the label that appears before the first ','.
                    prefSummaryItems.push(
                        input.getNext().getText().split(',')[0]
                        );
                }
            }
        }
        );
    $$('#'+ prefContainer.id + ' h4 span')[0]
    .setHTML(prefSummaryItems.join(', '))
    .removeClass('required');
}
function checkCountry()
{
    var country = $('countrySubscribe').value;
    if (country == 'Australia')
    {
		$('stateHolder').setStyle('display', 'block');
        $('stateSubscribe').setProperty('title', 'required');
    }
    else
    {
		$('stateHolder').setStyle('display', 'none');
        $('stateSubscribe').removeProperty('title');
    }
}

function checkAll(mySpan)
{
for (var n=0; n < document.forms[0].length; n++) 
{
if (document.forms[0].elements[n].type=='checkbox')
{
if (document.forms[0].elements[n].parentNode.id=='lndProjectInterest' && document.getElementById('allProjects_0').checked==true || document.forms[0].elements[n].parentNode.id=='aptProjectInterest' && document.getElementById('allProjects_0').checked==true)
{
document.forms[0].elements[n].checked='true';
}
}
}
}
