(function ($, window, document) {
    var settings,
        loc,
        getIpLocation = function () {
            $.ajax({
                url: settings.controllerBase + 'user/get_ip_location',
                type: 'POST'
            }).success(function (data) {
                loc = {
                    lat: data.lat,
                    long: data.long
                };
            });
        };

    $(document).ready(function () {
        settings = $.parseJSON($('#page-settings').text());
        /*
        if (typeof settings.lat === 'undefined') {
            if (geo_position_js.init({ maximumAge: 60 * 60 * 1000 })) {
                geo_position_js.getCurrentPosition(
                    function (p) {
                        loc = {
                            lat: p.coords.latitude,
                            long: p.coords.longitude
                        };
                        $.ajax({
                            url: settings.controllerBase + 'user/set_location',
                            data: loc,
                            type: 'POST'
                        });
                    },
                    function () {
                        getIpLocation();
                    }
                
                );
            } else {
                getIpLocation();
            }

        }
        */

        /*JCROP*/
        /*
        $('img#thumbnail').load(function(){
            $('img#thumbnail').Jcrop({
                aspectRatio: 1,
                onChange: preview,
                onSelect: preview,
                setSelect: [0,0,100,100],
                minSize: [100,100]
            });
        });
        */

        /*REMOVE BUTTON*/
        $('.remove-photo').live('click',function(){
            var photoID = $(this).attr('id');
            photoID = photoID.replace('remove-photo-','');
            $.post(settings.controllerBase + 'photo/remove',
                   {'photoID' : photoID},
                   function(data){
                       if (data.result)
                       {
                           $('img#photo-'+photoID).parents('div.thumb').first().remove();
                       }
                    }, 'json');
        });
        /*END REMOVE BUTTON*/
        
        if (typeof listMap === 'object')
        {
            var center = new google.maps.LatLng(listMap.avg_lat, listMap.avg_lon);
            var listGMap = new google.maps.Map(document.getElementById(listMap.divId),
                                          {
                                              zoom : listMap.zoom,
                                              center : center,
                                              mapTypeId : google.maps.MapTypeId.ROADMAP
                                          });
            for (placeId in listMap.points)
            {
                listMap.points[placeId].marker = new google.maps.Marker({
                    position : new google.maps.LatLng(listMap.points[placeId].latitude,
                                                      listMap.points[placeId].longitude),
                    map : listGMap,
                    title : listMap.points[placeId].place_name
                });
                /* Commenting out the infowindows
                listMap.points[placeId].infoWindow = new google.maps.InfoWindow({
                    content : '<div class="place-info-window">' +
                              listMap.points[placeId].name +
                              '<br />' +
                              listMap.points[placeId].address +
                              '</div>'
                });

                google.maps.event.addListener(listMap.points[placeId].marker, 'click', function() {
                    listMap.points[placeId].infoWindow.open(listGMap,listMap.points[placeId].marker);
                });
                */
            }
        }
        $('#search_place, #search_local').keypress(function (e) {
            if (e.which === 13) {
                e.preventDefault();
                if ($(this).val()) {
                    $(this.form).submit();
                }
            }
        });

        $('.fancybox-trigger').fancybox({
            'titlePosition': 'inside',
            'transitionIn': 'none',
            'transitionOut': 'none',
            'width': '500'
        });

        $('.fancybox-form').live('submit',function(e){
            e.preventDefault();
            $(this).ajaxSubmit({
                success:function(data){
                    $.fancybox({
                        'titlePosition':'inside',
                        'transitionIn':'none',
                        'transitionOut':'none',
                        'width':'500',
                        onComplete: function()
                        {
                            if (typeof(window.initJcrop) == 'function')
                            {
                                $('#thumbnail').one('load', initJcrop).each(function(){
                                    if (this.complete) $(this).load();
                                });
                            }
                        },
                        'content':data
                    });
                }
            });
            return false;
        });

		$('.fancybox-learnmore').fancybox({
		    'titlePosition'		: 'inside',
			'transitionIn'		: 'none',
			'transitionOut'		: 'none',
			'width'             :  600,
			'height'            :  520,
			'autoDimensions'    :  false,
			'autoScale'			:  false
			});

        $('.overlay-close').live('click',function(){
            $.fancybox.close();
        });

        $('.fancybox-edit-note').fancybox({
            onStart: function (anchor, obj) {
                $('#editnote').find(':input[name=user_place_id]').val(
                    $(anchor).closest('li').data('user-place-id')
                );
            }
        });
		
		$(".next").click(function(){
	        console.log('apple');
	        $(this).closest('.learnmore').hide();
	        $(this).closest('.learnmore').next().show();
	    });
	    $(".prev").click(function(){
	        $(this).closest('.learnmore').hide();
	        $(this).closest('.learnmore').prev().show();
	    });
        /*

        $('body').append('<div id="fb-root"></div>');

        $.getScript(document.location.protocol +
            '//connect.facebook.net/en_US/all.js');
        */
        get_blog_posts = function()
        {
            $.get(settings.controllerBase + 'rss/read/blog', {}, function(data){
                if (data.html)
                {
                    $('div#blog-posts').html(data.html);
                }
            });
        }
        if ($('#blog-posts').length !== 0)
        {
            get_blog_posts();
        }

        get_twitter_posts = function()
        {
            $.get(settings.controllerBase + 'rss/read/twitter', {}, function(data){
                if (data.html)
                {
                    $('div#twitter-posts').html(data.html);
                }
            });
        }
        if ($('#twitter-posts').length !==0)
        {
            get_twitter_posts();
        }
    });

    window.fbAsyncInit = function () {
        FB.init({
            appId: settings.appId,
            cookie: true,
            status: true,
            xfbml: true
        });

        FB.getLoginStatus(function (response) {
            if (response.status === 'connected') {
                $('body').addClass('logged-in');
                console.log(response);
            }
        });

        FB.Event.subscribe('auth.login', function (response) {
            window.location.reload();
        });

        FB.Event.subscribe('auth.logout', function (response) {
            window.location.reload();
        });
    };

    toggle_follow = function(followLink, userID)
    {
        $.post(settings.controllerBase + 'user/ajax_toggle_follow/' + userID, {"user_id":userID}, function(data){
            if (data.follow_status == 'following')
            {
                $(followLink).html('remove from friends');
            }
            else if (data.follow_status = 'not following')
            {
                $(followLink).html('add to friends');
            }
            else
            {
                //error out
            }
        });
    }
	$(document).ready(function () {
		$('.tooltip-trigger').tooltip({
			offset:[10,0],
			effect: 'slide',
			events: { widget: 'click, '}
		}).dynamic({ bottom: { direction: 'down', bounce: true } });
	
		$('.close-tooltip').click(function(){
			$(this).parent().prev().tooltip().hide();
		});


		$('.close-welcome').click(function(){
			$(this).parent().slideUp();
		});
	});
	
	$('[placeholder]').blur(function() {
		var input = $(this);
		if (input.val() != input.attr('placeholder')) {
			input.addClass('has-content');
		}
		else{
			input.removeClass('has-content');
		}
	});
	
	$('input').blur(function() {
		var input = $(this);
			if(input.attr('type')=='text'|| input.attr('type')=='password'|| input.attr('type')=='email' || input.attr('type')=='tel' || input.attr('type')=='search'){
			if (input.val() != input.attr('placeholder')) {
				input.addClass('has-content');
			}
			else{
				input.removeClass('has-content');
			}
		}
	});
	$('textarea').blur(function() {
		var input = $(this);
		if (input.val() != input.attr('placeholder')) {
			input.addClass('has-content');
		}
		else{
			input.removeClass('has-content');
		}
	});
	
	if(!Modernizr.input.placeholder){

	$('[placeholder]').focus(function() {
	  var input = $(this);
	  if (input.val() == input.attr('placeholder')) {
		input.val('');
		input.removeClass('placeholder');
	  }
	}).blur(function() {
	  var input = $(this);
	  if (input.val() == '' || input.val() == input.attr('placeholder')) {
		input.addClass('placeholder');
		input.val(input.attr('placeholder'));
	  }
	}).blur();
	$('[placeholder]').parents('form').submit(function() {
	  $(this).find('[placeholder]').each(function() {
		var input = $(this);
		if (input.val() == input.attr('placeholder')) {
		  input.val('');
		}
	  })
	});

}
}(this.jQuery, this, this.document));

