/***********************************************************************
 * 
 * INICIO DAS FUNÇÕES JQUERY
 * 
 ************************************************************************/
// Extend jQuery with a case-insensitive :contains selector
jQuery.extend(jQuery.expr[':'], {
  containsIgnoreCase: "(a.textContent||a.innerText||jQuery(a).text()||'').toLowerCase().indexOf((m[3]||'').toLowerCase())>=0"
});


// Center an object on the screen
jQuery.fn.center = function() {
	var w = $(window);
	this.css("position","absolute");
	this.css("top",(w.height()-this.height())/2+w.scrollTop() + "px");
	this.css("left",(w.width()-this.width())/2+w.scrollLeft() + "px");
	return this;
}

jQuery.fn.popupWindow = function(instanceSettings){

		return this.each(function(){

			$(this).click(function(){

				$.fn.popupWindow.defaultSettings = {
						centerBrowser:0, // center window over browser window? {1 (YES) or 0 (NO)}. overrides top and left
						centerScreen:0, // center window over entire screen? {1 (YES) or 0 (NO)}. overrides top and left
						height:500, // sets the height in pixels of the window.
						left:0, // left position when the window appears.
						location:0, // determines whether the address bar is displayed {1 (YES) or 0 (NO)}.
						menubar:0, // determines whether the menu bar is displayed {1 (YES) or 0 (NO)}.
						resizable:0, // whether the window can be resized {1 (YES) or 0 (NO)}. Can also be overloaded using resizable.
						scrollbars:0, // determines whether scrollbars appear on the window {1 (YES) or 0 (NO)}.
						status:0, // whether a status line appears at the bottom of the window {1 (YES) or 0 (NO)}.
						width:600, // sets the width in pixels of the window.
						windowName:null, // name of window set from the name attribute of the element that invokes the click
						windowURL:null, // url used for the popup
						top:0, // top position when the window appears.
						toolbar:0 // determines whether a toolbar (includes the forward and back buttons) is displayed {1 (YES) or 0 (NO)}.
				};

				settings = $.extend({}, $.fn.popupWindow.defaultSettings, instanceSettings || {});

				var windowFeatures =    'height=' + settings.height +
				',width=' + settings.width +
				',toolbar=' + settings.toolbar +
				',scrollbars=' + settings.scrollbars +
				',status=' + settings.status +
				',resizable=' + settings.resizable +
				',location=' + settings.location +
				',menuBar=' + settings.menubar;

				settings.windowName = this.name || settings.windowName;
				settings.windowURL = this.href || settings.windowURL;
				var centeredY,centeredX;

				if(settings.centerBrowser){

					if ($.browser.msie) {//hacked together for IE browsers
						centeredY = (window.screenTop - 120) + ((((document.documentElement.clientHeight + 120)/2) - (settings.height/2)));
						centeredX = window.screenLeft + ((((document.body.offsetWidth + 20)/2) - (settings.width/2)));
					}else{
						centeredY = window.screenY + (((window.outerHeight/2) - (settings.height/2)));
						centeredX = window.screenX + (((window.outerWidth/2) - (settings.width/2)));
					}
					window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + centeredX +',top=' + centeredY).focus();
				}else if(settings.centerScreen){
					centeredY = (screen.height - settings.height)/2;
					centeredX = (screen.width - settings.width)/2;
					window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + centeredX +',top=' + centeredY).focus();
				}else{
					window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + settings.left +',top=' + settings.top).focus();
				}
				return false;
			});

		});
};

// Toggle text within an element using regular expressions.
// Useful for changing "show" to "hide" and back when toggling element displays, for example
jQuery.fn.toggleText = function(a,b) {
	return this.html(this.html().replace(new RegExp("("+a+"|"+b+")"),function(x){return(x==a)?b:a;}));
}


// Fire the resize event, but only after a given delay.
// This is because the resize() event fires continuously as the user drags the window to resize, for example.
// Using this method, it will only fire a certain number of ms after the user stops resizing.
jQuery.fn.resizeComplete = function(fn, ms) {
	var timer = null;
	this.resize(function() {
		if (timer) {
			clearTimeout(timer);
		}
		timer = setTimeout(fn,ms);
	});
}

jQuery.fn.unwrap = function() {
  this.parent(':not(body)')
    .each(function(){
      $(this).replaceWith( this.childNodes );
    });

  return this;
};

jQuery.fn.resizeImg = function (maxWidth, maxHeight) {
	
	w = $(this).width();
	h = $(this).height();
	
	if (w > maxWidth) {
		ratio = maxWidth/w;
		$(this).width(maxWidth);
		$(this).height(h*ratio);
		w = w*ratio;
		h = h*ratio;
	}
	
	if (h > maxHeight) {
		ratio = maxHeight / h;
		$(this).width(w*ratio);
		$(this).height(maxHeight);
		w = w*ratio;
	}
	
	return $(this);
	
}

$(document).ready(function() {
	$("#ajaxMsg").ajaxStart(function() {
		$(this).css('display', 'block');
		$(this).center();
		$(this).css('top', $(window).scrollTop() + 'px');
	});

	$("#ajaxMsg").ajaxComplete(function() {
		$(this).css('display', 'none');
	});
});

(function( $ ){
	
	var $scrollTo = $.scrollTo = function( target, duration, settings ){
		$(window).scrollTo( target, duration, settings );
	};

	$scrollTo.defaults = {
		axis:'xy',
		duration: parseFloat($.fn.jquery) >= 1.3 ? 0 : 1
	};

	// Returns the element that needs to be animated to scroll the window.
	// Kept for backwards compatibility (specially for localScroll & serialScroll)
	$scrollTo.window = function( scope ){
		return $(window)._scrollable();
	};

	// Hack, hack, hack :)
	// Returns the real elements to scroll (supports window/iframes, documents and regular nodes)
	$.fn._scrollable = function(){
		return this.map(function(){
			var elem = this,
				isWin = !elem.nodeName || $.inArray( elem.nodeName.toLowerCase(), ['iframe','#document','html','body'] ) != -1;

				if( !isWin )
					return elem;

			var doc = (elem.contentWindow || elem).document || elem.ownerDocument || elem;
			
			return $.browser.safari || doc.compatMode == 'BackCompat' ?
				doc.body : 
				doc.documentElement;
		});
	};

	$.fn.scrollTo = function( target, duration, settings ){
		if( typeof duration == 'object' ){
			settings = duration;
			duration = 0;
		}
		if( typeof settings == 'function' )
			settings = { onAfter:settings };
			
		if( target == 'max' )
			target = 9e9;
			
		settings = $.extend( {}, $scrollTo.defaults, settings );
		// Speed is still recognized for backwards compatibility
		duration = duration || settings.speed || settings.duration;
		// Make sure the settings are given right
		settings.queue = settings.queue && settings.axis.length > 1;
		
		if( settings.queue )
			// Let's keep the overall duration
			duration /= 2;
		settings.offset = both( settings.offset );
		settings.over = both( settings.over );

		return this._scrollable().each(function(){
			var elem = this,
				$elem = $(elem),
				targ = target, toff, attr = {},
				win = $elem.is('html,body');

			switch( typeof targ ){
				// A number will pass the regex
				case 'number':
				case 'string':
					if( /^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(targ) ){
						targ = both( targ );
						// We are done
						break;
					}
					// Relative selector, no break!
					targ = $(targ,this);
				case 'object':
					// DOMElement / jQuery
					if( targ.is || targ.style )
						// Get the real position of the target 
						toff = (targ = $(targ)).offset();
			}
			$.each( settings.axis.split(''), function( i, axis ){
				var Pos	= axis == 'x' ? 'Left' : 'Top',
					pos = Pos.toLowerCase(),
					key = 'scroll' + Pos,
					old = elem[key],
					max = $scrollTo.max(elem, axis);

				if( toff ){// jQuery / DOMElement
					attr[key] = toff[pos] + ( win ? 0 : old - $elem.offset()[pos] );

					// If it's a dom element, reduce the margin
					if( settings.margin ){
						attr[key] -= parseInt(targ.css('margin'+Pos)) || 0;
						attr[key] -= parseInt(targ.css('border'+Pos+'Width')) || 0;
					}
					
					attr[key] += settings.offset[pos] || 0;
					
					if( settings.over[pos] )
						// Scroll to a fraction of its width/height
						attr[key] += targ[axis=='x'?'width':'height']() * settings.over[pos];
				}else{ 
					var val = targ[pos];
					// Handle percentage values
					attr[key] = val.slice && val.slice(-1) == '%' ? 
						parseFloat(val) / 100 * max
						: val;
				}

				// Number or 'number'
				if( /^\d+$/.test(attr[key]) )
					// Check the limits
					attr[key] = attr[key] <= 0 ? 0 : Math.min( attr[key], max );

				// Queueing axes
				if( !i && settings.queue ){
					// Don't waste time animating, if there's no need.
					if( old != attr[key] )
						// Intermediate animation
						animate( settings.onAfterFirst );
					// Don't animate this axis again in the next iteration.
					delete attr[key];
				}
			});

			animate( settings.onAfter );			

			function animate( callback ){
				$elem.animate( attr, duration, settings.easing, callback && function(){
					callback.call(this, target, settings);
				});
			};

		}).end();
	};
	
	// Max scrolling position, works on quirks mode
	// It only fails (not too badly) on IE, quirks mode.
	$scrollTo.max = function( elem, axis ){
		var Dim = axis == 'x' ? 'Width' : 'Height',
			scroll = 'scroll'+Dim;
		
		if( !$(elem).is('html,body') )
			return elem[scroll] - $(elem)[Dim.toLowerCase()]();
		
		var size = 'client' + Dim,
			html = elem.ownerDocument.documentElement,
			body = elem.ownerDocument.body;

		return Math.max( html[scroll], body[scroll] ) 
			 - Math.min( html[size]  , body[size]   );
			
	};

	function both( val ){
		return typeof val == 'object' ? val : { top:val, left:val };
	};

})( jQuery );
/***********************************************************************
 * 
 * FIM DAS FUNÇÕES JQUERY
 * 
 ************************************************************************/

function nospam(u, d) {
	return window.open('mailto:'+u+'@'+d);
}
function dw(str) {
	return document.write(str);
}

function goToURL(url, w) {
	if (!w) w = window;
	w.location.href = url;
	return true;
}

function submitBuscaProdutos(form) {
	
	el = form.q;
	if (!el.value || el.value.length < 3) {
		
		alert('Desculpe, não foi informado o texto a ser pesquisado (min. de 3 caractéres)');
		
		el.focus();
		
		return false;
		
	}
	
	return true;
	
}

function getRadioGroupValue(groupName) {
	
	var radio = document.getElementsByName(groupName);
	
	for (var i=0; i < radio.length; i++) {
		if (radio[i].checked) {
			return radio[i].value;
		}
	}
	
	return false;
}

function hideFormElement(elementId) {
	$("#"+elementId).parent().css('display', 'none');
}

function showFormElement(elementId) {
	$("#"+elementId).parent().css('display', 'block');
}

function checkAll(prefixo) {
	
	$("#"+prefixo+"*").each(function() {
		$(this).attr('checked', true);
	});
	
}

function getPlural(qtde) {
	return (qtde == 0 || qtde > 1 ? 's' : ''); 
}

function showMsgStatus(elementoId, msg) {
	$("#"+elementoId).html(msg).css('display', 'block');
	timeToFadeOut(elementoId);
}


function timeToFadeOut(elementoId, tempo) {
	if (!tempo) tempo = 5000;
	window.setTimeout(function() {
		$("#"+elementoId).fadeOut(300, function() { $(this).css('display', 'none'); });
	}, tempo);
}

function highlight(fieldId) {
       document.getElementById(fieldId).focus();
       document.getElementById(fieldId).select();
}

function extractTime(dateStr) {
	dateArr = dateStr.split(' ');
	if (typeof dateArr[1] == 'string') {
		if (dateArr[1].length >= 8) {
			return dateArr[1];
		}
	}
	return '00:00:00';
}

function resetSelect(selectId) {
	
	$('#'+selectId).attr('length', 1);
	
}

function disableSelect(selectId) {
	
	$('#'+selectId).attr('disabled', 'disabled');
	$('#'+selectId).html('<option value="" selected="selected">Carregando...</option>');
	
}

function enableSelect(selectId) {
	
	$('#'+selectId).attr('disabled', false);
	
	if ($('#'+selectId+' option:first').attr('value') == '0')
		$('#'+selectId+' option:first').attr('value', '');
	
}

function holdSession() {
	
	window.setInterval(function() {
		$.getJSON('/cms/index/holdsession');
	}, 10000);
	
}

function number_format(number, decimals, dec_point, thousands_sep) {
    // Formats a number with grouped thousands  
    // 
    // version: 1001.2911
    // discuss at: http://phpjs.org/functions/number_format    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    var n = !isFinite(+number) ? 0 : +number, 
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }    return s.join(dec);
}

function tr(str, from, to) {
    var subst;
    for (i = 0; i < from.length; i++) {
        subst = (to[i]) ? to[i] : to[to.length-1];
        str = str.replace(new RegExp(str[str.indexOf(from[i])], 'g'), subst);
    }
    return str;
}

function removeReq() {
    $('form').each(function() {
        $(this).attr('novalidate', 'novalidate');
    });
}

function easyFriendlyUrl(name2friendlyurl, target, validchars, separator) {
	
	var a_chars = new Array(
		    new Array("a",/[áàâãªÁÀÂÃ]/g),
		    new Array("e",/[éèêÉÈÊ]/g),
		    new Array("i",/[íìîÍÌÎ]/g),
		    new Array("o",/[òóôõºÓÒÔÕ]/g),
		    new Array("u",/[úùûÚÙÛ]/g),
		    new Array("c",/[çÇ]/g),
		    new Array("n",/[Ññ]/g)
		  );
	for(var i=0;i<a_chars.length;i++)
		name2friendlyurl = name2friendlyurl.replace(a_chars[i][1],a_chars[i][0]);
	
	var str = name2friendlyurl.toLowerCase() // change everything to lowercase
	.replace(/^\s+|\s+$/g, "") // trim leading and trailing spaces		
	.replace(/[_|\s]+/g, separator) // change all spaces and underscores to a hyphen
	.replace(/[^a-z0-9-]+/g, "") // remove all non-alphanumeric characters except the hyphen
	.replace(/[-]+/g, separator) // replace multiple instances of the hyphen with a single instance
	.replace(/^-+|-+$/g, "") // trim leading and trailing hyphens
	document.getElementById(target).value = str;
}

function igualarTamanho(elemento){
	var size = [];
	$(elemento).each(function(){
		size.push($(this).height());
	});

	var max = Math.max.apply(null,size);

	$(elemento).height(max);
}
