// Copyright (c) 2005 ePark Labs, Inc.
// All right reserved

// Compatability functions

// Handle getElementById in old browsers
if(!document.getElementById){
  if(document.all)
  document.getElementById=function(){
    if(typeof document.all[arguments[0]]!="undefined")
      return document.all[arguments[0]]
    else
      return null
  }
  else if(document.layers)
  document.getElementById=function(){
    if(typeof document[arguments[0]]!="undefined")
      return document[arguments[0]]
    else
      return null
  }
}

function node(id)
{
  return document.getElementById(id) 
}

String.prototype.toTitleCase = function () {
   var firstLetter = this.substr(0,1).toUpperCase()
   return this.substr(0,1).toUpperCase() + this.substr(1,this.length);
}

// Event handlers (By Scott Andrew)   
function addEvent(elm,evType,fn,useCapture)
{
  if (elm.addEventListener){
    elm.addEventListener(evType,fn,useCapture);
    return true;
  }else if (elm.attachEvent){
    var r =elm.attachEvent('on'+evType,fn);
    return r;
  }else {
    elm ['on'+evType ] = fn;
  }
}

// Event object unification
function cleanEvent(e)
{
  if(!e.target && window.event.srcElement)
  {
    e.target = window.event.srcElement
  }
  return e
}

function getElementsByClassName(parent_object, tag, class_name)
{
  var elements = (tag == "*" && document.all)? document.all : 
  parent_object.getElementsByTagName(tag);
  var return_elements = new Array();
  class_name = class_name.replace(/\-/g, "\\-");
  var regex = new RegExp("(^|\\s)" + class_name + "(\\s|$)");
  var element;
  for(var i=0; i<elements.length; i++)
  {
    element = elements[i];      
    if(regex.test(element.className))
    {
      return_elements.push(element);
    }   
  }
  return (return_elements)
}

// Container resizer for iframes
function resizeContainer(container_id) 
{
	container = parent.document.getElementById(container_id);
	container.style.height = "0px"; // Fixes a bug in firefox will not reduce the height
	container.style.height = (document.body.scrollHeight + 10) + "px";
}

// Select all from a list
function selectAll(form,field)
{
  for(i = 0; i < form.elements.length; i++)
  {
    if(form.elements[i].type == 'checkbox')
    {
      form.elements[i].checked = field.checked
    }
  }
}

// Set field value from select frame option
function setSelectFrameValue(item,target_id,value)
{
 
  parent.document.getElementById(target_id).value = value
  currently_on = getElementsByClassName(document, 'div', 'selected_item')
  for(i = 0; i < currently_on.length; i++ )
  {
    currently_on[i].className = 'select_item'
  }
  item.className = 'select_item selected_item'
  window.scrollTo(0,item.offsetTop)
}

function hideSiblings(node_id)
{
  node = document.getElementById(node_id)
  //alert(node.id)
  //alert(node.parentNode.id)
  siblings = node.parentNode.getChildren
  for(i = 0; i < siblings.length; i++)
  {
    if(node != siblings[i])
    {
      siblings[i].style.display = 'none'
    }
  }
}

//////////////////////////////
// Suggest functions
//////////////////////////////

//////////////////////////////
// Combobox functions
//////////////////////////////
select_bg_color = 'rgb(204, 204, 204)'

// Set the value of an input text field
function selectOption(option,target)
{
  field = document.getElementById(target)
  field.value = option.innerHTML
  highlightFirstMatchOption(field)
  nextOption(field,0,false)
  option.parentNode.style.display = 'none'
  field.focus()
}

function selectKeyUp(e)
{
  e = cleanEvent(e)
  field = e.target
  switch(e.keyCode)
  {
    case 9: // Tab
    case 13: // Return
    case 38: // Up Arrow
    case 40: // Down arrow
      //alert("Up: " + e.keyCode)
      // Block the form from being submitted (return)
      if (window.event && window.event.returnValue)
      {
        window.event.returnValue = false;
      }
      if (e && e.preventDefault)
      {
        e.preventDefault();
      }
      return false;
    break;
    case 8: // Delete
      document.getElementById(field.id+'_select').style.display = 'block'
      highlightFirstMatchOption(field)
    break;
    default:
      //alert(e.keyCode)
      document.getElementById(field.id+'_select').style.display = 'block'
      highlightFirstMatchOption(field)
    break;
  }
}

function selectKeyDown(e)
{
  e = cleanEvent(e)
  field = e.target
  switch(e.keyCode)
  {
    case 9: // Tab
      document.getElementById(field.id+'_select').style.display = 'none'
      nextOption(field,0,false)
    break;
    case 13: // Return
      //alert("Down: " + e.keyCode)
      document.getElementById(field.id+'_select').style.display = 'none'
      nextOption(field,0,false)
      // Block the form from being submitted (return)
      if (window.event && window.event.returnValue)
      {
        window.event.returnValue = false;
      }
      if (e && e.preventDefault)
      {
        e.preventDefault();
      }
      return false;
    break;
    case 38: // Up Arrow
      nextOption(field,-1,true)
    break;
    case 40: // Down arrow
      nextOption(field,1,true)
    break;
  }
}

function nextOption(field,np,select_first)
{
  option_box = document.getElementById(field.id+'_select')
  for(i = 0; i < option_box.childNodes.length; i++)
  {
    //alert(option_box.childNodes[i].style.backgroundColor)
    if(option_box.childNodes[i].style.backgroundColor.replace(/ /g,"") == select_bg_color.replace(/ /g,""))
    {
      option_box.childNodes[i].style.backgroundColor = 'white'
      option_box.childNodes[Math.max(0,Math.min(option_box.childNodes.length - 1,i + np))].style.backgroundColor = select_bg_color
      field.value = option_box.childNodes[Math.max(0,Math.min(option_box.childNodes.length - 1,i + np))].innerHTML
      return true
    }
  }
  if(select_first)
  {
    option_box.childNodes[0].style.backgroundColor = select_bg_color
    field.value = option_box.childNodes[0].innerHTML
  }
}

function highlightFirstMatchOption(field)
{
  // Highlight the closest match
  option_box = document.getElementById(field.id+'_select')
  is_one_selected = false
  for(i = 0; i < option_box.childNodes.length; i++)
  {
    //alert(option_box.childNodes[i].style.backgroundColor)
    if(option_box.childNodes[i].innerHTML.substr(0,field.value.length).toLowerCase() == field.value.toLowerCase())
    {
      if(!is_one_selected)
      {
        option_box.childNodes[i].style.backgroundColor = select_bg_color
        is_one_selected = true
      }else{
        option_box.childNodes[i].style.backgroundColor = 'white'
      }
      //option_box.childNodes[i].style.display = 'block' 
    }else{
      option_box.childNodes[i].style.backgroundColor = 'white'
      //option_box.childNodes[i].style.display = 'none' 
    }
  }
}

function toggleSelectOptions(e)
{
  e = cleanEvent(e)
  field = e.target
  options = document.getElementById(field.id+'_select')
  if(options)
  {
    options.style.display = options.style.display == 'block' ? 'none' : 'block'
  }
}

// Set the phone3 field value from the parts
function setPhone3(field)
{
  cc = document.getElementById(field+'_cc').value
  ac = document.getElementById(field+'_ac').value
  num = document.getElementById(field+'_num').value
  document.getElementById(field).value = '+'+cc+' ('+ac+') '+num
}

// Set the phone4 field value from the parts
function setPhone4(field)
{
  cc = document.getElementById(field+'_cc').value
  ac = document.getElementById(field+'_ac').value
  num = document.getElementById(field+'_num').value
  ex = document.getElementById(field+'_ex').value
  document.getElementById(field).value = '+'+cc+' ('+ac+') '+num+(ex.length > 0 ? ' x'+ex : '')
}

// Popup
function popup(url,h,w)
{
  win = open(url,'win','height='+h+',width='+w+',toolbar=0,location=0,directories=0,status=1,menubar=0,scrollbars=1,resizable=1')
  win.focus()
}

// Toggle displaying an element
function toggleRows(element)
{
  x = document.getElementById(element)
  if(x)
  {
    x.style.display = x.style.display == 'none' ? '' : 'none'
  }
}


var is_checked = true;
function traverseAndCheck(tree) 
{
    if(tree.hasChildNodes()) 
    {
        var nodes=tree.childNodes.length;
        for(var i = 0; i < nodes; i++)
        {
            traverseAndCheck(tree.childNodes[i]);
        }
    }else{
        if(tree.nodeName == "INPUT")
        {
            tree.checked = is_checked;
        }
    }
}

// Toggle the checkboxes within a container
function toggleContainerCheckboxes(field,section)
{
    is_checked = field.checked;
    tree = document.getElementById(section);
    traverseAndCheck(tree);    
}

// Set a field value and focus on it
function setField(id,val)
{
    document.getElementById(id).focus();
    document.getElementById(id).value = val;
}

function selectOther(f)
{
  if(f.options[f.selectedIndex].value == 'Other...')
  {
    other = prompt("Enter another value:","")
    if(other != null)
    {
      f.options[0].value = other
      f.options[0].text = other
      f.options[0].selected = true
    }else{
      f.options[0].selected = true 
    }
  }
}

// Prompt the user for their email address then forward them on to get their password
function passwordPrompt()
{
  name = prompt('Please enter your user name or email address. A new password will be emailed to you.','')
  if(name == null){ return }
  if(name.length > 0)
  {
    location = APP_URI + '/admin/request_password?name=' + escape(name) 
  }
}

function toggleElementDisplay(id)
{
  x = document.getElementById(id)
  if(x)
  {
    x.style.display = x.style.display == 'none' ? '' : 'none'
  }
}

function toggleBlock(id)
{
  x = document.getElementById(id)
  if(x)
  {
    x.style.display = x.style.display == 'block' ? 'none' : 'block'
  }
}

var req;
var res;

function request(url,responseHandler)
{
  if (window.XMLHttpRequest) {
      req = new XMLHttpRequest();
  }else if (window.ActiveXObject) {
      req = new ActiveXObject("Microsoft.XMLHTTP");
  }else{
  	alert('Sorry. Your browser does not support this function.')
  	return false
  }
  req.onreadystatechange = responseHandler; //processRequest;
  req.open("GET", url, true);
  req.send("");
}

function ajaxRequest(v,u,h)
{
  if (window.XMLHttpRequest) {
      v = new XMLHttpRequest();
  }else if (window.ActiveXObject) {
      v = new ActiveXObject("Microsoft.XMLHTTP");
  }else{
  	alert('Sorry. Your browser does not support this function.')
  	return false
  }
  v.onreadystatechange = h; //processRequest;
  v.open("GET", u, true);
  v.send("");
}

function processRequest() {
  if (req.readyState == 4) {
    if (req.status == 200) {
    	alert("pr" + req.getAllResponseHeaders())
      parseMessages();
    } else {
      alert("There was a problem retrieving the data:\n" + req.statusText);
    }
  }
}

function showResponse()
{
	if (req.readyState == 4) 
	{
    if (req.status == 200) 
    {
      alert("Response:\n" + req.responseText);
    }else{
      alert("Application Error:\n" + req.statusText);
    }
  }
}

function showResponseError()
{
	if (req.readyState == 4) 
	{
    if (req.status != 200) 
    {
      alert("Application Error:\n" + req.statusText);
    }
  }
}

function parseMessages() {
  //res = req.responseXML
	//response  = res.documentElement;
  //itemDescription = response.getElementsByTagName('description')[0].firstChild.data;
	//alert ( itemDescription );
}

function setAct(act)
{
  document.getElementById('act').value = act; 
}

//////////////////////////////////
// DHTML
//////////////////////////////////
      
function appendNode(parent_id,node_id)
{
  document.getElementById(parent_id).appendChild(document.getElementById(node_id))
}

function prependNode(parent_id,bottom_node_id,node_id)
{
  document.getElementById(parent_id).insertBefore(document.getElementById(node_id),document.getElementById(bottom_node_id))
}

function removeNode(node_id)
{
  node = document.getElementById(node_id)
  if (node.parentNode)
  {
    node.parentNode.removeChild(node);
  }
}

function createNode(type,value,attributes)
{
  node = document.createElement(type);
  text = document.createTextNode(value);
  node.appendChild(text);
  // Add the attributes
  for(i = 0; i < attributes.length; i++)
  {
    eval("node."+attributes[i][0]+" = '"+attributes[i][1]+"';")
  }
  return node
}

//////////////////////////////////
// Tree
//////////////////////////////////

function toggleTree()
{
  if(document.getElementById('nav_tree_container').style.display == 'none')
  {
    document.getElementById('nav_tree_container').style.display = ''
    document.getElementById('tree_slider').style.display = ''
    //Effect.BlindDown('nav_tree_container')
    document.getElementById('apppage').style.left = parseInt(document.getElementById('nav_tree_container').style.width) + 4
    //document.getElementById('tree_toggle').innerHTML = '-'
    request(APP_URI + '/app_session/set_tree_options?show_tree=1',showResponseError)
  }else{
    document.getElementById('nav_tree_container').style.display = 'none'
    document.getElementById('tree_slider').style.display = 'none'
    //Effect.BlindUp('nav_tree_container')
    document.getElementById('apppage').style.left = '4px'
    //document.getElementById('tree_toggle').innerHTML = '+'
    request(APP_URI + '/app_session/set_tree_options?show_tree=0',showResponseError)
  }
}
function resizeTree(slider)
{
  tree = document.getElementById('nav_tree_container')
  width = parseInt(slider.style.left)
  tree.style.width = width 
  document.getElementById('apppage').style.left = width + 4
  request(APP_URI + '/app_session/set_tree_options?tree_width=' + width,showResponseError)
}
function handleTreeSlider()
{
  alert('tree slider')
}

////////////////////////////////
// File management
////////////////////////////////

function deleteFileFromFolder(table,id,field,file)
{
  if(confirm("Are you sure you want to delete this file?"))
  {
    request(APP_URI + '/' + table + '/delete_file_from_folder/' + id + '?table=' + table + ';field=' + field + ';file=' + escape(file), deleteFileFromFolderHandler)
  }
}

function deleteFileFromFolderHandler()
{
  
	if (req.readyState == 4) 
	{
    if (req.status == 200) 
    {
      try{
        eval(req.responseText)
      }catch(e){
        alert("A programming error has occured. Please contact customer service.") 
        return false
      }
      if(response.code == 0)
      {
        removeNode(response.table + '_' + response.oid + '_' + response.field + '_' + response.file.replace(/\W/g,'_'))
      }else{
        alert("Sorry. The file could not be deleted: " + response.message) 
      }
    }else{
      alert("Application Error:\n" + req.statusText);
    }
  }
}

function selectFolderThumbnail(table,id,field,file)
{
  //if(confirm("Are you sure you want to set this file as the thumbnail?"))
  //{
    request(APP_URI + '/' + table + '/select_folder_thumbnail/' + id + '?table=' + table + ';field=' + field + ';file=' + escape(file), selectFolderThumbnailHandler)
  //}
}

function selectFolderThumbnailHandler()
{
  
	if (req.readyState == 4) 
	{
    if (req.status == 200) 
    {
      try{
        eval(req.responseText)
      }catch(e){
        alert("A programming error has occured. Please contact customer service.") 
        return false
      }
      if(response.code == 0)
      {
        document.location.reload()
      }else{
        alert("Sorry. The file could not be created: " + response.message) 
      }
    }else{
      alert("Application Error:\n" + req.statusText);
    }
  }
}