/**
 * JavaScript Components
 * 
 * @author   Kasem Mohamed Abou-Ali Junior (kasemjr AT gmail DOT com)
 * @version  1.1
 * @requires Prototype JavaScript Framework, version 1.3.1 (prototype.js)
 * 
 * */
 
/** JSC CORE
 * */

	// Funcao que valida a data passando uma mascara
	// EXEMPLO: (isDate('12/06/1984', 'DD/MM/YYYY'))?alert("data v?lida"):alert("data inv?lida");
	function isDate (dateValue, format) {
		if (typeof format != "string") { format = "MM/DD/YYYY"; }
		var reLiteral = format.replace(/([$^.*+?=!:|\/\\\(\)\[\]\{\}])/g, "\\$1");
		reLiteral = reLiteral.replace( "YYYY", "([0-9]{4})" );
		reLiteral = reLiteral.replace( "MM", "(0[1-9]|10|11|12)" );
		reLiteral = reLiteral.replace( "M", "([1-9]|10|11|12)" );
		reLiteral = reLiteral.replace( "DDD", "(00[1-9]|0[1-9][0-9]|[12][0-9][0-9]|3[0-5][0-9]|36[0-6])" );
		reLiteral = reLiteral.replace( "DD", "(0[1-9]|[12][0-9]|30|31)" );
		reLiteral = reLiteral.replace( "D", "([1-9]|[12][0-9]|30|31)" );
		reLiteral = reLiteral.replace( "ww", "(0[1-9]|[1-4][0-9]|5[0-3])" );
		reLiteral = reLiteral.replace( "d", "([1-7])" );
		reLiteral = "^" + reLiteral + "$";
		var re = new RegExp(reLiteral);
		if (!re.test(dateValue))  return false;
		var year = 0, month = 1, date = 1, dayofyear = 1, week = 1, day = 1;
		var tokens = format.match( /(YYYY|MM|M|DDD|DD|D|ww|d)/g );
		var values = re.exec(dateValue);
		for (var i = 0; i < tokens.length; i++) {
			switch (tokens[i]) {
				case "YYYY": year = Number(values[i+1]); break;
				case "M":
				case "MM": month = Number(values[i+1]); break;
				case "D":
				case "DD": date = Number(values[i+1]); break;
				case "DDD": dayofyear = Number(values[i+1]); break;
				case "ww": week = Number(values[i+1]); break;
				case "d": day = Number(values[i+1]); break;
			}
		}
		var leapyear = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (date == 31 && (month == 4 || month == 6 || month == 9 || month == 11)) return false;
		if (date >= 30 && month == 2) return false;
		if (date == 29 && month == 2 && !leapyear) return false;
		if (dayofyear == 366 && !leapyear)  return false;
		return true;
	}

	// pacote
	var JSC  = new Object();
	JSC.Base = function(){};
	JSC.Base.prototype = {
		
		debug: false,
		
		errors : function(e) {
			if (this.debug) { alert(e); }
		},
		
		setOptions: function(options) {
			this.options = {};
			Object.extend(this.options, options || {});
		}
		 
	};
	
	JSC.HtmlElement = Class.create();
	JSC.HtmlElement.prototype = Object.extend(new JSC.Base(), {
		initialize: function(elementID, opts) {
			this.el = $(elementID);
			this.setOptions(opts);
			if (this.main) { this.main(); }
		}
	});
	
	JSC.HtmlForm = Class.create();
	JSC.HtmlForm.prototype = Object.extend(new JSC.Base(), {
		initialize: function(formName, opts) {
			this.frm = document.forms[formName];
			this.setOptions(opts);
			if (this.main) { this.main(); }
		}
	});

/** JSC LIST TABLE - Tabela para listagem de registros.
  * 
  * */
 
	JSC.Table = Class.create();
	Object.extend(Object.extend(JSC.Table.prototype, JSC.HtmlElement.prototype), {
		
		rows_v: Array(),
		cbox_v: Array(),
		
		main: function() {
			this.update();
		},
	
		update: function() {
			
			try {
			
				this.getRows();
				this.getCBoxes();
				
				// linhas
				for (var i=0; i<this.rows_v.length; i++) {
					
					this.rows_v[i].clSelected = this.options.clSelected;
					this.rows_v[i].clHover    = this.options.clHover;
					
					if (this.options.clOdd) {
						this.rows_v[i].clOut = (i%2)?this.options.clOut:this.options.clOdd;
					} else {
						this.rows_v[i].clOut = this.options.clOut;
					}
					
					if (this.cbox_v[i]) {
						this.rows_v[i].selected = this.cbox_v[i].checked;
						this.rows_v[i].className = (this.cbox_v[i].checked) ? this.options.clSelected : this.rows_v[i].clOut;
					} else {
						this.rows_v[i].className = this.rows_v[i].clOut;
					}
					
					this.rows_v[i].onmouseover = function() {
						if (this.clHover) {
							if (this.selected) {
								if (!this.selected) this.className=this.clHover;
							} else {
								this.className=this.clHover;
							}
						}
					}
					
					this.rows_v[i].onmouseout = function() {
						if (this.clOut) {
							if (this.selected) {
								if (!this.selected) this.className=this.clOut;
							} else {
								this.className=this.clOut;
							}
						}
					}
					
				}
				// linhas - fim
				
				// selection checkbox
				var cboxSelection = $(this.options.cboxSelection);
				
				if (cboxSelection && this.cbox_v.length > 0) {
					cboxSelection.cboxes = this.cbox_v;
					cboxSelection.onclick = function() {
						for(var i=0; i<this.cboxes.length; i++) {
							this.cboxes[i].checked = this.checked;
							this.cboxes[i].update();
						}
					}
				}
				// selection checkbox - fim
				
				// checkboxes
				for (var i=0; i<this.cbox_v.length; i++) {
					
					this.cbox_v[i].cboxSelection = cboxSelection;
					this.cbox_v[i].cboxes  = this.cbox_v;
					this.cbox_v[i].row     = this.cbox_v[i].parentNode.parentNode; //this.rows_v[i];
                                        this.cbox_v[i].rowSpan = this.cbox_v[i].parentNode.rowSpan;
					
					this.cbox_v[i].update = function() {
                                                
                                                if (this.rowSpan>1) {
                                                
                                                    var theadRows = this.row.parentNode.parentNode.tHead.rows.length;
                                                    
                                                    var limit = (this.row.rowIndex-theadRows);
                                                
                                                    for (var idx=limit; idx < (limit+this.rowSpan); idx++) {
                                                    
                                                        this.row.parentNode.rows[idx].className = (this.checked)?
                                                            this.row.parentNode.rows[idx].clSelected:
                                                            this.row.parentNode.rows[idx].clOut;
                                                            
                                                        this.row.parentNode.rows[idx].selected = this.checked;
                                                        
                                                    }
                                                
                                                } else {
                                                
                                                    this.row.className = (this.checked)?this.row.clSelected:this.row.clOut;
                                                    this.row.selected = this.checked;
                                                
                                                }
                                                
					}
					
					this.cbox_v[i].onclick = function () {
						if (this.cboxSelection) {
							var aux=0;
							for (var i=0;i<this.cboxes.length;i++) {
								if (this.cboxes[i].checked) {
									aux++;
								}
							}
							this.cboxSelection.checked = (aux==this.cboxes.length);
						}
						this.update();
					}
					
				}
				// checkboxes - fim
				
			} catch(e) { this.errors(e); }
			
		},
		
		getRows: function() {
			
			try {
				
				this.rows_v = Array();
				
				for (var x=0; x < this.el.tBodies.length; x++) {
					for (var i=0; i < this.el.tBodies[x].rows.length; i++) {
						this.rows_v.push(this.el.tBodies[x].rows[i]);
					}
				}
				
			} catch(e) { this.errors(e); }
			
		},
		
		getCBoxes: function() {
			
			try {
				
				this.cbox_v = Array();
				
				for(var i=0; i<this.rows_v.length; i++) {
					for(var j=0; j<this.rows_v[i].cells.length; j++) {
						if (this.rows_v[i].cells[j].firstChild) {
							if (this.rows_v[i].cells[j].firstChild.nodeName.toLowerCase() == "input") {
								if (
									(this.rows_v[i].cells[j].firstChild.type.toLowerCase() == "checkbox") ||
									(this.rows_v[i].cells[j].firstChild.type.toLowerCase() == "radio")) {
										this.cbox_v.push(this.rows_v[i].cells[j].firstChild);
								}
							}
						}
					}
				}
				
			} catch(e) { this.errors(e); }
			
		},
		
		toggle: function(opt) {
			
			try {
				
				if (opt) {
					switch (opt.toLowerCase()) {
					case "on":
						for(var i=0; i<this.cbox_v.length; i++) {
							this.cbox_v[i].checked = true;
							this.cbox_v[i].update();
						}
						break;
						
					case "off":
						for(var i=0; i<this.cbox_v.length; i++) {
							this.cbox_v[i].checked = false;
							this.cbox_v[i].update();
						}
						break;
					}
				} else {
					for(var i=0; i<this.cbox_v.length; i++) {
						this.cbox_v[i].checked = !this.cbox_v[i].checked;
						this.cbox_v[i].update();
					}				
				}
				
			} catch(e) { this.errors(e); }
			
		},
		
		isChecked: function() {
			
			try {
				
				for (var i=0;i<this.cbox_v.length;i++) {
					if (this.cbox_v[i].checked) {
						return true;
					}
				}
				
				return false;
				
			} catch(e) { this.errors(e); }
			
		}
	
	});
	
/* *********************************************
 * */ 
 
	JSC.Mask = Class.create();
	Object.extend(Object.extend(JSC.Mask.prototype, JSC.HtmlForm.prototype), {
	   	   
		fields   : Array(),
		reserved : ("*", "9", "#"),
		
		voidKey: function(c, e) {
		
			var can = false;
			var key = Util.getKey(e);
			
			if (key > 31) {
			
				switch(c) {
					case '9' : can = ((key>=48)&&(key<=57)); break;
					case '#' : can = (((key>=48)&&(key<=57))||((key>=65)&&(key<=90)||((key>=97)&&(key<=122)))); break;
				}
				
			}
			
			return can;
		
		},
		
		isReserved: function(c) {
		   
		   return (c=='9'||c=='#');
		   
		},
	  
	   addField: function(field, mask) {
	      
			var inp = eval("this.frm." + field);
			
			inp.maxLength = mask.length;
			
			inp.frm       = this;
			inp.oldValue  = inp.value;
	      inp.mask      = mask;
	      inp.modifield = false;
	      
	      inp.onkeypress = function(e) {
	         
	         /* ======================================================= */
	         
	         if (Util.getKey(e)!=0) this.modifield = true;
	         
				var v = new Array();
				var index = this.value.length;
				
				for (var q=0; q<this.mask.length; q++) v.push(this.mask.substr(q, 1));
				
				if (Util.getKey(e) > 31) {
				
					if (this.frm.isReserved(v[index])) {
					   
						if (this.frm.voidKey(v[index], e)) {
						   
							this.value[index] += Util.getAscii(Util.getKey(e));
							
							if (!this.frm.isReserved(v[index+1])) {
							   
								if (v[index+1]) {
								   
									this.value += Util.getAscii(Util.getKey(e)) + v[index+1];
									return false;
									
								}
								
							}
							
						} else {
						   
							return false;
							
						}
						
					} else {
					   
						if (v[index+1]) {
						   
							if (this.frm.isReserved(v[index+1])) {
							   
								if (this.frm.voidKey(v[index+1], e)) {
								   
									this.value += v[index] + Util.getAscii(Util.getKey(e));
									return false;
									
								} else {
								   
									return false;
									
								}
								
							}
							
						}
						
					}
					
				} else {
				   
					return true;
					
				}
	         
	         /* ======================================================= */
	         
	      };
	      
	      this.fields.push(inp);
	      
	   },
	   
	   getCaretPos: function (oField) {

			// Initialize
			var iCaretPos = 0;
			
			if (document.selection) { // IE Support
			
				// Set focus on the element
				oField.focus ();
				  
				// To get cursor position, get empty selection range
				var oSel = document.selection.createRange ();
				  
				// Move selection start to 0 position
				oSel.moveStart ('character', -oField.value.length);
				  
				// The caret position is selection length
				iCaretPos = oSel.text.length;
				
			} else { // Firefox support
			   
			   if (oField.selectionStart || oField.selectionStart == '0')
				iCaretPos = oField.selectionStart;
				
			}
			
			// Return results
			return (iCaretPos);
		
	   }
	   
	});
	
	
	Util = {
	   
	   getAscii: function(decimalCode) {
	      
	      var ascii = new Array();

			ascii[48] = '0'; ascii[49] = '1'; ascii[50] = '2';
			ascii[51] = '3'; ascii[52] = '4'; ascii[53] = '5';
			ascii[54] = '6'; ascii[55] = '7'; ascii[56] = '8';
			ascii[57] = '9';
		
			ascii[65] = 'A'; ascii[66] = 'B'; ascii[67] = 'C';
			ascii[68] = 'D'; ascii[79] = 'E'; ascii[70] = 'F';
			ascii[71] = 'G'; ascii[72] = 'H'; ascii[73] = 'I';
			ascii[74] = 'J'; ascii[75] = 'K'; ascii[76] = 'L';
			ascii[77] = 'M'; ascii[78] = 'N'; ascii[79] = 'O';
			ascii[80] = 'P'; ascii[81] = 'Q'; ascii[82] = 'R';
			ascii[83] = 'S'; ascii[84] = 'T'; ascii[85] = 'U';
			ascii[86] = 'V'; ascii[87] = 'W'; ascii[88] = 'X';
			ascii[89] = 'Y'; ascii[90] = 'Z';
		
			ascii[97]  = 'a'; ascii[98]  = 'b'; ascii[99]  = 'c';
			ascii[100] = 'd'; ascii[101] = 'e'; ascii[102] = 'f';
			ascii[103] = 'g'; ascii[104] = 'h'; ascii[105] = 'i';
			ascii[106] = 'j'; ascii[107] = 'k'; ascii[108] = 'l';
			ascii[109] = 'm'; ascii[110] = 'n'; ascii[111] = 'o';
			ascii[112] = 'p'; ascii[113] = 'q'; ascii[114] = 'r';
			ascii[115] = 's'; ascii[116] = 't'; ascii[117] = 'u';
			ascii[118] = 'v'; ascii[119] = 'w'; ascii[120] = 'x';
			ascii[121] = 'y'; ascii[122] = 'z';
		
			return ascii[decimalCode];
	      
	   },
	   
	   getKey: function(e) {
	      
	      return (navigator.appName.indexOf("Microsoft")!=-1)?event.keyCode:e.charCode;
	      
	   },
	   
		isEmpty: function (inputVal) {
			
			return (inputVal==null||inputVal=="");
			
		},
		
		isInteger: function (inputVal) {

			var inputStr = inputVal.toString();
			for (var i = 0; i < inputStr.length; i++) {
				var oneChar = inputStr.charAt(i)
				if (i == 0 && oneChar == "-") {
					continue;
				}
				if (oneChar < "0" || oneChar > "9") {
					return false;
				}
			}
			return true;
			
		},
		
		isNumber: function (inputVal) {
		   
                    if (!this.isEmpty(inputVal)) {
                    
			var oneDecimal = false;
			var inputStr = inputVal.toString();
			for (var i = 0; i < inputStr.length; i++) {
				var oneChar = inputStr.charAt(i);
				if (i == 0 && oneChar == "-") {
					continue;
				}
				if (oneChar == "." && !oneDecimal) {
					oneDecimal = true;
					continue;
				}
				if (oneChar < "0" || oneChar > "9") {
					return false;
				}
			}
                        
			return true;
                    
                    } else {
                    
                        return false;
                    }
			
		},
		
		inRange: function (inputVal, minVal, maxVal) {
		   
			var mn = minVal.parseInt();
			var mx = maxVal.parseInt();
			return (inputVal > mn && inputVal < mx);
			
		}
	   
	}
	
/** JSC Dynamic Table
  * 
  * */
 
	JSC.DynamicTable = Class.create();
	Object.extend(Object.extend(JSC.DynamicTable.prototype, JSC.HtmlElement.prototype), {
		
		cells_v: Array(), // vetor com o conteudo de cada celula...
		cbox_v: Array(),
		
		main: function() {
			
			this.update();
			
		},
	
		update: function() {

			try {
			
				this.getCells();
				this.getCBoxes();
				
			} catch(e) { this.errors(e); }
			
		},
		
		addRow: function() {
			
			try {
				
				var nr = this.el.insertRow(-1);
				
				for (var i=0; i<this.cells_v.length; i++) {
					
					var nc = nr.insertCell(i);
					nc.innerHTML = this.cells_v[i].innerHTML;
					
					if (nc.lastChild.nodeName.toLowerCase()=="input") {
						
						nc.lastChild.value = "";
						
					}
					
				}
				
				Behaviour.apply();
				
			} catch(e) { this.errors(e); }
			
		},
		
		remRow: function(msg) {
			
			try {
				
				this.getCBoxes();
				
				if (Util.isEmpty(msg)) {
				
					for (var i=0; i < this.cbox_v.length; i++) {
						
						if (this.cbox_v[i].checked) {
							
							if (this.el.rows.length==2) {
						
								for (var j=0; j<this.el.rows[1].cells.length; j++) {
									
									if (this.el.rows[1].cells[j].lastChild.nodeName.toLowerCase() == "input") {
										
										this.el.rows[1].cells[j].lastChild.value = "";
										
									}
									
								}
								
								this.el.rows[1].cells[0].lastChild.checked = false;
						
							} else {
								
								this.el.deleteRow(this.cbox_v[i].parentNode.parentNode.rowIndex);
								
							}
						
						}
						
					}
					
				} else {
					
					if (confirm(msg)) {
						
						this.remRow();
						
					}
					
				}
				
			} catch(e) { this.errors(e); }
			
		},
		
		getCells: function() {
			
			try {
				
				if (this.el.rows.length > 0) {
					
					for (var i=0; i<this.el.rows[1].cells.length; i++ ) {
						
						this.cells_v.push(this.el.rows[1].cells[i]);
						
					}
					
				}
				
			} catch(e) { this.errors(e); }
			
		},
		
		getCBoxes: function() {
			
			try {
				
				this.cbox_v = Array();
				
				if (!Util.isEmpty(this.options.formName) && !Util.isEmpty(this.options.cboxItens)) {
					
					var frm = document.forms[this.options.formName];
					
					for (var i=0; i<frm.elements.length; i++) {
						
						if (frm.elements[i].name==this.options.cboxItens) this.cbox_v.push(frm.elements[i]);
						
					}
					
				}
				
			} catch(e) { this.errors(e); }
			
		},
		
		isChecked: function() {
			
			try {
				
				this.getCBoxes();
				
				for (var i=0;i<this.cbox_v.length;i++) {
					
					if (this.cbox_v[i].checked) {
						
						return true;
						
					}
					
				}
				
				return false;
				
			} catch(e) { this.errors(e); }
			
		}
	
	});

