
var TaxiForm = window.TaxiForm || {};

TaxiForm = {};

TaxiForm.streetObjectTypeId = '0';

TaxiForm.PhoneField = Ext.extend(Ext.form.TextField ,{
	fieldLabel: 'Телефон',
	emptyText: 'xxx-ххх-хх-хх',
	maxLength: 16,
	enableKeyEvents: true,
	stripCharsRe: /[^0-9-]/gi,
	/*
	** Sets the caret (cursor) position of the specified text field.
	** Valid positions are 0-oField.length.
	*/
	doGetCaretPosition: function (ctrl) {
	    
	    var CaretPos = 0;
	    // IE Support
	    if (document.selection) {

	        ctrl.focus ();
	        var Sel = document.selection.createRange();
	        var SelLength = document.selection.createRange().text.length;
	        Sel.moveStart ('character', -ctrl.value.length);
	        CaretPos = Sel.text.length - SelLength;
	    }
	    // Firefox support
	    else if (ctrl.selectionStart || ctrl.selectionStart == '0')
	    CaretPos = ctrl.selectionStart;

	    return (CaretPos);
	},
	doSetCaretPosition: function (oField, iCaretPos) {
	
		// IE Support
		if (document.selection) {
		
			// Set focus on the element
			oField.focus ();
		
			// Create empty selection range
			var oSel = document.selection.createRange ();
		
			// Move selection start and end to 0 position
			oSel.moveStart ('character', -oField.value.length);
		
			// Move selection start and end to desired position
			oSel.moveStart ('character', iCaretPos);
			oSel.moveEnd ('character', 0);
			oSel.select ();
		}
	
		// Firefox support
		else if (oField.selectionStart || oField.selectionStart == '0') {
			oField.selectionStart = iCaretPos;
			oField.selectionEnd = iCaretPos;
			oField.focus ();
		}
	},

	validatePhone: function() {
	    var phone = this.getValue();
		var pattern = /^(380|80|0)\d{2}?-\d{3}-\d{2}-\d{2}$/;
		var city_pattern = /^\d{3}-\d{2}-\d{2}$/;
		
	    return (pattern.test(phone) || city_pattern.test(phone)) ? true : false;
	},
	listeners: {
	    change: function(field) {
    
    		//поиск телефона в клиентах
    		/*searchClientByPhone();*/
    		
    		if (field.getValue() && !field.validatePhone()) {
    		    Ext.MessageBox.alert(
        		    'Добавление заказов',
        		    'Не корректный формат телефона(например 352-45-58 - для городского или 097-125-02-19 - моб.)!',
        		    function() { field.focus(true); }
    		    );
    		}


    		//*поиск телефона в клиентах
    		/*
    		//формирование лога справа
    		if (LOGGING_VAR == 1) {
    			proxy_right = new Ext.data.ScriptTagProxy({
    				url: common_url + 'action.php?action=log_client&clientphone=' + getPhone() + '&password=' + Ext.get('id_dcard').getValue()
    			});
    			dsright.proxy = proxy_right;
    			dsright.load();
    		}
    */
    		//*формирование лога справа
    /*
    		var str = getPhone();
    		var city_filter = /^((\(\d{3}\) ?)|(\d{3}-))?\d{2}-\d{2}$/; //( (123) 456-7890 | 123-45-78 )
    		var mobil_filter = /^((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{2}-\d{2}$/; //( (123) 456-7890 | 066-123-45-78 )
    		if ((!city_filter.test(str) && !mobil_filter.test(str)) || str == '') {
    			Ext.MessageBox.alert('Добавление заказов', 'Не корректный формат телефона(например 352-45-58 - для городского и 097-125-02-19 - моб.)!'
    				,function() { Ext.get('id_phone_text_field').focus(true); } );
    			//return false;
    		}
    */
    	},
	    keydown: function(field, e) {
    		var value = field.getValue();
    		if (value.length>15) {
    		    field.setValue(value.substr(0,15));
    		}
    	},
    	keyup: function(field, e) {
    		var key = e.getKey();
    		var value = field.getValue();
    		var position = field.doGetCaretPosition(field.getEl().dom);
    
    		value = value.replace(/-/g,"");
    		var re;
    		var pattern = '';
    		var length = 0;
    
    		if (value.length>2 && value.substr(0,3)=='380') {
    			pattern = "(\\d{5})";
    			length = 5;
    		} else if (value.length>1 && value.substr(0,2)=='80') {
    			pattern = "(\\d{4})";
    			length = 4;
    		} else if (value.length>0 && value.substr(0,1)=='0') {
    			pattern = "(\\d{3})";
    			length = 3;
    		}
    
    		if (value.length>(length+7)) {
    			value = value.substr(0,length+7);
    			field.setValue(value);
    		}
    		if (value.length<=(length+3)) {
    			pattern = pattern+"(\\d{1,3})";
    			re = new RegExp(pattern,"");
    			value = value.replace(re, length==0?"$1":"$1-$2");
    		}
    		else if (value.length<=(length+5)) {
    			pattern = pattern+"(\\d{3})(\\d{1,2})";
    			re = new RegExp(pattern,"");
    			value = value.replace(re, length==0?"$1-$2":"$1-$2-$3");
    		}
    		else if (value.length<=(length+7)) {
    			pattern = pattern+"(\\d{3})(\\d{2})(\\d{1,2})";
    			re = new RegExp(pattern,"");
    			value = value.replace(re, length==0?"$1-$2-$3":"$1-$2-$3-$4");
    		}
    
    		field.setValue(value);
    
    		if (key==e.LEFT || key==e.RIGHT || key==e.DELETE) {
    			field.doSetCaretPosition(field.getEl().dom, position);
    		} else if (key==e.BACKSPACE){
    			if (value.substr(position==0?0:position-1,position)=='-') {
    			    field.doSetCaretPosition(field.getEl().dom, position-1);
    			} else {
    			    field.doSetCaretPosition(field.getEl().dom, position);
    			}
    		} else {
    			//if (value.substr(position<2?0:position-2,position>0?position-1:0)=='-')
    			if (value.substr(position-1,1)=='-') {
    				field.doSetCaretPosition(field.getEl().dom, position+1);
    			} else {
    			    field.doSetCaretPosition(field.getEl().dom, position);
    			}
    		}
    	}
	}
});

/* AddressObjectTypeCombo */

TaxiForm.AddressObjectTypeCombo = Ext.extend(Ext.form.ComboBox, {
    fieldLabel: 'Тип объекта',
    valueField: 'num',
	displayField: 'name',
	typeAhead: true,
	mode: 'local',
	selectOnFocus: true,
	triggerAction: 'all',
    listeners: {
	    render: function(combo){
	        combo.store.on('load', function(){
	            combo.setValue(TaxiForm.streetObjectTypeId);
	        });
	        combo.setValue(TaxiForm.streetObjectTypeId);
        }
    },
    initComponent: function(){
        this.store = TaxiForm.AddressObjectTypeCombo.getStore();
        TaxiForm.AddressObjectTypeCombo.superclass.initComponent.call(this);
    }
});

TaxiForm.AddressObjectTypeCombo.getStore = function(){
    if (!common_url) {
        throw 'common_url is not set';
    }
    if (!TaxiForm.AddressObjectTypeCombo.store) {
        TaxiForm.AddressObjectTypeCombo.store = new Ext.data.JsonStore({
    		url: common_url + 'action.php?action=get_refobjects',
            root: 'data',
            fields: ['num', 'name'],
            remoteSort: true,
    		autoLoad: true
        });
    }
    return TaxiForm.AddressObjectTypeCombo.store;
};

/*  TaxiForm.AddressObjectCombo  */
TaxiForm.AddressObjectCombo = Ext.extend(Ext.form.ComboBox, {
    valueField: 'id',
	displayField: 'name',
	typeAhead: true,
	mode: 'local',
    disabled: true,
    fieldLabel: 'Объект',
	selectOnFocus: true,
	//lazyInit: false,
	triggerAction: 'all',
	initComponent: function() {
	    if (!this.objectTypeCombo) {
	        throw 'параметр objectTypeCombo обязательно должен быть передан конструктору класса TaxiForm.AddressObjectCombo';
	    }
	    
	    if (!(this.objectTypeCombo instanceof TaxiForm.AddressObjectTypeCombo)) {
	        throw 'параметр objectTypeCombo должен быть объектом класса TaxiForm.AddressObjectTypeCombo';
	    }
        this.store = TaxiForm.AddressObjectCombo.getStore();
        
        this.objectTypeCombo.on('select', function(combo) {
            var objectNum = combo.getValue();
            if (objectNum != TaxiForm.streetObjectTypeId) {
                var params = {object_num: objectNum}; 
                this.store.reload({params: params});
                this.enable();
            } else {
                this.disable();
            }
        }, this);
        
        TaxiForm.AddressObjectCombo.superclass.initComponent.call(this);
        
        this.on('render', function(combo){
//            alert(1);
            window.combo = combo;
        });
    }
});

TaxiForm.AddressObjectCombo.getStore = function() {
    if (!common_url) {
        throw 'common_url is not set';
    }
    return new Ext.data.JsonStore({
		url: common_url + 'action.php',
		baseParams: {
		    action: 'getplace'
		},
        root: 'refplace',
        fields: ['id', 'name'],
        remoteSort: true
    });
};
