/*!
 * Branded Content
 * Requires: jQuery v1.8 or later
 */
(function( $ ) {

var sponsored_logo = "http://sap.summitmedia.com.ph/images/default/sponsored-content-image-no-logo.png";

  $.BrandedContent = function( options ) {

		//article settings
		var settings = $.extend( {
			flashboxAPI 		: '',
			newsFeedAPI			: '',
			sectionFeedAPI 		: '',
			selectedChannel		: 0,
			flashboxItem		: 'branded-flashbox',
			latestItem			: 'branded-latest',
			siteName			: 'pep',
			channel 			: '',
			flashboxAnimated	: true
		}, options);

		//flashbox
		if(settings.flashboxAPI!=""){
			
			$.ajax({

				type: "GET",
				
				url: settings.flashboxAPI,

			    success: function(response){
			    
			    	data = $.parseJSON(response);

			    	if(!data) { 
			    		$('.roundup-small-thumbails:last').removeClass("hidden"); 
			    		console.log("BOOM");
			    		return; 
			    	}

					var param = $.param(data.payload);

			        $('.roundup-small-thumbails:last').removeClass("hidden");

					$('.roundup-small-thumbails:last').find('.hover-photo, .hover-video').remove();

		        	$('.roundup-small-thumbails:last').find('a').attr('href', data.cf_redirect+'?'+param);
		        	$('.roundup-small-thumbails:last').find('img').attr('src', data.image);
		        	$('.roundup-small-thumbails:last').find('img').attr('alt', data.atitle);
		        	$('.roundup-small-thumbails:last').find('img').attr('data-original', data.image);

			        $('.roundup-small-thumbails:last').find('a').attr('href', data.cf_redirect+'?'+param);

			        $('.roundup-small-thumbails:last').find('.roundup-caption').html('<p><img src="http://sap.summitmedia.com.ph/images/default/sponsored-content-image-no-logo.png" /><br />'+data.atitle+'</p>');

			        $('.roundup-small-thumbails:last').find('.roundup-caption-xs').html('<p><img src="http://sap.summitmedia.com.ph/images/default/sponsored-content-image-no-logo.png" /><br />'
			       			+ data.atitle + '</p>'
			       			+ '<p class="ru article-timestamp"><span class="story-list-section">' + data.channelName.split("/")[0] + '</span> </p>');
					
			        $('.roundup-small-thumbails:last')
			        	.removeClass("hidden")
			        	.data('branded', 'flashbox')
			        	.data('branded_flashbox', '')
			        	.data('announcer', data);

			        attachHandlers('flashbox', $('.roundup-small-thumbails:last'));

			    },

			    error: function( jqXHR , textStatus ) {
			    	if(textStatus === 'timeout')
						console.log('Failed from timeout');         
			        else 
			        	console.log("Something went wrong with api url");

			        $('.roundup-small-thumbails:last').removeClass("hidden");
			    },

			    timeout: 5000

			});
		}


		//news feed
		if(settings.newsFeedAPI!=""){
			$.ajax({
				type: "GET",
				url: settings.newsFeedAPI,
			    success: function(response){
			    	dataRet = $.parseJSON(response);

			    	if(!dataRet){return;}

			    	$.each(dataRet, function (key, data) {
				    	slot = parseInt(data.slot) - 1;

				    	console.log( "SLOT :: " + data.slot );

				    	var param = $.param(data.payload);

						strData = '<hr class="clear-both">'+
								'<div class="row">' +
								'	<div class="">' +
								'		<figure class="just-in clear-left">' +
								'			<a href="' + data.cf_redirect + '?' + param + '">' +
								'				<img src="' + data.image + '" class="lazy roundup-images-small just-in-mobile-home" alt="' + data.stitle + '">' +
								'				<div class="just-in-layer"></div>' + 
								'			</a>' +
								'		</figure>' +
								'	</div>' +
								'		<a href="' + data.cf_redirect + '?' + param + '">' +
								'			<div class="article-details" style="">' +
								'				<p class="article-title">' + ( screen_width < 736 ? data.atitle : data.atitle) + '</p>' +
								'				<p class="article-timestamp"><span class="story-list-section">' + data.channelName.split("/")[0] + '</span> &bull; ' + data.publish + '</p>' +
												( data.isAggregate ? '<div class="brTextFeed"><a href="'+BASE_URL+'/'+data.aggrSlug+'" onclick="richSatClick('+data.trackLogo+',\'\')"><img src="'+data.brandLogo+'" /></a></div>' : '<div  class="brTextFeed"><img src="'+data.brandLogo+'" onerror="this.src=\'' + sponsored_logo + '\'" /></div><br />' ) +
								'				<p id="radiumone" class="pw-widget share-icons share-home hidden-small" pw:url="' + BASE_URL + (data.forwardUrl) + '" pw:twitter-via="PEPalerts" pw:title="' + data.atitle + '">'+
								'				<a class="pw-button-facebook pw-counter"></a>' +
								'				<a class="pw-button-twitter pw-counter"></a>' +
								'				</p>' +
								'			</div>' +
								'		</a>' +
								'</div>' ;


				        $(strData).insertBefore('.this-just-in-list .row:eq(' + slot + ')');
				        $('.this-just-in-list .row:eq(' + slot + ')').data('branded', 'home-latest').data('branded_latest', '').data('announcer', data);

			        	attachHandlers('home-latest', $('article:eq('+slot+') a.linkBrand'));
			        });
			    },

			    error: function( jqXHR , textStatus ) {
			    	if(textStatus === 'timeout')
						console.log('Failed from timeout');         
			        else 
			        	console.log("Something went wrong with api url");

			    },

			    timeout: 5000
			});
		}

		//section feed
		if( settings.sectionFeedAPI!="" ){
			$.ajax({
				type: "GET",
				url: settings.sectionFeedAPI,
			    success: function(response){
			    	dataRet = $.parseJSON(response);

			    	if(!dataRet){return;}

			    		$.each(dataRet, function (key, data) {

					    	slot = parseInt(data.slot) - 1;

					    	var param = $.param(data.payload);

					    	if(settings.selectedChannel==data.channel){

								strData = '<hr class="clear-both"><div class="row">' +
										'	<div class="">' +
										'		<figure class="news just-in clear-left" style="">' +
										'			<a href="' + data.cf_redirect + '?' + param + '">' +
										'				<img src="'+data.image+'" style="margin: 0;" class="roundup-images-small" alt="' + data.atitle + '">' +
										'				<div class="just-in-layer"></div>' + 
										'			</a>' +
										'		</figure>' +
										'	</div>' +
										'	<div class="news article-details" style="">' +
										'		<a href="' + data.cf_redirect + '?' + param + '">' + 
										'			<p class="news article-title hidden-small" style="">' + data.atitle + '</p>' +
										'			<p class="news article-title visible-small" style="">' + data.atitle + '</p>' +
										'			<p class="article-timestamp">' + data.publish + '</p>' +
										'		</a>' +
										(data.isAggregate ? '<div class="brTextFeed"><a href="'+PUBLIC_DOMAIN+'/'+data.aggrSlug+'" onclick="richSatClick('+data.trackLogo+',\'\')"><img src="'+data.brandLogo+'" /></a></div>' : '<div class="brTextFeed"><img src="'+data.brandLogo+'" /></div>') +
										'	</div>' +
										'		</div>' +
										'		</div>';


					    		attachHandlers('channel-latest', $('.latest .row:eq('+slot+') a.linkBrand'));

								$(strData).insertBefore('.latest .row:eq(' + slot + ')');

								$('.latest .row:eq('+slot+')').data('branded', 'channel-latest').data('branded_channel_latest', '').data('announcer', data);
					    	}
					    });




			    },

			    error: function( jqXHR , textStatus ) {
			    	if(textStatus === 'timeout')
						console.log('Failed from timeout');         
			        else 
			        	console.log("Something went wrong with api url");

			    },

			    timeout: 5000

			});
		}

		function attachHandlers(type, payload){

			switch(type){

				case 'flashbox':

				if(settings.flashboxAnimated){
					payload
						.on('sendImpression', payload.data(), sendImpression)
						.click(payload.data(), attachClick);
				}
				else
				{
					payload.click(payload.data(), attachClick);
					sendImpression({data : payload.data()});
				}

				break;

				case 'home-latest':
				case 'channel-latest':

					payload.click(payload.data(), attachClick);
					 sendImpression({data : payload.data()});

				break;

			}
		}

		function sendImpression(evt){

			console.log('sending impression..');

			data = evt.data;

			category = settings.siteName+' Branded Content '+data.announcer.atitle;
			medium = settings.selectedChannel+' '+data.branded+' impression';

			var req = {};

			req.type = "POST";

			req.error = function(){
				console.error('ERROR: cant cast api call to SAT server using link: \n'+data.announcer.impression+'\n\nsomething went wrong. try again')
			}
			req.success = function(){
				console.log('event sent to analytics server!');
			}

			req.url = data.announcer.impression;

			req.data = data.announcer.payload;

			$.ajax(req);

			$(this).off(evt);
			return false;
		}

		function attachClick(evt){

			evt.stopPropagation();

			data = evt.data;
			var url = $(evt.target).attr('href');

			category =settings.siteName+' Branded Content '+data.announcer.atitle;
			medium = settings.selectedChannel+' '+data.branded+' click';

			$(this).off(evt);
			//location = data.redirect;

			var req = {};

			req.async = false;

			req.type = "POST";
			req.success = function(){
				console.log('event sent to analytics server!');
			}

			req.error = function(){
				console.log('ERROR: cant cast api call to SAT server using link: \n'+data.announcer.impression+'\n\nsomething went wrong. try again')
			}

			req.url = data.announcer.redirect;

			req.data = {
				'others'		: {
					'section'				: data.announcer.channelName
				}
			};

			$.ajax(req).always(function(){
				// console.log('error')
				// location = data.announcer.url;
			});
		}

  	};

})( jQuery );
