/* ------------------------------------------------------------------------
 * share.js
 * Copyright (c) Perfect Memorials. All rights reserved.
 * ------------------------------------------------------------------------ */

$(document).ready(function(){
    // Determine max number of recipients
    PMTShare.maxRecipients = $('.recipient').length;
    PMTShare.setEventHandlers();
    PMTShare.redisplayRecipients();
});

var PMTShare = {
    
    maxRecipients:    0,
    previousCount:    0,
    recipientCount:   1,
    
    setEventHandlers: function(){
        // Add recipient button onclick event handler
    	$('#add-recipient-btn').click(function() {
    		PMTShare.addRecipient();
    		return false;
    	});
        // Remove recipient links onclick event handler
    	$('.link-remove-recipient').click(function() {
    	    this.blur();
    		PMTShare.removeRecipient(this);
    		return false;
    	});
    },
    
    addRecipient: function(){
        // Check how many recipients exist
        if(this.recipientCount==this.maxRecipients)   return false;
        // Display form fields for another recipient
        this.recipientCount++;
        var recipientRef = $('#recipient-' + this.recipientCount);
        if(recipientRef){
            recipientRef.addClass('hidden').removeClass('hide');    // Fix for IE7 to prevent rendering bug when removing recipients
            recipientRef.slideDown('fast');
            var firstInput = $('#recipient-' + this.recipientCount + ' input:first');
            $('html,body').animate({ scrollTop: firstInput.offset().top }, function(){
                firstInput.focus();
            });
        }
        // Update recipient count in hidden form field
        $('#recipient-count').val(this.recipientCount);
        // Check max recipients
        this.checkMaxRecipients();
    },
    
    removeRecipient: function(elmt){
        var fieldsetElmt    = $(elmt).parents('fieldset.recipient');
        var recipientNumber = this.parseNumberFromId(fieldsetElmt.attr('id'));
        if(recipientNumber){
            // Get names of input fields
            this.getRecipientFieldIds();
            if(this.fieldIds.length){
                // Deleting when there are only 2 recipients 
                if(recipientNumber==this.recipientCount){
                    this.resetRecipient(recipientNumber);
                    this.stripRecipientErrors(recipientNumber);
                }
                // Deleting when there are more than 2 recipients
                else{
                    for(var currentNumber = (recipientNumber + 1); currentNumber <= this.recipientCount; currentNumber++){
                        var previousNumber = (currentNumber - 1);
                        // If not last recipient move values from current fieldset to previous one
                        for(var key in this.fieldIds){
                            $('input#' + this.fieldIds[key] + previousNumber).val($('input#' + this.fieldIds[key] + currentNumber).val());
                        }
                        // Clear any error messages or classes from previous fieldset
                        this.stripRecipientErrors(previousNumber);
                        // Move any error messages or classes from current fieldset to previous
                        $('#recipient-' + currentNumber + ' div.row').each(function(fieldNum){
                            // Check for error class
                            if($(this).attr('class').indexOf('field-error') != -1){
                                $('#recipient-' + previousNumber + ' div.row:eq(' + fieldNum + ')').addClass('field-error');
                            }
                            // Check for error message
                            var errorMsg = $(this).children('span.error');
                            if(errorMsg.length==1){
                                errorMsg.clone().appendTo('#recipient-' + previousNumber + ' div.row:eq(' + fieldNum + ')');
                            }
                        });
                        // Clear any error messages or classes from current fieldset
                        this.stripRecipientErrors(currentNumber);
                        // If last recipient clear field values and hide
                        if(currentNumber==this.recipientCount){
                            this.resetRecipient(currentNumber);
                        }
                    }
                }
                this.recipientCount--;
                this.checkMaxRecipients();
            }
        }
    },
    
    resetRecipient: function(recipientNumber){
        for(var key in this.fieldIds){
            $('input#' + this.fieldIds[key] + recipientNumber).val('');
        }
        $('#recipient-' + recipientNumber).addClass('hide');
    },
    
    stripRecipientErrors: function(recipientNumber){
        $('#recipient-' + recipientNumber + ' div.row')
            .removeClass('field-error')
            .children('span.error')
            .remove();
    },
    
    redisplayRecipients: function(){
        this.recipientCount = this.previousCount;
        // Redisplay recipients
        for(var n = 1; n <= this.recipientCount; n++){
            $('#recipient-' + n).removeClass('hidden');
        }
        // Check max recipients
        this.checkMaxRecipients();
    },
    
    checkMaxRecipients: function(){
        // Apply disabled style to add button if max reached
        if(this.recipientCount==this.maxRecipients){
            $('#add-recipient-btn').addClass('disabled');
        }
        else{
            $('#add-recipient-btn').removeClass('disabled');
        }
    },
    
    parseNumberFromId: function(recipientId, type){
        if(/^recipient\-[0-9]{1,2}/.test(recipientId)){
            recipientId = recipientId.split('-');
            if(recipientId[1] && parseInt(recipientId[1])==recipientId[1]){
                return parseInt(recipientId[1]);
            }
        }
        return false;
    },
    
    parseNameFromId: function(fieldId){
        if(/^f_([a-z_]+)[0-9]{1,2}/.test(fieldId)){
            fieldId = fieldId.substr(0, (fieldId.lastIndexOf('_') + 1));
            if(fieldId){
                return fieldId;
            }
        }
        return false;
    },
    
    getRecipientFieldIds: function(){
        var fieldIds  = [];
        $('#recipient-1 input[type="text"]').each(function(){
            var fieldId = PMTShare.parseNameFromId($(this).attr('id'));
            if(fieldId){
                fieldIds[fieldIds.length] = fieldId;
            }
        });
        this.fieldIds = fieldIds;
    }
    
};