var stickFeedURL = 'http://blog.credera.com/feed/stickyfeed';

$(function () {
    SP.SOD.executeFunc('sp.js', 'SP.ClientContext.get_current', Credera.executeAfterClientObjectModelLoaded ());
    Credera.populateNewsDivs();
    Credera.initKenBurnsEffect();
});


var Credera = Credera = Credera || {};

Credera.executeAfterClientObjectModelLoaded = function(){
	Credera.getHighlightedStories();
	Credera.getClientLogos(6);
};

Credera.populateNewsDivs = function () {
    // News Feed
    var newsFeedURL = stickFeedURL;
    var numberOfNewsStories = 3;
    $.jGFeed(newsFeedURL, function (feeds) {
        if (!feeds) { return false; }

        for (var i = 0; i < feeds.entries.length; i++) {  
            var newsFeedContent = "";
            var entry = feeds.entries[i];

            var title = entry.title;
            var content = entry.contentSnippet;
            var link = entry.link;
            var publishedDate = new Date(entry.publishedDate);

            newsFeedContent = "<h3>" + title + "</h3><p>" + content + "</p><p><a href='" + link + "'><img src='/Style Library/Credera/img/button_read-more.png' alt='Read More'></a></p>";
            $("#latestnews-" + i).html(newsFeedContent);
        }

    }, numberOfNewsStories);
};

Credera.getHighlightedStories = function () {
    var clientContext = new SP.ClientContext.get_current();
    var myList = clientContext.get_site().get_rootWeb().get_lists().getByTitle('Highlighted Stories');
    var query = new SP.CamlQuery();
    query.set_viewXml('<View><Query><OrderBy><FieldRef Name="Sort_x0020_Order" Ascending="TRUE" /></OrderBy></Query></View>');
    var collListItems = myList.getItems(query);
    //clientContext.load(collListItems, 'Include(StartDate,EndDate1,Title,SubTitle,FileRef,URL)'); 
    clientContext.load(collListItems);
    
    // execute the actual query against the server, and pass the objects we have created to either a success or failure function 
    clientContext.executeQueryAsync( 
    	function(){    
		    var listItemEnumerator = collListItems.getEnumerator();
		    var itemCount = collListItems.get_count();
		    var currentIndex = 0;
		
		    // loop through the list items 
		    while (listItemEnumerator.moveNext()) {
		        if (currentIndex > 2)
		            break;
		
		        var oListItem = listItemEnumerator.get_current();
		
		        var image = '';
		        var link = '';
		        var imageLink = '';
		        var title = '';
		        var subtitle = '';
		        var startDate = null;
		        var endDate = null;
		        var currentDate = new Date();
		        var imageHeight = 0;
		
		        startDate = oListItem.get_item('StartDate');
		
		        if (currentDate >= startDate) {
		            endDate = oListItem.get_item('EndDate1');
		
		            if (endDate == null || currentDate <= endDate) {
		                title = oListItem.get_item('Title');
		                subtitle = oListItem.get_item('SubTitle');
		                image = oListItem.get_item('FileRef');
		                if (oListItem.get_item('URL') != null)
		                    link = oListItem.get_item('URL').get_url();
		                 
		                if (oListItem.get_item('Image_x0020_URL') != null)
		                	imageLink = oListItem.get_item('Image_x0020_URL').get_url()
		                    
		                imageHeight = oListItem.get_item('ImageHeight');

						clientLogosHTML = "<div class='highlightedStory'>";
						if (imageLink != '')
						{
							clientLogosHTML += "<a href='" + imageLink + "' target='_blank'><div class='shadow' id='highlightedstory-img-" + currentIndex + "'></div></a>";
						}
						else
						{
							clientLogosHTML += "<div class='shadow' id='highlightedstory-img-" + currentIndex + "'></div>";
						}
						
						if (link != '')
						{
							clientLogosHTML += "<a href='" + link + "'><div><h2>" + title + "</h2><br><div class='home_feature_tagline'>" + subtitle + "</div></div></a>";
						}
						else
						{
							clientLogosHTML += "<h2>" + title + "</h2><br><div class='home_feature_tagline'>" + subtitle + "</div>";
						}
						clientLogosHTML += "</div>";
		                
		                $('#highlightedstory-' + currentIndex).html(clientLogosHTML);

						var imagePath = "'" + image + "'";
		                $('#highlightedstory-img-' + currentIndex).css('background', 'url(' + imagePath + ')');
		                $('#highlightedstory-img-' + currentIndex).css('height', imageHeight + 'px');
		
		                currentIndex++;
		            }
		        }
		    }
			$('.highlightedStory a[href*="youtube.com"][target="_blank"]').click(function() {
				$.fancybox({
						'padding'		: 0,
						'autoScale'		: false,
						'title'			: this.title,
						'href'			: this.href.replace(new RegExp("watch\\?v=", "i"), 'v/') + "&fs=1",
						'type'			: 'swf',
						'swf'			: {'wmode' : 'transparent', 'allowfullscreen' : 'true'}
					});
		
				return false;
			});
			
			$('.highlightedStory a[href*="vimeo.com"][target="_blank"]').click(function() {
				$.fancybox({
						'padding'		: 0,
						'autoScale'		: false,
						'title'			: this.title,
						'href'			: this.href.replace(new RegExp("([0-9])","i"),'moogaloop.swf?clip_id=$1'),
						'type'			: 'swf',
						'swf'			: {'wmode' : 'transparent', 'allowfullscreen' : 'true'}
					});
		
				return false;
			});
		},
	function(){ /* Do something if we can */ });
};



var kenBurnsRunning = new Array();

Credera.initKenBurnsEffect = function(){
	kenBurnsRunning[0] = false;
	kenBurnsRunning[1] = false;
};

Credera.startKenBurnsEffect = function(index, imagePath, imageAlt) {

    if (kenBurnsRunning[index] == false) {
        kenBurnsRunning[index] = true;
              
		$('#highlightedstory-img-' + index).crossSlide({
            fade: 1,
            variant: true,
            loop: 1
        }, [
          {
              src: imagePath,
              alt: imageAlt,
              from: '100% 100% 1.0x',
              to: '100% 100% 1.15x',
              time: 5
          },
          {
              src: imagePath,
              alt: imageAlt,
              from: '100% 100% 1.15x',
              to: '100% 100% 1.0x',
              time: 5
          }
        ], function (idx, img, idxOut, imgOut) {
            if (idxOut != undefined) {
               // $('#highlightedstory-img-' + index).crossSlidePause();
               // kenBurnsRunning[index] = false;
            }
        });
    }
};


   
    
 Credera.getClientLogos = function(numberOfLogos) {
    var clientContext = new SP.ClientContext.get_current();
    var myList = clientContext.get_site().get_rootWeb().get_lists().getByTitle('Client Logos');
    var query = new SP.CamlQuery();
    query.set_viewXml('<View Scope="RecursiveAll"><Query/></View>');
    var collListItems = myList.getItems(query);
    clientContext.load(collListItems, 'Include(Title,FileRef,URL)'); 


    // execute the actual query against the server, and pass the objects we have created to either a success or failure function 
    clientContext.executeQueryAsync(
    	function() {
		    var listItemEnumerator = collListItems.getEnumerator(); 
		    var itemCount = collListItems.get_count();
		    
		    var currentIndex = 1;
		    var maxLogos = numberOfLogos;
		    var currentLogoCount = 0;
		
		    var clientLogosHTML = "";
		    var logoIndexArray = new Array();
		
		    if (itemCount > maxLogos) {
		        while (currentLogoCount < maxLogos) {
		            var randomIndex = Credera.randomFromTo(1, itemCount);
		
		            if ($.inArray(randomIndex, logoIndexArray) == -1) {
		                logoIndexArray[currentLogoCount] = randomIndex;
		                currentLogoCount++;
		            }
		        }
		    }            
		
		    // loop through the list items 
		    while (listItemEnumerator.moveNext()) {
		        var oListItem = listItemEnumerator.get_current();
		
		        var image = '';
		        var link = '';
		        var title = '';
		        
		        if ($.inArray(currentIndex, logoIndexArray) > -1 || itemCount <= maxLogos) {
		            title = oListItem.get_item('Title');
		            image = oListItem.get_item('FileRef');
		            if (oListItem.get_item('URL') != null) {
		                link = oListItem.get_item('URL').get_url();
		                clientLogosHTML += "<li><a href='" + link + "'><img src='" + image + "' alt='" + title + "'></a></li>";
		            }
		            else {
		                clientLogosHTML += "<li><img src='" + image + "' alt='" + title + "'></li>";
		            }
		        }
		        currentIndex++;
		    }
		
		    $('#featured_clients ul').html(clientLogosHTML);
		},
		function(sender, args) { /* Do something if possible */ });
};
        
Credera.randomFromTo = function(from, to) {
    return Math.floor(Math.random() * (to - from + 1) + from);
};
