window.onload = function() {
  useLoadingImage('/litesale/images/spinner_medium.gif');
};

function getObjById(id) {
  return $(id);
}

function gotoLocation(loc) {
  document.location = loc;
}

function executeAction(action_name, form) {
  executeActionWithTarget(action_name, '_self', form);
}

function executeActionWithConfirm(action_name, form, confirmMessage) {
    if (confirm(confirmMessage)) {
        executeActionWithTarget(action_name, '_self', form);
    }
}

function gotoLocationWithConfirm(loc, confirmMessage) {
    if (confirm(confirmMessage)) {
        document.location = loc;
    }
}

function executeActionWithTarget(action_name, target_name, form) {
  $$("input[id='i_formActionName']").each(function(e) {
    e.value = action_name;
  });

  if (form == null) {
    form = getObjById('i_formAction');
  }

  form.target = target_name;
  form.submit();
}

function executeActionWithRedirect(action_name, url, form) {
  $$("input[id='i_formActionName']").each(function(e) {
    e.value = action_name;
  });

  if (form == null) {
    form = getObjById('i_formAction');
  }

  form.action = url;
  form.submit();
}

function setFocus(elementName) {
  try {
    pageElement = getObjById(elementName);
    pageElement.select();
    pageElement.focus();
  } catch(e) {
    // silence
  }
}

function showSendEmailPage(invoiceId) {
  removeEditor('i_messageContent');
  AjaxServices.showEmailMessageSendPage(invoiceId, function(data) {
    dwr.util.setValue("messageSendBox", data, { escapeHtml:false });
    setFocus("i_messageTitle");
    initEditor('i_messageContent');
    showEditor('i_messageContent');
  });
}

function showSendSMSPage() {
  removeEditor('i_messageContent');

  AjaxServices.showSmsMessageSendPage(function(data) {
    dwr.util.setValue("messageSendBox", data, { escapeHtml:false });
    setFocus("i_messageContent");
  });
}

function useLoadingImage(imageSrc) {
  var loadingImage;
  if (imageSrc) loadingImage = imageSrc;
  else loadingImage = "ajax-loader.gif";
  dwr.engine.setPreHook(function() {
    var disabledImageZone = $('disabledImageZone');
    if (!disabledImageZone) {
      disabledImageZone = document.createElement('div');
      disabledImageZone.setAttribute('id', 'disabledImageZone');
      disabledImageZone.style.position = "absolute";
      disabledImageZone.style.zIndex = "1000";
      disabledImageZone.style.left =  (document.viewport.getWidth() / 2) + "px";;
      disabledImageZone.style.top = (document.viewport.getHeight() / 2) + "px";
      disabledImageZone.style.width = "32px";
    disabledImageZone.style.height = "32px";
      var imageZone = document.createElement('img');
      imageZone.setAttribute('id', 'imageZone');
      imageZone.setAttribute('src', imageSrc);
      imageZone.style.position = "absolute";
      imageZone.style.top = "0px";
      imageZone.style.right = "0px";
      disabledImageZone.appendChild(imageZone);
      document.body.appendChild(disabledImageZone);
    }                                                      
    else {
      $('imageZone').src = imageSrc;
      disabledImageZone.style.visibility = 'visible';
    }
  });
  dwr.engine.setPostHook(function() {
    $('disabledImageZone').style.visibility = 'hidden';
  });
}

function sendSMSMessage() {
  var content = dwr.util.getValue("i_messageContent");
  if (content.length == 0 || trim(content).length == 0) {
    alert('Please enter the message text');
    return;
  }
  executeAction('send_sms');
}

function trim(str) {
  if (!str || typeof str != 'string')
    return null;

  return str.replace(/^[\s]+/, '').replace(/[\s]+$/, '').replace(/[\s]{2,}/, ' ');
}

function textCharCount(txtAreaObject, txtFieldObject, maxlen)
{
  if (txtAreaObject.value.length > maxlen) {
    txtAreaObject.value = txtAreaObject.value.substring(0, maxlen);
  }
  n = maxlen - txtAreaObject.value.length;
  txtFieldObject.value = "" + n;
}

function sendEmailMessage(act_name) {
  var messageTitle = dwr.util.getValue("i_messageTitle");
  if (messageTitle.length == 0 || trim(messageTitle).length == 0) {
    alert('Please enter the message subject');
    return;
  }
  //  var messageContent = dwr.util.getValue("i_messageContent");
  //  if (messageContent.length == 0 || trim(messageContent.length) == 0) {
  //    alert('Please enter the message text');
  //    return;
  //  }
  executeAction(act_name);
}

function openwindow(url, name, w, h) {
  // Fudge factors for window decoration space.
  // In my tests these work well on all platforms & browsers.
  w += 32;
  h += 96;
  wleft = (screen.width - w) / 2;
  wtop = (screen.height - h) / 2;
  // IE5 and other old browsers might allow a window that is
  // partially offscreen or wider than the screen. Fix that.
  // (Newer browsers fix this for us, but let's be thorough.)
  if (wleft < 0) {
    w = screen.width;
    wleft = 0;
  }
  if (wtop < 0) {
    h = screen.height;
    wtop = 0;
  }
  var win = window.open(url,
    name,
    'width=' + w + ', height=' + h + ', ' +
    'left=' + wleft + ', top=' + wtop + ', ' +
    'location=no, menubar=no, ' +
    'status=no, toolbar=no, scrollbars=no, resizable=yes');
  // Just in case width and height are ignored
  win.resizeTo(w, h);
  // Just in case left and top are ignored
  win.moveTo(wleft, wtop);
  win.focus();
}

function checkContactForm() {
  if ($('i_contactform_name').value == '' || $('i_contactform_name').value == 'Enter your name') {
    alert('Please enter you name');
    return false;
  }

  if ($('i_contactform_email').value == '' || $('i_contactform_email').value == 'Enter your email') {
    alert('Please enter you email');
    return false;
  }

  if ($('i_contactform_message').value == '' || $('i_contactform_message').value == 'Comments') {
    alert('Please type in the comment or question');
    return false;
  }

  return true;
}

function submitContactForm() {
  if (checkContactForm()) {
    $('i_contactform').submit();
  }
}

function switchTemplate(templateId) {
  AjaxServices.switchTemplate(templateId, function (et) {
      if ($('textleftcharacters') != null) {
          if (et.contentText.length > 160) {
              $('i_messageContent').value = et.contentText.substring(0, 160);
          } else {
              $('i_messageContent').value = et.contentText;
          }
          textCharCount($('i_messageContent'), $('textleftcharacters'), 160);
      } else {
          var ed = tinyMCE.get('i_messageContent');
          if (ed!= null) {
            ed.setContent(et.contentText);
          }

          $('i_messageTitle').value = et.name;
      }

    try {
      $('i_messageContent').focus();
    } catch(e) {
      // silence
    }
  });
}

function initEditor(editorId) {
    tinyMCE.init({
      mode : "textareas",
      theme : "advanced",
      editor_selector: editorId,
      // Theme options
      theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect,removeformat,cut,copy,paste,pastetext,pasteword,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,|,image,|,cleanup",
      theme_advanced_buttons2 : "",
      theme_advanced_buttons3 : "",
      theme_advanced_buttons4 : "",
      theme_advanced_toolbar_location : "top",
      theme_advanced_toolbar_align : "left",
      theme_advanced_statusbar_location : "none",
      theme_advanced_resizing : false,

      external_image_list_url : "/litesale/layout/litesale2/editor-image-list.jsp"
    });
  }

function showEditor(editorId) {
  tinyMCE.execCommand('mceAddControl', false, editorId);
}

function removeEditor(editorId) {
    if (tinyMCE.get(editorId)) {
       tinyMCE.execCommand('mceRemoveControl', false, editorId);
    }
}

