/* Rules for Money */
$.fn.form.settings.rules.decimal_money = function(value) {
  var regex  = /^\d+(?:\.\d{0,2})$/;
  return regex.test(value);
};

if (typeof Handlebars.registerHelper === 'function') {
    Handlebars.registerHelper('ifeq', function (a, b, options) {
        if (a == b) { return options.fn(this); }
        return options.inverse(this);
    });

    Handlebars.registerHelper('ifnoteq', function (a, b, options) {
        if (a != b) { return options.fn(this); }
        return options.inverse(this);
    });   
}

function empty(str) {
  return (typeof str == 'undefined' || !str || str.length === 0 || str === "" || !/[^\s]/.test(str) || /^\s*$/.test(str) || str.replace(/\s/g,"") === "") ? true : false;
}

/* Helper for has_error */
function get_json_from_html(str) {
  var curly_brace_start = false;
  var ret = '';
  for (var x = 0; x < str.length; x++) {
    var c = str.charAt(x);
    if (c === '{' && str.charAt(x + 1) === '"') {
      curly_brace_start = true;
    }
    if (curly_brace_start === true) {
      ret += c;
    }
    if (c === '"' && str.charAt(x + 1) === '}') {
      return ret + '}'; // Return JSON Data
    }
  }
  return false;
}

function has_saved(response, xhr, info) {
  try {
    var ct = xhr.getResponseHeader("content-type") || "";
    if (ct.indexOf('json') > -1) {
      var t = (response.time) ? response.time : '';
      if (response.saved === true) {
        saved_toast(info + ' at ' + t);
        return true;
      }
    }
    return false;
  } catch(err) { }
}

function has_error(response, xhr, header) {
  var heading = (typeof header === "undefined") ? 'Saving' : header;
  var ct = xhr.getResponseHeader("content-type") || "";
  if (ct.indexOf('html') > -1) {
    if (response.indexOf('hadError') === -1) {
      return false;
    }
    var jsonData = get_json_from_html(response);
    if (jsonData === false) {
      return false;
    }
    try {
      response = JSON.parse(jsonData); // Convert HTML to JSON
    } catch(err) {
      // debug_print(err);
    }
  }
  if (response.user_message) {
    reset_save_toast();
    if (response.fatal === true) {
      $.toast({
        heading: 'Error ' + heading,
        showHideTransition: 'slide',
        text: response.user_message,
        icon: 'error',
          position: {
            right: 35,
            bottom: 65
        },
        hideAfter: 5000   // in milli seconds
      });
    } else {
      $.toast({
        heading: 'Notice ' + heading,
        showHideTransition: 'slide',
        text: response.user_message,
        icon: 'info',
          position: {
            right: 35,
            bottom: 65
        },
        hideAfter: 5000   // in milli seconds  
      });
    }    
    
    if (response.user_message !== 'Check the Error Console...') {
      debug_print(response.user_message);
    }
  }
  if (response.message) {
    debug_print(response.message);
  }
  if (response.fatal === true) {
    return true;
  } else {
    return false;
  }
}

var saving = '';
function saving_toast() {
  saving = $.toast({
                text: '<i class="spinner loading icon"></i><b>Saving!</b> Please wait..',
                textAlign: 'left',
                loader: false,
                showHideTransition: 'slide',
                allowToastClose: false,
                  position: {
                    right: 35,
                    bottom: 65
                  },
              });
}

function reset_save_toast() {
  if (typeof saving === 'object') {
    saving.reset();
  }
}

function saved_toast(field) {
  window.setTimeout(function() {
                $.toast({
                  heading: 'Success',
                  showHideTransition: 'slide',
                  text: 'Saved '+field+'.',
                  icon: 'success',
                  loader: true, 
                  hideAfter: 3000
                });
                reset_save_toast();
            }, 2000);
}

function show_loading() {
      /* Show the Loader / Hide the Clock */
      $('#topLoad').css('display', 'inline-block');
      $('#clock').css('display', 'none');
}

function done_loading() {
    $("time.timeago").timeago();
    // Hide the Loader / Show the Clock
    $('#topLoad').css('display', 'none');
    $('#clock').css('display', 'inline-block');
}

/* Show a modal and load its data */
function show_modal(url, id, modalname) {
  $.ajax({
    url: url,
    type: 'GET',
    global: false,
    async: true,
    success: function (response, status, xhr) {
      if (!has_error(response, xhr)) {
        $("#" + id).html(response);
        $("#" + modalname).modal('show');
      }
    }
  });
}

function logout() {
  $.ajax({
    url: "app/page/session.php",
    type: 'GET',
    data: {logout: 'true'},
    dataType: "html",
    global: false,
    async: true,
    success: function (response) {
      location.reload();
    }
  });
}


var array_of_frames = []; /* Needed to track open iFrames */
var print_frame_id = 0;
/* id is the  id of the iframe */
function print_frame(id, src) {
  try {
    for (var i = 0; i < array_of_frames.length; i++) {
      document.body.removeChild(array_of_frames[i]); // Delete old page when done, for new data
      array_of_frames.pop();
    }

    var newIframe = document.createElement('iframe');
    newIframe.width = '0';
    newIframe.height = '0';
    newIframe.name = id;
    newIframe.id = id;
    newIframe.src = src;
    print_frame_id = id;

    document.body.appendChild(newIframe);
    array_of_frames.push(newIframe); /* Add frame to list to be removed next time */
    
    newIframe.onload=done_print_frame;
        
  } catch (err) {
    debug_print(err.message);
  }
  return false;
}

function done_print_frame() {
    var frm = document.getElementById(print_frame_id).contentWindow;
    frm.focus(); // set focus on contentWindow is needed on some ie versions
    frm.print();
}


/*
 * Form Messages:
 */
function check_for_error(id, response, xhr, header) {
  var heading = (typeof header === "undefined") ? 'Saving' : header;
  var ct = xhr.getResponseHeader("content-type") || "";
  if (ct.indexOf('html') > -1) {
    if (response.indexOf('hadError') === -1) {
      return false;
    }
    var jsonData = get_json_from_html(response);
    if (jsonData === false) {
      return false;
    }
    try {
      response = JSON.parse(jsonData); // Convert HTML to JSON
    } catch(err) {
      // debug_print(err);
    }
  }
  if (response.user_message) {
    if (response.fatal === true) {
      do_message(id, 'error', 'Error:', heading);
    } else {
      do_message(id, 'info', 'Notice:', heading)
    }
    
    if (response.user_message !== 'Check the Error Console...') {
      debug_print(response.user_message);
    }
    
    }
    if (response.message) {
      debug_print(response.message);
    }
    if (response.fatal === true) {
      return true;
    } else {
      return false;
    }
}

function did_save(id, response, xhr, info) {
  try {
    var ct = xhr.getResponseHeader("content-type") || "";
    if (ct.indexOf('json') > -1) {
      var t = (response.time) ? response.time : '';
      if (response.saved === true) {
        do_message(id, 'success', 'Saved:', info + ' at ' + t);
        return true;
      }
    }
    return false;
  } catch(err) { }
}


function do_message(id, kind, bold, normal) {
  switch(kind) {
    case 'success':
      $('#'+id).removeClass('info');
      $('#'+id).removeClass('error');
      $('#'+id).addClass('success');
      $('#'+id).html('<p><i class="check circle icon"></i><b>'+bold+'</b> '+normal+'</p>');
      break;
    case 'info':
      $('#'+id).removeClass('error');
      $('#'+id).removeClass('success');
      $('#'+id).addClass('info');
      $('#'+id).html('<p><i class="info circle icon"></i><b>'+bold+'</b> '+normal+'</p>');
      break;
    case 'error':
      $('#'+id).removeClass('info');
      $('#'+id).removeClass('success');
      $('#'+id).addClass('error');
      $('#'+id).html('<p><i class="exclamation triangle icon"></i><b>'+bold+'</b> '+normal+'</p>');
      break;
  }
  $('#'+id).show();
}