;/**
 * Generic and re-usable form methods
 */
SF.FORMS = 
{
    /**
     * Default handling of forms that don't validate
     */
    invalidForm: function(e, validator, fieldMappings)
    {
        var errorString = '';
        $.each(validator.errorMap, function(key, val)
        {
            var fieldKey = '';
            if(typeof fieldMappings != 'undefined' && typeof fieldMappings[key] != 'undefined')
            {
                fieldKey = fieldMappings[key];
            }
            else
            {
                fieldKey = SF.UTIL.camalCaseCapitalise(key);
            }
            errorString += '  - ' + fieldKey + ': ' + val + '\n';
        });
        errorString = errorString.substring(0, errorString.length-1);
        
        var errors = validator.numberOfInvalids();
        if(errors) 
        {
            var message = errors == 1
                ? '1 field has errors: \n ' + errorString
                : errors + ' fields have errors: \n' + errorString;
            window.alert(message);
        }
    },
    
    /**
     * Behaviour for fields that have intial text in them such as 'search here...'. When focus is 
     * applied, the default clears out
     
     * @param jQuery element
     */	
    inputTextShowHide: function(element)
    {
        if(element.length === 0)
        {
            return;
        }
        
        try
        {
            element.attr('itext', element.val());
            element.bind('focus', function(e)
            {
                if($(this).val() === $(this).attr('itext'))
                {
                    $(this).val('');
                }
            });
            
            element.bind('blur', function(e)
            {
                if($(this).val() == '')
                {
                    $(this).val($(this).attr('itext'));
                }
            });
        }
        catch(e){}
    },

    /**
     * Attach a replacement image after the submit button and attach an event listener
     * that when fired, hides the submit button and shows its replacement
     */
    replaceSubmitButton: function($button)
    {
        if($button.length == 0)
        {
            return;
        }
        
        $button.after('<img />').next()
                                .attr('class', 'replacedSubmitButton')
                                .attr('src', '/images/general/waiting.gif')
                                .attr('alt', 'Your form request is being processed')
                                .attr('title', 'Your form request is being processed');
                                
        var $form = $button;
        while($form[0].tagName.toLowerCase() !== 'form')
        {
            $form = $form.parent();
        }
        
        $form.bind('replaceSubmit', function()
        {
            $button.hide();
            $(this).find('.replacedSubmitButton').show();
        });
    },
    
    checkFormFieldExistsNotEmpty: function($element)
    {
        //  Check obvious
        if($element.length == 0 || $element.val() == '')
        {
            return false;
        }
        
        // Check checkboxes and radio
        var type = $($element[0]).attr('type');
        if(type != 'radio' && type != 'checkbox')
        {
            return true;
        }
        
        var checked = false;
        $element.each(function()
        {
            if($(this).attr('checked'))
            {
                checked = true;
            }
        });
        
        return checked;
    }
};

(function(){

    /**
     *
     * @param inputName
     * @param value
     */
    $.validator.addMethod('departureArrivalDates', function(value, element, params)
    {
        var $parentForm = $(element.form);
        return FCL.DATETIME.stringToDate($parentForm.find('[name=departureDate]').val()) < FCL.DATETIME.stringToDate($parentForm.find('[name=returnDate]').val());

    }, 'Return date must be after departure date');


   /**
   * This jQuery Extension adds the ability to access form fields by the shortcut property .field()
   * which gets and sets input field values by name using the .find() method.
   * @param string inputName
   * @param mixed value (optional)
   */
    $.fn.field = function( inputName, value){

        if(typeof inputName!=='string' ){
            return false;
        }

        var $inputElement = $(this).find('[name='+inputName+']');

        /*
         *  Get request, return the input fields value.
         */
        if(typeof value==='undefined' && $inputElement.length>=1)
        {
            switch($inputElement.attr('type')){
                case 'checkbox':
                    return $inputElement.is(':checked');
                case 'radio':
                    var result;
                    $inputElement.each(function(i,val){
                        if($(this).is(':checked'))
                        {
                            result = $(this).val();
                        }
                    });
                    return result;
                default:
                   return $inputElement.val();
            }
        }

         /*
         *  Set request, set the input field to the value provided
         *  and return a reference to the jQuery selector for the input
         */
        else
        {
            switch($inputElement.attr('type')){
                case 'checkbox':
                    $inputElement.attr({checked: value});
                    break;
                case 'radio':
                    $inputElement.each(function(i){
                       if($(this).val()===value)
                          $(this).attr({checked: true});
                    });
                    break;
                case undefined:
                   $(this).append('<input type="hidden" name="'+inputName+'" value="'+value+'" />' );
                   break;
                default:
                   $inputElement.val(value);
                   break;
            }
            return $inputElement;
        }
    };
})();
