var $ = jQuery;
var JSON = JSON;

$utils = new Utils();

function Utils() {

}

Utils.prototype.charsInBag = function(s) {
	var bugchars = '!#$^&*()+|}{[]?><~%:;/,=`"\'';
	var i;
	var lchar="";
    for (i = 0; i < s.length; i++)  {   
    	var c = s.charAt(i);
    	if(i>0)lchar=s.charAt(i-1)
    	if (bugchars.indexOf(c) != -1 || (lchar=="." && c==".")) return false;
    }
    return true;
}

Utils.prototype.isInteger = function(s) {
	var i;
	for (i = 0; i < s.length; i++) {   
        var c = s.charAt(i);
        if ((c >= "0") && (c <= "9") && (c != ".")) return false;
	}
    return true;
}

Utils.prototype.emailCheck = function(str) {
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	
	if (str.indexOf(at)==-1){
		return "E-mail inválido";
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		return "E-mail inválido";
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		return "E-mail inválido";
	}

	 if (str.indexOf(at,(lat+1))!=-1){
		 return "E-mail inválido";
	 }

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		 return "E-mail inválido";
	 }

	 if (str.indexOf(dot,(lat+2))==-1){
		 return "E-mail inválido";
	 }
	
	 if (str.indexOf(" ")!=-1){
		 return "E-mail inválido";
	 }
	 
	 if($utils.charsInBag(str)==false){
		 return "E-mail inválido";
	 }

	 var arrEmail=str.split("@")
	 var ldot=arrEmail[1].indexOf(".")
	 
	 if($utils.isInteger(arrEmail[1].substring(ldot+1))==false){
		 return "E-mail inválido";
	 }	 

	 return null;					
}

Utils.prototype.emptyCheck = function(str) {
	return (this.trim(str).length == 0);
}

Utils.prototype.codeIsLetter = function(code) {
	return (((parseInt(code) >= 97) && (parseInt(code) <= 122)) ||
			((parseInt(code) >= 65) && (parseInt(code) <= 90)));
}

Utils.prototype.codeIsNumber = function(code) {
	return ((parseInt(code) >= 48) && (parseInt(code) <= 57));
}

Utils.prototype.nicknameCheck = function(nickname) {
	var resultValue = null;

	if ((nickname.length == 0)) {				
		resultValue = "Digite um apelido.";
	} else if ((nickname.length < 3) || (nickname.length > 16)) {
		resultValue = "Deve ter de 3 a 16 caracteres.";
	} else {
		for (i =0; i < (nickname.length - 1); i++) {
			charCode = nickname.charCodeAt(i);			
			if (!((this.codeIsLetter(charCode)) || (this.codeIsNumber(charCode)) || (charCode == 95))) {
				resultValue = "Car\u00E1cter inv\u00E1lido \"" + nickname.charAt(i) + "\"";
				break;
			}
		}
	}

	return resultValue;			
}

Utils.prototype.passwordCheck = function(passwordField, passwordMatch) {

	var resultValue = null;

	if (passwordField.length == 0) {				
		resultValue = "Digite uma senha.";
	}
	else if (passwordField.length < 6) {				
		resultValue = "Senha deve ter de 6 a 12 caracteres.";
	} 
	
	return resultValue;			
}

Utils.prototype.trim = function(str) {
	str = str + "";
	return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}

Utils.prototype.getValidDate = function(year, month, day) {
	var validDate = new Date(year, month - 1, day);
	
	if ((validDate.getMonth() + 1 != month) || (validDate.getDate() != day) || (validDate.getFullYear() != year)) {
		return null;
	}

	return validDate;
}

Utils.prototype.refresh = function() {
	var currentURL = unescape(window.location.pathname + window.location.search);
	window.location.href = currentURL;
}

Utils.prototype.refresh = function() {
	var currentURL = unescape(window.location.pathname + window.location.search);
	window.location.href = currentURL;
}

Utils.prototype.getHost = function() {
	siteHost = window.location + "";
	posEnd = siteHost.indexOf("://") + 3;
	posEnd = siteHost.indexOf("/", posEnd);
	siteHost = siteHost.substr(0, posEnd);
	return siteHost;  
}

Utils.prototype.getTopLeft = function(elm){
	var x, y, i = 0;
	x = elm.offsetLeft;
	y = elm.offsetTop;
	elm = elm.offsetParent;
	while(elm != null)	{
		i++
		x = parseInt(x) + parseInt(elm.offsetLeft);
		y = parseInt(y) + parseInt(elm.offsetTop);	
		if (elm.offsetParent) {
			if (parseInt(elm.offsetLeft) == parseInt(elm.offsetParent.offsetLeft)) {
				elm = elm.offsetParent.offsetParent;
			} else {
				elm = elm.offsetParent;
			}
		} else {
			elm = null;
		}
	}
    return {top:y, left: x};
}


Utils.prototype.getPageSize = function () {
	var xScroll, yScroll;

	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){// all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else {// Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}

	var windowWidth, windowHeight;

	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	

	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}

	return {width:pageWidth, height: pageHeight};
}

Utils.prototype.createMask = function(selector, alpha, color, loading) {
	var element = $($(selector).get(0));
	if (element) {
		mask_id = "div_mask_" + (new Date()).getTime();
		
		var mask_attr = selector;
		
		var mask = $("div[mask=" + mask_attr + "]").get(0); 
		
		if (!mask) {
			mask = document.createElement("DIV");
		}
		
		var maskWidth = element.outerWidth() + "px";
		var maskHeight = element.outerHeight() + "px";

		if (element.get(0).tagName == 'BODY') {
			var page = $utils.getPageSize();
			maskWidth = page.width + "px";
			maskHeight = page.height + "px";	
		}

		var pos = $utils.getTopLeft(element.get(0));
		$(mask).attr("id", mask_id);
		$(mask).attr("mask", mask_attr);
		$(mask).css("position", "absolute");
		$(mask).css("top", pos.top + "px");
		$(mask).css("left", pos.left + "px");
		$(mask).css("width", maskWidth);
		$(mask).css("height", maskHeight);
		$(mask).css("z-index", 451);
		$(mask).css("background-color", color);
		$(mask).css("text-align", "center");
		
		if (loading) {			
			var img = $("#" + mask_id + " img").get(0); 			
			if (!img) {
				img = document.createElement("IMG");
			}
			$(img).attr("src", "img/ajax-loader.gif");
			$(img).css("width", "32px");
			$(img).css("height", "32px");
			$(img).css("margin-top", (element.outerHeight() / 2 - 16) + "px");
	
			$(mask).append($(img));
		}
		
		if (alpha > 0) {
			if((navigator.appName.indexOf('Explorer') > -1)){
				$(mask).css('filter', 'alpha(opacity=' + (alpha * 100) + ')');
			}
			else{
				$(mask).css('filter', 'alpha(' + alpha + ')');
				$(mask).css('moz-opacity', alpha);
				$(mask).css('khtm-opacity', alpha);
				$(mask).css('opacity', alpha);
			}
		}

		$(mask).show();

		$('body').append($(mask));
	}
}
Utils.prototype.removeMask = function(selector) {
	var element = $(selector);

	if (element) {
		var mask_attr = selector;
		var mask = $("div[mask=" + mask_attr + "]"); 
		mask.remove();
	}
}

Utils.prototype.limitCheckbox =  function(selector, limit, restrictSelector, element) {	
	var checkboxes = $(selector);
	var cont = 0;
	var unmark = false;
	if (restrictSelector) {
		var restrict = $(restrictSelector).get(0);
		
		if ((restrict) && (restrict == element)) {
			unmark = restrict.checked;
		} else {
			if ((element) && (restrict)) {
				if (restrict.checked) {
					restrict.click();
					return;
				}
			}
		}
	}
	checkboxes.each(function(i) {
		if ($(this).get(0).checked) {
			if (unmark) {
				$(this).get(0).click();
			} else {
				cont++;
			}
		}
	});
	if (parseInt(cont) > parseInt(limit)) {
		if (element) {
			element.checked = false;
		}
	}
}

Utils.prototype.selectAllCheckbox =  function(selector, allSelector, element) {	
	var checkboxes = $(selector);
	var mark = false;
	var all = $(allSelector).get(0);
		
	if ((all) && (all == element)) {
		mark = all.checked;

		checkboxes.each(function(i) {
			if ($(this).get(0) != all) {
				if (!$(this).get(0).checked) {				
					if (mark) {
						$(this).get(0).click();
					}
				} else {
					if (!mark) {
						$(this).get(0).click();
					}			
				}
			}
		});
	} else {
		if ((!element.checked) && (all.checked)) {
			all.click();
			checkboxes.each(function(i) {
				if ($(this).get(0) != all) {
					$(this).get(0).click();
				}
			});			
		}
	}
}

Utils.prototype.fillEntity = function(elementId, entityName, entity) {
	
	var returnArrayFieldValue = function(arrayField ,entityField){		
		var value = "";
		for (var j in arrayField) {
			var obj = arrayField[j];
			if ((entityField) && ($utils.trim(entityField).length > 0)) {
				value+= ", " + obj[entityField];
			} else {
				value+= obj;
			}
		}
		return value.substring(2, value.length);
	}

	var returnFieldValue = function(entityField){
		var value = "";
		if ((entityField) && ($utils.trim(entityField).length > 0)) {
			fields = entityField.split(".");
			var obj = entity;
			for (var i in fields) {
				if (obj[fields[i]]) {
					if ($.isArray(obj[fields[i]])) {
						var index = parseInt(i) + 1;
						if (index <= (fields.length - 1)) {
							obj = returnArrayFieldValue(obj[fields[i]], fields[index]);						
						} else {
							obj = returnArrayFieldValue(obj[fields[i]], "");
						}
						break;
					} else {
						obj = obj[fields[i]];
					}
				} else {
					obj = "";
				}
			}
			value = obj;
		}
		return value;
	};

	var elements = null;
	if ((elementId) && ($utils.trim(elementId).length > 0)) {		
		 elements = $("#" + elementId + " [entity='" + entityName + "']");
	} else {
		elements = $("[entity='" + entityName + "']");
	}

	if (elements) {
		elements.each(function(i) {
			var value = returnFieldValue($(this).attr('entity_field'));
			$(this).html(value);			
		});
	}
}

Utils.prototype.showNotification =  function(content, cssClass, time) {
	var newDiv = $('<div>' + content + '</div>');
	var alertID = "alert-" + (new Date()).getTime();
	$(newDiv).attr("id", alertID);
	$(document.body).after(newDiv);

	$(newDiv).dialog({ 
		 autoOpen: true,
		 draggable: false,
		 hide: 'fast', 
		 modal: false,
		 resizable: false,
		 position: ['right','bottom'] ,
		 dialogClass: 'alert',
		 close: function(event, ui) {$utils.closeNotification(event, ui, $(newDiv))},
		 minHeight: 0,
		 width: 243 
		 });

	$(newDiv).hide();
	
	$("#" + alertID).parent().addClass(cssClass);
	
	var alertBottomSpace = 10; 
	$('div[alert]').each(function(index) {
		var parentHeight = parseInt($(this).parent().height());
		alertBottomSpace += (parentHeight + 25);
	 });
	
	var closeTime = 5000;
	if (time) {
		closeTime = time;
	}

	$(newDiv).attr("alert", alertID);
	$(newDiv).parent().css({position:"fixed", bottom: alertBottomSpace + "px",right:"10px",top:"auto",left:"auto"});
	$(newDiv).oneTime(closeTime, function() { $(this).dialog('close');});
	$(newDiv).fadeIn("slow");
}

Utils.prototype.closeNotification = function(event, ui, dialog) {
	$(dialog).fadeOut("fast");
	$(dialog).remove(); 
}

Utils.prototype.serializeForm = function(form) {
	var fields = $(form).serializeArray();
	var formObject = new Object();
	for (var i in fields) {
		if (formObject[fields[i].name]) {
			if ($.isArray(formObject[fields[i].name])) {
				formObject[fields[i].name].push(fields[i].value);
			} else {
				formObject[fields[i].name] = new Array(formObject[fields[i].name], fields[i].value);
			}
		} else {
			formObject[fields[i].name] = fields[i].value;
		}
	}
	return formObject;
}
