/*
                Inroads General User Interface JavaScript Functions

                        Written 2007-2010 by Randall Severy
                         Copyright 2007-2010 Inroads, LLC
*/

function button_mouseover(row)
{
   row.className = "button_over";
}

function button_mouseout(row)
{
   row.className = "button_out";
}

function log_server(msg)
{
   var fields = "cmd=logserver&Msg=" + encodeURIComponent(msg.replace(/\r/g,'').replace(/\n/g,' '));
   var request = new XMLHttpRequest();
   request.open('POST',"../engine/utility.php",true);
   request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
   request.setRequestHeader('Content-length',fields.length);
   request.setRequestHeader('Connection','close');
   request.send(fields);
}

function process_error(msg,url,linenumber)
{
   if (typeof(url) == "undefined") var error_msg = msg;
   else var error_msg = 'JavaScript Error: ' + url + ', line ' +
                        linenumber+':\n' + msg;
   log_server(error_msg);
   return true;
}

function Ajax(script_name,fields,async_flag)
{
   this.request = new XMLHttpRequest();
   this.script_name = script_name;
   this.fields = fields;
   this.async_flag = async_flag;
   this.error_msg = '';
   this.show_alert = false;
   this.show_log_details = false;
   this.show_error_status = false;
   this.parse_response = false;
   this.callback_function = null;
   this.ajax_data = null;
   this.timeout_seconds = 0;
   this.aborted = false;
   this.timeout = false;
}

Ajax.prototype.enable_alert = function()
{
   this.show_alert = true;
}

Ajax.prototype.enable_log_details = function()
{
   this.show_log_details = true;
}

Ajax.prototype.enable_parse_response = function()
{
   this.parse_response = true;
}

Ajax.prototype.set_callback_function = function(callback_function,ajax_data)
{
   this.callback_function = callback_function;
   this.ajax_data = ajax_data;
}

Ajax.prototype.set_timeout = function(timeout_seconds)
{
   this.timeout_seconds = timeout_seconds;
}

Ajax.prototype.process_error = function(error_text)
{
   var error_msg = '';   var log_msg = '';
   var show_error_status = this.show_error_status;
   if (this.show_log_details) {
      log_msg += 'Script: ' + this.script_name + '\n';
      log_msg += 'Content-Length: ' + this.fields.length + '\n';
      log_msg += 'Fields: ' + this.fields + '\n';
      log_msg += 'Status: ' + this.status + '\n';
      log_msg += 'Error: ';
   }
   if (! error_text) {
      if (this.request && this.request.responseText)
         error_text = this.request.responseText;
      else if (this.timeout) error_text = "Request Timed Out";
      else {
         error_text = "Internal Ajax Error";   show_error_status = true;
      }
   }
   if (error_text.length > 255)
      error_msg += 'Error: ' + error_text.substring(0,255) + '...';
   else error_msg += 'Error: ' + error_text;
   log_msg += error_text;
   if (show_error_status) {
      error_msg += ' (' + this.status + ')';
      if (! this.show_log_details) log_msg += ' (' + this.status + ')';
   }
   alert(error_msg);   log_server(log_msg);
}

Ajax.prototype.parse_value = function(response,field_name)
{
   start_pos = response.indexOf("<" + field_name + ">");
   if (start_pos != -1) start_pos += field_name.length + 2;
   end_pos = response.indexOf("</" + field_name + ">");
   if ((start_pos == -1) || (end_pos == -1)) return null;
   var field_value = response.substring(start_pos,end_pos);
   return field_value;
}

Ajax.prototype.display_error = function()
{
   if ((this.status >= 200) && (this.status < 300)) {
      var parsed_error = this.parse_value(this.request.responseText,'message');
      if (parsed_error) var error_msg = parsed_error;
      else var error_msg = this.request.responseText;
      this.process_error(error_msg);
   }
}

Ajax.prototype.send = function()
{
   this.request.open('POST',this.script_name,this.async_flag);
   this.request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
   this.request.setRequestHeader('Content-length',this.fields.length);
   this.request.setRequestHeader('Connection','close');
   if (this.callback_function || (this.timeout_seconds != 0)) {
      var ajax_request = this;
      this.request.onreadystatechange = function() {
         if (ajax_request.aborted) return;
         if ((ajax_request.timeout_seconds != 0) &&
             (ajax_request.request.readyState == 4))
            window.clearTimeout(ajax_request.timeout_id);
         if (ajax_request.callback_function) {
            ajax_request.state = ajax_request.request.readyState;
            ajax_request.callback_function(ajax_request,ajax_request.ajax_data);
         }
      }
   }
   this.request.send(this.fields);
   if (this.timeout_seconds != 0) {
      var ajax_request = this;
      this.timeout_id = window.setTimeout(function() {
         if (ajax_request.request.readyState != 4) {
            ajax_request.timeout = true;   ajax_request.request.abort();
         }
      },(this.timeout_seconds * 1000));
   }
   if (! this.async_flag) {
// alert('status = '+this.request.status+', response = '+this.request.responseText);
      this.status = this.request.status;
      if ((this.status < 200) || (this.status > 299)) {
         if (this.show_alert) this.process_error(this.request.responseText);
         this.error = this.request.responseText;
      }
      else if (this.parse_response) {
         parsed_status = this.parse_value(this.request.responseText,'status');
         if (parsed_status) this.status = parsed_status;
         if ((this.status < 200) || (this.status > 299)) {
            var parsed_error = this.parse_value(this.request.responseText,'message');
            if (parsed_error) this.error = parsed_error;
            else this.error = this.request.responseText;
            if (this.show_alert) this.process_error(this.error);
         }
      }
      return this.status;
   }
   return 0;
}

Ajax.prototype.abort = function()
{
   this.aborted = true;
   this.request.abort();
   if (this.timeout_seconds != 0) window.clearTimeout(this.timeout_id);
}

Ajax.prototype.get_status = function()
{
   if (this.aborted) return 0;
   this.status = this.request.status;
   if ((this.status < 200) || (this.status > 299)) {
      if (this.show_alert) this.process_error(this.request.responseText);
      this.error = this.request.responseText;
   }
   else if (this.parse_response) {
      parsed_status = this.parse_value(this.request.responseText,'status');
      if (parsed_status) this.status = parsed_status;
      if ((this.status < 200) || (this.status > 299)) {
         var parsed_error = this.parse_value(this.request.responseText,'message');
         if (parsed_error) this.error = parsed_error;
         else this.error = this.request.responseText;
         if (this.show_alert) this.process_error(this.error);
      }
   }
   return this.status;
}

function build_form_data(form)
{
   var fields = "";
   for (i=0;  i < form.elements.length;  i++) {
      if (form.elements[i].name == "") continue;
      if (form.elements[i].tagName == "INPUT") {
         if (form.elements[i].type == "text") {
            fields += encodeURIComponent(form.elements[i].name) + "=" +
               encodeURIComponent(form.elements[i].value) + "&";
         }
         else if (form.elements[i].type == "hidden") {
            fields += encodeURIComponent(form.elements[i].name) + "=" +
               encodeURIComponent(form.elements[i].value) + "&";
         }
         else if (form.elements[i].type == "password") {
            fields += encodeURIComponent(form.elements[i].name) + "=" +
               encodeURIComponent(form.elements[i].value) + "&";
         }
         else if (form.elements[i].type == "checkbox") {
            if (form.elements[i].checked) {
               fields += encodeURIComponent(form.elements[i].name) + "=" +
                  encodeURIComponent(form.elements[i].value) + "&";
            } else {
               fields += encodeURIComponent(form.elements[i].name) + "=&";
            }
         }
         else if (form.elements[i].type == "radio") {
            if (form.elements[i].checked) {
               fields += encodeURIComponent(form.elements[i].name) + "=" +
                  encodeURIComponent(form.elements[i].value) + "&";
            }
         }
      }
      else if (form.elements[i].tagName == "SELECT") {
         var select = form.elements[i];
         if (select.selectedIndex == -1)
            fields += encodeURIComponent(select.name) + "=&";
         else for (var loop = 0;  loop < select.options.length;  loop++)
            if (select.options[loop].selected)
               fields += encodeURIComponent(select.name) + "=" +
                  encodeURIComponent(select.options[loop].value) + "&";
      }
      else if (form.elements[i].tagName == "TEXTAREA")
         fields += encodeURIComponent(form.elements[i].name) + "=" +
            encodeURIComponent(form.elements[i].value) + "&";
   }
   return fields;
}

var current_ajax_request;

function complete_ajax_call(ajax_request,complete_function)
{
   if (ajax_request.state != 4) return;
   complete_function(ajax_request);
   current_ajax_request = null;
}

function abort_current_request()
{
   if (current_ajax_request) current_ajax_request.abort();
}

function submit_form_data(script_name,prefix,form,complete_function,
                          timeout_seconds)
{
   if (typeof(complete_function) != "undefined") var async_flag = true;
   else var async_flag = false;
   var fields = prefix + "&" + build_form_data(form);
   var ajax_request = new Ajax(script_name,fields,async_flag);
   ajax_request.enable_alert();
   ajax_request.enable_parse_response();
//   ajax_request.enable_log_details();
   if (async_flag) {
      ajax_request.set_callback_function(complete_ajax_call,complete_function);
      if (typeof(timeout_seconds) != "undefined")
         ajax_request.set_timeout(timeout_seconds);
      else ajax_request.set_timeout(30);
   }
   current_ajax_request = ajax_request;
   return ajax_request.send();
}

function call_ajax(script_name,fields,show_alert,complete_function,
                   timeout_seconds)
{
   if (typeof(complete_function) != "undefined") var async_flag = true;
   else var async_flag = false;
   var ajax_request = new Ajax(script_name,fields,async_flag);
   if (show_alert) {
      ajax_request.enable_alert();
      ajax_request.enable_parse_response();
//      ajax_request.enable_log_details();
   }
   if (async_flag) {
      ajax_request.set_callback_function(complete_ajax_call,complete_function);
      if (typeof(timeout_seconds) != "undefined")
         ajax_request.set_timeout(timeout_seconds);
      else ajax_request.set_timeout(30);
   }
   current_ajax_request = ajax_request;
   return ajax_request.send();
}

function validate_form_field(form_field,label,tab_function)
{
   if (form_field.value == '') {
      if (typeof(tab_function) != "undefined") eval(tab_function);
      alert('You must enter a ' + label);
      form_field.focus();
      return false;
   }
   return true;
}

function format_amount(num,currency)
{
   if (typeof(num) == "undefined") return 0;
   num = num.toString().replace(/\$|\,/g,'');
   if (num == '') return '';
   if (isNaN(num)) num = "0";
   var sign = (num == (num = Math.abs(num)));
   num = Math.floor(num*100+0.50000000001);
   var cents = num%100;
   num = Math.floor(num/100).toString();
   if (cents < 10) cents = "0" + cents;
   for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
      num = num.substring(0,num.length-(4*i+3))+','+
            num.substring(num.length-(4*i+3));
   var curr_prefix = '';   var curr_suffix = '';
   if (typeof(currency) != "undefined") {
      if (currency == 'EUR') {
         curr_prefix = '€';   curr_suffix = ' EUR';
      }
      else if (currency == 'CAD') curr_prefix = 'Can$';
      else curr_prefix = '$';
   }
   return (((sign)?'':'-') + curr_prefix + num + '.' + cents + curr_suffix);
}

function parse_amount(num)
{
   if (typeof(num) == "undefined") return 0;
   num = num.toString().replace(/\$|\,|Can/g,'');
   if (isNaN(num)) return 0;
   var float_num = parseFloat(num);
   if (isNaN(float_num)) return 0;
   return float_num;
}

function parse_int(num)
{
   if (typeof(num) == "undefined") return 0;
   if (isNaN(num)) return 0;
   var int_num = parseInt(num,10);
   if (isNaN(int_num)) return 0;
   return int_num;
}

function get_selected_radio_button(field_name)
{
   var radio_buttons = document.getElementsByName(field_name);
   var selected_value = '';
   for (var loop = 0;  loop < radio_buttons.length;  loop++) {
      if (radio_buttons[loop].checked) selected_value = radio_buttons[loop].value;
   }
   return selected_value;
}

function get_selected_list_value(field_name)
{
   var list_field = document.forms[0][field_name];
   if (list_field.selectedIndex == -1) return null;
   return list_field.options[list_field.selectedIndex].value;
}

function iso8601_date(date_obj)
{
   var month = date_obj.getMonth() + 1;
   if (month < 10) month = "0" + month;
   var day = date_obj.getDate();
   if (day < 10) day = "0" + day;
   var date_string = date_obj.getFullYear() + "-" + month + "-" + day +
                     " 12:00";
   return date_string;
}

function validate_number_field(number_field,label)
{
   if (number_field.value == '') return true;
   if (isNaN(number_field.value)) {
      alert(label + ' must be a number');
      number_field.focus();   return false;
   }
   return true;
}

function edit_htmleditor_field(field_name,field_title)
{
   var dialog_name = top.get_current_dialog_name();
   var url = '../engine/htmleditor.php?dialog=' + dialog_name + '&field=' +
             field_name + '&title=' + encodeURIComponent(field_title);
   top.create_dialog('htmleditor',null,null,700,400,false,url,null);
}

var htmleditor_document;
var htmleditor_field_name;
var editor_base_path;

function load_htmleditor(dialog_name,field_name,editor_base_path,
                         editor_admin_path,base_url,doctype)
{
   htmleditor_document = top.get_dialog_document(dialog_name);
   htmleditor_field_name = field_name;
   var field = htmleditor_document.getElementById(field_name);
   var field_value = field.value;
   if (base_url) var base_href = base_url;
   else {
      var base_href = document.location.href;
      var slash_pos = base_href.indexOf('/');
      if (slash_pos) slash_pos = base_href.indexOf('/',slash_pos + 1);
      if (slash_pos) slash_pos = base_href.indexOf('/',slash_pos + 1);
      if (slash_pos) base_href = base_href.substr(0,slash_pos + 1);
      base_href += 'index.html';
   }

   var editor = new FCKeditor('field');
   editor.BasePath = editor_base_path;
   editor.Config['EnableXHTML'] = true;
   editor.Config['EnableSourceXHTML'] = true;
   editor.Config['FillEmptyBlocks'] = false;
   editor.Config['FormatSource'] = true;
   editor.Config['FormatOutput'] = true;
   editor.Config['StartupFocus'] = true;
   editor.Config['CustomConfigurationsPath'] = editor_admin_path + "editor.js";
   editor.Config['BaseHref'] = base_href;
   if (doctype) editor.Config['DocType'] = doctype;
   editor.Config['LinkBrowserURL'] = editor_base_path +
      'editor/filemanager/browser/default/browser.html?Connector=' +
      encodeURIComponent(editor_base_path +
                         'editor/filemanager/connectors/php/connector.php');
   editor.Config['ImageBrowserURL'] = editor_base_path +
      'editor/filemanager/browser/default/browser.html?Type=Image&Connector=' +
      encodeURIComponent(editor_base_path +
                         'editor/filemanager/connectors/php/connector.php');
   editor.Config['FlashBrowserURL'] = editor_base_path +
      'editor/filemanager/browser/default/browser.html?Type=Flash&Connector=' +
      encodeURIComponent(editor_base_path +
                         'editor/filemanager/connectors/php/connector.php');
   editor.ToolbarSet = "Inroads";
   editor.Width = 670;
   editor.Height = 330;
   editor.Value = field_value;
   editor.Create();
}

function set_htmleditor_styles(editor_instance)
{
   var editor_frame = document.getElementById(editor_instance.Name+'___Frame');
   var editor_doc = editor_frame.contentWindow.document;
   var editor_head = editor_doc.getElementsByTagName("head")[0];
   var path_elements = admin_path.split('/');
   path_elements[path_elements.length - 2] = 'admin';
   var url = path_elements.join('/') + 'colors.css';
   var css_node = editor_doc.createElement('link');
   css_node.type = 'text/css';
   css_node.rel = 'stylesheet';
   css_node.href = url;
   css_node.media = 'screen';
   editor_head.appendChild(css_node);
   editor_frame.style.display = '';
}

function FCKeditor_OnComplete(editorInstance)
{
   set_htmleditor_styles(editorInstance);
}

function update_htmleditor_field()
{
   var editor = FCKeditorAPI.GetInstance('field');
   var field_value = editor.GetHTML();
   var field = htmleditor_document.getElementById(htmleditor_field_name);
   field.value = field_value;
   var div = htmleditor_document.getElementById(htmleditor_field_name + "_div");
   div.innerHTML = field_value;
   top.close_current_dialog();
}

function on_enter(evt,funct)
{
   var keyCode = null;
   if (evt.which) keyCode = evt.which;
   else if (evt.keyCode) keyCode = evt.keyCode;
   if (keyCode == 13) {
      funct();   return false;
   }
   return true;
}

function strip_html(text)
{
   start_pos = text.indexOf("<");
   while (start_pos != -1) {
      end_pos = text.indexOf(">");
      if (end_pos == -1) return text;
      text = text.substring(0,start_pos) + text.substring(end_pos + 1);
      start_pos = text.indexOf("<");
   }
   return text;
}

function array_index(arr,value)
{
    var len = arr.length >>> 0;
    var from = Number(arguments[2]) || 0;
    from = (from < 0)?Math.ceil(from):Math.floor(from);
    if (from < 0) from += len;
    for (; from < len; from++) {
      if ((from in arr) && (arr[from] === value)) return from;
    }
    return -1;
}

function select_date(field_name)
{
    var date_popup = eval(field_name + '_popup');
    var date_string_field = document.forms[0][field_name + '_string'];
    var date_value = date_string_field.value;
    if (date_value.length != 8) {
       var date_info = date_value.split("/");
       if (date_info.length == 3) {
          if (date_info[0].length == 1) date_info[0] = '0' + date_info[0];
          if (date_info[1].length == 1) date_info[1] = '0' + date_info[1];
          date_string_field.value = date_info[0] + '/' + date_info[1] +
                                    '/' + date_info[2];
       }
    }
    date_popup.select(date_string_field,field_name + '_icon','MM/dd/yy');
}

function parse_date_field(date_string_field,field_name)
{
    var date_value = date_string_field.value;
    var date_field = document.forms[0][field_name];
    if (date_value == '') {
       date_field.value = '';   return;
    }
    var date_info = date_value.split("/");
    if (date_info.length != 3) {
       date_field.value = '';   return;
    }
    var month = parse_int(date_info[0]) - 1;
    var day = parse_int(date_info[1]);
    var year = parse_int(date_info[2]);
    if (year < 70) year += 2000;
    else year += 1900;
    var date_obj = new Date(year,month,day,12,0,0);
    if (isNaN(date_obj)) {
       date_field.value = '';   return;
    }
    date_field.value = date_obj.getTime() / 1000;
}

function process_selected_date(y,m,d)
{
    if (window.CP_targetInput != null) {
       var dt = new Date(y,m - 1,d,0,0,0);
       if (window.CP_calendarObject != null) {
          window.CP_calendarObject.copyMonthNamesToWindow();
       }
       window.CP_targetInput.value = formatDate(dt,window.CP_dateFormat);
    }
    var field_name = window.CP_targetInput.name;
    field_name = field_name.substring(0,field_name.length - 7);
    parse_date_field(window.CP_targetInput,field_name);
}

function format_date_value(date_value)
{
    if (date_value) var date_obj = new Date(date_value * 1000);
    else var date_obj = new Date();
    var month_value = date_obj.getMonth() + 1;
    if (month_value < 10) month_value = '0' + month_value;
    var day_value = date_obj.getDate();
    if (day_value < 10) day_value = '0' + day_value;
    var date_string = month_value + '/' + day_value + '/' +
                      date_obj.getFullYear();
    return date_string;
}

var month_names = ["January","February","March","April","May","June","July",
                   "August","September","October","November","December"];

function format_date_time_value(date_value)
{
    if (date_value) var date_obj = new Date(date_value * 1000);
    else var date_obj = new Date();
    var minutes = date_obj.getMinutes();
    if (minutes < 10) minutes = "0" + minutes;
    var hours = date_obj.getHours();
    var ampm = "am";
    if (hours == 0) hours = 12;
    if (hours > 11) ampm = "pm";
    if (hours > 12) hours -= 12;
    var date_string = month_names[date_obj.getMonth()] + " " + date_obj.getDate() + ", " +
                      date_obj.getFullYear() + " " + hours + ":" + minutes + " " + ampm;
    return date_string;
}

function add_onload_function(funct)
{
    if (typeof(window.addEventListener) != "undefined")
       window.addEventListener("load",funct,false);
    else if (typeof(document.addEventListener) != "undefined")
       document.addEventListener("load",funct,false);
    else if (typeof(window.attachEvent) != "undefined")
       window.attachEvent("onload",funct);
    else {
       var oldfunct = window.onload;
       if (typeof(window.onload) != "function") window.onload = funct;
       else window.onload = function() { oldfunct(); funct(); }
    }
}


