var menu_loaded = false;
var right_side_min_width = 75;
var min_height = 75;

function boundingBoxPrepValues() {
  //Need to set
  var x_offset = document.getElementById('default_composite_image').offsetLeft;
  var y_offset = document.getElementById('default_composite_image').offsetTop + document.getElementById('template_page_body').offsetTop;
  document.getElementById('bounding_box_x').value = document.getElementById('user_supplied_region').offsetLeft - x_offset;
  document.getElementById('bounding_box_y').value = document.getElementById('user_supplied_region').offsetTop - y_offset;
  document.getElementById('bounding_box_w').value = document.getElementById('user_supplied_region').offsetWidth;
  document.getElementById('bounding_box_h').value = document.getElementById('user_supplied_region').offsetHeight;
  document.getElementById('bounding_box_form').submit();
}
function showTransparentPanel() {
  if (!document.getElementById('default_composite_image')) return;
  
  var x_offset = document.getElementById('default_composite_image').offsetLeft + document.getElementById('resizablepanel_c').offsetLeft;
  var y_offset = document.getElementById('default_composite_image').offsetTop + document.getElementById('resizablepanel_c').offsetTop;
  var user_image_size = [x_offset, y_offset, x_offset + document.getElementById('default_composite_image').width, y_offset + document.getElementById('default_composite_image').height]; //min x, min y, max x, max y
  if (document.getElementById('user_supplied_region') && document.getElementById('default_composite_image')) {
    var resize_user_supplied_image = new YAHOO.util.Resize('user_supplied_region', {
        handles: 'all',
        knobHandles: true,
        maxHeight: (user_image_size[3] - user_image_size[1]),
        maxWidth: (user_image_size[2] - user_image_size[0]),
        maxX: user_image_size[2],
        maxY: user_image_size[3],
        minHeight: 10,
        minWidth: 10,
        minX: user_image_size[0],
        minY: user_image_size[1],
        proxy: false,
        draggable: true,
        animate: true,
        animateDuration: .5
    });

    document.getElementById('user_supplied_region').style.left = (parseInt(document.getElementById('user_supplied_region').style.left) + document.getElementById('default_composite_image').offsetLeft) + "px";
    document.getElementById('user_supplied_region').style.top = (parseInt(document.getElementById('user_supplied_region').style.top) + document.getElementById('default_composite_image').offsetTop + document.getElementById('template_page_body').offsetTop) + "px";
    // resize_user_supplied_image.dd.on('endDragEvent', function(args) { resize_user_supplied_image.fireChangeEvent('endResize', args); }); // DIDN'T WORK
  }
}
function customInitializePage() {

  if (document.getElementById('button_bar')) {
    buttonBarPosition();
    onResizeCalls.push(new onResizeCall('buttonBarPosition',''));
  }
  if (document.getElementById('e_signature') && document.getElementById('sig_name')) {
    if (document.getElementById('e_signature').addEventListener) {
      document.getElementById('e_signature').addEventListener('keyup', syncSigs, false);
    } else if (document.getElementById('e_signature').attachEvent) {
      document.getElementById('e_signature').attachEvent('onkeyup', syncSigs);
    }
  }
  setTimeout("ajaxSend('index.php', 'action=stay_alive', 'GET');", 300000);

  if (!document.getElementById('resizablepanel')) {
    return;
  }

  YAHOO.widget.DateCellEditor.prototype.resetForm = function() {
    if (!this.value) {
      //Handle empty values
      this.value = new Date();
    }
    var value = this.value;
    if (value.length == 0) {
      this.value = new Date();
    }
    var selectedValue = (value.getMonth()+1)+"/"+value.getDate()+"/"+value.getFullYear();
    this.calendar.cfg.setProperty("selected",selectedValue,false);

   // This is the missing line:
    this.calendar.cfg.setProperty("pagedate",(value.getMonth()+1)+"/"+value.getFullYear());
    this.calendar.render();
  };
  var inner_window_settings = YAHOO.util.Cookie.get("iwp");
  if (inner_window_settings == null) {
    iw_width = (getWidth()*.8);
    iw_height = (getHeight()*.8);
    iw_x = Math.floor((getWidth() - iw_width)/2);
    iw_y = Math.floor((getHeight() - iw_height)/2);
    YAHOO.util.Cookie.set("iwp", iw_x + "," + iw_y + "," + iw_width + "," + iw_height, { expires: new Date("January 12, 2025") });  //inner_window_position x, y, width, height
  } else {
    iws_pieces = inner_window_settings.split(',');
    iw_x = iws_pieces[0];
    iw_y = iws_pieces[1];
    iw_width = iws_pieces[2];
    iw_height = iws_pieces[3];
  }
  /*
  Initialize and render the MenuBar when the page's DOM is ready
  to be scripted.
  */
  YAHOO.util.Event.onDOMReady(function () {
    if (menu_loaded) {
      return;
    }
    menu_loaded = true;
  /*
     Define an array of object literals, each containing
     the data necessary to create the items for a MenuBar.
  */

  /*
    Instantiate a Menu:  The first argument passed to the constructor
    is the id for the Menu element to be created, the second is an
    object literal of configuration properties.
  */
  var oMenuBar = new YAHOO.widget.MenuBar("kg_menu_bar", {
                      lazyload: true,
                      itemdata: aItemData,
                      zIndex: 10
                      });

  /*
     Since this MenuBar instance is built completely from
     script, call the "render" method passing in a node
     reference for the DOM element that its should be
     appended to.
  */
  oMenuBar.render(document.body);
  
  displayViewOriginalInvoiceInput();

  // Add a "show" event listener for each submenu.

  function onSubmenuShow() {
    var oIFrame, oElement, nOffsetWidth;

    // Keep the left-most submenu against the left edge of the browser viewport
    if (this.id == "yahoo") {
    YAHOO.util.Dom.setX(this.element, 0);
    oIFrame = this.iframe;
    if (oIFrame) {
      YAHOO.util.Dom.setX(oIFrame, 0);
    }
    this.cfg.setProperty("x", 0, true);
    }

    /*
    Need to set the width for submenus of submenus in IE to prevent the mouseout
    event from firing prematurely when the user mouses off of a MenuItem's
    text node.
    */

    if ((this.id == "emails_sub_menu" || this.id == "settings_menu"  || this.id == "loyalty_lock_sub_menu" || this.id == "report_menu" || this.id == "admin_sub_menu" || this.id == "agent_sub_menu" || this.id == "user_menu" || this.id == "karingtongroup") && YAHOO.env.ua.ie) {
      oElement = this.element;
      nOffsetWidth = oElement.offsetWidth;

      /*
        Measuring the difference of the offsetWidth before and after
        setting the "width" style attribute allows us to compute the
        about of padding and borders applied to the element, which in
        turn allows us to set the "width" property correctly.
      */

      oElement.style.width = nOffsetWidth + "px";
      oElement.style.width = (nOffsetWidth - (oElement.offsetWidth - nOffsetWidth)) + "px";
    }
  }

  // Subscribe to the "show" event for each submenu
  oMenuBar.subscribe("show", onSubmenuShow);
  /*
  var oPanel = new YAHOO.widget.Panel("welcomewindow", { constraintoviewport: true, fixedcenter: true, width: "400px", zIndex: 2});

  oPanel.setHeader("Welcome");
  oPanel.setBody("Welcome to the new Karington Marketing Group, Inc Administration Panel!  Menu options are now along the top and tips will be provided throughout to help guide you through getting the most from the new system.");
  oPanel.render(document.body);
  */

  // Create a panel Instance, from the 'resizablepanel' DIV standard module markup
  //alert(iw_x + "," + iw_y + "," + iw_width + "," + iw_height);
  var panel = new YAHOO.widget.Panel("resizablepanel", {
    draggable: true,
    fixedCenter: false,
    close: false,
    width: iw_width + "px",
    height: iw_height + "px",
    autofillheight: "body", // default value, specified here to highlight its use in the example
    constraintoviewport:true,
    x: parseInt(iw_x),
    y: parseInt(iw_y),
    context: ["showbtn", "tl", "bl"],
    effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration: 1}
  });

 panel.render();
 setTimeout("showTransparentPanel();", 1000);

  if (document.getElementById('icc_panes')) {
    //var accordion = new YAHOO.widget.AccordionView('icc_nav_view', {width:'98%', expandItem:0});
    var left_nav_height = YAHOO.util.Dom.getStyle('left_navigation_nav', 'height').replace(/px/,'') ;
    if (left_nav_height == 'auto') {
      left_nav_height =  document.getElementById('left_navigation_nav').offsetHeight;
    }
    var new_height = Math.max((parseInt(YAHOO.util.Dom.getStyle('resizablepanel', 'height')) - left_nav_height - 70), min_height) + 'px';
    YAHOO.util.Dom.setStyle(YAHOO.util.Dom.get('icc_left_pane'), 'height', new_height);
    YAHOO.util.Dom.setStyle(YAHOO.util.Dom.get('icc_right_pane'), 'height', new_height);
    YAHOO.util.Dom.setStyle(YAHOO.util.Dom.get('icc_nav_view_scroll'), 'height', Math.max(new_height.replace(/px/, '') - 30, 100) + 'px');
    // left_navigation_nav
    // icc_nav_view_scroll
    YAHOO.util.Dom.setStyle(YAHOO.util.Dom.get('icc_right_pane'), 'width', Math.max((parseInt(YAHOO.util.Dom.getStyle('resizablepanel', 'width')) - parseInt(YAHOO.util.Dom.getStyle('icc_left_pane', 'width').replace(/px/,'')) - 55),right_side_min_width) + 'px');
    YAHOO.util.Dom.setStyle(YAHOO.util.Dom.get('icc_left_pane'), 'width', Math.min((parseInt(YAHOO.util.Dom.getStyle('resizablepanel', 'width')) - parseInt(YAHOO.util.Dom.getStyle('icc_right_pane', 'width').replace(/px/,'')) - 55), parseInt(YAHOO.util.Dom.getStyle('resizablepanel', 'width')) - right_side_min_width) + 'px');
    
    if (document.getElementById('selected_nav_link')) {
      document.getElementById('selected_nav_link').scrollIntoView(true);
    }
  }
  if (document.getElementById('cer_selected_client')) {
    document.getElementById('cer_selected_client').scrollIntoView(true);
  }

  panel.dd.subscribe('endDragEvent', function(args) {
    iw_x = panel.cfg.config.x.value;
    iw_y = panel.cfg.config.y.value;
    YAHOO.util.Cookie.set("iwp", iw_x + "," + iw_y + "," + iw_width + "," + iw_height, { expires: new Date("January 12, 2025") });  //inner_window_position x, y, width, height
  }, panel, true);

  // Create Resize instance, binding it to the 'resizablepanel' DIV
  var resize = new YAHOO.util.Resize("resizablepanel", {
    handles: ["br"],
    autoRatio: false,
    minWidth: 300,
    minHeight: 100,
    status: false
  });

  // Setup startResize handler, to constrain the resize width/height
  // if the constraintoviewport configuration property is enabled.
  resize.on("startResize", function(args) {

  if (this.cfg.getProperty("constraintoviewport")) {
      var D = YAHOO.util.Dom;

      var clientRegion = D.getClientRegion();
      var elRegion = D.getRegion(this.element);

      resize.set("maxWidth", clientRegion.right - elRegion.left - YAHOO.widget.Overlay.VIEWPORT_OFFSET);
      resize.set("maxHeight", clientRegion.bottom - elRegion.top - YAHOO.widget.Overlay.VIEWPORT_OFFSET);
    } else {
      resize.set("maxWidth", null);
      resize.set("maxHeight", null);
  }

  }, panel, true);

  // Setup resize handler to update the Panel's 'height' configuration property
  // whenever the size of the 'resizablepanel' DIV changes.

  // Setting the height configuration property will result in the
  // body of the Panel being resized to fill the new height (based on the
  // autofillheight property introduced in 2.6.0) and the iframe shim and
  // shadow being resized also if required (for IE6 and IE7 quirks mode).
  resize.on("resize", function(args) {
    var panelHeight = args.height;
    this.cfg.setProperty("height", panelHeight + "px");

    var left_nav_height = YAHOO.util.Dom.getStyle('left_navigation_nav', 'height').replace(/px/,'') ;
    if (left_nav_height == 'auto') {
      left_nav_height =  document.getElementById('left_navigation_nav').offsetHeight;
    }
    var new_height = Math.max((parseInt(YAHOO.util.Dom.getStyle('resizablepanel', 'height')) - left_nav_height - 70), min_height) + 'px';
    YAHOO.util.Dom.setStyle(YAHOO.util.Dom.get('icc_left_pane'), 'height', new_height);
    YAHOO.util.Dom.setStyle(YAHOO.util.Dom.get('icc_right_pane'), 'height', new_height);
    YAHOO.util.Dom.setStyle(YAHOO.util.Dom.get('icc_nav_view_scroll'), 'height', Math.max(new_height.replace(/px/, '') - 30, 100) + 'px');
    
    YAHOO.util.Dom.setStyle(YAHOO.util.Dom.get('icc_right_pane'), 'width', Math.max((parseInt(YAHOO.util.Dom.getStyle('resizablepanel', 'width')) - parseInt(YAHOO.util.Dom.getStyle('icc_left_pane', 'width').replace(/px/,'')) - 55),right_side_min_width) + 'px');
    YAHOO.util.Dom.setStyle(YAHOO.util.Dom.get('icc_left_pane'), 'width', Math.min((parseInt(YAHOO.util.Dom.getStyle('resizablepanel', 'width')) - parseInt(YAHOO.util.Dom.getStyle('icc_right_pane', 'width').replace(/px/,'')) - 55), parseInt(YAHOO.util.Dom.getStyle('resizablepanel', 'width')) - right_side_min_width) + 'px');
  }, panel, true);

  resize.on("endResize", function(args) {
    iw_height = args.height;
    iw_width = args.width;
    YAHOO.util.Cookie.set("iwp", iw_x + "," + iw_y + "," + iw_width + "," + iw_height, { expires: new Date("January 12, 2025") });  //inner_window_position x, y, width, height
  }, panel, true);
  });
  if (document.getElementById('icc_left_pane')) {
    var resize2 = new YAHOO.util.Resize("icc_left_pane", {
      handles: ["r"],
      autoRatio: true,
      minWidth: 150,
      minHeight: 100,
      status: false
    });
    resize2.on('resize', function(ev) {
              var left_nav_height = YAHOO.util.Dom.getStyle('left_navigation_nav', 'height').replace(/px/,'') ;
              if (left_nav_height == 'auto') {
                left_nav_height =  document.getElementById('left_navigation_nav').offsetHeight;
              }
              var new_height = Math.max((parseInt(YAHOO.util.Dom.getStyle('resizablepanel', 'height')) - left_nav_height - 70), min_height) + 'px';
              YAHOO.util.Dom.setStyle(YAHOO.util.Dom.get('icc_left_pane'), 'height', new_height);
              YAHOO.util.Dom.setStyle(YAHOO.util.Dom.get('icc_right_pane'), 'height', new_height);
              YAHOO.util.Dom.setStyle(YAHOO.util.Dom.get('icc_nav_view_scroll'), 'height', Math.max(new_height.replace(/px/, '') - 30, 100) + 'px');

              YAHOO.util.Dom.setStyle(YAHOO.util.Dom.get('icc_right_pane'), 'width', Math.max((parseInt(YAHOO.util.Dom.getStyle('resizablepanel', 'width')) - ev.width - 55),right_side_min_width) + 'px');
              YAHOO.util.Dom.setStyle(YAHOO.util.Dom.get('icc_left_pane'), 'width', Math.min((parseInt(YAHOO.util.Dom.getStyle('resizablepanel', 'width')) - parseInt(YAHOO.util.Dom.getStyle('icc_right_pane', 'width').replace(/px/,'')) - 55), parseInt(YAHOO.util.Dom.getStyle('resizablepanel', 'width')) - right_side_min_width) + 'px');
              });
  }
  if (document.getElementById('chart_earnings')) {
    var chart1XML = createCommissionChartXML('chart_earnings');
    var chart = new FusionCharts("../resources/fusion-chart/FCF_Line.swf", "ChartId", "750", "350");
    chart.addParam('wmode','transparent');
    chart.setDataXML(chart1XML);
    chart.render('chart_earnings');
  }
  if (document.getElementById("main_chart")) {
    initializeForm();
    showChart();
  }
  if (document.getElementById('service_fee_table')) {
    updateServiceFeeTable('additional_terminals');
    updateServiceFeeTable('addl_cards_4_1');
    updateServiceFeeTable('addl_cards_4_4');
  }
  if (document.getElementById('map')) {
    mapLoad();
  }
}

function pageUnload() {
  if (document.getElementById('map')) {
    GUnload();
  }
}

var chart_data = {};
function createCommissionChartXML(graph_id) {
  switch (graph_id) {
    case 'chart_earnings':
      return_value = "<graph caption='Your Commissions' xAxisName='Month' yAxisName='$' hovercapbg='FFECAA' hovercapborder='F47E00' formatNumberScale='0' decimalPrecision='0' showvalues='0' animation='1' numdivlines='5' numVdivlines='0' yaxisminvalue='0' yaxismaxvalue='100' lineThickness='3' rotateNames='1' showAnchors='1' anchorSides='4' anchorRadius='3' numberPrefix='$' lineColor='009900'>"+"\n";
      return_value += "<set value='0' />"+"\n";
      if (chart_data.chart_earnings.length > 0) {
        for (t=1;t<13;t++) {
          return_value += "<set name='" + chart_data.chart_earnings[t].label + "' value='"+chart_data.chart_earnings[t].amount.toFixed(2)+"' />"+"\n";
        }
      }

      return_value += "</graph>"+"\n";

      //document.getElementById('ta').value = return_value;
      return return_value;
  }
}

function tocAction(action_type,marketing_plan_section_id) {
  if (action_type == 'delete') {
    if (confirm("Are you sure you want to delete this section?")) {
      //Delete section
      if (false && ajax_on) {
        fetchPage('marketing-plan&section='+marketing_plan_section_id+'&action=delete');
      } else {
        location.href = 'index.php?current_page=marketing-plan&section='+marketing_plan_section_id+'&action=delete';
      }
    }
  }
}
function tocContextMenu(marketing_plan_section_id,display_order,display_indent,tocSize) {
  text = "";
  if (marketing_plan_section_id > 0) {
    if (display_order > 1) {
      //text += '<a href="index.php?current_page=marketing-plan&section='+marketing_plan_section_id+'&new_display_order='+Math.max(0,display_order-1)+'&new_display_indent='+(display_indent-1)+'"'+((ajax_on)?' onClick="fetchPage(\'marketing-plan&section='+marketing_plan_section_id+'&new_display_order='+Math.max(0,display_order-1)+'&new_display_indent='+(display_indent-1)+'\');return false;"':'')+'>&uarr;</a>';
      text += '<a href="index.php?current_page=marketing-plan&section='+marketing_plan_section_id+'&new_display_order='+Math.max(0,display_order-1)+'&new_display_indent='+(display_indent-1)+'"'+'>&uarr;</a>';
    }
    if (display_order < tocSize) {
      //text += '<a href="index.php?current_page=marketing-plan&section='+marketing_plan_section_id+'&new_display_order='+(display_order+1)+'&new_display_indent='+(display_indent-1)+'"'+((ajax_on)?' onClick="fetchPage(\'marketing-plan&section='+marketing_plan_section_id+'&new_display_order='+(display_order+1)+'&new_display_indent='+(display_indent-1)+'\');return false;"':'')+'>&darr;</a>';
      text += '<a href="index.php?current_page=marketing-plan&section='+marketing_plan_section_id+'&new_display_order='+(display_order+1)+'&new_display_indent='+(display_indent-1)+'"'+'>&darr;</a>';
    }
    //text += '<a href="index.php?current_page=marketing-plan&section='+marketing_plan_section_id+'&new_display_order='+display_order+'&new_display_indent='+(display_indent)+'"'+((ajax_on)?' onClick="fetchPage(\'marketing-plan&section='+marketing_plan_section_id+'&new_display_order='+display_order+'&new_display_indent='+(display_indent)+'\');return false;"':'')+'>&rarr;</a>';
    text += '<a href="index.php?current_page=marketing-plan&section='+marketing_plan_section_id+'&new_display_order='+display_order+'&new_display_indent='+(display_indent)+'"'+'>&rarr;</a>';
    if ((display_indent-1) > 0) {
      //text += '<a href="index.php?current_page=marketing-plan&section='+marketing_plan_section_id+'&new_display_order='+display_order+'&new_display_indent='+Math.max(0,display_indent-2)+'"'+((ajax_on)?' onClick="fetchPage(\'marketing-plan&section='+marketing_plan_section_id+'&new_display_order='+display_order+'&new_display_indent='+Math.max(0,display_indent-2)+'\');return false;"':'')+'>&larr;</a>';
      text += '<a href="index.php?current_page=marketing-plan&section='+marketing_plan_section_id+'&new_display_order='+display_order+'&new_display_indent='+Math.max(0,display_indent-2)+'"'+'>&larr;</a>';
    }
    text += '<hr />';
    text += '<a href="index.php?current_page=marketing-plan&display_order='+(display_order)+'&display_indent='+display_indent+'">Add Subsection</a>';
    text += '<a href="javascript:void(0);"  onClick="tocAction(\'delete\','+marketing_plan_section_id+')">Delete</a>';
  } else {
    text += '<a href="index.php?current_page=marketing-plan&display_order='+(display_order)+'&display_indent='+display_indent+'">Add Subsection</a>';
  }

  document.getElementById('context_menu').style.display = "block";
  document.getElementById('context_menu').style.top = (mousey-10)+"px";
  document.getElementById('context_menu').style.left = (mousex-10)+"px";

  document.getElementById('context_menu').innerHTML = text;
  return false;
}
function clientTocContextMenu(client_id, store_id, marketing_plan_id, marketing_plan_section_id, display_order, display_indent, tocSize, section_status, current_section) {
  text = "";
  if (marketing_plan_section_id > 0) {
    if (display_order > 1) {
      //text += '<a href="index.php?current_page=clients&client_tab=marketing_plan&edit='+client_id+'&marketing_plan='+marketing_plan_id+'&store_id='+store_id+'&section='+marketing_plan_section_id+'&new_display_order='+Math.max(0,display_order-1)+'&new_display_indent='+(display_indent-1)+'"'+((ajax_on)?' onClick="fetchPage(\'clients&client_tab=marketing_plan&edit='+client_id+'&marketing_plan='+marketing_plan_id+'&store_id='+store_id+'&section='+marketing_plan_section_id+'&new_display_order='+Math.max(0,display_order-1)+'&new_display_indent='+(display_indent-1)+'\');return false;"':'')+'>&uarr;</a>';
      text += '<a href="index.php?current_page=clients&client_tab=marketing_plan&edit='+client_id+'&marketing_plan='+marketing_plan_id+'&store_id='+store_id+'&section='+marketing_plan_section_id+'&new_display_order='+Math.max(0,display_order-1)+'&new_display_indent='+(display_indent-1)+'"'+'>&uarr;</a>';
    }
    if (display_order < tocSize) {
      //text += '<a href="index.php?current_page=clients&client_tab=marketing_plan&edit='+client_id+'&marketing_plan='+marketing_plan_id+'&store_id='+store_id+'&section='+marketing_plan_section_id+'&new_display_order='+(display_order+1)+'&new_display_indent='+(display_indent-1)+'"'+((ajax_on)?' onClick="fetchPage(\'clients&client_tab=marketing_plan&edit='+client_id+'&marketing_plan='+marketing_plan_id+'&store_id='+store_id+'&section='+marketing_plan_section_id+'&new_display_order='+(display_order+1)+'&new_display_indent='+(display_indent-1)+'\');return false;"':'')+'>&darr;</a>';
      text += '<a href="index.php?current_page=clients&client_tab=marketing_plan&edit='+client_id+'&marketing_plan='+marketing_plan_id+'&store_id='+store_id+'&section='+marketing_plan_section_id+'&new_display_order='+(display_order+1)+'&new_display_indent='+(display_indent-1)+'"'+'>&darr;</a>';
    }
    //text += '<a href="index.php?current_page=clients&client_tab=marketing_plan&edit='+client_id+'&marketing_plan='+marketing_plan_id+'&store_id='+store_id+'&section='+marketing_plan_section_id+'&new_display_order='+display_order+'&new_display_indent='+(display_indent)+'"'+((ajax_on)?' onClick="fetchPage(\'clients&client_tab=marketing_plan&edit='+client_id+'&marketing_plan='+marketing_plan_id+'&store_id='+store_id+'&section='+marketing_plan_section_id+'&new_display_order='+display_order+'&new_display_indent='+(display_indent)+'\');return false;"':'')+'>&rarr;</a>';
    text += '<a href="index.php?current_page=clients&client_tab=marketing_plan&edit='+client_id+'&marketing_plan='+marketing_plan_id+'&store_id='+store_id+'&section='+marketing_plan_section_id+'&new_display_order='+display_order+'&new_display_indent='+(display_indent)+'"'+'>&rarr;</a>';
    if ((display_indent-1) > 0) {
      //text += '<a href="index.php?current_page=clients&client_tab=marketing_plan&edit='+client_id+'&marketing_plan='+marketing_plan_id+'&store_id='+store_id+'&section='+marketing_plan_section_id+'&new_display_order='+display_order+'&new_display_indent='+Math.max(0,display_indent-2)+'"'+((ajax_on)?' onClick="fetchPage(\'clients&client_tab=marketing_plan&edit='+client_id+'&marketing_plan='+marketing_plan_id+'&store_id='+store_id+'&section='+marketing_plan_section_id+'&new_display_order='+display_order+'&new_display_indent='+Math.max(0,display_indent-2)+'\');return false;"':'')+'>&larr;</a>';
      text += '<a href="index.php?current_page=clients&client_tab=marketing_plan&edit='+client_id+'&marketing_plan='+marketing_plan_id+'&store_id='+store_id+'&section='+marketing_plan_section_id+'&new_display_order='+display_order+'&new_display_indent='+Math.max(0,display_indent-2)+'"'+'>&larr;</a>';
    }
    text += '<hr />';
    text += '<a href="index.php?current_page=clients&edit='+client_id+'&marketing_plan='+marketing_plan_id+'&store_id='+store_id+'&client_tab=marketing_plan&display_order='+(display_order)+'&display_indent='+display_indent+'">Add Subsection</a>';

    if (section_status == 'Yes') {
      //text += '<a href="index.php?current_page=clients&client_tab=marketing_plan&edit='+client_id+'&marketing_plan='+marketing_plan_id+'&store_id='+store_id+'&section='+marketing_plan_section_id+'&new_status=inactive&return_to='+current_section+'"'+((ajax_on)?' onClick="fetchPage(\'clients&client_tab=marketing_plan&edit='+client_id+'&marketing_plan='+marketing_plan_id+'&store_id='+store_id+'&section='+marketing_plan_section_id+'&new_status=inactive&return_to='+current_section+'\');return false;"':'')+'>Deactivate</a>';
      text += '<a href="index.php?current_page=clients&client_tab=marketing_plan&edit='+client_id+'&marketing_plan='+marketing_plan_id+'&store_id='+store_id+'&section='+marketing_plan_section_id+'&new_status=inactive&return_to='+current_section+'"'+'>Deactivate</a>';
    } else {
      //text += '<a href="index.php?current_page=clients&client_tab=marketing_plan&edit='+client_id+'&marketing_plan='+marketing_plan_id+'&store_id='+store_id+'&section='+marketing_plan_section_id+'&new_status=active&return_to='+current_section+'"'+((ajax_on)?' onClick="fetchPage(\'clients&client_tab=marketing_plan&edit='+client_id+'&marketing_plan='+marketing_plan_id+'&store_id='+store_id+'&section='+marketing_plan_section_id+'&new_status=active&return_to='+current_section+'\');return false;"':'')+'>Activate</a>';
      text += '<a href="index.php?current_page=clients&client_tab=marketing_plan&edit='+client_id+'&marketing_plan='+marketing_plan_id+'&store_id='+store_id+'&section='+marketing_plan_section_id+'&new_status=active&return_to='+current_section+'"'+'>Activate</a>';
    }
  } else {
    text += '<a href="index.php?current_page=clients&edit='+client_id+'&marketing_plan='+marketing_plan_id+'&store_id='+store_id+'&client_tab=marketing_plan&display_order='+(display_order)+'&display_indent='+display_indent+'">Add Subsection</a>';
  }

  document.getElementById('context_menu').style.display = "block";
  document.getElementById('context_menu').style.top = (mousey-10)+"px";
  document.getElementById('context_menu').style.left = (mousex-10)+"px";

  document.getElementById('context_menu').innerHTML = text;
  return false;
}
function bodyClicked() {
  if (document.getElementById('context_menu')) {
    document.getElementById('context_menu').style.display = "none";
  }
}
function toggleToc() {
  if (document.getElementById('toc_nav_control').src.indexOf('toc_up') > -1) {
    //Switch to showing TOC
    document.getElementById('toc_nav_control').src = '../images/toc_dn.png';
    document.getElementById('marketing_plan_toc').style.display = 'block';
    document.getElementById('marketing_plan_page').className = 'show_toc';
    document.getElementById('marketing_plan_nav').className = 'show_toc';
  } else {
    //Switch to hiding TOC
    document.getElementById('toc_nav_control').src = '../images/toc_up.png';
    document.getElementById('marketing_plan_toc').style.display = 'none';
    document.getElementById('marketing_plan_page').className = 'hide_toc';
    document.getElementById('marketing_plan_nav').className = 'hide_toc';
  }
}
function toggleMainEdit() {
  return;
  if (document.getElementById('main_edit_nav_control').src.indexOf('main_edit_up') > -1) {
    //Switch to showing settings
    document.getElementById('main_edit_nav_control').src = '../images/main_edit_dn.png';
    document.getElementById('marketing_plan_settings').style.display = 'block';
    document.getElementById('client_marketing_plan_nav').style.display = 'none';
    document.getElementById('client_marketing_plan_main').style.display = 'none';
  } else {
    //Switch to hiding settings
    document.getElementById('main_edit_nav_control').src = '../images/main_edit_up.png';
    document.getElementById('marketing_plan_settings').style.display = 'none';
    document.getElementById('client_marketing_plan_nav').style.display = 'block';
    document.getElementById('client_marketing_plan_main').style.display = 'block';
  }
}
function toggleClientToc() {
  if (document.getElementById('toc_nav_control').src.indexOf('toc_up') > -1) {
    //Switch to showing TOC
    document.getElementById('toc_nav_control').src = '../images/toc_dn.png';
    document.getElementById('client_marketing_plan_toc').style.display = 'block';
    document.getElementById('client_marketing_plan_page').className = 'show_toc';
    document.getElementById('client_marketing_plan_nav').className = 'show_toc';
  } else {
    //Switch to hiding TOC
    document.getElementById('toc_nav_control').src = '../images/toc_up.png';
    document.getElementById('client_marketing_plan_toc').style.display = 'none';
    document.getElementById('client_marketing_plan_page').className = 'hide_toc';
    document.getElementById('client_marketing_plan_nav').className = 'hide_toc';
  }
}
function marketingPlanTab(active_tab) {
  if (active_tab == "adding") {
    alert("Section must be added first.");
    return;
  }
  if (active_tab.active_tab) {
    //For when page is returned via Ajax.
    active_tab = active_tab.active_tab;
  }
  tabs = new Array('content','links','files','options');
  for (i=0;i<tabs.length;i++) {
    if (active_tab == tabs[i]) {
      document.getElementById('marketing_plan_'+tabs[i]+'_tab').className = "selected_tab";
      document.getElementById('marketing_plan_'+tabs[i]+'_box').className = "show_box";
    } else {
      document.getElementById('marketing_plan_'+tabs[i]+'_tab').className = "";
      document.getElementById('marketing_plan_'+tabs[i]+'_box').className = "hide_box";
    }
  }
}
function clientMarketingPlanTab(active_tab) {
  if (active_tab == "adding") {
    alert("Section must be added first.");
    return;
  }
  if (active_tab.active_tab) {
    //For when page is returned via Ajax.
    active_tab = active_tab.active_tab;
  }
  tabs = new Array('content','links','files');
  for (i=0;i<tabs.length;i++) {
    if (active_tab == tabs[i]) {
      if (document.getElementById('client_marketing_plan_'+tabs[i]+'_tab')) {
      document.getElementById('client_marketing_plan_'+tabs[i]+'_tab').className = "selected_tab";
      }
      if (document.getElementById('client_marketing_plan_'+tabs[i]+'_box')) {
      document.getElementById('client_marketing_plan_'+tabs[i]+'_box').className = "show_box";
        }
    } else {
      if (document.getElementById('client_marketing_plan_'+tabs[i]+'_tab')) {
      document.getElementById('client_marketing_plan_'+tabs[i]+'_tab').className = "";
      }
      if (document.getElementById('client_marketing_plan_'+tabs[i]+'_box')) {
      document.getElementById('client_marketing_plan_'+tabs[i]+'_box').className = "hide_box";
    }
  }
}
}
function clientTab(active_tab) {
  if (active_tab == "adding") {
    alert("Client must be added first.");
    return;
  } else if (active_tab == "no-evaluation") {
    alert("Client does not have an evaluation on file.");
    return;
  }
  if (active_tab.active_tab) {
    //For when page is returned via Ajax.
    active_tab = active_tab.active_tab;
  }
  tabs = new Array('profile','stores','marketing_plan','invoices','notes','reports','files');
  if (document.getElementById('client_ll_checklist_tab')) {
    tabs[tabs.length] = 'll_checklist';
  }
  for (i=0;i<tabs.length;i++) {
    if (active_tab == tabs[i]) {
      document.getElementById('client_'+tabs[i]+'_tab').className = "selected_tab";
      document.getElementById('client_'+tabs[i]+'_box').className = "show_box";
    } else {
      document.getElementById('client_'+tabs[i]+'_tab').className = "";
      document.getElementById('client_'+tabs[i]+'_box').className = "hide_box";
    }
  }
}
function vendorTab(active_tab) {
  if (active_tab == "adding") {
    alert("Vendor must be added first.");
    return;
  }
  if (active_tab.active_tab) {
    //For when page is returned via Ajax.
    active_tab = active_tab.active_tab;
  }
  tabs = new Array('profile','programs','clients');
  for (i=0;i<tabs.length;i++) {
    if (active_tab == tabs[i]) {
      document.getElementById('vendor_'+tabs[i]+'_tab').className = "selected_tab";
      document.getElementById('vendor_'+tabs[i]+'_box').className = "show_box";
    } else {
      document.getElementById('vendor_'+tabs[i]+'_tab').className = "";
      document.getElementById('vendor_'+tabs[i]+'_box').className = "hide_box";
    }
  }
}
function agentTab(active_tab) {
  if (active_tab == "adding") {
    alert("Agent must be added first.");
    return;
  }
  if (active_tab.active_tab) {
    //For when page is returned via Ajax.
    active_tab = active_tab.active_tab;
  }
  tabs = new Array('profile','clients','leads','files');
  for (i=0;i<tabs.length;i++) {
    if (active_tab == tabs[i]) {
      document.getElementById('agent_'+tabs[i]+'_tab').className = "selected_tab";
      document.getElementById('agent_'+tabs[i]+'_box').className = "show_box";
    } else {
      document.getElementById('agent_'+tabs[i]+'_tab').className = "";
      document.getElementById('agent_'+tabs[i]+'_box').className = "hide_box";
    }
  }
}
function affTab(active_tab) {
  if (active_tab == "adding") {
    alert("Affiliate must be added first.");
    return;
  }
  if (active_tab.active_tab) {
    //For when page is returned via Ajax.
    active_tab = active_tab.active_tab;
  }
  tabs = new Array('profile','referrals','files');
  for (i=0;i<tabs.length;i++) {
    if (active_tab == tabs[i]) {
      document.getElementById('aff_'+tabs[i]+'_tab').className = "selected_tab";
      document.getElementById('aff_'+tabs[i]+'_box').className = "show_box";
    } else {
      document.getElementById('aff_'+tabs[i]+'_tab').className = "";
      document.getElementById('aff_'+tabs[i]+'_box').className = "hide_box";
    }
  }
}
function productTab(active_tab) {
  if (active_tab == "adding") {
    alert("Product must be added first.");
    return;
  }
  if (active_tab.active_tab) {
    //For when page is returned via Ajax.
    active_tab = active_tab.active_tab;
  }
  tabs = new Array('details','sales_pages');
  for (i=0;i<tabs.length;i++) {
    if (active_tab == tabs[i]) {
      document.getElementById('product_'+tabs[i]+'_tab').className = "selected_tab";
      document.getElementById('product_'+tabs[i]+'_box').className = "show_box";
    } else {
      document.getElementById('product_'+tabs[i]+'_tab').className = "";
      document.getElementById('product_'+tabs[i]+'_box').className = "hide_box";
    }
  }
}
function optionsTab(active_tab) {
  if (active_tab == "adding") {
    alert("Program must be added first.");
    return;
  }
  if (active_tab.active_tab) {
    //For when page is returned via Ajax.
    active_tab = active_tab.active_tab;
  }
  tabs = new Array('settings','products');
  for (i=0;i<tabs.length;i++) {
    if (active_tab == tabs[i]) {
      document.getElementById('vendor_programs_'+tabs[i]+'_tab').className = "selected_tab";
      document.getElementById('vendor_programs_'+tabs[i]+'_box').className = "show_box";
    } else {
      document.getElementById('vendor_programs_'+tabs[i]+'_tab').className = "";
      document.getElementById('vendor_programs_'+tabs[i]+'_box').className = "hide_box";
    }
  }
}
function showBillingType(source,program_product_id) {
  if (source.options[source.options.selectedIndex].value == "Per Impression") {
    document.getElementById('billing_type_options_impression['+program_product_id+']').style.display = 'block';
    document.getElementById('billing_type_options_flat['+program_product_id+']').style.display = 'none';
    document.getElementById('billing_type_options_monthly['+program_product_id+']').style.display = 'none';
  } else if (source.options[source.options.selectedIndex].value == "Flat") {
    document.getElementById('billing_type_options_impression['+program_product_id+']').style.display = 'none';
    document.getElementById('billing_type_options_flat['+program_product_id+']').style.display = 'block';
    document.getElementById('billing_type_options_monthly['+program_product_id+']').style.display = 'none';
  } else if (source.options[source.options.selectedIndex].value == "Monthly") {
    document.getElementById('billing_type_options_impression['+program_product_id+']').style.display = 'none';
    document.getElementById('billing_type_options_flat['+program_product_id+']').style.display = 'none';
    document.getElementById('billing_type_options_monthly['+program_product_id+']').style.display = 'block';
  }
}
function showKeysBox() {
  document.getElementById('magic_keys_popup').style.display = "block";
  document.getElementById('magic_keys_popup').style.top = (mousey-50)+"px";
  document.getElementById('magic_keys_popup').style.left = (mousex-50)+"px";

  //document.getElementById('magic_keys_popup').innerHTML = text;
}
function showFileUploadProgress() {
  document.getElementById("files_uploading").style.display = 'block';
  document.getElementById("files_uploading").style.top = "150px";//((getHeight()-200)*.5)+'px';
  document.getElementById("files_uploading").style.width = (getWidth()-300)+'px';
  document.getElementById("files_uploading").style.height = (getHeight()-150)+'px';
  document.getElementById("files_uploading").style.left = '150px';
  return true;
}
function showURL(targetURL) {
  if (targetURL.substring(0,6) != 'mailto' && targetURL.substring(0,4) != 'http' ) {
    targetURL = 'http://'+targetURL;
  }
  window.open(targetURL,'_blank');
}

function emailPreview(source) {
  document.getElementById('fck_preview_'+source).style.display="block";
  document.getElementById('fck_edit_'+source).style.display="none";
  document.getElementById('fck_edit_text_'+source).style.display="none";

  document.getElementById('fck_preview_nav_'+source).className="fck_selected";
  document.getElementById('fck_edit_nav_'+source).className="fck_not_selected";
  document.getElementById('fck_edit_text_nav_'+source).className="fck_not_selected";

  var oEditor = FCKeditorAPI.GetInstance(source);
  document.getElementById('fck_preview_'+source).innerHTML = oEditor.GetXHTML(false);
}
var emailEdit_flag = false;
function emailEdit(source) {
  document.getElementById('fck_preview_'+source).style.display="none";
  document.getElementById('fck_edit_'+source).style.display="block";
  document.getElementById('fck_edit_text_'+source).style.display="none";

  document.getElementById('fck_preview_nav_'+source).className="fck_not_selected";
  document.getElementById('fck_edit_nav_'+source).className="fck_selected";
  document.getElementById('fck_edit_text_nav_'+source).className="fck_not_selected";

  if (!emailEdit_flag) {
    var oFCKeditor = new FCKeditor('email_body');
    oFCKeditor.BasePath = "../resources/fckeditor/";
    oFCKeditor.Height = "97%";
    oFCKeditor.Width = "100%";
    oFCKeditor.ReplaceTextarea();
    emailEdit_flag = true;
  }
}
function emailTextEdit(source) {
  convertedToText = 1;
  document.getElementById('fck_preview_'+source).style.display="none";
  document.getElementById('fck_edit_'+source).style.display="none";
  document.getElementById('fck_edit_text_'+source).style.display="block";

  document.getElementById('fck_preview_nav_'+source).className="fck_not_selected";
  document.getElementById('fck_edit_nav_'+source).className="fck_not_selected";
  document.getElementById('fck_edit_text_nav_'+source).className="fck_selected";

  var oEditor = FCKeditorAPI.GetInstance(source);
  document.getElementById('email_text_body').value = htmlToText(oEditor.GetXHTML(false));
  if (document.getElementById('email_text_body').value == "null") {
    document.getElementById('email_text_body').value = "";
  }
}
function htmlToText(initial_text) {
  initial_text = initial_text.replace(/ *<\/p>/g,"\n\n");
  initial_text = initial_text.replace(/<li>/g,"*");
  initial_text = initial_text.replace(/&nbsp;/g," ");
  initial_text = initial_text.replace(/ <hr/g,"------------------------------------------<");

  //Taken from http://www.ozoneasylum.com/5782
  var newString = "";
  var inTag = false;
  for(var i = 0; i < initial_text.length; i++) {
    if(initial_text.charAt(i) == '<') {
      if (i > 2 && initial_text.charAt(i-1) == " " && (initial_text.charAt(i-2) == ">" || initial_text.charAt(i-2) == "\n")) {
        //Remove initial white space
        newString = newString.substring(0,newString.length-1);
      }
      inTag = true;
    }
    if(initial_text.charAt(i) == '>') {
      inTag = false;
      i++;
    }

    if(!inTag) newString += initial_text.charAt(i);
  }
  return newString;
}
function updateEmailEditor() {
  document.getElementById("email_product_box").style.display = "none";
  if (document.getElementById("email_type").options[document.getElementById("email_type").options.selectedIndex].value == "Product Not Available Email" || document.getElementById("email_type").options[document.getElementById("email_type").options.selectedIndex].value == "Product Purchased Email" || document.getElementById("email_type").options[document.getElementById("email_type").options.selectedIndex].value == "New LoyaltyLock Client" || document.getElementById("email_type").options[document.getElementById("email_type").options.selectedIndex].value == "New Client Welcome Email" || document.getElementById("email_type").options[document.getElementById("email_type").options.selectedIndex].value == "Invoice Notification") {
    document.getElementById("email_product_box").style.display = "block";
    document.getElementById("email_optgroup_label").innerHTML = "";
  } else {
    document.getElementById("email_optgroup_label").innerHTML = document.getElementById("email_type").options[document.getElementById("email_type").options.selectedIndex].parentNode.label;
  }
}
var convertedToText = 0;
function validateEmailConversion() {
  if (convertedToText == 0) {
    emailTextEdit("email_body");
  }
  return true;
}
function showEmailTokens() {
  document.getElementById("email_tokens_box").style.display = "block";
  document.getElementById("email_tokens_box").style.top = "0px";
  document.getElementById("email_tokens_box").style.left = (getWidth()-500)+"px";
}
function programProductEdit(program_product_id) {
  program_product_boxes = document.getElementById("program_product_list").getElementsByTagName('div');

  for (i=0;i<program_product_boxes.length;i++) {
    if(program_product_boxes[i].className == 'program_product_edit') {
      document.getElementById(program_product_boxes[i].id).style.display = 'none';
    }
  }
  document.getElementById('product['+program_product_id+']_box').style.display = 'block';
}
function toggleFullScreenBudget() {
  if (document.getElementById('budget_full_screen_control').style.position == 'fixed') {
    document.getElementById('budget_full_screen_control').style.position = 'static';
    document.getElementById('budget_full_screen_control').style.top = '';
    document.getElementById('budget_full_screen_control').style.left = '';
  } else {
    document.getElementById('budget_full_screen_control').style.position = 'fixed';
    document.getElementById('budget_full_screen_control').style.top = '0px';
    document.getElementById('budget_full_screen_control').style.left = '0px';
    document.getElementById('budget_full_screen_control').style.width = '100%';
    document.getElementById('budget_full_screen_control').style.height = '100%';
  }
}
function toggleFullScreenGANTT() {
  if (document.getElementById('gantt_full_screen_control').style.position == 'fixed') {
    document.getElementById('gantt_full_screen_control').style.position = 'static';
    document.getElementById('gantt_full_screen_control').style.top = '';
    document.getElementById('gantt_full_screen_control').style.left = '';
  } else {
    document.getElementById('gantt_full_screen_control').style.position = 'fixed';
    document.getElementById('gantt_full_screen_control').style.top = '0px';
    document.getElementById('gantt_full_screen_control').style.left = '0px';
    document.getElementById('gantt_full_screen_control').style.width = '100%';
    document.getElementById('gantt_full_screen_control').style.height = '100%';
  }
}
function toggleFullScreenProgramProductEditor() {
  if (document.getElementById('program_product_editor_full_screen_control').style.position == 'fixed') {
    document.getElementById('program_product_editor_full_screen_control').style.position = 'static';
    document.getElementById('program_product_editor_full_screen_control').style.top = '';
    document.getElementById('program_product_editor_full_screen_control').style.left = '';
  } else {
    document.getElementById('program_product_editor_full_screen_control').style.position = 'fixed';
    document.getElementById('program_product_editor_full_screen_control').style.top = '0px';
    document.getElementById('program_product_editor_full_screen_control').style.left = '0px';
    document.getElementById('program_product_editor_full_screen_control').style.width = '100%';
    document.getElementById('program_product_editor_full_screen_control').style.height = '100%';
  }
}
function updateProgramProductEditorLineTotal(program_product_identifier, program_product_id) {
  qty = parseFloat(document.getElementById('program_product_period['+program_product_id+'][quantity]').value.replace(/,/,''));
  fee = parseFloat(document.getElementById('program_product_period['+program_product_id+'][fee]').value.replace(/,/,''));

  line_total = "" + Math.round(qty*fee*100)/100; //empty string addition casts result as a string
  //Pad zeroes to right of decimal
  decimal_index = line_total.indexOf('.');
  if (decimal_index == -1) {
    line_total += '.';
    decimal_index = line_total.length-1;
  }
  if (decimal_index > (line_total.length-3)) {
    line_total += '0';
  }
  if (decimal_index > line_total.length-3) {
    line_total += '0';
  }
  //Now, add commas in in the right spot.
  line_total_w_comma = '';
  for(counter=line_total.length-4;counter>-1;counter--) {
    line_total_w_comma = line_total[counter]+line_total_w_comma;
    if ((line_total.length-counter)%3 == 0 && (counter-1) > -1) {
      line_total_w_comma = ","+line_total_w_comma;
    }
  }
  line_total = line_total_w_comma + "." + line_total[line_total.length-2] + line_total[line_total.length-1];

  document.getElementById('program_product_period_cost_'+program_product_identifier).innerHTML = '$' + line_total;
}
function updateProgramProductEditor(program_product_identifier, program_product_id) {
  //Need to update display for Program, Vendor, and Billing
  if (document.getElementById('program_product_period_program_'+program_product_identifier) && document.getElementById('program_product_period_vendor_'+program_product_identifier) && document.getElementById('program_product_period_billing_'+program_product_identifier)) {
    if (document.getElementById('program_product_period['+program_product_id+'][product]').options.selectedIndex == 0) {
      document.getElementById('program_product_period_program_'+program_product_identifier).innerHTML = "N/A";
      document.getElementById('program_product_period_vendor_'+program_product_identifier).innerHTML = "N/A";
      document.getElementById('program_product_period_billing_'+program_product_identifier).innerHTML = "N/A";

      document.getElementById('program_product_period_program_'+program_product_identifier).innerHTML = '';
      document.getElementById('program_product_period_vendor_'+program_product_identifier).innerHTML = '';
      document.getElementById('program_product_period_billing_'+program_product_identifier).innerHTML = '';
      document.getElementById('program_product_period['+program_product_id+'][start_date]').value = '';
      document.getElementById('program_product_period['+program_product_id+'][end_date]').value = '';
      document.getElementById('program_product_period['+program_product_id+'][mail_date]').value = '';
      document.getElementById('program_product_period['+program_product_id+'][quantity]').value = '';
      document.getElementById('program_product_period['+program_product_id+'][cost_per_unit]').value = '';
      document.getElementById('program_product_period['+program_product_id+'][fee]').value = '';
      document.getElementById('program_product_period['+program_product_id+'][period]').value = '';
      document.getElementById('program_product_period['+program_product_id+'][mail_date]').disabled = true;
      document.getElementById('program_product_period['+program_product_id+'][period]').disabled = true;

    } else {
      selected_index_value = document.getElementById('program_product_period['+program_product_id+'][product]').options[document.getElementById('program_product_period['+program_product_id+'][product]').options.selectedIndex].value;
      //Determine if __ is part of selected_index_value and update (is zone iff __ is present)
      split_index_value = selected_index_value.split('__');
      if (split_index_value.length > 1 || program_product_data[selected_index_value].zones == 'Yes') {
        selected_index_value = split_index_value[0];
        selected_index_zone_row = split_index_value[1];
        document.getElementById('program_product_period['+program_product_id+'][mail_date]').disabled = false;
      } else {
        //deactivate mail options
        document.getElementById('program_product_period['+program_product_id+'][mail_date]').disabled = true;
      }

      if (typeof program_product_data[selected_index_value].program_group != 'undefined') {
        document.getElementById('program_product_period_program_'+program_product_identifier).innerHTML = program_product_data[selected_index_value].program_group;
      }
      if (typeof program_product_data[selected_index_value].vendor_name != 'undefined') {
        document.getElementById('program_product_period_vendor_'+program_product_identifier).innerHTML = program_product_data[selected_index_value].vendor_name;
      }
      if (typeof program_product_data[selected_index_value].billing_type != 'undefined') {
        if (program_product_data[selected_index_value].billing_type == 'Monthly') {
          document.getElementById('program_product_period['+program_product_id+'][period]').disabled = false;
          document.getElementById('program_product_period_billing_'+program_product_identifier).innerHTML = 'Periodic';
        } else {
          document.getElementById('program_product_period_billing_'+program_product_identifier).innerHTML = program_product_data[selected_index_value].billing_type;
          document.getElementById('program_product_period['+program_product_id+'][period]').disabled = true;
        }
      }
      if (program_product_data[selected_index_value].zones == 'Yes') {
        document.getElementById('program_product_period['+program_product_id+'][zone_name]').disabled = false;
      } else {
        document.getElementById('program_product_period['+program_product_id+'][zone_name]').disabled = true;
        document.getElementById('program_product_period['+program_product_id+'][zone_name]').selectedIndex = 0;
      }
      if (typeof program_product_data[selected_index_value].start_date != 'undefined') {
        document.getElementById('program_product_period['+program_product_id+'][start_date]').value = program_product_data[selected_index_value].start_date;
      }
      if (typeof program_product_data[selected_index_value].end_date != 'undefined') {
        document.getElementById('program_product_period['+program_product_id+'][end_date]').value = program_product_data[selected_index_value].end_date;
      }
      if (typeof program_product_data[selected_index_value].mail_date != 'undefined') {
        document.getElementById('program_product_period['+program_product_id+'][mail_date]').value = program_product_data[selected_index_value].mail_date;
      }
      if (typeof program_product_data[selected_index_value].quantity != 'undefined') {
        if (program_product_data[selected_index_value].zones == 'Yes' && document.getElementById('program_product_period['+program_product_id+'][zone_name]').options.selectedIndex != 0) {
          //alert(document.getElementById('program_product_period['+program_product_id+'][zone_name]').options[document.getElementById('program_product_period['+program_product_id+'][zone_name]').options.selectedIndex].value);
          document.getElementById('program_product_period['+program_product_id+'][quantity]').value = zone_count_data[document.getElementById('program_product_period['+program_product_id+'][zone_name]').options[document.getElementById('program_product_period['+program_product_id+'][zone_name]').options.selectedIndex].value];
        } else {
        document.getElementById('program_product_period['+program_product_id+'][quantity]').value = program_product_data[selected_index_value].quantity;
        }
      }
      if (typeof program_product_data[selected_index_value].cost_per_unit != 'undefined') {
        document.getElementById('program_product_period['+program_product_id+'][cost_per_unit]').value = program_product_data[selected_index_value].cost_per_unit;
      }
      if (typeof program_product_data[selected_index_value].fee != 'undefined') {
        document.getElementById('program_product_period['+program_product_id+'][fee]').value = program_product_data[selected_index_value].fee;
      }
      if (typeof program_product_data[selected_index_value].period != 'undefined') {
        document.getElementById('program_product_period['+program_product_id+'][period]').value = program_product_data[selected_index_value].period;
      }
    }
    updateProgramProductEditorLineTotal(program_product_identifier, program_product_id);
  }
}

function showAddProgramProductBox() {
  document.getElementById('program_product_manager_box').style.display = 'block';
}
function loadForm(source, client_id) {
  if (source.options[source.options.selectedIndex].value > -1) {
    location.href = 'index.php?current_page=form-editor&form_id='+source.options[source.options.selectedIndex].value+'&client_id='+client_id;
  }
}
function createCoupon() {
  document.getElementById('coupon_creator_box').style.display = 'block';
  document.getElementById('coupon_creator_box').style.left = Math.floor(.5*(getWidth() - 400))+'px';
  document.getElementById('coupon_creator_iframe').style.display = 'block';
  document.getElementById('coupon_creator_iframe').style.left = Math.floor(.5*(getWidth() - 400) - 300)+'px';
  resizeCouponWindow();
}
function resizeCouponWindow() {
  document.getElementById('coupon_creator_iframe').style.width=(parseInt(document.getElementById('image_width').value)+35)+'px';
  document.getElementById('coupon_creator_iframe').style.left=Math.max(15,parseInt(document.getElementById('coupon_creator_box').style.left) - (parseInt(document.getElementById('image_width').value)+55))+'px';
  if (parseInt(document.getElementById('coupon_creator_iframe').style.left) == 15) {
    document.getElementById('coupon_creator_box').style.left = (parseInt(document.getElementById('coupon_creator_iframe').style.left) + parseInt(document.getElementById('coupon_creator_iframe').style.width) + 20) + "px";
  }
}
function updateMailDate(source, target_id) {
  if (typeof(target_id) == 'undefined') return;
  mailing_date = Date.parse(source.value);
  start_date_milli = mailing_date - 1000*60*60*24*5;
  end_date_milli = mailing_date + 1000*60*60*24*5;
  start_date = new Date();
  start_date.setTime(start_date_milli);
  end_date = new Date();
  end_date.setTime(end_date_milli);
  document.getElementById('program_product_period['+target_id+'][start_date]').value = (start_date.getMonth() + 1) + "/" + start_date.getDate() + "/" + start_date.getFullYear();
  document.getElementById('program_product_period['+target_id+'][end_date]').value = (end_date.getMonth() + 1) + "/" + end_date.getDate() + "/" + end_date.getFullYear();
}
function createCLVToken() {
  document.getElementById('clv_token_creator').style.display = 'block';
}
function updateCLVToken() {
  if (document.getElementById('clv_lifetime').value.length == 0 || document.getElementById('clv_yearly_purchases').value.length == 0 || document.getElementById('clv_avg_purchase').value.length == 0 || document.getElementById('clv_avg_margin').value.length == 0) {
    return;
  }
  token = '#CLV__';
  token += document.getElementById('clv_lifetime').value + '__';
  token += document.getElementById('clv_yearly_purchases').value + '__';
  token += document.getElementById('clv_avg_purchase').value + '__';
  token += document.getElementById('clv_avg_margin').value;
  document.getElementById('clv_token').value = token + '#';
}
function setDistrictsEntryForm() {
  if (document.getElementById('parent_agent_id').options.selectedIndex > 0) {
    document.getElementById('district_input_box').style.display = 'block';
  } else {
    document.getElementById('district_input_box').style.display = 'none';
  }
}
function toggleAgentLeadBar(client_id,target_id_num) {
  if (document.getElementById('lead_box_details_'+client_id+'_'+target_id_num).style.display != 'block') {
    document.getElementById('lead_box_details_'+client_id+'_'+target_id_num).style.display = 'block';
  } else {
    document.getElementById('lead_box_details_'+client_id+'_'+target_id_num).style.display = 'none';
  }
}
function adminPermissionsCheckboxToggle(column, toggle_type, source) {
  var inputs = document.getElementById('admin_permissions_form').getElementsByTagName('INPUT');
  if (toggle_type == 'check') {
    if (source.checked) {
      for (i=0;i<inputs.length;i++) {
        if (inputs[i].name.length > 0) {
          if (inputs[i].type == "checkbox") {
            cpRegEx = new RegExp(column);
            if (column == 'all' || inputs[i].name.search(cpRegEx) != -1) {
              inputs[i].checked = 1;
              inputs[i].title = "["+column +"]\n"+inputs[i].name+inputs[i].name.search(cpRegEx);
            }
          }
        }
      }
    } else {
      for (i=0;i<inputs.length;i++) {
        if (inputs[i].name.length > 0) {
          if (inputs[i].type == "checkbox") {
            cpRegEx = new RegExp(column);
            if (column == 'all' || inputs[i].name.search(cpRegEx) != -1) {
              inputs[i].checked = 0;
              inputs[i].title = "["+column +"]\n"+inputs[i].name+inputs[i].name.search(cpRegEx);
            }
          }
        }
      }
    }
  } else {
    for (i=0;i<inputs.length;i++) {
      if (inputs[i].name.length > 0) {
        if (inputs[i].type == "checkbox") {
          cpRegEx = new RegExp(column);
          if (column == 'all' || inputs[i].name.search(cpRegEx) != -1) {
            inputs[i].checked = !inputs[i].checked;
          }
        }
      }
    }
  }
}
function sessionAlive(returnVal) {
  //Re-do in 5 minutes
  setTimeout("ajaxSend('index.php','action=stay_alive','GET');",300000);
}
onLoadCalls.push(new onLoadCall('sessionAlive',''));

var activeLoginTarget = '';

function flashToHtmlPage(code_phrase) {
  if (code_phrase == 'home') {
    location.href='index.php?page='+code_phrase;
  } else {
    if (location.href.search(/admin/) > -1) {
      location.href='../admin_old/index.php?current_page='+code_phrase;
    } else if (location.href.search(/agent/) > -1) {
      location.href='index.php?page='+code_phrase;
    }
  }
}

function yuiNavigation(p_sType, p_aArgs, p_oValue) {
  // ../admin_old/
  if (p_oValue.substr(0,13) == '../admin_old/') {
    location.href = p_oValue;
  } else {
    location.href = "index.php?page=" + p_oValue;
  }
}
function tableDate(oData) {
  if (oData.length > 0) {
    return new Date(oData);
  } else {
    return null;
  }
}

onLoadCalls.push(new onLoadCall('customInitializePage',''));
function toggleSearchBox() {
  if (document.getElementById('search_box').className == "closed") {
    document.getElementById('search_box').className = "open";
  } else {
    document.getElementById('search_box').className = "closed";
  }
}function checkSearchResults() {
  //alert('Got to checkSearchResults');
}
var inverse_payment_box_conversion = {'eft':'cc', 'cc':'eft'};
function showPaymentMethod(method) {
  document.getElementById('pay_by_'+method+'_box').style.display='block';
  document.getElementById('pay_by_'+inverse_payment_box_conversion[method]+'_box').style.display='none';
}
//See agent/includes/pages/process/add-client.php (search for $allowed_products)

var addl_cards = {'addl_cards_4_1':new Array(), 'addl_cards_4_4':new Array()};
addl_cards.addl_cards_4_1[0] = new AdditionalCard(100,249,.95);
addl_cards.addl_cards_4_1[1] = new AdditionalCard(250,499,.85);
addl_cards.addl_cards_4_1[2] = new AdditionalCard(500,999,.75);
addl_cards.addl_cards_4_1[3] = new AdditionalCard(1000,1999,.65);
addl_cards.addl_cards_4_1[4] = new AdditionalCard(2000,2999,.55);
addl_cards.addl_cards_4_1[5] = new AdditionalCard(3000,4999,.45);
addl_cards.addl_cards_4_1[6] = new AdditionalCard(5000,9999,.35);
addl_cards.addl_cards_4_1[7] = new AdditionalCard(10000,10000000,.29);
/*
addl_cards.addl_cards_4_4[0] = new AdditionalCard(100,249,1.45);
addl_cards.addl_cards_4_4[1] = new AdditionalCard(250,499,1.25);
addl_cards.addl_cards_4_4[2] = new AdditionalCard(500,999,1.05);
addl_cards.addl_cards_4_4[3] = new AdditionalCard(1000,1999,.85);
addl_cards.addl_cards_4_4[4] = new AdditionalCard(2000,2999,.70);
addl_cards.addl_cards_4_4[5] = new AdditionalCard(3000,4999,.55);
addl_cards.addl_cards_4_4[6] = new AdditionalCard(5000,9999,.45);
*/
function updateServiceFeeTable(source) {
  document.getElementById(source).value = parseInt(document.getElementById(source).value);
  if (document.getElementById(source).value == 'NaN') {
    document.getElementById(source).value = 0;
  }
  var display_value = '$0.00';
  var source_val = document.getElementById(source).value;
  var discount_amount = 0;
  switch (source) {
    case 'initial_terminal':
      display_value = '$'+addCommas((source_val * 99).toFixed(2));
      break;
    case 'additional_terminals':
      display_value = '$'+addCommas((source_val * 225).toFixed(2));
      break;
    case 'addl_cards_4_1':
    case 'addl_cards_4_4':
      for(var i=0;i<8;i++) {
        if (addl_cards[source][i].minimum <= source_val && source_val <= addl_cards[source][i].maximum) {
          document.getElementById(source+'_per_unit').innerHTML = '$'+addCommas((addl_cards[source][i].per_unit).toFixed(2));
          display_value = '$'+addCommas((addl_cards[source][i].per_unit * source_val).toFixed(2));
          break;
        }
      }
      if (display_value == '$0.00' && source_val > 0) {
        if (source_val > 10000000) {
          display_value = '<span style="color:#ff0000;"><blink>&mdash; CALL &mdash;</blink></span>';
        } else {
          display_value = '<span style="color:#ff0000;"><blink>100 Min</blink></span>';
        }
        document.getElementById(source).value = 0;
        setTimeout('updateServiceFeeTable("' + source + '");',5000);
      }
      //Update discount

      if (parseInt(document.getElementById(source).value) >= 250) {
        //Discount
        //discount_amount = addl_cards[source][i].per_unit*100;

        document.getElementById('discount_label').innerHTML = 'Loyalty Lock 100 Card Credit';
        document.getElementById('discount_quantity').innerHTML = '100';
        document.getElementById('discount_per_unit').innerHTML = '- $' + addl_cards[source][i].per_unit.toFixed(2);
        document.getElementById('discount_line_total').innerHTML = '- $' + addCommas((addl_cards[source][i].per_unit*100).toFixed(2));
      } else {
        //No discount
        document.getElementById('discount_label').innerHTML = '&nbsp;';
        document.getElementById('discount_quantity').innerHTML = '&nbsp;';
        document.getElementById('discount_per_unit').innerHTML = '&nbsp;';
        document.getElementById('discount_line_total').innerHTML = '&nbsp;';
      }

      break;
  }

  discount_amount = parseFloat(document.getElementById('discount_line_total').innerHTML.replace(/[^0-9\.]/g,''));

  if (isNaN(discount_amount)) {
    discount_amount = 0;
  }

  document.getElementById(source+'_line_total').innerHTML = display_value;

  //Calculate form total (DOES NOT ACCOUNT FOR ADDITIONAL CARDS)
  document.getElementById('form_total').innerHTML = '$' + addCommas((parseInt(document.getElementById('additional_terminals').value) * 225 + parseInt(document.getElementById('initial_terminal').value) * 99 + parseFloat(document.getElementById('addl_cards_4_1_line_total').innerHTML.substr(1).replace(/,/,'')) - discount_amount).toFixed(2));
}
function toggleInitialTerminal() {
  if (document.getElementById('toggle_initial_terminal_deposit').checked) {
    //Remove 99 fee
    document.getElementById('initial_terminal').value = 0;
    document.getElementById('transaction_fee_text').style.display = 'none';
  } else {
    //Add 99 fee
    document.getElementById('initial_terminal').value = 1;
    document.getElementById('transaction_fee_text').style.display = 'inline';
  }
  updateServiceFeeTable('initial_terminal');
}
function AdditionalCard(min, max, cost) {
  this.minimum = min;
  this.maximum = max;
  this.per_unit = cost;
}
function addCommas(nStr) {
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  x2 = x2.length == 2 ? x2 + '0' : x2;
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  }
  return x1 + x2;
}
var new_fees = {'dynamic_monthly_fee':'197', 'dynamic_trans_fee':'10'};
var mousex, mousey;
function dynamicCM(source_obj) {
  if (document.getElementById(source_obj).innerHTML == new_fees[source_obj]) return true;

  document.getElementById('fees_context_menu').style.display="block";
  document.getElementById('fees_context_menu').style.top = (mousey+10)+"px";
  document.getElementById('fees_context_menu').style.left = (mousex-10)+"px";
  document.getElementById('fees_context_menu').innerHTML = '<div onClick="document.getElementById(\'' + source_obj + '\').innerHTML = new_fees[\'' + source_obj + '\']; document.getElementById(\'fees_context_menu\').style.display=\'none\';">Agent Override</div>';
  return false;
}
var last_checked_availability = '';
function checkAvailability() {
  return;
  var current_availability_check = document.getElementById('restaurant_type').options[document.getElementById('restaurant_type').options.selectedIndex].value+','+document.getElementById('street_address_line_1').value + ', ' + document.getElementById('city').value + ' ' + document.getElementById('state').options[document.getElementById('state').options.selectedIndex].value + ' ' + document.getElementById('zip').value;

  if (document.getElementById('restaurant_type').options.selectedIndex > 0 && document.getElementById('street_address_line_1').value.length > 0 && document.getElementById('zip').value.length > 0 && document.getElementById('city').value.length > 0 && last_checked_availability != current_availability_check) {
    last_checked_availability = current_availability_check;
    //Need to check message
    document.getElementById('availability_message').innerHTML = '';
    ajaxSend('../agent-map/index.php','quick_check=true&show_potential_conflicts=Yes&restaurant_type='+encodeURI(document.getElementById('restaurant_type').options[document.getElementById('restaurant_type').options.selectedIndex].value)+'&manual_addresses[0][street_address]='+encodeURI(document.getElementById('street_address_line_1').value)+'&manual_addresses[0][zip]='+encodeURI(document.getElementById('zip').value),'POST');
  }
}
function setAvailabilityMessage(return_response) {
  var html_output = '<h4 style="text-align:center;">Automated Zone Availability Check</h4>';
  switch (return_response.display_message) {
    case 'n_a':
      html_output += '<img src="../agent-map/marker-n_a.png" height="20"/> An automated check of this address indicates that this location may or may not be available or that a temporary hold is in place. Please contact the office...';
      break;
    case 'ok':
      html_output += '<img src="../agent-map/marker-ok.png" height="20"/> An automated check of this address indicates that this address is currently available for protection!';
      break;
  }

  var form_output = '<input type="hidden" name="show_potential_conflicts" value="Yes" /> <input type="hidden" name="ok_draw_circle" value="Yes" /> <input type="hidden" name="ok_radii" value="' + return_response.ok_radii + '" /> <input type="hidden" name="forced_radii" value="" />';


    form_output += '<input type="hidden" name="active_restaurant_type[]" value="' + document.getElementById("restaurant_type").options[document.getElementById("restaurant_type").options.selectedIndex].value + '" />';
    /*
    form_output += '<input type="hidden" name="active_restaurant_type[]" value="American Casual" />';
    form_output += '<input type="hidden" name="active_restaurant_type[]" value="BBQ" />';
    form_output += '<input type="hidden" name="active_restaurant_type[]" value="Breakfast and Bakery" />';
    form_output += '<input type="hidden" name="active_restaurant_type[]" value="Bar and Grill" />';
    form_output += '<input type="hidden" name="active_restaurant_type[]" value="Coffee House" />';
    form_output += '<input type="hidden" name="active_restaurant_type[]" value="Sandwich/Sub/Deli" />';
    form_output += '<input type="hidden" name="active_restaurant_type[]" value="Fast Food" />';
    form_output += '<input type="hidden" name="active_restaurant_type[]" value="Italian" />';
    form_output += '<input type="hidden" name="active_restaurant_type[]" value="Spanish/Mexican/Tex-Mex" />';
    form_output += '<input type="hidden" name="active_restaurant_type[]" value="Pizzeria" />';
    form_output += '<input type="hidden" name="active_restaurant_type[]" value="Steak and Seafood" />';
    form_output += '<input type="hidden" name="active_restaurant_type[]" value="Ice Cream/Yogurt/Desserts" />';
    */

  form_output += '<input type="hidden" name="manual_addresses[0][business_name]" value="' + document.getElementById('store_name').value + '" />';
  form_output += '<input type="hidden" name="manual_addresses[0][phone]" value="' + document.getElementById('phone').value + '" />';
  form_output += '<input type="hidden" name="manual_addresses[0][street_address]" value="' + document.getElementById('street_address_line_1').value + '" />';
  form_output += '<input type="hidden" name="manual_addresses[0][zip]" value="' + document.getElementById('zip').value + '" />';

  html_output += '<br /><input type="button" onClick="document.getElementById(\'zone_map_form\').submit(); return false;" value="View Map" style="background:#ffffff;border:2px #999999 ridge;cursor:pointer;"/>';

  document.getElementById('zone_map_form').innerHTML = form_output;
  document.getElementById('availability_message').innerHTML = html_output;

  document.getElementById('availability_message').style.display = "block";
  //setTimeout("hideAvailabilityMessage();",10000);
}

function calculateSalesPage() {
  var sales_page_total = 0;
  var item_price, item_quantity;

  for (var product_id in product_pricing) {
    document.getElementById('product_' + product_id + '_item_price').innerHTML = '$0.00';
    document.getElementById('product_' + product_id + '_line_total').innerHTML = '$0.00';
    item_quantity = parseInt(document.getElementById('product_' + product_id).value);
    //Manually set value using DOM so that the HTML capture retains the value
    document.getElementById('product_' + product_id).setAttribute("value", item_quantity);
    if (product_id == 27 && document.getElementById('product_28') && document.getElementById('product_29')) {
      document.getElementById('product_29').setAttribute("value", item_quantity);
      //document.getElementById('product_28').setAttribute("value", item_quantity);
    }

    item_price = getSalesPageProductPrice(item_quantity, product_id);
    //alert("Search for " + item_quantity + " prod: " +  product_id + " and found " + item_price);
    document.getElementById('product_' + product_id + '_item_price').innerHTML = '$' + addCommas(item_price);

    document.getElementById('product_' + product_id + '_line_total').innerHTML = '$' + addCommas(parseFloat(item_quantity * item_price));
    sales_page_total += item_quantity * item_price;
  }
  if (document.getElementById('order_form_subtotal')) {
    document.getElementById('order_form_subtotal').value = '$' + addCommas(parseFloat(sales_page_total));
  }
  //Discounts
  var discount_amount = 0;
  var line_discount = 0;
  var product_discount_id = -1;
  var td_elements = document.getElementsByTagName('TD');
  var discount_basis_total = 0;
  if (td_elements.length > 0) {
    for(var i in td_elements) {
      if (td_elements[i].id && td_elements[i].id.substr(0,18) == 'discount_per_unit_') {
        product_discount_id = td_elements[i].id.substr(18);
        if (invoice_discounts[product_discount_id].product_id > 0) {
          for (var product_id in product_pricing) {
            if (product_id == invoice_discounts[product_discount_id].product_id) {
              //Product is in cart, so apply discount
              item_quantity = parseInt(document.getElementById('product_' + product_id).value);
              document.getElementById('discount_quantity_'+product_discount_id).innerHTML = item_quantity;
              if (invoice_discounts[product_discount_id].amount_type == '$') {
                if (product_id == 27 && item_quantity > 2) {
                  //Sysco customization
                  invoice_discounts[product_discount_id].amount = 10;
                } else {
                  invoice_discounts[product_discount_id].amount = 50;
                }
                document.getElementById('discount_per_unit_'+product_discount_id).innerHTML = '$' + addCommas(parseFloat(invoice_discounts[product_discount_id].amount));
                line_discount = item_quantity * invoice_discounts[product_discount_id].amount;
                discount_amount += item_quantity * invoice_discounts[product_discount_id].amount;
              } else {
                line_discount = (item_quantity * getSalesPageProductPrice(item_quantity, product_id)) * (parseFloat(invoice_discounts[product_discount_id].amount) / 100);
                discount_amount += (item_quantity * getSalesPageProductPrice(item_quantity, product_id)) * (parseFloat(invoice_discounts[product_discount_id].amount) / 100);
              }
            }
          }
        } else if (invoice_discounts[product_discount_id].product_class_id > 0) {
          // var product_classes = {8: [1]};  product_id=>product_class_ids
          for (var product_id in product_pricing) {
            if (!product_classes[product_id]) continue;
            for (var j=0;j<product_classes[product_id].length;j++) {
              if (product_classes[product_id][j] == invoice_discounts[product_discount_id].product_class_id) {
                //Product of this product_class is in cart, so apply discount
                item_quantity = parseInt(document.getElementById('product_' + product_id).value);
                document.getElementById('discount_quantity_'+product_discount_id).innerHTML = item_quantity;
                if (invoice_discounts[product_discount_id].amount_type == '$') {
                  line_discount = item_quantity * invoice_discounts[product_discount_id].amount;
                  discount_amount += item_quantity * invoice_discounts[product_discount_id].amount;
                } else {
                  line_discount = (item_quantity * getSalesPageProductPrice(item_quantity, product_id)) * (parseFloat(invoice_discounts[product_discount_id].amount) / 100);
                  discount_amount += (item_quantity * getSalesPageProductPrice(item_quantity, product_id)) * (parseFloat(invoice_discounts[product_discount_id].amount) / 100);
                }
              }
            }
          }
        } else {
          //discount is not tied to a product or product class, so applies to the sales_page_total
          if (invoice_discounts[product_discount_id].amount_type == '$') {
            line_discount = invoice_discounts[product_discount_id].amount;
            discount_amount += invoice_discounts[product_discount_id].amount;
          } else {
            line_discount = sales_page_total * (parseFloat(invoice_discounts[product_discount_id].amount) / 100);
            discount_amount += sales_page_total * (parseFloat(invoice_discounts[product_discount_id].amount) / 100);
          }
        }
        //alert(invoice_discounts[product_discount_id].amount); //:25.00, amount_type:"%", "product_id":0, "product_class_id":0}
        document.getElementById('discount_line_total_'+product_discount_id).innerHTML = '-$' + addCommas(parseFloat(line_discount));
      }
    }
  }
  sales_page_total -= discount_amount;
  if (sales_page_total < 0) {
    sales_page_total = 0;
  }
  /*
    discount_quantity_
    discount_per_unit_
    discount_line_total_
    */

  document.getElementById('order_form_total').value = '$' + addCommas(parseFloat(sales_page_total));
}
function getSalesPageProductPrice(current_product_qty, current_product_id) {
  for (var product_price in product_pricing[current_product_id]) {
  //alert ("Checking " + product_price + " against " + product_pricing[current_product_id][product_price].price);
    if ((    current_product_qty >= product_pricing[current_product_id][product_price].quantity_min
          && current_product_qty <= product_pricing[current_product_id][product_price].quantity_max)
        || (product_pricing[current_product_id][product_price].quantity_min == 0 && product_pricing[current_product_id][product_price].quantity_max == 0)
        || (current_product_qty >= product_pricing[current_product_id][product_price].quantity_min && product_pricing[current_product_id][product_price].quantity_max == 0)
        ) {
      return parseFloat(product_pricing[current_product_id][product_price].price);
    } //else pricing does not apply to this quantity
  }
  return 0;
}
function validateSalesPageForm(form_id) {

  var TextInputs = document.getElementById('sales_page_form').getElementsByTagName("INPUT");
  for (counter = 0;counter < TextInputs.length;counter++) {
    if (TextInputs[counter].id == "cc_name" || TextInputs[counter].id == "cc_number" || TextInputs[counter].id == "eft_routing_num" || TextInputs[counter].id == "eft_account_num") {
    } else {
      TextInputs[counter].setAttribute("value", TextInputs[counter].value);
    }
  }

  var SelectInputs = document.getElementById('sales_page_form').getElementsByTagName("SELECT");
  for (counter = 0;counter < SelectInputs.length;counter++) {
    for (var i = 0; i < SelectInputs[counter].options.length; i++) {
      if (SelectInputs[counter].options.selectedIndex == i) {
        SelectInputs[counter].options[i].setAttribute("selected","selected");
      } else {
        SelectInputs[counter].options[i].removeAttribute("selected");
      }
    }
  }

  var markup = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">" + document.getElementsByTagName("html")[0].innerHTML + "</html>";
  document.getElementById('sales_page_record').value = Base64.encode(markup);
  var form_inputs = document.getElementById(form_id).getElementsByTagName('input');
  var form_selects = document.getElementById(form_id).getElementsByTagName('select');
  var output = "";
  var missing_field = "";
  if (form_inputs.length > 0) {
    for (i=0;i<form_inputs.length;i++) {
      if (form_inputs[i].className.search(/required/) != -1) {
        if (form_inputs[i].value.trim().length == 0) {
          missing_field = form_inputs[i].name;
          if (form_inputs[i].name.search(/\[[0-9\-]+\]/) != -1) {
            //table_name[record_id][field_name]
            missing_field = missing_field.substr(missing_field.lastIndexOf("[")+1);
            missing_field = missing_field.substr(0,missing_field.length-1);
          } //who knows what format?  Just output it all
          missing_field = missing_field.replace(/\_/g,' ');
          missing_field = missing_field.ucwords();
          output += missing_field + "\n";
        }
       }
    }
  }

  if (form_selects.length > 0) {
    for (i=0;i<form_selects.length;i++) {
      if (form_inputs[i].className.search(/required/) != -1) {
        if (form_selects[i].options[form_selects[i].options.selectedIndex].value.trim().length == 0) {
          output += "Select Required &amp; Empty";
          missing_field = form_inputs[i].name;
          if (form_selects[i].name.search(/\[[0-9\-]+\]/) != -1) {
            //table_name[record_id][field_name]
            missing_field = missing_field.substr(missing_field.lastIndexOf("[")+1);
            missing_field = missing_field.substr(0,missing_field.length-1);
          } //who knows what format?  Just output it all
          missing_field = missing_field.replace(/\_/g,' ');
          missing_field = missing_field.ucwords();
          output += missing_field + "\n";
        }
      }
    }
  }
  if (output.length == 0) {
    //Show processing dialog
    var popup = document.createElement("DIV");
    popup.id = "processing_form_box";
    /**
     *
     *<br /><img src="https://www.karingtongroup.com/images/animated-logo.gif" alt="Loading&hellip;">
     */
    popup.innerHTML = '<div style="position:fixed;top:0px;left:0px;width:100%;height:100%;background:#fff;"><div style="position:fixed;top:' + Math.min(50,Math.floor(.5*getHeight() - 200)) + 'px;left:' + Math.floor(.5*getWidth() - 150) + 'px;height:100px;width:300px;"><h1>Processing&hellip; Please Wait&hellip;</h1><p>Refreshing this page or using your back button can cause your card to be charged twice.</div></div>';
    document.body.appendChild(popup);
    return true;
  } else {
    alert("The following fields must be entered: \n" + output);
    return false;
  }
}
/* START DIV slideshow code */
var slide_id_prefix = 'slide_';

var div_slide_show_active_slide = 1;

var slide_next_message = ['Add Stores', 'Next Store','Additional Items','Electronic Signature'];

var num_slides = 0;

function divSlideShowOnload() {
  document.getElementById(slide_id_prefix+div_slide_show_active_slide).className = slide_id_prefix+'visible';
  var potential_divs = document.getElementById('slide_viewport').getElementsByTagName('DIV')
  while (potential_divs[slide_id_prefix+(++num_slides)]) {}
  num_slides--;

  for (var i=1; i<=num_slides; i++) {
    if (i == div_slide_show_active_slide) {
      document.getElementById(slide_id_prefix+i).className = slide_id_prefix+'visible';
    } else {
      document.getElementById(slide_id_prefix+i).className = slide_id_prefix+'hidden';
    }
  }
}

function divSlideShowControl(control_name) {
  var active_slide_number = div_slide_show_active_slide;
  switch (control_name) {
    case 'prev':
      div_slide_show_active_slide--;
      if (div_slide_show_active_slide < 1) {
        div_slide_show_active_slide = 1;
      }
      break;
    case 'next':
      div_slide_show_active_slide++;
      if (div_slide_show_active_slide > num_slides) {
        div_slide_show_active_slide = num_slides;
      }
      break;
    case 'save':
      document.getElementById(slide_id_prefix+'form').submit();
      return;
      break;
  }

  if (active_slide_number != div_slide_show_active_slide) {
    document.getElementById(slide_id_prefix+active_slide_number).className = slide_id_prefix+'hidden';
    document.getElementById(slide_id_prefix+div_slide_show_active_slide).className = slide_id_prefix+'visible';
  }

  if (div_slide_show_active_slide == num_slides) {
    document.getElementById('control_next').className = slide_id_prefix+"control_hidden";
    document.getElementById('control_save').className = slide_id_prefix+"control_active";
  } else {
    document.getElementById('control_next').className = slide_id_prefix+"control_active";
    document.getElementById('control_save').className = slide_id_prefix+"control_hidden";
    //Determine "Next" text
    var message_index = 0;
    if (div_slide_show_active_slide == num_slides-2) {
      //Last slide before save
      message_index = 3;
    } else if (div_slide_show_active_slide == num_slides-3) {
      //Second to last slide before save
      message_index = 2;
    } else if (div_slide_show_active_slide == 1) {
      //First slide
      message_index = 0;
    } else {
      //Store slide
      message_index = 1;
    }
    document.getElementById('control_next').innerHTML = slide_next_message[message_index];
  }
  if (div_slide_show_active_slide == 1) {
    document.getElementById('control_prev').className = slide_id_prefix+"control_inactive";
  } else {
    document.getElementById('control_prev').className = slide_id_prefix+"control_active";
  }
  window.scroll(0,0);
}
/* END DIV slideshow code */
function storeDetailsInterfaceManager() {
  var divs = document.getElementById('chain_stores_information_box').childNodes;

  if (divs.length > 0) {
    var empty_exists = false;
    var empty_divs_contents = document.getElementById('stores_information_empty_div').firstChild.innerHTML;
    var next_insert_id = -1;

    for (i=0; i<divs.length; i++) {
      if (divs[i].className == "chain_store_details") {
        var inputs = divs[i].getElementsByTagName('INPUT');
        var num_empties = 0;

        for(j=0; j<inputs.length; j++) {
          if (inputs[j].id.indexOf("_contact_name") > -1 || inputs[j].id.indexOf("_store_name") > -1) {
            //alert('Got to 597 for '+ inputs[j].id + "("+inputs[j].value+")");
            var current_css_id = inputs[j].id.replace(/client\_store\_/,'').replace(/\_store\_name/,'').replace(/\_contact\_name/,'');
            var current_id = parseInt(current_css_id.replace(/_/,'-'));
            if (next_insert_id > current_id) {
              next_insert_id = current_id;
            }
            if (inputs[j].value.length == 0) {
              num_empties++;
            }
          }
        }

        if (num_empties == 2) {
          if (empty_exists) {
            //Already 1 empty exists, so remove all others.
            document.getElementById('chain_stores_information_box').removeChild(document.getElementById(divs[i].id));
          }
          empty_exists = true;
        }
        //Process last insert id
      }
    }
    next_insert_id--;
    //alert("Number of empties:"+num_empties);
    if (!empty_exists) {
      //Add new set of fields
      //document.getElementById('chain_stores_information_box').innerHTML += empty_divs_contents.replace(/CLIENT_STORE_ID/,-2).replace(/CLIENT_STORE_CSS_ID/,'_2');
      var new_empty_child = document.createElement('DIV');
      new_empty_child.className = "chain_store_details";
      new_empty_child.id = "store_" + (''+next_insert_id).replace(/-/,'_') + "_details";
      new_empty_child.innerHTML = empty_divs_contents.replace(/CLIENT_STORE_ID/g,next_insert_id).replace(/CLIENT_STORE_CSS_ID/g,(''+next_insert_id).replace(/-/,'_'));
      document.getElementById('chain_stores_information_box').appendChild(new_empty_child);
    }

  }
  //updateChainServiceFees();
}
var chain_store_ip_terminals = 0;
var chain_store_dial_up_deposit_terminals = 0;
var chain_store_dial_up_terminals = 0;
var chain_store_cards = 0;

function updateChainServiceFees() {
  var additional_ip_terminals = Math.max(0,document.getElementById('ip_terminals').value - chain_store_ip_terminals);
  var additional_dial_up_terminals = Math.max(0,document.getElementById('dial_up_terminals').value - chain_store_dial_up_terminals);
  var additional_cards = Math.max(0,document.getElementById('addl_cards_4_1').value - chain_store_cards);

  var divs = document.getElementById('chain_stores_information_box').childNodes;

  //alert("[646] additional_dial_up_terminals=" + additional_dial_up_terminals);

  if (divs.length > 0) {
    chain_store_ip_terminals = 0;
    chain_store_dial_up_terminals = 0;
    chain_store_dial_up_deposit_terminals = 0;

    chain_store_cards = 0;
    for (i=0; i<divs.length; i++) {
      if (divs[i].id.length == 0) continue;
      var current_css_id = divs[i].id.replace(/store\_/,'').replace(/\_details/,'');
      if (document.getElementById('client_store_' + current_css_id + '_terminal').options[document.getElementById('client_store_' + current_css_id + '_terminal').options.selectedIndex].value == 'IP') {
        chain_store_ip_terminals += parseInt(document.getElementById('client_store_' + current_css_id + '_additional_terminals').options[document.getElementById('client_store_' + current_css_id + '_additional_terminals').options.selectedIndex].value);
      } else if (document.getElementById('client_store_' + current_css_id + '_terminal').options[document.getElementById('client_store_' + current_css_id + '_terminal').options.selectedIndex].value == 'Dial-up') {
        chain_store_dial_up_terminals += parseInt(document.getElementById('client_store_' + current_css_id + '_additional_terminals').options[document.getElementById('client_store_' + current_css_id + '_additional_terminals').options.selectedIndex].value);
        if (chain_store_dial_up_terminals > 0) {
          chain_store_dial_up_deposit_terminals++;
          chain_store_dial_up_terminals--;
        }
        //alert("[665] " + 'client_store_' + current_css_id + '_additional_terminals');
        //alert("[666] chain_store_dial_up_terminals=" + chain_store_dial_up_terminals);
      }
      if (document.getElementById('client_store_' + current_css_id + '_cards').value.length == 0) {
        document.getElementById('client_store_' + current_css_id + '_cards').value = 0;
      }
      document.getElementById('client_store_' + current_css_id + '_cards').value = parseInt(document.getElementById('client_store_' + current_css_id + '_cards').value.replace(/\,/g,''));
      chain_store_cards += parseInt(document.getElementById('client_store_' + current_css_id + '_cards').value);

    }
    document.getElementById('ip_terminals').value = chain_store_ip_terminals + additional_ip_terminals;
    document.getElementById('dial_up_terminals').value = chain_store_dial_up_terminals + additional_dial_up_terminals;
    document.getElementById('dial_up_terminal_deposit').value = chain_store_dial_up_deposit_terminals;
    document.getElementById('addl_cards_4_1').value = chain_store_cards + additional_cards;

    updateChainServiceFeeTable('ip_terminals');
    updateChainServiceFeeTable('dial_up_terminal_deposit');
    updateChainServiceFeeTable('dial_up_terminals');
    updateChainServiceFeeTable('addl_cards_4_1');
  }
}
function updateChainServiceFeeTable(source) {
  //Validate minimums
  if (document.getElementById('ip_terminals').value < chain_store_ip_terminals) {
    document.getElementById('ip_terminals').value = chain_store_ip_terminals;
  }
  if (document.getElementById('dial_up_terminals').value < chain_store_dial_up_terminals) {
    document.getElementById('dial_up_terminals').value = chain_store_dial_up_terminals;
  }
  if (document.getElementById('addl_cards_4_1').value < chain_store_cards) {
    document.getElementById('addl_cards_4_1').value = chain_store_cards;
  }

  document.getElementById(source).value = parseInt(document.getElementById(source).value);
  if (document.getElementById(source).value == 'NaN') {
    document.getElementById(source).value = 0;
  }
  var display_value = '$0.00';
  var source_val = document.getElementById(source).value;
  var discount_amount = 0;
  switch (source) {
    case 'dial_up_terminals':
      display_value = '$'+addCommas((source_val * 225).toFixed(2));
      break;
    case 'dial_up_terminal_deposit':
      display_value = '$'+addCommas((source_val * 99).toFixed(2));
      break;
    case 'ip_terminals':
      display_value = '$'+addCommas((source_val * 285).toFixed(2));
      break;
    case 'addl_cards_4_1':
    case 'addl_cards_4_4':
      for(var i=0;i<8;i++) {
        if (addl_cards[source][i].minimum <= source_val && source_val <= addl_cards[source][i].maximum) {
          document.getElementById(source+'_per_unit').innerHTML = '$'+addCommas((addl_cards[source][i].per_unit).toFixed(2));
          display_value = '$'+addCommas((addl_cards[source][i].per_unit * source_val).toFixed(2));
          break;
        }
      }
      if (display_value == '$0.00' && source_val > 0) {
        if (source_val > 10000000) {
          display_value = '<span style="color:#ff0000;"><blink>&mdash; CALL &mdash;</blink></span>';
        } else {
          display_value = '<span style="color:#ff0000;"><blink>100 Min</blink></span>';
        }
        document.getElementById(source).value = 0;
        setTimeout('updateChainServiceFeeTable("' + source + '");',5000);
      }
      //Update discount
      /*

      if (parseInt(document.getElementById(source).value) >= 250) {
        //Discount
        discount_amount = addl_cards[source][i].per_unit*100;

        document.getElementById('discount_label').innerHTML = 'Loyalty Lock 100 Card Credit';
        document.getElementById('discount_quantity').innerHTML = '100';
        document.getElementById('discount_per_unit').innerHTML = '- $' + addl_cards[source][i].per_unit.toFixed(2);
        document.getElementById('discount_line_total').innerHTML = '- $' + addCommas((addl_cards[source][i].per_unit*100).toFixed(2));
      } else {
        //No discount
        document.getElementById('discount_label').innerHTML = '&nbsp;';
        document.getElementById('discount_quantity').innerHTML = '&nbsp;';
        document.getElementById('discount_per_unit').innerHTML = '&nbsp;';
        document.getElementById('discount_line_total').innerHTML = '&nbsp;';
      }
      */

      break;
  }
  document.getElementById(source+'_line_total').innerHTML = display_value;

  //Calculate form total (DOES NOT ACCOUNT FOR ADDITIONAL CARDS)
  document.getElementById('form_total').innerHTML = '$' + addCommas((parseInt(document.getElementById('dial_up_terminal_deposit').value) * 99 + parseInt(document.getElementById('dial_up_terminals').value) * 225 + parseInt(document.getElementById('ip_terminals').value) * 285 + parseFloat(document.getElementById('addl_cards_4_1_line_total').innerHTML.substr(1).replace(/,/,''))- discount_amount).toFixed(2));
}
/* START BROWSER DETECTION SOFTWARE */
var BrowserDetect = {
  init: function () {
    this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
    this.version = this.searchVersion(navigator.userAgent)
      || this.searchVersion(navigator.appVersion)
      || "an unknown version";
    this.OS = this.searchString(this.dataOS) || "an unknown OS";
  },
  searchString: function (data) {
    for (var i=0;i<data.length;i++)  {
      var dataString = data[i].string;
      var dataProp = data[i].prop;
      this.versionSearchString = data[i].versionSearch || data[i].identity;
      if (dataString) {
        if (dataString.indexOf(data[i].subString) != -1)
          return data[i].identity;
      }
      else if (dataProp)
        return data[i].identity;
    }
  },
  searchVersion: function (dataString) {
    var index = dataString.indexOf(this.versionSearchString);
    if (index == -1) return;
    return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
  },
  dataBrowser: [
    {
      string: navigator.userAgent,
      subString: "Chrome",
      identity: "Chrome"
    },
    {   string: navigator.userAgent,
      subString: "OmniWeb",
      versionSearch: "OmniWeb/",
      identity: "OmniWeb"
    },
    {
      string: navigator.vendor,
      subString: "Apple",
      identity: "Safari",
      versionSearch: "Version"
    },
    {
      prop: window.opera,
      identity: "Opera"
    },
    {
      string: navigator.vendor,
      subString: "iCab",
      identity: "iCab"
    },
    {
      string: navigator.vendor,
      subString: "KDE",
      identity: "Konqueror"
    },
    {
      string: navigator.userAgent,
      subString: "Firefox",
      identity: "Firefox"
    },
    {
      string: navigator.vendor,
      subString: "Camino",
      identity: "Camino"
    },
    {    // for newer Netscapes (6+)
      string: navigator.userAgent,
      subString: "Netscape",
      identity: "Netscape"
    },
    {
      string: navigator.userAgent,
      subString: "MSIE",
      identity: "Explorer",
      versionSearch: "MSIE"
    },
    {
      string: navigator.userAgent,
      subString: "Gecko",
      identity: "Mozilla",
      versionSearch: "rv"
    },
    {     // for older Netscapes (4-)
      string: navigator.userAgent,
      subString: "Mozilla",
      identity: "Netscape",
      versionSearch: "Mozilla"
    }
  ],
  dataOS : [
    {
      string: navigator.platform,
      subString: "Win",
      identity: "Windows"
    },
    {
      string: navigator.platform,
      subString: "Mac",
      identity: "Mac"
    },
    {
         string: navigator.userAgent,
         subString: "iPhone",
         identity: "iPhone/iPod"
      },
    {
      string: navigator.platform,
      subString: "Linux",
      identity: "Linux"
    }
  ]

};
BrowserDetect.init();
/* END BROWSER DETECTION SOFTWARE */
function toggleTOS() {
  if (document.getElementById('agree_to_electronic_signature').checked) {
    document.getElementById('electronic_icon').src = 'https://www.karingtongroup.com/images/blue-checkbox.png';
    document.getElementById('electronic_icon').style.marginTop = '6px';
    document.getElementById('electronic_icon').style.marginRight = '5px';
  } else {
    document.getElementById('electronic_icon').src = 'https://www.karingtongroup.com/images/blue-checkbox-checked.png';
    document.getElementById('electronic_icon').style.marginTop = '0px';
    document.getElementById('electronic_icon').style.marginRight = '0px';
  }
  document.getElementById('agree_to_electronic_signature').checked = !document.getElementById('agree_to_electronic_signature').checked;
}
String.prototype.trim = function() {
a = this.replace(/^\s+/, '');
return a.replace(/\s+$/, '');
};
function sessionAlive(returnVal) {
  //Re-do in 5 minutes
  setTimeout("ajaxSend('index.php','action=stay_alive','GET');",300000);
}
String.prototype.ucwords = function() {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Waldo Malqui Silva
    // +   bugfixed by: Onno Marsman
    return (this+'').replace(/^(.)|\s(.)/g, function ( $1 ) { return $1.toUpperCase ( ); } );
}
function toggleAgentLeadBar(client_id,target_id_num) {
  if (document.getElementById('lead_box_details_'+client_id+'_'+target_id_num).style.display != 'block') {
    document.getElementById('lead_box_details_'+client_id+'_'+target_id_num).style.display = 'block';
  } else {
    document.getElementById('lead_box_details_'+client_id+'_'+target_id_num).style.display = 'none';
  }
}
function showLeadTab(tab_to_show) {
  document.getElementById('lead_local_box').style.display = 'none';
  document.getElementById('lead_notes_box').style.display = 'none';
  document.getElementById('lead_profile_box').style.display = 'none';
  document.getElementById('lead_' + tab_to_show + '_box').style.display = 'block';
}
function toggleDeadReason() {
  var sysco_ar_view_state = '';
  switch (document.getElementById('lead_action').options[document.getElementById('lead_action').options.selectedIndex].value) {
    case 'Dead':
      document.getElementById('reminder_date').style.display = 'none';
      document.getElementById('dead_reason').style.display = 'block';
      sysco_ar_view_state = 'none';
      break;
    case 'Follow-Up':
      sysco_ar_view_state = 'block';
      document.getElementById('reminder_date').style.display = 'block';
      document.getElementById('dead_reason').style.display = 'none';
      break;
    case 'Demonstration':
      sysco_ar_view_state = 'none';
      document.getElementById('reminder_date').style.display = 'block';
      document.getElementById('dead_reason').style.display = 'none';
      break;
    case 'Note':
      sysco_ar_view_state = 'none';
      document.getElementById('reminder_date').style.display = 'none';
      document.getElementById('dead_reason').style.display = 'none';
  }
  if (document.getElementById('sysco_ar')) {
    document.getElementById('sysco_ar').style.display = sysco_ar_view_state;
  }
}
function updateMailDate() {}
function showNews(box_id) {
  document.getElementById('popup_message').style.display = "block";
  document.getElementById('popup_message').style.top = "0px";
  document.getElementById('popup_message').style.left = "0px";
  document.getElementById('popup_message').style.height = getHeight() + "px";

  document.getElementById('popup_message').innerHTML = document.getElementById('news_box_'+box_id).innerHTML;
}
client_details = new Array();
function showClientDetails(client_id) {
  if (client_details[client_id]) {
    document.getElementById('popup_message').style.display = "block";
    document.getElementById('popup_message').style.top = (mousey+10)+"px";
    document.getElementById('popup_message').style.left = (mousex+10)+"px";

    document.getElementById('popup_message').innerHTML = client_details[client_id];
  } else {
    alert("Error retrieving client data.  Please contact Karington Group for assistance.");
  }
}
function calendarPopup(source_id) {
  //document.getElementById('popup_message').style.height = '';

  document.getElementById('popup_message').style.display = "block";
  document.getElementById('popup_message').style.top = (mousey+10)+"px";
  document.getElementById('popup_message').style.left = (mousex+10)+"px";

  document.getElementById('popup_message').innerHTML = document.getElementById('calendar_popup_'+source_id).innerHTML;
}
function syncSigs() {
  document.getElementById('sig_name').value = document.getElementById('e_signature').value;
}
function required_check(source) {
  if (source.value.length > 0) {
    source.className = source.className.replace(/required\_field/,"");
  } else {
    source.className = source.className+" required_field";
  }
  source.style.backgroundColor = null;
}

function updateBBOrderForm(client_id) {
  //Shipping
  if (document.getElementById('client['+client_id+'][state]')) {
    if (document.getElementById('client['+client_id+'][state]').options[document.getElementById('client['+client_id+'][state]').options.selectedIndex].value == 'NV') {
      document.getElementById('county_box').style.display = "block";
    } else {
      document.getElementById('county_box').style.display = "none";
    }
  }
  if (document.getElementById('client['+client_id+'][country]')) {
    if (document.getElementById('client['+client_id+'][country]').options[document.getElementById('client['+client_id+'][country]').options.selectedIndex].value == 'US') {
      document.getElementById('state_box').style.display = "block";
      document.getElementById('province_box').style.display = "none";
    } else {
      document.getElementById('state_box').style.display = "none";
      document.getElementById('province_box').style.display = "block";
      document.getElementById('county_box').style.display = "none";
    }
  }
  //Billing
  if (document.getElementById('client['+client_id+'][billing_state]').options[document.getElementById('client['+client_id+'][billing_state]').options.selectedIndex].value == 'NV') {
      document.getElementById('billing_county_box').style.display = "block";
  } else {
      document.getElementById('billing_county_box').style.display = "none";
  }

  if (document.getElementById('client['+client_id+'][billing_country]').options[document.getElementById('client['+client_id+'][billing_country]').options.selectedIndex].value == 'US') {
      document.getElementById('billing_state_box').style.display = "block";
      document.getElementById('billing_province_box').style.display = "none";
  } else {
      document.getElementById('billing_state_box').style.display = "none";
      document.getElementById('billing_province_box').style.display = "block";
      document.getElementById('billing_county_box').style.display = "none";
  }
  if (document.getElementById('client_billing_same_as_shipping')) {
    if (document.getElementById('client_billing_same_as_shipping]').checked) {
      document.getElementById('client['+client_id+'][county]').options.selectedIndex = document.getElementById('client['+client_id+'][billing_county]').options.selectedIndex;
      document.getElementById('client['+client_id+'][state]').options.selectedIndex =  document.getElementById('client['+client_id+'][billing_state]').options.selectedIndex
    }
  }
  //Calculate Tax
  tax_amount = 0;
  document.getElementById('invoice_sales_tax').innerHTML = "$0.00";
  if (document.getElementById('client['+client_id+'][country]')) {
    if (document.getElementById('client['+client_id+'][country]').options[document.getElementById('client['+client_id+'][country]').options.selectedIndex].value == 'US' && document.getElementById('client['+client_id+'][state]').options[document.getElementById('client['+client_id+'][state]').options.selectedIndex].value == 'NV') {
    tax_rate = county_tax[document.getElementById('client['+client_id+'][county]').options[document.getElementById('client['+client_id+'][county]').options.selectedIndex].value];    tax_amount = Math.round((parseFloat(tax_rate)/100)*(parseFloat(document.getElementById('bb_price').value) - parseFloat(document.getElementById('discount_amount').value))*100)/100;    document.getElementById('invoice_sales_tax').innerHTML = "$"+tax_amount.toFixed(2);
    }
  }
  invoice_total_amount = parseFloat(tax_amount)+parseFloat(document.getElementById('bb_price').value) - parseFloat(document.getElementById('discount_amount').value);  document.getElementById('invoice_total').innerHTML = "$"+invoice_total_amount.toFixed(2);
}

function toggleShippingAddress(client_id) {
  if (document.getElementById('client_billing_same_as_shipping').checked) {
    document.getElementById('shipping_address_box').style.display = 'none';
  } else {
    document.getElementById('shipping_address_box').style.display = 'block';
  }
}

function updateConfirmOrderForm() {
  shipping_amount = shipping_fees[document.getElementById("invoice[shipping_method]").options[document.getElementById("invoice[shipping_method]").options.selectedIndex].value];
  tax_rate = parseFloat(document.getElementById("sales_tax_rate").value);
  tax_amount = (parseFloat(tax_rate)/100)*(parseFloat(document.getElementById("line_items_total").value) + parseFloat(shipping_amount));
  tax_amount = Math.round(tax_amount*100)/100;
  total_amount = parseFloat(document.getElementById("line_items_total").value) + shipping_amount + tax_amount;
  document.getElementById("invoice_sales_tax").innerHTML = "$" + tax_amount.toFixed(2);
  document.getElementById("invoice_shipping").innerHTML = "$"+shipping_amount.toFixed(2);
  document.getElementById("invoice_total").innerHTML = "$"+total_amount.toFixed(2);
}
function updateCountry(source_id) {
  if (document.getElementById(source_id).options[document.getElementById(source_id).options.selectedIndex].value == 'US') {
    //Show US state options
    document.getElementById(source_id.replace(/country/,'state')).style.display = 'block';
    document.getElementById(source_id.replace(/country/,'province')).style.display = 'none';
    if (document.getElementById(source_id.replace(/country/,'state') + '_label')) {
      document.getElementById(source_id.replace(/country/,'state') + '_label').innerHTML = 'State';
    }
  } else {
    //Show province text field
    document.getElementById(source_id.replace(/country/,'state')).style.display = 'none';
    document.getElementById(source_id.replace(/country/,'province')).style.display = 'block';
    if (document.getElementById(source_id.replace(/country/,'state') + '_label')) {
      document.getElementById(source_id.replace(/country/,'state') + '_label').innerHTML = 'Province';
    }
  }
}
function updateICCView() {
  var current_href = location.href;

  current_href = current_href.replace(/\&product_id=[0-9]*/,'');
  current_href += '&product_id=' + document.getElementById('sub_nav_product_id').options[document.getElementById('sub_nav_product_id').options.selectedIndex].value;
  
  current_href = current_href.replace(/\&ach\_type=[a-z]*/,'');
  current_href += '&ach_type=' + document.getElementById('sub_nav_ach_type').options[document.getElementById('sub_nav_ach_type').options.selectedIndex].value;

  current_href = current_href.replace(/\&balance\_type=[a-z]*/,'');
  current_href += '&balance_type=' + document.getElementById('sub_nav_balance_type').options[document.getElementById('sub_nav_balance_type').options.selectedIndex].value;

  if (document.getElementById('sub_nav_status')) {
    current_href = current_href.replace(/\&status=[a-z]*/,'');
    current_href += '&status=' + document.getElementById('sub_nav_status').options[document.getElementById('sub_nav_status').options.selectedIndex].value;
  }
  if (document.getElementById('sub_nav_date_created')) {
    current_href = current_href.replace(/\&date\_created=[0-9\-]*/,'');
    current_href += '&date_created=' + document.getElementById('sub_nav_date_created').value;
  }
  if (document.getElementById('name_type')) {
    current_href = current_href.replace(/\&name\_type=[co]*/,'');
    current_href += '&name_type=' + document.getElementById('name_type').options[document.getElementById('name_type').options.selectedIndex].value;
  }
  if (document.getElementById('sub_nav_rr_canceled')) {
    current_href = current_href.replace(/\&sub\_nav\_rr\_canceled=[1]*/,'');
    if (document.getElementById('sub_nav_rr_canceled').checked) {
      current_href += '&sub_nav_rr_canceled=1';
    }
  }
  var year_pieces;
  current_href = current_href.replace(/\&date\_created\_start=[^&]*/,'');
  if (document.getElementById('sub_nav_date_created_start') && document.getElementById('sub_nav_date_created_start').value.length > 0) {
    year_pieces = document.getElementById('sub_nav_date_created_start').value.split('/');
    current_href += '&date_created_start=' + year_pieces[2] + '-' + year_pieces[0] + '-' + year_pieces[1];
  }
  current_href = current_href.replace(/\&date\_created\_end=[^&]*/,'');
  if (document.getElementById('sub_nav_date_created_end') && document.getElementById('sub_nav_date_created_end').value.length > 0) {
    year_pieces = document.getElementById('sub_nav_date_created_end').value.split('/');
    current_href += '&date_created_end=' + year_pieces[2] + '-' + year_pieces[0] + '-' + year_pieces[1];
  }
  current_href = current_href.replace(/\&action=[a-z\-\_]*/,'');
  current_href = current_href.replace(/\&action\_target\_id=[0-9]*/,'');

  current_href = current_href.replace(/\&nav\_view=[a-z]*/,'');
  current_href += '&nav_view=' + document.getElementById('sub_nav_nav_view').options[document.getElementById('sub_nav_nav_view').options.selectedIndex].value;

  if (document.getElementById('sub_nav_nav_view').options[document.getElementById('sub_nav_nav_view').options.selectedIndex].value == 'client') {
    current_href = current_href.replace(/\&invoice\_id=[0-9]*/,'');
  } else {
    current_href = current_href.replace(/\&client\_id=[0-9]*/,'');
  }

  if (document.getElementById('sub_nav_client_id') && document.getElementById('sub_nav_client_id').value.length > 0) {
    current_href = current_href.replace(/\&client\_id=[0-9]*/,'');
    current_href = current_href.replace(/\&invoice\_id=[0-9]*/,'');
    current_href = current_href.replace(/\&nav\_view=[a-z]*/,'');
    current_href += '&nav_view=client&client_id=' + document.getElementById('sub_nav_client_id').value;
  }
  if (document.getElementById('sub_nav_invoice_id') && document.getElementById('sub_nav_invoice_id').value.length > 0) {
    current_href = current_href.replace(/\&client\_id=[0-9]*/,'');
    current_href = current_href.replace(/\&invoice\_id=[0-9]*/,'');
    current_href = current_href.replace(/\&nav\_view=[a-z]*/,'');
    current_href += '&nav_view=invoice&invoice_id=' + document.getElementById('sub_nav_invoice_id').value;
  }

  //if (confirm("Jeremy's testing, so just click ok.")) {
    location.href = current_href;
  /*
  } else {
    console.log(current_href);
  }
  */
}
function toggleCheckAll(source_id) {
  var checkboxes = document.getElementById(source_id).getElementsByTagName('INPUT');
  if (checkboxes && checkboxes.length > 0) {
    for (var i=0; i<checkboxes.length; i++) {
      if (checkboxes[i].getAttribute('type') == 'checkbox') {
        checkboxes[i].checked = !checkboxes[i].checked;
      }
    }
  }
}
function numberChecked(source_id) {
  var checkboxes = document.getElementById(source_id).getElementsByTagName('INPUT');
  var return_count = 0;
  if (checkboxes && checkboxes.length > 0) {
    for (var i=0; i<checkboxes.length; i++) {
      if (checkboxes[i].getAttribute('type') == 'checkbox') {
        if (checkboxes[i].checked) return_count++;
      }
    }
  }
  return return_count;
}
function checkedValues(source_id) {
  var checkboxes = document.getElementById(source_id).getElementsByTagName('INPUT');
  var return_values = [];
  if (checkboxes && checkboxes.length > 0) {
    for (var i=0; i<checkboxes.length; i++) {
      if (checkboxes[i].getAttribute('type') == 'checkbox') {
        if (checkboxes[i].checked) return_values.push(checkboxes[i].value);
      }
    }
  }
  return return_values;
}
function validateCheckedAction(source) {
  var display_msg = '';
  var error_flag = false;
  if (source.id == 'checked_action_client_invoice') {
    //Display confirmation

    //Count checked checkboxes
    if (numberChecked('invoice_table') == 0) {
      display_msg = 'No invoices are checked!';
      error_flag = true;
    } else {
      switch (source.options[source.options.selectedIndex].value) {
        case 'bill_now':
          display_msg += '<p>Are you sure you want to bill all selected invoices on Hold or Unpaid status?</p>';
          break;
        default:
          display_msg += '<p>Are you sure you want to mark the following invoices as &quot;' + source.options[source.options.selectedIndex].value + '&quot;?</p>';
          break;
      }
      display_msg += '<h3>Invoices</h3>'
      var invoice_ids = checkedValues('invoice_table');
      if (invoice_ids.length > 0) {
        for (var i=0;i<invoice_ids.length;i++) {
          display_msg += '#' + invoice_ids[i] + '<br />';
        }
      }
      document.getElementById('mass_action').value = source.options[source.options.selectedIndex].value;
    }

    if (!error_flag) {
      display_msg += '<input type="button" onClick="return submitMassAction(\'checked_action_client_invoice_form\');" value="Yes, I want to take this action"/>';
    }

  } else if (source.id == 'checked_action_invoice') {
    //Display confirmation
    //display_msg += '<p>' + source.options[source.options.selectedIndex].value + '</p>';
    
    //Count checked checkboxes
    if (numberChecked('checked_action_invoice_form') == 0) {
      display_msg = 'No invoices are checked!';
      error_flag = true;
    } else {
      switch (source.options[source.options.selectedIndex].value) {
        case 'bill_now':
          display_msg += '<p>Are you sure you want to bill all selected invoices on Hold or Unpaid status?</p>';
          break;
        default:
          display_msg += '<p>Are you sure you want to mark the following invoices as &quot;' + source.options[source.options.selectedIndex].value + '&quot;?</p>';
          break;
      }
      display_msg += '<h3>Invoices</h3>'
      var invoice_ids = checkedValues('checked_action_invoice_form');
      if (invoice_ids.length > 0) {
        for (var i=0;i<invoice_ids.length;i++) {
          display_msg += '#' + invoice_ids[i] + '<br />';
        }
      }
      document.getElementById('mass_action').value = source.options[source.options.selectedIndex].value;
    }

    if (!error_flag) {
      display_msg += '<input type="button" onClick="return submitMassAction(\'checked_action_invoice_form\');" value="Yes, I want to take this action"/>';
    }
  }
  if (display_msg.length > 0) {
    document.getElementById('popup_message').style.padding = '0';
    display_msg = '<div style="display:block;clear:both;background:#009;color:#fff;font-weight:bold;padding:3px;text-align:left;">Confirm<div style="float:right;cursor:pointer;margin-left:1em;" onClick="undoCheckedAction();"><img src="../images/cross.png" /></div></div><div style="padding:.75em;display:block;clear:both;">' + display_msg + '</div>';
    showPopup(display_msg, null, true, true);
  }
}
function undoCheckedAction() {
  if (document.getElementById('checked_action_client_invoice')) {
    document.getElementById('checked_action_client_invoice').options.selectedIndex = 0;
  }
  if (document.getElementById('checked_action_invoice')) {
    document.getElementById('checked_action_invoice').options.selectedIndex = 0;
  }
  hidePopup();
  document.getElementById('mass_action').value = '';
}
function submitMassAction(target_form) {
  document.getElementById(target_form).submit();
}
function showYUIWin(window_id, header_text, contents_div) {
  var oPanel = new YAHOO.widget.Panel(window_id, { constraintoviewport: true, fixedcenter: true, width: "400px", zIndex: 3});

  oPanel.setHeader(header_text);
  oPanel.setBody(document.getElementById(contents_div).innerHTML);
  oPanel.render(document.body);
}
function addEvent(evname, handler, object){
  if (window.addEventListener) {
    object.addEventListener(evname.substr(2), handler, false);
  } else if (window.attachEvent) {
    object.attachEvent(evname, handler);
  }
}
function buttonBarPosition() {
  document.getElementById('button_bar').style.top = Math.max(0, document.getElementById('qse_header').offsetTop + 15, window.pageYOffset || document.documentElement.scrollTop) + "px";
  document.getElementById('button_bar').style.left = Math.min(getWidth() - 280, (Math.floor((getWidth() - document.getElementById('page_wrapper_left').offsetWidth)/2) + document.getElementById('page_wrapper_left').offsetWidth - 40)) + "px";
}
function displayViewOriginalInvoiceInput() {
  document.getElementById('original_invoice_input').style.display = 'block';
  document.getElementById('original_invoice_input').style.left = (getWidth() - 125) + "px";
}
function displayJustinReevesTestimonial() {
  if (document.getElementById('justin_reeves_testimonial_win')) {
    document.getElementById('justin_reeves_testimonial_win').style.left = Math.floor((getWidth() - 800)/2) + "px";
    document.getElementById('justin_reeves_testimonial_win').style.display = 'block';
  }
}