function replaceURLWithHTMLLinks(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/i;
    return text.replace(exp,"<a target=\"_blank\" href='$1'>$1</a>"); 
}

function relative_time(time_value,lang) {
    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 = new Date();
    var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
    delta = delta + (relative_to.getTimezoneOffset() * 60);
  
    if (typeof(lang) === 'undefined') {
        lang = 'en';
    }
	
    switch (lang) {
    	// French
        case 'fr' :
            if (delta < 2) {
            	return 'Tout &agrave; l\'heure';
            } else if (delta < 60) {
                return 'Il y a ' + (parseInt(delta)).toString() + ' secondes';
            } else if(delta < 120) {
                return 'Il y a 1 minute';
            } else if(delta < (60*60)) {
                return 'Il y a ' + (parseInt(delta / 60)).toString() + ' minutes';
            } else if(delta < (120*60)) {
                return 'Il y a 1 heure';
            } else if(delta < (24*60*60)) {
                return 'Il y a ' + (parseInt(delta / 3600)).toString() + ' heures';
            } else if(delta < (48*60*60)) {
                return 'Il y a un jour';
            } else {
                return 'Il y a ' + (parseInt(delta / 86400)).toString() + ' jours';
            }
            break;
    	// Spanish
        case 'es' :
            if (delta < 2) {
            	return 'en este momento';
            } else if (delta < 60) {
                return 'hace ' + (parseInt(delta)).toString() + 'segundos';
            } else if(delta < 120) {
                return 'hace un minuto';
            } else if(delta < (60*60)) {
                return 'hace ' + (parseInt(delta / 60)).toString() + ' minutos';
            } else if(delta < (120*60)) {
                return 'hace una hora';
            } else if(delta < (24*60*60)) {
                return 'hace  ' + (parseInt(delta / 3600)).toString() + ' horas';
            } else if(delta < (48*60*60)) {
                return 'hace una d&iacute;a';
            } else {
                return (parseInt(delta / 86400)).toString() + ' days ago';
            }
            break;
    	// Italian
        case 'it' :
            if (delta < 2) {
            	return 'ora';
            } else if (delta < 60) {
                return (parseInt(delta)).toString() + 'secondi fa';
            } else if(delta < 120) {
                return '1 minuto fa';
            } else if(delta < (60*60)) {
                return (parseInt(delta / 60)).toString() + ' minuti fa';
            } else if(delta < (120*60)) {
                return '1 ora fa';
            } else if(delta < (24*60*60)) {
                return (parseInt(delta / 3600)).toString() + ' ore fa';
            } else if(delta < (48*60*60)) {
                return '1 giorno ago';
            } else {
                return (parseInt(delta / 86400)).toString() + ' giorni fa';
            }
            break;
        // English (default)
        case 'en' :
        default :
            if (delta < 2) {
            	return 'now';
            } else if (delta < 60) {
                return (parseInt(delta)).toString() + 'seconds ago';
            } else if(delta < 120) {
                return 'about a minute ago';
            } else if(delta < (60*60)) {
                return (parseInt(delta / 60)).toString() + ' minutes ago';
            } else if(delta < (120*60)) {
                return 'about an hour ago';
            } else if(delta < (24*60*60)) {
                return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
            } else if(delta < (48*60*60)) {
                return '1 day ago';
            } else {
                return (parseInt(delta / 86400)).toString() + ' days ago';
            }
            break;
    }

}

// Input Placeholder plugin
$.fn.inputPlaceholder = function(){
    var $form = $(this).parentsUntil('form').parent(),
    $inputs = $(this);
	
    $form.submit(function(){
        $inputs.each(function(){
            $input = $(this),
            placeholder = $(this).attr('data-placeholder');
            if ($input.val() == placeholder)
                $input.val('');
        });
    });

    return this.each(function(){
        var $input = $(this),
        placeholder = $(this).attr('data-placeholder');
		
        $input.focus(function(){
            if ($input.val() == placeholder)
                $input.val('');
        }).blur(function(){
            if ($input.val() == '')
                $input.val(placeholder);
        }).blur();
    });
};

// Hide archive plugin
$.fn.hideArchive = function(){
    return $(this).each(function(){
        var $list = $(this),
        $listItems = $('li',$list),
        initialCount = 6,
        //$listToggle = $('<li class="more-arrow more-arrow-bottom"><a href="#" title="">See more monthly archives</a></li>'),
        $listToggle = $('<li class="more-arrow more-arrow-bottom"><a href="#" title="">'+ $("#more-archives").text() +'</a></li>'),
        $hiddenItems;
			
        if ($listItems.length > (initialCount)) {
            $listItems.filter(':eq('+(initialCount-1)+')').after($listToggle);
            $hiddenItems = $listItems.slice(initialCount).hide();
				
            $listToggle.click(function(){
                $(this).off('click').remove();
                $hiddenItems.fadeIn('fast');
					
                return false;
            });
        }
			
    });	
};

// Footer Twitter plugin
function twitterFooterInsert(data) {
    var lang = $('#tweets-footer').attr('data-lang');
    $('#tweets-footer').html('');
    for (var i = 0; i < data.length; i++) {
        $('#tweets-footer').append('<li><a target="_blank" class="profile-link" href=http://twitter.com/#!/viadeo/status/'+data[i].id_str+'><img src="'+data[i].user.profile_image_url+'" /></a>'+replaceURLWithHTMLLinks(data[i].text)+'<br /><span class="tweet-timestamp">- '+relative_time(data[i].created_at,lang)+'</span></li>');
    }
}

$.fn.loadFooterTweets = function(){
    return this.each(function(){
	
        var $container  = $(this),
        username    = $container.attr('data-username'),
        tweetCount = $container.attr('data-tweets'),
        items = [];
			
        if (username == '') username = 'viadeo';
        if (tweetCount == '') tweetCount = 5;
		
        var twitterJSON = document.createElement('script');
        twitterJSON.type='text/javascript'
        twitterJSON.src='http://api.twitter.com/1/statuses/user_timeline.json?callback=twitterFooterInsert&screen_name='+username+'&count='+tweetCount;
        document.getElementsByTagName("head")[0].appendChild(twitterJSON);
        $('#tweets-footer').html('<p style="text-align:center">Loading...</p>');
		
    });	
};


// Author Twitter plugin
function twitterAuthorInsert(data) {
    var lang = $('#tweets-author').attr('data-lang');
    $('#tweets-author').html('');
    
    $('#tweets-author').append('<a target="_blank" class="profile-link" href=http://twitter.com/#!/viadeo/status/'+data[0].id_str+'></a>'+replaceURLWithHTMLLinks(data[0].text)+'<br /><span class="tweet-timestamp">- '+relative_time(data[0].created_at,lang)+'</span>');
    
}

$.fn.loadAuthorTweets = function(){
    return this.each(function(){
	
        var $container  = $(this),
        username    = $container.attr('data-username'),
        tweetCount = 1,
        items = [];
			
        if (username == '') username = 'viadeo';
		
        var twitterJSON = document.createElement('script');
        twitterJSON.type='text/javascript'
        twitterJSON.src='http://api.twitter.com/1/statuses/user_timeline.json?callback=twitterAuthorInsert&screen_name='+username+'&count='+tweetCount;
        document.getElementsByTagName("head")[0].appendChild(twitterJSON);
        $('#tweets-author').html('Loading...');
		
    });	
};

// Team profile plugin
$.fn.teamProfiles = function(){

	return this.each(function(){
	    var $current = false,
		    $previous = false,
		    $current_index = '',
		    $prev_index = '',
		    $current_link = '',
		    $container = $(this);

		$container.bind('checkScrollPos',function(){
			var $profileInfo = $('.selected-profile'),
				containerPos = $profileInfo.offset(),
				containerHeight = $profileInfo.outerHeight();
			
			if ($(window).scrollTop()+$(window).height() < containerPos.top+containerHeight) {
				$('html,body').animate({
					scrollTop : containerPos.top-240
				},650);
			}
		}).delegate('.profile','click mouseover mouseout',function(event){
	        if (event.type == 'click') {
	            $current_index = $(this).children(1).attr('href');                
		
	            $current = $(this);
	            $current_link = $(this).children(1).attr('href');
		        
	            $(".profile",$container).not(this).stop().animate({
	                opacity: 0.7
	            }, 250);
		        
	            var $elem = $('<div class="selected-profile"></div>');
	            
	            if($previous == false){   
	                                                         
	                $elem.load($current_link + ' #author-box', function(){
	                    $prev_index = $current_index;
	                    $previous = $current.parent().after($elem.addClass('selected-'+($current.index()+0)));
	                    $elem.slideDown(500,function(){
	                    	$container.trigger('checkScrollPos');
	                    });
	                });
	               
	            } else {
	                 
	                $("#team-profiles").find($(".selected-profile")).slideUp(400,function(){
	                    if($prev_index != $current_index){ 
	                        $container.find($(".selected-profile")).remove();
	                                 
	                        $elem.load($current_link + ' #author-box', function(){
	                            $prev_index = $current_index;
	                            $previous = $current.parent().after($elem.addClass('selected-'+($current.index()+0)));
	                            $elem.slideDown(400,function(){
	                            	$container.trigger('checkScrollPos');
	                            });
	                        });                   
	                    } else {
	                    	$prev_index = '';
	                    
	                        $(".profile",$container).not(this).stop().animate({
	                            opacity: 1
	                        }, 250);
	                    }
	                }); 
	                
	            }                       
		        
	            return false;    	
	        }
	    	
	        if (event.type == 'mouseover') {
	            if($current != false){
	                $(this).stop().animate({
	                    opacity: 1.0
	                }, 300); 
	            }
	        }
	    	
	        if (event.type == 'mouseout') {
	            if($current != false){
	                $(this).stop().not($current).animate({
	                    opacity: 0.7
	                }, 300); 
	            }
	        }
	    });
		
	});
}


$(function(){
    // Input placeholders
    $('.input-placeholder').inputPlaceholder();
    
    // Prevent empty search forms been submitted
    $('form').each(function(){
        var $form = $(this),
        $search = $('input[name=s]',$form);
        			
        if ($search.length) {
            $form.submit(function(){
                if ($search.val() == '') {
                    $('.search-warning',$form).fadeIn().delay(1200).fadeOut();
					
                    return false;
                }
            });
        }
    });
    
    // Footer Twitter feed
    $('#tweets-footer').loadFooterTweets();
    
	// Author Twitter feed
    $('#tweets-author').loadAuthorTweets();
	
	// Team profile and images
    $("#team-profiles").teamProfiles();
    $('.profile-image-container').each(function(){
        var $link = $(this),
	        $img = $link.find('img'),
	        src = $img.attr('src');
        
        $link.css('background-image','url('+src+')');
        $img.remove();
    });
    
	// Search form submit validation
    $('.header-searchform #searchsubmit').click(function(){
        if ($('.header-searchform input[name=s]').val() == $('.header-searchform input[name=s]').attr('data-placeholder')) {
            $('.header-searchform .search-warning').fadeIn().delay(800).fadeOut();
			
            return false;
        }
    });
    
    // Archive list
    if (!$.browser.msie || parseInt($.browser.version,10) >= 8) {
	    $('li.widget_archive>ul').hideArchive();
	}
    
    // Style classes
    $('#footer #footer-columns .column').each(function(){
    	$(this).find('h2:eq(0)').addClass('first-heading');
    });
    
    $(document).on('click','a[href^="#"]',function(){
    	var $target = $(this.hash),
    		pos = $target.offset().top-40;
    		
    	$('html,body').stop().animate({
    		scrollTop : pos
    	},800);
    });
    
    if ($.browser.msie && parseInt($.browser.version,10)<7) {
    	$('#menu-main .menu-item.nav-lang').hover(function(){
    		$(this).addClass('menu-item-hover');
    	},function(){
    		$(this).removeClass('menu-item-hover');
    	});
    }
    
    var homeUrl = $('#header a.logo')[0].href,
    	preloadImages = [homeUrl+'wp-content/themes/viadeo-blogs/assets/images/profile-selected-top.png'],
    	imgArr = [];
    	
    for (var i = 0, l = preloadImages.length; i < l; i++) {
    	var img = new Image();
		img.src = preloadImages[i];
		imgArr[i] = img;
    }
});
