/**
 * Inicialização
**/
$(function(){
	Main.defValTextInput();
	Main.hoverEffect();
	Main.formFocus();
});

/**
 * Main
**/
var Main = {};

/**
 * Restaura valores padrão em campos ao ficar em branco.
 * Utilizar classe css "def-value-text" nos campos.
 * Invocação automática
 */
Main.defValTextInput = function () {
	var defVal = {};
	$(".def-value-text").focus(function () {
		var _this = $(this),
		ident = _this.attr("id") + '_' + _this.parents("form:first").attr("id");
		if (!defVal[ident]) defVal[ident] = $(this).val();
		if (defVal[ident] == $(this).val()) $(this).val('');
	}).blur(function () {
		var _this = $(this),
		ident = _this.attr("id") + '_' + _this.parents("form:first").attr("id")
		if ($(this).val() == '')
			$(this).val(defVal[ident]);
	});
}

/**
 * Efeito passar o mouse
 * Utilizar classe css "hover-effect" nos campos.
 * Invocação automática
 */
Main.hoverEffect = function () {
	$(".hover-effect").hover (
		function () { $(this).css("opacity", 0.88); },
		function () { $(this).css("opacity", 1); }
	);
};

Main.socialBookmark = function (data) {
	if (data.url) var url = data.url;
	else var url = document.location.href;
	
	var description = data.description;
	
	if (data.tracker) url+=data.tracker;
	
	if (description.length > 200) description=description.substring(0,197)+'...';

	switch (data.service.toLowerCase()){
		case 'orkut':
			window.open('http://promote.orkut.com/preview?nt=orkut.com&tt='+data.title+'&du='+url+'&tn='+data.thumb+'&cn='+description);		
			break;
			
		case 'facebook':
			window.open('http://www.facebook.com/share.php?u='+url+'&t='+data.title);
			break;
			
		case 'twitter':
			window.open('http://twitter.com/share?url='+encodeURIComponent(url)+'&text='+encodeURIComponent(data.title)+' '+encodeURIComponent(data.txtTwitt)+'&via=lojawinsports');
			break;
	}
}

/**
 * Seta Focus para o primeiro input do formulário
 * Utilizar classe css "field-focus" em qualquer tag ancestral.
 * Invocação automática
 */
Main.formFocus = function () {
	$(".field-focus :input:visible:first").focus();
};


Main.obtemIdent = function (str, sep) {
	if (sep == undefined) sep = '_';
	str = str.split('_');
	str = str.pop();
	return str;
}

Main.number_format = function (number, decimals, dec_point, thousands_sep){
  var exponent = "";
  var numberstr = (number ? number.toString () : 0);
  var eindex = numberstr.indexOf ("e");
  
  if (eindex > -1) {
    exponent = numberstr.substring(eindex);
    number = parseFloat(numberstr.substring (0, eindex));
  }
  
  if (decimals != null) {
    var temp = Math.pow (10, decimals);
    number = Math.round (number * temp) / temp;
  }
  var sign = number < 0 ? "-" : "";
  var integer = (number > 0 ? 
      Math.floor (number) : Math.abs (Math.ceil (number))).toString ();
  
  var fractional = number.toString ().substring (integer.length + sign.length);
  dec_point = dec_point != null ? dec_point : ".";
  fractional = decimals != null && decimals > 0 || fractional.length > 1 ? 
               (dec_point + fractional.substring (1)) : "";
  if (decimals != null && decimals > 0) {
    for (i = fractional.length - 1, z = decimals; i < z; ++i)
      fractional += "0";
  }
  
  thousands_sep = (thousands_sep != dec_point || fractional.length == 0) ? 
                  thousands_sep : null;
  if (thousands_sep != null && thousands_sep != "") {
	for (i = integer.length - 3; i > 0; i -= 3)
      integer = integer.substring (0 , i) + thousands_sep + integer.substring (i);
  }
  
  return sign + integer + fractional + exponent;
}

Main.getNumId = function (str) {
	var numId = str;
		numId = numId.split('_');
		numId = numId.pop();
	
	return numId;
};

Main.popUp = function (url, nome, parms, width, height,msg_anti_popup) {
	var msg_anti_popup = "Lembrete: Favor desbloquear o bloqueador de Pop Up para este site.";
 	var str = "height=" + height + ",innerHeight=" + height;
	str += ",width=" + width + ",innerWidth=" + width;
	var hwnd = null;
	if (parms != "") {
		str += ", " + parms;
	}
	if (window.screen) 
	{
		var ah = screen.availHeight - 30;
		var aw = screen.availWidth - 10;
		var xc = (aw - width) / 2;
		var yc = (ah - height) / 2;

	} else {
		var xc = 0, xy = 0;
	}
	str += ",left=" + xc + ",screenX=" + xc;
	str += ",top=" + yc + ",screenY=" + yc;
	hwnd = window.open(url, nome, str);
	if (hwnd != null)
	{
		if(hwnd.window.focus){hwnd.window.focus();}
	} 
	else 
	{
		alert (msg_anti_popup)
	}
//	if(text != "") hwnd.document.write(text);
//	hwnd.document.close();
	return hwnd;
};

Main.trocaponto = function (valor) {
	return (valor ? valor.replace(".", "").replace(",",".") : 0);
}

Main.number_format = function (number, decimals, dec_point, thousands_sep){
  var exponent = "";
  var numberstr = number.toString ();
  var eindex = numberstr.indexOf ("e");
  if (eindex > -1) {
    exponent = numberstr.substring (eindex);
    number = parseFloat (numberstr.substring (0, eindex));
  }
  
  if (decimals != null){
    var temp = Math.pow (10, decimals);
    number = Math.round (number * temp) / temp;
  }
  var sign = number < 0 ? "-" : "";
  var integer = (number > 0 ? 
      Math.floor (number) : Math.abs (Math.ceil (number))).toString ();
  
  var fractional = number.toString ().substring (integer.length + sign.length);
  dec_point = dec_point != null ? dec_point : ".";
  fractional = decimals != null && decimals > 0 || fractional.length > 1 ? 
               (dec_point + fractional.substring (1)) : "";
  if (decimals != null && decimals > 0) {
    for (i = fractional.length - 1, z = decimals; i < z; ++i)
      fractional += "0";
  }
  
  thousands_sep = (thousands_sep != dec_point || fractional.length == 0) ? 
                  thousands_sep : null;
  if (thousands_sep != null && thousands_sep != ""){
	for (i = integer.length - 3; i > 0; i -= 3)
      integer = integer.substring (0 , i) + thousands_sep + integer.substring (i);
  }
  
  return sign + integer + fractional + exponent;
}

/**
 * Loaders
**/
var Loader = {};
Loader.window = {};
Loader.window.show = function (texto, callback) {
	Loader.window.hide();
	
	var _loadingArea = $('<div class="loading-window-area">');
	var _loadingAreaImg = $('<div class="loading-window-area-img">');
	var _loadingAreaText = $('<div class="loading-window-area-text">');
	var _body = $('body');
	var _window = $(window);
	var windowScrollTop = _window.scrollTop();
	var windowHeight = _window.height();
	var windowWidth = _window.width();

	_body.append(_loadingArea);
	_body.append(_loadingAreaImg);
	_body.append(_loadingAreaText);
	
	_loadingArea.css("height",$(document).height()-4).css("width","100%");
	_loadingArea.css('opacity', 0.85);
	_loadingAreaImg.show();
	_loadingAreaText.show();
	
	_loadingAreaImg.css("top", (windowScrollTop + windowHeight/2) - 40 +'px');
	_loadingAreaText.css("top", (windowScrollTop + windowHeight/2) - 35 +'px');
	
	_loadingAreaImg.css("left", (windowWidth/2.5)+'px');
	_loadingAreaText.css("left", (windowWidth/2.5) + _loadingAreaImg.width() + 7 + 'px');

	if (texto != undefined) _loadingAreaText.html(texto);
	
	_window.scroll(function(){
		var _this = $(this);
		var thisScrollTop = _this.scrollTop();
		var thisHeight = _this.height();
							
		_loadingAreaImg.css("top", (thisScrollTop + thisHeight/2) - 40 +'px');
		_loadingAreaText.css("top", (thisScrollTop + thisHeight/2) - 35 +'px');
	});
	
	_loadingArea.fadeIn('fast', function(){
		if (callback != undefined) setTimeout(function(){callback.call()}, 500);
	});
};
Loader.window.hide = function () {
	if ($(".loading-window-area").length > 0){
		$(".loading-window-area").fadeOut(200, function(){
			$(".loading-window-area").remove();
			$(".loading-window-area-img").remove();
			$(".loading-window-area-text").remove();
		});
	}
}

/**
 ** Traducoes
**/
var Translate = {};
Translate.traduz = function (str) {	
	if (typeof(locale) != 'undefined') {
		var strt = locale[str];
		if (strt) 
			str = strt;
	}
	
	return str;
}
function __(str) {
	return Translate.traduz(str);	
}

/**
 ** Validacoes
**/
var Valida = {};
Valida.msg = {
	'empty' 	:	'Este campo é um campo obrigatório',
	'email'		:	'E-mail inválido',
	'cep'		:	'CEP inválido',
	'cpf'		:	'CPF inválido',
	'cnpj'		:	'CNPJ inválido',
	'numeric'	:	'Valor não é um número',
	'min'		:	'Este campo deve conter no mínimo %s caracteres',
	'max'		:	'Este campo deve conter no máximo %s caracteres',
	'len'		:	'A quantidade de %s caracteres não foi preenchida',
	'#='		:	'Confirmação não confere',
	'<>'		:	'Escolha um valor corretamente',
	'option'	:	'Escolha uma opção',
	'date'		:	'Data inválida',
	'ddd'		:	'DDD inválido',
	'estado'	:	'Estado inválido',
	'final'		:	'Alguns campos estão inválidos.\nPor favor confirme os dados nos campos marcados em vermelho.'
};

Valida.valida = function (fields, parent_tag, sufix) {
	if (parent_tag == undefined) parent_tag = 'div';
	if (sufix == undefined) sufix = null;
	
	var err = 0;
	var formObj = null;

	var i = 0;
	for (var value in fields) {
		var fieldObj = $("#" + value + (sufix != null ? '_' + sufix : ''));
		formObj = fieldObj.parents("form:first");
		var tipo_valida = fields[value];
		var valida = false;
		var tipo_erro = null;
		
		if (typeof(tipo_valida) != 'object') 
			tipo_valida = new Array(tipo_valida);
		
		if (i == 0) {
			formObj.find(parent_tag+".form-error").removeClass('form-error');
			formObj.find(".form-error-text").remove();
		}
		
		// Efetua Validação
		for (var vvalid in tipo_valida) {
			var tipo_v_t = tipo_valida[vvalid];
			var tipo_v = null;
			var tipo_v_p = null;
			var msg = null;
			
			if (typeof(tipo_v_t) == 'object') {
				tipo_v = tipo_v_t[0];
				tipo_v_p = tipo_v_t[1];
			} else {
				tipo_v = tipo_v_t;
			}
			
			switch (tipo_v) {
				case 'empty': valida = Valida.empty(fieldObj.val()); break;
				case 'email': valida = Valida.email(fieldObj.val()); break;
				case 'cep':	valida = Valida.cep(fieldObj.val()); break;
				case 'numeric': valida = Valida.numeric(fieldObj.val()); break;
				case 'min':	valida = Valida.min(fieldObj.val(), tipo_v_p); break;
				case 'max':	valida = Valida.max(fieldObj.val(), tipo_v_p); break;
				case '#=': valida = (fieldObj.val() == $("#" + tipo_v_p).val()); break;
				case '<>': valida = (fieldObj.val() != tipo_v_p); break;
				case 'option': valida = (fieldObj.val() != tipo_v_p); break;
				case 'cpf': valida = Valida.cpf(fieldObj.val()); break;
				case 'cnpj': valida = Valida.cnpj(fieldObj.val()); break;
				case 'len': valida = Valida.len(fieldObj.val(), tipo_v_p); break;
				case 'ddd': valida = Valida.len(fieldObj.val(), 2); break;
				case 'date': valida = Valida.data(fieldObj.val(), tipo_v_p); break;
				case 'estado': valida = Valida.estado(fieldObj.val()); break;
			}
			
			if (!valida) {
				tipo_erro = tipo_v;
				
				var msg = Valida.msg[tipo_erro];
				
				// Realiza tradução se funcao existe
				if (typeof(__) == 'function')
					var msg = __(msg);
				
				// Utiliza caracteres coringas
				if (tipo_v_p)
					msg = msg.replace('%s', tipo_v_p);	
				
				if (msg != null && msg != '' && msg != undefined) {
					var thisParent = fieldObj.parent();
					if (thisParent.find(".form-error-text").length < 1) {
						thisParent.append('<div class="form-error-text">' + msg + '</div>');
					}
				}
				
				break;
			}
		}
		
		if (!valida) {
			fieldObj.parents(parent_tag+":first").addClass('form-error');
			err++;
		}
		i++;
	}
	
	if (err > 0) {
		if (formObj != null) formObj.find(".form-error:first").find(':input:first').focus();
		alert(Valida.msg['final']);	
		
		return false;
	} else
		return true;
};
Valida.cep = function (cep) {
	cep = cep.replace(/\-/g, '');
	if (cep.length != 8) 
		return false;
	return true;
};
Valida.numeric = function (str) {
	if (isNaN(str) || str == '') return false;
	return true;
};
Valida.min = function (str, min) {
	if (str.length < min) return false;
	return true;
};
Valida.max = function (str, max) {
	if (str.length > max) return false;
	return true;
};
Valida.len = function (str, len) {
	if (str.length != len) return false;
	return true;
};
Valida.empty = function (str) {
	if (str.length < 1 || str == "" || str == 0)
		return false;
	return true;
};
Valida.email = function (str) {
	if (!(/^[\w!#$%&'*+\/=?^`{|}~-]+(\.[\w!#$%&'*+\/=?^`{|}~-]+)*@(([\w-]+\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/.test(str)) || !str) 
		return false;
 
	return true;
};
Valida.cpf = function (cpf) {
	erro = new String;
	cpf = cpf.replace(/\./g, '').replace(/\-/g, '');

	if (cpf.length == 11){    
		var nonNumbers = /\D/;
		if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999")
			return false;
	
		var a = [];
		var b = new Number;
		var c = 11;
	
		for (i=0; i<11; i++){
			a[i] = cpf.charAt(i);
			if (i < 9) b += (a[i] * --c);
		}
	
		if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
		b = 0;
		c = 11;
	
		for (y=0; y<10; y++) b += (a[y] * c--); 
		if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
	
		if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10]))
			return false;
	} else 
		return false;
	
    return true; 
};
Valida.cnpj = function (cnpj) {
	var cnpj = cnpj.replace(".","").replace(".","").replace("-","").replace("/","");
	var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;
	digitos_iguais = 1;
	
	if (cnpj.length < 14 && cnpj.length < 15)
		return false;
		
	for (i = 0; i < cnpj.length - 1; i++)
		if (cnpj.charAt(i) != cnpj.charAt(i + 1)){
			  digitos_iguais = 0;
			  break;
		}
		if (!digitos_iguais){
			tamanho = cnpj.length - 2
			numeros = cnpj.substring(0,tamanho);
			digitos = cnpj.substring(tamanho);
			soma = 0;
			pos = tamanho - 7;
			for (i = tamanho; i >= 1; i--){
				  soma += numeros.charAt(tamanho - i) * pos--;
				  if (pos < 2)
						pos = 9;
			}
			resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
			if (resultado != digitos.charAt(0))
				  return false;
			tamanho = tamanho + 1;
			numeros = cnpj.substring(0,tamanho);
			soma = 0;
			pos = tamanho - 7;
			for (i = tamanho; i >= 1; i--){
				soma += numeros.charAt(tamanho - i) * pos--;
				if (pos < 2)
					pos = 9;
			}
			resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
			if (resultado != digitos.charAt(1))
				return false;
		
		return true;
	} else
		return false;
};
Valida.data = function (campo, idioma) {
	if (idioma == 'en_us') {
		campot = campo.split('/');
		campo = campot[1] + '/' + campot[0] + '/' + campot[2];
	}
	
	
	var expReg = /^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[1-2][0-9]\d{2})$/;
	if ((campo.match(expReg)) && (campo!='')){
		var dia = campo.substring(0,2);
		var mes = campo.substring(3,5);
		var ano = campo.substring(6,10);

		if((mes==4 || mes==6 || mes==9 || mes==11) && dia > 30){
			return false;
		} else{
			if(ano%4!=0 && mes==2 && dia>28)
				return false;
			else{
				if(ano%4==0 && mes==2 && dia>29)
					return false;
				else
					return true;
			}
		}
	} else
		return false;
};
Valida.estado = function (estado){
	var estados = new Array('AC','AL','AP','AM','BA','DF','CE','ES','GO','MA','MT','MS','MG','PB','PR','PA','PE','PI','RJ','RN','RS','RO','RR','SC','SP','SE','TO');
	for (var i = 0; i < estados.length; i++){
		if (estados[i] == estado.toUpperCase()){
			return true;
		}
	}
	return false;
};

/**
 * Alerts
**/
var Alert = {
	idIdent : 0,
	int	: []
};
Alert.set = function setAlert(text, type, int, obj_ident) {
	alert(text);
	/*if (obj_ident == undefined) obj_ident = "alerts";
	if (int == undefined) int = 5;
	var _alert = $('#' + obj_ident);
	
	Alert.idIdent++;

	if (_alert.length == 0) {
		$("body").prepend('<div id="' + obj_ident + '"></div>');
		_alert = $('#' + obj_ident);
	}

	var ret = '<p class="alert-text">'+text+'</p>';
	ret = '<div class="alert-textarea">'+ret+'</div>';
	ret = '<div class="alert-bg"></div>'+ret;
	ret = '<div id="alert_id_' + Alert.idIdent  +'" class="alert alert-'+type+'">'+ret+'</div>';
	
	_alert.append(ret);
	Alert.actions(Alert.idIdent, int);
	if (Alert.idIdent>15) Alert.idIdent = 0;*/
}
Alert.actions = function (id, intt) {
	var _alert = $(".alert");
	
	//$("object").css("visibility", "hidden");
	//$("embed").css("visibility", "hidden");

	$("#alert_id_"+id).slideDown("normal");
	$("form").submit(function(){_alert.click()});	
	_alert.click(function(){Alert.remove(this.id);});
	Alert.int[id] = setTimeout(function(){
		clearInterval(Alert.int[id]);
		Alert.remove("alert_id_"+id);
	}, ((intt * 1000))+200);
}
Alert.remove = function (id) {
	var _alert = $("#"+id);
	
	_alert.slideUp("fast", function(){
		_alert.remove();
		//$("object").css("visibility", "visible");
		//$("embed").css("visibility", "visible");
	});
	id = id.split('_');
	id = id.pop();
	clearInterval(Alert.int[id]);
}
Alert.json = function (object, int) {
	Alert.set(object.msg, object.type, int);	
}


