// 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
  }
}

node = document.getElementById

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)
{
  n = node(node_id)
  //alert(n.id)
  //alert(n.parentNode.id)
  siblings = n.parentNode.getChildren
  for(i = 0; i < siblings.length; i++)
  {
    if(n != siblings[i])
    {
      siblings[i].style.display = 'none'
    }
  }
}


function moneyFormat(n) {
  return dollarFormat(Math.floor(n-0) + '') + centFormat(n - 0);
}

function formatMoney(n){return moneyFormat(n)}

function dollarFormat(n) {
    if (n.length <= 3)
        return (n == '' ? '0' : n);
    else {
        var mod = n.length%3;
        var output = (mod == 0 ? '' : (n.substring(0,mod)));
        for (i=0 ; i < Math.floor(n.length/3) ; i++) {
            if ((mod ==0) && (i ==0))
                output+= n.substring(mod+3*i,mod+3*i+3);
            else
                output+= ',' + n.substring(mod+3*i,mod+3*i+3);
        }
        return (output);
    }
}

function centFormat(n) {
    n = Math.round( ( (n) - Math.floor(n) ) *100);
    return (n < 10 ? '.0' + n : '.' + n);
}

//////////////////////////////
// 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'
  }
}

function toggleNodesOnCheck(f,elements)
{
  display = f.checked ? '' : 'none'
  for(i = 0; i < elements.length; i++)
  {
    document.getElementById(elements[i]).style.display = display
  } 
}

// 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,name)
{
  if(name == undefined){name = 'win'}
  win = open(url,name,'height='+h+',width='+w+',toolbar=0,location=0,directories=0,status=1,menubar=0,scrollbars=1,resizable=1')
  win.focus()
  return win
}


// 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)
{
  n = node(node_id)
  if (n.parentNode)
  {
    n.parentNode.removeChild(n);
  }
}

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

//////////////////////////////////
// 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)
      {
        try{
          removeNode(response.table + '_' + response.oid + '_' + response.field + '_' + response.file.replace(/\W/g,'_'))
        }catch(e){
          n = YAHOO.util.Dom.get(response.table + '_' + response.oid + '_' + response.field + '_' + response.file.replace(/\W/g,'_'));
          n.parentNode.removeChild(n);
        }
      }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);
    }
  }
}

function setTimestamp(node_id)
{
  ts = document.getElementById(node_id) 
  ts.value = document.getElementById(node_id + '_date').value + ' ' 
  ts.value += document.getElementById(node_id + '_hour').value + ':' 
  ts.value += document.getElementById(node_id + '_minute').value + ' ' 
  ts.value += document.getElementById(node_id + '_zone').value
}

var calendar_dialog;

function showCalendar(field_id)
{
  calendar_dialog = new YAHOO.widget.Calendar("cal", "calContainer");
  calendar_dialog.minDate = YAHOO.widget.DateMath.add(new Date(), YAHOO.widget.DateMath.DAY, 1);
  calendar_dialog.render();
  calendar_dialog.onSelect = selectDate
}

function selectDate()
{
   
}

/*
    json.js
    2006-10-05

    This file adds these methods to JavaScript:

        object.toJSONString()

            This method produces a JSON text from an object. The
            object must not contain any cyclical references.

        array.toJSONString()

            This method produces a JSON text from an array. The
            array must not contain any cyclical references.

        string.parseJSON()

            This method parses a JSON text to produce an object or
            array. It will return false if there is an error.

    It is expected that these methods will formally become part of the
    JavaScript Programming Language in the Fourth Edition of the
    ECMAScript standard.
*/
(function () {
    var m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        s = {
            array: function (x) {
                var a = ['['], b, f, i, l = x.length, v;
                for (i = 0; i < l; i += 1) {
                    v = x[i];
                    f = s[typeof v];
                    if (f) {
                        v = f(v);
                        if (typeof v == 'string') {
                            if (b) {
                                a[a.length] = ',';
                            }
                            a[a.length] = v;
                            b = true;
                        }
                    }
                }
                a[a.length] = ']';
                return a.join('');
            },
            'boolean': function (x) {
                return String(x);
            },
            'null': function (x) {
                return "null";
            },
            number: function (x) {
                return isFinite(x) ? String(x) : 'null';
            },
            object: function (x) {
                if (x) {
                    if (x instanceof Array) {
                        return s.array(x);
                    }
                    var a = ['{'], b, f, i, v;
                    for (i in x) {
                        v = x[i];
                        f = s[typeof v];
                        if (f) {
                            v = f(v);
                            if (typeof v == 'string') {
                                if (b) {
                                    a[a.length] = ',';
                                }
                                a.push(s.string(i), ':', v);
                                b = true;
                            }
                        }
                    }
                    a[a.length] = '}';
                    return a.join('');
                }
                return 'null';
            },
            string: function (x) {
                if (/["\\\x00-\x1f]/.test(x)) {
                    x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                        var c = m[b];
                        if (c) {
                            return c;
                        }
                        c = b.charCodeAt();
                        return '\\u00' +
                            Math.floor(c / 16).toString(16) +
                            (c % 16).toString(16);
                    });
                }
                return '"' + x + '"';
            }
        };

    Object.prototype.toJSONString = function () {
        return s.object(this);
    };

    Array.prototype.toJSONString = function () {
        return s.array(this);
    };
})();

String.prototype.parseJSON = function () {
    try {
        return (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(this)) &&
            eval('(' + this + ')');
    } catch (e) {
        return false;
    }
};