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

var lang_strings = {};
var default_lang = "en";
var dialog_active = false;

// Fix Firebug console not defined error
// http://www.codecouch.com/2008/10/referenceerror-console-is-not-defined/
if (window['loadFirebugConsole']) {
 window.loadFirebugConsole();
} else {
 if (!window['console']) {
   window.console = {};
   window.console.info = alert;
   window.console.log = alert;
   window.console.warn = alert;
   window.console.error = alert;
 }
}

// TODO: David & Tracy:  this function was not available in all the cases it was needed for the
// account search dialog, so we moved it here temporarily so it will always be available.  It should
// be moved into an appropriate object as part of refactoring the search account controls
//
function deactivateDialog() {
  dialog_active = false;
  Dialog.closeInfo();
  return false;
}

function toggleBlocks(block_to_hide, block_to_show, hidden, excludedIds) {
  setAllHidden($(block_to_hide), hidden, excludedIds);
  setAllHidden($(block_to_show), !hidden, excludedIds);
}

function setAllHidden(element, hidden, excludedIds) {
	if (hidden) {
		$(element).hide()
	} else {
		$(element).show()
	}
	setAllDisabled(element, hidden, excludedIds);
}

function setAllDisabled(element, disabled, excludedIds) {
  if (typeof excludedIds == 'undefined')
    excludedIds = [];

  excluded = $A(excludedIds);
	$(element).descendants().each(function(e) {
	  if (!excluded.include(e.id))
	    e.disabled = disabled;
	})
}

function toggleSearchCriteria() {
	toggleElements(['search_div', 'hide_search_div_link', 'modify_search_id', 'criteria_summary_div']);
};

function toggleBrowseCriteria() {
	toggleElements(['browse_div','show_browse_link','hide_browse_link'])
};

function toggleElements(elements) {
	for (var i = 0; i < elements.length; i++) {
		Element.toggle(elements[i]);
	}
};

function togglePanel(element_id) {
  toggleElements(["hide_" + element_id + "_link", "show_" + element_id + "_link", element_id])
}; 

function enableDisable(divDomId) {
	var checkboxes = $$("#" + divDomId + " input[type=checkbox]");
	for (i = 0; i < checkboxes.length; i++) {
		checkboxes[i].disabled = !checkboxes[i].disabled;
	}
};

function popupBidHistory(url) {
  window.open(url,null,'height=600,width=800,toolbar=0');
};

function popupForgotPassword(url) {
  var w = document.body.clientWidth;
  var h = document.body.clientHeight;
  var x = window.screenX;
  var y = window.screenY;
  var popW = 800
  var popH = 600;
  var leftPos = ((w-popW)/2)+x
  var topPos = ((h-popH)/2)+y;
  window.open(url,'popup','width='+popW+',height='+popH+',top='+topPos+',left='+leftPos+'toolbar=no,resizable=no,scrollbars=no');
	return false;
};

function classify(string) {
	return string.replace(/(^|_)(.)/g,function(match,previousChar,lowercase) {return lowercase.toUpperCase()});
};

function with_toolbocks_calendar(rails_convention_id,block) {
	input = $('DatetimeToolbocks' + classify(rails_convention_id) + 'Input');
  button = $('DatetimeToolbocks' + classify(rails_convention_id) + 'Button');
	block(input, button);
};

function disable_toolbocks_calendar(rails_convention_id) {
	with_toolbocks_calendar(rails_convention_id, function(input, button) {
		input.disable();
		button.hide();
	});
};

function enable_toolbocks_calendar(rails_convention_id) {
	with_toolbocks_calendar(rails_convention_id, function(input, button) {
		input.enable();
		button.show();
	});
};

function set_toolbocks_calendar_disable(rails_convention_id, disabled) {
	if (disabled) {
		disable_toolbocks_calendar(rails_convention_id);
	} else {
		enable_toolbocks_calendar(rails_convention_id);
	}
};

function stripOnSubmit(field) {
	var oldOnsubmit = field.form.onsubmit;
 	field.form.onsubmit = function() { 
 	  field.value = field.value.strip();
 	  if(oldOnsubmit) 
 	    return oldOnsubmit();
  };
  field.onfocus = null;
}

/* Append an element after another - helper method for DOM */
function insertAfter(newElement,targetElement) {
	var parent = targetElement.parentNode;
	if (parent.lastChild == targetElement) {
		parent.appendChild(newElement);
	} else {
		parent.insertBefore(newElement,targetElement.nextSibling);
	}
};
/* Attach onload events safely without overwriting any existing events */
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
};

function CalendarRangeCallback( start_str, end_str ) {
  var start = new Date();
  start.setTime( Date.parse( start_str ) );
  
  var end   = new Date();
  end.setTime( Date.parse( end_str ) );

  this.disableSelectionFor = disableSelectionFor;

  function disableSelectionFor( date ) {
    if( start <= date && date < end ) {
      return false;
    }
    return true;
  }
  return this.disableSelectionFor;
}
function hideInfo(ele,container) {
	changeZIndex(container,1);
	Element.hide(ele);
}
function showInfo(ele,container) {
	changeZIndex(container,200);
	Element.show(ele);
}
function changeZIndex(ele,ind) {
	document.getElementById(ele).style.zIndex = ind;
}
function toggleAllEquipment(state) {
	var container = document.getElementById('optional_vehicle_equipment_form');
	var checkboxes = container.getElementsByTagName('input');
	for (var i=0; i<checkboxes.length; i++) {
		checkboxes[i].checked = state;
	}
}

function toggleGroup(group_to_enable, group_to_disable_id) {
  $$('#' + $(group_to_enable).id + ' .toggle').invoke('enable');
  $$('#' + group_to_disable_id + ' .toggle').invoke('disable');
}

function l(key) {
  return lang_strings[current_lang][key];
}

function set_language(lang) {
  current_lang = lang || default_lang;
}

// copied from sapphire
function baseDomainString(){
	e = document.domain.split(/\./);
	if(e.length > 1) {
		return(e[e.length-2] + "." +  e[e.length-1]);
	} else {
		return(document.domain);
	}
}

// This is needed because the sapphire function baseDomainString is used to set the domain on the seller tools/manheim site
// this breaks our iframes due to cross site security issues, so we need to set it in the target of any iframe.
function setBaseDomainOnDocument() {
  document.domain = baseDomainString();  
}

function load_localized_string(key, msg) {
  lang_strings[current_lang] = lang_strings[current_lang] || {};
  lang_strings[current_lang][key] = msg;
}
// Globals to store javascript objects handles like TreeView
// var SearchPageForm = {};

function wtClickTrack(url, title, actionId, event) { 
	dcsMultiTrack('DCS.dcsuri', 'click:' + url, 'WT.ti', 'Click:' + title, 'WT.z_actionId', actionId, 'WT.z_event', event, 'WT.dl', '999', 'DCS.dcsqry', '', 'WT.si_n', '', 'WT.si_p', '', 'WT.cg_n', '', 'WT.cg_s', '', 'WT.z_search_type', '', 'WT.z_search_criteria', '', 'WT.tx_e', '', 'WT.oss_r', '', 'DCSext.pf', '', 'DCSext.pfv', '', 'DCSext.sct', ''); 
	DCS.dcsuri=WT.ti=WT.dl=WT.z_actionId=WT.z_event=''; 
}

function webtrendsQuickBidTrack (url, title, scenario, scenario_step, listing_id, error_count, errors) {
	dcsMultiTrack('DCS.dcsuri', url
								,'WT.ti', title
								,'WT.cg_n', 'OVE | Buy'
								,'WT.cg_s', 'OVE | Buy | Bid'
								,'WT.si_n', scenario
								,'WT.si_x', scenario_step
								,'WT.z_listingid', listing_id
								,'DCSext.errct', error_count
								,'WT.z_errors', errors
								,'WT.dl', '999'
								);
}

function highlightText(text_id) {
  if (window.getSelection) {
    s = window.getSelection();
    var r1 = document.createRange();
    r1.setStartBefore($(text_id));
    r1.setEndAfter($(text_id)) ;
    s.addRange(r1);
  } else if (document.selection) {
    var r1 = document.body.createTextRange();
    r1.moveToElementText($(text_id));
    r1.setEndPoint("EndToEnd", r1);
    r1.select();
  }
}


CheckboxAndLabel = function(checkbox_id, label_id, options) {
	this.options = options;
	this.checkbox = $(checkbox_id);
	this.label = $(label_id);
	this.checkbox.checkbox_and_label = this;
}

CheckboxAndLabel.prototype = {

	initializeView : function() {
		this.setVisible(!this.options.shouldHideOnLoad);
		this.setEnabled(!this.options.shouldDisableOnLoad);
	},
	
	update : function(checked) {
		this.setVisible(checked);
		this.setEnabled(checked);
		
		if (!checked) {
			this.setChecked(false);
		}
	},
	
	setEnabled : function(enabled) {
		if (this.options.shouldAlwaysDisable) {
			this.privateSetEnabled(false);
		} else {
			this.privateSetEnabled(enabled);
		}
	},
	
	setChecked : function(setChecked) {
		if (!this.options.shouldAlwaysKeepValue) {
			this.checkbox.checked = setChecked;
		}
	},
	
	setVisible : function(visible) {
			if (this.options.shouldAlwaysHide) {
				this.privateSetVisible(false);
			} else {
				this.privateSetVisible(visible);
			}
	}, 

	privateSetEnabled : function(enabled) {
	    if (enabled) {
				this.checkbox.enable();
				this.label.removeClassName(this.options.disable_class);
	    } else {	
				this.checkbox.disable();
	      this.label.addClassName(this.options.disable_class);
	    }		
	},
	
	privateSetVisible : function(visible) {
    if (visible) {
			this.label.show();
			this.checkbox.show();
    } else {			
			this.label.hide();
	    this.checkbox.hide();
    }		
	}
}
