jQuery.noConflict();

jQuery(document).ready(function() {		
				      
	/* Hover image opacity */
	jQuery("a[data-rel^='fadeimg'] img").hover(function() {
		jQuery(this).stop().fadeTo("fast", 0.5); 
	},function(){
		jQuery(this).stop().fadeTo("fast", 1.0); 
	});
	
	/* Menu */
	ddsmoothmenu.init({
		mainmenuid: "smoothmenu1", //menu DIV id
		orientation: 'h', //Horizontal or vertical menu: Set to "h" or "v"
		classname: 'ddsmoothmenu', //class added to menu's outer DIV
		contentsource: "markup" //"markup" or ["container_id", "path_to_menu_file"]
	});
			
	/* Partners Carousel */
	if(jQuery('#partners').length != 0){
		jQuery('#partners').tinycarousel({ display: 4, interval: true, intervaltime: 5000, duration: 1000});
	}
	
	/* Partners Tooltip */
	jQuery('.overview img[title]').tooltip({opacity: 1, effect: 'toggle', delay: 0});
	
	/* Content Tabs */
	jQuery("ul.tabs").tabs("div.panes > div");
	
	/* Pricing Table Alternate Row Color */
	jQuery('.pricingtable td:odd').css({background: '#e5e5e5'});
	
	/* Contact Form */
	if(jQuery('#contactform').length != 0){
		addForm('#contactform');
	}
	
	/* Newsletter Subscription */
	if(jQuery('#newsletterform').length != 0){
		addForm('#newsletterform');
	}
	
	/* Blog Comments */
	if(jQuery('#replyform').length != 0){
		addForm('#replyform');
	}
	
	/* Blog & Portfolio Social Sharing */
	addFacebook();
	addTwitter();
	addGoogleplus();
	
	/* PrettyPhoto */
	addPrettyPhoto();
	
	/* Portfolio Quicksand */
	addPortfolio('1');
	addPortfolio('3');
	
	/* Tweet List */
	if(jQuery('#tweets').length != 0){
		jQuery.ajaxSetup({ cache: true });
		jQuery.getJSON("http://twitter.com/status/user_timeline/envato.json?count=2&callback=?", function(data){
			jQuery.each(data, function(index, item){
					jQuery(".tweetlist").append("<li>" + item.text.linkify() + "<p>" + relative_time(item.created_at) + "</p></li>");
			});
		});
	}
	
});

jQuery(window).load(function() {

	/* Nivo Slider */
	if(jQuery('#nivoSlider').length != 0){
		jQuery('#nivoSlider').nivoSlider({
			effect:'random', // Specify sets like: 'fold,fade,sliceDown'
			slices:15, // For slice animations
			boxCols: 8, // For box animations
			boxRows: 4, // For box animations
			animSpeed:500, // Slide transition speed
			pauseTime:3000, // How long each slide will show
			startSlide:0, // Set starting Slide (0 index)
			directionNav:false, // Next & Prev navigation
			directionNavHide:true, // Only show on hover
			controlNav:true, // 1,2,3... navigation
			controlNavThumbs:false, // Use thumbnails for Control Nav
			controlNavThumbsFromRel:false, // Use image rel for thumbs
			controlNavThumbsSearch: '.jpg', // Replace this with...
			controlNavThumbsReplace: '_thumb.jpg', // ...this in thumb Image src
			keyboardNav:true, // Use left & right arrows
			pauseOnHover:true, // Stop animation while hovering
			manualAdvance:false, // Force manual transitions
			captionOpacity:1, // Universal caption opacity
			prevText: '&larr;', // Prev directionNav text
			nextText: '&rarr;', // Next directionNav text
			beforeChange: function(){}, // Triggers before a slide transition
			afterChange: function(){}, // Triggers after a slide transition
			slideshowEnd: function(){}, // Triggers after all slides have been shown
			lastSlide: function(){}, // Triggers when last slide is shown
			afterLoad: function(){} // Triggers when slider has loaded
		});
	}
	
	/* Google Maps */
	loadGoogleMaps();
	
});

/* Linkify and Relative Time functions by Ralph Whitbeck http://ralphwhitbeck.com/2007/11/20/PullingTwitterUpdatesWithJSONAndJQuery.aspx */
String.prototype.linkify = function() {
        return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
                return m.link(m);
        });
};

function relative_time(time_value) {
  var values = time_value.split(" ");
  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
  var parsed_date = Date.parse(time_value);
  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
  delta = delta + (relative_to.getTimezoneOffset() * 60);

  var r = '';
  if (delta < 60) {
        r = 'a minute ago';
  } else if(delta < 120) {
        r = 'couple of minutes ago';
  } else if(delta < (45*60)) {
        r = (parseInt(delta / 60)).toString() + ' minutes ago';
  } else if(delta < (90*60)) {
        r = 'an hour ago';
  } else if(delta < (24*60*60)) {
        r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
  } else if(delta < (48*60*60)) {
        r = '1 day ago';
  } else {
        r = (parseInt(delta / 86400)).toString() + ' days ago';
  }
  
  return r;
}

function addPrettyPhoto() {
	/* PrettyPhoto init */
	jQuery("a[data-rel^='prettyPhoto']").prettyPhoto({
		overlay_gallery: true,
		show_title: false,
		hideflash: true
	});
	
	/* PrettyPhoto hover image opacity */
	jQuery("a[data-rel^='prettyPhoto'] img").hover(function() {
		jQuery(this).stop().fadeTo("fast", 0.5); 
	},function(){
		jQuery(this).stop().fadeTo("fast", 1.0); 
	});	
}

function addGoogleplus() {
	/* Google Plus One */
	if(jQuery('#googleplusone').length != 0){
        jQuery("#googleplusone").append('<g:plusone size="tall"></g:plusone>'); 
		var gpscript = document.createElement('script'); 
		gpscript.type = 'text/javascript'; 
		gpscript.src = 'https://apis.google.com/js/plusone.js'; 
		document.getElementsByTagName('head')[0].appendChild(gpscript);
	}
}

function addFacebook() {
	/* Facebook */
	if(jQuery('#facebooklike').length != 0){
		window.fbAsyncInit = function() { 
			jQuery("#facebooklike").append('<fb:like href="" layout="box_count" show_faces="false" width="55"></fb:like>'); 
		};
		var fbscript = document.createElement('script'); 
		fbscript.type = 'text/javascript'; 
		fbscript.src = 'http://connect.facebook.net/en_US/all.js#xfbml=1'; 
		document.getElementsByTagName('head')[0].appendChild(fbscript);
	}
}

function addTwitter() {
	/* Twitter */
	if(jQuery('#twittertweet').length != 0){
		jQuery("#twittertweet").append('<a href="http://twitter.com/share" class="twitter-share-button" data-url="#" data-text="Notorious Creative Portfolio Template" data-count="vertical">Tweet</a>'); 
		var twscript = document.createElement('script'); 
		twscript.type = 'text/javascript'; 
		twscript.src = 'http://platform.twitter.com/widgets.js'; 
		document.getElementsByTagName('head')[0].appendChild(twscript);
	}
}

function addSidebarSlider(){
	/* Blog Sidebar Slider */
	if(jQuery('#sidebarslider').length != 0){
		jQuery('#sidebarslider').tinycarousel({ 
			controls: false, 
			pager: true, 
			interval: true, 
			intervaltime: 3000
		});	
	}
}

function initGoogleMaps() {
	/* Google Maps Init */
	var myLatlng = new google.maps.LatLng(-29.157254, -51.18026);
	var myOptions = {
		zoom: 14,
		center: myLatlng,
		popup: true,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	}
	var map = new google.maps.Map(document.getElementById("googlemap"), myOptions);
	
	var marker = new google.maps.Marker({
		position: myLatlng, 
		map: map,
		title:"Excelência Consultores"
	});
	google.maps.event.addListener(marker, 'click', function() {
		map.setZoom(17);
	});
}
  
function loadGoogleMaps() {
	/* Google Maps Load */
	if(jQuery('#googlemap').length != 0){
		var script = document.createElement("script");
		script.type = "text/javascript";
		script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=initGoogleMaps";
		document.body.appendChild(script);
	}
}

function addPortfolio(portfolioid) {
	/* Portfolio Quicksand */
	var $list = jQuery('#portfoliolist'+portfolioid+'column');
	
	if(jQuery($list).length != 0){
		
		var $data = $list.clone();
		
		if(portfolioid==1){
			
			jQuery('.portfoliofilter_sidebar li').click(function(e) {
		
				jQuery(".portfoliofilter_sidebar li a").addClass("sidebarmenuselect_noselect");
				jQuery(".portfoliofilter_sidebar li a").removeClass("sidebarmenuselect");	
				jQuery(this).children('a').removeClass("sidebarmenuselect_noselect");
				jQuery(this).children('a').addClass("sidebarmenuselect");
		
				var filterClass = jQuery(this).attr('class');
		
				if (filterClass == 'all') {
					var $filteredData = $data.find('.blogpost');
				} else {
					var $filteredData = $data.find('.blogpost[data-type=' + filterClass + ']');
				}
				
				jQuery($list).quicksand($filteredData, {
					duration: 500,
					easing: 'swing',
					adjustHeight: 'dynamic',
					enhancement: function() {
						
					}
				}, function(){
					addPrettyPhoto();
				});
				
				return false;
			});
			
		}else{
	
			jQuery('.portfoliofilter li').click(function(e) {
		
				jQuery(".portfoliofilter li a").addClass("portfoliobutton_noselect");
				jQuery(".portfoliofilter li a").removeClass("portfoliobutton");	
				jQuery(this).children('a').removeClass("portfoliobutton_noselect");
				jQuery(this).children('a').addClass("portfoliobutton");
		
				var filterClass = jQuery(this).attr('class');
		
				if (filterClass == 'all') {
					var $filteredData = $data.find('.portfolio');
				} else {
					var $filteredData = $data.find('.portfolio[data-type=' + filterClass + ']');
				}
				
				jQuery($list).quicksand($filteredData, {
					duration: 500,
					easing: 'swing',
					adjustHeight: 'dynamic',
					enhancement: function() {
						
					}
				}, function(){
					addPrettyPhoto();
				});
				
				return false;
			});
		
		}
	}
}

/* Contact Form */
function addForm(formtype) {

	var formid = jQuery(formtype);
	var emailsend = false;
	
	formid.find("button[name=send]").click(sendemail);
	
	function validator() {
		
		var emailcheck = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
		var othercheck = /.{4}/;
		var noerror = true;
		
		formid.find(".requiredfield").each(function () {
													 
			var fieldname = jQuery(this).attr('name');
			var value = jQuery(this).val();

			if(fieldname == "email"){
				if (!emailcheck.test(value)) {
					jQuery(this).addClass("formerror");
					noerror = false;
				} else {
					jQuery(this).removeClass("formerror");
				}	
			}else{
				if (!othercheck.test(value)) {
					jQuery(this).addClass("formerror");
					noerror = false;
				} else {
					jQuery(this).removeClass("formerror");
				}	
			}
		})
		
		if(!noerror){
			formid.find(".errormessage").fadeIn();
		}
		
		return noerror;
	}
	
	function resetform() {
		formid.find("input").each(function () {
			jQuery(this).val("");	
		})
		formid.find("textarea").val("");
		emailsend = false;
	}
	
	function sendemail() {
		formid.find(".successmessage").hide();
		var phpfile = "";
		if(formtype=="#contactform"){
			phpfile = "php/contact.php";
		}else if(formtype=="#newsletterform"){
			phpfile = "php/signup.php";
		}else{
			phpfile = "";
		}
		if (validator()) {
			if(!emailsend){
				emailsend = true;
				formid.find(".errormessage").hide();
				formid.find(".sendingmessage").show();
				jQuery.post(phpfile, formid.serialize(), function() {
					formid.find(".sendingmessage").hide();
					formid.find(".successmessage").fadeIn();
					resetform();
				});
			}
		} 
		return false
	}
}

/* jQuery Smooth Tabs version 1.1.0 */
(function($) {  
	$.fn.smoothTabs = function(fadeSpeed) {
		// Visible index
		var currentIndex = 0;
		// Clicked tab class
		var smoothTabsLiCurrent = 'smoothTabsLiCurrent';
		// Hidden div class
		var smoothTabsDivHidden = 'smoothTabsDivHidden';
		// Visible div class
		var smoothTabsDivVisible = 'smoothTabsDivVisible';
		// Current hash if any.
		var hash = document.location.hash.substr(1, document.location.hash.length);

		if (hash && $('#'+hash, this).size()) {
			currentIndex = $('#'+hash, this).index();
		}

		// Makes first tab current, hides all divs and fades in the first one
		this.each(function() {
			$('ul li:eq('+currentIndex+')', this).addClass(smoothTabsLiCurrent);
			$(this).children("div").addClass(smoothTabsDivHidden);
			$('div:eq('+currentIndex+')', this).fadeIn(fadeSpeed)
								.addClass(smoothTabsDivVisible)
								.removeClass(smoothTabsDivHidden);
		});

		// Tab click function
		$('ul li', this).click(function(){
			var $parentUl = $(this).parent();
			var $parentDiv = $($parentUl).parent();
			$('li', $parentUl).removeClass(smoothTabsLiCurrent);
			$(this).addClass(smoothTabsLiCurrent);
			var $clickedIndex = $('li', $parentUl).index(this);
			var $currentDiv = $('div', $parentDiv).get($clickedIndex);
			
			// If current tab is clicked - we're done
			if ($($currentDiv).attr('class') == smoothTabsDivVisible) {
				return false;
			}
			
			// Current div is replaced by the selected one
			$('.'+smoothTabsDivVisible, $parentDiv).fadeOut(fadeSpeed, function(){
				$($currentDiv).fadeIn(fadeSpeed).addClass(smoothTabsDivVisible).removeClass(smoothTabsDivHidden);
			});
			$('.'+smoothTabsDivVisible, $parentDiv).removeClass(smoothTabsDivVisible).addClass(smoothTabsDivHidden);
		});
	};
})(jQuery);
  
