
$(document).ready(function()
{
    var $walls = $('#memorial-content .walls').css('overflow', 'hidden');
    var $panels = $('#memorial-content .walls-content > div');
    var $container = $('#memorial-content .walls-content');
    
    // IE fix to ensure overflow is hidden
    if ($.browser.msie) {
        $panels.css({'position' : 'relative'});
    }
    // MacOS likes to bold text
    if (navigator.appVersion.indexOf('Mac') != -1 || $.browser.safari) {
        $('.memorial .popup-post, .memorial .popup-form, .memorial .popup-post h3, .memorial .popup-form h3, '+
          '.memorial #btn-addmemorial span, .memorial .btn span, form button, '+
          '#tooltip').css('font-weight','normal');
    }

    // set nav arrow links
    $('.nav-left').html('<img class="scrollButtons left" src="imgs/memorial-arrow-left.png" width="65" height="41" alt="Previous list" />');
    $('.nav-right').html('<img class="scrollButtons right" src="imgs/memorial-arrow-right.png" width="65" height="41" alt="Next list" />');
    
    // calculate a new width for the container (so it holds all walls)
    if ($panels[0]) {
        $container.css('width', $panels[0].offsetWidth * $panels.length);
    }
    
    var scrollOptions = {
        target: $walls, // the element that has the overflow

        // can be a selector which will be relative to the target
        items: $panels,

        prev: '.nav-left .left', 
        next: '.nav-right .right',

        axis: 'x', // scroll effect to runs in horizontal direction

        offset: -1,
        
        cycle: true, // return to the first or end of slides

        duration: 500, // duration of the sliding effect

        easing: 'swing'
    };

    // apply serialScroll to the slider - we chose this plugin because it 
    // supports the indexed next and previous scroll along with hooking 
    // in to our navigation.
    $('#memorial-content').serialScroll(scrollOptions);
    
    /** end slide scroll **/
    
    // tooltips
    $('#memorial-content h3.name, #memorial-content ul li.wire img').Tooltip({
        delay: 0,
        track: true,
        showURL: false
    });
    // fix cursor flickering
    if ($.browser.msie && $.browser.msie.version == '6.0') {
        $('#memorial-content h3.name, #memorial-content ul li.wire').css('cursor','default');
    }
        
    // toggle popup info windows
    $('.nav-left, .nav-right').click(function() {
        $('.popup-form, .popup-post').fadeOut('slow').removeClass('show');
    });
    
    /** 
     * Handles popup window functionality:
     * - closes other popups before opening up a new one
     * - loads popup with content via script call
     * - attach js functionality and styling to new popup
     *
     * @param Object obj - ex: {arg:"db_key", id:"db_value"}
     * @return void
     */
    function makePopup(obj)
    {
        var popupObj = $('.memorial .popup-post');
        
        //hide other popups
        if (popupObj.attr('id') != obj.id) {
            popupObj.removeClass('show');
        }
        $('#addmemorial').removeClass('show');
        
        // ajax function to retrieve popup window content
        popupObj.load('memorial.js.php', obj, function(result)
        {
            $(this).html(result).attr('id',obj.id);
            
            // function to close popup
            $('.popup-post .btn').click(function() {
                $(this).parent().parent().fadeOut('slow').toggleClass('show');
            });
            $('.popup-post h3').click(function() {
                $(this).parent().fadeOut('slow').toggleClass('show');
            });
            
            // add padding to images
            $('.popup-post img[align=left]').css({ paddingRight:'1em', paddingBottom:'1em' });
            $('.popup-post img[align=right]').css({ paddingLeft:'1em', paddingBottom:'1em' });
            //alert($(this).text());

            // now show it
            $('.memorial .popup-post').fadeIn(1000).toggleClass('show');
        });
    }
    
    /**
     * Strips the hash from href.
     * @param String ref
     * @return String
     */
    function hrefToId(ref) {
        return ref.substring(1, ref.length);
    }
    
    // create a parameters obj to pass to script
    $('#memorial-content h3.name a').click(function() {
        //ex: "#name-1" -> "name-1"
        var thisId = $(this).parent().parent().attr('id');
        if (thisId) {
            //ex: "?arg=name&id=name-1"
            makePopup({id: thisId, arg: 'name'});
        }
    });
    
    // create a parameters obj to pass to script
    $('#memorial-content ul li.wire a').click(function() {
        //ex: "#post-1" -> post-1
        var thisId = hrefToId($(this).attr('href'));
        if (thisId) {
            //ex: "?arg=posting&id=post-1"
            makePopup({id: thisId, arg: 'posting'});
        }
    });
    
    
    /* add to the memorial form and button */
    
    $('#btn-addmemorial').click(function() {
        $('.popup-post').fadeOut('slow').removeClass('show');
        $('#addmemorial').fadeIn(1000).toggleClass('show');
    });
    
    var addoptions = {
        target: '#addmemorial .popup-content',   // target element(s) to be updated with server response 

        //dataType:  null      // 'xml', 'script', or 'json' (expected server response type) 
        clearForm: true,       // clear all form fields after successful submit
        resetForm: true,        // reset the form after successful submit 
        //timeout:   3000,
        
        url: 'memorial.js.php',
        beforeSubmit: validate,
        success: function(result) {
            $('#addmemorial .popup-content').html(result);
            
            // function to close popup
            $('#addmemorial.popup-form .btn').click(function() {
                $(this).parent().parent().fadeOut('slow').toggleClass('show');
            });
            $('#addmemorial.popup-form h3').click(function() {
                $(this).parent().fadeOut('slow').toggleClass('show');
            });
        }
    };
    
    $('.addmemorial').ajaxForm(addoptions); 
    
    
    /* misc styling */
    
    // center the popup to the wall
    $('.popup-post, .popup-form').css({ left: (($('#memorial-content').width()/2) - ($('.popup-form').width()/2))+'px', top: '10px' });
    
    // arrange placement of wires
    $('#memorial-content .box ul li:nth-child(1), '+
      '#memorial-content .box ul li:nth-child(2), '+
      '#memorial-content .box ul li:nth-child(3), '+
      '#memorial-content .box ul li:nth-child(4), '+
      '#memorial-content .box ul li:nth-child(5), '+
      '#memorial-content .box ul li:nth-child(6), '+
      '#memorial-content .box ul li:nth-child(7)').css({top:'-10px'});
    $('#memorial-content .box ul li:lt(7)').css({top:'-20px'});
    
    $('form a.toggleShow').click(function() {
        $(this).parent().next('.hidden-fields').css('display','block');
    });
    
    // function to close popup
    $('#addmemorial.popup-form .btn').click(function() {
        $(this).parent().parent().fadeOut('slow').toggleClass('show');
    });
    $('#addmemorial.popup-form h3').click(function() {
        $(this).parent().fadeOut('slow').toggleClass('show');
    });
});


function validate(formData, jqForm, options)
{
    // formData is an array of objects representing the name and value of each field 
    // that will be sent to the server.
    // 
    // To validate, we can examine the contents of this array to see if the 
    // username and password fields have values.  If either value evaluates 
    // to false then we return false from this method.
    
    var isGood = true;
    var lbl;
    
    var dat = jqForm[0];
    
    lbl = $('#addmemorial form #add-title').siblings('label');
    // post a notice if there is not text
    if ( !dat['add-title'].value )
    {
        if (!lbl.children('span.error').text()) {
            lbl.append(' <span class="error" title="Please enter a title for your comment.">(!)</span>'); 
        }
        isGood = false;
    }
    // there is text, remove notice
    else {
        if (lbl.children('span.error').text()) {
            lbl.children('span.error').remove();
        }
    }

    lbl = $('#addmemorial form #add-comment').siblings('label');
    if ( !dat['add-comment'].value )
    {
        lbl = $('#addmemorial form #add-comment').siblings('label');
        if (!lbl.children('span.error').text()) {
            lbl.append(' <span class="error" title="Please enter a comment.">(!)</span>'); 
        }
        isGood = false; 
    }
    else {
        if (lbl.children('span.error').text()) {
            lbl.children('span.error').remove();
        }
    }
        
    if ( dat['add-image'].value )
    {
        var lbl = $('#addmemorial form #add-image').siblings('label');
        
        if (dat['add-image'].value.indexOf('http://') < 0 && 
                (dat['add-image'].value.indexOf('jpg') < 0 || 
                 dat['add-image'].value.indexOf('gif') < 0 ||
                 dat['add-image'].value.indexOf('png') < 0) )
        {
            if (!lbl.children('span.error').text()) {
                lbl.append(' <span class="error" title="Please ensure the photo link is valid.">(!)</span>'); 
            }
            isGood = false;
        }
        else {
            if (lbl.children('span.error').text()) {
                lbl.children('span.error').remove();
            }
        }
    }

    if ( dat['add-video'].value )
    {
        var lbl = $('#addmemorial form #add-video').siblings('label');
        
        if (dat['add-video'].value.indexOf('http://') < 0 ||
            dat['add-video'].value.indexOf('youtube') < 0)
        {
            if (!lbl.children('span.error').text()) {
                lbl.append(' <span class="error" title="Please ensure the youtube link is valid.">(!)</span>'); 
            }
            isGood = false; 
        }
        else{
            if (lbl.children('span.error').text()) {
                lbl.children('span.error').remove();
            }
        }
    }
    
    if (!isGood) {
        return false;
    }
}


/**
 * Sources:
 * Slider code and effects borrowed from: http://jqueryfordesigners.com/coda-slider-effect/
 * Please refer to that for full code comment.
 *
 */
