(function($){

	$( document ).ready( function(){

		var onRequest = function( response ){
		
			if( 200 == response.meta.code ){
				var markUp = '';

				for( x in response.data ){

					var data = response.data[ x ],
						lowImg = data.images.low_resolution.url,
						standardImg = data.images.standard_resolution.url;

					if( 0 == x ){
						jQuery( '.wrap-instagram-section .instagram-title a' ).attr( 'href', '//instagram.com/' + data.user.username );
					}	
					
					markUp += '<a class="insta-img" rel="keon-insta" data-link="' + data.link +'" href="'+standardImg+'">\
									<img src="'+lowImg+'">\
								</a>'
					
				}
				
				$('.keon-instagram').append( markUp );

				jQuery(".insta-img").colorbox({
					rel         : 'keon-insta',
					maxWidth	: 800,
					maxHeight	: 600,
					onOpen      : function(){
						$( 'body' ).addClass( 'keon-colorbox-open' );
					},
					onClosed    : function(){
						$( 'body' ).removeClass( 'keon-colorbox-open' );
					},
					title: function(){
						return;
					  var url = $( this ).attr( 'data-link' );
					  return '<a href="' + url + '" target="_blank">' + INSTA.new_link_text + '</a>';
					}
				});

				$( '.keon-instagram' ).owlCarousel({
				    loop:true,
				    margin:2,
				    responsiveClass:true,
				    responsive:{
				        0:{
				            items:2,
				            nav:true
				        },
				        768:{
				            items:3,
				            nav:false
				        },
				        992:{
				            items:6,
				            nav:true,
				            loop:false
				        }
				    }
				});

				$( '.instagram-title' ).show();

			}else{

				$( '.keon-instagram-error' ).show().html( response.meta.error_message );
				$( '.instagram-title' ).hide();
			}
			
			jQuery( '.wrap-instagram-section' ).css( { opacity: 1 } );
		};

		var request = $.ajax({
			type        : 'GET',
			dataType    : 'jsonp',
			contentType : 'application/json',
			data        : {
				access_token : INSTA.access_token,
				count	     : INSTA.count
			},
			beforeSend : function(){
				jQuery( '.wrap-instagram-section' ).css( { opacity: 0 } );
			},
			url     : "https://api.instagram.com/v1/users/self/media/recent",
			success : onRequest
		});
	});

})( jQuery );