/* Copyright (c) 2011 mezz, Inc.  All Rights Reserved
*/
var mz_latestfeed = "http://l.mezz.com/m/v1/feed/latest";
var mz_userfeed = "http://l.mezz.com/m/v1/user/cards";
var mz_apikey;
var mz_username = null;
var mz_arrayIndex = 0;
var mz_limit;
var mz_radius;
var mz_donefn = null;
var mz_lat = 0;
var mz_lon = 0;
var mz_divid;
var mz_timeoutId = 0;
var mz_timestamp = 0;
var mz_firstTime = true;
var mz_search = null;
var mz_category = null;
var COL_WIDTH = 222;
var SIDE_MARGIN = 80;
var GUTTER = 22;
var mz_array;
var mz_clear = false;
var gmaps_image_url = "http://maps.googleapis.com/maps/api/staticmap?center={0},{1}&zoom=13&size=60x60&sensor=false";
var gmaps_link_url = "http://maps.google.com?q={0},{1}";
//	var gmaps_url = "http://maps.googleapis.com/maps/api/staticmap?center={0},{1}&zoom=13&size=75x75&sensor=false&markers=color:red%7Clabel:A%7C{0},{1}"
var mz_card_array = [];
var num_columns = 0;

/*
 * Entry point to load an animated feed:
 * apikey: Specify the API Key
 * lat: Latitude
 * lon: Longitude
 * radius: Radius of the data.
 * limit: # of items to load at a time.  Note that each will be still animated.
 * divid: Id of the div.  Make sure to specify it leading with #
 * interval: The interval specified in milliseconds.
 */
function feedcolumns(apikey, lat, lon, radius, limit, divid, donefn, search, category)
{
	mz_donefn = donefn;
	doInit(apikey, lat, lon, radius, limit, divid, null, search, category);
	loadLatest();
}

function userfeed(username, apikey, lat, lon, radius, limit, divid, donefn, search, category)
{
	mz_donefn = donefn;
	doInit(apikey, lat, lon, radius, limit, divid, username, search, category);
	loadUserFeed();
}

function doInit(apikey, lat, lon, radius, limit, divid, username, search, category)
{
	mz_apikey = apikey;
	mz_lat = +lat;  // + in front converts variable to numbers if they are strings.
	mz_lon = +lon;
	mz_radius = +radius;
	mz_limit = +limit;
	mz_divid = divid;
	mz_search = search;
	mz_category = category;
	
	if (!varIsEmpty(username)) mz_username = username;
	
	// Zero out timestamp for a fresh load.
	mz_timestamp = 0;
	mz_clear = true;
}

/*
 * Load the feed and then call addItem to animate.
 */
function loadLatest()
{
	var args = { "auth_userid": mz_apikey, 
			"latitude": mz_lat,
			"longitude": mz_lon,
			"limit": mz_limit
		};
	
	if (mz_timestamp > 0) args.timestamp = mz_timestamp;
	if (mz_radius > 0) args.radius = mz_radius;
	if (!varIsEmpty(mz_search)) args.keyword = mz_search;
	if (!varIsEmpty(mz_category)) args.category_name = mz_category;

	$.ajaxSetup({ 
        scriptCharset: "utf-8" 
	});
	
	$('#mz_loading_icon').show();
	
	$.get(mz_latestfeed, args, 
			function(data) {
				if (!varIsEmpty(data) && !varIsEmpty(data.results)) {
					addResults(data.results);
				} else {
					reportError();
				}
			}, 
			"jsonp")
		.error(function() { reportError(); });
}

/*
 * Load the user feed and then call addItem to animate.
 */
function loadUserFeed()
{
	var args = { "auth_userid": mz_apikey, 
			"username": mz_username,
			"limit": mz_limit
		};
	
	if (mz_timestamp > 0) args.timestamp = mz_timestamp;
	if (mz_radius > 0) args.radius = mz_radius;
	if (mz_search != null) args.keyword = mz_search;
	if (mz_category != null) args.category_name = mz_category;

	$.ajaxSetup({ 
        scriptCharset: "utf-8" 
	});
	
	$('#mz_loading_icon').show();

	$.get(mz_userfeed, args, 
			function(data) {
				if (!varIsEmpty(data) && !varIsEmpty(data.results)) {
					addResults(data.results);
				} else {
					reportError();
				}
			}, 
			"jsonp")
		.error(function() { reportError(); });

}

function reportError()
{
	$('#mz_loading_icon').hide();
	// Only report error if we are not loading more.
	if (mz_card_array.length == 0) {
		clearData();
		$(mz_divid).append($('<p>').attr('class', 'errorMsg').html("No data available.  You may need to widen the radius, change the category selection or search."));
//		alert("No data available.  Please widen the radius.");
	}
}


function initArrays()
{
	num_columns = Math.max(1, parseInt((document.documentElement.clientWidth - SIDE_MARGIN) / (COL_WIDTH + GUTTER)));
	var startLeft = Math.max(0, parseInt((document.documentElement.clientWidth - (num_columns * (COL_WIDTH + GUTTER))) / 2));
	
	mz_array = Create2DArray(num_columns);
	
	for (var c = 0; c < num_columns; c++) {
		mz_array[c][1] = makeColumn(c);
		mz_array[c][1].css({left: startLeft + (c * (COL_WIDTH + GUTTER))});
		$(mz_divid).append(mz_array[c][1]);
	}	
}

function clearData()
{
	// Clear out the data
	if (!varIsEmpty(mz_divid)) $(mz_divid).empty();
	mz_card_array = [];
}

/*
 * add all the items in the array to the page.
 */
function addResults(results)
{
	if (mz_clear) {
		// First clean up the scroller in case of reloading
		// This is done hear in order to do a delayed cleanup.
		// Otherwise the page is emptied first, and there is a delay until
		// the new data is downloaded.  By doing it here, there this keeps the
		// time the page is empty to a minimum.  Otherwise this could have been
		// done in doInit().
		clearData();
		// initialize columns
		initArrays();

		mz_clear = false;
	}

	for (var r = 0; r < results.length; r++) {
		$el = makeCard(results[r], mz_lat, mz_lon, mz_card_array);

		var colnum = shortestColumn(mz_array);

		mz_array[colnum][1].append($el);

		var height = $el.height();
		
		mz_array[colnum][0] += height;
	}
	
	// Save the last timestamp;
	if (results.length > 0) {
		mz_timestamp = results[results.length - 1].card.timestamp;
	}
	
	if (mz_donefn != null && typeof(mz_donefn)==='function') {
		mz_donefn.call(this);
	}
	$('#mz_loading_icon').hide();
	
	// Reparse newly added HTML to make sure FB Like and Twitter buttons are displayed properly.
	reparseSocialMediaLinks();

}

function makeColumn(colnum)
{
	return $('<div>').attr('class', 'mz_column').attr('id', 'mz_column').html('');
}

function shortestColumn(arr)
{
	var colnum = 0;
	var minlen = arr[0][0];
	
	for (var i = 0; i < arr.length; i++) {
		if (arr[i][0] < minlen) {
			colnum = i;
			minlen = arr[i][0];
		}
	}
	return colnum;
}


/*
 * Create the card structure.
 */
function makeCard(item, lat, lon, cardarray)
{
	var heart = "like";
	if (item.card.like_count > 0) heart = "liked";
	var cardurl = item.card.mezz_url;
	var mapimageurl = gmaps_image_url.format(item.card.latitude, item.card.longitude);
	var maplinkurl = gmaps_link_url.format(item.card.latitude, item.card.longitude);
	var profilepicurl = "";
	var username = "";
	
	if (item.card.author.user_object != null) {
		if (item.card.author.user_object.profile_pic_url != null) {
			profilepicurl = item.card.author.user_object.profile_pic_url;	
		}
		if (item.card.author.user_object.username != null) {
			username = item.card.author.user_object.username;	
		}
	}
	var userurl = "/u/" + username;
	
	// This is the position where the new element will be added.
	var pos = cardarray.length;
	cardarray.push(item.card);
	
	// Compose Comments
//	var comments = "";
//	if (item.card.comments != null) {
//		comments = '<div class="mz_comments_container">';
//		var likes = "";
//		for (var i = 0; i < item.card.comments.length; i++) {
//			if (item.card.comments[i].like) {
//				// this is a like
//				likes += ''
//					  + '<a href="/u/' + item.card.comments[i].username + '"><img class="mz_likepic" src="' + item.card.comments[i].profile_pic_url + '" border="0" title="' + item.card.comments[i].username + '"/></a>';
//			}
//		}
//		comments += likes + '</div>';
//	}
	
	var img;
	if (num_columns == 1) {
		// no popup if only one column displayed - because this is most likely a mobile phone.
		img = '    <img class="mz_photo" src="' + item.card.image_url + '" alt=""/>';
	
	} else {
		img = '    <a href="#" onClick="displayCardPopup(' + pos + ');return false;"><img class="mz_photo" src="' + item.card.image_url + '" alt=""/></a>';

	}
	
	// Overall card	
	$el = $('<div>').attr('class', 'mz_card').attr('id', 'mz_card').html(''
			+ img
//			+ '    <a href="' + cardurl + '" target="_blank"><img class="mz_photo" src="' + item.card.image_url + '" alt=""/></a>'
			+ '    <div class="mz_flag" id="mz_flag"><a href="#" onClick="doFlag(this, \'' + item.card.card_id + '\');return false;" class="mz_flag_link" style="display: none;"></a></div>'
			+ '    <div class="mz_desc">'+ item.card.text.parseURL() + '</div>'
			+ '    <div class="mz_map_container">'
			+ '     <a href="' + maplinkurl + '" target="_blank"><img class="mz_map" src="'+ mapimageurl + '" alt = "" title="View map location"/></a>'
			+ '     <div class="mz_dist">' +  distance(lat, lon, item.card.latitude, item.card.longitude, true) + '</div>'
			+ '     <img class="mz_clock" src="/image/clock.png" alt=""/>'
			+ '     <div class="mz_time">' + item.card.timeDisplay + '</div>'
			+ '    </div>'
			+ '    <div class="mz_like_container">'
			+ '      <div class="fb-like" href="' + cardurl + '"data-send="false" data-layout="button_count" data-width="50" data-show-faces="false"></div>'
			+ '      <div class="twitter-share"><a href="https://twitter.com/share" class="twitter-share-button" data-url="' + cardurl + '" data-text="' + item.card.text.replace(/"/g,"\'") + '" data-count="none" data-via="mezzapp">Tweet</a></div>'
			+ '    </div>'
			+ '    <div class="mz_auth_container">'
			+ '     <a href="' + userurl + '"><img class="mz_authpic" src="' + profilepicurl + '" alt="" /></a>'
			+ '     <div class="mz_auth"><a href="' + userurl + '">' + username + '</a></div>'
			+ '     <img class="mz_heart" src="/image/' + heart + '.png" alt="" border="0"/>'
			+ '     <div class="mz_likecount">' + item.card.like_count + '</div>'
//			+ comments
			+ '    </div>'
			);
	
	if (num_columns == 1) {
		showHideLikeContainers($el, true);
	} else {
		showHideLikeContainers($el, false);
		$el.hover(
				  function()
				  {
					  showHideLikeContainers(this, true);
				  },
				  function()
				  {
					  showHideLikeContainers(this, false);
				  }
				);
	}
	return $el;
//	
//	$qr = $('<div>').attr('class', 'quickflip-wrapper');
//	$qr.append($el);
//	$qr.append($('<div>').html('<a href="#" class="quickFlipCta">Click to flip back panel</a>'));
//	
//	// Initialize quickflip
//	//$qr.quickFlip();
//	
//
//	return $qr;
}

function displayCardPopup(cardnum)
{
	var item = mz_card_array[cardnum];
	
	// Size the dialog properly based on the size of the current window.
	var w = 1088;
	if ($(window).width() <= 510) { 
		w = 310;
	} else if ($(window).width() <= 880) { 
		w = 510;
	} else if ($(window).width() <= 1140) { 
		w = 860;
	}
	
	var $dialog = $('<div id="popupDialog"></div>');
	var $card = makeCardDetail(item);
	// Replace the default class to be a popup class.
	$card.removeClass("mzdet_card").addClass("mzdet_card_popup");
	
	$dialog
	.html($card)
	.dialog({
//		autoOpen: false,
		modal: true,
		draggable: false,
		closeOnEscape: true,
		resizeable: false,
		width: w,
	    create: function (event, ui) {
	    	// Hide the titlebar and remove the padding from the popup.
	        $(".ui-dialog-titlebar").hide();
	        $(".ui-resizable-handle").hide();
	        $(".ui-dialog").css('padding', '0');
	        $(".ui-dialog-content").css('padding', '0');
	    },
	    open: function (event, ui) {
	    	// Change the background of the remaining page when the popup is displayed.
	    	// And add a Close handler when the mouse is clicked outside the dialog.
	        $(".ui-widget-overlay").css({background: '#444444', opacity: 0.7});
	        $(".ui-widget-overlay").bind('click', function(){ $dialog.dialog('close'); });
	    	// Reparse newly added HTML to make sure FB Like and Twitter buttons are displayed properly.
	    	reparseSocialMediaLinks();
	    }

	});

//	$card.prepend('<button id="close" class="closePopup" style="position: absolute; top: 2px; right: -20px;">x</button>')
	$card.prepend('<div class="mz_closePopup"><a href="#">&nbsp;x&nbsp;</a></div>');

	// This implements the close button for the X on the upper right.
	$dialog.find('.mz_closePopup').data('jqpopup', $dialog);
	$('.mz_closePopup').click(function() {
	    $(this).data('jqpopup').dialog('close');
	});
	
	// For some reason links are not being followed when the dialog is
	// modal.  This attaches a click handler to all a href links on the
	// dialog - and first closes the dialog.  Does not return "false" so in
	// effect, the link is followed once the dialog is closed.
	$dialog.on('click', 'a', $dialog, function(event){
		event.data.dialog('close');
	});
	
	$dialog.dialog('open');

}


// Implements showing or hiding the FB & Twitter buttons dynanically.
function showHideLikeContainers(item, display)
{
	if (display) {
		  $(".fb-like", item).show();
		  $(".twitter-share", item).show();
	} else {
		  $(".fb-like", item).hide();
		  $(".twitter-share", item).hide();
	}
}



