// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

new_analysis_show_step_one = function() {
  $('step_0').hide(); 

  selected_starting_point = $A([
    $F('analysis_starting_point_fresh'),
    $F('analysis_starting_point_month'),
    $F('analysis_starting_point_revision')
  ]).compact().first();
  
  $('step_' + selected_starting_point).show();
}

new_analysis_show_step_zero = function(button) {
  $(button).up(".wizard_step").hide();
  $('step_0').show();   
}
  



get_page_size = function() {
  var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	
	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}

	return [pageWidth, pageHeight];
}













show_modal_overlay = function() {
  
  page_dimensions = get_page_size();
  
  $('modal_overlay').setStyle({ height: page_dimensions[1] + "px" });
  $('modal_overlay').show();
}

hide_modal_overlay = function() {
  $('modal_overlay').hide();
  $$('#modal_overlay .modal_box').each(function(box) { box.hide(); });
}

show_message_box = function(title, message, show_with_progress_indicator, show_as_error, show_with_close_button) {

  // default arguments
  if (!show_as_error) { show_as_error = false; }
  if (!show_with_progress_indicator) { show_with_progress_indicator = true; }
  if (!show_with_close_button) { show_with_close_button = false; }
  
  // title = $('modal_message_box_title')
  // message = $('modal_message_box_message')
}

hide_message_box = function() {
  hide_modal_overlay();
}

show_calendar_for_touch_form = function(assign_to_user_id) {
  if(/[0-9]+/.match(assign_to_user_id)) {
    $('assign_to_user_fields').show();
    init_wide_calendar();
  } else {
    $('assign_to_user_fields').hide();
  }
}






refresh_managers_select_box = function(select_box) {
  
  if ($('no_users_error') != null) {
    $('no_users_error').remove();
  }
  
  target_business_id = select_box.value;
  request_uri        = "/api/businesses/" + target_business_id + "/users.json";
  select_box         = $(select_box);
  users_box          = $$('#suitable_users_wrapper select')[0];
  activity_indicator = new Element('img', { id: 'activity_indicator', src: '/images/loading_indicator.gif' });



  no_users_message   = new Element('span', { id: 'no_users_error', style: 'display: none;' });
  no_users_message.addClassName('notice');

  no_users_message.insert("The selected business has no users.");
  
  new Ajax.Request(request_uri, {
    
    method: "get",

    
    onLoading: function(transport) {
      
      // set up our pending transition state
      users_box.hide();    

      $('suitable_users_wrapper').insert({ top: activity_indicator });
      $('suitable_users_wrapper').insert({ top: no_users_message });
    },


    onSuccess: function(transport) {
      response_blob = transport.responseText.evalJSON();
      
      // clear options
      users_box.options.length = 0;

      // give us a set of usable user objects
      users = $A(response_blob).map(function(o) {
        return o.user;
      });
      
      // iterate and add to our options
      users.each(function(user) {         
        new_option = new Element('option', { value: user.id });
        new_option.insert(user.name);
        
        users_box.insert({ bottom: new_option });
      });

      users_box.show();
      activity_indicator.remove();
      no_users_message.remove();
    },
    
    on404: function(transport) {
      activity_indicator.remove();
      no_users_message.show();  
    }
    
    
    
  });
}




















set_solution_bar_colour = function(swatch_id, new_colour)
{
  $$('div#swatch_box div.solution_swatch').each(function(swatch) { swatch.removeClassName('selected'); });
  $(swatch_id).addClassName('selected');
  $('solution_bar_colour').value = new_colour;
}

show_spinner = function() {
  $('spinner_container').show();
}
 
hide_spinner = function() {
  $('spinner_container').hide();
}

show_failure = function(request) {
  alert("There was a problem: " + request.status);
}

toggle_assign_box = function(show_box, show_cal) {

    show_cal = typeof(show_cal) != 'undefined' ? show_cal : true;

    if (show_box) {
      $('assign_to_wrapper').show();
      if(show_cal) { init_calendar(); }
    } else {
      $('assign_to_wrapper').hide();
    }
}

onDateClick = function(name, date_array_param) {
    date_array = date_array_param[0][0];
    
    year = date_array[0];
    month = date_array[1];
    date = date_array[2];
    
    $('note_due_date').value = year + "-" + month + "-" + date;
}

onDeadlineDateClick = function(name, date_array_param) {
    date_array = date_array_param[0][0];
    
    year = date_array[0];
    month = date_array[1];
    date = date_array[2];
    
    $('project_deadline').value = year + "-" + month + "-" + date;
}


init_wide_calendar = function(select_date) {

    YAHOO.namespace("fcg.calendar");
    YAHOO.fcg.calendar.init = function() { 

			sd = (typeof(select_date) != 'undefined' && select_date != "") ? new Date(/[0-9]{4}-[0-9]{2}-[0-9]{2}/.exec(select_date)[0]) : new Date();	
			pd = (sd.getMonth() + 1) + "/" + sd.getFullYear()
			p = { pagedate: pd, PAGES: 3 };
		
			YAHOO.fcg.calendar.due_date = new YAHOO.widget.CalendarGroup('due_date','calendar_container', p);                     
			YAHOO.fcg.calendar.due_date.selectEvent.subscribe(onDateClick);
			
			if (typeof(select_date) != 'undefined' && select_date != "") {
				YAHOO.fcg.calendar.due_date.select(sd);
			}
					
			YAHOO.fcg.calendar.due_date.render();                    
    }

	YAHOO.util.Event.onDOMReady(YAHOO.fcg.calendar.init);    
}

init_deadline_calendar = function(select_date) {

    YAHOO.namespace("fcg.calendar");
    YAHOO.fcg.calendar.init = function() { 

			sd = (typeof(select_date) != 'undefined' && select_date != "") ? new Date(/[0-9]{4}-[0-9]{2}-[0-9]{2}/.exec(select_date)[0]) : new Date();	
			pd = (sd.getMonth() + 1) + "/" + sd.getFullYear()
			p = { pagedate: pd, PAGES: 3 };
		
			YAHOO.fcg.calendar.due_date = new YAHOO.widget.CalendarGroup('due_date','calendar_container', p);                     
			YAHOO.fcg.calendar.due_date.selectEvent.subscribe(onDeadlineDateClick);
			
			if (typeof(select_date) != 'undefined' && select_date != "") {
				YAHOO.fcg.calendar.due_date.select(sd);
			}
					
			YAHOO.fcg.calendar.due_date.render();                    
    }

	YAHOO.util.Event.onDOMReady(YAHOO.fcg.calendar.init);    
}

init_calendar = function(select_date) {

    YAHOO.namespace("fcg.calendar");
    YAHOO.fcg.calendar.init = function() { 



			sd = (typeof(select_date) != 'undefined') ? new Date(/[0-9]{4}-[0-9]{2}-[0-9]{2}/.exec(select_date)[0]) : new Date();	
			pd = (sd.getMonth() + 1) + "/" + sd.getFullYear()	
			p = { pagedate: pd };
		
			YAHOO.fcg.calendar.due_date = new YAHOO.widget.CalendarGroup('due_date','calendar_container', p);                     
			YAHOO.fcg.calendar.due_date.selectEvent.subscribe(onDateClick);

			if (typeof select_date != 'undefined') {
				YAHOO.fcg.calendar.due_date.select(sd);
			}

			YAHOO.fcg.calendar.due_date.render();                    
    }

	YAHOO.util.Event.onDOMReady(YAHOO.fcg.calendar.init);    
}

add_file_field = function(ff) {
    Element.extend(ff);    
    parent_ff_prime = ff.parentNode.cloneNode(true);    
    $('file_wrapper').appendChild(parent_ff_prime);
    new Effect.Highlight(parent_ff_prime);
}

remove_file_field = function(ff) {

    files = $('file_wrapper').getElementsByClassName('attached_file_wrapper');
    
    if(files.length > 1) {
        Element.extend(ff);
        ff.parentNode.remove();        
    }
}



select_colour = function(selected_td, colour, foreground) {
  
  // clear all
  $A($('colour_table').getElementsByTagName('td')).each(function(x) {
    x.className = ''
  });
  
  $('category_colour').value = colour;
  $('category_text_colour').value = foreground;
 
  Element.addClassName(selected_td, 'selected');
}




kase_type_other_callback = function(dropdown) {
    $('kase_kase_type_text').disabled = (dropdown.value != 999)
    if($('case_state_wrapper') != null)
    {
      ( dropdown.value < 300 ) ? $('case_state_wrapper').show() : $('case_state_wrapper').hide();
    }
}

kase_status_callback = function(dropdown) {
  $('kase_closure_reason').disabled = (dropdown.value != 4) 
}

contract_type_toggle_callback = function(dropdown, field) {
  $(field).disabled = (dropdown.value != "Other...") 
}

generic_toggle_callback = function(dropdown, field) {
  $(field).disabled = (dropdown.value != -1) 
}


business_type_callback = function(dropdown, field) {
	(dropdown.value == 'Other...') ? $(field).show() : $(field).hide();
}



plan_type_callback = function(dropdown) {

  // do nothing yet...
  
  // fixed_array_fields = new Array('line_rental', 'cap_')
  // 
  // if (dropdown.value == 'fixed') 
  // {
  //   $A()
  // }
  // 
  // else
  // {
  // 
  // }
  
}



copy_address = function() {
  // if($F('contact_postal_address_line_1') == '') 
  // {
		$('contact_postal_address_line_1').value = $F('contact_address_line_1');
		$('contact_postal_address_line_2').value = $F('contact_address_line_2');
		$('contact_postal_suburb').value = $F('contact_suburb');
		$('contact_postal_postcode').value = $F('contact_postcode');
		$('contact_postal_state').selectedIndex = $('contact_state').selectedIndex;
  // }
}



sanity_check_for_date = function(dropdown) {

  /contract_notification_([0-9]+)_time_unit/.exec(dropdown.id)
  unit = dropdown.value
  notification_id = RegExp.$1
  time_amount = $('contract_notification_' + notification_id + '_time_amount').value
  
  if( (unit == "Days" && time_amount > 1825) || (unit == "Weeks" && time_amount > 260) || (unit == "Months" && time_amount > 60))
  {
    alert("Bad date.");
    $('contract_notification_' + notification_id + '_time_amount').focus();
  }
}




swap_analysis_type_labels = function(dropdown, show_flash)
{
  if (dropdown.value == 'mobile') 
  {
    $('primary_lines_label').innerHTML = "Number of Mobile Lines"
    $('secondary_lines_label').innerHTML = "Number of Fixed Lines"
    $('secondary_lines_h2').innerHTML = "Fixed Lines"
  }
  
  else
  {
    $('primary_lines_label').innerHTML = "Number of Fixed Lines"
    $('secondary_lines_label').innerHTML = "Number of Mobile Lines"
    $('secondary_lines_h2').innerHTML = "Mobiile Lines"
  }

  if (show_flash) {
    new Effect.Highlight('primary_lines_label')
    new Effect.Highlight('secondary_lines_label')
    new Effect.Highlight('secondary_lines_h2')
  }
}


line_type_other_callback = function(dropdown) {
    $('phone_line_type_other').disabled = (dropdown.value != -1)
}


save_and_show = function(next_action) {
  $('next_action').value = next_action
  $('line_form').onsubmit()
}











show_report_page = function(page_id) {
  $$(".report_page_wrapper").each(function(el){
    el.addClassName('hidden')
  })
  
  $(page_id + '_wrapper').removeClassName('hidden');
}

show_solution_graph = function(solution_index) {
  $$(".solution_view").each(function(el){
    el.addClassName('hidden')
  })

  $('solution_chart').removeClassName('hidden');
}



print_report = function() {
  $$(".hidden").each(function(el){ el.removeClassName('hidden'); })

  if(confirm("To print the report at the best possible quality, make sure that you select 'Print Images and Backgrounds' in your Advanced Options. Hit OK to print or Cancel to change your settings."))
  {
    window.print();
    
    window.set_timeout(5000, function() {
      $$(".report_page_wrapper").each(function(el){
        el.addClassName('hidden')
      })

      $$(".solution_view").each(function(el){
        el.addClassName('hidden')
      })

      $('summary_wrapper').removeClassName('hidden');      
    })
  }

}


toggle_all = function(group, trigger){
  boxen = $(trigger).up('.tab_view_container').select('input.' + group + '_box');
  
  toggle_value = boxen.first().checked ? false : true;

  
  boxen.each(function(box) {
    box.checked = toggle_value;
  })
}




disable_phone_line_selects = function(selected_value)
{
  phone_line_selects = $$('select.phone_line');
  phone_line_group_selects = $$('select.phone_line_group');  

  all_phone_line_groups_are_blank = true
  
  phone_line_group_selects.each(function(sel) {
    all_phone_line_groups_are_blank = all_phone_line_groups_are_blank && (sel.value == "-1")
  });
  
  phone_line_selects.each(function(sel) {
    if (all_phone_line_groups_are_blank) {
      sel.disabled = false
    } else {
      sel.disabled = true
      sel.selectedIndex = 0
    }    
  });



}

disable_phone_line_group_selects = function(selected_value)
{
  phone_line_selects = $$('select.phone_line');
  phone_line_group_selects = $$('select.phone_line_group');  

  all_phone_lines_are_blank = true

  phone_line_selects.each(function(sel) {
    all_phone_lines_are_blank = all_phone_lines_are_blank && (sel.value == "-1")
  });

  
  phone_line_group_selects.each(function(sel) {
    if (all_phone_lines_are_blank) {
      sel.disabled = false
    } else {
      sel.disabled = true
      sel.selectedIndex = 0
    }    

  }); 
}


filter_client_list = function(target_letter) {
  // clear links
  $$('div#list_clients_jump_to_box a').each(function(a_tag) { a_tag.removeClassName('current_option'); });
  
  // apply link
  $('index_link_' + target_letter).addClassName('current_option');
  
  // hide boxes
  $$('div.client_index_card').each(function(index_card) { index_card.hide(); });
  
  // show box
  $('client_index_card_' + target_letter).show();
  
  return true;
}

clear_client_list_filter = function() {

  // clear links
  $$('div#list_clients_jump_to_box a').each(function(a_tag) { a_tag.removeClassName('current_option'); });
  
  // apply link
  $('show_all_link').addClassName('current_option');
  
  // hide boxes
  $$('div.client_index_card').each(function(index_card) { index_card.show(); });
  
  return true;
}



scrollViewTo = function(box, target_element) {
  target_element = $(target_element);
  box            = $(box);
  box.scrollTop  = (target_element.offsetTop - box.offsetTop);
}

// 
// reindex_scrolly_list = function(list_id) {
//   current_index = 1
// 
//   $(list_id).select('div').each(function(list_item) {
//     list_item.select('span')[0].update(current_index);
//     current_index++;
//   });
// }

reindex_and_scroll_to_bottom_of_scrolly_list = function(list_id) {
  // reindex_scrolly_list(list_id);

  el = $(list_id).select('div').last();
  scrollViewTo(list_id, el);
}

show_solution_tab = function(which_tab) {

  // hide tabs
  $$('div.solution_tab_container').each(function(tab_container) { tab_container.hide(); });

  // show selected
  $(which_tab).show();

  // next-tab to show is
  $('next_action').value = which_tab;
}





function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}





function bytesToSize(bytes, precision, base)
{  
    if (base == 2) {
      var kilobyte = 1024;
      var megabyte = kilobyte * 1024;
      var gigabyte = megabyte * 1024;
      var terabyte = gigabyte * 1024;      
    } else {
      var kilobyte = 1000;
      var megabyte = kilobyte * 1000;
      var gigabyte = megabyte * 1000;
      var terabyte = gigabyte * 1000;      
    }

    if ((bytes >= 0) && (bytes < kilobyte)) {
        return bytes + 'B';
 
    } else if ((bytes >= kilobyte) && (bytes < megabyte)) {
        return (bytes / kilobyte).toFixed(precision) + 'KB';
 
    } else if ((bytes >= megabyte) && (bytes < gigabyte)) {
        return (bytes / megabyte).toFixed(precision) + 'MB';
 
    } else if ((bytes >= gigabyte) && (bytes < terabyte)) {
        return (bytes / gigabyte).toFixed(precision) + 'GB';
 
    } else if (bytes >= terabyte) {
        return (bytes / terabyte).toFixed(precision) + 'TB';
 
    } else {
        return bytes + 'B';
    }
}


