﻿/*
	//Author:   rebecca.mccay
    //Created:  11/16/2009 10:41:41 AM

	Add fields:
	Link:
	http://www.bennadel.com/index.cfm?dax=blog:1375.view
	
	
*/

var addFields = {

      MaxTripInputs: 5, 
      MaxTripInputsUsed: false, 

      ElementIDs: {
        TripDirectionsWrapper: 'panel1',
        TripFieldsInputs: 'tripFieldsInputs',
        TripFieldTemplate: 'element-templates',
        TripFieldRow: 'tripFieldRow',
        TxtTripStreet: 'txtTripStreet',
        TxtTripSuburb: 'txtTripSuburb',
        AddTripFieldRow: 'add-tripFieldRow',
        ShowStreet: 'showStreet'   
     },
     
     ElementClass: {
         TripIcon: 'tripIcon',
         RemoveLink: 'removeLink'
     },
     
     ElementNames: {
        TxtTripStreet: 'txtTripStreet',
        TxtTripSuburb: 'txtTripSuburb',
        RemoveLink: 'removeLink',
        ShowStreet: 'showStreet'
     
     },

    initFields: function(){
        var _SELF = this;

        // When the DOM has loaded, init the form link.
        $(function(){
		        // Get the add new upload link.
		        
		        var addRow = ( "#" + _SELF.ElementIDs.AddTripFieldRow );
		        var jAddNewUpload = $( addRow);
         
		        // Hook up the click event.
		        jAddNewUpload
			        .attr( "href", "javascript:void( 0 )" )
			        .click(
				        function( objEvent ){
					        addFields.addNewTripRow();
         
					        // Prevent the default action.
					        objEvent.preventDefault();
					        return( false );
				        });
				        
				 _SELF.addLinksClickEvent();       
	        }
	        )
     }, 
     
     // Add the click event to the Show/Hide street links and the Remove field links 
     addLinksClickEvent: function(){
     
        
        
         $('a[name=showStreet]').each(function(i) {
         
            $(this).unbind('click');
            
            var linkID = i + 1;
            $(this).click( function() {Locator.showStreet(linkID);});
            
         });
         
         var removeLink = this.ElementNames.RemoveLink;
         
         $('a[name=removeLink]').each(function(i) {
         
            $(this).unbind('click');
            
            var linkID = i + 1;
            $(this).click( function() {addFields.removeField(linkID);});
            
         });
     
     
     },
     
     //Adds new trip input field row to the trip planner
    addNewTripRow: function(){
    
    // This adds a new file upload to the form.
        var _SELF = this;
	    // Get a reference to the upload container.
	    var jFilesContainer = $( "#" + _SELF.ElementIDs.TripFieldsInputs );
     
	    // Get the file upload template.
	    
	    var templateID = "#" + _SELF.ElementIDs.TripFieldTemplate + " div.row";
	    
	    var jUploadTemplate = $( templateID );
	    
	    // Duplicate the upload template. This will give us a copy
	    // of the templated element, not attached to any DOM.
	    var jUpload = jUploadTemplate.clone();
     
	    // At this point, we have an exact copy. This gives us two
	    // problems; on one hand, the values are not correct. On
	    // the other hand, some browsers cannot dynamically rename
	    // form inputs. To get around the FORM input name issue, we
	    // have to strip out the inner HTML and dynamically generate
	    // it with the new values.
	    var strNewHTML = jUpload.html();
     
	    // Now, we have the HTML as a string. Let's replace the
	    // template values with the correct ones. To do this, we need
	    // to see how many upload elements we have so far.
	    var intNewFileCount = (jFilesContainer.find( "div.row" ).length + 1);
	    

	    // Set the proper ID.
	    jUpload.attr( "id", (_SELF.ElementIDs.TripFieldRow + intNewFileCount) );
	    
	    
	    //Define the fields to be replaced and the class/name to replace it with. These are used to update IDs further down. 
	    var txtInputValues = [
	        {
	            txtRegExp: '::FIELD2::',
	            txtReplace: _SELF.ElementClass.TripIcon 
	        },
	        {
	            txtRegExp: '::FIELD3::',
	            txtReplace: "routeMarker"
	         },
	         {
	            txtRegExp: '::FIELD4::',
	            txtReplace: "tripFieldsSpan"
	         },
	         {
	            txtRegExp: '::FIELD5::',
	            txtReplace: _SELF.ElementIDs.TxtTripStreet
	          },
	          
	             {
	            txtRegExp: '::FIELD6::',
	            txtReplace: _SELF.ElementIDs.TxtTripSuburb
	          },
	         {
	            txtRegExp: '::FIELD7::',
	            txtReplace: _SELF.ElementIDs.TxtTripSuburb + intNewFileCount 
	          },
	            {
	            txtRegExp: '::FIELD8::',
	            txtReplace: _SELF.ElementIDs.TxtTripSuburb
	          },
	            {
	            txtRegExp: '::FIELD12::',
	            txtReplace: "row" 
	          },
	            {
	            txtRegExp: '::FIELD14::',
	            txtReplace: 'showStreet'
	          },
	            {
	            txtRegExp: '::FIELD15::',
	            txtReplace: 'removeLink'
	          }           
	    ];
	    
	    
	     // Replace the values.
	    for (x in txtInputValues){
	    
	         strNewHTML = strNewHTML
	            .replace(
	                new RegExp ( txtInputValues[x].txtRegExp , "i" ),
	                (txtInputValues[x].txtReplace)
	                );
	    };
	    
     
	 
	    // Now that we have the new HTML, we can replace the
	    // HTML of our new upload element.
	    jUpload.html( strNewHTML );
     
	    // At this point, we have a totally intialized file upload
	    // node. Let's attach it to the DOM.
	    jFilesContainer.append( jUpload );
	    
	    //After field has been added update values
	    _SELF.updateTripFields();
	    
	    if (intNewFileCount == _SELF.MaxTripInputs){ 
	        
	         var addRow = ( "#" + _SELF.ElementIDs.AddTripFieldRow );
	         _SELF.MaxTripInputsUsed = true;
	         $(addRow).addClass('hide');
	    }
    	
        if (intNewFileCount > 2){    
            $('.' + _SELF.ElementClass.RemoveLink).removeClass('hide'); 
        }    
        
        var suburbTxt = ('#' + _SELF.ElementIDs.TxtTripSuburb + intNewFileCount);

        $('#' + _SELF.ElementIDs.TripFieldsInputs + ' input:text[title!=""]').hint();
        
       autoCompleteFunction.initAutoComplete(suburbTxt); 	
    },
    
    
    // Remove a trip input row
    removeField: function(id){
      var _SELF = this;
      var removeDiv = (_SELF.ElementIDs.TripFieldRow + id);
     //Logger.log(removeDiv);
      var d = document.getElementById( _SELF.ElementIDs.TripFieldsInputs);
      var olddiv = document.getElementById(removeDiv);
      d.removeChild(olddiv);
      
     var removeClass =_SELF.ElementIDs.RemoveLink;
	    var jFilesContainer = $( "#" + _SELF.ElementIDs.TripFieldsInputs );

	    var intNewFileCount = (jFilesContainer.find( "div.row" ).length );
    	
    	var addRow = ( "#" + _SELF.ElementIDs.AddTripFieldRow );
        $(addRow).removeClass('hide'); 
        _SELF.MaxTripInputsUsed = false;

       if (intNewFileCount < 3){  
            $('.removeLink').addClass('hide');
        }
        
       var divID = _SELF.ElementIDs.TxtTripSuburb + id;  
       autoCompleteFunction.removeFieldID(divID);      
      _SELF.updateTripFields(); 
    },
    
    
    // After the new fields are added/ removed icons are updated 
    updateTripFields: function(){
    
    var _SELF = this;
    var oldID = '';
    var newID = '';
    var removeLink = this.ElementNames.RemoveLink;
    var showStreet = this.ElementNames.ShowStreet;
    var txtTripStreet = this.ElementNames.TxtTripStreet;
    var txtTripSuburb = this.ElementNames.TxtTripSuburb;
    var inputsUpdate = new Array();
    
    $( ("#" +  _SELF.ElementIDs.TripFieldRow)  + 'input[title!=" "]').hint();

       $('input:text[name=txtTripStreet]').each(function(i) {
                    k = i + 1;    
                    this.id = (_SELF.ElementIDs.TxtTripStreet + k);   
                     });
    
      $('input:text[name=txtTripSuburb]').each(function(i) {
                    k = i + 1;     
                    oldID = this.id;     
                    this.id = (_SELF.ElementIDs.TxtTripSuburb + k); 
                    newID = this.id;  
                    
                        inputsUpdate.push({
                            oldID: oldID,
                            newID: newID
                        } );
                     });
                   
          autoCompleteFunction.updateFieldID(inputsUpdate);            

                                       
      $('img[class=routeMarker]').each(function(i) { 
                     k = i + 1; 
                     var tripicon = 'images/tripmarkers/' + k + '.png';     
                    this.src =(tripicon);            
                     });   
      
      $('div[class=row]').each(function(i) {
                    k = i + 1;   
                    this.id = (_SELF.ElementIDs.TripFieldRow + k);  
                     }); 
                     
      $('a[name=showStreet]').each(function(i) {
                    k = i + 1;   
                    this.id = (_SELF.ElementIDs.ShowStreet + k);
                     });   
                     
     _SELF.addLinksClickEvent();                              
                        
    }

}; addFields.initFields();


