$(document).ready(function() {
    launchModalsForSelects();
		recheck_fields();

    onDeleteRemoveTheParentFormGroup();
    onAddOfRowPostAndReplaceTheForm();
    refreshTheAmountsWithJson();

    filterTheClockTimeSelect();

		$('div.tab_container').live('keypress', function (event){ return event.keyCode == 13 ? false : true; });
});

function handleSelectChange(selectControl, modalSelectorCallback) {
	selectControl.parents('div.content_body').block({ message: '<h1 style="padding: 25px">Updating</h1>' }); 		

  
  if (selectControl.find(":selected").is(".modal")) {
    var modalSelector = modalSelectorCallback(selectControl);
    var modalObject = $(modalSelector);
    if (modalObject) {
      modalObject.modal(standard_modal_options);
    }                
		refreshTheForm($('#refresh_form_path')[0].value)	;
  } else {
    if (selectControl.siblings('.add_item_path')[0]) {
      refreshTheForm(selectControl.siblings('.add_item_path')[0].value);
    }
  }
  selectControl.parents('div.content_body').unblock();
  if (selectControl.is('.scroll_to')) {
    $.scrollTo(selectControl);				
  }
}

function launchModalForSelects(selectControlSelector, modalSelectorCallback) {
  $(selectControlSelector).livequery('change', function() {
	  handleSelectChange($(this), modalSelectorCallback);
	  return false;
 	});
}

function launchRegularModalsForSelects() {
    launchModalForSelects('select.modal_launcher',
    function(selectControl) {
        return '#' + selectControl.attr('id') + '_' + selectControl.val();
    });
}


/* SQ: ATTN DB: I'm just adding the new item in to the list. Leaving the auto selection for now as it's not right (decision approved by DT)  */
function addNewItemToSelectControlAndSelectIt(selectControl, new_item) {
	selectControl.find('option').attr('selected', null);
	selectControl.find('option:last').before("<option selected='selected' value='" + new_item.id + "'>" + new_item.name + "</option>");
}

function addNewItemToSelectControlAndSelectItAndReact(selectControl, new_item) {
	addNewItemToSelectControlAndSelectIt(selectControl, new_item);
  if ($(selectControl).siblings('.add_item_path')[0]) {
 	  refreshTheForm($(selectControl).siblings('.add_item_path')[0].value);
	}		
}

function ajaxModalAddToSelect(formToObserve, selectControl) {
  ajaxPost(formToObserve,
    function(resp) {
		  addNewItemToSelectControlAndSelectIt($('#' + selectControl), resp.new_item);
			$.modal.close();   
  	});
}

function ajaxModalRefreshForm(formToObserve, selectControl) {
	ajaxPost(formToObserve,
	function(resp) {
	  addNewItemToSelectControlAndSelectItAndReact($('#' + selectControl), resp.new_item);
		$.modal.close();   
	});
}


//this is all a bit double negativey
function isOkToAddNewItemToSelectControl(selectControl, newItem) {
    return ! (selectControl.hasClass('project_manager_only') && !newItem.is_project_manager)
}

function handleAjaxPostForNewEmployees() {
    ajaxPost('form#new_employee',
    function(resp) {
        $('select.employee_modal_launcher').each(function() {
            newItem = resp.new_item;
            if (isOkToAddNewItemToSelectControl($(this), newItem)) {
                addNewItemToSelectControlAndSelectItAndReact($(this), newItem);
            }
        });
				$.modal.close();   
    });
}

function onDeleteRemoveTheParentFormGroup() {
    $('form.new_project a.remove_this').live('click',
    function() {
        var answer = confirm('Are you sure?');
        if (answer) {
            $(this).parent().parent('div.form_group').remove();
            refreshTheForm($('#refresh_form_path')[0].value);
        }
        return false;
    });

    $('form.edit_project a.remove_this').live('click',
    function() {
				$(this).parent().next('input._delete').removeAttr("disabled");
        $(this).parent('div.fields').remove();
        refreshTheForm($('#refresh_form_path')[0].value);
        return false;
    });

}

function refreshTheForm(url, extraFormVariables) {
  var formSerialized = $('form.project').serialize();
  $.extend(formSerialized, extraFormVariables);

	if ($('div.tab_container')) {
		var currenttab = $('div.tab_container').data('tabbedForm').currentTabIndex();				
	}		

  $.ajax({
      url: url,
      type: "POST",
      dataType: 'html',
      data: formSerialized,
      success: function(resp) {
				entireForm = $('#NewProject .content_block');
				entireForm.empty();
				entireForm.html(resp);
				substituteSubmitButtonsForStyledHyperlinks();
				refreshTheAmountsWithJson();
				recheck_fields();
				if (currenttab && $('div.tab_container').data('tabbedForm')) {
				  $('div.tab_container').data('tabbedForm').openTab(currenttab, true);						 							
				}
      }
  });
	
}

function onAddOfRowPostAndReplaceTheForm() {
	$('a.add_item').live('click',
		function() {
	 		refreshTheForm($(this).siblings('.add_item_path')[0].value);
	 		return false;
		});
}

function launchModalsForSelects() {
	launchRegularModalsForSelects();
}

function updateProjectPhaseFromJson(projectPhaseElement, projectPhaseJson) {
    projectPhaseElement.children('.time_amount').html(projectPhaseJson.time_amount);
    var involvementsElements = projectPhaseElement.children('.involvement_row');
    var involvementsJson = projectPhaseJson.involvements;
    var index = 0;
    involvementsElements.each(function() {
        $(this).children('.involvement_rate').html(involvementsJson[index]);
        index++;
    });
}

function updatePhasesAndInvolvementRatesFromJson(resp) {
    var projectPhasesElements = $('.phase');
    var projectPhasesJson = resp.project_phases;
    var index = 0;
    projectPhasesElements.each(function() {
        updateProjectPhaseFromJson($(this), projectPhasesJson[index]);
        index++;
    });
}

function updateTotalsFromJson(resp) {
    $('#project_estimated_total_employee_costs').html(resp.estimated.total_employee_costs);
    $('#project_estimated_total_fixed_costs').html(resp.estimated.total_fixed_costs);
    $('#project_estimated_total_costs').html(resp.estimated.total_costs);
}


function refreshTheAmountsWithJson() {
   $('.cost_factor').live('click',
		function() {
			$(this).unbind('change');
			$(this).change( function() {
				$(this).parents('div.content_body').block({ message: '<h1 style="padding: 25px">Updating</h1>' }); 						
				refreshTheForm($('#refresh_form_path')[0].value);
  			$(this).parents('div.content_body').unblock();	
			});
 		});

    $('div.involvement_row input.text').live('click',
    function() {
			$(this).focus();
			$(this).select();
    });

    $('div.estimated_fixed_cost input.text').live('click',
    function() {
			$(this).focus();
			$(this).select();
    });
}


function filterTheClockTimeSelect() {
    $('#time_log_project_id').change(function() {
        $.getJSON(
							$('#project_phases_path').attr('value'),
							{project_id:  $('#time_log_project_id').attr('value')}, 
							function(resp) {
                projectPhasesSelectControl = $('#time_log_project_phase_id');
                projectPhasesSelectControl.empty();
								if (resp.project_phases.length == 0) {
									$('#time_log_project_phase_id').hide();
									$('#no_active_phases').show();
								} else {
									$('#no_active_phases').hide();									
									$('#time_log_project_phase_id').show();									
									
              	  $.each(resp.project_phases,
	                function(index) {					
	                    projectPhase = resp.project_phases[index];
	                    projectPhasesSelectControl.append("<option value='" + projectPhase.id + "'>" + projectPhase.name + "</option>");
	                });
							}
            }	
        );
    });
}

function replace_field_with_datepicker( jq_obj ) {
  jq_obj.datepicker( { dateFormat: 'yy-mm-dd', onClose: 
  function(dateText, inst) {
      var field = $(this);
      var date_obj = new Date(Date.parse(field.val().replace(/\-/g, '/'))); // Replace is needed in case we haven't changes the field
      field.next().html( $.datepicker.formatDate( 'd MM yy', date_obj ) );
			if ($('#refresh_form_path').length) {
	   		refreshTheForm($('#refresh_form_path')[0].value);
			}
    },
    showOptions: { duration: 1 }
  });
  jq_obj.width(1);
  jq_obj.height(1);
  if ( $.browser.msie ) {
    jq_obj.css({ 'position': 'absolute', 'left': '-9999em'});
  } else {
    jq_obj.css({ 'visibility': 'hidden'});
  }
  var a = jq_obj[0].value;
  if ( a.length > 0 ) {
    a = a.replace(/\-/g, '/');
    a = new Date(Date.parse(a));
    jq_obj.after('<a class=\"datepicker_text\" href=\"#\">' + $.datepicker.formatDate( 'd MM yy', a ) + '</a>');
  } else {
    jq_obj.after('<a class=\"datepicker_text\" href=\"#\">undefined</a>');
  	}
  var next_node = jq_obj.next();
  next_node.click( function(e) {
    if ( $.browser.msie ) {
      $(this).prev().css({ 'position': 'static', 'left': '0'});
    }
    $(this).prev().datepicker('show');
    return false;
  });
  jq_obj.removeClass('replace_with_datepicker');
}


function dim_phase_form_fields( jq_obj ) {
  if ( jq_obj.is('.dimmed') ) { return; }
  jq_obj.find('div.add_involvement').hide();
  jq_obj.find('a.remove_this').hide();
  jq_obj.find('select').each( function(i) {
    $(this).after("<span class=\"select_replacement\">" +  find_select_option_title($(this), $(this).val()) + "</span>");
    $(this).hide();
  });
  var cost_factor = find_select_option_title(jq_obj.find('select.cost_factor'), jq_obj.find('select.cost_factor').val() );
  jq_obj.find('.involvement_row input[type=text]').each( function(i) {
    $(this).after("<span class=\"input_replacement\">" + $(this).val() + " " + cost_factor + "</span>");
    $(this).hide();
  });
  jq_obj.addClass('dimmed');
}

function reenable_phase_form_field( jq_obj ) {
  if ( jq_obj.is('.dimmed') ) {} else { return; }
  jq_obj.find('div.add_involvement').show();
  jq_obj.find('a.remove_this').show();
  jq_obj.find('select').show();
  jq_obj.find('span.select_replacement').remove();
  jq_obj.find('.involvement_row input[type=text]').show();
  jq_obj.find('span.input_replacement').remove();
  jq_obj.removeClass('dimmed');
  jq_obj.removeClass('hovered');
}

function find_select_option_title( jq_obj, val ) {
  var option = jq_obj.find('option[value=' + val + ']');
  if ( option ) {
    return option.html();
  } else {
    return val;
  }
}

function dim_and_highlight_phases(url) {
  var show_phase_index = $('div.phase').length - 1;
  if ( url && url.match(/project\_phase\_index\=(\d+)$/) ) {
    show_phase_index = parseInt(RegExp.$1);
  }
  show_only_this_phase( $('div.phase').eq( show_phase_index ) );
  $('div.phase').click( function(e) {
    var jq_obj = $(this);
    if ( jq_obj.is('.dimmed') ) {
      e.stopPropagation();
      show_only_this_phase( jq_obj );
    }
  });
  $('div.phase').mouseenter( function(e) {
    var jq_obj = $(this);
    if ( jq_obj.is('.dimmed') ) {
      jq_obj.addClass('hovered');
    }
  });
  $('div.phase').mouseleave( function(e) {
    var jq_obj = $(this);
    if ( jq_obj.is('.dimmed') ) {
      jq_obj.removeClass('hovered');
    }
  });
}

function show_only_this_phase( jq_obj ) {
  $('div.phase').each( function(i) {
    if ( jq_obj.find('input[type=hidden]').eq(0).attr('id') == $(this).find('input[type=hidden]').eq(0).attr('id') ) {
      reenable_phase_form_field( jq_obj );
    } else {
      dim_phase_form_fields($(this));
    }
  });
}

function recheck_fields() {
  $('input.replace_with_datepicker').each( function(i) {
    replace_field_with_datepicker($(this));
  }); 
}

function hide_client_for_internal_project() {
	$('input#project_internal').click(function() {
		if ($("input#project_internal").is(":checked")) {
			$('div#client_details').hide("fast");
		} else {
			$('div#client_details').show("fast");			
		}
	});
}


// Tabbed form widget

$.widget('ui.tabbedForm', {
  _init: function() {
    var tabs = new Array;
    var tabs_themselves_lis = new Array();
    var tab_mode = this._getData('mode');
    var current_tab_index = this._getData('current_tab');

    // Set the tab mode as a class (for CSS)
    this.element.addClass('tab_mode_' + tab_mode);
    
    // Hide all but the first tab; add in the next or save buttons
    this.element.find('fieldset.tab_content').each( function(j) {
      var current_tab = $(this);
      if ( j != current_tab_index ) { current_tab.hide(); }
      tabs.push( current_tab.find('h3.legend').html() );
      
      if ( tab_mode != 'sequential' ) {
        current_tab.find('div.button_group').remove();
      } else {
      
      if ( current_tab.find('div.button_group').length == 0) {
        var button_text = 'Proceed &#187;' ;
        var form_group_classes = ( tab_mode == 'sequential' ) ? ' button_group ui_tabbedForm_buttons' : ' button_group disabled_buttons ui_tabbedForm_buttons';
        current_tab.append('<div class="form_group' + form_group_classes + '"><a class="button" href="#"><span>' + button_text + '</span></a></div>');
      }
			}
      
    });
    
    // If tabs exist, add tabular navigation
    if ( tabs.length > 0 ) {

      this.element.prepend('<ul class="tabs_themselves"></ul>');
      var tabs_themselves = this.element.find('ul.tabs_themselves');

      for ( var k = 0; k < tabs.length; k++ ) {
        var classname = '';
        if ( k == current_tab_index ) { 
          classname = ' class="selected"'
        } else if ( ( k < current_tab_index ) && ( tab_mode == 'sequential' ) ) {
          classname = ' class="completed"'
        }
        tabs_themselves.append('<li' + classname + '>' + tabs[k] + '</li>');
      }
      
      tabs_themselves.find('li').each( function(k) {
        $(this).click( function() {
          $(this).parents('.tab_container').data('tabbedForm').openTab( k, ( tab_mode != 'sequential' ) );
        });
      });
      
    }
    
    var obj = this;
    this.element.find('fieldset.tab_content').each( function(i) { obj.setupEvents( $(this) ); } );
    
    // Store everything we need
    this._setData('current_tab', current_tab_index);
    this._setData('tabs', this.element.find('fieldset.tab_content') );
    this._setData('tabs_themselves_lis', this.element.find('ul.tabs_themselves>li') );
    this._setData('current_tab_html', this.element.find('fieldset.tab_content').eq(current_tab_index).html() );
  },
  setupEvents: function(tab) {
    
    var tab_mode = this._getData('mode');

    if ( tab_mode != 'sequential' ) {
      // Set up watchers on the form fields
      var watcher_fn = function() {
        $(this).parents('.tab_container').data('tabbedForm').activateSave( );
      }
      tab.find('input,textarea').keyup( watcher_fn );
      tab.find('select').change( watcher_fn );
    }
    
    tab.find('div.ui_tabbedForm_buttons a.button').click( function() {
      if ( tab_mode == 'sequential' ) {
        $(this).parents('.tab_container').data('tabbedForm').nextTab();
      } else {
        $(this).parents('.tab_container').data('tabbedForm').saveTab();            
      }
      return false;
    });

  },
  nextTab: function() {
    this.openTab(this.currentTabIndex() + 1, true);
  },
  currentTabIndex: function() {
    return this._getData('current_tab');
  },
  activateSave: function() {
    this._getData('tabs').eq( this.currentTabIndex() ).find('.button_group:last').removeClass('disabled_buttons');
  },
  openTab: function( tab_index, allow_forwards ) {

    var tab_mode = this._getData('mode');
    var tabs = this._getData('tabs');
    var tabs_themselves = this._getData('tabs_themselves_lis');
    
    // Check to see if we can switch tabs
    if ( !( allow_forwards ) && ( this.currentTabIndex() <= tab_index ) ) {
      return;
    }
        
    if ( ( tab_mode != 'sequential' ) && ( tabs.eq( this.currentTabIndex() ).find('.disabled_buttons').length == 0 ) ) {
        // Restore tabs content so we can continue cleanly
        var current_tab = tabs.eq( this.currentTabIndex() );
        current_tab.html( this._getData('current_tab_html') );
        this.setupEvents( current_tab );
    }

    // Selection
    tabs_themselves.removeClass('selected');
    tabs_themselves.eq(tab_index).addClass('selected');  
    
    for ( var i = 0; i < tabs.length; i++ ) {
      if ( i == tab_index ) {
        tabs.eq(i).show();
      } else {
        tabs.eq(i).hide();
      }

      // Mark parts as completed (if we are in sequential mode)
      if ( tab_mode == 'sequential') {
        if ( i < tab_index ) {
          tabs_themselves.eq(i).addClass('completed');
        } else {
          tabs_themselves.eq(i).removeClass('completed');
        }
      }
    }
    
    this._setData('current_tab', tab_index);
    this._setData('current_tab_html', this.element.find('fieldset.tab_content').eq(tab_index).html() );

  },
  saveTab: function() {
    // Is the button disabled? Then don't save
    var current_tab = this._getData('tabs').eq( this.currentTabIndex() );
    if ( current_tab.find('.button_group:last').is('.disabled_buttons') ) { return; }

    // Implement actual saving
    
    // Ajax loadify
    current_tab.find('.button_group:last a.button span').html('Saving <img src="' + this._getData('ajaxImage') + '" class="ajax_loader" />');
    
    window.setTimeout( function() { $('.tab_container').eq(0).data('tabbedForm').finishSave(); }, 2000 );
  },
  finishSave: function() {
    var current_tab = this._getData('tabs').eq( this.currentTabIndex() );
    var button_group = current_tab.find('.button_group');
    button_group.addClass('disabled_buttons');
    button_group.find('a.button span').html('Save');
    button_group.append('<em class="saved_notification">Saved!</em>');
    button_group.find('em:last').fadeTo(1500, 0.99, function() { $(this).fadeOut( 500, function() { $(this).remove() } ); } );
  }
  
});

$.extend($.ui.tabbedForm, {
  getter: "currentTabIndex",
  defaults: {
    mode: 'sequential',
    ajaxImage: '/images/ajax-load.gif',
    current_tab: 0
  }
});

var ProjectDetails = new function() {
  $(function() {
		hide_client_for_internal_project();
    ajaxModalAddToSelect('form#new_client', 'client_name');
	});	
};


var ProjectPhases = new function() {
	$(function() {
		ajaxModalRefreshForm('form#new_phase', 'phase_id');
    //ajaxModalAddToSelect('form#new_employee', 'employee_id');		
	
	  launchModalForSelects('select.employee_modal_launcher',
      function(selectControl) {
        return $('#employee_create_new');
      });

		handleAjaxPostForNewEmployees();
	});
};

var ProjectCosts = new function() {
	$(function() {
		ajaxModalRefreshForm('form#new_material', 'material_id');    
	});
};

var ProjectSummary = new function() {
	$(function() {
	});
};