$(document).ready(function(){
    $.fn.serializeObject = function()
    {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function() {
            if (o[this.name] !== undefined) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };

    var form_accordion = $('form .accordion').accordion({
        autoHeight:false,
        collapsible: true,
        disabled: true
    });
    
    $('form.application select.fill_values_between').each(function(){
         
        var  bookends = $(this).children('option');
        
    
       if($(bookends).size()==2){ //Needs to be filled with years between these dates
          var first_item = $(this).find(":first-child");
          var first_val = first_item.val();
          var last_val = $(this).find(":last-child").val();
          
          
          
          for(var i = (++last_val); i<first_val; i++){
              $(first_item).after('<option value="'+i+'">'+i+'</option>');
          }
       
        
       } else {
          
		  
       } 
    });
    
    $('.trigger').change(function(){
        var id_value = $(this).attr('id');

        var trigger_class = id_value.substring(0,id_value.length-1); //The class that is being triggered
        var trigger_num = id_value.substring(id_value.length-1,id_value.length); //The number of this box

        var numBoxes = $('input[name=\''+$(this).attr('name')+'\']').length //Number of sibling to iterate
        var i = 0;
        for(i=0;i<=numBoxes;i++){ //goes through each # in yyy_yyyyyyy#, for 3 radio boxes it'd be 3 times
            if(i==trigger_num){
                $('.'+id_value).slideDown(); //Show all these classes (yyy__yyyyyy#), this has been selected
                $('.'+id_value).removeClass('dependant')
            } else {
                $('.'+trigger_class+i).each(function(elem){ // for each element that does not have a selected class
                    if(!$(this).hasClass(id_value)){ //don't fade this class out, if it also contains the class that is selected
                        $(this).slideUp();
                        $(this).addClass('dependant')
                    }
                })
            }
        }
    });

    $('.next a').click(function(){
        var currentContainer = $(this).closest('.ui-accordion-content');		
		var proceed = true;
		
		$(currentContainer).find('input.mandatory').each(function(){
			
			if(($(this).val()=="") && ($(this).closest('.toclone').children().size()==0)){
				proceed = false;
				if($(this).is('input[name=vehicle__serial_number]')){
					currentContainer.find('p.next').prepend('<span class="alert">Without the VIN this quote may not be accurate</span>');
					currentContainer.find('p.next .ui-button-text').html('I Will Supply Later');
					$(this).removeClass('mandatory');
					$(this).change( function(){
						currentContainer.find('p.next .alert').remove();
						currentContainer.find('p.next .ui-button-text').html('Next Section');						
					});
				} else {
					if(currentContainer.has('p.next .alert').length==0){
						currentContainer.find('p.next').prepend('<span class="alert">You are missing a few details</span>');

					}

					currentContainer.find('a.next .ui-button-text').html('Next Section');
				}
			$(this).animate({
					backgroundColor: "#c5e5e7"
				}, 150, function(){
					$(this).effect("shake", { times:2 }, 100, function(){
						$(this).animate({
						backgroundColor: "#fff"
						}, 150);
					}	
				);
				
				});
			} 
			});
		
		if(proceed){
			currentContainer.find('p.next .alert').remove();			
			form_accordion.accordion("option","disabled",false)
			form_accordion.accordion("option","active",(currentContainer.parent().children('.ui-accordion-content').index(currentContainer)+1));
			form_accordion.accordion("option","disabled",true)

		} else {
			
		}	
    });

    $('.previous a').click(function(){
        // TODO: some sort of verification
        //form_accordion.accordion("option","disabled",true)
        var currentContainer = $(this).closest('.ui-accordion-content');
        form_accordion.accordion("option","disabled",false)
        form_accordion.accordion("option","active",(currentContainer.parent().children('.ui-accordion-content').index(currentContainer)-1));
        form_accordion.accordion("option","disabled",true)
    });

    $('form .previous a').button({
        icons: {
            primary:'ui-icon-triangle-1-w'
        }
    });

    $('form .next a, form input[type=submit]').button({
        icons: {
            secondary:'ui-icon-triangle-1-e'
        }
    });

    $('form .add_button a').button({
        icons: {
            primary:'ui-icon-plusthick'
        }
    })
    
    $('form .remove_button a').button({
        icons: {
            primary:'ui-icon-minusthick'
        }
    }).hide();

    $('.button').button();

    $.fn.applyScriptToInput = function(){
        if($(this).attr("title")){
            var tip_type;
            if($(this).attr("title").length<60){
                  tip_type = 'micro-inputtip';
                
            } else if ($(this).attr("title").length<120) {
              tip_type = 'mini-inputtip';
            } else if ($(this).attr("title").length<180) {
                tip_type = 'standard-inputtip';
                
            } else {
                tip_type = 'large-inputtip'
            }
            
            $(this).tooltip({
                position: "bottom right",
                offset: [0, 0],
                effect: "fade",
                opacity: 0.95,
                tipClass: tip_type
            });
        }

        if($(this).hasClass('phone')){
            $(this).mask("(999) 999-9999");
        }  else if($(this).hasClass('postal_code')){
            $(this).mask("a9a-9a9");
        }

        if($(this).is('select')){
           /* $(this).selectbox({
                effect: "fade",
                onChange: function(){
                
                }                
            }); */
        } else if ( $(this).hasClass('date')){
            $(this).datepicker({
                changeYear : true,
                yearRange: "1930:2015"
            });
        }
    }

    $('form.application :input').each(function(){  // Form javascript effects and helpers, not applied to uncloned 
        if(!($(this).closest('.toclone').length)){
            $(this).applyScriptToInput();
        }
    });
	
	$('form.message :input').each(function(){  // Form javascript effects and helpers, not applied to uncloned 
		$(this).applyScriptToInput();
    });

    $('a').each(function(){
        $(this).applyScriptToInput();
    });
    
    $('a.button').each(function(){
        $(this).applyScriptToInput();
    });

    $.fn.cloneNew = function(){ // creates a new clone, run on an element which has the container Id in it before a '__'

        var dividerPosition = $(this).attr("id").search("__");
        var containerName = $(this).attr("id").substring(0,dividerPosition);
        var cloned = $("#"+containerName+"__new").clone()

        $(cloned).find(':input').each(function(){
            $(this).applyScriptToInput();
        });

        $("#"+containerName+"__add_new").parent().before(cloned);
        cloned.slideDown();
        cloned.attr("class","cloned") //So it doesn't get duplicated next time
        return true;
    }


    $('p.add_button a').click(function(){
        $(this).cloneNew();
        $(this).closest('.additionals').find('p.remove_button a').fadeIn();
    });
    
    $('p.remove_button a').click(function(){
        if($(this).closest('.additionals').children('.cloned').size()==2){
             $(this).closest('.additionals').children('.cloned').last().slideUp(function(){
                 $(this).closest('.additionals').children('.cloned').last().remove();
             });
             $(this).fadeOut();
        } else {            
            $(this).closest('.additionals').children('.cloned').last().slideUp(function(){
                 $(this).closest('.additionals').children('.cloned').last().remove();
            });
        }
    });

    $('.toclone').each(function(){ // initial setup of form, duplication of first values 
        $(this).cloneNew();
        $(this).find('.prefix_additional').show();
        $(this).find('h3').addClass("additional");
    });
   
    $.get("/formsubmit/get_start/application",function(txt){
      $("form.application").append('<input type="hidden" name="start_time" value="'+txt+'" />');
    });
    
     $.get("/formsubmit/get_start/message",function(txt){
      $("form.message").append('<input type="hidden" name="start_time" value="'+txt+'" />');
    });   

    /*************
     * Submit.
     *
     * Check for things needed, expand whole form
     *
     * Find all trigger boxes, if they are not selected trim their trigger classes
     * before submission so the blank irrelevant boxes are not submitted (and cluttering)
     * */

    $('form.application').submit(function(){
        if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } 
        
        $('form.application .toclone').each(function(){
            $(this).remove()
        });

        $('form.application .dependant').each(function(){
            if(!$(this).is(":visible")){
                $(this).remove()
            }
        });

        var jasonObject = $(this).serializeObject();
      

        $('.page_text').fadeOut();
        $.post($(this).attr('action'), jasonObject,
            function(data){
                $('.page_text').html(data);
                $('.page_text').fadeIn();
            });
            
        return false
        
    });
    
    //Message to employee
     $('form.message').submit(function(){
        if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } 
        
        
        var jasonObject = $(this).serializeObject();
      

        $('#message_employee .form').fadeOut();
        $.post($(this).attr('action'), jasonObject,
            function(data){
                $('#message_employee :input').not(':button, :submit, :reset, :hidden').val('').removeAttr('checked').removeAttr('selected');
                $('#message_employee .result').html(data);
                $('#message_employee .result').fadeIn();
            });
        return false
    });
	
	

});
