text:
"""This module provides the main functionality of HTTPie.

Invocation flow:

    1. Read, validate and process the input (args, `stdin`).
    2. Create and send a request.
    3. Stream, and possibly process and format, the requested parts
       of the request-response exchange.
    4. Simultaneously write to `stdout`
    5. Exit.

"""
import sys
import errno

import requests
from httpie import __version__ as httpie_version
from requests import __version__ as requests_version
from pygments import __version__ as pygments_version

from .cli import parser
from .compat import str, is_py3
from .client import get_response
from .downloads import Download
from .models import Environment
from .output import build_output_stream, write, write_with_colors_win_py3
from . import ExitStatus

def get_exit_status(http_status, follow=False):
    """Translate HTTP status code to exit status code."""
    if 300 <= http_status <= 399 and not follow:
        # Redirect
        return ExitStatus.ERROR_HTTP_3XX
    elif 400 <= http_status <= 499:
        # Client Error
        return ExitStatus.ERROR_HTTP_4XX
    elif 500 <= http_status <= 599:
        # Server Error
        return ExitStatus.ERROR_HTTP_5XX
    else:
        return ExitStatus.OK

def print_debug_info(env):
    sys.stderr.writelines([
        'HTTPie %s\n' % httpie_version,
        'HTTPie data: %s\n' % env.config.directory,
        'Requests %s\n' % requests_version,
        'Pygments %s\n' % pygments_version,
        'Python %s %s\n' % (sys.version, sys.platform)
    ])

def main(args=sys.argv[1:], env=Environment()):
    """Run the main program and write the output to ``env.stdout``.

    Return exit status code.

    """
    if env.config.default_options:
        args = env.config.default_options + args

    def error(msg, *args, **kwargs):
        msg = msg % args
        level = kwargs.get('level', 'error')
        env.stderr.write('\nhttp: %s: %s\n' % (level, msg))

    debug = '--debug' in args
    traceback = debug or '--traceback' in args
    exit_status = ExitStatus.OK

    if debug:
        print_debug_info(env)
        if args == ['--debug']:
            return exit_status

    download = None

    try:
        args = parser.parse_args(args=args, env=env)

        if args.download:
            args.follow = True  # --download implies --follow.
            download = Download(
                output_file=args.output_file,
                progress_file=env.stderr,
                resume=args.download_resume
            )
            download.pre_request(args.headers)

        response = get_response(args, config_dir=env.config.directory)

        if args.check_status or download:

            exit_status = get_exit_status(
                http_status=response.status_code,
                follow=args.follow
            )

            if not env.stdout_isatty and exit_status != ExitStatus.OK:
                error('HTTP %s %s',
                      response.raw.status,
                      response.raw.reason,
                      level='warning')

        write_kwargs = {
            'stream': build_output_stream(
                args, env, response.request, response),

            # This will in fact be `stderr` with `--download`
            'outfile': env.stdout,

            'flush': env.stdout_isatty or args.stream
        }

        try:

            if env.is_windows and is_py3 and 'colors' in args.prettify:
                write_with_colors_win_py3(**write_kwargs)
            else:
                write(**write_kwargs)

            if download and exit_status == ExitStatus.OK:
                # Response body download.
                download_stream, download_to = download.start(response)
                write(
                    stream=download_stream,
                    outfile=download_to,
                    flush=False,
                )
                download.finish()
                if download.interrupted:
                    exit_status = ExitStatus.ERROR
                    error('Incomplete download: size=%d; downloaded=%d' % (
                        download.status.total_size,
                        download.status.downloaded
                    ))

        except IOError as e:
            if not traceback and e.errno == errno.EPIPE:
                # Ignore broken pipes unless --traceback.
                env.stderr.write('\n')
            else:
                raise
    except (KeyboardInterrupt, SystemExit):
        if traceback:
            raise
        env.stderr.write('\n')
        exit_status = ExitStatus.ERROR

    except requests.Timeout:
        exit_status = ExitStatus.ERROR_TIMEOUT
        error('Request timed out (%ss).', args.timeout)

    except Exception as e:
        # TODO: Better distinction between expected and unexpected errors.
        #       Network errors vs. bugs, etc.
        if traceback:
            raise
        error('%s: %s', type(e).__name__, str(e))
        exit_status = ExitStatus.ERROR

    finally:
        if download and not download.finished:
            download.failed()

    return exit_status


text:
#ifndef IOKIT_TRANSFER_HPP
#define IOKIT_TRANSFER_HPP

#include "types.h"

#include "iokit_types.hpp"

#include "usb_standard_types.hpp"
#include "dsi_timer.hpp"
#include "dsi_thread.h"

//////////////////////////////////////////////////////////////////////////////////
// Public Definitions
//////////////////////////////////////////////////////////////////////////////////

struct TransferStatus
{
   enum Enum
   {
      //Transfer completed without error. Note that this does not indicate
      //that the entire amount of requested data was transferred.
      COMPLETED,

      //Transfer failed
      ERROR,

      //Transfer timed out
      TIMED_OUT,

      //Transfer was cancelled
      CANCELLED,

      //For bulk/interrupt endpoints: halt condition detected (endpoint
      //  stalled). For control endpoints: control request not supported.
      STALL,

      //Device was disconnected
      NO_DEVICE,

      //Device sent more data than requested
      OVERFLOWED,

      //transfer was interrupted by a system signal
      INTERRUPTED
   };

   private: TransferStatus();

};

struct TransferType
{
   enum Enum
   {
      //Control endpoint
      CONTROL = 0,

      //Isochronous endpoint
      ISOCHRONOUS = 1,

      //Bulk endpoint
      BULK = 2,

      //Interrupt endpoint
      INTERRUPT = 3
   };

   private: TransferType();

};

struct USBMessage  //!!Can be private!
{
   enum Enum
   {
      DEVICE_GONE,
      ASYNC_IO_COMPLETE
   };

   private: USBMessage();
};

//////////////////////////////////////////////////////////////////////////////////
// Public Class Prototypes
//////////////////////////////////////////////////////////////////////////////////

class IOKitDeviceHandle;

//NOTE: If this is an isochronous transfer, status may read COMPLETED even
//if there were errors in the frames. Use the
//\ref libusb_iso_packet_descriptor::status "status" field in each packet
//to determine if errors occurred.

//!!All input data should be const!
//!!Make sure all data is initialized!
//!!NOTE: This transfer is expected to only be sent once!

class IOKitTransfer
{

   public:
      static IOKitTransfer* MakeControlTransfer(const IOKitDeviceHandle& dev_handle_, struct libusb_control_setup& setup_,
                             const int pipe[2],
                             unsigned char data_buffer_[],
                             unsigned int timeout_);

      static IOKitTransfer* MakeInterruptTransfer(const IOKitDeviceHandle& dev_handle_, unsigned char endpoint_,
                             const int pipe[2],
                             unsigned char data_buffer_[], unsigned long data_length_,
                             unsigned int timeout_);

      static IOKitTransfer* MakeBulkTransfer(const IOKitDeviceHandle& dev_handle_, unsigned char endpoint_,
                             const int pipe[2],
                             unsigned char data_buffer_[], unsigned long data_length_,
                             unsigned int timeout_);

      IOKitError::Enum Submit();
      TransferStatus::Enum Receive();
      IOKitError::Enum Cancel();

      unsigned char* GetDataBuffer() const { return buffer; }  //can someone change our buffer pointer unless we return unsigned char* const?
      int GetDataLength() const { return actual_length; }

      virtual ~IOKitTransfer();

   protected:
      // Control Transfer //
      IOKitTransfer(const IOKitDeviceHandle& dev_handle_, struct libusb_control_setup& setup_,
                             const int pipe[2],
                             unsigned char data_buffer_[],
                             unsigned char type_, unsigned int timeout_);
      // Interrupt/Bulk Transfer //
      IOKitTransfer(const IOKitDeviceHandle& dev_handle_,
                             const int pipe[2], unsigned char endpoint_,
                             unsigned char data_buffer_[], unsigned long data_length_,
                             unsigned char type_, unsigned int timeout_);

   private:

      ///////////
      // SUBMIT
      ///////////
      IOKitError::Enum SubmitControlTransfer();
      IOKitError::Enum SubmitBulkTransfer();

      ///////////
      // RECEIVE
      ///////////
      TransferStatus::Enum HandleEvent(struct pollfd& poll_fd);

      TransferStatus::Enum HandleCallback(kern_return_t result, UInt32 io_size);
      TransferStatus::Enum ControlCallback(kern_return_t result, UInt32 io_size);
      TransferStatus::Enum BulkCallback(kern_return_t result, UInt32 io_size);

      TransferStatus::Enum HandleTransferCancellation();
      TransferStatus::Enum HandleTransferCompletion(TransferStatus::Enum status_);

      ///////////
      // CANCEL
      ///////////
      IOKitError::Enum CancelControlTransfer() const;
      IOKitError::Enum AbortTransfer() const;
      static DSI_THREAD_RETURN TimeoutTransfer(void *pvParameter_);
      BOOL transfer_complete; //used to ensure a transfer abort does not discard properly transferred contents

      ///////////
      // OTHER
      ///////////

      static void Callback(void* refcon, IOReturn result, void* arg0);  //IOAsyncCallback1 function
      static IOKitError::Enum EndpointToPipeRef(const IOKitDeviceHandle& dev_handle, uint8_t ep, uint8_t& pipep, uint8_t& ifcp);

      int device_pipe[2];
      int return_pipe[2];
      DSI_MUTEX stMutexCriticalSection;

      //SUBMIT DATA
      const unsigned char endpoint;  //Address of the endpoint where this transfer will be sent.
      const unsigned char type; //Type of the endpoint from \ref libusb_transfer_type
      const unsigned int timeout;  //Timeout for this transfer in millseconds. A value of 0 indicates no timeout.
      const libusb_control_setup control_setup;  //setup for control transfers
      DSITimer *pclTimer; //used to initiate USB transfer timeouts, instead of making timeouts the responsibility of the IOKit, which generates kernel warnings

      //RECEIVE DATA
      int transferred;  //length of data transferred (the variable that is not read by user)
      int actual_length;  //length of data that was transferred (the variable that is read by user)

      //SUBMIT/RECEIVE
      unsigned char* const buffer;  //Length of full data buffer  //!!Should we have our own buffer?  Should there be a read and const write buffer?
      const int length;             //Length of the data buffer
      const IOKitDeviceHandle& dev_handle; 		//Handle of the device that this transfer will be submitted to

      ////////////////////
      // usbi_transfer
      ////////////////////
      unsigned long time_done;  //system time the transfer should be done before or else it times out
      BOOL timedout;  //whether transfer timed out

};

#endif // !defined(USB_TRANSFER_HPP)

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.

namespace Microsoft.Azure.Search
{
    using System;

    public partial interface ISearchIndexClient
    {
        /// <summary>
        /// Gets the credentials used to authenticate to an Azure Search service.
        /// </summary>
        SearchCredentials SearchCredentials { get; }

        /// <summary>
        /// Indicates whether the index client should use HTTP GET for making Search and Suggest requests to the
        /// Azure Search REST API. The default is <c>false</c>, which indicates that HTTP POST will be used.
        /// </summary>
        bool UseHttpGetForQueries { get; set; }

        /// <summary>
        /// Changes the BaseUri of this client to target a different index in the same Azure Search service. This method is NOT thread-safe; You
        /// must guarantee that no other threads are using the client before calling it.
        /// </summary>
        /// <param name="newIndexName">The name of the index to which all subsequent requests should be sent.</param>
        void TargetDifferentIndex(string newIndexName);
    }
}


text:
//The MIT License(MIT)

//Copyright(c) 2016 Alberto Rodriguez & LiveCharts Contributors

//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:

//The above copyright notice and this permission notice shall be included in all
//copies or substantial portions of the Software.

//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//SOFTWARE.

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;
using LiveCharts.Definitions.Points;
using LiveCharts.Definitions.Series;
using LiveCharts.Dtos;
using LiveCharts.SeriesAlgorithms;
using LiveCharts.Wpf.Charts.Base;
using LiveCharts.Wpf.Points;

namespace LiveCharts.Wpf
{
    /// <summary>
    /// The stacked row series compares the proportion of every series in a point
    /// </summary>
    public class StackedRowSeries : Series, IStackedRowSeriesView
    {
        #region Constructors

        /// <summary>
        /// Initializes a new instance of StackedRow series class
        /// </summary>
        public StackedRowSeries()
        {
            Model = new StackedRowAlgorithm(this);
            InitializeDefuaults();
        }

        /// <summary>
        /// Initializes a new instance of StackedRow series class, with a given mapper
        /// </summary>
        public StackedRowSeries(object configuration)
        {
            Model = new StackedRowAlgorithm(this);
            Configuration = configuration;
            InitializeDefuaults();
        }

        #endregion

        #region Private Properties

        #endregion

        #region Properties

        /// <summary>
        /// The maximum row height property
        /// </summary>
        public static readonly DependencyProperty MaxRowHeightProperty = DependencyProperty.Register(
            "MaxRowHeight", typeof (double), typeof (StackedRowSeries), new PropertyMetadata(default(double)));
        /// <summary>
        /// Gets or sets the maximum height of row, any row height will be capped at this value.
        /// </summary>
        public double MaxRowHeight
        {
            get { return (double) GetValue(MaxRowHeightProperty); }
            set { SetValue(MaxRowHeightProperty, value); }
        }

        /// <summary>
        /// The row padding property
        /// </summary>
        public static readonly DependencyProperty RowPaddingProperty = DependencyProperty.Register(
            "RowPadding", typeof (double), typeof (StackedRowSeries), new PropertyMetadata(default(double)));
        /// <summary>
        /// Gets or sets the padding between each row in the series.
        /// </summary>
        public double RowPadding
        {
            get { return (double) GetValue(RowPaddingProperty); }
            set { SetValue(RowPaddingProperty, value); }
        }

        /// <summary>
        /// The stack mode property
        /// </summary>
        public static readonly DependencyProperty StackModeProperty = DependencyProperty.Register(
            "StackMode", typeof (StackMode), typeof (StackedRowSeries), new PropertyMetadata(default(StackMode)));
        /// <summary>
        /// Gets or sets the stacked mode, values or percentage.
        /// </summary>
        public StackMode StackMode
        {
            get { return (StackMode) GetValue(StackModeProperty); }
            set { SetValue(StackModeProperty, value); }
        }

        /// <summary>
        /// The labels position property
        /// </summary>
        public static readonly DependencyProperty LabelsPositionProperty = DependencyProperty.Register(
            "LabelsPosition", typeof(BarLabelPosition), typeof(StackedRowSeries),
            new PropertyMetadata(BarLabelPosition.Parallel, CallChartUpdater()));
        /// <summary>
        /// Gets or sets where the label is placed
        /// </summary>
        public BarLabelPosition LabelsPosition
        {
            get { return (BarLabelPosition)GetValue(LabelsPositionProperty); }
            set { SetValue(LabelsPositionProperty, value); }
        }
        #endregion

        #region Overridden Methods

        /// <summary>
        /// Gets the view of a given point
        /// </summary>
        /// <param name="point"></param>
        /// <param name="label"></param>
        /// <returns></returns>
        public override IChartPointView GetPointView(ChartPoint point, string label)
        {
            var pbv = (RowPointView) point.View;

            if (pbv == null)
            {
                pbv = new RowPointView
                {
                    IsNew = true,
                    Rectangle = new Rectangle(),
                    Data = new CoreRectangle()
                };

                Model.Chart.View.AddToDrawMargin(pbv.Rectangle);
            }
            else
            {
                pbv.IsNew = false;
                point.SeriesView.Model.Chart.View
                    .EnsureElementBelongsToCurrentDrawMargin(pbv.Rectangle);
                point.SeriesView.Model.Chart.View
                    .EnsureElementBelongsToCurrentDrawMargin(pbv.HoverShape);
                point.SeriesView.Model.Chart.View
                    .EnsureElementBelongsToCurrentDrawMargin(pbv.DataLabel);
            }

            pbv.Rectangle.Fill = Fill;
            pbv.Rectangle.StrokeThickness = StrokeThickness;
            pbv.Rectangle.Stroke = Stroke;
            pbv.Rectangle.StrokeDashArray = StrokeDashArray;
            pbv.Rectangle.Visibility = Visibility;
            Panel.SetZIndex(pbv.Rectangle, Panel.GetZIndex(this));

            if (Model.Chart.RequiresHoverShape && pbv.HoverShape == null)
            {
                pbv.HoverShape = new Rectangle
                {
                    Fill = Brushes.Transparent,
                    StrokeThickness = 0
                };

                Panel.SetZIndex(pbv.HoverShape, int.MaxValue);

                var wpfChart = (Chart)Model.Chart.View;
                wpfChart.AttachHoverableEventTo(pbv.HoverShape);

                Model.Chart.View.AddToDrawMargin(pbv.HoverShape);
            }

            if (pbv.HoverShape != null) pbv.HoverShape.Visibility = Visibility;

            if (DataLabels)
            {
                pbv.DataLabel = UpdateLabelContent(new DataLabelViewModel
                {
                    FormattedText = label,
                    Point = point
                }, pbv.DataLabel);
            }

            if (!DataLabels && pbv.DataLabel != null)
            {
                Model.Chart.View.RemoveFromDrawMargin(pbv.DataLabel);
                pbv.DataLabel = null;
            }

            pbv.LabelPosition = LabelsPosition;

            return pbv;
        }

        #endregion

        #region Private Methods

        private void InitializeDefuaults()
        {
            SetCurrentValue(StrokeThicknessProperty, 0d);
            SetCurrentValue(MaxRowHeightProperty, 35d);
            SetCurrentValue(RowPaddingProperty, 2d);
            SetCurrentValue(ForegroundProperty, Brushes.White);

            Func<ChartPoint, string> defaultLabel = x =>  Model.CurrentXAxis.GetFormatter()(x.X);
            SetCurrentValue(LabelPointProperty, defaultLabel);

            DefaultFillOpacity = 1;
        }

        #endregion
    }
}


text:
package org.drools.core.spi;

import org.drools.core.ClassObjectFilter;
import org.kie.api.runtime.KieRuntime;
import org.kie.api.runtime.process.CaseAssignment;
import org.kie.api.runtime.process.CaseData;
import org.kie.api.runtime.process.NodeInstance;
import org.kie.api.runtime.process.ProcessInstance;
import org.kie.api.runtime.process.WorkflowProcessInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;

public class ProcessContext implements org.kie.api.runtime.process.ProcessContext {

    private static Logger logger = LoggerFactory.getLogger(ProcessContext.class);

    private KieRuntime kruntime;
    private ProcessInstance processInstance;
    private NodeInstance nodeInstance;

    public ProcessContext(KieRuntime kruntime) {
        this.kruntime = kruntime;
    }

    public ProcessInstance getProcessInstance() {
        if (processInstance != null) {
            return processInstance;
        }
        if (nodeInstance != null) {
            return (ProcessInstance) nodeInstance.getProcessInstance();
        }
        return null;
    }

    public void setProcessInstance(ProcessInstance processInstance) {
        this.processInstance = processInstance;
    }

    public NodeInstance getNodeInstance() {
        return nodeInstance;
    }

    public void setNodeInstance(NodeInstance nodeInstance) {
        this.nodeInstance = nodeInstance;
    }

    public Object getVariable(String variableName) {
        if (nodeInstance != null) {
            return nodeInstance.getVariable(variableName);
        } else {
            return ((WorkflowProcessInstance) getProcessInstance()).getVariable(variableName);
        }
    }

    public void setVariable(String variableName, Object value) {
        if (nodeInstance != null) {
            nodeInstance.setVariable(variableName, value);
        } else {
            ((WorkflowProcessInstance) getProcessInstance()).setVariable(variableName, value);
        }
    }

    public KieRuntime getKieRuntime() {
        return kruntime;
    }

    public KieRuntime getKnowledgeRuntime() {
    	return kruntime;
    }

    public Logger getLogger() {
        return logger;
    }

    public CaseData getCaseData() {

        Collection<? extends Object> objects = kruntime.getObjects(new ClassObjectFilter(CaseData.class));
        if (objects.size() == 0) {
            return null;
        }

        return (CaseData) objects.iterator().next();
    }

    public CaseAssignment getCaseAssignment() {
        Collection<? extends Object> objects = kruntime.getObjects(new ClassObjectFilter(CaseAssignment.class));
        if (objects.size() == 0) {
            return null;
        }

        return (CaseAssignment) objects.iterator().next();
    }
}


text:
//  The purpose of this example is to demonstrate a simple use case for the
//  flush_multi_pass parser.

#include <iostream>
#include <fstream>
#include <string>

//[qi_flush_multi_pass_includes
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/repository/include/qi_flush_multi_pass.hpp>
//]

//[qi_flush_multi_pass_namespace
namespace spirit = boost::spirit;
using boost::spirit::repository::flush_multi_pass;
//]

namespace client
{
    //[qi_flush_multi_pass_clear_buffer
    template <typename Iterator, typename Skipper>
    struct preprocessor : spirit::qi::grammar<Iterator, Skipper>
    {
        // This is a simplified preprocessor grammar recognizing
        //
        //   #define MACRONAME something
        //   #undef MACRONAME
        //
        // Its sole purpose is to show an example how to use the
        // flush_multi_pass parser. At the end of each line no backtracking can
        // occur anymore so that it's safe to clear all internal buffers in the
        // multi_pass.
        preprocessor() : preprocessor::base_type(file)
        {
            using spirit::ascii::char_;
            using spirit::qi::eol;
            using spirit::qi::lit;

            file =
                *line
                ;

            line =  ( command |  *(char_ - eol) )
                >>  eol
                >>  flush_multi_pass
                ;

            command =
                    "#define" >> *lit(' ') >> *(char_ - ' ') >> *lit(' ') >> *(char_ - eol)
                |   "#undef"  >> *lit(' ') >> *(char_ - eol)
                ;
        }

        spirit::qi::rule<Iterator, Skipper> file, line, command;
    };
    //]
}

template <typename Iterator, typename Skipper>
bool parse(Iterator& first, Iterator end, Skipper const& skipper)
{
    client::preprocessor<Iterator, Skipper> g;
    return boost::spirit::qi::phrase_parse(first, end, g, skipper);
}

int main()
{
    namespace spirit = boost::spirit;
    using spirit::ascii::char_;
    using spirit::qi::eol;

    std::ifstream in("flush_multi_pass.txt");    // we get our input from this file
    if (!in.is_open()) {
        std::cout << "Could not open input file: 'flush_multi_pass.txt'" << std::endl;
        return -1;
    }

    typedef std::istreambuf_iterator<char> base_iterator_type;
    spirit::multi_pass<base_iterator_type> first =
        spirit::make_default_multi_pass(base_iterator_type(in));
    spirit::multi_pass<base_iterator_type> end =
        spirit::make_default_multi_pass(base_iterator_type());

    bool result = parse(first, end, '#' >> *(char_ - eol) >> eol);
    if (!result) {
        std::cout << "Failed parsing input file!" << std::endl;
        return -2;
    }

    std::cout << "Successfully parsed input file!" << std::endl;
    return 0;
}


text:
=begin

=end
#RightTeam
class RightTeam < Team

  def initialize window, name
    super window, name, "right"
    generate_player Goalkeeper.new(@window, self, 780, 300)
    generate_player Defender.new(@window, self, 650, 150)
    generate_player Defender.new(@window, self, 650, 450)
    generate_player Midfielder.new(@window, self, 550, 150)
    generate_player Midfielder.new(@window, self, 550, 300)
    generate_player Forward.new(@window, self, 450, 300)
  end

end


text:
var db = require('db'),
//    sms_utils = require('kujua-sms/utils'),
    querystring = require('querystring'),
//    jsonforms = require('views/lib/jsonforms'),
    utils = require('kujua-utils'),
    logger = utils.logger,
    templates = require('duality/templates'),
    _ = require('underscore'),
    _s = require('underscore-string'),
    moment = require('moment'),
    settings = require('settings/root'),
//    objectpath = require('views/lib/objectpath'),
    ddoc = settings.name;

/*
 * TODO use proper/consistent style here, camel case only for functions,
 * underscores for vars.
 * */

var RE_PHONE = /.*?(\+?[\d]{10,15}).*/;

var db = null
    , timeoutID = null
    , nextStartKey = null
    , firstRender = true
    , lastRecord = null
    , limit = 50
    , district = ''
    , cache = {revs_info:{}}
    , dh_id = null
    , cl_id = null
    , form = null
    , locale
    , $modal
    , isAdmin
    , baseURL;

function render(err, data) {
    var html;

    if (err) {
        return alert(err);
    }

    if (data.rows && data.rows.length === 1) {
        lastRecord = data.rows[0];
        nextStartKey = null;
    } else if (data.total_rows < limit) {
        lastRecord = data.rows[data.rows.length - 1];
    } else if (data.rows && data.rows.length < limit) {
        lastRecord = data.rows[data.rows.length - 1];
        nextStartKey = null;
    } else if (data.rows && data.rows.length > 1) {
        nextStartKey = data.rows.pop().key;
    }
    var rows = _.map(data.rows, function(row) {
        return sms_utils.makeDataRecordReadable(row.doc || row.value);
    });

    // render base template if this is the first render or we have no rows.
    if (firstRender) {
        html = templates.render('data_records_table.html', {}, {
            data_records: rows
        });

        $('[data-page=activity] #loader').html(html);

        firstRender = false;
        if (!nextStartKey && rows.length > 0) {
            $('.reached-last-record').show();
        }
    } else {
        html = templates.render('data_records_rows.html', {}, {
            data_records: rows
        });

        $('[data-page=activity] #data-records .wrap-rows').append(html);

        if (!nextStartKey) {
            $('.reached-last-record').show();
        }
    }

    // update data api values as well
    _.each(rows, function(row) {
        if (row._id) {
            $('[rel='+row._id+']').data('data-record', sms_utils.makeDataRecordOriginal(row));
        }
    });

    delete timeoutID;

    $('.ajax-loader').hide();
}

function renderRecords(options) {
    if  (!options) {
        if (cache.viewOptions) {
            options = cache.viewOptions;
        } else {
            return;
        }
    }

    if (nextStartKey) {
        options.query['startkey'] = nextStartKey;
    }

    if (!options.view) {
        render(null, []);
    } else if (!lastRecord) {
        if (/^_fti/.test(options.view)) {
            if (!db.getFTI) {
                require('views/lib/couchfti').addFTI(db);
            }
            db.getFTI(
                ddoc,
                options.view.split('/').pop(),
                options.query,
                render
            );
        } else {
            db.getView(ddoc, options.view, options.query, render);
        }
    }
}

function highlightRows($divs, flag) {
    flag = flag === undefined ? true : flag;

    $divs.toggleClass('highlight', flag);
}

/*
 * take result from changes feed or doc as argument and update screen
 */
var renderRecord = function(result) {

    if (!result) return;

    var doc = result.doc,
        div = $('[rel='+ result.id +']'),
        newDiv;

    // remove deleted records
    if (result.deleted && div.length)
        return div.fadeOut(500, function() { $(this).remove(); });

    // also only update for this district or _admin
    if (!isInDistrict(doc)) return;

    // render new/updated records
    var html = templates.render( 'data_records_rows.html', {}, {
        data_records: [
            sms_utils.makeDataRecordReadable(doc)
        ]
    });

    newDiv = $(html.trim()); // jQuery gets confused at leading line return

    if(div.length) {
        // preserve expando visibility
        var css = div.removeClass('highlight').attr('class');
        div.replaceWith(function() {
            newDiv.attr('class', css);
            return newDiv;
        });
    } else {
        newDiv.insertBefore('#data-records .data-record:first')
            .hide().fadeIn(500);
    }

    // attach original doc to element with jquery data api. use separate
    // jquery call, for some reason chaining failed.  and undo
    // makeDataRecordReadable.
    newDiv.data('data-record', sms_utils.makeDataRecordOriginal(doc));

    if (newDiv.is('.expanded')) {
        updateRevNav(newDiv);
    }
};

var onDataRecordUpdated = function(ev, data) {

    if (!data) return;

    _.each(data.results, function(result) {
        if (cache.revs_info[result.id])
            delete cache.revs_info[result.id];
        renderRecord(result);
    });

}

// close modal after changes feed updates records, but only if modal has
// triggered the change. TODO
var closeModal = function() {
    if ($modal) {
        $modal.modal('hide');
        $modal.remove();
        $modal = null;
    }
}

var cancelScroll = function() {
    if(typeof timeoutID === "number") {
        window.clearTimeout(timeoutID);
        delete timeoutID;
    }
};

var setupScroll = function() {
    cancelScroll();
    if(!lastRecord) {
        $('.ajax-loader').show();
        timeoutID = window.setTimeout(function() {
            renderRecords();
        }, 700);
    }
};

var handleSelectRow = function(ev) {
    var checkbox = $(this);
    ev.stopPropagation();
    highlightRows(checkbox.parents('.data-record'), checkbox.prop('checked'));
}

function toggleRows(checked) {
    var rows = $('#data-records .data-record');

    rows.find('[name=select-row-checkbox]').prop('checked', checked);

    highlightRows(rows, checked);
}
function handleSelectAllRows() {
    toggleRows(true);
}

function handleUnselectAllRows(ev) {
    toggleRows(false);
}

// verify changes feed reflects same docs in bulk update response, so we can
// verify when the browser screen has received update from the changes feed
// after a bulk update. couldn't figure out a better way to do this.
var isBulkUpdateDone = function(changesData, data) {
    var valid = true;
    var ids = _.map(changesData.results, function(el) { return el._id; });
    _.each(data, function(el) {
        if (ids.indexOf(el._id) === -1) valid = false;
    });
    return valid;
};

// close modal when a changes feed sends in a result with same amount of
// records changed.  this avoids closing modal based on a event from unrelated
// record updated.
var setupModalClose = function(data) {

    // check errors
    var errors = [];
    _.each(data, function(result) {
        if (result.ok) return;
        errors.push(result);
    });

    if (errors.length)  {
        handleModalError(errors);
    }

    // setup close
    function onRecordUpdate(ev, changesData) {
        if (isBulkUpdateDone(changesData, data)) {
            closeModal();
            $(document).off('data-record-updated', onRecordUpdate);
        } else {
            console.error('changesData does not match', changesData, data);
        }
    }

    $(document).on('data-record-updated', onRecordUpdate);
}

function getSelectedDocs(options) {
    var docs = [],
        extra = options && options.extra;

    $('#data-records [name=select-row-checkbox]:checked').each(function(idx, el) {
        var div = $(el).parents('.data-record'),
            record  = div.data().dataRecord;

        if (record && record._id && record._rev) {
            if (extra && extra !== null) {
                docs.push( _.extend(record, extra) );
            } else {
                docs.push(record);
            }
        }
    });

    return docs;
}

function doBulkEdit(options, callback) {
    var docs = getSelectedDocs(options);

    if (docs.length === 0) {
        return callback('No rows selected.');
    }

    callback(null, docs);
};

var onModalCancel = function(ev) {
    ev.preventDefault();
    closeModal();
}

// keep modal in foreground until update occurs, depending on how many
// records are updated it can take a while. This gets called by changes feed
// listener that updates screen and closes modal windows.
var updateInModalMode = function(callback) {
    if ($modal) {
        $modal.find('.submit').text('Updating...');
        $modal.find('.btn').attr('disabled','disabled');
        $modal.find('[name]').attr('disabled','disabled');
    }
    callback();
}

// set buttons and fields back to normal to allow for another try at submit
var handleModalError = function(err) {
    $modal.find('.submit').text('Submit');
    $modal.find('.btn').removeAttr('disabled');
    $modal.find('[name]').removeAttr('disabled');
    alert('Bulk Edit Errors: ' + JSON.stringify(err));
    console.error('bulk edit errors', err);
}

var handleMarkInvalid = function(ev) {
    ev.preventDefault();

    var docs = [],
        msg;

    var validate = function($form) {
        var valid = true;
        $form.find(':input').each(function(idx, el) {
            var $el = $(el);
            if (!$el.val().trim()) {
                $el.closest('.control-group').addClass('error');
                $form.find('.error-msg').show();
                valid = false;
            }
        });
        return valid;
    };

    var onSubmit = function(ev) {
        ev.preventDefault();
        var $el = $(this),
            $form = $el.closest('.modal').find('form');

        if (!validate($form)) return;

        var reason = $form.find('[name=reason]').val().trim();

        for (var i in docs) {
            docs[i].errors.push({
                code:'marked_invalid',
                message: reason
            });
        }

        updateInModalMode(function() {
            db.bulkSave(docs, function(err, data) {
                if (err) return handleModalError(err);
                setupModalClose(data);
                //changes listener will update screen
            });
        });
    }

    var options = {};

    doBulkEdit(options, function(err, _docs) {
        if (err) return alert(err);
        // setup modal
        var note = 'Updating '+_docs.length+' records';
        $modal = $(templates.render('modal_edit_invalid.html', {}, {note: note}));
        $modal.modal('show');
        $modal.on('click','.cancel', onModalCancel);
        $modal.on('click','.submit', onSubmit);
        $('#invalid-reason').focus();
        docs = _docs;
    });
}

var handleEditDelete = function(ev) {
    ev.preventDefault();
    var docs = [];

    var onSubmit = function(ev) {
        ev.preventDefault();
        var $el = $(this);
        updateInModalMode(function() {
            db.bulkSave(docs, function(err, data) {
                if (err) return handleModalError(err);
                setupModalClose(data);
                //changes listener will update screen
            });
        });
    }

    var options = {extra: {_deleted: true}};
    doBulkEdit(options, function(err, _docs) {
        if (err) return alert(err);
        // setup modal
        var title = 'Permanently remove '+_docs.length+' records?';
        $modal = $(templates.render('modal.html', {}, {title: title}));
        $modal.modal('show');
        $modal.on('click','.cancel', onModalCancel);
        $modal.on('click','.submit', onSubmit);
        docs = _docs;
    });

}

// update related_entities property on data record, ignores facility if it's a
// district.
var updateFacility = function(docs, facility) {
    docs.forEach(function(record) {
        if (!record.related_entities)
            record.related_entities = {clinic: {}};
        if (!record.related_entities.clinic)
            record.related_entities.clinic = {};
        if (facility.type === 'health_center')
            record.related_entities.clinic = {parent: facility}
        else
            record.related_entities.clinic = facility
        record.errors = _.reduce(record.errors, function(errors, error) {
          if (!(error.code === 'sys.facility_not_found' && record.related_entities.clinic)) {
            errors.push(error);
          }
          return errors;
        }, []);
    });
};

var getFacilityDesc = function(doc) {
  doc = doc || {};
  var parts = [],
      contact = doc.contact;
  if (doc.name) parts.push(doc.name)
  if (contact && contact.name) parts.push(contact.name)
  if (contact && contact.rc_code) parts.push(contact.rc_code)
  if (contact && contact.phone) parts.push(contact.phone)
  return parts.join(', ');
}

function toggleDropdownLink(cls, enable) {
    var $el = $('.controls .edit-mode ' + cls).parent('li');

    $el.toggleClass('disabled', !enable);
    if (enable) {
        $el.attr('href', '#');
    } else {
        $el.removeAttr('href');
    }
}

exports.handleUpdateDropdown = function(ev) {
    var docs = getSelectedDocs(),
        updateable,
        deletable,
        markValid,
        markInvalid;

    ev.preventDefault();

    deletable = !!docs.length;
    updateable = docs.length > 0 && _.all(docs, function(doc) {
        return doc.form;
    });
    markInvalid = _.any(docs, function(doc) {
        return doc.form && (!doc.errors || doc.errors.length === 0);
    });
    markValid = _.any(docs, function(doc) {
        return doc.form && (doc.errors && doc.errors.length > 0);
    });

    toggleDropdownLink('.edit-update', updateable);
    toggleDropdownLink('.edit-delete', deletable);
    toggleDropdownLink('.mark-invalid', markInvalid);
    toggleDropdownLink('.clear-invalid', markValid);
};

function handleUpdateFacility(ev) {
    ev.preventDefault();

    var docs = [],
        data = [];

    function onSubmit(ev) {
        ev.preventDefault();
        var $el = $(this),
            formData = $el.closest('.modal').find('form').serializeArray(),
            facility = _.findWhere(data, {
                id: formData[0].value
            });

        if (facility) {
            updateFacility(docs, facility.doc);
        } else {
            // error — short circuit
            return $modal.find('.alert').show();
        }
        updateInModalMode(function() {
            db.bulkSave(docs, function(err, data) {
                if (err) return handleModalError(err);
                setupModalClose(data);
                //changes listener will update screen
            });
        });
    }

    doBulkEdit({}, function(err, _docs) {
        if (err) return alert(err);
        // setup modal
        var note = 'Update '+_docs.length+' records?';

        $modal = $(templates.render('update_facility_modal.html', {}, {
            note: note
        }));
        $modal.modal('show');
        configureControl({
            allowClear: false,
            el: $modal.find('[name=facility]'),
            data: data,
            placeholder: 'Select facility',
            onSelectChange: function() {} // do nothing special
        });
        $modal.on('click','.cancel', onModalCancel);
        $modal.on('click','.submit', onSubmit);
        docs = _docs;
        var view = 'facilities',
            q = {include_docs: true};

        if (district) {
             view = 'facilities_by_district';
             q.startkey = [district];
             q.endkey = [district, {}];
        }

        db.getView(ddoc, view, q, function(err, result) {
            _.each(result.rows, function(row) {
                if (row.doc.type !== 'district_hospital') {
                    data.push({
                        doc: row.doc,
                        id: row.id,
                        text: getFacilityDesc(row.value)
                    });
                }
            });
            data.sort(sortSelect2Data);
        });
    });
}

var handleClearInvalid = function(ev) {
    ev.preventDefault();

    var docs = [];

    var onSubmit = function(ev) {
        ev.preventDefault();
        for (var i in docs) {
            docs[i].errors = [];
        }
        updateInModalMode(function() {
            db.bulkSave(docs, function(err, data) {
                if (err) return handleModalError(err);
                setupModalClose(data);
            });
        });
    }

    var options = {};
    doBulkEdit(options, function(err, _docs) {
        if (err) {
            return alert(err);
        }
        // setup modal
        var title = 'Mark as Valid',
            note = _s.sprintf('Update %d records', _docs.length);

        $modal = $(templates.render('modal.html', {}, {
            title: title,
            note: note
        }));

        $modal.modal('show');
        $modal.on('click','.cancel', onModalCancel);
        $modal.on('click','.submit', onSubmit);
        docs = _docs;
    });
}

var handleScheduleGroupUpdate = function(ev) {
    // just handle state changes for now
    ev.preventDefault();
    var el = $(ev.target),
        state_val = el.attr("data-state-val"),
        doc = el.closest('[rel]').data('data-record'),
        tasks = el.closest('tbody').find('[data-tasks-idx]');

    if (!doc) return alert("Failed to find record.");
    if (!tasks) return alert("Failed to find tasks.");

    var onSubmit = function(ev) {
        ev.preventDefault();
        tasks.each(function(i, el) {
            var idx = parseInt($(el).attr('data-tasks-idx'), 10);
            // ignore sent tasks
            if (doc.scheduled_tasks[idx].state === 'sent') {
                return;
            }
            doc.scheduled_tasks[idx].state = state_val;
        });
        updateInModalMode(function() {
            db.saveDoc(doc, function(err, data) {
                if (err) return handleModalError(err);
                setupModalClose([data]);
            });
        });
    }

    // setup modal
    var title = 'Modify Schedule Group';
    var note = 'Update '+tasks.length+' messages?';
    $modal = $(templates.render('modal.html', {}, {
        title: title,
        note: note
    }));
    $modal.modal('show');
    $modal.on('click','.cancel', onModalCancel);
    $modal.on('click','.submit', onSubmit);
};

// if the message doesn't have a document, create one and append related_entities if possible
exports.checkMessageDoc = function(doc, data, callback) {
    var user,
        name,
        phone;

    if (doc) {
        callback(doc);
    } else {
        user = exports.user;
        phone = user && user.phone;
        name = user && user.name;

        doc = {
            errors: [],
            form: null,
            from: phone,
            reported_date: Date.now(),
            tasks: [],
            kujua_message: true,
            type: 'data_record',
            sent_by: name || 'unknown'
        };

        // contact id for phone selected
        if (data.id) {
            db.getDoc(data.id, function(err, contact) {
                doc.related_entities = {
                    clinic: contact
                };
                callback(doc);
            });
        } else {
            callback(doc);
        }
    }
}

exports.countChars = function($message, $modal) {
    var count = $message.val().length;
    if (count > 100) {
        $modal.find('.modal-footer .note').html(count + ' characters');
    }
}

exports.handleSendMessage = function(ev) {
    ev.preventDefault();

    var $el = $(ev.currentTarget),
        docId = $el.attr('data-doc'),
        doc = $el.closest('[rel]').data('data-record'),
        $form,
        $phone,
        phoneData,
        $message,
        to;

    function validate() {
        var valid = true;

        $phone = $form.find('[name=phone]');
        phoneData = $phone.select2('data') || {};
        $message = $form.find('[name=message]');
        if (!RE_PHONE.test(phoneData.phone)) {
            $phone.closest('.control-group').addClass('error')
                .find('.help-block').show();
            valid = false;
        } else {
            $phone.closest('.control-group').find('.help-block').hide();
        }
        if (!$message.val().trim()) {
            $message.closest('.control-group').addClass('error')
                .find('.help-block').show();
            valid = false;
        } else  {
            $message.closest('.control-group').find('.help-block').hide();
        }
        return valid;
    };

    function onSubmit(ev) {
        ev.preventDefault();

        if (!validate()) {
            return;
        }

        exports.checkMessageDoc(doc, phoneData, function(doc) {
            updateInModalMode(function() {

                db.newUUID(function (err, uuid) {
                    var user = exports.user;

                    if (err) {
                        return handleModalError(err);
                    }
                    doc.tasks.push({
                        messages: [{
                            from: user && user.phone,
                            sent_by: user && user.name || 'unknown',
                            to: phoneData.phone,
                            message: $message.val().trim(),
                            uuid: uuid
                        }],
                        state: 'pending'
                    });
                    db.saveDoc(doc, function(e, data) {
                        if (err) {
                            handleModalError(e);
                        } else {
                            setupModalClose([data]);
                        }
                    });
                });
            });
        });
    }

    // setup modal
    if (doc) {
        to = objectpath.get(doc, 'related_entities.clinic.contact.phone');

        if (!to) {
            to = doc.from;
        }
    } else {
        to = $el.attr('data-phone');
    }
    $modal = $(templates.render('modal_send_message.html', {}, {
        to: to
    }));
    $modal.modal({
        backdrop: 'static',
        show: true,
        noFocus: true
    });
    $modal.on('click','.cancel', onModalCancel);
    // lazily bind doc
    if (docId) {
        $modal.find('.submit').attr('disabled', 'disabled');
        db.getDoc(docId, function(err, _doc) {
            doc = _doc;
            $modal.on('click', '.submit', onSubmit);
            $modal.find('.submit').removeAttr('disabled');
        });
    } else {
        $modal.on('click','.submit', onSubmit);
    }
    $form = $modal.find('form');
    $phone = $form.find('[name=phone]');
    setupPhoneTypeahead($phone);
    $message = $form.find('[name=message]');

    if ($phone.val()) {
        $message.focus();
    } else {
        $phone.focus();
    }

    $message.on('keyup', function() {
        exports.countChars($message, $modal);
    });
};

function setupPhoneTypeahead($el, requirePhone) {
    configureControl({
        el: $el,
        query: function(query) {
            query.requirePhone = !!requirePhone;
            queryContacts(query);
        },
        initSelection: function($el, callback) {
            var number = $el.val();

            queryContacts({
                callback: function(data) {
                    callback(_.first(data && data.results));
                },
                create: true,
                term: number
            });
            callback({
                id: number,
                phone: number,
                text: number
            });
        },
        placeholder: 'Phone',
        createSearchChoice:function(term, data) {
            var results = $(data).filter( function() {
                return this.text.localeCompare(term) === 0;
            });

            if (/^\+?\d*$/.test(term) && results.length === 0) {
                return {
                    id: term,
                    phone: term,
                    text: term
                };
            }
        },
        onSelectChange: function() {}
    });
}

var toggleEditMode = function(table) {
    table = $(table);
    if (table.hasClass('read-mode')) {
        table.addClass('edit-mode').removeClass('read-mode')
            .find('.btn-group.menu').hide();
        table.siblings().find('.btn-group.menu').hide();
    } else if (table.hasClass('edit-mode')) {
        table.removeClass('edit-mode').addClass('read-mode')
            .find('.btn-group.menu').show();
        table.siblings().find('.btn-group.menu').show();
    }
    table.find('[data-tasks-remove-idx]')
        .removeAttr('data-tasks-remove-idx')
        .removeClass('tasks-removal-pending');
    table.find('.tasks-removal').remove();
};

var handleScheduleGroupSave = function(ev) {
    ev.preventDefault();
    //save scheduled tasks data
    var button = $(ev.target),
        doc = button.closest('[rel]').data('data-record'),
        table = button.closest('tbody');

    // disable while we do IO
    button.attr('disabled', 'disabled');
    button.siblings('.cancel').attr('disabled', 'disabled');

    var tasks = table.find('[data-tasks-idx]'),
        new_tasks = table.find('.new-task'),
        group,
        type;

    var finalize = function(err, doc) {

        button.removeAttr('disabled');
        button.siblings('.cancel').removeAttr('disabled', 'disabled');

        if (err) return alert("Save failed. " + err);

        // purge removed tasks
        // originally used .splice here to remove but had issues
        var keep_tasks = [];
        for (var i in doc.scheduled_tasks) {
            if (doc.scheduled_tasks[i])
                keep_tasks.push(doc.scheduled_tasks[i]);
        }
        doc.scheduled_tasks = keep_tasks;

        db.saveDoc(doc, function(err, data) {
            if (err) return alert('Save failed. ' + err);
            if (!data.ok) return alert('Save failed.');
            toggleEditMode(table);
            //once doc is saved changes listener will update the row
        });
    };

    if (tasks.length === 0 && new_tasks.length === 0)
        return finalize('Nothing to update.');

    if (!doc)
        return finalize('No data record found.');

    var updated = false,
        valid = [];

    // update existing tasks
    tasks.each(function(idx, el) {
        var task = $(el),
            task_idx = task.attr('data-tasks-idx'),
            remove_idx = task.attr('data-tasks-remove-idx');

        // ignore sent messages/tasks
        if (task.find('.tasks-state-sent').length > 0) {
            return;
        }

        // mark undefined, remove tasks later to not affect index
        // values
        if (remove_idx) {
            updated = true;
            return doc.scheduled_tasks[remove_idx] = null;
        }

        // state
        var task_field = task.find('.tasks-state'),
            val = task_field.find('[data-save-val]').attr('data-save-val'),
            orig = task_field.find('[data-orig-val]').attr('data-orig-val');
        if (!val) {
            valid.push('State value is empty.');
            task_field.find('.control-group').addClass('error');
        }
        if (val && doc.scheduled_tasks[task_idx].state !== val) {
            doc.scheduled_tasks[task_idx].state = val;
            updated = true;
        }

        // due
        task_field = task.find('.tasks-due');
        val = task_field.find('.datepicker').data('datetimepicker').getLocalDate().toISOString();
        orig = task_field.find('[data-orig-val]').attr('data-orig-val');
        if (!val) {
            valid.push('Date is empty.');
            task_field.find('.control-group').addClass('error');
        }
        if (val && doc.scheduled_tasks[task_idx].due !== val) {
            doc.scheduled_tasks[task_idx].due = val;
            updated = true;
        }

        // to/phone
        task_field = task.find('.tasks-to');
        val = (task_field.find('input').select2('data') || {}).phone;
        orig = task_field.find('.val').text();
        if (!val) {
            valid.push('Phone field is empty.');
            task_field.find('.control-group').addClass('error');
        }
        if (!RE_PHONE.test(val)) {
            valid.push('Failed to parse phone number.');
            task_field.find('.control-group').addClass('error');
        } else {
            val = RE_PHONE.exec(val)[1];
        }
        if (val && doc.scheduled_tasks[task_idx].messages[0].to !== val) {
            doc.scheduled_tasks[task_idx].messages[0].to = val;
            updated = true;
        }

        // message
        task_field = task.find('.tasks-message');
        val = task_field.find('textarea').val();
        orig = task_field.find('.val').text();
        if (!val) {
            valid.push('Message field is empty.');
            task_field.find('.control-group').addClass('error');
        }
        if (val && doc.scheduled_tasks[task_idx].messages[0].message !== val) {
            doc.scheduled_tasks[task_idx].messages[0].message = val;
            updated = true;
        }

        // save the type and group the same as siblings
        if (!type || !group) {
            type = doc.scheduled_tasks[task_idx].type;
            group = doc.scheduled_tasks[task_idx].group;
        }
    });

    for (var i = 0; i < new_tasks.length; i++) {

        var new_task = $(new_tasks.get(i));

        var to = new_task.find('.tasks-to [name=phone]'),
            match = (to.select2('data') || {}).phone.match(RE_PHONE),
            state = new_task.find('[data-save-val]').attr('data-save-val'),
            due = new_task.find('.tasks-due input'),
            msg = new_task.find('.tasks-message textarea'),
            msg_val = msg.val();

        if (!due.val()) {
            due.closest('.control-group').addClass('error');
            return finalize('Date is not valid.');
        }
        if (!match) {
            to.closest('.control-group').addClass('error');
            return finalize('Phone number is not valid.');
        }
        if (!msg_val) {
            msg.closest('.control-group').addClass('error');
            return finalize('Please include a message.');
        }

        var task = {
            due: moment(due.val(), 'DD-MM-YYYY HH:mm').toISOString(),
            state: state,
            type: type,
            group: group,
            messages: [{
                to: match[1],
                message: msg_val
            }]
        };
        doc.scheduled_tasks.push(task);
        updated = true;
    }

    if (valid.length !== 0)
        return finalize('Data is not valid:\n  '+valid.join('\n  '));

    if (!updated)
        return finalize('Nothing was changed.');

    finalize(null, doc);
};

/*
 * get revs_info (exclusive with fetching rev)
 */
var fetchRevsInfo = function(id, callback) {
    if (!id || !callback) {
        return;
    } else if (cache.revs_info[id]) {
        return callback(cache.revs_info[id]);
    }
    db.getDoc(id, {
        revs_info: true
    }, function(err, doc) {
        if (err) {
            alert('Error fetching document.', err);
        } else {
            cache.revs_info[id] = doc._revs_info;

            callback(cache.revs_info[id]);
        }
    });
};

/*
 * optional rev
 */
var fetchDoc = function(id, rev, callback) {
    var q = {};
    if (!id) return;
    if (typeof(rev) === 'function' && !callback) {
        callback = rev;
        rev = undefined;
    }
    if (rev) q = {rev: rev};
    db.getDoc(id, q, callback);
};

function updateRevNav($div) {
    var id = $div.attr('rel'),
        rev = $div.attr('data-rev'),
        $nav = $div.find('.data-record-revisions'),
        $fwd = $nav.find('.next'),
        $back = $nav.find('.prev');

    fetchRevsInfo(id, function(revs) {
        var entry,
            index,
            next,
            prev;

        entry = _.findWhere(revs, {
            rev: rev
        });
        index = _.indexOf(revs, entry);
        next = revs[index - 1];
        prev = revs[index + 1];
        // revs are in reverse chronological
        if (next) {
            $fwd.enable().attr('data-rev', next.rev).attr('title', 'Next revision');
        } else {
            $fwd.disable().removeAttr('data-rev').attr('title', 'No next revision');
        }
        if (prev && prev.status === 'available') {
            $back.enable().attr('data-rev', revs[index + 1].rev).attr('title', 'Previous revision');
        } else {
            $back.disable().removeAttr('data-rev');
            if (prev) {
                $back.attr('title', 'Previous revision not available.');
            } else {
                $back.attr('title', 'No previous revision');
            }
        }
    });
};

function renderRevision(id, rev, callback) {
    fetchDoc(id, rev, function(err, data) {
        if (!err) {
            renderRecord({
                doc: data,
                id: data._id
            });
            callback();
        }
    });
}

var handleClickRevision = function(ev) {
    ev.preventDefault();
    var $btn = $(this),
        $div = $btn.closest('.data-record'),
        id = $div.attr('rel'),
        rev = $btn.attr('data-rev');

    // disable btn until done processing
    $btn.disable();

    renderRevision(id, rev, function() {
        var $div = $('[rel=' + id + ']');

        $div.attr('data-rev', rev);
        updateRevNav($div);
    });
};

/*
 * TODO move all listeners into object so they are named and can be
 * removed/added with iterator.
 **/
function setupListeners() {
    var $document = $(document),
        $window = $(window),
        onScroll;

    onScroll = _.throttle(function() {
        if (!lastRecord) {
            $('.ajax-loader').show();
            renderRecords();
        }
    }, 700);

    $window.on('scroll', function () {
        if ($window.scrollTop() >= $document.height() - $window.height() - 10) {
            onScroll();
        }
    });

    // update screen from new records in changes feed
    $document.on('data-record-updated', onDataRecordUpdated);

    // bind to: field error marks so they can be updated
    $document.on('click', '.tasks-data_record .error-missing-phone', function(ev) {
        var $this = $(this),
            form = $this.siblings('form');

        $this.hide();
        form.css({
            display: 'inline',
            position: 'absolute',
            padding: '10px',
            width: 'auto',
            background: '#fff',
            'border-radius': '4px',
            border: '1px solid #ccc'
        });
        // configure bootstrap typeahead effect
        setupPhoneTypeahead($('[name=phone]', form));
    });

    // remove error highlighting on subsequent tries
    $document.on( 'focus', '.tasks-data_record .control-group [type=text]', function(ev) {
            $(this).closest('.control-group').removeClass('error');
    });

    // handle updating of 'to' field in message task
    $document.on('click', '.tasks-data_record [type=submit]', function(ev) {
        ev.stopPropagation();
        ev.preventDefault();
        var btn = $(this),
            form = btn.closest('form'),
            rev = btn.siblings('input[name=_rev]').val(),
            id = btn.siblings('input[name=_id]').val(),
            tasks_idx = parseInt(
                btn.closest('[data-tasks-idx]').attr('data-tasks-idx'), 10
            ),
            idx = parseInt(btn.siblings('input[name=idx]').val(), 10),
            input = btn.siblings('input[type=text]'),
            match = (input.select2('data') || {}).phone.match(RE_PHONE),
            phone = match ? match[1] : '';
        if (!phone) {
            btn.closest('.control-group').addClass('error');
            return;
        }
        db.getDoc(id, function(err, data) {
            if (err) { return alert(err); }
            data.tasks[tasks_idx].messages[idx].to = phone;
            data.tasks[tasks_idx].state = 'pending';
            data._rev = rev; // set the rev from the form

            for (var i in data.errors) {
                // remove related errors
                var e = data.errors[i];
                if (e.error === 'Could not find message recipient.') {
                    // legacy error messages
                    data.errors.splice(i, 1);
                } else if (e.code && e.code.match(/recipient_not_found/)) {
                    data.errors.splice(i, 1);
                }
            }

            db.saveDoc(data, function(err, data) {
                if (err) { return alert(err); }
                if(!data.ok) {
                    return alert('saveDoc failed.');
                }
                //once doc is saved changes listener will update the row
            });
        });
    });

    $document.on('click', '#data-records [name=select-row-checkbox]', handleSelectRow);

    $document.on('click', '#data-records [data-action=select-all]', handleSelectAllRows);

    $document.on('click', '#data-records [data-action=unselect-all]', handleUnselectAllRows);

    $document.on('click', '.controls .edit-mode li:not(.disabled) .edit-update', handleUpdateFacility);

    $document.on('click', '.controls .edit-mode li:not(.disabled) .edit-delete', handleEditDelete);

    $document.on('click', '.controls .edit-mode li:not(.disabled) .mark-invalid', handleMarkInvalid);

    $document.on('click', '.controls .edit-mode li:not(.disabled) .clear-invalid', handleClearInvalid);

    $document.on('click', '#data-records .message', function(ev) {
        var $record;
        if ($(ev.target).closest('button').length === 0) {
            ev.preventDefault();
            $record = $(this).parents('.data-record');
            $record.toggleClass('expanded');
            if ($record.is('.expanded')) {
                updateRevNav($record);
            }
        }
    });

    $document.on('click', '.tasks-data_record .group-header .update', handleScheduleGroupUpdate);

    $document.on('click', '.tasks-data_record .group-header .edit', function(ev) {
        ev.preventDefault();
        var el = $(ev.target),
            table = el.closest('tbody');
        toggleEditMode(table);
        table.find('.tasks-due .datepicker').datetimepicker().each(function(idx, el) {
            var $el = $(el),
                picker = $el.data('datetimepicker'),
                val = $el.closest('.tasks-due').find('[data-orig-val]').attr('data-orig-val');

            if (val) {
                if (!/^\d{4}-\d{2}-\d{2}/.test(val)) { // if not ISOString format, parseInt
                    val = parseInt(val, 10);
                }
                picker.setLocalDate(new Date(val));
            } else {
                return;
            }
        });
        setupPhoneTypeahead(table.find('.tasks-to input'), true);
    });

    $document.on('click', '.tasks-data_record .group-header .cancel', function(ev) {
        // undo changes for group
        ev.preventDefault();
        var table = $(ev.target).closest('tbody');

        if (table.find('.new-task').length !== 0) {
            if (confirm('New rows were created, cancel anyway?'))
                table.find('.new-task').remove();
            else
                return;
        }

        // reset field values to original on cancel
        table.find('.tasks-state').each(function(idx, td) {
            var el = $(td).find('[data-orig-val]'),
                orig_val = el.attr('data-orig-val'),
                save_val = el.attr('data-save-val');

            if (!orig_val) return;
            el.attr('data-save-val', orig_val);
            el.attr('data-orig-val', '');
            el.removeClass('tasks-state-'+save_val);
            el.addClass('tasks-state-'+orig_val);
        });
        table.find('.tasks-to').each(function(idx, td) {
            td = $(td);
            td.find('input').val(td.find('.val').text());
        });
        table.find('.tasks-message').each(function(idx, td) {
            td = $(td);
            td.find('textarea').val(td.find('.val').text());
        });
        toggleEditMode(table);
    });

    $document.on('click', '.tasks-data_record .remove', function(ev) {
        ev.preventDefault();
        var el = $(ev.target),
            row = el.closest('tr');
        if (row.attr('data-tasks-idx')) {
            // setup task for removal or cancel
            row.attr('data-tasks-remove-idx', row.attr('data-tasks-idx'));
            row.addClass('tasks-removal-pending');
            row.after(
                '<tr class="tasks-removal">'
                + '<td colspan="5" class="tasks-removal">'
                + '<p>Save to complete removal.</p>'
                + '</td>'
                + '</tr>'
            );
        } else {
            // just update the DOM if task doesn't exist yet
            row.remove();
        }
    });

    $document.on('click', '.tasks-data_record .add-new', function(ev) {
        ev.preventDefault();
        var el = $(ev.target),
            table = el.closest('table');
        // setup new row
        var new_task = table.find('#new-task-template').clone();
        new_task.removeAttr('id')
            .addClass('new-task')
            .find('.tasks-due .datepicker')
            .datetimepicker();
        // revert select2 changes
        new_task.find('.select2-container').replaceWith(new_task.find('[name=phone]').removeClass('select2-offscreen'));
        el.closest('tr').after(new_task);
        setupPhoneTypeahead(new_task.find('.tasks-to [name=phone]'));
    });

    $document.on('click', '.tasks-data_record .group-header .save', handleScheduleGroupSave);

    $document.on('click', '.tasks-data_record .tasks-state .dropdown-menu a', function(ev) {
        // maintain data-orig-val and data-save-val on state element. used for
        // saving later on.
        ev.preventDefault();
        var el = $(ev.target),
            changeEl = el.closest('.tasks-state').find('[data-save-val]'),
            new_val = el.closest('a').attr('data-state'),
            orig_val = changeEl.attr('data-orig-val'),
            old_val = changeEl.attr('data-save-val');

        if (!new_val || (new_val === old_val))
            return;

        // on first change save original value for cancel
        if (!orig_val)
            changeEl.attr('data-orig-val', old_val);

        changeEl.attr('data-save-val', new_val);
        changeEl.removeClass('tasks-state-'+old_val);
        changeEl.addClass('tasks-state-'+new_val);
    });

    $document.on('click', '.data-record-revisions [data-rev]', handleClickRevision);
}

// return boolean true if the record matches the logged in user
var isInDistrict = function(record) {
    if(isAdmin) { return true; }

    if (record.related_entities &&
        record.related_entities.clinic &&
        record.related_entities.clinic.parent &&
        record.related_entities.clinic.parent.parent &&
        record.related_entities.clinic.parent.parent._id) {

        return district === record.related_entities.clinic.parent.parent._id;
    } else {
        return false;
    }
};

//
// user must either be admin or have associated district to view records.
// show records by reported_date if no district filter is applied.
//
// returns options for renderRecords function
//
function getViewOptionsForFilter(req) {
    if (!req) {
        if (cache.viewOptions) {
            return cache.viewOptions;
        } else {
            return;
        }
    }

    // null form key is used to query for records without a matching form def
    var hasForm = req.query.form === "null" || req.query.form,
        form = req.query.form === "null" ? null : req.query.form,
        valid = req.query.valid,
        dh_id = district ? district : req.query.dh_id,
        search = req.query.search,
        cl_id = req.query.cl_id,
        hc_id = req.query.hc_id,
        startkey = [1e15],
        endkey = [0],
        view = 'data_records';

    // always check for admin or enforce district filtering.
    if (!isAdmin && !district) {
        return {};
    }

    var q = _.extend(req.query, {
        include_docs: true,
        limit: limit || 50,
        descending: true,
        startkey: startkey,
        endkey: endkey
    });

    if (hasForm) {
        if (form === null) {
            startkey.unshift('null_form');
            endkey.unshift('null_form');
        } else {
            startkey.unshift(form + '');
            endkey.unshift(form + '');
        }
    }
    if (dh_id) {
        if (hc_id) {
            startkey.unshift(hc_id);
            endkey.unshift(hc_id);
        } else if (cl_id) {
            startkey.unshift(cl_id);
            endkey.unshift(cl_id);
        }
        startkey.unshift(dh_id);
        endkey.unshift(dh_id);
    } else if (hc_id) {
        startkey.unshift(hc_id);
        endkey.unshift(hc_id);
    } else if (cl_id) {
        startkey.unshift(cl_id);
        endkey.unshift(cl_id);
    }

    if (valid) {
        startkey.unshift(valid === 'true');
        endkey.unshift(valid === 'true');
    }

    // search id trumps the other filters
    // prepare fti search
    if (search) {
        view = '_fti/data_records';
        if (dh_id) {
            search += ' AND district: '+dh_id
        }
        q = {
            limit: 50,
            q: search,
            include_docs: true
        }
    }

    cache.viewOptions = {
        query: q,
        view: view
    };
    return {
        query: q,
        view: view
    };
}

function li_template(query, title, baseURL) {
    return _.template('<li><a href="{{baseURL}}/?{{query}}">{{title}}</a></li>', {
        baseURL: baseURL,
        query: querystring.stringify(query),
        title: title
    });
}

function configureControl(options) {
    var el = options.el;

    el.parent().show();

    if (options.placeholder) {
        options.placeholder = $.kansotranslate(options.placeholder);
    }
    _.defaults(options, {
        allowClear: true
    });

    el.select2(options);
    el.on('change', function(ev) {
        options.onSelectChange(ev);
    });
}

function sortSelect2Data(a, b) {
    if (a.text === b.text) {
        return 0;
    } else {
        return a.text < b.text ? -1 : 1;
    }
}

function handleSelectChange(q, e, options) {
    var val = e.val,
        removeKeys = options.removeKeys || [];

    // fix for null & select2 for form filtering
    if (options.idKey === 'form' && val === '_messages') {
        val = 'null';
    }

    if (val && e.type !== 'select2-removed') {
        q[options.idKey] = val;
        if (options.textKey) {
            q[options.textKey] = options.text;
        }
        removeKeys = _.without(removeKeys, options.idKey, options.textKey);
    } else {
        q = _.omit(q, options.idKey);
        if (options.textKey) {
            q = _.omit(q, options.textKey);
        }
    }
    q = _.omit(q, removeKeys);

    require('duality/core').handleUrl(e, baseURL + '/?' + querystring.stringify(q));
}

function mapContactResult(row) {
    var doc = row.doc,
        contact = doc.contact,
        name = doc.name,
        contactName = contact && contact.name,
        code = contact && contact.rc_code,
        phone = contact && contact.phone,
        result;

    result = [name, contactName, code, phone];

    return {
        id: row.id,
        contactName: contactName,
        code: code,
        phone: phone,
        name: name,
        text: _.compact(result).join(', '),
        type: doc.type
    }
}

function handleContactResult(err, result, query) {
    var data;

    if (err) {
        if (Math.floor(err.status / 100) === 5 && !query.useView) {
            query.useView = true;
            queryContacts(query);
        } else {
            query.callback({
                results: []
            });
        }
    } else {
        if (result.rows.length === 0 && query.create) {
            data = [{
                id: query.term,
                phone: query.term,
                text: query.term
            }];
        } else {
            data = _.map(result.rows, mapContactResult);
        }
        if (query.doSort) {
            data.sort(sortSelect2Data);
        }
        if (query.requirePhone) {
            data = _.filter(data, function(item) {
                return !!item.phone;
            });
        }
        query.callback({
            results: data
        });
    }
}

function queryContacts(query) {
    var term = _s.trim(query.term).toLowerCase().replace(/^[*?]/, ''),
        view = 'contacts_by_id';

    if (query.byId || query.useView || !/[\w\d]/.test(term)) {
        if (query.useView) {
            view = 'contacts';
        }
        db.getView(ddoc, view, {
            include_docs: true,
            limit: 50,
            startkey: [district || null, term],
            endkey: [district || null, term + 'Z']
        }, function(err, result) {
            query.doSort = true;
            handleContactResult(err, result, query);
        });
    } else {
        if (!db.getFTI) {
            require('views/lib/couchfti').addFTI(db);
        }

        if (district) {
            term = 'district:' + district + ' AND ' + term;
        }

        db.getFTI(ddoc, 'contacts', {
            limit: 50,
            q: term.replace(/\*?$/, '*'),
            include_docs: true
        }, function(err, result) {
            handleContactResult(err, result, query);
        });
    }
}
//
// take query params and update clinics dropdown button on data records screen
//
function updateClinicsControl(query) {
    var q = _.clone(query),
        $select,
        val = q.dh_id || q.hc_id || q.cl_id;

    $select = $('#clinics-filter [name=clinics]');

    configureControl({
        display: val,
        el: $select,
        query: queryContacts,
        initSelection: function($el, callback) {
            queryContacts({
                byId: true,
                term: $el.val(),
                callback: function(data) {
                    callback(_.first(data && data.results));
                }
            });
        },
        placeholder: 'Contact',
        onSelectChange: function(e) {
            var data = $select.select2('data'),
                removeKeys = ['search', 'dh_id', 'dh_name', 'cl_id', 'cl_name', 'hc_id', 'hc_name'],
                idKey,
                textKey;

            if (data) {
                if (data.type === 'clinic') {
                    idKey = 'cl_id';
                    textKey = 'cl_name';
                } else if (data.type === 'district_hospital') {
                    idKey = 'dh_id';
                    textKey = 'dh_name';
                } else if (data.type === 'health_center') {
                    idKey = 'hc_id';
                    textKey = 'hc_name';
                }
            }

            handleSelectChange(q, e, {
                idKey: idKey,
                removeKeys: removeKeys,
                textKey: textKey,
                text: data && data.text
            });
        }
    });

    if (val) {
        $select.select2('val', val);
    }
}

function updateFormsControl(query) {
    var q = _.omit(query, 'search'),
        data = [],
        view = 'data_records_by_district_and_form',
        form = query.form;

    $select = $('#form-filter [name=forms]');

    configureControl({
        el: $select,
        data: data,
        placeholder: 'Form',
        onSelectChange: function(e) {
            handleSelectChange(q, e, {
                idKey: 'form'
            });
        }
    });

    // populate forms filter
    getCachedView(view, {
        q: {
            group: true
        },
        uniq: ['key',1]
    }, function(err, rows) {
        var val = form;

        if (err) {
            return alert(err);
        }

        if (form === 'null') {
            val = '_messages';
        }

        // clear old data
        data.splice(0, data.length);
        _.each(rows, function(row) {
            var key = row.key[1] + '';

            if (key !== 'null') {
                data.push({
                    id: key,
                    text: sms_utils.getFormTitle(key)
                });
            }
        });
        data.sort(sortSelect2Data);
        data.unshift({
            id: '_messages',
            text: 'Messages'
        });
        data.unshift({
            id: '*',
            text: 'Forms'
        });

        $select.select2('val', val);
    });
}

function updateSearchControl(query) {
    var q = _.clone(query);
    $('#search-filter').show().find('form').attr('action', baseURL);
    $('#search-filter .btn').off('click');
    $('#search-filter .btn').on('click', function(ev) {
        ev.preventDefault();
        $(ev.target).closest('form').submit();
    });
}

function getCachedView(view, options, callback) {

    if (!view || !callback) return;
    cache[view] = cache[view] ? cache[view] : [];
    options = options ? options : {q:{}};

    if (cache[view] && cache[view].length > 0) {
        return callback(null, cache[view]);
    }

    // populate cache
    db.getView(ddoc, view, options.q, function(err, data) {
        if (err) return callback(err);
        if (!options.uniq) {
            cache[view] = data.rows;
            return callback(null, cache[view]);
        }
        var uniq = {};
        _.each(data.rows, function(row) {
            if (options.uniq) {
                var val = row[options.uniq[0]][options.uniq[1]];
                if (uniq[val]) return;
                uniq[val] = 1; // hack to make unique list
            }
            cache[view].push(row);
        });
        callback(null, cache[view]);
    });

};

// update filters for records screen
function updateControls(req, callback) {

    // gather query params.
    var q = {
        dh_id: req.query.dh_id,
        dh_name: req.query.dh_name,
        hc_id: req.query.hc_id,
        hc_name: req.query.hc_name,
        cl_id: req.query.cl_id,
        cl_name: req.query.cl_name,
        form: req.query.form,
        valid: req.query.valid,
        search: req.query.search
    };

    var noneLink = '<li><a href="' + baseURL + '/">Show All</a></li>';

    if(!isAdmin && !district) return;

    $('.page-header .controls').first().html(
        templates.render('data_records_controls.html', req, {query:q})
    ).show();

    // add show all link
    $('.page-header .controls .records-filter')
        .find('.dropdown-menu').html(noneLink);

    $('#valid-filter').show().find('a.btn').html(
        'Valid' + (q.valid ? ': <b>' + q.valid + '</b>' : '') +
        ' <span class="caret"></span>'
    );

    // setup valid link
    $('.dropdown-menu.valid a').attr(
        'href', baseURL + '/?' + querystring.stringify(_.omit(q, 'valid'))
    );

    // append addl links for valid filter
    _.each(['true', 'false'], function(val) {
        var p = _.extend({}, q, { valid: val });
        $('.dropdown-menu.valid').append(
            li_template(p, (val === 'true' ? 'Valid' : 'Invalid'), baseURL)
        );
    });

    // update controls that use caching
    updateFormsControl(q);
    updateClinicsControl(q);
    updateSearchControl(q);

    callback();
}

function subDataRecordChanges() {
    db.changes({
        include_docs: true,
        filter:'emr/data_records'
    }, function(err, data) {
        if (!err && data && data.results) {
            $(document).trigger('data-record-updated', data);
        }
    });
}

exports.setupAddRecordButton = function() {
    var $iframe = $('#add-record-panel iframe'),
        src = $iframe.attr('src');

    /* don't show add record button if src on iframe is not ok */
    if (!src || src.substring(0, src.indexOf('?')) === window.location.pathname) {
        if (!$iframe.attr('data-visited')) {
            // if first retry wait 5s and retry
            $iframe.attr('data-visited', 'true');
            _.delay(exports.setupAddRecordButton, 5 * 1000);
        }
        return;
    }

    function finish() {
        /*
         * couldn't hide/unhide because some bootstrap code was causing it to
         * always be visible, decided to modify the DOM instead
         */
        var $btn = $(
            '<li class="add-record">'
              +'<div class="btn-group">'
              +'<button class="btn btn-primary dropdown-toggle" data-toggle="dropdown">'
                  +'<i class="icon-file-alt"></i>'
              +'</button>'
              +'</div>'
            +'</li>'
        );

        var existing = $('#topnav .add-record');

        if (existing.length) {
            existing.replaceWith($btn);
        } else {
            $btn.insertAfter('#topnav .add-message');
        }

        // TODO include sync_url param in iframe src
        $btn.on('click', 'button', function(ev) {
            // toggle add record div
            ev.preventDefault();
            ev.stopPropagation();
            $('#add-record-panel .dropdown-menu').toggle();
            $(this).closest('.btn-group').toggleClass('open');
        });
    };

    db = db || require('db').current();
    db.request({method:'HEAD', url: src}, function(err, data) {
        // if probably getting iframe src then don't show add record button
        if (err) return;
        finish();
    });

    $('#add-record-panel .close').on('click', function(ev) {
        $(this).closest('.dropdown-menu').hide();
        $('.navbar .add-record .btn-group').removeClass('open');
    });
};

exports.onDualityInit = function() {
    db = db || require('db').current();
    setupListeners();
//    subDataRecordChanges();
};

// exposed for testing purposes
exports.setDb = function(database) {
    db = database;
};

exports.init = function(req, options) {
    if (!options) {
        return;
    }
    district = options.district;
    isAdmin = options.isAdmin;
    locale = utils.getUserLocale(req);
    db = require('db').current(req);
    baseURL = require('duality/core').getBaseURL(req);

    // we need these reset for the initial show
    nextStartKey = null;
    lastRecord = null;
    firstRender = true;

    var options = getViewOptionsForFilter(req);

    updateControls(req, function() {
        renderRecords(options);
    });
}


text:
'use strict';

var expect  = require('chai').expect,
    _       = require('underscore'),
    model   = require('../../lib/model/db'),
    moment  = require('moment'),
    schedule= model.Schedule.build({ company_id : 1 }),
    CalendarMonth = require('../../lib/model/calendar_month');

describe('Check calendar month object', function(){

    it('Normalize provided date to be at the begining of the month',function(){
        var january = new CalendarMonth('2015-01-10', {schedule : schedule, today : moment.utc()});

        expect(
            january.get_base_date().date()
        ).to.be.equal(1);
    });

    it('Knows on which week day month starts', function(){
        var january = new CalendarMonth('2015-01-21', {schedule : schedule, today : moment.utc()});
        expect( january.week_day() ).to.be.equal(4);

        var feb = new CalendarMonth('2015-02-21', {schedule : schedule, today : moment.utc()});
        expect( feb.week_day() ).to.be.equal(7);
    });

    it('Knows how many blanks to put before first day of the month', function(){
        var january = new CalendarMonth('2015-01-11', {schedule : schedule, today : moment.utc()});
        expect( january.how_many_blanks_at_the_start() ).to.be.equal(3);

        var feb = new CalendarMonth('2015-02-11', {schedule : schedule, today : moment.utc()});
        expect( feb.how_many_blanks_at_the_start() ).to.be.equal(6);
    });

    it('Knows how many blanks to put after the last day of the month', function(){
        var january = new CalendarMonth('2015-01-11', {schedule : schedule, today : moment.utc()});
        expect( january.how_many_blanks_at_the_end() ).to.be.equal(1);

        var feb = new CalendarMonth('2015-02-11', {schedule : schedule, today : moment.utc()});
        expect( feb.how_many_blanks_at_the_end() ).to.be.equal(1);
    });

    it('Knows whether day is weekend', function(){
        var feb = new CalendarMonth('2015-02-12', {schedule : schedule, today : moment.utc()});
        expect(feb.is_weekend(12)).not.to.be.ok;
        expect(feb.is_weekend(21)).to.be.ok;
        expect(feb.is_weekend(22)).to.be.ok;
        expect(feb.is_weekend(23)).not.to.be.ok;
    });

    it('Knows how to generate data structure for template', function(){
        var january = new CalendarMonth('2015-01-11', { schedule : schedule, today : moment.utc() }),
          object_to_test = january.as_for_template();
        delete object_to_test['moment'];
        object_to_test.weeks.forEach(function(week){
          week.forEach(function(day){ delete day.leave_obj });
        });
        expect( object_to_test ).to.be.eql(
            {"month":"January","weeks":[[{"val":""},{"val":""},{"val":""},{"val":1},{"val":2},{"val":3,"is_weekend":true},{"val":4,"is_weekend":true}],[{"val":5},{"val":6},{"val":7},{"val":8},{"val":9},{"val":10,"is_weekend":true},{"val":11,"is_weekend":true}],[{"val":12},{"val":13},{"val":14},{"val":15},{"val":16},{"val":17,"is_weekend":true},{"val":18,"is_weekend":true}],[{"val":19},{"val":20},{"val":21},{"val":22},{"val":23},{"val":24,"is_weekend":true},{"val":25,"is_weekend":true}],[{"val":26},{"val":27},{"val":28},{"val":29},{"val":30},{"val":31,"is_weekend":true},{"val":""}]]}
        );

        var apr = new CalendarMonth('2015-04-11', { schedule : schedule, today : moment.utc() });
        object_to_test = apr.as_for_template();
        delete object_to_test['moment'];
        object_to_test.weeks.forEach(function(week){
          week.forEach(function(day){ delete day.leave_obj });
        });
        expect( object_to_test ).to.be.eql(
            {"month":"April","weeks":[[{"val":""},{"val":""},{"val":1},{"val":2},{"val":3},{"val":4,"is_weekend":true},{"val":5,"is_weekend":true}],[{"val":6},{"val":7},{"val":8},{"val":9},{"val":10},{"val":11,"is_weekend":true},{"val":12,"is_weekend":true}],[{"val":13},{"val":14},{"val":15},{"val":16},{"val":17},{"val":18,"is_weekend":true},{"val":19,"is_weekend":true}],[{"val":20},{"val":21},{"val":22},{"val":23},{"val":24},{"val":25,"is_weekend":true},{"val":26,"is_weekend":true}],[{"val":27},{"val":28},{"val":29},{"val":30},{"val":""},{"val":""},{"val":""}]]}
        );

    });

    it('Sanity checks pass', function(){

        var apr = new CalendarMonth('2015-04-01', { schedule : schedule, today : moment.utc() });

        expect(apr).to.be.a('object');

        expect(apr.how_many_days()).to.be.equal(30);
    });

    it('It knows whether day is bank holiday', function(){
        var mar = new CalendarMonth('2015-03-19', { bank_holidays : [{date : '2015-03-08'}], schedule : schedule, today : moment.utc() });

        expect(mar.is_bank_holiday(8)).to.be.ok;
        expect(mar.is_bank_holiday(10)).not.to.be.ok;
    });

});


text:
// Copyright(c) DEVSENSE s.r.o.
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN  *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.

using System;
using System.Diagnostics;

namespace Devsense.PHP.Syntax.Ast
{
	#region JumpStmt

	///
	/// Represents a branching (jump) statement (return, continue, break).
	///
    public sealed class JumpStmt : Statement
	{
		///
		/// Type of the statement.
		///
		public enum Types { Return, Continue, Break };

		private Types type;
        /// Type of current statement
        public Types Type { get { return type; } }

		///
        /// In case of continue and break, it is number of loop statements to skip. Note that switch is considered to be a loop for this case
        /// In case of return, it represents the returned expression.
        /// Can be null.
		///
        public Expression Expression { get { return expr; } internal set { expr = value; } }
		private Expression expr; // can be null

		public JumpStmt(Text.Span span, Types type, Expression expr)
			: base(span)
		{
			this.type = type;
			this.expr = expr;
		}

		///
        /// Call the right Visit* method on the given Visitor object.
        ///
        /// <param name="visitor">Visitor to be called.</param>
        public override void VisitMe(TreeVisitor visitor)
        {
            visitor.VisitJumpStmt(this);
        }
	}

	#endregion

	#region GotoStmt

    public sealed class GotoStmt : Statement
	{
		/// Label that is target of goto statement
        public VariableNameRef LabelName { get { return _labelName; } }
        private VariableNameRef _labelName;

		public GotoStmt(Text.Span span, VariableNameRef/*!*/labelName)
			: base(span)
		{
            Debug.Assert(!string.IsNullOrEmpty(labelName.Name.Value));
            _labelName = labelName;

        }

		///
        /// Call the right Visit* method on the given Visitor object.
        ///
        /// <param name="visitor">Visitor to be called.</param>
        public override void VisitMe(TreeVisitor visitor)
        {
            visitor.VisitGotoStmt(this);
        }
	}

	#endregion

	#region LabelStmt

    public sealed class LabelStmt : Statement
	{
        public VariableNameRef Name { get { return _name; } }
		private VariableNameRef _name;

		internal bool IsReferred { get { return isReferred; } set { isReferred = value; } }
		private bool isReferred;

		public LabelStmt(Text.Span span, VariableNameRef/*!*/name)
			: base(span)
		{
            Debug.Assert(!string.IsNullOrEmpty(name.Name.Value));

			_name = name;
		}

		///
        /// Call the right Visit* method on the given Visitor object.
        ///
        /// <param name="visitor">Visitor to be called.</param>
        public override void VisitMe(TreeVisitor visitor)
        {
            visitor.VisitLabelStmt(this);
        }
	}

	#endregion
}


text:
/**
 * Model class for the java type executable submission web flow
 *
 */
package org.imirsel.nema.webapp.model;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.imirsel.nema.model.JavaPredefinedCommandTemplate;

import edu.emory.mathcs.backport.java.util.Arrays;

/**
 * A null wrapper for {@link org.imirsel.nema.model.JavaPredefinedCommandTemplate}.
 * It supports for various display purpose.
 * @author gzhu1
 * @since 0.6.0
 *
 */
public class DiyJavaTemplate extends JavaPredefinedCommandTemplate {
	static private Log logger = LogFactory.getLog(DiyJavaTemplate.class);

	 MemoryOption[] memoryOptions = {
				new MemoryOption("max:1024m,min:512m", 0, "-Xmx1024m", "-Xms512m"),
				new MemoryOption("max:512m,min:256m", 1, "-Xmx512m", "-Xms256m"),
				new MemoryOption("max:256m,min:128m", 2, "-Xmx256m", "-Xms128m"),
				new MemoryOption("max:128m,min:64m", 3, "-Xmx128m", "-Xms64m") };

	@SuppressWarnings("unchecked")
	public List<MemoryOption> getMemoryOptions() {

		logger.debug("getMemoryOptions");
		return (List<MemoryOption>)Arrays.asList(memoryOptions);
	}

	private String zipJar;
	private static final long serialVersionUID = 1L;

	private int memoryOption;

	private String disableAssertionPackages;

	public String getDisableAssertionPackages() {
		return disableAssertionPackages;
	}

	public void setDisableAssertionPackages(String disableAssertionPackages) {
		this.disableAssertionPackages = disableAssertionPackages;
	}

	public void setMemoryOption(int memoryOption) {
		this.memoryOption = memoryOption;
		MemoryOption mo=getMemoryOptions().get(memoryOption);

		setMinMemory(mo.min);
		setMaxMemory(mo.max);
	}

	public int getMemoryOption() {
		return memoryOption;
	}

	public void setZipJar(String zipJar) {
		this.zipJar = zipJar;
	}

	public String getZipJar() {
		return zipJar;
	}

}


text:
package br.com.concretesolutions.canarinho.formatador;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.text.ParsePosition;
import java.util.Locale;
import java.util.regex.Pattern;

/** */
public final class FormatadorValor implements Formatador {

    private static final DecimalFormat FORMATADOR_MOEDA = (DecimalFormat) NumberFormat.getCurrencyInstance(new Locale("pt", "BR"));
    private static final Pattern PADRAO_DECIMAL = Pattern.compile("^\\d+(\\.\\d{1,2})?$");
    private static final Pattern PADRAO_MOEDA = Pattern.compile("\\d{1,3}(\\.\\d{3})*(,\\d{2})?");

    static {
        final DecimalFormatSymbols decimalFormatSymbols = FORMATADOR_MOEDA.getDecimalFormatSymbols();
        decimalFormatSymbols.setCurrencySymbol("");
        FORMATADOR_MOEDA.setMinimumFractionDigits(2);
        FORMATADOR_MOEDA.setDecimalFormatSymbols(decimalFormatSymbols);
        FORMATADOR_MOEDA.setNegativePrefix("-");
        FORMATADOR_MOEDA.setNegativeSuffix("");
        FORMATADOR_MOEDA.setPositivePrefix("");
        FORMATADOR_MOEDA.setParseBigDecimal(true);
    }

    private static class SingletonHolder {
        private static final FormatadorValor INSTANCE = new FormatadorValor();
    }

    static FormatadorValor getInstance() {
        return SingletonHolder.INSTANCE;
    }

    // No instance creation
    private FormatadorValor() {
    }

    @Override
    public String formata(String value) {
        return FORMATADOR_MOEDA.format(new BigDecimal(value));
    }

    @Override
    public String desformata(String value) {
        final BigDecimal valor = (BigDecimal) FORMATADOR_MOEDA.parse(value, new ParsePosition(0));
        return valor.toPlainString();
    }

    @Override
    public boolean estaFormatado(String value) {

        if (value == null)
            throw new IllegalArgumentException("Valor não pode ser nulo");

        return PADRAO_MOEDA.matcher(value).matches();
    }

    @Override
    public boolean podeSerFormatado(String value) {

        if (value == null)
            throw new IllegalArgumentException("Valor não pode ser nulo");

        return PADRAO_DECIMAL.matcher(value).matches();
    }
}