//var BLOG_FEEDS		= ['http://flamingolondon.com/feed/', 'http://www.flamingo-singapore.com/feed/', 'http://www.flamingoshanghai.com/blog/feed/', 'http://flamingonewyork.com/feed/'],
var BLOG_FEEDS		= ['http://flamingolondon.com/custom.rss', 'http://flamingosingapore.com/custom.rss', 'http://flamingonewyork.com/custom.rss', 'http://www.flamingotokyo.com/custom.rss.php', 'http://www.flamingoshanghai.com/blog/custom.rss.php'],
	BLOG_NAMES		= ['LONDON', 'SINGAPORE', 'NEW YORK', 'TOKYO', 'SHANGHAI'],
	MONTH_NAMES		= ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
	READ_ON_BLOG	= 'READ THE ARTICLE ON THE {NAME} BLOG';

var numLoaded		= 0,
	entriesObj		= {},
	entriesToLoad	= 1,
	allEntries		= [],
	postCount		= 0;

google.load("feeds", "1");

isLoadingRss		= true;

function initializeFeeds() {
	
	//set feed url
	var baseUrl		= 'http://sennep.dreamhosters.com/clients/flamingo/feedtest/';
	//var baseUrl		= 'http://ketchup.sennep.com/flamingo/build/';
	
	var date		= new Date();
	var uniqueNum	= date.getTime(); //avoid loading cached rss
	/*for (var j=0; j<BLOG_FEEDS.length; j++) {
		//if (j < 4) BLOG_FEEDS[j]	= BLOG_FEEDS[j] + '?' + uniqueNum;
		//else BLOG_FEEDS[j]	= baseUrl + BLOG_FEEDS[j] + '?' + uniqueNum;
		
		//BLOG_FEEDS[j] + '?' + uniqueNum; //uncomment to make load not cached version
	}*/
	
	if ($$('body').hasClass('home')[0]) entriesToLoad	= 4;
	
	for (var i=0; i<BLOG_FEEDS.length; i++) {
		
		loadFeed(BLOG_FEEDS[i], BLOG_NAMES[i]);
		
	}
}
google.setOnLoadCallback(initializeFeeds);

function allBlogsLoaded() {
	//TODO: get images
	
	var i	= 0;
	
	if ($$('body').hasClass('home')[0]) {
		//for (var e in allEntries) if (allEntries.hasOwnProperty(e)) log('allEntries[' + e + '].title = ' + allEntries[e].publishedDate);
		sortEntries();
		//for (var e in allEntries) if (allEntries.hasOwnProperty(e)) log('allEntries[' + e + '].title = ' + allEntries[e].publishedDate);
	}
	
	//blogsummary on homepage
	$$('.blogsummary').each(function(el) {
	
		if (i < allEntries.length) {
		
			var entry		= allEntries[i],
				imgUrl		= entry.mediaGroups[0].contents[0].url,
				useImage	= false;
				/*date		= new Date(entry.publishedDate),
				day			= date.getDate(),
				month		= date.getMonth(),
				year		= date.getFullYear(),
				monthString = MONTH_NAMES[month],
				html		= '',*/
				
			if (imgUrl) {
				var img 	= new Image();
				img.onload	= function() {
					var minRatio	= 1.48,
						maxRatio	= 1.51,
						ratio		= this.width / this.height;
					
					if (ratio >= minRatio && ratio <= maxRatio) useImage = true;
					
					setHomepageBlog(useImage, entry, el);
				};
				img.src		= imgUrl;
			} else {
				//useImage	= false;
				setHomepageBlog(useImage, entry, el);
			}
		}
			
		i++;
		
	});
	
	//blogentry on blogs page
	$$('.blogentry').each(function(el) {
	
		var id		= el.getParent().get('id').toUpperCase();
		if (id == 'NEWYORK') id = 'NEW YORK';
		var entry		= entriesObj[id][0];
		
		if (entry) {
			var imgUrl		= entry.mediaGroups[0].contents[0].url,
				useImage	= false;
			
			if (imgUrl) {
				var img 	= new Image();
				img.onload	= function() {
					/*var minRatio	= 1.48,
						maxRatio	= 1.51,
						ratio		= this.width / this.height;*/
					
					//if (ratio >= minRatio && ratio <= maxRatio) useImage = true;
					var minWidth	= 719;
					if (this.width >= minWidth) useImage = true;
					
					setBlogpageBlog(useImage, entry, el, id);
				};
				img.src		= imgUrl;
			} else {
				//useImage	= false;
				setBlogpageBlog(useImage, entry, el, id);
			}
		}
	});
	
	
	//if ($$('body').hasClass('home')[0]) setupImageHovers();
	
	//setupSubNav();
	
	var blogContainers	= $$('.blogentry')
	
	if (isHome) {
		loadFlickr();
		loadVimeo();
		blogContainers	= $$('.blogsummary');
	}
	
	//fade in content
	blogContainers.setStyle('opacity', 1);
	
	/*if (isIE) {
		//alert('bajs');
		blogContainers.setStyle('opacity', 0);
		blogContainers.set('tween', {
			duration: 2000
		});
		blogContainers.tween('opacity', 1);
	} else {
		blogContainers.setStyle('opacity', 1);
	}*/
}

function setHomepageBlog(_useImage, _entry, _el) {
	var entry		= _entry,
		el			= _el,
		imgUrl		= entry.mediaGroups[0].contents[0].url,
		date		= new Date(entry.publishedDate),
		day			= date.getDate(),
		month		= date.getMonth(),
		year		= date.getFullYear(),
		monthString = MONTH_NAMES[month],
		html		= '',
		useImage	= false;
	
	//if (!_useImage) {
	if (!imgUrl) {
		imgUrl	= 'img/placeholder_' + entry.name.toLowerCase() + '.jpg';
	}
	
	html	= '<p class="category">' + entry.name + ' BLOG</p>' +
				'<h2><a target="_blank" href="' + entry.link + '">' + entry.title + '</a></h2>' +
				'<a target="_blank" href="' + entry.link + '"><div class="blogSummareImgCont"><img width="220" src="' + imgUrl + '" alt="' + entry.title + '" /></div></a>' +
				'<time pubdate datetime="' + year + '-' + (month + 1) + '-' + day + '">' + day + ' ' + monthString + ' ' + year + '</time>';
	
	el.set('html', html);
	
	//IE is not doing hover effect on links from blogs & twitter
	if (isIE) {
		el.getChildren('h2 a').addEvent('mouseover', function() {
			this.setStyle('color', DEFAULT_COLOR);
		});
		el.getChildren('h2 a').addEvent('mouseout', function() {
			this.setStyle('color', '#444');
		});
	}
	
	postCount++;
	if (postCount == 4) {
		//log('do hovers');
		if ($$('body').hasClass('home')[0]) setupImageHovers();
		setupSubNav();
	}
}

function setBlogpageBlog(_useImage, _entry, _el, _region) {
	var entry		= _entry,
		el			= _el,
		imgUrl		= entry.mediaGroups[0].contents[0].url,
		date		= new Date(entry.publishedDate),
		day			= date.getDate(),
		month		= date.getMonth(),
		year		= date.getFullYear(),
		monthString = MONTH_NAMES[month],
		html		= '';
	
	//if(_region == 'SHANGHAI') log(entry.content);
	
	entry.content	= entry.content.trim();
	entry.content	= entry.content.clean();
	entry.content	= entry.content.replace(/<[^\/>][^>]*><\/[^>]+>/gi, '');
	//entry.content	= entry.content.replace(/<[^\/>][^>]*> <\/[^>]+>/gi, ''); //this broke a shanghai post, might need this again in the future
	entry.content	= entry.content.replace(/<[^\/>][^>]*><\/[^>]+>/gi, ''); //do again in case replacement has created new emtpy tags (remove vimeo ifram foe example creates <p></p>)
	
	//if (_useImage) html	= '<img src="' + imgUrl + '" width="719" height="481" alt="' + entry.title + '" />';
	
	//if(_region == 'SHANGHAI') log(entry.content);
	
	if (isIpad) {
		html += '<h3 class="sectionTitle">Blog / ' + _region + '</h3>';
	}
	
	html	+= '<h2>' + entry.title + '</h2>';
	
	//temp
	if (_useImage) html	+= '<img src="' + imgUrl + '" width="719" alt="' + entry.title + '" />';
	
	html	+= entry.content +
				'<time pubdate datetime="' + year + '-' + (month + 1) + '-' + day + '">' + day + ' ' + monthString + ' ' + year + '</time>' +
				'<a class="iconLink readblog" target="_blank" href="' + entry.link + '">' + READ_ON_BLOG.replace('{NAME}', entry.name) + '</a>';
	
	el.set('html', html);
	
	if (isIE) {
		el.getChildren('p a').addEvent('mouseover', function() {
			this.setStyle('color', DEFAULT_COLOR);
		});
		el.getChildren('p a').addEvent('mouseout', function() {
			this.setStyle('color', '#c8c8c8');
		});
	}
	
	postCount++;
	if (postCount == 5) {
		if ($$('body').hasClass('home')[0]) setupImageHovers();
		else checkBottomMargin();
		setupSubNav();
	}
}

function sortEntries() {
	//log('sortEntries');
	allEntries.sort(function(a, b){
		var dateA	= new Date(a.publishedDate),
			dateB	= new Date(b.publishedDate);
			
		return dateB - dateA; //sort by date ascending
	});
}

function loadFeed(_url, _name) {
	log('loadFeed() _url = ' + _url);
	var Feed = {
		
		feed	: new google.feeds.Feed(_url),
		url		: _url,
		name	: _name,
		
		ini: function() {
			
			Feed.feed.setNumEntries(entriesToLoad);
			entriesObj[Feed.name]	= [];
			
			Feed.feed.load(function(result) {
				
				if (!result.error) {
					//log(result);
					for (var i = 0; i < result.feed.entries.length; i++) {
						var entry = result.feed.entries[i];
						
						entry['name']	= Feed.name;
						entriesObj[Feed.name].push(entry);
						allEntries.push(entry);
						//log('entriesObj[' + Feed.name + '] = ' + entriesObj[Feed.name]);
						
						//log(entry);
						
					}
					
					numLoaded++;
					if (numLoaded == BLOG_FEEDS.length) allBlogsLoaded();
				} else {
					traceAllPropertiesOf(result.error);
					log('BLOG LOADING ERROR');
					numLoaded++;
					if (numLoaded == BLOG_FEEDS.length) allBlogsLoaded();
				}
			});
		}
		
	}
	
	Feed.ini();
}


function traceAllPropertiesOf(_obj) {
	for (var p in _obj) if (_obj.hasOwnProperty(p)) log('_obj[' + p + '] = ' + _obj[p]);
}
