/*
	MMF From Display Support Functions
*/

//Set change_triggers var that validation includes will use to set
jQuery(document).ready(function() {

	
	MMF.validation.change_triggers_open = {};
	
	MMF.validation.validators = {};
		
	// Form Depency Displays
	MMF.validation.display_form_dependencies = function(form, dependee, dependent, value) {
				
        selector = '#' + form + ' #id_' + dependee;
        dependent_shown = false;
                
        if($(selector).attr('type') == 'checkbox') {
        	dependent_shown = $(selector).attr('checked');
        } else if($(selector).attr('type') == 'hidden') {
        	dependent_shown = $(selector).val() == 'false' ? true : false;
        } else {
    		dependent_shown = value == 'True' ? $(selector).val() : $(selector).val() == value;
    	}  
                	
        if (dependent_shown) {
            $('#' + form +  ' #'+ dependent + '_row').removeClass('hidden');
        } else {
            $('#' + form +  ' #'+ dependent + '_row').addClass('hidden');
        }        
    }
	
	MMF.validation.add_default_opened = function(collapse_id){
		MMF.validation.change_triggers_open[collapse_id] = true;
	}
	
	// Datepicker
	// Transform the Big Endian Date Format provided by Django 
	// to the Local, Checks for a _ prefix which is added by 
	// DatePickerField to indicate a Django sourced date
	
	MMF.validation.datepicker = function(field, date_format, icon_source) {
		// A persistant DatePicker indicator, so we don't depend on
        // the meta-class DatePicker adds.
		field.addClass('mmfDatePicker');
		if( icon_source != "" ){
			field.datepicker({dateFormat: date_format, duration: '', changeMonth: true, changeYear: true, yearRange:'-100:+100',  buttonImage: icon_source, buttonImageOnly: true, showOn:'both' });
		} else {
			field.datepicker({dateFormat: date_format, duration: '', changeMonth: true, changeYear: true, yearRange:'-100:+100'});
		}
	}
	
	
	// Submission Wrapper
	MMF.validation.submit_wrapper = function(form, form_error, validator, partial) {
				
		//console.log('submit_wrapper initialized...')
		
        var btnGeneric = {
            classOuter: "warning",
            tagOuter: "a",
            tagInner: "span",
            submitOnReturn: false
        };
        		
		$('#' + form).bind('submit', function(e) {
						
			if(partial) {
				//console.log('returning false since partial...')
				return false;
			}
			
			if(MMF.validation.presubmit_validate(form, validator) == false) {
				//console.log('returning false due to invalidation...')
				return false;
			}
			
			
        });
	}
	
	MMF.validation.presubmit_validate = function(form, validator) {
		
		// This is a TOTAL HACK, Run Through Watermarks Again, Really Need a 
		// Submission Queue :)
		
		$('.form_watermark').val('');
		
		//console.log('Hit MMF.validation.presubmit_validate', form, validator)
		
		// Clear "Error Count" Between Validations...
		MMF.validation.clear_count(form);

            if (validator) {
                if(!validator.valid()) {
                        //console.log('removing hidden class...')
                    $('#' + validator.mmf_form_error).removeClass('hidden');
                    return false
                } else {
                    $('#' + validator.mmf_form_error).addClass('hidden');
                }
            }
        }
	//Validate Choices
	jQuery.validator.addMethod('choices', function(value, element, params) {
	    
	    function test(value, element, params) {
	        // This is backwards, you 'return false' when true to break 
	        // the .each() iterator, and need to pass on the success 
	        // via a variable. 
	        valid = false;
	        jQuery.each(params, function(choice, verbose) {
	            if(choice == value) {
	                valid = true;
	                return false;
	            }
	        });
	        return valid;
	    }
	
	    return this.optional(element) || test(value, element, params);
	}, jQuery._('Select a valid choice. This is not one of the available choices.', 'validation'));
	
	// Borkened?
    jQuery.validator.addMethod('regex', function(value, element, params) {
        re = new RegExp(params);
        return this.optional(element) || re.test(value);
    }, jQuery._('Enter a valid value.', 'validation'));
    
    // Validate Time
    jQuery.validator.addMethod('time', function(value, element) {
        
        function test(value, element) {
            time_elements = value.split(':');
            
            // Validate Length, Type
            if(time_elements.length < 2 || time_elements.length > 3 || time_elements.length < 2 || !(time_elements instanceof Array)) {
                return false;
            }
            
            // Validate Intergerness
            for(key in time_elements) {
                if(time_elements[key] != parseInt(time_elements[key]) || time_elements[key] < 0) {
                    return false;
                }
            }
            
            if(time_elements[1] > 59) {
                return false;
            }
            
            if(time_elements[2] && time_elements[2] > 59) {
                return false;
            }
            
            return true;
        }
        
        return this.optional(element) || test(value, element);
    }, jQuery._('Enter a valid time.', 'validation'));
    
    // You are entering dangerous territory, do not use validator.format, 
    // it will cause errors far down the line that will appear totally 
    // unreleated!
    
    // Validate Total Numbers Places
    jQuery.validator.addMethod('maxdigits', function(value, element, params) {
            	
        function test(value, element, params) {
            // Already Validated as Number, so Skip That...
            digits = value.replace('.', '');
            if(digits.length > params) {
                return false;
            }
            return true;
        }
        
        return this.optional(element) || test(value, element, params);
    }, jQuery.format(jQuery._("Ensure that there are no more than {0} digits in total.")));
        
    // Validate Decimal Places
    jQuery.validator.addMethod('decimalplaces', function(value, element, params) {
        
        function test(value, element, params) {
            // Already Validated as Number, so Skip That...
            decimal_elements = value.split('.');
            
            // If Not a Decimal Number, This is Always True...
            if(!(decimal_elements instanceof Array) || !decimal_elements[1]){
                return true;
            }
        	                    	
            if(decimal_elements[1].length > params) {
                return false;
            }
            
            return true;
        }
        
        return this.optional(element) || test(value, element, params);
    }, jQuery.format(jQuery._("Ensure that there are no more than {0} decimal places.")));	

	// Validate Minimum Choices in MultipleChoice
    // TODO: Make This Support Multiple Browsers
    jQuery.validator.addMethod('minchoices', function(value, element, params) {
        
        function test(value, element, params) {
            if(jQuery(element+':selected').length-1 < params) {
            	//alert(jQuery(element+':selected').length-1)
                //return false
            }
            return true;
        }
        
        return this.optional(element) || test(value, element, params);
    }, jQuery.format(jQuery._("Must select at least {0} choices")));	
    
    // Ensure Watermark Text Doesn't Cause Errorneous True Validation
    jQuery.validator.addMethod('watermark', function(value, element, params) {
    	
    	function test(value, element, params) {
            if(jQuery(element).hasClass('form_watermark')) {
                return false;
            }
            return true;
        }
        
        return !this.isRequired(element) || test(value, element, params);
    }, jQuery._("This field is required."));

    // Validate Maximum Choices in MultipleChoice
    // TODO: Make This Support Multiple Browsers
    jQuery.validator.addMethod('maxchoices', function(value, element, params) {
        
        function test(value, element, params) {
            if(jQuery(element+':selected').length-1 > params) {
            	//alert(jQuery(element+':selected').length-1)
                //return false
            }
            return true;
        }
        
        return this.optional(element) || test(value, element, params);
    }, jQuery.format(jQuery._("Must select no more than {0} choices")));
	
    /*
    $('.form_help_trigger').each(function(){
    		trigger = $(this)
    		container_name = trigger.attr('id').replace('_trigger', '')
    		search_raw = '#' + container_name
    		search = $(search_raw)
    		
    		search.append('<br /><br /><a href="#" id="' + container_name + '_close"><b>Close</b></a>')

    		trigger.tooltip({
    			position: "bottom right", 
    			tip: search_raw, 
    			tooltip: 'mouseover',
    			events: {
    				// Why the fuck doesn't this work?
    				tooltip: 'mouseover',
				},
    		})
    		
    		var api = trigger.data('tooltip')
    		//console.log('API', api)
    		//console.log('DATA', trigger.tooltip())
    })
    */
    	
    // TODO: Move to a Real Plugin    
    
    MMF.validation.load_tooltips = function() {
    	
    	// Has a list of processed tooltips, allows for the lazy loading of 
        // Tooltips for some events (e.g. hiding all other tooltips when 
    	// Something is openned
        var form_tooltip_instances = [];

    	// Show/Hide Help
        jQuery('.form_help_trigger').bind('mouseover', function(e){
    	     	
        	// Determine Tooltip to Display
        	trigger = jQuery(this);
        	searchElement = jQuery('#' + trigger.attr('id').replace('_trigger', ''));    	
        	closeElement = searchElement.find('.form_tooltip_close');
        	    
        	available_instance = false;
        	// Hide if not same element, so that a double hover / click doesn't 
        	// result in the element coming up again...
        	jQuery.each(form_tooltip_instances, function() {
        		if(this.attr('id') != searchElement.attr('id')) {
        			this.hide();
        		} else {
        			available_instance = true;
        		}
        	})
        	    	
    		// Side Adjust
    		// Move ALL to CSS
           
            arrow = searchElement.find('.form_tooltip_arrow');
            
            if(arrow) {
            	arrow.css('position', 'absolute');
            	arrow.css('left', -9);
            }
                	
            // Push to Instance Keeper
            if(!available_instance) {	
    		      form_tooltip_instances.push(searchElement);
    		}
        	
        	// Add Close Button
        	closeElement.bind('click', function(){
        		searchElement.hide();
        	})
            
            searchElement.slideDown(200);
        })
    }
    
    MMF.validation.load_tooltips();
	
	//Initialize collapse trigger click functions
    jQuery('.collapse_trigger').bind('click', function(e){
    	$this = $(this);
    	id = $this.attr('id');
    	collapse = $('#id_' + id + '_collapse');
    	
    	if(collapse.val() == 'true') {
    		$this.removeClass('collapse_true');
    		$this.addClass('collapse_false');
    		collapse.val('false');
    	} else {
    		$this.removeClass('collapse_false');
    		$this.addClass('collapse_true');
    		collapse.val('true');
    	}
    	
    	collapse.trigger('change');
    });
});
