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

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

// Get a timestamp to break the cache
function decacher(){
  return Math.round(new Date().getTime()/1000.0)
}

// Get the parts of a field
function getFieldParts(id){
  parts = id.split(/(\w*)_([0-9]*)_(\w*)/)
  return {table: parts[1], id: parts[2], name: parts[3]}
}

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

// Container resizer for iframes
function resizeContainer(container_id) 
{
	container = parent.document.getElementById(container_id);
	container.style.height = "10px"; // Fixes a bug in firefox will not reduce the height
	container.style.height = (parseInt(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)
  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) {
    return numberFormat(n);
}

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

function numberFormat(n){
  n = String(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;
  }
}

//////////////////////////////
// Cookie Manager
//////////////////////////////
function createCookie(name,value,days) {
    //console.log("createCookie("+name+", "+value+", " + days +")")
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	//console.log("readCookie("+name+") " + document.cookie)
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		//console.log(c)
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0){
			var re = c.substring(nameEQ.length,c.length);
			//console.log("readCookie return: " + re);
			return re;
		}
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

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

// Toggle the checkboxes within a container
function toggleContainerCheckboxes(field,container)
{
    $('#' + container + ' :checkbox').attr('checked',field.checked)
}

// 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=' + encodeURIComponent(name) 
  }
}

function toggleElementDisplay(id){$('#' + id).toggle();}

function toggleBlock(id){$('#' + id).toggle();}

function request(url,responseHandler){$.get(url,null,responseHandler);}

function showResponse(response){alert("Response:\n" + response);}

function showResponseError(response){alert("Application Error:\n" + response.statusText);}

function setAct(act){$('#act').value(act); }

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

function toggleTree()
{
  if(document.getElementById('nav_tree_container').style.display == 'none')
  {
    left = parseInt(document.getElementById('tree_slider').style.left) - 10;
    if(isNaN(left)){left = 190;}
    $('#apppage').animate({left: left},'normal');
    $('#nav_tree_container').show('normal');
    $('#tree_slider').show('normal');
    $.get(APP_URI + '/app_session/set_tree_options?show_tree=1');
  }else{
    $('#tree_slider').hide('normal');
    $('#nav_tree_container').hide('normal');
    $('#apppage').animate({left: 4},'normal');
    $.get(APP_URI + '/app_session/set_tree_options?show_tree=0');
  }
}
function resizeTree(slider)
{
  tree = document.getElementById('nav_tree_container')
  width = parseInt(slider.style.left)
  tree.style.width = width - 10
  document.getElementById('apppage').style.left = width + 4
  $.get(APP_URI + '/app_session/set_tree_options?tree_width=' + width)
}
function handleTreeSlider()
{
  alert('tree slider')
}

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

function deleteFileFromFolder(table,id,field,file)
{
  if(confirm("Are you sure you want to delete this file?"))
  {
    $.getJSON(APP_URI + '/' + table + '/delete_file_from_folder/' + id + '.json?table=' + table + ';field=' + field + ';file=' + encodeURIComponent(file), null, function(response){
  		//console.log(response)
  		$('#' + response.table + '_' + response.oid + '_' + response.field + '_' + response.file.replace(/\W/g,'_')).css('display','none')
    });
	}
}

function selectFolderThumbnail(table,id,field,file)
{
  request(APP_URI + '/' + table + '/select_folder_thumbnail/' + id + '?table=' + table + ';field=' + field + ';file=' + encodeURIComponent(file), selectFolderThumbnailHandler)
}

function selectFolderThumbnailHandler(response)
{
	try{
    eval(response)
  }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) 
  }
}

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
}

// toJSON
(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 + '"';
            }
        };

	$.toJSON = function(v) {
		var f = isNaN(v) ? s[typeof v] : s['number'];
		if (f) return f(v);
	};
	
	$.parseJSON = function(v, safe) {
		if (safe === undefined) safe = $.parseJSON.safe;
		if (safe && !/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(v))
			return undefined;
		return eval('('+v+')');
	};
	
	$.parseJSON.safe = false;

})(jQuery);

// jQuery.fastSerialize 
$.fn.fastSerialize = function() {
  var a = [];
  $('input,textarea,select,button', this).each(function() {
    var n = this.name;
    var t = this.type;
    if ( !n || this.disabled || t == 'reset' ||
      (t == 'checkbox' || t == 'radio') && !this.checked ||
      (t == 'submit' || t == 'image' || t == 'button') && this.form.clicked != this ||
      this.tagName.toLowerCase() == 'select' && this.selectedIndex == -1)
      return;
    if (t == 'image' && this.form.clicked_x)
      return a.push(
        {name: n+'_x', value: this.form.clicked_x},
        {name: n+'_y', value: this.form.clicked_y}
      );
    if (t == 'select-multiple') {
      $('option:selected', this).each( function() {
        a.push({name: n, value: this.value});
      });
      return;
    }
    a.push({name: n, value: this.value});
  });
  return a;
};

$.clientCoords = function() {
   var dimensions = {width: 0, height: 0};
   if (document.documentElement) {
     dimensions.width = document.documentElement.offsetWidth;
     dimensions.height = document.documentElement.offsetHeight;
   } else if (window.innerWidth && window.innerHeight) {
     dimensions.width = window.innerWidth;
     dimensions.height = window.innerHeight;
   }
   return dimensions;
}