var browser_ie = false;
var initialized = false;
var list_pre_use_image = true;

function sub_query_value(url, name, new_value) {
  var new_url = "";
  var assign = name + '=' + new_value;
  var regex = new RegExp(name + "=[^&]*", "");
  if (url.search(regex) != -1) {
    new_url = url.replace(regex, assign);
  } else if (url.indexOf('?') != -1) {
    new_url = url + '&'+ assign;
  } else {
    new_url = url + '?' + assign;
  }
  return new_url;
}

function change_sort_filter(sort_value, filter_value) {
  var this_url = String(window.location);
  new_url = sub_query_value(this_url, 'sort', sort_value);
  new_url = sub_query_value(new_url, 'filter', filter_value);
  window.location = new_url;
}

function change_vote(idea_id, value) {
  window.location = "vote?idea_id=" + idea_id + "&vote=" + value;
}

function check_form(form, which, message) {
  var form_element = form.elements[which];
  var form_value;
  if (typeof form_element.value != 'undefined') {
    form_value = form_element.value;
  } else {
    form_value = form_element.options[form_element.selectedIndex];
  }
  if (form_value == '') {
    var node = form_element.parentNode;
    node.style.border = "3px #e60000 solid";
    return false;
  }
  return true;
}

function get_list_pre() {
  var result = document.createDocumentFragment();

  if (list_pre_use_image) {
    var img = new Image(); img.src = 'images/list-dot.png';
    img.className = 'list-dot';
    img.style.position = 'relative';
    img.style.top = '3px';
    var text = document.createTextNode('\u00a0');

    result.appendChild(img);
    result.appendChild(text);
  } else {
    var span = document.createElement('span');
    span.className = 'list-dot';
    var text = document.createTextNode('\u2027\u00a0');
    span.appendChild(text);

    result.appendChild(span);
  }

  return result;
}

function fix_lists() {
  /* Yet another bad hack to fix yet more IE brokenness
   *
   * For some reason, IE doesn't support :before pseudoelements,
   * so here we just insert them manually. :(
   */
  if (browser_ie) {
    ul_list = document.getElementsByTagName('ul');

    for (var i = 0; i < ul_list.length; i++) {
      li_list = ul_list[i].getElementsByTagName('li');

      for (var j = 0; j < li_list.length; j++) {
        /* insert dot image + nbsp before each unordered list element */
        var li = li_list[j];
        if (li.className == 'nodot') { continue; }
        var pre = get_list_pre();
        li.insertBefore(pre, li.firstChild);
      }
    }
  }
}

function ButtonChanger (element, regular, rollover) {
  this.element = element;
  this.regular = regular;
  this.rollover = rollover;
  this.img = img = new Image();
  alternate = new Image;
  img.src = regular;
  alternate.src = rollover;
  element.appendChild(img);
  element.style.cursor = 'pointer';

  var self = this;

  this.mouseover = function () {
    self.img.src = self.rollover;
  }

  this.mouseout = function () {
    self.img.src = self.regular;
  }

  element.onmouseout = this.mouseout;
  element.onmouseover = this.mouseover;
}

var button_list = [
  [ 'stop-tracking-selected', 'button_stoptrackingselected' ],
  [ 'stop-tracking-all', 'button_stoptrackingall' ],
  [ 'save-info', 'button_saveinfo' ],
  [ 'search-now', 'button_searchnow' ],
  [ 'search-now-dupl', 'button_searchnow' ]
];

function find_buttons() {
  for (var i = 0; i < button_list.length; i++) {
    var div = document.getElementById(button_list[i][0]);
    if (div) {
      new ButtonChanger(div, 'images/' + button_list[i][1] + '.png',
                             'images/' + button_list[i][1] + '_rollover.png');
    }
  }
}

function initialize() {
  if (!initialized) { 
    browser_ie = (navigator.appName == 'Microsoft Internet Explorer');
    initialized = true;
  }
}

function generic_onload() {
  /* do some quick browser detection */
  initialize();

  fix_lists();
  find_buttons();
}

var state = { };
function select_all(form, name) {
  if (typeof state[name] == 'undefined') { state[name] = false; }
  state[name] = !state[name];

  input_list = document.forms[form].getElementsByTagName('input');
  for (var i = 0; i < input_list.length; i++) {
    var input = input_list[i];
    if (input.name == name) {
      input.checked = state[name];
    }
  }
}

function is_disabled(target) {
  initialize();
  var cond;
  if (browser_ie) { cond = target.disabled; }
  else { cond = target.hasAttribute('disabled'); }
  return cond;
}

function disable_input(form_name, element_name) {
  var form = document.forms[form_name];
  var elt = form.elements[element_name];
  var cond = !is_disabled(elt);
  if (cond) {
    elt.setAttribute('disabled', 'disabled');
  }
}

function enable_input(form_name, element_name) {
  var form = document.forms[form_name];
  var elt = form.elements[element_name];
  var cond = is_disabled(elt);
  if (cond) {
    elt.removeAttribute('disabled');
  }
}

function open_calendar(form_name, element_name, base) {
  var form = document.forms[form_name];
  var elt = form.elements[element_name];
  if (elt.disabled) {
    window.open(base + 'util/calendar.php?style=' + base + '/calendar.css&formName=' + form_name + '&elementName=' + name, 'calendar', 'width=320,height=320,status');
  }
}

function showPopupWindow (id, label, url)
{
	dhtmlwindow.open(id,"iframe",url,label,"width=590px,height=350px,resize=1,scrolling=1,center=1","recal") ;
}

function showTermsWindow ()
{
	dhtmlwindow.open("termsWindow","iframe","/about?action=terms&showHeader=false&isPopup=true","Terms and Conditions","width=590px,height=350px,resize=1,scrolling=1,center=1","recal") ;
}

function showPrivacyWindow ()
{
	dhtmlwindow.open("privacyWindow","iframe","/about?action=privacy&showHeader=false&isPopup=true","Privacy Policy","width=590px,height=350px,resize=1,scrolling=1,center=1","recal") ;
}

function evalElement (elementId)
{
	var e = document.getElementById(elementId) ;
	var x = e.getElementsByTagName("script") ;
	for(var i=0;i<x.length;i++)
	{
	    eval(x[i].text) ;
	}
}

function setCookie (name, value, expires)
{
	document.cookie = escape(name)+"="+escape(value)+"; path="+((expires==null)?"":"; expires="+expires.toGMTString()) ;
}

function getCookie (name)
{
	var cookieName = name+"=" ;
	var cookies = document.cookie ;
	var begin, end ;
	if (cookies.length>0)
	{
		begin = cookies.indexOf(cookieName) ;
		if (begin!=-1)
		{
			begin += cookieName.length ;
			end = cookies.indexOf(";",begin) ;
			if (end=-1)
				end = cookies.length ;
			return unescape(cookies.substring(begin,end)) ;
		}
	}
	return null ;
}

function deleteCookie (name)
{
	document.cookie = name+"=; expires=Thu, 01-Jan-70 00:00:01 GMT; path=" ;
}

function setInnovaEditorProperties (editor)
{
	editor.mode='HTMLBody' ;
	editor.width='100%' ;
	editor.height='300px' ;
	editor.useBR = false ;
	editor.useDIV = false ;
	editor.features=["Save","FullScreen","Preview","Print",
		"Search","SpellCheck",
		"Superscript","Subscript","LTR","RTL",
		"Table","Guidelines","Absolute",
		"Flash","Media","InternalLink","CustomObject",
		"Characters","ClearAll","BRK",
		"Cut","Copy","Paste","PasteWord","PasteText",
		"Undo","Redo","Hyperlink","Bookmark","Image",
		"JustifyLeft","JustifyCenter","JustifyRight","JustifyFull",
		"Numbering","Bullets","Indent","Outdent",
		"Line","RemoveFormat","BRK","HTMLSource",
		"StyleAndFormatting","TextFormatting","ListFormatting",
		"BoxFormatting","ParagraphFormatting","CssText","Styles",
		"CustomTag","Paragraph","FontName","FontSize",
		"Bold","Italic","Underline","Strikethrough",
		"ForeColor","BackColor"] ;
}

function decodeURI2 (value)
{
	return decodeURIComponent(value.replace(/\+/g," ")) ;
}
