jQuery(document).ready(function($) {
    /**
     * Twitter feed code
     */
    var username = 'thegadlesgroup';
	var count = 1;
	
    $.getJSON('http://twitter.com/status/user_timeline/'+ username +'.json?count='+ count +'&callback=?', function(data) {
        $('div.tweets li').remove();
        
        for (i=0; i<count; i++) {
            var text = data[i].text;
            var timestamp = data[i].created_at;
            $('div.tweets ul').append('<li><p>' + replaceURLWithHTMLLinks(text) + '</p><span class="tweetTime">' + relativeTime(timestamp) + '</span></li>');
        }
    });
    
    
    /**
     * Sidebar accordion code
     */
    $('aside h5 a').toggle(function() {
        $(this).addClass('collapsed');
        $(this).parent('h5').next('div').hide();
        return false;
    }, function() {
        $(this).removeClass('collapsed');
        $(this).parent('h5').next('div').show();
        return false;
    });
    
    
    /**
     * Slideshow code
     */
    $('.slideshow').colorbox({
        photo: true,
        maxHeight: '60%',
        maxWidth: '60%',
        slideshow: true,
        slideshowSpeed: 6000,
        opacity: 0.8
    });
    
    $('.view-slideshow').click(function() {
        $(this).parents('.content').next('.slideshow-slides').find('.slideshow:first').trigger('click');
        return false;
    });
    
    
    /**
     * Homepage slideshow code
     */
    $('#banner-slideshow #image').cycle({
        fx: 'fade',
        timeout: 10000,
        speed: 500,
        pager: '#banner-pager',
        pagerAnchorBuilder: function(idx) {
            return '<a href="#"></a>';
        },
        before: function(curr, next, opts, flag) {
            var nextIndex = $('#banner-slideshow img').index(next);
            $('#banner-bar ul').cycle(nextIndex);
        },
        cleartypeNoBg: $.browser.msie ? true : false
        
    });
    
    $('#banner-bar ul').cycle({
        fx: 'scrollDown',
        timeout: 0,
        speed: 500,
        containerResize: 0
    });
    
    
    /**
     * Homepage videos code
     */
    $('#more-videos li a').click(function() {
        if (!$(this).hasClass('.current')) {
            $('#more-videos li').removeClass('current');
            $(this).parent('li').addClass('current');
            $('#featured-video').attr('src', $(this).attr('href'));
        }
        return false;
    })
    
    
    /**
     * Homepage team slideshow code
     */
    $('#team ul').cycle({
        slideExpr: 'li',
        timeout: 8000,
        fx: 'scrollHorz',
        pager: '#team .widget-pager',
        pagerAnchorBuilder: function(idx) {
            return '<a href="#">' + (idx + 1) + '</a>';
        }
    });
    
    
    /**
     * When user changes sort order, submit form
     */
    $('#sort-by').change(function() {
        $(this).parents('form').submit();
    });
    
    
    /**
     * When user focuses on input field in listing form
     */
    $('#listing-contact-form .text').focus(function() {
        $(this).addClass('focused');
    }).blur(function() {
        $(this).removeClass('focused');
    });
    
    
    /**
     * Infield labels
     */
    $('form.box-form label').inFieldLabels();
    
    
    /**
     * Fix footer
     */
    $('footer nav a:first').addClass('first');
    
    
    /**
     * Fix nav on-state for listing pages
     */
    if (window.location.href.indexOf('/listing/') >= 0) {
        $('#menu-item-72').addClass('current_page_item');
    }
    
    
    /**
     * Video lightbox
     */
    $('.youtube-video').colorbox({
        iframe: true,
        width: 640,
        height: 480
    });
    
    init_google($);
});

jQuery(document).unload(GUnload);


/**
 * Google maps code
 */
var g_bounds = new GLatLngBounds();;
var g_map = '';
var g_geocoder = new GClientGeocoder();;
var g_flag = new GIcon(G_DEFAULT_ICON);
var g_markers = [];

function init_google($) {
    if ($('#map-canvas').length == 0) {
        return false;
    }
    
    g_map = new GMap2($('#map-canvas').get(0));
    
    $('.listing-address').each(function(index) {
        var address = $(this).attr('data-address');
        
        g_geocoder.getLatLng(address, function(point) {
            if (!point) {
                // do nothing
            } else {
                var marker = new GMarker(point, g_flag);
                g_map.addOverlay(marker);
                g_bounds.extend(marker.getLatLng());
                g_map.setCenter(g_bounds.getCenter(), g_map.getBoundsZoomLevel(g_bounds));
                
                GEvent.addListener(marker, 'click', function() {
                    var html = '<img class="gmap-thumb" width="110" src="http://media.mlspin.com/photo.aspx?mls=' + $('.details:eq(' + index + ')').attr('data-mls-num') + '&n=0" />' +
                               '<p style="float:left; width:150px"><strong>' + $('.details:eq(' + index + ')').attr('data-price') + '</strong><br />' +
                               $('.details:eq(' + index + ')').attr('data-address') + '<br />' +
                               '# beds: ' + $('.details:eq(' + index + ')').attr('data-num-beds') + '<br />' +
                               '# baths: '+ $('.details:eq(' + index + ')').attr('data-num-baths') + '<br />' +
                               '<a href="listing/' + $('.details:eq(' + index + ')').attr('data-mls-num') + '.php">Details</a></p>';
                    
                    marker.openInfoWindowHtml(html);
                });
            }
        });
    });
    
    
}

function relativeTime(timestamp)
{
	var now = new Date();
	var dparts = timestamp.split(' ');
	var tparts = dparts[3].split(':');
	var then = new Date(dparts[1] +' '+ ' '+ dparts[2] +', '+ dparts[5] +' '+ tparts[0] +':'+ tparts[1] + ':'+ tparts[2]);
	var diff = (now.getTime() + (1000*60*60*4)) - then.getTime();    
	var timeDiff = getTimeDiffDescription(diff, 'day', 86400000);
	
	if (false === timeDiff) {
		timeDiff = getTimeDiffDescription(diff, 'hour', 3600000);
		if (false === timeDiff) {
			timeDiff = getTimeDiffDescription(diff, 'minute', 60000);
			if (false === timeDiff) {
				timeDiff = getTimeDiffDescription(diff, 'second', 60);
				if (false === timeDiff) {
					timeDiff = 'just now';
				}
			}
		}
	}
 
	return timeDiff; 
}


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


function getTimeDiffDescription(diff, unit, timeDivisor)
{ 
	var unitAmount = parseInt(diff / timeDivisor);
	if (unitAmount > 0) {
		return unitAmount + ' ' + unit + (unitAmount == 1 ? '': 's') + ' ago';
	} else if (unitAmount < 0) {
		return 'in ' + Math.abs(unitAmount) + ' ' + unit + (unitAmount == 1 ? '' : 's');
	} else {
		return false;
	}
}

jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
    phone_number = phone_number.replace(/\s+/g, ""); 
	return this.optional(element) || phone_number.length == 12 && phone_number.match(/([1-9]){3}-([0-9]){3}-([0-9]){4}/);
}, "Please specify a valid phone number i.e xxx-xxx-xxxx");
