$(document).ready(function() {
    /***************************************************************************
     * HOMEPAGE FEATURED SLIDER
     * Load the slideshow and link it to the accordian navigation.
     * Source: http://jquery.malsup.com/cycle/pager6.html
     **************************************************************************/
    if($('#slideshow').length != 0) {
        $('#slideshow').cycle({fx:'fade',
                            timeout: 8000,
                            before: function onBefore() { 
                                $('#featured li.activeSlide span').slideUp('slow');
                            },
                            after: function onAfter() { 
                                $('#featured li.activeSlide span').slideDown('slow'); 
                            },
                            pager:'.slide-nav',
                            pagerAnchorBuilder: function(idx, slide) { 
                            // return selector string for existing anchor 
                            return '.slide-nav li:eq(' + idx + ') a.postdiv';}
        });
        /***********************************************************************
        * HOMEPAGE FEATURED SLIDER NAVIGATION
        * Create an accordian navigation to content slider that hides all info but 
        * header on page load.
        * Source: http://www.stemkoski.com/stupid-simple-jquery-accordion-menu/
        ***********************************************************************/
       //ACCORDION BUTTON ACTION (ON CLICK DO THE FOLLOWING)
        $('.postdiv').click(function() {
            //NO MATTER WHAT WE CLOSE ALL OPEN SLIDES
            $('#featured li span').hide();

            //REMOVE THE ON CLASS FROM ALL BUTTONS
            $('.postdiv').removeClass('on');

            //IF THE NEXT SLIDE WASN'T OPEN THEN OPEN IT
            if($(this).next().is(':hidden') == true) {

                //ADD THE ON CLASS TO THE BUTTON
                $(this).addClass('on');

                //OPEN THE SLIDE
                $(this).next().slideDown();
                //Resume the slideshow (default is to stop on click)
                $('#cycle').cycle('resume');
            } 
        });

        //HIDE THE SLIDE ON PAGE LOAD	
        $('#featured li span').hide();
        //Show the active slide only on page load.
        $('#featured li.activeSlide span').show();
    }
    
   /****************************************************************************
    * EVENT/RENTAL ACCORDIAN
    * Create accordian navigation for event category pages.
    * Source: http://www.stemkoski.com/stupid-simple-jquery-accordion-menu/
    ***************************************************************************/
    if($('.archive .entry-content').length != 0){
        $('.postdiv').click(function(e) {
            if($(this).hasClass('on') == true){
                $(this).removeClass('on', function(){});
                $(this).next().slideUp();
            } else {
                $('.archive div.entry-content').slideUp();
                $('.postdiv').removeClass('on');
                if($(this).next().is(':hidden') == true) {
                    $(this).addClass('on');
                    $(this).next().slideDown();
                }
            }
            e.preventDefault();
        });
        // Hide all content on page load.
        $('.archive div.entry-content').hide();
    }
    
    $('figure.gallery-item a').attr('rel','gallery');
    $('figure.gallery-item a[rel="gallery"]').fancybox();
 
    /***************************************************************************
     * AJAX REGISTRATION FORM
     * Use Ajax to load registration form.
     **************************************************************************/
    //The url of the main page for relative urls.
    var homeURL = $('#logo').attr('href');
    var eventType;
    // Event description pages.
    $('a.register').click(function(e){
        // Look to the class of the article to set event for loading proper form.
        if($('article').hasClass('conferences') == true) {
            loadRegForm(homeURL, eventType = 'conf');
        } else if ($('article').hasClass('retreats') == true){
            loadRegForm(homeURL, eventType = 'ret');
        } else if ($('article').hasClass('camps') == true){
            loadRegForm(homeURL, eventType = 'cam');
        }
        e.preventDefault();
    })
    // Sidebar registration form.
    $('#register').live('change', function(e){
        //The type of the current selected event.
        var eventType = $('#reg option:selected').parent().attr('id');
        // Set the href of the form initiator and click it.
        if (eventType !== 'Choose an event'){
            loadRegForm(homeURL, eventType);
        }
        e.preventDefault();
    });
    
    // Clear form fieled warnings when focus is put on one.
    $('.required').focus(function(){
       $(this).css({'outline':'none'});
       $(this).next('label').css({'color':'black','font-weight':'normal'});
       $('.alert, .message, .confirm, .monologue').fadeOut(500, function(){$(this).remove()});
    });
    var submit = false;
    /**
     * Options for the current registration form.
     */
    $('#reg a.autostart').fancybox({
        'padding': 0,
        'autoScale': false,
        'hideOnOverlayClick':false,
        'hideOnContentClick':false,
        'centerOnScroll': true,
        // Manipulate the form when it loads.
        'onComplete': function(){
            // Hide all fields no matter what.
            $('fieldset').hide();
            // Initially add 'open' class to first fieldset & show.
            $('#page1').addClass('open').show();
            // The name of the current selected event.
            var event = $('#reg option:selected').val();
            // Set the event if not selected in sidebar.
            if (event == "Choose an event"){
                event = $('article h1').html();
            } else if (event == undefined){
                event = $('.on header h2').html();
            }
            // Only display the details of the event you chose.
            if(event == "Boys Camp" || event == 'Challenge Week'){
                $('div.girls, ul.girls').hide();
            }else if(event == "Girls Camp"){
                $('div.boys, ul.boys').hide();
            } else {
                // For the conference registration form.
                $('#event').val(event);
                if (eventType !== 'cam'){
                     // Set the event dates to match the selected event.
                     changeEventInfo(event);
                }
            }
            // Set the event dates to match the selected event.
            $('#event').live('change', function(){
                    var event = $('#event').val();
                    changeEventInfo(event);
            });
            // Expand/contract camp information based on event selection.
            $('a h5.girls').click(function(e){
                if('div.girls:hidden'){
                    $('div.boys').slideUp(function(){
                        $('div.girls').slideDown();
                        $('ul.boys').hide();
                        $('ul.girls').show();
                    });
                }
                e.preventDefault;
            });
            $('a h5.boys').click(function(e){
                if('div.boys:hidden'){
                    $('div.girls').slideUp(function(){
                        $('div.boys').slideDown();
                        $('ul.girls').hide();
                        $('ul.boys').show();
                    });
                }
                e.preventDefault;
            });
            $('#rooms').keyup(function(){
                var rooms = parseInt($('input[name=rooms]').val(), 10);
                var fee = parseInt($('span.fee').val(), 10);
                var reg_fee = fee;
                if(rooms == 0 || rooms == undefined){
                    reg_fee = fee;
                } else if (rooms != 0 || rooms != undefined) {
                    reg_fee = rooms * fee;
                }
                $('span.reg-fee').html(reg_fee);
                $('input[name=fee]').val(reg_fee);
            });
            $('input[name=camp]').change(function(){
                $('input[name=event]').val($(this).val());
            });
            // Clear form filed warnings when focus is put on one.
            $('.required').focus(function(){
               $(this).css({'outline':'none'});
               $(this).next('label').css({'color':'black','font-weight':'normal'});
               $('.alert, .confirm, .monologue').fadeOut(500, function(){$(this).remove()});
            });
            $('input[name=camp]').click(function(){$('.alert').remove();})
            
            // Close the current fieldset and open the next one.
            $('a.form-next').click(function(e){
                e.preventDefault();
                // Validate current page first.
                var allClear = true;
                $('fieldset.open input.required').each(function(){
                    // Check each required field.
                    if ($(this).val().length == 0){
                        // Change CSS properties if empty.
                        $(this).css({'outline':'1px solid #FF0000'});
                        $(this).next('label').css({'color':'red','font-weight':'bold'});
                        // Note that form did not validate.
                        allClear = false;
                    }
                });
                if($('fieldset.open input[name=camp]').length != 0){
                    if (!$('input[name=camp]:checked').val()){
                        var isCamp = true;
                        allClear = false;
                    } 
                }
                // Display message if not valid.
                if (!allClear){
                    if($('.alert').length == 0){
                        if (isCamp){
                            $('#registration').append('<span class="alert">Please select a camp before proceeding.</span>');
                        } else {
                            $('#registration').append('<span class="alert">Please complete all required fields before proceeding.</span>');
                        }
                        return false;
                    }
                } else {  
                    // Move forward (after validation ensured).
                    $('fieldset.open').removeClass('open').slideUp('slow', function(){
                        if($(this).next().is(':hidden') == true) {
                            $(this).next().addClass('open').slideDown('slow');
                            $(document).scrollTop(0,0);
                        }
                    });
                }
            });
            // Close the current fieldset and open the previous one.
            $('a.form-back').click(function(e){
                e.preventDefault();
                $('fieldset.open').removeClass('open').slideUp('slow', function(){
                    if($(this).prev().is(':hidden') == true) {
                        $(this).prev().addClass('open').slideDown('slow');
                    }
                });
            });
            // Show/hide first-time visitor textarea.
            $('span.first-time').hide();
            $("input[id='first-time']").click(function(){
               if ($('span.first-time').is(':hidden')== true){
                   $('span.first-time').slideDown('slow');
               } else {
                   $('span.first-time').slideUp('slow');
               }
            });
            // Add guests to conference form.
            var count = 4;
            $('a.add-guest').click(function(e){
                $('#guests').append('<div id="guest'+count+'">\n'+
                                        '<span class="same-line">\n'+
                                            '<input name="name'+count+'" value="" id="name'+count+'" class="required" size="38" type="text">\n'+
                                            '<label for="name'+count+'">Name*</label>\n'+
                                        '</span>\n'+
                                        '<span class="same-line">\n'+
                                            '<input name="age'+count+'" value="" id="age'+count+'" class="required" size="2" maxlength="2" type="text">\n'+
                                            '<label for="age'+count+'">Age*</label>\n'+
                                        '</span>\n'+
                                        '<span class="same-line">\n'+
                                            '<input name="relation'+count+'" value="" id="relation'+count+'" class="required" size="10" type="text">\n'+
                                            '<label for="relation'+count+'">Relationship*</label>\n'+
                                        '</span>\n'+
                                        '<span class="same-line">\n'+
                                            '<input name="need'+count+'" value="" id="need'+count+'" size="20" type="text">\n'+
                                            '<label for="need'+count+'">Special Needs<br>(crib, cot, etc.)</label>\n'+
                                        '</span>\n'+
                                        '<a href="#" class="remove-guest" ></a>\n'+
                                    '</div>');
                count++;
                e.preventDefault();
            });
            // Remove guests from conference form.
            $('a.remove-guest').live('click', function(e){
               $(this).parent().remove();
               e.preventDefault();
            });
            // Show/hide payment information depending on which option is selected.
            $('li.pay-info').hide();
            $('li input[name=payment]').click(function(){
                $('li.open').removeClass('open').hide('fade');
                if($(this).parent().siblings('.pay-info').is(':hidden') == true){
                    $(this).parent().siblings('.pay-info').addClass('open').show('fade');
                }
                // Remove validation warnings.
                $('.alert').remove();
                return true;
            })
            $('#close').live('click', function(e){
                $.fancybox.close();
                e.preventDefault();
            });
            var options = { 
                target:        '#ending',
                beforeSubmit:  function(formData, jqForm, options){
                    // Be sure a payment type was selected
                    if($('input[name=payment]').val() == 'online'){
                         $('#fancybox-content').html("<div class='confirm'>Test</div>");
                         return true;
                    } else if(!$('input[name=payment]:checked').val()){
                        if($('.alert').length == 0){
                            $('#registration').append('<span class="alert">Please select a method of confirming your registration.</span>');
                        }
                        return false;
                    } else {

                        $('#fancybox-content').append("<div id='page5'></fieldset>");
                        $('#page5').html("<div id='ending'>One moment while your form is submitted...</div>").hide();
                        $('fieldset.open').removeClass('open').hide('fade', function(){
                            $('#page5').addClass('open').show('fade');
                        });                            
                    }
                   return submit = true;
                }
            }; 

            // bind form using 'ajaxForm' 
            $('.reg-form').ajaxForm(options);
        },
        // Give user the option to stay before closing the form
        onCleanup: function(){
            var conf_text = 'If you close this form you will loose all current progress.\n\n'+
                             'Press "OK" to continue working.\n\n'+
                             'Press "Cancel" to close the form.';
            if (!submit){
                var confirmation = confirm(conf_text);
                if (confirmation){
                    return false;
                } else {
                    $.fancybox.close();
                    return true;
                }
            }
            
        }
    });
    
   /****************************************************************************
    * IFRAME EXTERNAL WEBSITES
    * Load content from other websites into a fancybox (not working with twitter/facebook).
    ***************************************************************************/
    $('a.extLink').fancybox({
        'autoScale' : false,
        'type': 'iframe'
    });
    var options = { 
        target:        '.monologue',
        beforeSubmit:  function(formData, jqForm, options){
            var allClear = true;
            $('#registration input.required').each(function(){
                // Check each required field.
                if ($(this).val() == 0){
                    // Change CSS properties if empty.
                    $(this).css({'outline':'1px solid #FF0000'});
                    $(this).next('label').css({'color':'red','font-weight':'bold'});
                    // Note that form did not validate.
                    allClear = false;
                }
            });
            if(!allClear){
                $('.contact-form').prepend('<div class="alert">Please complete all required fields before proceeding.</div>');
                return false;
            } else {
                $('.contact-form').prepend("<div class='monologue'>One moment while your form is submitted...</div>");
            }
        },
        resetForm: true
    }; 
    if($('form.contact-form').length != 0){
        $('.contact-form').ajaxForm(options);
    }
});

/**
 * Function to display the proper registration form based on the user's selection.
 */
function loadRegForm(homeURL, eventType){
    if (eventType == 'conf' ){
        $('#reg a.autostart').attr('href', homeURL + 'conference-registration/');
    } else if(eventType == 'ret'){
        $('#reg a.autostart').attr('href', homeURL + 'retreat-registration/');
    } else if(eventType == 'cam'){
        $('#reg a.autostart').attr('href', homeURL + 'camper-registration/');
    }
    // Auto-click the form initiator.
    $('#reg a.autostart').trigger('click');
}
/**
 * Function that checks for a change in event and changes the start date, end date,
 * and registration fee accordingly.
 */
function changeEventInfo(event){
    for(x in eventDetails){
        if(event == eventDetails[x][0]){
            $('#arrive').val(eventDetails[x][1]);
            $('#depart').val(eventDetails[x][2]);
            $('span.fee').val(eventDetails[x][3]);
            $('span.fee').html(eventDetails[x][3]);
        }
    }
}
