<commit_before>/**
 * @module ember-paper
 */
import Ember from 'ember';
import ContentComponent from 'ember-basic-dropdown/components/basic-dropdown/content';
import { nextTick } from 'ember-css-transitions/mixins/transition-mixin';
const { $ } = Ember;

function waitForAnimations(element, callback) {
  let computedStyle = window.getComputedStyle(element);
  if (computedStyle.transitionDuration && computedStyle.transitionDuration !== '0s') {
    let eventCallback = function() {
      element.removeEventListener('transitionend', eventCallback);
      callback();
    };
    element.addEventListener('transitionend', eventCallback);
  } else if (computedStyle.animationName !== 'none' && computedStyle.animationPlayState === 'running') {
    let eventCallback = function() {
      element.removeEventListener('animationend', eventCallback);
      callback();
    };
    element.addEventListener('animationend', eventCallback);
  } else {
    callback();
  }
}

/**
 * @class PaperMenuContent
 * @extends ContentComponent
 */
export default ContentComponent.extend({
  animateIn() {
    nextTick().then(() => {
      this.set('isActive', true);
      this.dropdownElement.style.transform = '';
    });
  },

  animateOut(dropdownElement) {
    let parentElement = this.get('renderInPlace') ? dropdownElement.parentElement.parentElement : dropdownElement.parentElement;
    let clone = dropdownElement.cloneNode(true);
    clone.id = `${clone.id}--clone`;
    let $clone = $(clone);
    parentElement.appendChild(clone);
    nextTick().then(() => {
      if (!this.get('isDestroyed')) {
        this.set('isActive', false);
        $clone.addClass('md-leave');
        waitForAnimations(clone, function() {
          $clone.removeClass('md-active');
          parentElement.removeChild(clone);
        });
      }
    });
  }
});<commit_msg>clone still needs to be removed if the component has been destroyed (#505)<commit_after>/**
 * @module ember-paper
 */
import Ember from 'ember';
import ContentComponent from 'ember-basic-dropdown/components/basic-dropdown/content';
import { nextTick } from 'ember-css-transitions/mixins/transition-mixin';
const { $ } = Ember;

function waitForAnimations(element, callback) {
  let computedStyle = window.getComputedStyle(element);
  if (computedStyle.transitionDuration && computedStyle.transitionDuration !== '0s') {
    let eventCallback = function() {
      element.removeEventListener('transitionend', eventCallback);
      callback();
    };
    element.addEventListener('transitionend', eventCallback);
  } else if (computedStyle.animationName !== 'none' && computedStyle.animationPlayState === 'running') {
    let eventCallback = function() {
      element.removeEventListener('animationend', eventCallback);
      callback();
    };
    element.addEventListener('animationend', eventCallback);
  } else {
    callback();
  }
}

/**
 * @class PaperMenuContent
 * @extends ContentComponent
 */
export default ContentComponent.extend({
  animateIn() {
    nextTick().then(() => {
      this.set('isActive', true);
      this.dropdownElement.style.transform = '';
    });
  },

  animateOut(dropdownElement) {
    let parentElement = this.get('renderInPlace') ? dropdownElement.parentElement.parentElement : dropdownElement.parentElement;
    let clone = dropdownElement.cloneNode(true);
    clone.id = `${clone.id}--clone`;
    let $clone = $(clone);
    parentElement.appendChild(clone);
    nextTick().then(() => {
      if (!this.get('isDestroyed')) {
        this.set('isActive', false);
        $clone.addClass('md-leave');
        waitForAnimations(clone, function() {
          $clone.removeClass('md-active');
          parentElement.removeChild(clone);
        });
      } else {
        parentElement.removeChild(clone);
      }
    });
  }
});<|endoftext|>


<commit_before><commit_msg>chore: Add link to readme.md for depend help (#1996)<commit_after><|endoftext|>


<commit_before>import Ember from 'ember';
const { computed, typeOf } = Ember;  // jshint ignore:line

import layout from './template';

const a = Ember.A;

const xToggle = Ember.Component.extend({
  layout: layout,
  classNames: ['x-toggle-component'],

  name: 'default',
  disabled: false,
  value: 'off',
  onLabel: undefined,
  offLabel: undefined,

  _on: computed('onLabel', function() {
    const {onLabel, defaultOnLabel} = this.getProperties('onLabel', 'defaultOnLabel');
    return typeOf(onLabel) === 'undefined' ? defaultOnLabel : onLabel;
  }),

  _off: computed('offLabel', function() {
    const {offLabel, defaultOffLabel} = this.getProperties('offLabel', 'defaultOffLabel');
    return typeOf(offLabel) === 'undefined' ? defaultOffLabel : offLabel;
  }),

  toggled: computed('value', 'onValue', 'offValue', function() {
    const { value, _onValue, _offValue } = this.getProperties('value', '_onValue', '_offValue');
    const validValues = a([_onValue, _offValue]);

    if(validValues.includes(value)) {
      return value === _onValue;
    } else {
      return undefined;
    }
  }),

  invalidState: computed('toggled', function() {
    return Ember.typeOf(this.get('toggled')) === 'undefined' ? ' invalid-state' : '';
  }),

  _preferBoolean(value) {
    if(value === 'true') { return true; }
    if(value === 'false') { return false; }

    return value;
  },

  _onValue: computed('_on', function () {
    const attrs = String(this.get('_on') || '').split('::');

    return this._preferBoolean(attrs.length === 1 ? attrs[0] : attrs[1]);
  }),

  _onLabel: computed('_on', function () {
    const _on = String(this.get('_on')) || '';
    return _on.split('::')[0];
  }),

  _offValue: computed('_off', function () {
    const attrs = String(this.get('_off') || '').split('::');

    return this._preferBoolean(attrs.length === 1 ? attrs[0] : attrs[1]);
  }),

  _offLabel: computed('_off', function () {
    const _off = String(this.get('_off')) || '';

    return _off.split('::')[0];
  }),

  themeClass: computed('theme', function () {
    var theme = this.get('theme') || 'default';

    return 'x-toggle-' + theme;
  }),

  forId: computed(function () {
    return this.get('elementId') + '-x-toggle';
  }),

  actions: {
    onClick(e) {
      const {value, _offValue, _onValue} = this.getProperties('value', '_offValue', '_onValue');
      e.stopPropagation();
      e.preventDefault();
      const currentState = value === _onValue;
      const oldValue = currentState ? _onValue : _offValue;
      const newValue = currentState ? _offValue : _onValue;

      this.ddau('onToggle', {
        code: 'toggled',
        oldValue: oldValue,
        newValue: newValue,
        context: this
      }, newValue);
    },

    setToValue(state, e) {
      const {toggled,_offValue, _onValue} = this.getProperties('toggled', '_offValue', '_onValue');
      e.stopPropagation();
      e.preventDefault();

      if(toggled !== state) {
        this.ddau('onToggle', {
          code: 'set',
          oldValue: state ? _offValue : _onValue,
          newValue: !state ? _offValue : _onValue,
          context: this
        }, !state ? _offValue : _onValue);
      }
    }
  },

  /**
   * Provide a DDAU "action" or "mut" response
   * @param  {string } action The name of the exposed action property
   * @param  {hash}    hash   A hash of attributes that are passed back to a "action"
   * @param  {mixed}   value  A value that is passed to the "update" function (aka, mut helper) if available
   * @return {boolean}        Pass back true if `mut` not used; if used then proxies mut's response back
   */
  ddau(action, hash, value) {
    if (this.attrs[action] && this.attrs[action].update) {
      this.attrs[action].update(value);
      return true;
    } else if (this.attrs[action]) {
      return this.attrs[action](hash);
    } else {
      // assume that container is using old-style actions
      this.sendAction(action, hash);
      return undefined;
    }
  }
});

xToggle[Ember.NAME_KEY] = 'x-toggle';
export default xToggle;
<commit_msg>fix: Don't trigger action if `disabled` is set<commit_after>import Ember from 'ember';
import layout from './template';

const { A, computed, typeOf } = Ember;  // jshint ignore:line

const xToggle = Ember.Component.extend({
  layout: layout,
  classNames: ['x-toggle-component'],

  name: 'default',
  disabled: false,
  value: 'off',
  onLabel: undefined,
  offLabel: undefined,

  _on: computed('onLabel', function() {
    const { onLabel, defaultOnLabel } = this.getProperties('onLabel', 'defaultOnLabel');
    return typeOf(onLabel) === 'undefined' ? defaultOnLabel : onLabel;
  }),

  _off: computed('offLabel', function() {
    const { offLabel, defaultOffLabel } = this.getProperties('offLabel', 'defaultOffLabel');
    return typeOf(offLabel) === 'undefined' ? defaultOffLabel : offLabel;
  }),

  toggled: computed('value', 'onValue', 'offValue', function() {
    const { value, _onValue, _offValue } = this.getProperties('value', '_onValue', '_offValue');
    const validValues = A([_onValue, _offValue]);

    if (validValues.includes(value)) {
      return value === _onValue;
    } else {
      return undefined;
    }
  }),

  invalidState: computed('toggled', function() {
    return Ember.typeOf(this.get('toggled')) === 'undefined' ? ' invalid-state' : '';
  }),

  _preferBoolean(value) {
    if (value === 'true') {
      return true;
    }

    if (value === 'false') {
      return false;
    }

    return value;
  },

  _onValue: computed('_on', function () {
    const attrs = String(this.get('_on') || '').split('::');

    return this._preferBoolean(attrs.length === 1 ? attrs[0] : attrs[1]);
  }),

  _onLabel: computed('_on', function () {
    const _on = String(this.get('_on')) || '';
    return _on.split('::')[0];
  }),

  _offValue: computed('_off', function () {
    const attrs = String(this.get('_off') || '').split('::');

    return this._preferBoolean(attrs.length === 1 ? attrs[0] : attrs[1]);
  }),

  _offLabel: computed('_off', function () {
    const _off = String(this.get('_off')) || '';

    return _off.split('::')[0];
  }),

  themeClass: computed('theme', function () {
    var theme = this.get('theme') || 'default';

    return 'x-toggle-' + theme;
  }),

  forId: computed(function () {
    return this.get('elementId') + '-x-toggle';
  }),

  actions: {
    onClick(e) {
      const { value, _offValue, _onValue } = this.getProperties('value', '_offValue', '_onValue');
      const currentState = value === _onValue;
      const oldValue = currentState ? _onValue : _offValue;
      const newValue = currentState ? _offValue : _onValue;

      e.stopPropagation();
      e.preventDefault();

      this.ddau('onToggle', {
        code: 'toggled',
        oldValue: oldValue,
        newValue: newValue,
        context: this
      }, newValue);
    },

    setToValue(state, e) {
      const { toggled, _offValue, _onValue } = this.getProperties('toggled', '_offValue', '_onValue');

      e.stopPropagation();
      e.preventDefault();

      if (toggled !== state) {
        this.ddau('onToggle', {
          code: 'set',
          oldValue: state ? _offValue : _onValue,
          newValue: !state ? _offValue : _onValue,
          context: this
        }, !state ? _offValue : _onValue);
      }
    }
  },

  /**
   * Provide a DDAU "action" or "mut" response
   * @param  {string } action The name of the exposed action property
   * @param  {hash}    hash   A hash of attributes that are passed back to a "action"
   * @param  {mixed}   value  A value that is passed to the "update" function (aka, mut helper) if available
   * @return {boolean}        Pass back true if `mut` not used; if used then proxies mut's response back
   */
  ddau(action, hash, value) {
    if (this.get('disabled')) {
      return;
    }

    if (this.attrs[action] && this.attrs[action].update) {
      this.attrs[action].update(value);
      return true;
    } else if (this.attrs[action]) {
      return this.attrs[action](hash);
    } else {
      // assume that container is using old-style actions
      this.sendAction(action, hash);
      return undefined;
    }
  }
});

xToggle[Ember.NAME_KEY] = 'x-toggle';

export default xToggle;
<|endoftext|>


<commit_before><commit_msg>[fix]<commit_after><|endoftext|>


<commit_before>import Ember from 'ember';
import OptionsSupport from './options-support';
import getControl from 'furnace-forms/utils/get-control';
export default Ember.Mixin.create({

	_decoratorName : 'select',

	optionControl : null,

	showOptionControl : false,

	select: function(index) {
		if(index==="0") {
			this.set('value',null);
		} else {
			Ember.assert('furnace-forms: no option with index '+index,this.get('_options')[index-1]);
			this.set('value',this.get('_options')[index-1].value);
		}
//		this.get("_options").invoke('set','selected',false);

//		var option=this.get("_options").findBy('index',index);
//		if(option) {
//			option.set('selected',true);
//		}

//		this._valueObserver();
		this.send('onSelect',index);
	},

	_controlForOption: null,

	_selectedIndexObserver:Ember.observer('selectedIndex', function() {
		var option = this.getOption();

		if(option && option.value!==this.get('value')) {
			this.set('value',option.value);
		}
		else {
			if(this.get('selectedIndex')===null) {
				this.set('value',null);
			}
		}
		var ret=null;

		option = this.get("_options").findBy('index',this.get('selectedIndex'));
		if(option && !option.get('selected')) {
			this.get("_options").invoke('set','selected',false);
			option.set('selected',true);
		} else if(!option) {
			this.get("_options").invoke('set','selected',false);
		}

		if(this._controlForOption!==option) {
			this._controlForOption=option;
			if(this._controlsLoaded) {
				var control=this.get("controls").findBy('index',this.get('selectedIndex'));
				if(control) {
					ret = control.get('optionControl');
				}
			} else if(option && option.control) {
				var meta=option.control;
				var options={};
				options['for']=this.get('value');
				options._path=this._panel._path;
				if(this.get('optionControl')) {
					this.get('optionControl').destroy();
				}
				ret = getControl.call(this,'value',meta,options);
			}

			if(ret) {
				this.set('showOptionControl',true);
			}
			else {
				this.set('showOptionControl',false);
			}

			if(ret!==this.get('optionControl')) {
				this.set('optionControl',ret);
			}
		}
	}),

	init: function() {
		Ember.warn('No options support for single-select',OptionsSupport.detect(this),{id:'furnace-forms:control.options-support-missing'});
		this._super();
		this._updateSelected();
		this._selectedIndexObserver();
	},

	getOption: function(index) {
		if(index===undefined) {
			index=this.get('selectedIndex')-1;
		}
		return this.get('_options')[index];
	},

	selectedOption : Ember.computed({
		get : function(key,value) {
			if(value) {
				this.set('value',value.get('value'));
			}
			return this.getOption();
		}
	}).readOnly(),

	selectedIndex : 0,

	_valueObserver: Ember.observer('value',function() {
		let selectedOption=this.get("_options").findBy('value',this.get('value'));
		let index=0;
		if(selectedOption) {
			index=selectedOption.index;
		}
		this.set('selectedIndex',index);
		this._super();
	}),

	_updateSelected : Ember.observer('_options.[].selected',function() {
		var option=this.getOption();
		if(!option || this.get('value')!==option.value) {
			if(this.get('_options')) {
				var value=this.get('value');
				option = this.get('_options').findBy('value',value);
				this.set('selectedIndex',this.get('_options').indexOf(option)+1);
			}

		} else if(option && !option.get('selected')){
			this._selectedIndexObserver();
		}
	}),

	_optionsObserver: Ember.observer('_options,_options.[]',function() {
//		this._valueObserver();
		this._selectedIndexObserver();
	}),

	_syncValid: function(valid) {
		if(this.optionControl && valid && this.get('optionControl.isValid')===false) {
			var isValid=this.get('isValid');
			this.setFlag('isValid',false);
			this.set('_valid',valid);
			if(isValid===true) {
				this.notifyChange();
			}
		}
		else if(valid!==this._valid || valid!==this.isValid) {
			this.setFlag('isValid',valid);
			this.set('_valid',valid);
			this.notifyChange();
		}
	},

	_apply : function() {
		if(this.optionControl) {
			// Notify the optionControl the model has changed
			// The optionControl is tied to the option, don't reset
			//this.optionControl._reset(true);
		}
		this._super();
	},

	_reset : function(modelChanged) {
		if(this.optionControl) {
			this.optionControl._reset(modelChanged);
		}
		this._super(modelChanged);
	},

	_controlValidObserver : Ember.observer('optionControl,optionControl.isValid',function() {
		Ember.run.once(this,function() {
			this.setValid(this._valid);
		});
	}),

});<commit_msg>Single-select only set value to null if it wasn't already<commit_after>import Ember from 'ember';
import OptionsSupport from './options-support';
import getControl from 'furnace-forms/utils/get-control';
export default Ember.Mixin.create({

	_decoratorName : 'select',

	optionControl : null,

	showOptionControl : false,

	select: function(index) {
		if(index==="0") {
			this.set('value',null);
		} else {
			Ember.assert('furnace-forms: no option with index '+index,this.get('_options')[index-1]);
			this.set('value',this.get('_options')[index-1].value);
		}
//		this.get("_options").invoke('set','selected',false);

//		var option=this.get("_options").findBy('index',index);
//		if(option) {
//			option.set('selected',true);
//		}

//		this._valueObserver();
		this.send('onSelect',index);
	},

	_controlForOption: null,

	_selectedIndexObserver:Ember.observer('selectedIndex', function() {
		var option = this.getOption();

		if(option && option.value!==this.get('value')) {
			this.set('value',option.value);
		}
		else {
			if(this.get('selectedIndex')===null && this.get('value')!==null) {
				this.set('value',null);
			}
		}
		var ret=null;

		option = this.get("_options").findBy('index',this.get('selectedIndex'));
		if(option && !option.get('selected')) {
			this.get("_options").invoke('set','selected',false);
			option.set('selected',true);
		} else if(!option) {
			this.get("_options").invoke('set','selected',false);
		}

		if(this._controlForOption!==option) {
			this._controlForOption=option;
			if(this._controlsLoaded) {
				var control=this.get("controls").findBy('index',this.get('selectedIndex'));
				if(control) {
					ret = control.get('optionControl');
				}
			} else if(option && option.control) {
				var meta=option.control;
				var options={};
				options['for']=this.get('value');
				options._path=this._panel._path;
				if(this.get('optionControl')) {
					this.get('optionControl').destroy();
				}
				ret = getControl.call(this,'value',meta,options);
			}

			if(ret) {
				this.set('showOptionControl',true);
			}
			else {
				this.set('showOptionControl',false);
			}

			if(ret!==this.get('optionControl')) {
				this.set('optionControl',ret);
			}
		}
	}),

	init: function() {
		Ember.warn('No options support for single-select',OptionsSupport.detect(this),{id:'furnace-forms:control.options-support-missing'});
		this._super();
		this._updateSelected();
		this._selectedIndexObserver();
	},

	getOption: function(index) {
		if(index===undefined) {
			index=this.get('selectedIndex')-1;
		}
		return this.get('_options')[index];
	},

	selectedOption : Ember.computed({
		get : function(key,value) {
			if(value) {
				this.set('value',value.get('value'));
			}
			return this.getOption();
		}
	}).readOnly(),

	selectedIndex : 0,

	_valueObserver: Ember.observer('value',function() {
		let selectedOption=this.get("_options").findBy('value',this.get('value'));
		let index=0;
		if(selectedOption) {
			index=selectedOption.index;
		}
		this.set('selectedIndex',index);
		this._super();
	}),

	_updateSelected : Ember.observer('_options.[].selected',function() {
		var option=this.getOption();
		if(!option || this.get('value')!==option.value) {
			if(this.get('_options')) {
				var value=this.get('value');
				option = this.get('_options').findBy('value',value);
				this.set('selectedIndex',this.get('_options').indexOf(option)+1);
			}

		} else if(option && !option.get('selected')){
			this._selectedIndexObserver();
		}
	}),

	_optionsObserver: Ember.observer('_options,_options.[]',function() {
//		this._valueObserver();
		this._selectedIndexObserver();
	}),

	_syncValid: function(valid) {
		if(this.optionControl && valid && this.get('optionControl.isValid')===false) {
			var isValid=this.get('isValid');
			this.setFlag('isValid',false);
			this.set('_valid',valid);
			if(isValid===true) {
				this.notifyChange();
			}
		}
		else if(valid!==this._valid || valid!==this.isValid) {
			this.setFlag('isValid',valid);
			this.set('_valid',valid);
			this.notifyChange();
		}
	},

	_apply : function() {
		if(this.optionControl) {
			// Notify the optionControl the model has changed
			// The optionControl is tied to the option, don't reset
			//this.optionControl._reset(true);
		}
		this._super();
	},

	_reset : function(modelChanged) {
		if(this.optionControl) {
			this.optionControl._reset(modelChanged);
		}
		this._super(modelChanged);
	},

	_controlValidObserver : Ember.observer('optionControl,optionControl.isValid',function() {
		Ember.run.once(this,function() {
			this.setValid(this._valid);
		});
	}),

});<|endoftext|>


<commit_before>var checkObj = { /**数据验证类**/
    checkFunc: {}, //验证数据的函数对象集合
    // errorMessage:[],//错误消息
    // rightMessage:[],//正确消息
    showInfoFunc: {}, //显示消息的函数
    getType: function(data) {
        var to = Object.prototype.toString,
            type = 'string';
        if (to.call(data, null) === '[object Array]') {
            // 传入的是个数组
            type = 'array'
        } else if (typeof data === 'string') {
            // 仅仅传入了一个字符串
            type = 'string';
        } else if (to.call(data, null) === '[object Object]') {
            // 传入的是个对象
            type = 'object';
        } else if (to.call(data, null) === '[object Function]') {
            type = 'function';
        } else {
            type = 'null';
        }
        return type;
    },
    showMsg: function(opts) {
        return {
            _error: function() {
                opts.errorContainer.text(opts.checker.message).show();
                opts.checkElement.addClass('error-border');
                opts.tipsContainer.hide();
            },
            OK: function() {
                opts.errorContainer.text('').hide();
                opts.checkElement.removeClass('error-border');
            }
        }
    },
    // 此处验证，可以考虑把错误信息压到数组中进行处理
    // 对于不存在的tips，还需要进一步健壮处理
    check: function(checkElement, checkConfig) {
        var checker, result_ok, checkType, value,
            errorContainer, tipsContainer, i, j, validateArr, dLoop, dLen;
        // 获取数值这里，需要判断dom类型
        value = checkElement.val(); //获取当前的字段值
        errorContainer = checkElement.parents('.form-item').find('.error');
        tipsContainer = checkElement.parents('.form-item').find('.tips');
        // 需要遍历checkConfig
        // 判断checkConfig是数组，还是对象，还是字符串
        checkType = this.getType(checkConfig);
        tipsContainer.hide();
        if (checkType === 'string') {
            checker = this.checkFunc[checkConfig];
            result_ok = checker.validate(value); //对单个进行验证
            if (!result_ok) {
                this.showMsg({
                    checkElement: checkElement,
                    errorContainer: errorContainer,
                    tipsContainer: tipsContainer,
                    checker: checker
                })._error();
                return false;
            }
            this.showMsg({
                checkElement: checkElement,
                errorContainer: errorContainer,
                tipsContainer: tipsContainer,
                checker: checker
            }).OK();
        } else if (checkType === 'array') {
            for (i = 0, j = checkConfig.length; i < j; i++) {
                checker = this.checkFunc[checkConfig[i]];
                result_ok = checker.validate(value);
                if (!result_ok) {
                    this.showMsg({
                        checkElement: checkElement,
                        errorContainer: errorContainer,
                        tipsContainer: tipsContainer,
                        checker: checker
                    })._error();
                    return false;
                }
            }
            this.showMsg({
                checkElement: checkElement,
                errorContainer: errorContainer,
                tipsContainer: tipsContainer,
                checker: checker
            }).OK();
        } else if (checkType === 'object') {
            // 调用自定义函数
            // 应当还支持混合验证，即调用通用验证和自定义验证函数
            for (i in checkConfig) {
                if (i === 'tips') {} else if (i === 'defaultValidate') {
                    validateArr = checkConfig.defaultValidate;
                    for (dLoop = 0, dLen = validateArr.length; dLoop < dLen; dLoop++) {
                        checker = this.checkFunc[validateArr[dLoop]];
                        result_ok = checker.validate(value);
                        if (!result_ok) {
                            this.showMsg({
                                checkElement: checkElement,
                                errorContainer: errorContainer,
                                tipsContainer: tipsContainer,
                                checker: checker
                            })._error();

                            return false;
                        }
                    }
                    this.showMsg({
                        checkElement: checkElement,
                        errorContainer: errorContainer,
                        tipsContainer: tipsContainer,
                        checker: checker
                    }).OK();
                } else {
                    checker = checkConfig[i];
                    result_ok = checker.validate(value);
                    if (!result_ok) {
                        this.showMsg({
                            checkElement: checkElement,
                            errorContainer: errorContainer,
                            tipsContainer: tipsContainer,
                            checker: checker
                        })._error();

                        return false;
                    }
                    this.showMsg({
                        checkElement: checkElement,
                        errorContainer: errorContainer,
                        tipsContainer: tipsContainer,
                        checker: checker
                    }).OK();
                }
            }
        }
        result_ok = true;
        return result_ok;
    },
    tips: function(checkElement, checkName, checkConfig) {
        var result_ok,
            errorContainer, tipsContainer;
        // 获取数值这里，需要判断dom类型
        errorContainer = checkElement.parents('.form-item').find('.error');
        tipsContainer = checkElement.parents('.form-item').find('.tips');
        // 需要遍历checkConfig
        // 判断checkConfig是数组，还是对象，还是字符串
        checkElement.removeClass('error-border');
        errorContainer.hide();
        // console.log(checkConfig);
        if (!checkConfig.tips) {
            tipsContainer.text('').hide();
        } else {
            tipsContainer.text(checkConfig.tips).show();
        }
    },
    initialize: function(formId, validateData, checkConfig, callback) {
        // 针对文本输入框进行blur事件绑定
        // 需要支持对无事件隐藏字段的绑定
        var that = this;
        $.each(validateData, function(i, ele) {
            ele.blur(function() {
                checkObj.check(ele, checkConfig[i]);
            }).focus(function() {
                checkObj.tips(ele, i, checkConfig[i]);
            });
            /*ele.keyup(function() {
                checkObj.check(ele, checkConfig[i]);
            }).keydown(function() {
                checkObj.tips(ele, i, checkConfig[i]);
            });*/
        });

        formId.find('input[type="submit"]').click(function(e) {
            var flag = true;
            // 若验证全部完成，则进行表单提交
            $.each(validateData, function(i, ele) {
                if (!checkObj.check(ele, checkConfig[i])) {
                    flag = false;
                };
            });

            if ( !! callback && (that.getType(callback) === 'function')) {
                //存在回调的情形
                flag && callback();
            } else {
                //使用默认提交的action
                // 阻止默认提交
                !flag&&e.preventDefault();
                // flag && formId.get(0).submit();
            }
        });
    }
}
/*
 * 考虑到常用的字段验证包含了基本验证函数中的一些，所以，可以把这些封装起来，而不用通过数组的方式调用最小验证函数
 */
// 用户名验证
checkObj.checkFunc.userName = {
    validate: function(val) {
        if ($.trim(val) === '') {
            this.message = '用户名不能为空';
            return false;
        }
        if (/\w/g.test(val) === false) {
            this.message = '用户名输入只能为数字，字母和下划线';
            return false;
        }
        if ($.trim(val).length > 16 || $.trim(val).length < 2) {
            this.message = '用户名长度错误';
            return false;
        }
        return true;
    },
    message: ''
};

/*checkObj.checkFunc.userName = {
    validate:function(val){
        if($.trim(val)===''){
            this.message='用户名不能为空';
            return false;
        }
        if(/\w/g.test(val)===false){
            this.message='用户名输入只能为数字，字母和下划线';
            return false
        }
        return true;
    },
    message:''
};*/
/*
 * 检查是否为空
 */
checkObj.checkFunc.isEmpty = {
    validate: function(val) {
        return $.trim(val) !== '';
    },
    message: '输入不能为空！' //错误消息
}
/*
 * 检查电子邮件
 */
checkObj.checkFunc.isEmail = {
    validate: function(val) {
        var _reg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
        return _reg.test(val);
    },
    message: '请填写正确的邮件格式！' //错误消息
}
/*
 * 检查用户名
 * 用户名只能为数字，字母，中划线，下滑线组合，长度不做限制
 */
checkObj.checkFunc.isUserName = {
    validate: function(val) {
        var _reg = /[0-9a-zA-Z_-]/;
        return _reg.test(val);
    },
    message: '请填写正确的用户名！' //错误消息
}
/*
 * 检查密码格式
 * 此处密码为数字，字母，下划线组合，6-16位
 */
checkObj.checkFunc.isPassword = {
    validate: function(val) {
        var _reg = /^[0-9a-zA-Z]{6,16}$/;
        return _reg.test(val);
    },
    message: '请输入正确的密码格式'
};
/*
 * 检查是否选择项目
 */
checkObj.checkFunc.isChecked = {
    validate: function(val) {
        return val;
    },
    message: '未选择值!' //错误消息
}<commit_msg>删除提交按钮绑定，使用表单默认绑定<commit_after>var checkObj = { /**数据验证类**/
    checkFunc: {}, //验证数据的函数对象集合
    // errorMessage:[],//错误消息
    // rightMessage:[],//正确消息
    showInfoFunc: {}, //显示消息的函数
    getType: function(data) {
        var to = Object.prototype.toString,
            type = 'string';
        if (to.call(data, null) === '[object Array]') {
            // 传入的是个数组
            type = 'array'
        } else if (typeof data === 'string') {
            // 仅仅传入了一个字符串
            type = 'string';
        } else if (to.call(data, null) === '[object Object]') {
            // 传入的是个对象
            type = 'object';
        } else if (to.call(data, null) === '[object Function]') {
            type = 'function';
        } else {
            type = 'null';
        }
        return type;
    },
    showMsg: function(opts) {
        return {
            _error: function() {
                opts.errorContainer.text(opts.checker.message).show();
                opts.checkElement.addClass('error-border');
                opts.tipsContainer.hide();
            },
            OK: function() {
                opts.errorContainer.text('').hide();
                opts.checkElement.removeClass('error-border');
            }
        }
    },
    // 此处验证，可以考虑把错误信息压到数组中进行处理
    // 对于不存在的tips，还需要进一步健壮处理
    check: function(checkElement, checkConfig) {
        var checker, result_ok, checkType, value,
            errorContainer, tipsContainer, i, j, validateArr, dLoop, dLen;
        // 获取数值这里，需要判断dom类型
        value = checkElement.val(); //获取当前的字段值
        errorContainer = checkElement.parents('.form-item').find('.error');
        tipsContainer = checkElement.parents('.form-item').find('.tips');
        // 需要遍历checkConfig
        // 判断checkConfig是数组，还是对象，还是字符串
        checkType = this.getType(checkConfig);
        tipsContainer.hide();
        if (checkType === 'string') {
            checker = this.checkFunc[checkConfig];
            result_ok = checker.validate(value); //对单个进行验证
            if (!result_ok) {
                this.showMsg({
                    checkElement: checkElement,
                    errorContainer: errorContainer,
                    tipsContainer: tipsContainer,
                    checker: checker
                })._error();
                return false;
            }
            this.showMsg({
                checkElement: checkElement,
                errorContainer: errorContainer,
                tipsContainer: tipsContainer,
                checker: checker
            }).OK();
        } else if (checkType === 'array') {
            for (i = 0, j = checkConfig.length; i < j; i++) {
                checker = this.checkFunc[checkConfig[i]];
                result_ok = checker.validate(value);
                if (!result_ok) {
                    this.showMsg({
                        checkElement: checkElement,
                        errorContainer: errorContainer,
                        tipsContainer: tipsContainer,
                        checker: checker
                    })._error();
                    return false;
                }
            }
            this.showMsg({
                checkElement: checkElement,
                errorContainer: errorContainer,
                tipsContainer: tipsContainer,
                checker: checker
            }).OK();
        } else if (checkType === 'object') {
            // 调用自定义函数
            // 应当还支持混合验证，即调用通用验证和自定义验证函数
            for (i in checkConfig) {
                if (i === 'tips') {} else if (i === 'defaultValidate') {
                    validateArr = checkConfig.defaultValidate;
                    for (dLoop = 0, dLen = validateArr.length; dLoop < dLen; dLoop++) {
                        checker = this.checkFunc[validateArr[dLoop]];
                        result_ok = checker.validate(value);
                        if (!result_ok) {
                            this.showMsg({
                                checkElement: checkElement,
                                errorContainer: errorContainer,
                                tipsContainer: tipsContainer,
                                checker: checker
                            })._error();

                            return false;
                        }
                    }
                    this.showMsg({
                        checkElement: checkElement,
                        errorContainer: errorContainer,
                        tipsContainer: tipsContainer,
                        checker: checker
                    }).OK();
                } else {
                    checker = checkConfig[i];
                    result_ok = checker.validate(value);
                    if (!result_ok) {
                        this.showMsg({
                            checkElement: checkElement,
                            errorContainer: errorContainer,
                            tipsContainer: tipsContainer,
                            checker: checker
                        })._error();

                        return false;
                    }
                    this.showMsg({
                        checkElement: checkElement,
                        errorContainer: errorContainer,
                        tipsContainer: tipsContainer,
                        checker: checker
                    }).OK();
                }
            }
        }
        result_ok = true;
        return result_ok;
    },
    tips: function(checkElement, checkName, checkConfig) {
        var result_ok,
            errorContainer, tipsContainer;
        // 获取数值这里，需要判断dom类型
        errorContainer = checkElement.parents('.form-item').find('.error');
        tipsContainer = checkElement.parents('.form-item').find('.tips');
        // 需要遍历checkConfig
        // 判断checkConfig是数组，还是对象，还是字符串
        checkElement.removeClass('error-border');
        errorContainer.hide();
        // console.log(checkConfig);
        if (!checkConfig.tips) {
            tipsContainer.text('').hide();
        } else {
            tipsContainer.text(checkConfig.tips).show();
        }
    },
    initialize: function(formId, validateData, checkConfig, callback) {
        // 针对文本输入框进行blur事件绑定
        // 需要支持对无事件隐藏字段的绑定
        var that = this;
        $.each(validateData, function(i, ele) {
            ele.blur(function() {
                checkObj.check(ele, checkConfig[i]);
            }).focus(function() {
                checkObj.tips(ele, i, checkConfig[i]);
            });
            /*ele.keyup(function() {
                checkObj.check(ele, checkConfig[i]);
            }).keydown(function() {
                checkObj.tips(ele, i, checkConfig[i]);
            });*/
        });

        // formId.find('input[type="submit"]').click(function(e) {
            formId.on('submit',function(e){
            var flag = true;
            // 若验证全部完成，则进行表单提交
            $.each(validateData, function(i, ele) {
                if (!checkObj.check(ele, checkConfig[i])) {
                    flag = false;
                };
            });

            if ( !! callback && (that.getType(callback) === 'function')) {
                //存在回调的情形
                flag && callback();
            } else {
                //使用默认提交的action
                // 阻止默认提交
                !flag&&e.preventDefault();
                // flag && formId.get(0).submit();
            }
        });
    }
}
/*
 * 考虑到常用的字段验证包含了基本验证函数中的一些，所以，可以把这些封装起来，而不用通过数组的方式调用最小验证函数
 */
// 用户名验证
checkObj.checkFunc.userName = {
    validate: function(val) {
        if ($.trim(val) === '') {
            this.message = '用户名不能为空';
            return false;
        }
        if (/\w/g.test(val) === false) {
            this.message = '用户名输入只能为数字，字母和下划线';
            return false;
        }
        if ($.trim(val).length > 16 || $.trim(val).length < 2) {
            this.message = '用户名长度错误';
            return false;
        }
        return true;
    },
    message: ''
};

/*checkObj.checkFunc.userName = {
    validate:function(val){
        if($.trim(val)===''){
            this.message='用户名不能为空';
            return false;
        }
        if(/\w/g.test(val)===false){
            this.message='用户名输入只能为数字，字母和下划线';
            return false
        }
        return true;
    },
    message:''
};*/
/*
 * 检查是否为空
 */
checkObj.checkFunc.isEmpty = {
    validate: function(val) {
        return $.trim(val) !== '';
    },
    message: '输入不能为空！' //错误消息
}
/*
 * 检查电子邮件
 */
checkObj.checkFunc.isEmail = {
    validate: function(val) {
        var _reg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
        return _reg.test(val);
    },
    message: '请填写正确的邮件格式！' //错误消息
}
/*
 * 检查用户名
 * 用户名只能为数字，字母，中划线，下滑线组合，长度不做限制
 */
checkObj.checkFunc.isUserName = {
    validate: function(val) {
        var _reg = /[0-9a-zA-Z_-]/;
        return _reg.test(val);
    },
    message: '请填写正确的用户名！' //错误消息
}
/*
 * 检查密码格式
 * 此处密码为数字，字母，下划线组合，6-16位
 */
checkObj.checkFunc.isPassword = {
    validate: function(val) {
        var _reg = /^[0-9a-zA-Z]{6,16}$/;
        return _reg.test(val);
    },
    message: '请输入正确的密码格式'
};
/*
 * 检查是否选择项目
 */
checkObj.checkFunc.isChecked = {
    validate: function(val) {
        return val;
    },
    message: '未选择值!' //错误消息
}<|endoftext|>


<commit_before>import Ember from 'ember';
import OptionsSupport from './options-support';
import Form from 'furnace-forms/controls/form';
import Forms from 'furnace-forms';
import getControl from 'furnace-forms/utils/get-control';

export default Ember.Mixin.create({
	optionControl : null,

	showOptionControl : false,

	actions : {

	},

	select: function(index) {
		this.set('value',this.get('_options')[index-1].value);
		if(this._controlsLoaded) {
			this.get("controls").invoke('set','selected',false);
			var control=this.get("controls").findBy('index',index);
			if(control)
				control.set('selected',true);
		}
		this._valueObserver();
	},

	_selectedIndexObserver:Ember.observer('selectedIndex', function() {
		Ember.run.once(this,function() {
			var option = this.getOption();
			if(option && option.value!==this.get('value')) {
				this.set('value',option.value);
			}
			else {
				if(this.get('selectedIndex')===null) {
					this.set('value',null);
				}
			}
			var ret=null;

			// Use option control directly instead of generating our own
//			var	oldValue=this.get('optionControl');
//			if(option && option.control) {
//				var options=option.control._meta.options;
//				options['for']=this.get('value');
//				options._path=this._panel._path;
//				ret = option.get('optionControl');
//				this.set('showOptionControl',true);
//			}
//			else {
//				this.set('showOptionControl',false);
//			}
			if(this._controlsLoaded) {
				this.get("controls").invoke('set','selected',false);
				var control=this.get("controls").findBy('index',this.get('selectedIndex'));
				if(control) {
					control.set('selected',true);
					ret = control.get('optionControl');
					if(ret)
						this.set('showOptionControl',true);
					else
						this.set('showOptionControl',false);
				}
			}
			// Since we're using the options control, dont destroy it.
//			if(oldValue) {
//				Ember.run.later(function() {
//					oldValue.destroy();
//				});
//			}
			this.set('optionControl',ret);
		});
	}),

	init: function() {
		this._super();
		Ember.warn('No options support for single-select',OptionsSupport.detect(this));
	},

	getOption: function(index) {
		if(index===undefined) {
			index=this.get('selectedIndex')-1;
		}
		return this.get('_options')[index];
	},

	selectedOption : Ember.computed(function(key,value) {
		if(value) {
			this.set('value',value.get('value'));
		}
		return this.getOption();
	}),

	selectedIndex : 0,

	_valueObserver: Ember.observer('value,_options',function() {
		this._super();
		var option=this.getOption();
		if(!option || this.get('value')!==option.value) {
			if(this.get('_options')) {
				option = this.get('_options').findBy('value',this.get('value'));
				this.set('selectedIndex',this.get('_options').indexOf(option)+1);
			}

		}
	}),

	setValid: function(valid) {
		Ember.run.once(this,function() {
			if(this.optionControl && valid && this.get('optionControl.isValid')===false) {
				var isValid=this.get('isValid');
				this.setFlag('isValid',false);
				this.set('_valid',valid);
				if(isValid===true)
					this.notifyChange();
			}
			else if(valid!==this._valid || valid!==this.isValid) {
				this.setFlag('isValid',valid);
				this.set('_valid',valid);
				this.notifyChange();
			}
		});
	},

	_apply : function() {
		if(this.optionControl) {
			// Notify the optionControl the model has changed
			this.optionControl._reset(true);
		}
		this._super();
	},

	_reset : function(modelChanged) {
		if(this.optionControl) {
			this.optionControl._reset(modelChanged);
		}
		this._super(modelChanged);
	},

	_controlValidObserver : function() {
		Ember.run.once(this,function() {
			this.setValid(this._valid);
		});
	}.observes('optionControl,optionControl.isValid'),

});<commit_msg>Fixed single-select selection update on model change without selectedIndex change<commit_after>import Ember from 'ember';
import OptionsSupport from './options-support';

export default Ember.Mixin.create({
	optionControl : null,

	showOptionControl : false,

	actions : {

	},

	select: function(index) {
		this.set('value',this.get('_options')[index-1].value);

		this.get("_options").invoke('set','selected',false);
		var option=this.get("_options").findBy('index',index);
		if(option) {
			option.set('selected',true);
		}
		this._valueObserver();
	},

	_selectedIndexObserver:Ember.observer('selectedIndex', function() {
		Ember.run.once(this,function() {
			var option = this.getOption();
			if(option && option.value!==this.get('value')) {
				this.set('value',option.value);
			}
			else {
				if(this.get('selectedIndex')===null) {
					this.set('value',null);
				}
			}
			var ret=null;

			// Use option control directly instead of generating our own
//			var	oldValue=this.get('optionControl');
//			if(option && option.control) {
//				var options=option.control._meta.options;
//				options['for']=this.get('value');
//				options._path=this._panel._path;
//				ret = option.get('optionControl');
//				this.set('showOptionControl',true);
//			}
//			else {
//				this.set('showOptionControl',false);
//			}

			this.get("_options").invoke('set','selected',false);
			option = this.get("_options").findBy('index',this.get('selectedIndex'));
			if(option) {
				option.set('selected',true);
			}
			if(this._controlsLoaded) {
				var control=this.get("controls").findBy('index',this.get('selectedIndex'));
				if(control) {
					ret = control.get('optionControl');
					if(ret) {
						this.set('showOptionControl',true);
					}
					else {
						this.set('showOptionControl',false);
					}
				}
			}
			// Since we're using the options control, dont destroy it.
//			if(oldValue) {
//				Ember.run.later(function() {
//					oldValue.destroy();
//				});
//			}
			this.set('optionControl',ret);
		});
	}),

	init: function() {
		this._super();
		Ember.warn('No options support for single-select',OptionsSupport.detect(this));
	},

	getOption: function(index) {
		if(index===undefined) {
			index=this.get('selectedIndex')-1;
		}
		return this.get('_options')[index];
	},

	selectedOption : Ember.computed(function(key,value) {
		if(value) {
			this.set('value',value.get('value'));
		}
		return this.getOption();
	}),

	selectedIndex : 0,

	_valueObserver: Ember.observer('value,_options',function() {
		this._super();
		var option=this.getOption();
		if(!option || this.get('value')!==option.value) {
			if(this.get('_options')) {
				option = this.get('_options').findBy('value',this.get('value'));
				this.set('selectedIndex',this.get('_options').indexOf(option)+1);
			}

		} else if(option && !option.get('selected')){
			this._selectedIndexObserver();
		}
	}),

	_optionsObserver: Ember.observer('_options',function() {
		Ember.debug('options changed');
//		this._valueObserver();
//		this._selectedIndexObserver();
	}),

	setValid: function(valid) {
		Ember.run.once(this,function() {
			if(this.optionControl && valid && this.get('optionControl.isValid')===false) {
				var isValid=this.get('isValid');
				this.setFlag('isValid',false);
				this.set('_valid',valid);
				if(isValid===true) {
					this.notifyChange();
				}
			}
			else if(valid!==this._valid || valid!==this.isValid) {
				this.setFlag('isValid',valid);
				this.set('_valid',valid);
				this.notifyChange();
			}
		});
	},

	_apply : function() {
		if(this.optionControl) {
			// Notify the optionControl the model has changed
			this.optionControl._reset(true);
		}
		this._super();
	},

	_reset : function(modelChanged) {
		if(this.optionControl) {
			this.optionControl._reset(modelChanged);
		}
		this._super(modelChanged);
	},

	_controlValidObserver : function() {
		Ember.run.once(this,function() {
			this.setValid(this._valid);
		});
	}.observes('optionControl,optionControl.isValid'),

});<|endoftext|>


<commit_before><commit_msg>unload event for main ui<commit_after><|endoftext|>


<commit_before>'use strict';

angular.module('talis.services.echo', []).factory("echo",["$rootScope","$http","applicationLoggingService", function($rootScope, $http, applicationLoggingService,ECHO_ENDPOINT) {
    var instance = function() {};
    var MAX_FLUSH_EVENTS = 10;
    var DEBOUNCE_INTERVAL = 2500;
    var MAX_INTERVAL = 5000;
    var BACK_OFF_FACTOR = 1.5;

    instance._instantFlush = function() {
        var ctx = this,
            _events = [];

        // pluck off up to MAX_FLUSH EVENTS
        if (this._events.length>MAX_FLUSH_EVENTS) {
            _events = _.first(this._events,MAX_FLUSH_EVENTS);
            this._events = _.rest(this._events,MAX_FLUSH_EVENTS);
            applicationLoggingService.debug("Only flushing "+MAX_FLUSH_EVENTS+" at a time - re-queued "+this._events.length+" events");
            this._flush();
        } else {
            _events = this._events;
            this._events = [];
        }

        if (_events.length>0) {
            $rootScope.$apply(function() {
                $http.post(ECHO_ENDPOINT+'/1/events',_events, {"headers":{"Content-Type":"application/json"}}).success(function(response) {
                    applicationLoggingService.debug("Successfully flushed "+_events.length+" events to backend");
                    // ok!
                }).error(function(response) {

                        // back off debounce and interval
                        DEBOUNCE_INTERVAL = Math.floor(DEBOUNCE_INTERVAL*BACK_OFF_FACTOR);
                        MAX_INTERVAL = Math.floor(MAX_INTERVAL*BACK_OFF_FACTOR);
                        instance._flush = _.debounce(instance._instantFlush,DEBOUNCE_INTERVAL,{'maxWait':MAX_INTERVAL});

                        applicationLoggingService.error("Error flushing "+_events.length+" events to backend, backing off to "+DEBOUNCE_INTERVAL+"/"+MAX_INTERVAL+", re-queueing...");

                        // have another crack
                        _events.forEach(function(event) {
                            ctx._events.push(event);
                        });
                        ctx._flush();
                    });
            });
        } else {
            applicationLoggingService.debug("No events to flush");
        }
    };

    instance._events = [];
    instance._flush = _.debounce(instance._instantFlush,DEBOUNCE_INTERVAL,{'maxWait':MAX_INTERVAL}); // debounce within 5s, wait no more than 10...

    instance.add = function(key,props) {
        if (_.isEmpty(key)) {
            applicationLoggingService.error("No key supplied to events.add");
            return;
        } else if (!_.isString(key)) {
            applicationLoggingService.error("key supplied to events.add is not a string: "+JSON.stringify(key));
            return;
        } else if (props!=null && !_.isObject(props)) {
            applicationLoggingService.error("props supplied to events.add should be null or object")
            return;
        }

        var event = {
            key: key,
            created: Math.floor(new Date().getTime() / 1000) // seconds since epoch
        };
        if (props != null) event['props'] = props;
        if ($rootScope.user != null && $rootScope.user.guid != null) event['user_guid'] = $rootScope.user.guid;

        this._events.push(event);
        this._flush();
    };

    return instance;
}]);<commit_msg>Fixed to actually work against echo, sends browser data too<commit_after>'use strict';

angular.module('talis.services.echo', []).factory("echo",[
    "$rootScope",
    "$http",
    "applicationLoggingService",
    "ECHO_ENDPOINT",
    "APP_ID",
    "BROWSER_NAME",
    "BROWSER_VERSION",
    "BROWSER_COMPAT_MODE", function($rootScope, $http, applicationLoggingService,ECHO_ENDPOINT,APP_ID,BROWSER_NAME,BROWSER_VERSION,BROWSER_COMPAT_MODE) {
        var instance = function() {};
        var MAX_FLUSH_EVENTS = 10;
        var DEBOUNCE_INTERVAL = 2500;
        var MAX_INTERVAL = 5000;
        var BACK_OFF_FACTOR = 1.5;

        instance._instantFlush = function() {
            var ctx = this,
                _events = [];

            // pluck off up to MAX_FLUSH EVENTS
            if (this._events.length>MAX_FLUSH_EVENTS) {
                _events = _.first(this._events,MAX_FLUSH_EVENTS);
                this._events = _.rest(this._events,MAX_FLUSH_EVENTS);
                applicationLoggingService.debug("Only flushing "+MAX_FLUSH_EVENTS+" at a time - re-queued "+this._events.length+" events");
                this._flush();
            } else {
                _events = this._events;
                this._events = [];
            }

            if (_events.length>0) {
                $rootScope.$apply(function() {
                    $http.post(ECHO_ENDPOINT+'/1/events',_events, {"headers":{"Content-Type":"application/json"}}).success(function(response) {
                        applicationLoggingService.debug("Successfully flushed "+_events.length+" events to backend");
                        // ok!
                    }).error(function(response) {

                            // back off debounce and interval
                            DEBOUNCE_INTERVAL = Math.floor(DEBOUNCE_INTERVAL*BACK_OFF_FACTOR);
                            MAX_INTERVAL = Math.floor(MAX_INTERVAL*BACK_OFF_FACTOR);
                            instance._flush = _.debounce(instance._instantFlush,DEBOUNCE_INTERVAL,{'maxWait':MAX_INTERVAL});

                            applicationLoggingService.error("Error flushing "+_events.length+" events to backend, backing off to "+DEBOUNCE_INTERVAL+"/"+MAX_INTERVAL+", re-queueing...");

                            // have another crack
                            _events.forEach(function(event) {
                                ctx._events.push(event);
                            });
                            ctx._flush();
                        });
                });
            } else {
                applicationLoggingService.debug("No events to flush");
            }
        };

        instance._events = [];
        instance._flush = _.debounce(instance._instantFlush,DEBOUNCE_INTERVAL,{'maxWait':MAX_INTERVAL}); // debounce within 5s, wait no more than 10...

        instance.add = function(className,props) {
            if (_.isEmpty(className)) {
                applicationLoggingService.error("No key supplied to events.add");
                return;
            } else if (!_.isString(className)) {
                applicationLoggingService.error("key supplied to events.add is not a string: "+JSON.stringify(className));
                return;
            } else if (props!=null && !_.isObject(props)) {
                applicationLoggingService.error("props supplied to events.add should be null or object")
                return;
            }

            var event = {
                class: className,
                source: APP_ID,
                timestamp: Math.floor(new Date().getTime() / 1000) // seconds since epoch
            };
            event['props'] = props || {};
            event.props.browser_name = BROWSER_NAME;
            event.props.browser_version = BROWSER_VERSION;
            event.props.browser_compat_mode = BROWSER_COMPAT_MODE;
            if ($rootScope.user != null && $rootScope.user.guid != null) event['user'] = $rootScope.user.guid;

            this._events.push(event);
            this._flush();
        };

        return instance;
    }]);<|endoftext|>


<commit_before>/*!
 * aFox (http://afox.kr)
 * Copyright 2016 afox, Inc.
 * Licensed under the MIT license
 */

+function ($) {
  'use strict';

	$(window).on('load', function() {
		var js = $('script[src^="'+request_uri+'addon/object_manager/object_manager.js?"]:eq(0)'),
			module = '',
			link_blank = false,
			autosize_image = false,
			autosize_video = false;

		if(js.length>0) {
			js = js.attr('src').getQuery();
			module = js['m'] || '';
			if((js['l'] || '0') == '1') link_blank = true;
			if((js['i'] || '0') == '1') autosize_image = true;
			if((js['v'] || '0') == '1') autosize_video = true;
		}

		if(autosize_video === true) {
			$('.current_content video,.current_content iframe[src*="youtube.com"]').each(function(){
				var $th = $(this),
					w1 = $th.closest('.current_content').width(),
					w2 = $th.width();
				$th.attr('width', w1).attr('height', (w1*0.5625));
			});
		}
		if(autosize_image === true) {
			$('.current_content img').each(function(){
				var $th = $(this);
				function img_resize(){
					var w1 = $th.closest('.current_content').width(),
						w2 = $th.width();
					if(w1<w2) {
						$th.attr('width', '100%');
						$th.removeAttr('height');
					}
					$th.on('load', img_resize);
				}
				img_resize();
			});
		}

		if(module == 'board' || module == 'page') {
			var is_modal = false;
			if(link_blank === true) {
				$('.current_content a[href]').each(function(){
					var target = $(this).attr('target') || '';
					if(target == '')
						$(this).attr('target', '_blank');
					else if(target == '_modal')
					{
						is_modal = true;
						$(this).on('click', function(e){
							e.preventDefault();
							$('#addon_object_manager_modal').modal('show').find('.modal-body').load($(this).attr('href'));
						});
					}
				});
			}
			if(is_modal && $('#addon_object_manager_modal').length === 0)
			{
				var html = '
'
						+ '

';
				$(html).appendTo('body')
				.on('shown.bs.modal', function(e) {
					$(this).find('.modal-body:eq(0)')
					.find('div:eq(0)').attr('style', 'width:100%!important;overflow:hidden!important')
					.find('img[data-scroll-src]').each(function(){
						var src = $(this).attr('data-scroll-src') || '';
						$(this).removeAttr('data-scroll-src').attr('src', src);
					});
				}).on('hidden.bs.modal', function(e) {
					$(this).find('.modal-body:eq(0)').empty();
				});
			}
		}
	});

}(jQuery);
<commit_msg>Update object_manager.js<commit_after>/*!
 * aFox (http://afox.kr)
 * Copyright 2016 afox, Inc.
 * Licensed under the MIT license
 */

+function ($) {
  'use strict';

	$(window).on('load', function() {
		var js = $('script[src^="'+request_uri+'addon/object_manager/object_manager.js?"]:eq(0)'),
			module = '',
			link_blank = false,
			autosize_image = false,
			autosize_video = false;

		if(js.length>0) {
			js = js.attr('src').getQuery();
			module = js['m'] || '';
			if((js['l'] || '0') == '1') link_blank = true;
			if((js['i'] || '0') == '1') autosize_image = true;
			if((js['v'] || '0') == '1') autosize_video = true;
		}

		if(autosize_video === true) {
			$('.current_content video,.current_content iframe[src*="youtube.com"]').each(function(){
				var $th = $(this),
					w1 = $th.closest('.current_content').width(),
					w2 = $th.width();
				$th.attr('width', w1).attr('height', (w1*0.5625));
			});
		}
		if(autosize_image === true) {
			$('.current_content img').each(function(){
				var $th = $(this);
				function img_resize(){
					var w1 = $th.closest('.current_content').width(),
						w2 = $th.width();
					if(w1<w2) {
						$th.attr('width', '100%');
						$th.removeAttr('height');
					}
					$th.on('load', img_resize);
				}
				img_resize();
			});
		}

		if(module == 'board' || module == 'page') {
			var is_modal = false;
			if(link_blank === true) {
				$('.current_content a[href]').each(function(){
					var target = $(this).attr('target') || '';
					if(target == '' && module == 'board')
						$(this).attr('target', '_blank');
					else if(target == '_modal')
					{
						is_modal = true;
						$(this).on('click', function(e){
							e.preventDefault();
							$('#addon_object_manager_modal').modal('show').find('.modal-body').load($(this).attr('href'));
						});
					}
				});
			}
			if(is_modal && $('#addon_object_manager_modal').length === 0)
			{
				var html = '
'
						+ '

';
				$(html).appendTo('body')
				.on('shown.bs.modal', function(e) {
					$(this).find('.modal-body:eq(0)')
					.find('div:eq(0)').attr('style', 'width:100%!important;overflow:hidden!important')
					.find('img[data-scroll-src]').each(function(){
						var src = $(this).attr('data-scroll-src') || '';
						$(this).removeAttr('data-scroll-src').attr('src', src);
					});
				}).on('hidden.bs.modal', function(e) {
					$(this).find('.modal-body:eq(0)').empty();
				});
			}
		}
	});

}(jQuery);
<|endoftext|>


<commit_before>
/*****************************************************************/
/* Creating event when clicking on marker                        */

//create function that reacts for marker event click
function onMarkerClick(e) {
    alert("Hey, you clicked it right " + e.toGeoJSON);
}

//put trigger on marker that shows interface
marker.on('click', onMarkerClick);

function onMarker2Click(e) {
    var interfaceBlock = document.getElementById('interfaceBlock');
    interfaceBlock.style.display = "block";
    //Display event in interface
    var event = ['
Bruno vous demande un café.
', '
Il n\'y a personne, une lettre se trouve par terre.
', '
Antoine Beauvilain vous saute dessus en criant "SQUIRREL !"
'];
    var event = event[Math.floor(Math.random()*event.length)];
    var paragraphe = document.getElementById('description');
    paragraphe.innerHTML = event;
}
//close the interface
function onClickclose() {
    var interfaceBlock = document.getElementById('interfaceBlock');
    interfaceBlock.style.display = "none";
}

function changeIcon(e) {
    console.log(e.getLatLng);
    marker.setIcon(fastfoodIcon);
}
//put trigger on marker
marker2.on('click', onMarker2Click);

//on map, popup appears with coordinates
/*var popup = L.popup();

function onMapClick(e) {
    popup
        .setLatLng(e.latlng)
        .setContent("You clicked the map at " + e.latlng.toString())
        .openOn(map);
}

map.on('click', onMapClick);
*/

//hotelsLayer.on('click', changeIcon);

hero.on('drag', function(event){
            var coordinates = hero.getLatLng();
            circle.setLatLng(coordinates);
});

hero.on('dragend', function(event){
    map.setView(hero.getLatLng(), 13);
});

function showHideInterface(){
    if (!Game.showHideInterface) {
        $('#interfaceBlock').animate({
            marginLeft: '-630px'
        }, 500);
        Game.showHideInterface = 1;
        document.getElementById('slideButton').innerHTML = ">";
        //console.log('boolean: ' + Game.showHideInterface);
    }
    else{
        $('#interfaceBlock').css('margin', '39px auto');
        Game.showHideInterface = 0;
        document.getElementById('slideButton').innerHTML = "<";
        //console.log('boolean: ' + Game.showHideInterface);
    }

    //console.log('Clicked');
}

//Set hero position to clicked marker
/*for (var i = 0; i < markerMusees.length; i++) {
    markerMusees[i].on('click', function(event) {*/
function moveMarker(marker, condition){
        switch(condition){
            case 'bar':
                var position = markerPub[marker].getLatLng();
            break;
            case 'hopital':
                var position = markerHopitaux[marker].getLatLng();
            break;
            case 'musee':
                var position = markerMusees[marker].getLatLng();
            break;
            case 'commissariat':
                var position = markerCommissariats[marker].getLatLng();
            break;

        }

        hero.setLatLng(position);
        circle.setLatLng(position);
        polyline.addLatLng(position);
        map.closePopup();
        displayMarker();
        map.setView(position, 15);
        storyNext(condition);
}
<commit_msg>Add possibility to click on the hero according to story<commit_after>
/*****************************************************************/
/* Creating event when clicking on marker                        */

//create function that reacts for marker event click
function onMarkerClick(e) {
    alert("Hey, you clicked it right " + e.toGeoJSON);
}

//put trigger on marker that shows interface
marker.on('click', onMarkerClick);

function onMarker2Click(e) {
    var interfaceBlock = document.getElementById('interfaceBlock');
    interfaceBlock.style.display = "block";
    //Display event in interface
    var event = ['
Bruno vous demande un café.
', '
Il n\'y a personne, une lettre se trouve par terre.
', '
Antoine Beauvilain vous saute dessus en criant "SQUIRREL !"
'];
    var event = event[Math.floor(Math.random()*event.length)];
    var paragraphe = document.getElementById('description');
    paragraphe.innerHTML = event;
}
//close the interface
function onClickclose() {
    var interfaceBlock = document.getElementById('interfaceBlock');
    interfaceBlock.style.display = "none";
}

function changeIcon(e) {
    console.log(e.getLatLng);
    marker.setIcon(fastfoodIcon);
}
//put trigger on marker
marker2.on('click', onMarker2Click);

//on map, popup appears with coordinates
/*var popup = L.popup();

function onMapClick(e) {
    popup
        .setLatLng(e.latlng)
        .setContent("You clicked the map at " + e.latlng.toString())
        .openOn(map);
}

map.on('click', onMapClick);
*/

//hotelsLayer.on('click', changeIcon);

hero.on('drag', function(event){
            var coordinates = hero.getLatLng();
            circle.setLatLng(coordinates);
});

hero.on('dragend', function(event){
    map.setView(hero.getLatLng(), 13);
});

function showHideInterface(){
    if (!Game.showHideInterface) {
        $('#interfaceBlock').animate({
            marginLeft: '-630px'
        }, 500);
        Game.showHideInterface = 1;
        document.getElementById('slideButton').innerHTML = ">";
        //console.log('boolean: ' + Game.showHideInterface);
    }
    else{
        $('#interfaceBlock').css('margin', '39px auto');
        Game.showHideInterface = 0;
        document.getElementById('slideButton').innerHTML = "<";
        //console.log('boolean: ' + Game.showHideInterface);
    }

    //console.log('Clicked');
}

//Set hero position to clicked marker
/*for (var i = 0; i < markerMusees.length; i++) {
    markerMusees[i].on('click', function(event) {*/
hero.on('click', function(event){
    storyNext('moi');
})

function moveMarker(marker, condition){
        switch(condition){
            case 'bar':
                var position = markerPub[marker].getLatLng();
            break;
            case 'hopital':
                var position = markerHopitaux[marker].getLatLng();
            break;
            case 'musee':
                var position = markerMusees[marker].getLatLng();
            break;
            case 'commissariat':
                var position = markerCommissariats[marker].getLatLng();
            break;

        }

        hero.setLatLng(position);
        circle.setLatLng(position);
        polyline.addLatLng(position);
        map.closePopup();
        displayMarker();
        map.setView(position, 15);
        storyNext(condition);
}
<|endoftext|>


<commit_before>//AL MOMENTO DE CARGAR LA PAGINA CARGA ESTO
$(document).ready(function() {

    //CARGA TABLA DE PACIENTES
    listado_consultas_medicas();

});

//FUNCION QUE PERMITE EDITAR UNA CONSULTA MEDICA
function editar_consulta_med(){

    alert("editar consulta medica");
}

//FUNCION QUE PERMITE VER INFORMACION DE UNA CONSULTA MEDICA
function ver_info_consulta_med(){

    alert("ver informacion consulta medica");
}

//FUNCION QUE PERMITE ELIMINAR UNA CONSULTA MEDICA
function eliminar_consulta_med(id_consulta_medica){

    var baseURL = $('body').data('baseurl');//url base

    swal({
        title: "¿Estas seguro de eliminar consulta médica n° "+id_consulta_medica+"?",
        text: "Recuerda que... sera eliminado!",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Si, eliminalo!",
        cancelButtonText: "Cancelar",
        closeOnConfirm: false
    },
    function(){

        //Iniciar peticion con ajax
        $.ajax({
            data: {"id_consulta" : id_consulta_medica},
            type: "POST",
            //dataType: "json",
            url: baseURL+"ficha_medica/eliminarConsultaMed"
        })
       .done(function(data,textStatus,jqXHR ) {

            if(data === "success"){//La solicitud se realizo correctamente

               //Consulta medica eliminada correctamente
               swal({
                    title: "Consulta Médica eliminada!",
                    text:  "consulta médica n° "+id_consulta_medica+" fue eliminada correctamente.",
                    type:  "success"
                },
                function(){
                    //recargar tabla de consultas medicas
                    listado_consultas_medicas();
                });

            }else{

                swal({
                    title: "Ha ocurrido un error",
                    text:  "Por favor intente nuevamente",
                    type:  "error"
                });

                return false;
            }
        })
        .fail(function( jqXHR, textStatus, errorThrown ) {

            if(textStatus === "error") {//La solicitud a fallado
                alert("Error: "+textStatus+" "+jqXHR);
                console.log("La solicitud a fallado: " +  textStatus);
                console.log(textStatus+" "+jqXHR);

                swal({
                    title: "Error: "+textStatus+" "+jqXHR,
                    text:  "",
                    type:  "error"
                });
            }
        });
    });

    return false;
}

//FUNCION QUE PERMITE CARGAR TABLA DE PACIENTES
function listado_consultas_medicas(){

    var id_paciente = $("#id_paciente").val();
    var baseURL = $('body').data('baseurl');//url base

    $('#consultas_medicas').dataTable({
        "destroy": true,//Variable que permite volver a cargar el ajax (tabla)
        "ajax": {
            "url": baseURL+"ficha_medica/listado_consultas_med/"+id_paciente,//data
            "dataSrc": ""
        },
        "columns": [ //columnas de nuestra tabla
            { "data": "id_consulta"},
            { "data": "fecha" },
            { "data": "motivo_consulta" },
            { "data": "anamnesis_proxima" },
            { "data": "acciones"}
        ],
        columnDefs: [
            { type: 'date-eu', //ordena fecha
              targets: 0
            }
        ],
        order: [[ 0, "desc" ]],//orden by por fecha de creacion
        "language": {
        "sProcessing":    "Procesando...",
        "sLengthMenu":    "Mostrar _MENU_ registros",
        "sZeroRecords":   "No se encontraron resultados",
        "sEmptyTable":    "Ningún dato disponible en esta tabla",
        "sInfo":          "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
        "sInfoEmpty":     "Mostrando registros del 0 al 0 de un total de 0 registros",
        "sInfoFiltered":  "(filtrado de un total de _MAX_ registros)",
        "sInfoPostFix":   "",
        "sSearch":        "Buscar:",
        "sUrl":           "",
        "sInfoThousands":  ",",
        "sLoadingRecords": "Cargando...",
        "oPaginate": {
            "sFirst":    "Primero",
            "sLast":    "Último",
            "sNext":    "Siguiente",
            "sPrevious": "Anterior"
            }
        },
        "oAria": {
            "sSortAscending":  ": Activar para ordenar la columna de manera ascendente",
            "sSortDescending": ": Activar para ordenar la columna de manera descendente"
        },
        responsive: false,//tabla responsive, agrega un boton
        "dom": 'T<"clear">lfrtip',
        "tableTools": {
            "sSwfPath": baseURL+"swf/copy_csv_xls_pdf.swf",//archivos necesario para que funcione
            "aButtons": [ //botones que sirven para exportar informacion de la tabla
                {
                    "sExtends": "csv",
                    "sButtonText": "CSV"
                },
                {
                    "sExtends": "xls",
                    "sButtonText": "Excel"
                },
                {
                    "sExtends": "pdf",
                    "sButtonText": "PDF"
                }
            ]
        }
    });
}

//FUNCION QUE PERMITE MOSTRAR UN MODAL CON LA INFORMACION DE UN PACIENTE
function ver_datos_paciente(id_paciente){

    var baseURL = $('body').data('baseurl');//url base

    $('#datos_paciente').html(' Cargando...');

    $.ajax({
        data: {"id_paciente" : id_paciente},
        type: "POST",
        dataType: "json",
        url: baseURL+"paciente_admin/dataPaciente"
    })
    .done(function(data,textStatus,jqXHR ) {

        if(textStatus === "success"){//La solicitud se realizo correctamente

            var nombre  =   data.primer_nombre+' '+data.segundo_nombre+' '+
                            data.apellido_paterno+' '+data.apellido_materno;

            var personas_contacto = Object.keys(data.personas_contacto).length;

            var html_personas_contacto = "";//personas de contacto

            //crear html de las personas de contacto
            for (i = 0; i < personas_contacto; i++) {

               html_personas_contacto += '
'+
               ''+data.personas_contacto[i].nombres+'	'+
               ''+data.personas_contacto[i].apellidos+'	'+
               ''+data.personas_contacto[i].correo+'	'+
               ''+data.personas_contacto[i].parentesco+'	'+
               '
';
           }

            var modal = '
'+
                '
'+
                  ''+
                    ''+
                  ''+
                '
'+
                '
'+
                    '
R.U.T: '+data.rut+'
'+
                    '
Nombre: '+nombre+'
'+
                    '
Genero: '+data.genero+'
'+
                    '
Edad: '+data.edad+'
'+
                '
'+
            '
'+
            '
'+
                '
'+
                    '
'+
                        '
'+
                            ''+
                                ' Datos de Identificación'+
                            ''+
                        '
'+
                    '
'+
                    '
'+
                        '
'+
                            '
'+
                                '
'+
                                     '
'+
                                        '
'+
                                           'Correo:	'+
                                           ''+data.email+'	 '+
                                           'Estado Civil:	'+
                                           ''+data.estado_civil+'	'+
                                        '
'+
                                        '
'+
                                           'Telefono fijo:	'+
                                           ''+data.telefono+'	'+
                                           'Celular:	'+
                                           ''+data.celular+'	'+
                                        '
'+
                                        '
'+
                                           'Religión:	'+
                                           ''+data.religion+'	'+
                                           'Previsión méd.:	'+
                                           ''+data.prevision+'	'+
                                        '
'+
                                        '
'+
                                           'País de res.:	'+
                                           ''+data.nacionalidad+'	'+
                                           '	'+
                                           '	'+
                                        '
'+
                                        '
'+
                                            'N. de estudio:	'+
                                            ''+data.nivel_estudio+'	'+
                                        '
'+
                                       '
'+
                                            'Fecha Nac.:	'+
                                            ''+data.fecha_nac+'	'+
                                            '	'+
                                            '	'+
                                        '
 '+
                                        '
'+
                                            'Lugar de Nac.:	'+
                                            ''+data.lugar_nac+'	'+
                                        '
'+
                                        '
'+
                                            'Ocupación:	'+
                                            ''+data.ocupacion+'	'+
                                        '
'+
                                     '
'+
                                 '
'+
                             '
'+
                        '
'+
                    '
'+
                '
'+
                '
'+
                    '
'+
                        '
'+
                            ''+
                                ' Datos de Residencia Actual'+
                            ''+
                        '
'+
                    '
'+
                    '
'+
                        '
'+
                            '
´'+
                                '
'+
                                    '
'+
                                        '
'+
                                            'Región:	'+
                                            ''+data.region+'	'+
                                        '
'+
                                        '
'+
                                            'Provincia:	'+
                                            ''+data.provincia+'	'+
                                        '
'+
                                       '
'+
                                            'Comuna:	'+
                                            ''+data.comuna+'	'+
                                        '
'+
                                        '
'+
                                            'Calle/pasaje/villa:	'+
                                            ''+data.calle+'	'+
                                        '
'+
                                    '
'+
                                '
'+
                            '
'+
                        '
'+
                    '
'+
                '
'+
                '
'+
                   '
'+
                        '
'+
                            ''+
                                ' Gr. Sanguineo/ F. RH'+
                            ''+
                        '
'+
                    '
'+
                    '
'+
                        '
'+
                                '
'+
                                '
'+
                                    '
'+
                                        '
'+
                                           'Grupo Sanguíneo:	'+
                                           ''+data.grupo_sang+'	'+
                                           'Factor RH:	'+
                                           ''+data.factor_rh+'	'+
                                        '
'+
                                    '
'+
                                '
'+
                            '
'+
                        '
'+
                    '
'+
                '
'+
                '
'+
                    '
'+
                        '
'+
                            ''+
                                ' Personas de Contacto'+
                            ''+
                        '
'+
                    '
'+
                    '
'+
                        '
'+
                            '
'+
                                '
'+
                                  '
'+
                                    'Nombres	'+
                                    'Apellidos	'+
                                    'Email	'+
                                    'Parentesco	'+
                                  '
'+
                                '
'+
                                '
'+
                                html_personas_contacto+
                                '
'+
                              '
'+
                        '
'+
                    '
'+
                '
'+
            '
';

            $('#datos_paciente').html(modal);
        }
    })
    .fail(function( jqXHR, textStatus, errorThrown ) {

        if(textStatus === "error") {//La solicitud a fallado

            console.log( "La solicitud a fallado: " +  textStatus);
            console.log(textStatus+" "+jqXHR);
        }
    });
}

//FUNCION QUE PERMITE ELIMINAR UN PACIENTE
function eliminar_paciente(id_paciente,nombre,rut){

    var baseURL = $('body').data('baseurl');//url base

    swal({
        title: "¿Estas seguro de eliminar al paciente "+nombre+" R.U.T. "+rut+"?",
        text: "Recuerda que todo su historial médico sera eliminado!",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Si, eliminalo!",
        cancelButtonText: "Cancelar",
        closeOnConfirm: false
    },
    function(){

        //Iniciar peticion con ajax
        $.ajax({
            data: {"id_paciente" : id_paciente},
            type: "POST",
            dataType: "json",
            url: baseURL+"paciente_admin/eliminarPaciente"
        })
       .done(function(data,textStatus,jqXHR ) {

            if(textStatus === "success"){//La solicitud se realizo correctamente

               //Paciente eliminado correctamente
               swal({
                    title: "Paciente eliminado!",
                    text:  "Historia medica del paciente fue eliminada correctamente.",
                    type:  "success"
                },
                function(){
                    //recargar tabla de pacientes
                    listado_pacientes();
                });
            }
        })
        .fail(function( jqXHR, textStatus, errorThrown ) {

            if(textStatus === "error") {//La solicitud a fallado
                alert("Error: "+textStatus+" "+jqXHR);
                console.log("La solicitud a fallado: " +  textStatus);
                console.log(textStatus+" "+jqXHR);
            }
        });
    });

    return false;

}

//FUNCION QUE PERMITE VISUALIZAR DETALLE DE LA HISTORIA MEDICA DE UN PACIENTE
function ver_HC(id_paciente){

    var baseURL = $('body').data('baseurl');//url base
    var url = baseURL+"ficha_medica/ver_detalle/"+id_paciente;
    $(location).attr('href',url);

}

<commit_msg>Avances modulo ficha clinica (11072016)<commit_after>//AL MOMENTO DE CARGAR LA PAGINA CARGA ESTO
$(document).ready(function() {

    //CARGA TABLA DE PACIENTES
    listado_consultas_medicas();

});

//FUNCION QUE PERMITE EDITAR UNA CONSULTA MEDICA
function editar_consulta_med(){

    alert("editar consulta medica");
}

//FUNCION QUE PERMITE VER INFORMACION DE UNA CONSULTA MEDICA
function ver_info_consulta_med(){

    alert("ver informacion consulta medica");
}

//FUNCION QUE PERMITE ELIMINAR UNA CONSULTA MEDICA
function eliminar_consulta_med(id_consulta_medica){

    var baseURL = $('body').data('baseurl');//url base

    swal({
        title: "¿Estas seguro de eliminar consulta médica n° "+id_consulta_medica+"?",
        text: "Recuerda que... sera eliminado!",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Si, eliminalo!",
        cancelButtonText: "Cancelar",
        closeOnConfirm: false
    },
    function(){

        //Iniciar peticion con ajax
        $.ajax({
            data: {"id_consulta" : id_consulta_medica},
            type: "POST",
            //dataType: "json",
            url: baseURL+"ficha_medica/eliminarConsultaMed"
        })
       .done(function(data,textStatus,jqXHR ) {

            if(data === "success"){//La solicitud se realizo correctamente

               //Consulta medica eliminada correctamente
               swal({
                    title: "Consulta Médica eliminada!",
                    text:  "consulta médica n° "+id_consulta_medica+" fue eliminada correctamente.",
                    type:  "success"
                },
                function(){
                    //recargar tabla de consultas medicas
                    listado_consultas_medicas();
                });

            }else{

                swal({
                    title: "Ha ocurrido un error",
                    text:  "Por favor intente nuevamente",
                    type:  "error"
                });

                return false;
            }
        })
        .fail(function( jqXHR, textStatus, errorThrown ) {

            if(textStatus === "error") {//La solicitud a fallado
                alert("Error: "+textStatus+" "+jqXHR);
                console.log("La solicitud a fallado: " +  textStatus);
                console.log(textStatus+" "+jqXHR);

                swal({
                    title: "Error: "+textStatus+" "+jqXHR,
                    text:  "",
                    type:  "error"
                });
            }
        });
    });

    return false;
}

//FUNCION QUE PERMITE CARGAR TABLA DE PACIENTES
function listado_consultas_medicas(){

    var id_paciente = $("#id_paciente").val();

    var baseURL = $('body').data('baseurl');//url base

    $('#consultas_medicas').dataTable({
        "destroy": true,//Variable que permite volver a cargar el ajax (tabla)
        "ajax": {
            "url": baseURL+"ficha_medica/listado_consultas_med/"+id_paciente,//data
            "dataSrc": ""
        },
        "columns": [ //columnas de nuestra tabla
            { "data": "id_consulta"},
            { "data": "fecha" },
            { "data": "motivo_consulta" },
            { "data": "anamnesis_proxima" },
            { "data": "acciones"}
        ],
        columnDefs: [
            { type: 'date-eu', //ordena fecha
              targets: 0
            }
        ],
        order: [[ 0, "desc" ]],//orden by por fecha de creacion
        "language": {
        "sProcessing":    "Procesando...",
        "sLengthMenu":    "Mostrar _MENU_ registros",
        "sZeroRecords":   "No se encontraron resultados",
        "sEmptyTable":    "Ningún dato disponible en esta tabla",
        "sInfo":          "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
        "sInfoEmpty":     "Mostrando registros del 0 al 0 de un total de 0 registros",
        "sInfoFiltered":  "(filtrado de un total de _MAX_ registros)",
        "sInfoPostFix":   "",
        "sSearch":        "Buscar:",
        "sUrl":           "",
        "sInfoThousands":  ",",
        "sLoadingRecords": "Cargando...",
        "oPaginate": {
            "sFirst":    "Primero",
            "sLast":    "Último",
            "sNext":    "Siguiente",
            "sPrevious": "Anterior"
            }
        },
        "oAria": {
            "sSortAscending":  ": Activar para ordenar la columna de manera ascendente",
            "sSortDescending": ": Activar para ordenar la columna de manera descendente"
        },
        responsive: false,//tabla responsive, agrega un boton
        "dom": 'T<"clear">lfrtip',
        "tableTools": {
            "sSwfPath": baseURL+"swf/copy_csv_xls_pdf.swf",//archivos necesario para que funcione
            "aButtons": [ //botones que sirven para exportar informacion de la tabla
                {
                    "sExtends": "csv",
                    "sButtonText": "CSV"
                },
                {
                    "sExtends": "xls",
                    "sButtonText": "Excel"
                },
                {
                    "sExtends": "pdf",
                    "sButtonText": "PDF"
                }
            ]
        }
    });
}

//FUNCION QUE PERMITE MOSTRAR UN MODAL CON LA INFORMACION DE UN PACIENTE
function ver_datos_paciente(id_paciente){

    var baseURL = $('body').data('baseurl');//url base

    $('#datos_paciente').html(' Cargando...');

    $.ajax({
        data: {"id_paciente" : id_paciente},
        type: "POST",
        dataType: "json",
        url: baseURL+"paciente_admin/dataPaciente"
    })
    .done(function(data,textStatus,jqXHR ) {

        if(textStatus === "success"){//La solicitud se realizo correctamente

            var nombre  =   data.primer_nombre+' '+data.segundo_nombre+' '+
                            data.apellido_paterno+' '+data.apellido_materno;

            var personas_contacto = Object.keys(data.personas_contacto).length;

            var html_personas_contacto = "";//personas de contacto

            //crear html de las personas de contacto
            for (i = 0; i < personas_contacto; i++) {

               html_personas_contacto += '
'+
               ''+data.personas_contacto[i].nombres+'	'+
               ''+data.personas_contacto[i].apellidos+'	'+
               ''+data.personas_contacto[i].correo+'	'+
               ''+data.personas_contacto[i].parentesco+'	'+
               '
';
           }

            var modal = '
'+
                '
'+
                  ''+
                    ''+
                  ''+
                '
'+
                '
'+
                    '
R.U.T: '+data.rut+'
'+
                    '
Nombre: '+nombre+'
'+
                    '
Genero: '+data.genero+'
'+
                    '
Edad: '+data.edad+'
'+
                '
'+
            '
'+
            '
'+
                '
'+
                    '
'+
                        '
'+
                            ''+
                                ' Datos de Identificación'+
                            ''+
                        '
'+
                    '
'+
                    '
'+
                        '
'+
                            '
'+
                                '
'+
                                     '
'+
                                        '
'+
                                           'Correo:	'+
                                           ''+data.email+'	 '+
                                           'Estado Civil:	'+
                                           ''+data.estado_civil+'	'+
                                        '
'+
                                        '
'+
                                           'Telefono fijo:	'+
                                           ''+data.telefono+'	'+
                                           'Celular:	'+
                                           ''+data.celular+'	'+
                                        '
'+
                                        '
'+
                                           'Religión:	'+
                                           ''+data.religion+'	'+
                                           'Previsión méd.:	'+
                                           ''+data.prevision+'	'+
                                        '
'+
                                        '
'+
                                           'País de res.:	'+
                                           ''+data.nacionalidad+'	'+
                                           '	'+
                                           '	'+
                                        '
'+
                                        '
'+
                                            'N. de estudio:	'+
                                            ''+data.nivel_estudio+'	'+
                                        '
'+
                                       '
'+
                                            'Fecha Nac.:	'+
                                            ''+data.fecha_nac+'	'+
                                            '	'+
                                            '	'+
                                        '
 '+
                                        '
'+
                                            'Lugar de Nac.:	'+
                                            ''+data.lugar_nac+'	'+
                                        '
'+
                                        '
'+
                                            'Ocupación:	'+
                                            ''+data.ocupacion+'	'+
                                        '
'+
                                     '
'+
                                 '
'+
                             '
'+
                        '
'+
                    '
'+
                '
'+
                '
'+
                    '
'+
                        '
'+
                            ''+
                                ' Datos de Residencia Actual'+
                            ''+
                        '
'+
                    '
'+
                    '
'+
                        '
'+
                            '
´'+
                                '
'+
                                    '
'+
                                        '
'+
                                            'Región:	'+
                                            ''+data.region+'	'+
                                        '
'+
                                        '
'+
                                            'Provincia:	'+
                                            ''+data.provincia+'	'+
                                        '
'+
                                       '
'+
                                            'Comuna:	'+
                                            ''+data.comuna+'	'+
                                        '
'+
                                        '
'+
                                            'Calle/pasaje/villa:	'+
                                            ''+data.calle+'	'+
                                        '
'+
                                    '
'+
                                '
'+
                            '
'+
                        '
'+
                    '
'+
                '
'+
                '
'+
                   '
'+
                        '
'+
                            ''+
                                ' Gr. Sanguineo/ F. RH'+
                            ''+
                        '
'+
                    '
'+
                    '
'+
                        '
'+
                                '
'+
                                '
'+
                                    '
'+
                                        '
'+
                                           'Grupo Sanguíneo:	'+
                                           ''+data.grupo_sang+'	'+
                                           'Factor RH:	'+
                                           ''+data.factor_rh+'	'+
                                        '
'+
                                    '
'+
                                '
'+
                            '
'+
                        '
'+
                    '
'+
                '
'+
                '
'+
                    '
'+
                        '
'+
                            ''+
                                ' Personas de Contacto'+
                            ''+
                        '
'+
                    '
'+
                    '
'+
                        '
'+
                            '
'+
                                '
'+
                                  '
'+
                                    'Nombres	'+
                                    'Apellidos	'+
                                    'Email	'+
                                    'Parentesco	'+
                                  '
'+
                                '
'+
                                '
'+
                                html_personas_contacto+
                                '
'+
                              '
'+
                        '
'+
                    '
'+
                '
'+
            '
';

            $('#datos_paciente').html(modal);
        }
    })
    .fail(function( jqXHR, textStatus, errorThrown ) {

        if(textStatus === "error") {//La solicitud a fallado

            console.log( "La solicitud a fallado: " +  textStatus);
            console.log(textStatus+" "+jqXHR);
        }
    });
}

//FUNCION QUE PERMITE ELIMINAR UN PACIENTE
function eliminar_paciente(id_paciente,nombre,rut){

    var baseURL = $('body').data('baseurl');//url base

    swal({
        title: "¿Estas seguro de eliminar al paciente "+nombre+" R.U.T. "+rut+"?",
        text: "Recuerda que todo su historial médico sera eliminado!",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Si, eliminalo!",
        cancelButtonText: "Cancelar",
        closeOnConfirm: false
    },
    function(){

        //Iniciar peticion con ajax
        $.ajax({
            data: {"id_paciente" : id_paciente},
            type: "POST",
            dataType: "json",
            url: baseURL+"paciente_admin/eliminarPaciente"
        })
       .done(function(data,textStatus,jqXHR ) {

            if(textStatus === "success"){//La solicitud se realizo correctamente

               //Paciente eliminado correctamente
               swal({
                    title: "Paciente eliminado!",
                    text:  "Historia medica del paciente fue eliminada correctamente.",
                    type:  "success"
                },
                function(){
                    //recargar tabla de pacientes
                    listado_pacientes();
                });
            }
        })
        .fail(function( jqXHR, textStatus, errorThrown ) {

            if(textStatus === "error") {//La solicitud a fallado
                alert("Error: "+textStatus+" "+jqXHR);
                console.log("La solicitud a fallado: " +  textStatus);
                console.log(textStatus+" "+jqXHR);
            }
        });
    });

    return false;

}

//FUNCION QUE PERMITE VISUALIZAR DETALLE DE LA HISTORIA MEDICA DE UN PACIENTE
function ver_HC(id_paciente){

    var baseURL = $('body').data('baseurl');//url base
    var url = baseURL+"ficha_medica/ver_detalle/"+id_paciente;
    $(location).attr('href',url);

}

<|endoftext|>