/**
 * @author Marcio Antunes cgslivre at cgslivre dot com
 */
 /**
 * simula a função var_dump() do PHP
 * @param arr
 * @param level
 * @return
 */
var dump = function (arr, level) {
	var dumped_text = "";
	if (!level)
		level = 0;
	var level_padding = "";
	for ( var j = 0; j < level + 1; j++)
		level_padding += "    ";
	if (typeof (arr) == 'object') {
		for ( var item in arr) {
			var value = arr[item];
			if (typeof (value) == 'object') {
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value, level + 1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else {
		dumped_text = "===>" + arr + "<===(" + typeof (arr) + ")";
	}
	return dumped_text;
};
var _msn_obj;
function msn_settings(obj){
	_msn_obj = obj;
};
$(document).ready(function(){
	
	setTimeout(function(){
		//alert(dump(_msn_obj));
		$('.web-messenger span')
		.text('Atendimento (' + _msn_obj.statusText + ')' )
		.css({
			color: (_msn_obj.statusText == 'Online' ? 'green' : 'red')
		});
		$('.web-messenger a, a[rel="webmessenger"]')
		.click(function(){
			if(_msn_obj.statusText == 'Online'){
				var win = window.open($(this).attr('href'), 'WebMessenger', 'width=400, height=450, left=0, top=0',true); 
			}else{
				alert('O atendimento está Offline');
			}
			return false;
		});
		
	}, 1000);
	
	$('a[href^="#"]')
	.click(function(){
		var el = $(this).next();
		if(el.hasClass("sub-menu")){
			if(el.is(':visible')){
				el.slideUp();
			}else{
				el.slideDown()
				.hover(function(){
				}, function(){
					el.slideUp();
				});
			}
		}
		return false;
	});
	
	/**
	 * Replace all images with .youtube_video classname
	 * to flash embed object from youtube.com
	 */
	$('.youtube_video')
	.load(function(){
		$(this)
		.each(function(){
			var el = $(this);
			var id_video = el.attr('alt');
			var _classes = el.attr('class');
			$(this).wrap(make_embed_obj(el, id_video, _classes));						
		});
	});
	
	$('.date').html( data_extenso() );
	
	/**
	 * Home slider
	 */
	var slider_home = $('.slider .chamadas')
	.cycle({
		fx:     'scrollHorz',
		pager:  '.slider-menu', 
		pagerAnchorBuilder: function(idx, slide) {
			return '.slider-menu li:eq(' + idx + ') a'; 
		},
		startingSlide: 0, 
		speed:   500,
	    timeout: 5000 
	})
	.hover(function(){
		$(this).cycle( 'pause' );
	}, function(){
		$(this).cycle( 'resume' );
	});
	
	$('..destaques .banner-pequeno')
	.cycle({
		fx:     'scrollHorz',
		startingSlide: 0, 
		speed:   500,
	    timeout: 3000 
	});
	
	setTimeout(function(){
		if($('.posts, .calendar').outerHeight() < $('.main').innerHeight() ){
			$('.calendar-list, .posts-list, .post-entry')
			.css({
				'min-height': $('.main').innerHeight()+'px'
			});
		}
	}, 50);
	
	$('.filter select')
	.each(function(){
		$(this).change(function(){
			set_filters($(this).attr('id'));
		});
	});
	
	var dim = get_dimensions();
	
	$("a[rel=colorbox]")
	.colorbox({
		maxWidth: parseInt(dim.ww * 0.9),
		maxHeight: parseInt(dim.wh * 0.85),
		fastIframe: true,
		scalePhotos: true
	});
	
	$(".video a")
	.colorbox({
		iframe:true, 
		innerWidth: parseInt(dim.ww * 0.6), 
		innerHeight: Math.ceil(parseInt(dim.ww * 0.6) * 0.6)
	});
	
	$('[rel="colorboxPDF"]')
	.colorbox({
		current: "Arquivo {current} de {total}",
		iframe:true, 
		innerWidth: parseInt(dim.ww * 0.9), 
		innerHeight: parseInt(dim.wh * 0.85)
	});
	
	var input_value = '';
	$('form input')
	.focus(function(){
		input_value = $(this).val();
		$(this).val('');
	})
	.blur(function(){
		if($(this).val() == ''){
			$(this).val( input_value );
		}
	});
	
	$('.search-and-date form')
	.submit(function(){
		var f = $('input[name="q"]');
		if( f.val() == '' || f.val() == "Digite um termo para pesquisa" ){
			f.focus();
			return false;
		}
		return true;
	});
	
	$('form.news-form')
	.submit(function(){
		
		var self = $(this);
		
		var error = false;
		
		$.each($('input', self), function(){
			
			if($(this).val() == 'Digite seu nome' || $(this).val() == 'Digite seu e-mail'){
				$(this).focus();
				error = true;
				return false;
			}
			
			if($(this).attr('name') == 'email'){
				var email = $(this).val();
				var regex = /^((([a-z]|[0-9]|!|#|$|%|&|'|\*|\+|\-|\/|=|\?|\^|_|`|\{|\||\}|~)+(\.([a-z]|[0-9]|!|#|$|%|&|'|\*|\+|\-|\/|=|\?|\^|_|`|\{|\||\}|~)+)*)@((((([a-z]|[0-9])([a-z]|[0-9]|\-){0,61}([a-z]|[0-9])\.))*([a-z]|[0-9])([a-z]|[0-9]|\-){0,61}([a-z]|[0-9])\.)[\w]{2,4}|(((([0-9]){1,3}\.){3}([0-9]){1,3}))|(\[((([0-9]){1,3}\.){3}([0-9]){1,3})\])))$/i;
				if(!regex.test( email )){
					$(this).focus().val(email);
					error = true;
					return false;
				}
			}
			
		});
		
		if(!error){
			
			$.ajax({
				url: '/cadastros/news',
				type: 'POST',
				data: self.serialize(),
				success: function(data){
					alert(data);
					self.reset();
					return false;
				}
			});
			
		}
		
		return false;
		
	});
	
	$('.galeria-de-imagens .item a')
	.fadeTo(50, 0.8)
	.hover(function(){
		$(this).fadeTo(300, 1)
	}, function(){
		$(this).fadeTo(300, 0.8)
	});
	
	$('span.link')
	.hover(function(){
		$(this).css('cursor', 'pointer');
	})
	.click(function(){
		window.location.href = $(this).attr('rel');
	});
	
});
var set_filters = function(base_path){
	var query = [];
	$('.filter select')
	.each(function(){
		if($(this).val() != ''){
			query.push( $(this).attr('name')+'='+$(this).val() );	
		}
	});
	query = query.length ? '?'+query.join('&') : '';
	window.location = '/'+base_path+query;
};
/**
 * Objeto com o nome dos meses
 */
var mes_extenso = {
	1: 'janeiro',
	2: 'fevereiro',
	3: 'mar&ccedil;o',
	4: 'abril',
	5: 'maio',
	6: 'junho',
	7: 'julho',
	8: 'agosto',
	9: 'setembro',
	10: 'outubro',
	11: 'novembro',
	12: 'dezembro'
};

/**
 * Retorna a data por extenso
 * @return String
 */
var data_extenso = function(){
	var hoje = new Date();
	var ano = hoje.getYear();
	ano += (ano < 1900) ? 1900 : 0;
	var mes = mes_extenso[hoje.getMonth()+1];
	var dia = hoje.getDate();
	return 'Arauc&aacute;ria, '+dia+' de '+mes+' de '+ano;
};
/**
 * @param el
 * @param id_video
 * @param _classes
 * @return String;
 */
var make_embed_obj = function(el, id_video, _classes){
	var h = el.outerHeight()+20;
	return '<div id="'+id_video+'" class="'+_classes+'" style="height: '+h+'px">'
		        +'<object>'
		            +'<param name="movie" value="http://www.youtube.com/v/'+id_video+'&amp;rel=0&amp;egm=0&amp;showinfo=0&amp;fs=1"></param>'
		            +'<param name="wmode" value="transparent"></param>'
		            +'<param name="allowFullScreen" value="true"></param>'
		            +'<embed src="http://www.youtube.com/v/'+id_video+'&amp;rel=0&amp;egm=0&amp;showinfo=0&amp;fs=1" type="application/x-shockwave-flash" allowFullScreen="true" wmode="transparent"></embed>'
		        +'</object>'
			+'</div>';
};
/**
 * jQuery reset form plugin
 */
jQuery.fn.reset = function (){
   $(this).each (function(){
      this.reset();
   });
};

var get_dimensions = function(){
	return {
		wh: $(window).height(),
		ww: $(window).width(),
		hh: $('.header').outerHeight(),
		mh: $('.main').outerHeight(),
		fh: $('.footer').outerHeight()
	};
};

