dojo.provide('enuncio');
dojo.declare('enuncio'); 
dojo.require("dojo.string");

enuncio.image = {
	_preloadimages: [],
	_preloadcount: 0,
	
	preload: function(url){
		var img = dojo.create('img', {src: url});
		this._preloadimages[this._preloadcount++] = img;
	}
};

enuncio.form = {
	
	clearMessage: function (fieldId) {
     	var input = dojo.byId(fieldId);
     	var div = input.parentNode.parentNode;
     	var msgs = dojo.query('.messages', div)[0];
     	if (msgs) {
     		msgs.parentNode.removeChild(msgs);
     	}
     },

     addMessage: function (fieldId, type, message) {
         var input = dojo.byId(fieldId);
         var field = input.parentNode;
         var div = field.parentNode;
         var desc = dojo.query('.hint', div)[0];
         var msgs = dojo.query('.messages', div)[0];
         
         if (!msgs) {
         	msgs = dojo.doc.createElement('div');
         	div.insertBefore(msgs, desc);
         }
         
         msgs.className = '';
         dojo.addClass(msgs, 'messages');
        	dojo.addClass(msgs, type);
        	
         msgs.innerHTML = message;
     },
     
	/**
	 * template: {count} caracteres usados de {limite} {rest}
	 */
	showLimitCounter: function (node, limit, messageTemplate) {
		
		node = dojo.byId(node);
		var span = '<span class="counter">oi</span>';
		var hint = dojo.query('.hint', node.parentNode.parentNode)[0];
		if (!hint) {
			hint = '<div class="hint"></div>';
			hint = dojo.place(hint, node.parentNode.parentNode);
		}
		var span = dojo.place(span, hint, 'first');
		
		var update = function (e) {
			var c = dojo.attr(this, 'value').length;
			var rest = limit - c;
			var msg = messageTemplate.replace(/\{count\}/, c).replace(/\{rest\}/, rest).replace(/\{limit\}/, limit);
			span.innerHTML = msg;
		};
		
		dojo.connect(node, 'keypress', update);
		dojo.connect(node, 'keydown', update);
		dojo.connect(node, 'keyup', update);
		node.updateCounter = update;
		node.updateCounter();
	},
	
	maskValidChars: function(node, pattern){
		node = dojo.byId(node);
		var f = function(e){
			var char = e.keyChar;
			if (char && !char.match(pattern)) {
				e.preventDefault();
			}
		};
		dojo.connect(node, 'keypress', f);
	},	
	
	maskCurrency: function(node, limit){
		node = dojo.byId(node);
		
		node.maskFilter = function(text){
			if (text) var s = text;
			else var s = this.value;
			
			s = s.replace(/\./g, '')
				.replace(/^(\d+)(\d{3})/g, '$1.$2')
				.replace(/^(\d+)(\d{3}\.)/g, '$1.$2')
				.replace(/,(\d{0,2}).*/g, ',$1')
				.replace(/,$/, ',00')
				.replace(/,(\d)$/, ',$10')
				;
			
			if (s.indexOf(',') == -1) {
				s += ',00';
			}	
			this.value = s;
			return s;
		};
		
		var f = function(e){
			var char = e.keyChar;
			var vg = node.value.indexOf(',');
			
			if (!char){
				if (e.keyCode != dojo.keys.DELETE && e.keyCode != dojo.keys.BACKSPACE) {
					return;
				}
				e.preventDefault();
				var start = enuncio.form.getSelectionStart(node);
				var end = enuncio.form.getSelectionEnd(node);	
				
				var numbs = 0;
				var posnumbs = 0;
				
				for (var i = 0; i <= node.value.length; ++i){
					if (node.value.charAt(i).match(/^[0-9,]$/)) numbs++;
					if (i == start) {
						posnumbs = numbs;
						break;
					}
				}		

				if (e.keyCode == dojo.keys.BACKSPACE) {
					if (start != end) {
						if (vg >= start && vg < end) {
							node.value = node.value.substring(0, start) + ',' + node.value.substring(end);
						}						
						else node.value = node.value.substring(0, start) + node.value.substring(end);
						var dif = 0;
					} 
					else if (start-1 == vg) {
						enuncio.form.setSelection(node, start-1);
						return;
					}
					else {
						node.value = node.value.substring(0, start-1) + node.value.substring(end);
						var dif = -1;
					}
					
					// corrige apos a virgula
					if (start-2 == vg) var dif = -1;
					else if (start-3 == vg) var dif = 0;
				}
				else {
					
					if (start != end) {
						if (vg >= start && vg < end) {
							node.value = node.value.substring(0, start) + ',' + node.value.substring(end);
						}
						else node.value = node.value.substring(0, start) + node.value.substring(end);
						var dif = 0;
					} 
					else if (start == vg) {
						enuncio.form.setSelection(node, start+1);
						return;
					}
					else {
						node.value = node.value.substring(0, start) + node.value.substring(end+1);
						var dif = 0;
					}
				}
				node.maskFilter();
				var j = 0, newpos = 0;
				for (var i = 0; i < node.value.length; ++i) {
					if (node.value.charAt(i).match(/^[0-9,]$/)) j++;
					if (j == posnumbs) {
						newpos = i;
						break;
					}
				}		
				enuncio.form._fixPosition(node, newpos+dif, /[^0-9,\.]/);
				return;
			}
			e.preventDefault();
			if (!char.match(/^[0-9,]$/) || node.value.length >= limit) return;
			node.maskAdd(char);
		};
		
		node.maskAdd = function(char){
			
			var pos = enuncio.form.getSelectionStart(node);
			
			if (pos-3 != node.value.indexOf(',') && char) var s = enuncio.form.insertAtSelection(node, char);
			else var s = node.value;
				
			
			
			var numbs = 0;
			var posnumbs = 0;
			
			for (var i = 0; i <= s.length; ++i){
				if (s.charAt(i).match(/^[0-9]$/)) numbs++;
				if (i == pos) {
					posnumbs = numbs;
					break;
				}
			}		

			s = node.maskFilter(s);
			
			var j = 0, newpos = 0;
			for (var i = 0; i < s.length; ++i) {
				if (s.charAt(i).match(/^[0-9]$/)) j++;
				if (j == posnumbs) {
					newpos = i;
					break;
				}
			}
			
			if (char) newpos++;
			
			if (char == ',') enuncio.form._fixPosition(node, s.indexOf(',')+1, /[^0-9,\.]/);
			else enuncio.form._fixPosition(node, newpos, /[^0-9,\.]/);				
		};
		
		node.maskEvent = f;
		node.maskFilter();
		dojo.connect(node, 'keypress', f);
	},	
			
		
	maskNoValue: function (node, message, nonevalue) {
		var node = dojo.byId(node);
		node._message = message;
		if (!nonevalue) var nonevalue = '';
		
		var m = nonevalue.replace(/\|/, '');
		var p = nonevalue.indexOf('|');
		
		var setnone = function(){
			dojo.removeClass(node, 'novalue');
			node.value = m;
			if (p != -1) {
				enuncio.form.setSelection(node, p);
			}
		};
		
		node.checkValue = function() {
			if (dojo.hasClass(this, 'novalue')) {
				setnone();
			}
		};
		node.checkNoValue = function() {
	    	if (!this.value || this.value == m) {
	    		dojo.addClass(this, 'novalue');
	    		this.value = this._message;
	    	}	
		};
		dojo.connect(node, 'focus', node.checkValue);
		dojo.connect(node, 'blur', node.checkNoValue);
		node.checkNoValue();
		
		dojo.connect(node.form, 'submit', function(e){
			if (dojo.hasClass(node, 'novalue')) {
				dojo.removeClass(node, 'novalue');
				node.value = m;
			}
		});
		
		if (node.value == node._message || node.value == m) {
			node.checkNoValue();
		}
	},
	
	getSelectionStart: function (o) {
		if (o.createTextRange) {
			var r = document.selection.createRange().duplicate();
			r.moveEnd('character', o.value.length);
			if (r.text == '') return o.value.length;
			return o.value.lastIndexOf(r.text);
		} else return o.selectionStart;
	},

	getSelectionEnd: function (o) {
		if (o.createTextRange) {
			var r = document.selection.createRange().duplicate();
			r.moveStart('character', -o.value.length);
			return r.text.length;
		} else return o.selectionEnd;
	},
	
	setSelection: function(field, start, end){
		if (!end) end = 0;
		
		field.focus();
		
	    if(field.createTextRange) { 
	        /* Create a TextRange, set the internal pointer to
	           a specified position and show the cursor at this
	           position
	        */ 
	        var range = field.createTextRange(); 
	        range.move("character", start);
	        range.moveEnd('character', end);
	        range.select(); 
	    } else if(field.selectionStart) { 
	        /* Gecko is a little bit shorter on that. Simply
	           focus the element and set the selection to a
	           specified position
	        */ 
	    	field.setSelectionRange(start, start+end);
	    }	
	},
	
	insertAtCaret: function (field, text)
	{
	   var t = field.value;
	   var s = enuncio.form.getSelectionStart(field);
	   var newtext = t.substring(0, s) + text + t.substring(s);
	   return newtext;
	},
	
	insertAtSelection: function (field, text)
	{
	   var t = field.value;
	   var s = enuncio.form.getSelectionStart(field);
	   var e = enuncio.form.getSelectionEnd(field);
	   var newtext = t.substring(0, s) + text + t.substring(e);
	   return newtext;
	},	
	
	attachMask: function(node, func){
		node = dojo.byId(node);
		node.maskValue = node.value;
		node.maskFunc = func;
		
		var f = function(e){
			var char = e.keyChar;
			if (!char) {
				return;
			}
			e.preventDefault();
			this.insertChar = char;
			this.maskFunc(e);
		};	
		
		dojo.connect(node, 'keypress', f);		
	},
	
	_fixPosition: function(field, pos, ignorePattern){
		var l = field.value.length;
		while (pos < l && field.value.charAt(pos).match(ignorePattern)) {
			pos++;
		}
		enuncio.form.setSelection(field, pos);
	},
	
	insertAtMask: function(field, char, mask) {
		if (!char.match(/^[0-9]$/)) {
			return;
		}
		
		if (mask.length == field.value.length && enuncio.form.getSelectionStart(field) == enuncio.form.getSelectionEnd(field)) {
			return;
		}
		
		var m = mask.split("");
		var pos = enuncio.form.getSelectionStart(field);
		
		var numbs = 0;
		var posnumbs = 0;
		var s = enuncio.form.insertAtSelection(field, char).replace(/\D/g, '').split("");
		for (var i = 0; i < field.value.length; ++i){
			if (field.value.charAt(i).match(/^[0-9]$/)) {
				numbs++;
			}
			if (i+1 == pos) {
				posnumbs = numbs;
				break;
			}
		}		
	    var l = s.length;
	    var jl = m.length;
	    var f = "";
	    var j = -1;
	    
	    var newpos = 0;
	    
	    for(var i = 0; i < l && ++j < jl; ++i) {
	    	
	    	if (posnumbs == i) {
	    		newpos = f.length;
	    	}
	    	
	    	// numeros
	    	if (m[j] == '#') {
	    		if (s[i].match(/^[0-9]$/)) {
	    			f += s[i];
	    		}
	    		continue;
	    	}
	    	// adiciona o separador especial
	    	else {
	    		f += m[j];
	    		i--;
	    	}
	    }
	    
	    while (++j < jl && m[j] != '#') {
	    	f += m[j];
	    }
	    field.value = f;
	    enuncio.form._fixPosition(field, newpos+1, /[^0-9]/);
	    
	},	
	
	maskPhone: function(node){
		this.attachMask(node, function(e){
			enuncio.form.insertAtMask(this, this.insertChar, '(##) ####-####');
		});
	},
	
	maskCep: function(node){
		this.attachMask(node, function(e){
			enuncio.form.insertAtMask(this, this.insertChar, '#####-###');
		});
	},
	
	mask: function(value, mask) {
		var m = mask.split("");
	    var s = value.replace(/\D/g, '').split("");
	    var l = s.length;
	    var jl = m.length;
	    var f = "";
	    var j = -1;
	    
	    for(var i = 0; i < l && ++j < jl; ++i) {
	    	// numeros
	    	if (m[j] == '#') {
	    		if (s[i].match(/^[0-9]$/)) {
	    			f += s[i];
	    		}
	    		continue;
	    	}
	    	// se for o separador especial
	    	if (m[j] == s[i]) {
    			f += m[i];
    			continue;
    		}
	    	// adiciona o separador especial
			f += m[j];
			i--;
	    }
	    
	    while (++j < jl && m[j] != '#') {
	    	f += m[j];
	    }
	    
	    return f;
	}	
};