




//Step two checkboxes 
$("input[name=selectedComps]").change(function(){
   disableCheckBoxes("")
})

//Step two checkboxes 
$("input[name=selectedComps_p]").change(function(){
   disableCheckBoxes("_p")
})
function disableCheckBoxes(sufx){
    var max= 3;
    if( $("input[name=selectedComps"+sufx+"]:checked").length == max ){
        $("input[name=selectedComps"+sufx+"]").attr('disabled', 'disabled');
        $("input[name=selectedComps"+sufx+"]:checked").removeAttr('disabled');
    }else{
         $("input[name=selectedComps"+sufx+"]").removeAttr('disabled');
    }
}

 /*hide popup  generic throughout for info boxes*/
$(document).ready(function(){	

if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  };
}

	 $.ui.autocomplete.prototype._renderItem = function( ul, item){
		  var term = this.term.split(' ').join('|');
		  var re = new RegExp("(" + term + ")", "gi") ;
		  var t = item.label.replace(re,"<span class='textred'>$1</span>");
		  return $( "<li></li>" )
		     .data( "item.autocomplete", item )
		     .append( "<a>" + t + "</a>" )
		     .appendTo( ul );
		};
    String.prototype.contains = function(it) { return this.indexOf(it) != -1; };
//Step1 Type Make Model Model Year
  var gloabalSearch = '';
  var cache = {};


   var limit = 100;
	 $(".veh").autocomplete({
	     minLength: 3,
	     source: function (request, response) {
            var term = request.term.toUpperCase().trim(); 
            var searchItems = term.split(" ");
            var regexStr = ''; 
            for (i = 0; i < searchItems.length; i++) {
                regexStr = regexStr + '(?=.*'+searchItems[i].trim()+')';              
            }
            var re = new RegExp(regexStr,"g");
            if (gloabalSearch !== null && gloabalSearch.length >1 && term.contains(gloabalSearch)) {
             var results=$.map(cache[ gloabalSearch ], function (item) {               
                  if (item.pd.match(re) != null) {
                         return {
                             label: item.pd,
                             prodId: item.id
                         }
                  }               
              })
              response(results.slice(0, limit));
              return;
           } 
           $("#indicator").show();
	         $.ajax({
	             url: "product.json?searchStr="+term,
	             dataType: "json",
	             
	             success: function (data) {
                   cache[ term ] = data;
                   gloabalSearch = term;
                   $("#indicator").hide();
	                 response($.map(data, function (item) {
	                     return {
	                         label: item.pd,
	                         prodId: item.id
	                     }
	                 }))
	             }            
	         })
	     },
	     select: function (event, ui) {
	    	
				// navigate to the selected item's url
       
           $("#h_prodname").val(ui.item.label);
	         $("#h_prodid").val(ui.item.prodId);         
	     }
	    /* focus: function(event, ui) {
				// prevent autocomplete from updating the textbox
				event.preventDefault();
			},*/
	 }).css('width','420px')
    $('#start_btn').click(function(){
        $("#start").hide(); 
      	$("#tabs").show();  
        $("#tabs").tabs( "option", "active", 0 );
    });
    
    $('.back').click(function(){
        $("#start").show(); 
      	$("#tabs").hide();  
    });
$(document).on("keyup",  ".veh", function(evt){
       var prodStr=$(this).val();
       if( $.isNumeric(prodStr)){
        $( ".veh" ).autocomplete( "option", "minLength", 4 );
       }else{
       $( ".veh" ).autocomplete( "option", "minLength", 3 );
       }
});
$(document).on("change",  "#sel_state", function(evt){
   var selectedText =$("#sel_state option:selected").text()
   document.getElementById("h_state").value=selectedText;
    });
   
   /*info hide shows throughout*/
 	$(document.body).on ('click', '.what-is', function(){
 	$(this).next(".that-is").show();	
 	return false;
 });
 $(document.body).on ('click', '.hide-it', function(){
 $(this).parent(".that-is").hide();
 return false;
 });
 
  /*morelessthrought*/
 	$(document.body).on ('click', '.showing0', function(){
 	$(this).next(".hiding0").show();
   $(".showing0" ).hide();
    $(".top0" ).hide();
 	return false;
 });
 $(document.body).on ('click', '.hiding-it0', function(){
 $(this).parent(".hiding0").hide();
  $(".showing0" ).show();
   $(".top0" ).show();
 return false;
 });
 
 	$(document.body).on ('click', '.showing3', function(){
 	$(this).next(".hiding3").show();
   $(".showing3" ).hide();
    $(".top3" ).hide();
 	return false;
 });
 $(document.body).on ('click', '.hiding-it3', function(){
 $(this).parent(".hiding3").hide();
  $(".showing3" ).show();
   $(".top3" ).show();
 return false;
 });
 


    var text_max = 1900;
    $('div.textarea_feedback').html(text_max + ' characters remaining');
    //handling ctrl-v event


    $('textarea[name=incidentDesc]').keyup(function() {
        var text_length = $('#incidentDesc').val().replace(/\n/g, "\r\n").length;
        var text_remaining = text_max - text_length;

       $('div.textarea_feedback').html(text_remaining + ' characters remaining');
    });
    //handling right-clikc & paste event
    $('textarea[name=incidentDesc]').bind('input propertychange', function() {
        var text_length = $('#incidentDesc').val().replace(/\n/g, "\r\n").length;
        var text_remaining = text_max - text_length;

       $('div.textarea_feedback').html(text_remaining + ' characters remaining');
    });


	/*Step 3 date picker*/
	$('input[class*=date_picker]').datepicker({
       showOn: "button",
       buttonImage:"resources/images/calendar.png" ,
       buttonImageOnly: true,
       buttonText: "Calendar",
       dateFormat: 'mm/dd/yy', 
       changeYear: true,
       changeMonth: true,
       yearRange: "-99:+1",
       maxDate: '0',
       onSelect: function() {
         $(this).change();
        }     
}).click(function() { $("#incidentDate").val(''); });
 
  $(".ui-datepicker-trigger").click(function() {
      $("#incidentDate").val(''); 
  });
	//Step 4

		
			 $(".crash").hide();
			 $(".injury").hide();
			 
			 $('input[type="radio"].crashYes').click(function(){
	        if($(this).attr("value")=="Y"){
	           
	            $(".crash").show();
	        }
	       else { $(".crash").hide();}
	    });
			 
			 $('input[type="radio"].injuryYes').click(function(){
			        if($(this).attr("value")=="Y"){
			           
			            $(".injury").show();
			        }
			       else { $(".injury").hide();}
			    });
      /** type only numbers */
      $('input[name="numOfFatalities"], input[name="numOfInjuries"],input[name="speed"], input[name="miles"]').keydown(function (event) {
            if (event.shiftKey) {
                event.preventDefault();
            }

            if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9) {
            }
            else {
                if (event.keyCode < 95) {
                    if (event.keyCode < 48 || event.keyCode > 57) {
                        event.preventDefault();
                    }
                }
                else {
                    if (event.keyCode < 96 || event.keyCode > 105) {
                        event.preventDefault();
                    }
                }
            }
        });
        
   indexArray=[4,3,2,1,0];
$(document).on("click",  ".addfile", function(evt){
    var i=indexArray.pop();
//    alert(i);
    var cnt=document.querySelectorAll("#doc_wrapper > div").length;
   

     if (i>-1){
  var div = document.createElement('div');

    div.className = 'row';
    
    div.innerHTML = '<div><label><input type="file" class="fileupl truncate" name="files['+i+']" accept="application/pdf,image/*"></label> <a href="#"'+
          ' indexid="'+i+'" class="removefile">Remove</a></div>\r\n';
       //  alert(html);
    document.getElementById('doc_wrapper').appendChild(div);
        
 }
    }); 


$(document).on("click",  ".removefile", function(evt){
   // alert( this.getAttribute("indexid"));
   
   indexArray.push(this.getAttribute("indexid"))
     
                $(this).closest('div').slideUp('slow', function(){$(this).remove();checkForFiles()});

             
           
    });  
    
 
 
$(document).on("change",  "#veh", function(evt){
 var prod_id=document.getElementById('h_prodid').value;
  var prod_name=document.getElementById('h_prodname').value;
  if(prod_id==null|| prod_id.trim().length==0||$(this).val()!=prod_name){
     document.getElementById('h_prodid').value="";
  
    $( "#error-prod" ).removeClass( "none" )
  }else{
     $("#error-prod").addClass("none");
  }
});

$(document).on("change",  ".injuryYes", function(evt){
   if($(this).val()=="N"){
   document.getElementById("fatalities").value=0;
    document.getElementById("injuries").value=0;
    $("input[name=medicalYn][value='N']").prop('checked', true);
   }
    });
$(document).on("change",  ".crashYes", function(evt){
   if($(this).val()=="N"){
   $("input[name=policeYn][value='N']").prop('checked', true);
   $("input[name=towedYn][value='N']").prop('checked', true);
   }
    });
       
 

 	
	});
	
 