// 1.0.33
/* First line must show version number - update as builds change
member.js

History:
  (older history - see ./member_changelog.txt)
1.0.33 (2008-12-13)
  1) Changes to rate better with jslint while (hopefully) not breaking anything
  2) Improvements to group permissions setting for selected users -
     better setting of advanced properties with basic controls
  3) order_items_refund_total() bug fix - used 'for in' on an array - breaks with prototype.js
1.0.32 (2008-12-04)
  1) Changes to details() to include a random portion to help cache busting with reloading popup form in case
     changes are not reflected.
1.0.31 (2008-11-06)
  1) Changes to details() and report() to allow URLs to contain a '.' - this is important as some
     forms and reports are renamed to 'module.name.report-name' type formats to identify them as belonging to modules
1.0.30 (2008-10-28)
  1) Support added in context menu for righ-clicking on menu items NOT rendered as images
  2) Extra parameter for details to allow passing of preset values when creating a new item (2008-10-28)
1.0.29 (2008-10-02)
  1) Added selected_send_email()
1.0.28 (2008-08-06)
  1) Added specific support added in context_menu for theme banner and each individual theme accent
1.0.27 (2008-07-26)
  1) Changes to context menu - no longer assumes edit buttonstyle is available, degrades gracefully if not
  2) Provision added where required for export navbutton, export navsuite, export navstyle and export content_block
  3) Provision added for Theme editing in context menu
1.0.26 (2008-07-02)
  1) Removed report_filter_save(reportID) - now in functions.js and renamed filterbar_save_onclick()
1.0.25 (2008-05-10)
  1) Inline context menu variable settings now in this file
  2) New function new_page() to generate new pages with a given layoutID
1.0.24 (2008-04-24)
  1) Big changes to credit memo functions for cicbv
1.0.23 (2008-04-11)
  1) Bug fix for color_picker path mode
  2) Changes to details() to better apply optional fields only where needed
1.0.22 (2008-04-08)
  1) Now checks use_friendly_urls to determine path for the following functions:
       details()
       report()
       popup_group_assign() (is this still used?)
       export_sql()
1.0.21 (2008-04-04)
  1) Changed references to ./ to use base_url variable instead
  2) New function popup_fileviewer()
1.0.20 (2008-04-03)
  1) Changes to order_issue_credit_memo() to warn if refund amount differs from suggested,
     largely to prevent zero-value refunds (Thanks James)
*/

// ************************************
// * External References (for JSLint) *
// ************************************

// Browser:
/*global alert, document, window, Option */

// Inline code:
/*global base_url, global_active_btns, rating_blocks, system_family, use_friendly_urls */

// Inline code when needed:
/*global destinationID_arr */

// functions.js:
/*global addEvent, attach_field_behaviour, combo_selector_set, gFckEditorsLoading, geid, geid_set, geid_val,
  popWin, popup_dialog, radio_group_get, radio_group_set, setDisplay, show_section, two_dp
*/


// ************************************
// * Context Menu Support             *
// ************************************
// Loosely based on code from http://luke.breuer.com/tutorial/js_contextmenu.htm
var _CM_type =          "";     // Context type
var _CM_ID =            [];	// Context ID
var _CM_text =          [];	// Additional text for context
var _replaceContext =   false;  // replace the system context menu?
var _mouseOverContext = false;  // is the mouse over the context menu?
var _contextActive = false;

function CM_Attach_Events(obj){
  var fn1, fn2;
  fn1 = function(e){ obj.style.backgroundColor='#ffff80';};
  fn2 = function(e){ obj.style.backgroundColor='#ffffff';};
  addEvent(obj, 'mouseover', fn1);
  addEvent(obj, 'mouseout', fn2);
}
function CM_InitContext(num) {
  var obj, i;
  for (i=1; i<num; i++){
    obj = geid('CMA_'+i);
    CM_Attach_Events(obj);
  }
  document.body.onmousedown = CM_MouseDown;
  document.body.oncontextmenu = CM_ContextShow;
  _contextActive = false;
  CM_CloseContext();
}
function CM_Navbutton_Over(
    bID,bText,bUp,bUpLabel,bDown,bDownLabel,bDel,
    bSubNavStyleID, bSuiteID,bSuiteName,bStyleID, bStyleName) {
  if (CM_visible('CM_navbutton')) {
    return;
  }
  _CM_type='navbutton';
  _CM_ID[0]=bID;
  _CM_text[0]='&quot;'+bText+'&quot;';
  _CM_ID[1]=bDel;
  _CM_ID[2]=bUp;
  _CM_text[2]=bUpLabel;
  _CM_ID[3]=bDown;
  _CM_text[3]=bDownLabel;
  _CM_ID[6]=bSubNavStyleID;
  _CM_ID[4]=bSuiteID;
  _CM_text[4]='&quot;'+bSuiteName+'&quot;';
  _CM_ID[5]=bStyleID;
  _CM_text[5]='&quot;'+bStyleName+'&quot;';
}
function CM_visible(menu) {
  return geid(menu).style.display!=='none';
}
// call from the onmousedown event, passing the event if standards compliant
function CM_MouseDown(event) {
  if (_mouseOverContext) {
    return;
  }
  if (!event) { event = window.event; }
  var target = (event.target ? event.target : event.srcElement);
  if (event.button === 2) {
    switch (_CM_type) {
      case 'article':
      case 'content_block':
      case 'event':
      case 'job':
      case 'news':
      case 'navbutton':
      case 'podcast':
      case 'report':
      case 'report_column':
      case 'report_filter':
      case 'theme_accent':
      case 'theme_banner':
        _replaceContext = true;
        _contextActive = true;
      break;
    }
  }
  else if (!_mouseOverContext) {
    CM_CloseContext();
  }
}

function CM_HideContext() {
  if (geid('CM_article')) {geid('CM_article').style.display = 'none';}
  if (geid('CM_content_block')) {geid('CM_content_block').style.display = 'none';}
  if (geid('CM_event')) {geid('CM_event').style.display = 'none';}
  if (geid('CM_job')) {geid('CM_job').style.display = 'none';}
  if (geid('CM_navbutton')) {geid('CM_navbutton').style.display = 'none';}
  if (geid('CM_news')) {geid('CM_news').style.display = 'none';}
  if (geid('CM_podcast')) {geid('CM_podcast').style.display = 'none';}
  if (geid('CM_report')) {geid('CM_report').style.display = 'none';}
  if (geid('CM_report_column')){geid('CM_report_column').style.display = 'none';}
  if (geid('CM_report_filter')) {geid('CM_report_filter').style.display = 'none';}
  if (geid('CM_theme_accent')) {geid('CM_theme_accent').style.display = 'none';}
  if (geid('CM_theme_banner')) {geid('CM_theme_banner').style.display = 'none';}
}
function CM_CloseContext() {
  _mouseOverContext = false;
  _contextActive = false;
  CM_HideContext();
}
function CM_ContextShow(event) {
  var btn, b_src, b_url, divContext, divID, target, scrollLeft, scrollTop;
  CM_HideContext();
  if (_mouseOverContext) {
    return false;
  }
  if (!_replaceContext) {
    return true;
  }
  if (!event) { event = window.event; }
  target = (event.target ? event.target : event.srcElement);
  scrollTop = document.body.scrollTop ? document.body.scrollTop : document.documentElement.scrollTop;
  scrollLeft = document.body.scrollLeft ? document.body.scrollLeft : document.documentElement.scrollLeft;
  switch (_CM_type) {
    case 'article':
      divID = 'CM_article';
      geid('CM_article_text').innerHTML=_CM_text[0];
      geid('CM_article_delete_text').innerHTML=_CM_text[1];
      geid('CM_article_view_text').innerHTML=_CM_text[1];
    break;
    case 'content_block':
      divID = 'CM_content_block';
      geid('CM_content_block_text').innerHTML=_CM_text[0];
      if (geid('CM_content_block_export_text')) { geid('CM_content_block_export_text').innerHTML=  _CM_text[0]; }
    break;
    case 'event':
      divID = 'CM_event';
      geid('CM_event_text').innerHTML=_CM_text[0];
      geid('CM_event_delete_label').innerHTML=     (_CM_ID[1] ? "Delete" : "<span class='disabled'>Delete</span>");
      geid('CM_event_delete_text').innerHTML=      (_CM_ID[1] ? _CM_text[1] : "<span class='disabled'>"+_CM_text[1]+"</span>");
      geid('CM_event_registrants_text').innerHTML=_CM_text[2];
      geid('CM_event_registrants').style.display = (_CM_ID[2] ? '':'none');
      geid('CM_event_view_text').innerHTML=        _CM_text[1];
    break;
    case 'navbutton':
      btn = document.getElementById('btn_'+_CM_ID[0]);
      geid('CM_navbutton_navbutton_text').innerHTML=          _CM_text[0];
      geid('CM_navbutton_navbutton_up_label').innerHTML=     (_CM_ID[2] ? "Move "+_CM_text[2] : "<span class='disabled'>Move "+_CM_text[2]+"</span>");
      geid('CM_navbutton_navbutton_down_label').innerHTML=   (_CM_ID[3] ? "Move "+_CM_text[3] : "<span class='disabled'>Move "+_CM_text[3]+"</span>");
      geid('CM_navbutton_navbutton_delete_label').innerHTML= (_CM_ID[1] ? "Delete" : "<span class='disabled'>Delete</span>");
      geid('CM_navbutton_navbutton_delete_text').innerHTML=   _CM_text[0];
      geid('CM_navbutton_subnav_add_label').innerHTML=       (_CM_ID[6]!=='1' && _CM_ID[6]!=='' && _CM_ID[6]!=='-1'  ? "Add Submenu to " : "<span class='disabled'>Add Submenu to</span>");
      geid('CM_navbutton_subnav_add_text').innerHTML=         _CM_text[0];
      if (geid('CM_navbutton_navbutton_export_text')) {
        geid('CM_navbutton_navbutton_export_text').innerHTML=  _CM_text[0];
      }
      geid('CM_navbutton_navsuite_edit_text').innerHTML= _CM_text[4];
      if (geid('CM_navbutton_navsuite_export_text')) {
        geid('CM_navbutton_navsuite_export_text').innerHTML= _CM_text[4];
      }
      if (geid('CM_navbutton_navstyle_text')) {
        geid('CM_navbutton_navstyle_text').innerHTML= _CM_text[5];
      }
      if (geid('CM_navbutton_navstyle_export_text')) {
        geid('CM_navbutton_navstyle_export_text').innerHTML= _CM_text[5];
      }
      if (btn){
        b_src = btn.style.backgroundImage;
        b_url = b_src.substr(4,b_src.length-5);
        geid('CM_navbutton_info_text').innerHTML=
          "<div>"+
          "  <div class='fl' style='width:40px;line-height:"+btn.height+"px;'>Active</div><img src='"+base_url+"img/?mode=spacer' style='margin:1px;background: "+b_src+" no-repeat "+(_CM_ID[1] ? '0' : '100%')+" 0px'      width='"+btn.width+"' height='"+btn.height+"' alt='Active'/><br class='clr_b'/>"+
          "  <div class='fl' style='width:40px;line-height:"+btn.height+"px;'>Down</div><img src='"+base_url+"img/?mode=spacer' style='margin:1px;background: "+b_src+" no-repeat "+(_CM_ID[1] ? '0' : '100%')+" "+(-1*btn.height)+"px'   width='"+btn.width+"' height='"+btn.height+"' alt='Down'/><br class='clr_b'/>\n"+
          "  <div class='fl' style='width:40px;line-height:"+btn.height+"px;'>Normal</div><img src='"+base_url+"img/?mode=spacer' style='margin:1px;background: "+b_src+" no-repeat "+(_CM_ID[1] ? '0' : '100%')+" "+(-2*btn.height)+"px' width='"+btn.width+"' height='"+btn.height+"' alt='Normal'/><br class='clr_b'/>\n"+
          "  <div class='fl' style='width:40px;line-height:"+btn.height+"px;'>Over</div><img src='"+base_url+"img/?mode=spacer' style='margin:1px;background: "+b_src+" no-repeat "+(_CM_ID[1] ? '0' : '100%')+" "+(-3*btn.height)+"px'   width='"+btn.width+"' height='"+btn.height+"' alt='Over'/>\n"+
          "</div>\n"+
          "<p class='clr_b' style='margin:0;' align='center'>(Width: "+btn.width+"px, Height: "+btn.height+"px, [<a target=\"_blank\" href=\""+b_url+"\">image</a>])</p>";
      }
      else {
        geid('CM_navbutton_info_text').innerHTML="(None - this button is not an image)";
      }
      divID = 'CM_navbutton';
    break;
    case 'job':
      divID = 'CM_job';
      geid('CM_job_text').innerHTML=_CM_text[0];
      geid('CM_job_delete_text').innerHTML=_CM_text[1];
      geid('CM_job_view_text').innerHTML=_CM_text[1];
    break;
    case 'news':
      divID = 'CM_news';
      geid('CM_news_text').innerHTML=_CM_text[0];
      geid('CM_news_delete_text').innerHTML=_CM_text[1];
      geid('CM_news_view_text').innerHTML=_CM_text[1];
    break;
    case 'podcast':
      divID = 'CM_podcast';
      geid('CM_podcast_text').innerHTML=_CM_text[0];
      geid('CM_podcast_delete_text').innerHTML=_CM_text[1];
      geid('CM_podcast_view_text').innerHTML=_CM_text[1];
    break;
    case 'report':
      divID = 'CM_report';
    break;
    case 'report_column':
      divID = 'CM_report_column';
    break;
    case 'report_filter':
      divID = 'CM_report_filter';
      geid('CM_report_filter_left_label').innerHTML=   (_CM_ID[2]=='1' ? "Move filter left" : "<span class='disabled'>Move filter left</span>");
      geid('CM_report_filter_right_label').innerHTML=  (_CM_ID[3]=='1' ? "Move filter right" : "<span class='disabled'>Move filter right</span>");
      if (geid('CM_report_filter_assign_me')) {
        geid('CM_report_filter_assign_me').style.display=
        (_CM_ID[4]=='system' ? 'inline' : 'none');
      }
      if (geid('CM_report_filter_assign_local')) {
        geid('CM_report_filter_assign_local').style.display=
        (_CM_ID[4]=='person' || (_CM_ID[4]=='system' && _CM_ID[5]=='1') ? 'inline' : 'none');
      }
      if (geid('CM_report_filter_assign_global')) {
        geid('CM_report_filter_assign_global').style.display=
        (_CM_ID[4]=='person' || (_CM_ID[4]=='system' && _CM_ID[5]!='1') ? 'inline' : 'none');
      }
    break;
    case 'theme_accent':
      divID = 'CM_theme_accent';
      if (geid('CM_theme_accent_text')) { geid('CM_theme_accent_text').innerHTML=_CM_text[0]; }
      if (geid('CM_theme_accent_edit_text')) { geid('CM_theme_accent_edit_text').innerHTML=_CM_text[0]; }
      if (geid('CM_theme_accent_num')) { geid('CM_theme_accent_num').innerHTML=_CM_ID[1]; }
      if (geid('CM_theme_accent_export_text')) { geid('CM_theme_accent_export_text').innerHTML=  _CM_text[0]; }
    break;
    case 'theme_banner':
      divID = 'CM_theme_banner';
      if (geid('CM_theme_banner_text')) { geid('CM_theme_banner_text').innerHTML=_CM_text[0]; }
      if (geid('CM_theme_banner_edit_text')) { geid('CM_theme_banner_edit_text').innerHTML=_CM_text[0]; }
      if (geid('CM_theme_banner_export_text')) { geid('CM_theme_banner_export_text').innerHTML=  _CM_text[0]; }
    break;
    default:
      // do nothing
    break;
  }
  divContext = geid(divID);
  // hide the menu first to avoid an 'up-then-over' visual effect
  divContext.style.display = 'none';
  divContext.style.left = event.clientX + scrollLeft + 'px';
  divContext.style.top = event.clientY + scrollTop + 'px';
  divContext.style.zIndex = 200;
  divContext.style.display = 'block';
  replaceContext = false;
  return false;
}


// ************************************
// * Groups support                   *
// ************************************
function add_to_group(targetReportID,popup_w,popup_h) {
  var obj_eventID, obj_filterExact, obj_filterField, obj_filterValue, obj_selectID;
  obj_eventID =		geid('eventID');
  obj_filterExact =	geid('filterExact');
  obj_filterField =	geid('filterField');
  obj_filterValue =	geid('filterField');
  obj_selectID =	geid('selectID');

  var opts = row_select_list(targetReportID);
  popWin(
    base_url+'?page=_admin_add_people_to_group' +
    '&targetReportID='+targetReportID +
    (opts ? "&targetID="+opts : "") +
    (obj_eventID && obj_eventID.value!=='' ? "&eventID="+obj_eventID.value : "") +
    (obj_filterExact && obj_filterExact.value!=='' ? "&filterExact="+obj_filterExact.value : "") +
    (obj_filterField && obj_filterField.value!=='' ? "&filterField="+obj_filterField.value : "") +
    (obj_filterValue && obj_filterValue.value!=='' ? "&filterValue="+obj_filterValue.value : "") +
    (obj_selectID && obj_selectID.value!=='' ? "&selectID="+obj_selectID.value : ""),
    "add_to_group",'scrollbars=0,resizable=0',popup_w,popup_h,'centre');
}

function group_add_people_group_select(field_name,width) {
  var group = combo_selector_set(field_name,width);
  setDisplay('step_3',group!=='');
}

function group_selector_basic_click(current_vals,span_arr) {
  var val = radio_group_get('basic_perms');
  if (typeof current_vals.basic=='undefined' || current_vals.basic !== val) {
    current_vals.basic = val;
    switch(val) {
      case 'email':
        radio_group_set('permADMINISTRATOR','');
        radio_group_set('permAPPROVER','');
        radio_group_set('permEDITOR','');
        radio_group_set('permEMAILRECIPIENT','1');
        radio_group_set('permVIEWER','');
      break;
      case 'viewer':
        radio_group_set('permADMINISTRATOR','');
        radio_group_set('permAPPROVER','');
        radio_group_set('permEDITOR','');
        radio_group_set('permEMAILRECIPIENT','');
        radio_group_set('permVIEWER','1');
      break;
      case 'email_viewer':
        radio_group_set('permADMINISTRATOR','');
        radio_group_set('permAPPROVER','');
        radio_group_set('permEDITOR','');
        radio_group_set('permEMAILRECIPIENT','1');
        radio_group_set('permVIEWER','1');
      break;
      case 'x':
        show_section(span_arr,'advanced','#f0f0ff','#c0c0f0');
        group_selector_advanced_click(current_vals,span_arr);
        return false;
      break;
    }
  }
  return true;
}

function group_selector_advanced_click(current_vals,span_arr) {
  // See if anything has changed:
  
  if (
    typeof current_vals.permEMAILRECIPIENT=='undefined' ||
    current_vals.permEMAILRECIPIENT!=radio_group_get('permEMAILRECIPIENT') ||
    current_vals.permVIEWER!=radio_group_get('permVIEWER') ||
    current_vals.permEDITOR!=radio_group_get('permEDITOR') ||
    current_vals.permAPPROVER!=radio_group_get('permAPPROVER') ||
    current_vals.permADMINISTRATOR!=radio_group_get('permADMINISTRATOR')
  ){
    current_vals.permEMAILRECIPIENT=radio_group_get('permEMAILRECIPIENT');
    current_vals.permVIEWER=radio_group_get('permVIEWER');
    current_vals.permEDITOR=radio_group_get('permEDITOR');
    current_vals.permAPPROVER=radio_group_get('permAPPROVER');
    current_vals.permADMINISTRATOR=radio_group_get('permADMINISTRATOR');
    if (
      current_vals.permEMAILRECIPIENT=='1' &&
      current_vals.permVIEWER==='' &&
      current_vals.permEDITOR==='' &&
      current_vals.permAPPROVER==='' &&
      current_vals.permADMINISTRATOR===''){
        radio_group_set('basic_perms','email');
    }
    else if (
      current_vals.permEMAILRECIPIENT==='' &&
      current_vals.permVIEWER=='1' &&
      current_vals.permEDITOR==='' &&
      current_vals.permAPPROVER==='' &&
      current_vals.permADMINISTRATOR===''){
        radio_group_set('basic_perms','viewer');
    }
    else if (
      current_vals.permEMAILRECIPIENT==='1' &&
      current_vals.permVIEWER=='1' &&
      current_vals.permEDITOR==='' &&
      current_vals.permAPPROVER==='' &&
      current_vals.permADMINISTRATOR===''){
        radio_group_set('basic_perms','email_viewer');
    }
    else {
      radio_group_set('basic_perms','x');
    }
  }
}

function popup_group_assign(item_type,itemID) {
  popWin(
    base_url+
    (use_friendly_urls ? 'details/group_assign/' + itemID + '/?target_value=' + item_type : '?mode=details&report_name=group_assign&ID=' + itemID + '&target_value=' + item_type),
    'assign_groups','status=1, scrollbars=1,resizable=1',720,400,1);
}

function popup_page_create(layoutID,width,height){
  popWin(
    base_url+
    (use_friendly_urls ? 'details/pages/?layoutID=' + layoutID : '?mode=details&report_name=pages&layoutID=' + layoutID),
    '','scrollbars=1,resizable=1',width,height);
}

// ************************************
// * color_picker() and support       *
// ************************************
// also uses dectohex()

function color_picker(field,rgb) {
  var obj_field = geid(field);
  obj_field.style.border='solid 1px #008000';
  obj_field.style.background='#e0ffe0';
  // CANNOT use friendly URLs - breaks code
  popWin(base_url + '?mode=color_picker&'+'field='+field+'&rgb='+rgb,'popColorPicker','scrollbars=0,resizable=1,status=0',440,286,'centre');
}

function cp_callback(field,value) {
  if (!window.opener) {
    return false;
  }
  if (value!==false) {
    window.opener.geid('img_swatch_'+field).src=base_url+'img/?mode=imgcol&color='+value;
    window.opener.geid(field).value=value;
  }
  window.opener.geid(field).style.border='1px solid #c0c0c0';
  window.opener.geid(field).style.background='#ffffff';
  return true;
}


function FCKeditor_OnComplete( editorInstance ){
  gFckEditorsLoading--;
}

// ************************************
// * Order Item Refunds               *
// ************************************
function order_issue_credit_memo(orderID,ref_items_arr){
  var h, j, dialogTitle, id;
  var val_arr = [];
  for (var i=0; i<ref_items_arr.length; i++) {
    id = ref_items_arr[i];
    val_arr[val_arr.length] = id + "=" + geid_val('ref_'+id+'_nra');
  }
  var suggestedTotal = geid('ref_suggested_total').innerHTML;
  var actualTotal = geid('ref_actual_total').value;
  if (suggestedTotal != actualTotal) {
    dialogTitle = "WARNING";
    h = 'Suggested Refund: ' + suggestedTotal + '<br />differs from<br />Actual Refund: ' + actualTotal + '<br /><br />Press OK to issue this Credit Memo anyway';
  }
  else {
    dialogTitle = "Credit Memo";
    h = "Issue Credit Memo for this order?";
  }
  j =
    "geid('command').value='order_issue_credit_memo';"+
    "geid('targetValue').value='"+
    orderID+"|"+
    val_arr.join(',')+"|"+
    geid_val('ref_actual_total')+"|"+
    geid_val('ref_notes_customer').replace(/\'/g,'\\\'').replace(/\"/g,'&quot;')+
    "';"+
    "geid('form').submit();";
  popup_dialog(dialogTitle,h,260,260,'OK','Cancel',j);
}

function order_item_refund_flag_set(page,orderID,orderItemID,available){
  var h, j;
  h =
    "Please confirm refund request:"+
    (available > 1 ?
      "<div style='padding-top:10px;'>"+
      "<table class='minimal' summary='Grid layout for popup form'>\n"+
      "  <tr>\n"+
      "    <td style='width:40px;'><input tabindex='1' type='text' id='qty' class='formField txt_r' style='width:30px;' value='"+available+"' /></td>\n"+
      "    <td>Quantity to refund</td>\n"+
      "  </tr>\n"+
      "</table>\n"+
      "</div>" : "<input type='hidden' id='qty' value='"+available+"' />")+
    "</div>";

  j =
    "if (parseInt(geid_val('qty'))<1 || parseInt(geid_val('qty'))>"+available+"){"+
    "geid('qty').value="+available+";return false;}"+
    "window.location='"+base_url+"?page="+page+
    "&ID="+orderID+
    "&print="+geid_val('print')+
    "&command=order_item_refund_flag_set"+
    "&targetID="+orderItemID+
    "&targetValue='+geid_val('qty')+'"+
    "#row_"+orderItemID+"'";
  popup_dialog("Refund Item",h,260,260,'OK','Cancel',j,(available>1 ? 'qty' : ''));
  if (available>1) {
    attach_field_behaviour('qty','int_s');
  }
}

function order_item_refund_calculate(orderItemID,qty,price,tax1,tax2,tax3,tax4,line) {
  var nra =   parseFloat(geid_val('ref_'+orderItemID+'_nra'));
  var diff =  (price-nra);
  var ratio = (diff/price);
  var sub =   price*ratio*qty;

//  geid('ref_'+orderItemID+'_nra').value= two_dp(nra);
  geid('ref_'+orderItemID+'_diff').innerHTML= two_dp(diff);
  geid('ref_'+orderItemID+'_sub').innerHTML = two_dp(sub);

  if (parseFloat(tax1)) {
    geid('ref_'+orderItemID+'_tax1').innerHTML = two_dp(ratio*tax1);
  }
  if (parseFloat(tax2)) {
    geid('ref_'+orderItemID+'_tax2').innerHTML = two_dp(ratio*tax2);
  }
  if (parseFloat(tax3)) {
    geid('ref_'+orderItemID+'_tax3').innerHTML = two_dp(ratio*tax3);
  }
  if (parseFloat(tax4)) {
    geid('ref_'+orderItemID+'_tax4').innerHTML = two_dp(ratio*tax4);
  }
  if (parseFloat(line)) {
    geid('ref_'+orderItemID+'_line').innerHTML = two_dp(ratio*line);
  }
}
function order_items_refund_total(line_arr) {
  if (!line_arr) {
    return;
  }
  var total = 0;
  for (var i=0 ; i<line_arr.length; i++){
    total += parseFloat(geid('ref_'+line_arr[i]+'_line').innerHTML);
  }
  geid('ref_suggested_total').innerHTML = two_dp(total);
}

function order_item_refund_nra_reset(orderItemID,nra){
  geid('ref_'+orderItemID+'_nra').value=nra;
  geid('ref_'+orderItemID+'_nra').onchange();
}
    
function order_item_refund_flag_clear(orderItemID){
  var h, j;
  h = "Cancel pending refund for item?";
  j =
    "geid('command').value='order_item_refund_flag_clear';"+
    "geid('targetID').value='"+orderItemID+"';"+
    "geid('form').submit();";
  popup_dialog("Cancel Refund",h,260,260,'Yes','No',j);
}


function popup_password_change(targetFieldID,targetReportID,targetID){
  var h, j;

  h =
    "Please enter new password"+
    "<div style='padding-top:10px;'>\n"+
    "<table class='minimal' summary='Grid layout for popup form'>\n"+
    "  <tr>\n"+
    "    <td style='width:70px;'>Password</td>\n"+
    "    <td><input type='password' id='pwd1' onkeyup='popup_password_test()' class='formField' style='width:100px;' value='' /></td>\n"+
    "  </tr>\n"+
    "  <tr>\n"+
    "    <td>Confirm</td>\n"+
    "    <td><input type='password' id='pwd2' disabled='disabled' onkeyup='popup_password_test()' class='formField fl' style='width:100px;background-color:#e8e8e8;' value='' /></td>\n"+
    "  </tr>\n"+
    "</table>"+
    "</div>\n";
  j = "popup_password_change_set('"+targetFieldID+"','"+targetReportID+"','"+targetID+"')";
  popup_dialog("Password",h,200,260,'OK','Cancel',j, 'pwd1');
  geid('btn_ok').disabled=true;
}
function popup_password_test() {
  var pwd1 = geid_val('pwd1');
  var pwd2 = geid_val('pwd2');
  geid('pwd2').disabled = !(pwd1.length>4);
  geid('pwd2').style.backgroundColor = (pwd1.length>4 ? '#ffffff' : '#e8e8e8');
  geid('btn_ok').disabled = !(pwd1.length>4 && pwd1==pwd2);
}
function popup_password_change_set(targetFieldID,targetReportID,targetID) {
  geid('submode').value =        'set_password';
  geid('targetFieldID').value =  targetFieldID;
  geid('targetReportID').value = targetReportID;
  geid('targetID').value =       targetID;
  geid('targetValue').value =    geid_val('pwd2');
  geid('form').submit();
}
function popup_fileviewer() {
  popWin(base_url+'js/FCKeditor_2.5.b/editor/ckfinder/ckfinder.html','popup_fileviewer','scrollbars=0,resizable=1,status=0',750,450,'centre');
}


// ************************************
// * 'With Selected' functions        *
// ************************************
function column_select(form,ID,val){
  for (i=0;i<=form.elements.length;i++){
    if (form.elements[i] && form.elements[i].name){
      var find = 'row_select_'+ID+'_';
      if (form.elements[i].name.substr(0,find.length)==find) {
        form.elements[i].checked = val;
      }
    }
  }
  eval("selected_operation_enable_"+ID+"(form,ID)");
}

function row_select_count(ID){
  var out, obj_frm, name, find;
  out = 0;
  obj_frm = geid('form');
  for (var i=0;i<=obj_frm.elements.length;i++){
    if (obj_frm.elements[i] && obj_frm.elements[i].name){
      name = obj_frm.elements[i].name;
      find = 'row_select_'+ID+'_';
      if (obj_frm.elements[i].name.substr(0,find.length)==find) {
        if (obj_frm.elements[i].checked){
          out++;
        }
      }
    }
  }
  return(out);
}

function row_select_list(ID){
  var out, obj_frm, name, find;
  out = [];
  obj_frm = geid('form');
  for (var i=0;i<=obj_frm.elements.length;i++){
    if (obj_frm.elements[i] && obj_frm.elements[i].name){
      name = obj_frm.elements[i].name;
      find = 'row_select_'+ID+'_';
      if (obj_frm.elements[i].name.substr(0,find.length)==find) {
        if (obj_frm.elements[i].checked){
          out[out.length]=name.substr(find.length);
        }
      }
    }
  }
  return(out.join(","));
}

function selected_send_email(targetReportID,popup_w,popup_h) {
  var opts = row_select_list(targetReportID);
  popWin(
    base_url+'?page=_admin_send_email' +
    '&targetReportID='+targetReportID +
    (opts!=="" ? "&targetID="+opts : ""),
    "send_email",'scrollbars=0,resizable=0',popup_w,popup_h,'centre');
}




// ************************************
// * Other functions                  *
// ************************************
function add_note(targetField,targetValue) {
  geid('submode').value='add_note';
  geid('targetField').value=targetField;
  geid('targetValue').value=targetValue;
  geid('form').submit();
}  
function field_csv_toggle(field,item,state) {
  var value_arr = geid(field).value.split(", ");
  var inthere = false;
  for (var i=0; i<value_arr.length; i++){
    if (!value_arr[i]) {
      value_arr.splice(i,1);
    }
    if (value_arr[i] == item) {
      if (!state){
        value_arr.splice(i,1);
      }
      else {
        inthere = true;
      }
    }
  }
  if (state==1 && !inthere) {
    value_arr[value_arr.length]=item;
  }
  geid(field).value = value_arr.join(', ');
}
function download_order_pdf(orderID,columnID,width,height) {
  var uri =
    window.location.protocol+"//"+window.location.host+
    "/?command=download_order_pdf&orderID="+orderID+"&columnID="+columnID;
  window.location=uri;
}
function details(report_name,ID,height,width,reportID,selectID,bulk_update,preset_values){
  var window_name;
  window_name = ('pop_form_'+report_name+"_"+ID).replace(/[ :,\/\-\.]/ig,"");
  var args = [];
  if (typeof reportID=="number") { args.push('reportID='+reportID); }
  if ((typeof selectID=="number" || typeof selectID=="string") && selectID!=='' ) { args.push('selectID='+selectID); }
  if (typeof bulk_update=="number") { args.push('bulk_update='+bulk_update); }
  if (typeof preset_values!="undefined") { args.push(preset_values); }
  args.push('rnd='+Math.random());

  popWin(
    base_url+
    (use_friendly_urls ? 'details/' + report_name + '/' + ID : '?mode=details&report_name=' + report_name + '&ID=' + ID) +
    (args.length ? (use_friendly_urls ? "?" : "&")+args.join("&") : ""),
    window_name,'scrollbars=1,resizable=1',width,height,'centre');
}
function report(report_name,selectID,height,width,print){
  var window_name;
  window_name = ('pop_report_'+report_name+"_"+selectID).replace(/[ :,\/\-\.]/ig,"");
  popWin(
    base_url+
    (use_friendly_urls ? 'report/' + report_name + '/?' : '?mode=report&report_name=' + report_name)+
    (typeof selectID=="number" || typeof selectID=="string" ? '&selectID='+selectID : '')+
    (typeof print=="number" ? '&print='+print : ''),
    window_name,'scrollbars=1,resizable=1',width,height,'centre');
}
function open_textdoc(theURL) {
  list_h = window.open(theURL,'textOutput', 'width=800,height=600,status=1,resizable=1,menubar=1,location=0,toolbar=1,scrollbars=1');
  list_h.focus();
}


function open_excel(theURL) {
  list_h = window.open(theURL,'excelOutput', 'width=800,height=600,status=1,resizable=1,menubar=1,location=0,toolbar=1,scrollbars=1');
  list_h.focus();
}

function decToHex(dec){
  var hexStr = "0123456789ABCDEF";
  var low = dec % 16;
  var high = (dec - low)/16;
  var hex = "" + hexStr.charAt(high) + hexStr.charAt(low);
  return hex;
}

function export_sql(report_name,targetID) {
  var theURL =
    base_url +
    (use_friendly_urls ? 'export/sql/' + report_name + '/?targetID=' +targetID : '?mode=export&submode=sql&report_name=' + report_name + '&targetID=' + targetID);
  list_h = window.open(theURL,'textOutput', 'width=800,height=600,status=1,resizable=1,menubar=1,location=0,toolbar=1,scrollbars=1');
  list_h.focus();
}

function popup_table_structure(url,table) {
  popWin(url+'/?command=get_table_structure&targetValue='+table,'','status=1, scrollbars=1,resizable=1',730,800,1);
}

function set_action_operation_options(){
  var parent_field = geid('destinationOperation');
  var child_field =  geid('destinationID');
  var parent_value='';
  var child_value='';
  if (parent_field.selectedIndex!=-1) {
    parent_value = parent_field.options[parent_field.selectedIndex].value;
  }
  if (child_field.selectedIndex!=-1 && child_field.options && child_field.options.length) {
    child_value =  child_field.options[child_field.selectedIndex].value;
  }
  if (child_field.selectedIndex!=-1) {
    geid('temp_id').value=child_value;
  }
  if (parent_field.selectedIndex!=-1) {
    child_field.options.length=0;
    var obj_option;
    for (var i=0; i<destinationID_arr[parent_value].length; i++) {
      obj_option = new Option(destinationID_arr[parent_value][i][0],destinationID_arr[parent_value][i][1]);
      obj_option.style.backgroundColor=destinationID_arr[parent_value][i][2];
      child_field.options[i] = obj_option;
      if (child_field.options[i].value==geid('temp_id').value) {
        child_field.selectedIndex = i;
      }
    }
  }
};

function validate_at_w3c(uri,width,height) {
  var _uri = window.location.protocol+"//"+window.location.host+"/"+escape(uri);
  popWin('http://validator.w3.org/check?uri='+_uri+'&ss=1','validate','status=1, scrollbars=1,resizable=1',width,height,1);
}
 


// ************************************
// * Option Transfer functions        *
// ************************************
// ===================================================================
// Author: Matt Kruse <matt@mattkruse.com>
// WWW: http://www.mattkruse.com/
//
// NOTICE: You may use this code for any purpose, commercial or
// private, without any further permission from the author. You may
// remove this notice from your final code if you wish, however it is
// appreciated by the author if at least my web site address is kept.
//
// You may *NOT* re-distribute this code in any way except through its
// use. That means, you can include it in your product, or your web
// site, or any other form where the code is actually being used. You
// may not put the plain javascript up on your site for download or
// include it in your javascript libraries for download.
// If you wish to share this code with others, please just point them
// to the URL instead.
// Please DO NOT link directly to my .js files from your site. Copy
// the files to your server and use them there. Thank you.
// ===================================================================

/* SOURCE FILE: selectbox.js */
function hasOptions(obj){if(obj!=null && obj.options!=null){return true;}return false;}
function selectUnselectMatchingOptions(obj,regex,which,only){if(window.RegExp){if(which == "select"){var selected1=true;var selected2=false;}else if(which == "unselect"){var selected1=false;var selected2=true;}else{return;}var re = new RegExp(regex);if(!hasOptions(obj)){return;}for(var i=0;i<obj.options.length;i++){if(re.test(obj.options[i].text)){obj.options[i].selected = selected1;}else{if(only == true){obj.options[i].selected = selected2;}}}}}
function selectMatchingOptions(obj,regex){selectUnselectMatchingOptions(obj,regex,"select",false);}
function selectOnlyMatchingOptions(obj,regex){selectUnselectMatchingOptions(obj,regex,"select",true);}
function unSelectMatchingOptions(obj,regex){selectUnselectMatchingOptions(obj,regex,"unselect",false);}
function sortSelect(obj){var o = [];if(!hasOptions(obj)){return;}for(var i=0;i<obj.options.length;i++){o[o.length] = new Option( obj.options[i].text, obj.options[i].value, obj.options[i].defaultSelected, obj.options[i].selected) ;}if(o.length==0){return;}o = o.sort(
function(a,b){if((a.text+"") <(b.text+"")){return -1;}if((a.text+"") >(b.text+"")){return 1;}return 0;});for(var i=0;i<o.length;i++){obj.options[i] = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);}}
function selectAllOptions(obj){if(!hasOptions(obj)){return;}for(var i=0;i<obj.options.length;i++){obj.options[i].selected = true;}}
function moveSelectedOptions(from,to){if(arguments.length>3){var regex = arguments[3];if(regex != ""){unSelectMatchingOptions(from,regex);}}if(!hasOptions(from)){return;}for(var i=0;i<from.options.length;i++){var o = from.options[i];if(o.selected){if(!hasOptions(to)){var index = 0;}else{var index=to.options.length;}to.options[index] = new Option( o.text, o.value, false, false);}}for(var i=(from.options.length-1);i>=0;i--){var o = from.options[i];if(o.selected){from.options[i] = null;}}if((arguments.length<3) ||(arguments[2]==true)){sortSelect(from);sortSelect(to);}from.selectedIndex = -1;to.selectedIndex = -1;}
function copySelectedOptions(from,to){var options = {};if(hasOptions(to)){for(var i=0;i<to.options.length;i++){options[to.options[i].value] = to.options[i].text;}}if(!hasOptions(from)){return;}for(var i=0;i<from.options.length;i++){var o = from.options[i];if(o.selected){if(options[o.value] == null || options[o.value] == "undefined" || options[o.value]!=o.text){if(!hasOptions(to)){var index = 0;}else{var index=to.options.length;}to.options[index] = new Option( o.text, o.value, false, false);}}}if((arguments.length<3) ||(arguments[2]==true)){sortSelect(to);}from.selectedIndex = -1;to.selectedIndex = -1;}
function moveAllOptions(from,to){selectAllOptions(from);if(arguments.length==2){moveSelectedOptions(from,to);}else if(arguments.length==3){moveSelectedOptions(from,to,arguments[2]);}else if(arguments.length==4){moveSelectedOptions(from,to,arguments[2],arguments[3]);}}
function copyAllOptions(from,to){selectAllOptions(from);if(arguments.length==2){copySelectedOptions(from,to);}else if(arguments.length==3){copySelectedOptions(from,to,arguments[2]);}}
function swapOptions(obj,i,j){var o = obj.options;var i_selected = o[i].selected;var j_selected = o[j].selected;var temp = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);var temp2= new Option(o[j].text, o[j].value, o[j].defaultSelected, o[j].selected);o[i] = temp2;o[j] = temp;o[i].selected = j_selected;o[j].selected = i_selected;}
function moveOptionUp(obj){if(!hasOptions(obj)){return;}for(i=0;i<obj.options.length;i++){if(obj.options[i].selected){if(i != 0 && !obj.options[i-1].selected){swapOptions(obj,i,i-1);obj.options[i-1].selected = true;}}}}
function moveOptionDown(obj){if(!hasOptions(obj)){return;}for(i=obj.options.length-1;i>=0;i--){if(obj.options[i].selected){if(i !=(obj.options.length-1) && ! obj.options[i+1].selected){swapOptions(obj,i,i+1);obj.options[i+1].selected = true;}}}}
function removeSelectedOptions(from){if(!hasOptions(from)){return;}for(var i=(from.options.length-1);i>=0;i--){var o=from.options[i];if(o.selected){from.options[i] = null;}}from.selectedIndex = -1;}
function removeAllOptions(from){if(!hasOptions(from)){return;}for(var i=(from.options.length-1);i>=0;i--){from.options[i] = null;}from.selectedIndex = -1;}
function addOption(obj,text,value,selected){if(obj!=null && obj.options!=null){obj.options[obj.options.length] = new Option(text, value, false, selected);}}

/* SOURCE FILE: OptionTransfer.js */
function OT_transferLeft(){moveSelectedOptions(this.right,this.left,this.autoSort,this.staticOptionRegex);this.update();}
function OT_transferRight(){moveSelectedOptions(this.left,this.right,this.autoSort,this.staticOptionRegex);this.update();}
function OT_transferAllLeft(){moveAllOptions(this.right,this.left,this.autoSort,this.staticOptionRegex);this.update();}
function OT_transferAllRight(){moveAllOptions(this.left,this.right,this.autoSort,this.staticOptionRegex);this.update();}
function OT_saveRemovedLeftOptions(f){this.removedLeftField = f;}
function OT_saveRemovedRightOptions(f){this.removedRightField = f;}
function OT_saveAddedLeftOptions(f){this.addedLeftField = f;}
function OT_saveAddedRightOptions(f){this.addedRightField = f;}
function OT_saveNewLeftOptions(f){this.newLeftField = f;}
function OT_saveNewRightOptions(f){this.newRightField = f;}
function OT_update(){var removedLeft = {};var removedRight = {};var addedLeft = {};var addedRight = {};var newLeft = {};var newRight = {};for(var i=0;i<this.left.options.length;i++){var o=this.left.options[i];newLeft[o.value]=1;if(typeof(this.originalLeftValues[o.value])=="undefined"){addedLeft[o.value]=1;removedRight[o.value]=1;}}for(var i=0;i<this.right.options.length;i++){var o=this.right.options[i];newRight[o.value]=1;if(typeof(this.originalRightValues[o.value])=="undefined"){addedRight[o.value]=1;removedLeft[o.value]=1;}}if(this.removedLeftField!=null){this.removedLeftField.value = OT_join(removedLeft,this.delimiter);}if(this.removedRightField!=null){this.removedRightField.value = OT_join(removedRight,this.delimiter);}if(this.addedLeftField!=null){this.addedLeftField.value = OT_join(addedLeft,this.delimiter);}if(this.addedRightField!=null){this.addedRightField.value = OT_join(addedRight,this.delimiter);}if(this.newLeftField!=null){this.newLeftField.value = OT_join(newLeft,this.delimiter);}if(this.newRightField!=null){this.newRightField.value = OT_join(newRight,this.delimiter);}}
function OT_join(o,delimiter){var val;var str="";for(val in o){if(str.length>0){str=str+delimiter;}str=str+val;}return str;}
function OT_setDelimiter(val){this.delimiter=val;}
function OT_setAutoSort(val){this.autoSort=val;}
function OT_setStaticOptionRegex(val){this.staticOptionRegex=val;}
function OT_init(theform){this.form = theform;if(!theform[this.left]){alert("OptionTransfer init(): Left select list does not exist in form!");return false;}if(!theform[this.right]){alert("OptionTransfer init(): Right select list does not exist in form!");return false;}this.left=theform[this.left];this.right=theform[this.right];for(var i=0;i<this.left.options.length;i++){this.originalLeftValues[this.left.options[i].value]=1;}for(var i=0;i<this.right.options.length;i++){this.originalRightValues[this.right.options[i].value]=1;}if(this.removedLeftField!=null){this.removedLeftField=theform[this.removedLeftField];}if(this.removedRightField!=null){this.removedRightField=theform[this.removedRightField];}if(this.addedLeftField!=null){this.addedLeftField=theform[this.addedLeftField];}if(this.addedRightField!=null){this.addedRightField=theform[this.addedRightField];}if(this.newLeftField!=null){this.newLeftField=theform[this.newLeftField];}if(this.newRightField!=null){this.newRightField=theform[this.newRightField];}this.update();return true;}
function OptionTransfer(l,r){this.form = null;this.left=l;this.right=r;this.autoSort=true;this.delimiter=",";this.staticOptionRegex = "";this.originalLeftValues = {};this.originalRightValues = {};this.removedLeftField = null;this.removedRightField = null;this.addedLeftField = null;this.addedRightField = null;this.newLeftField = null;this.newRightField = null;this.transferLeft=OT_transferLeft;this.transferRight=OT_transferRight;this.transferAllLeft=OT_transferAllLeft;this.transferAllRight=OT_transferAllRight;this.saveRemovedLeftOptions=OT_saveRemovedLeftOptions;this.saveRemovedRightOptions=OT_saveRemovedRightOptions;this.saveAddedLeftOptions=OT_saveAddedLeftOptions;this.saveAddedRightOptions=OT_saveAddedRightOptions;this.saveNewLeftOptions=OT_saveNewLeftOptions;this.saveNewRightOptions=OT_saveNewRightOptions;this.setDelimiter=OT_setDelimiter;this.setAutoSort=OT_setAutoSort;this.setStaticOptionRegex=OT_setStaticOptionRegex;this.init=OT_init;this.update=OT_update;}
