// browser version checks
// |--------------------------------|
// | isIE4 | isW3C | isIE4 && isW3C |
// |--------------------------------|
// | false | false | older browser  |
// | true  | false | IE4 only       |
// | true  | true  | IE5+           |
// | false | true  | NN6+           |
// |--------------------------------|
var txtBrowser = navigator.userAgent
var intIEVersion = parseFloat(txtBrowser.substring(txtBrowser.indexOf('MSIE')+5, txtBrowser.indexOf(';', txtBrowser.indexOf('MSIE'))))
var isIE4 = (navigator.appName.indexOf('Microsoft') > -1 && parseInt(intIEVersion) >= 4)
var isW3C = (document.documentElement) ? true : false
var isNN4 = (document.layers) ? true : false
var isOpera = (navigator.userAgent.indexOf('Opera') > -1)

// document.all simulator for NN6
if (isW3C && !isIE4) {
  Node.prototype.__defineGetter__("all", function() {
    if (document.getElementsByTagName("*").length) {
      switch (this.nodeType) {
        case 9: 
		  return document.getElementsByTagName("*")
          break
        case 1:
		  return this.getElementsByTagName("*")
		  break
		}
      }
      return ""
	  }
  )
  Node.prototype.__defineSetter__("all", function() {})
}

// innerText simulator for NN6
if (isW3C && !isIE4 && HTMLElement) {
  HTMLElement.prototype.__defineSetter__("innerText", function (txt) {
    var rng = document.createRange()
    rng.selectNodeContents(this)
    rng.deleteContents()
	var newText = document.createTextNode(txt)
	this.appendChild(newText)
	return txt
    }
  )
  HTMLElement.prototype.__defineGetter__("innerText", function () {
    var rng = document.createRange()
	rng.selectNode(this)
	return rng.toString()
    }
  )
}

// outerHTML simulator for NN6
if (isW3C && !isIE4 && HTMLElement) {
  HTMLElement.prototype.__defineSetter__("outerHTML", function (html) {
    var rng = document.createRange()
    rng.selectNode(this)
    var newHTML = rng.createContextualFragment(html)
    this.parentNode.replaceChild(newHTML,this)
    return html
    }
  )
  HTMLElement.prototype.__defineGetter__("outerHTML", function() {return ''})
}

// fix NN4 bug which destroys layout and eventhandlers after resize
function MM_reloadPage(blnInit) {  
  if (blnInit) {
    if (isNN4) {
      document.MM_pgW = innerWidth
	    document.MM_pgH = innerHeight
	    onresize = MM_reloadPage
	  }
  } else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) {
    location.reload()
  }
}
MM_reloadPage(true)

// avoid submit by disabling Enter key; usage: <BODY onKeyPress='return disableEnter(event)'>
function disableEnter(nsEvent) { 
  return ((isIE4) ? event.keyCode : nsEvent.which) != 13
}

// disable backspace; usage: <BODY onKeyDown='return disableBackspace(event)'>
function disableBackspace(nsEvent) { 
  return ((isIE4) ? event.keyCode : nsEvent.which) != 8
}

if (isIE4 || isW3C) {
  document.onmouseup=disableRightClick
  document.oncontextmenu=disableRightClick
} else {
  document.captureEvents(Event.MOUSEDOWN)
  document.onmousedown=disableRightClick
}
function disableRightClick(nsEvent) {
  if (isIE4) {
    return false
  } else {
    if (nsEvent.which == 2 || nsEvent.which == 3) {
      return false
    }
  }
}

// disable ctrl keys (use in combination with enableKeys to avoid copy and paste)
// usage: onKeyDown='return disableCtrl(event)'
function disableCtrl(nsEvent) {
  var ctrlPressed = (window.Event) ? nsEvent.modifiers & Event.CONTROL_MASK : nsEvent.ctrlKey;
  var intKey = (isIE4) ? event.keyCode : nsEvent.which;
  return !ctrlPressed
}

// disable insert key (use in combination with enableKeys to avoid copy and paste)
// usage: onKeyDown='return disableInsert(event)'
function disableInsert(nsEvent) {
  var intKey = (isIE4) ? event.keyCode : nsEvent.which; 
  return !(intKey == 45)
}

// disable copy and paste through shift+insert and ctrl+c
// usage: onKeyDown='return disableCopyAndPaste(event)'
function disableCopyAndPaste(nsEvent) {
  return (disableCtrl(nsEvent) && disableInsert(nsEvent));
}

// disable drag & drop for all textboxes (IE5+ only) (use in combination with enableKeys) 
// usage <BODY onLoad='disableDrag()'>
function disableDrag() {
  if (isIE4 && isW3C) {
    for (var i=0; i<document.all.tags("INPUT").length; i++) {				
      var obj = document.all.tags("INPUT")[i]			
      if (obj.type.toLowerCase() == "text") {
        obj.ondrag = function() { return false; }
      }
    }
  }
}
  
// maximize window to use all available space; usage: <BODY onload='maximizeWindow()'>
function maximizeWindow() {
  self.moveTo(0,0);
  self.resizeTo(screen.availWidth,screen.availHeight);
}

// count number of words in string
function countWords(str) {
  while (str.indexOf("  ") != -1) {
  	str = str.replace("  ", " ");
  } 
  if (str.length > 0) {
    var words = str.split(" ") 
    var count = words.length;
    count = (words[0]=="") ? count - 1 : count;
    count = (words[words.length-1]=="") ? count - 1 : count;
    return count
  } else {
    return 0
  }
}

function switchTab(tabName) {
	document.forms[0].selectedTab.value = tabName;
	document.forms[0].submit();
}

// add email validation method to String object; usage: document.formName.inputName.value.isEmail()
// email should not have:
// - two @ signs separated by 0 or more characters
// - two sequential periods not separated by any characters
// - @ sign directly followed by period
// - leading period
// email should have:
// - begin with one or more characters before @
// - one optional [ directly after @
// - one or more alphanumerics, numbers, dashes or periods (domain name doesn't allow underscore)
// - decimal followed by 2-3 alphanumerics or 1-3 numbers
// - one optional ] at the end
String.prototype.isEmail = function isEmail() {
  return (!/(@.*@)|(\.\.)|(@\.)|(^\.)/.test(this) && /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/.test(this))
}

// add trim method to String object; usage: document.formName.inputName.value.trim('left', 'trimtext')
// strTrimType is 'left' or 'right'; default (no parameters) is full trim of spaces
// character support check only available in IE4+ due to buggy ns4 (returns false every 2nd time in ns4)
String.prototype.trim = function trim(strTrimType, strChar) {
  strTrimType = (typeof strTrimType != 'string') ? 'full' : strTrimType
  strChar = (typeof strChar != 'string') ? ' ' : strChar
  if ((isIE4) && (!/^([ \^\$\*\+\?\.\|\[\]\\\(\)a-zA-z0-9,-~!@#_{}&%:;<=>])*$/g.test(strChar))) {return this} //check supported characters
  strChar = strChar.replace(/([\^\$\*\+\?\.\|\[\]\\\(\)])/g, '\\$1')
  return this.replace(new RegExp((/^left$/i.test(strTrimType) ? '^' : '')+'('+strChar+')+'+(/^right$/i.test(strTrimType) ? '$' : ''), 'g'), '')
}

function isEmail(obj) {
	if (obj.value.isEmail()) {
		return true;
	} else {
		alert("Invalid email");
		obj.select();	
		return false;
	}
}

function isEmpty(obj, title) {
	if (obj.value.replace(" ", "") == "") {
		alert("Please provide "+title);
		obj.select();
		return true;
	} else {
		return false;
	}
}

function hasMinimumLength(obj, title, length) {
	if (obj.value.trim().length < length) {
		alert(title+" should be at least "+length+" characters");
		obj.select();
		return false;
	} else {
		return true;
	}
}

function isSelected(obj, title) {
	if (obj.selectedIndex == 0) {
		alert("Please select "+title);
		obj.focus();
		return false;
	} else {
		return true;
	}
}

function submitPage(tabName, action) {
	document.forms[0][tabName+':action'].value = action;
	switch (action) {
		case "login":
			if (!isEmail(document.forms[0][tabName+":username"])) {return};
			if (isEmpty(document.forms[0][tabName+":password"], "password")) {return};
			break;
		case "email":
			if (!isEmail(document.forms[0][tabName+":email"])) {return};
			break;
		default: //update or register
			if (isEmpty(document.forms[0][tabName+":name"], "name")) {return};
			if (!isEmail(document.forms[0][tabName+":email"])) {return};
			if (isEmpty(document.forms[0][tabName+":password"], "password") || !hasMinimumLength(document.forms[0][tabName+":password"], "Password", 8)) {return};
			if (isEmpty(document.forms[0][tabName+":companyName"], "company name")) {return};
			if (isEmpty(document.forms[0][tabName+":city"], "city")) {return};
			if (!isSelected(document.forms[0][tabName+":country"], "country")) {return};
			break;
	}
	document.forms[0].submit();
}