//---- UTILS ---------------------------------------------------------------------
var localTimezoneIndex;
var timezoneOptions = [-12, -11, -10, -9, -8, -7, -6, -5, -4, -3.5, -3, -2, -1, 0, 1, 2, 3, 3.5, 4, 4.5, 5, 5.5, 5.75, 6, 7, 8, 9, 9.5, 10, 11, 12, 13, 14];
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var full_months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var days_of_week = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

function shuffle(o) {
	for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
	return o;
}

function show_props(obj, obj_name) {
   var result = "";
   for (var i in obj)
      result += obj_name + "." + i + " = " + obj[i] + "<br>\n";
   return result;
}

function limitLen(str, maxLen) {
	if (str.length > maxLen) str = str.substring(0, maxLen).replace(/(^\s+)|(\s+$)/, "")+"..";
	return str;
}

function in_array(needle, haystack) {
	for (var i in haystack) {
		if (haystack[i] == needle) return true;
	} return false;
}

function removeFromArray(elem, array, secondIndex) {
	for (var i=0; i<array.length; i++) {
		var elemInArr = array[i];
		if ((secondIndex || secondIndex === 0) && elemInArr) elemInArr = elemInArr[secondIndex];
		if (elemInArr == elem) {
			array.splice(i, 1);
			break;
		}
	}
}

function escapeQuotes(src) {
	// unescape single and double quotes from src and return
	if (typeof(src) == "string") {
		src = src.replace(/&#39;/g, "&rsquo;");
		src = src.replace(/'/g, "&rsquo;");
		src = src.replace(/"/g, "&quot;");
		return src;
	} return '';
}

function unescapeQuotes(src) {
	// unescape single and double quotes from src and return
	src = src.replace(/&#39;/g, "'");
	src = src.replace(/&rsquo;/g, "'");
	src = src.replace(/&quot;/g, '"');
	return src;
}

function cleanWhitespace(node) {
	for (var i=0; i<node.childNodes.length; i++) {
		var child = node.childNodes[i];
		if(child.nodeType == 3 && !/\S/.test(child.nodeValue)) {
			node.removeChild(child);
			i--;
		} if (child.nodeType == 1) cleanWhitespace(child);
	} return node;
}

function getFormattedTime(millitime, showZeros) {
	var time; var date = new Date(millitime);
	var hours = date.getHours();
	var minutes = date.getMinutes();
	if (minutes === 0) {
		minutes = '';
		if (showZeros) minutes = '0';
	} if (minutes) {
		if (minutes < 10) minutes = "0"+minutes;
		minutes = ":"+minutes;
	} if (!hours) time = "12"+minutes+" AM";
	else if (hours > 11) {
		hours -= 12;
		if (!hours) hours = 12;
		time = hours+minutes+" PM";
	} else time = hours+minutes+" AM";
	return time;
}

function getFormattedDay(millitime) {
	var d = new Date(millitime);
	var week = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
	var month = d.getMonth()+1;
	var day = d.getDate();
	var dow = week[d.getDay()]+", "+month+"/"+day;
	return dow;
}

function sortByLastName(a, b) {
	if (a['last_name'].toUpperCase() > b['last_name'].toUpperCase()) return 1;
	else if (a['last_name'].toUpperCase() < b['last_name'].toUpperCase()) return -1;
	return 0;
}

function buildImgTag(url, className, desc, id) {
	var id_attr = '';
	if (id) id_attr = ' id="'+id+'"';
	var tag = "<img"+id_attr+" class='"+className+"' alt='"+desc+"' title='"+desc+"' src='"+url+"'/>";
	return tag;
}

function getBaseUrl() {
	var url = location.href;
	var baseurl = url.split("?")[0];
	return baseurl;
}

function removeFid(url) {
	if (url.indexOf('?') != -1) {
		var page_regex = /fid=[^&]+&?/;
		url = url.replace(page_regex, '');
	} return url;
}

function getNewPageUrlWithParams(page) {
	var url = location.href;
	var page_param = 'p='+page;
	if (url.indexOf('?') != -1) {
		var page_regex = /([^\w])(p=[^&]+)/;
		if (url.match(page_regex)) url = url.replace(page_regex, RegExp.$1+page_param);
		else {
			if (!url.match(/\?$/)) url += '&';
			url += page_param;
		}
	} else url += '?'+ page_param;
	
	return url;
}

function writeToDebug(str) {
	var debug_div = document.getElementById("debugDiv");
	if (debug_div) debug_div.innerHTML += str + "<br/>";
}

function getServerErrorMessage() {
	return ("Uh uh! Someone effed up our server.  Please check back after we've had time to kick their asses.");
}

function extractJSONid(data) {
	data = JSON.parse(data);
	data = JSON.parse(data['result']);
	return data['id'];
}

function postExists(post_id) {
	var log_list = document.getElementById('user_news_feed');
	var log_suggestions = log_list.childNodes;
	
	for (var i=0; i<log_suggestions.length; i++) {
		if (log_suggestions[i].getAttribute('name') == post_id) return 1;
	} return 0;
}

function offsetToGMTStr(tzOffset) {
	var gmtStr = " GMT";
	var tzOffsetInt = parseInt(tzOffset, 10);
	var gmtOffset = tzOffsetInt*100 + (tzOffset-tzOffsetInt)*60;
	if (gmtOffset >= 0) gmtStr += '+';
	gmtStr += gmtOffset;
	return gmtStr;
}

function getAdjustedTimeDate(utcStart) {
	if (!utcStart) utcStart = getSts;
	utcStart = parseInt(utcStart,10);
	var tzOffset = timezoneOptions[localTimezoneIndex]*60*60*1000;
	return utcStart+tzOffset+new Date(utcStart+tzOffset).getTimezoneOffset()*60*1000;
	//return getSts-tzOffset+new Date(getSts-tzOffset).getTimezoneOffset()*60*1000
}

function getFormattedDate(input) {
	if (!input) input = getAdjustedTimeDate();
	var startDate = new Date(input);
	return startDate.getMonth()+1 +"/"+ startDate.getDate() +"/"+ startDate.getFullYear();
}

function calendarDateStr(no_day) {
	if (calendar_date) {
		var calendar_str = !no_day? days_of_week[calendar_date.getDay()]+', ' : '';
		var date_val = calendar_date.getDate().toString();
		var ordinal = date_val.charAt(date_val.length-1);
		if (ordinal == 1 && date_val != 11) ordinal = 'st'; else if (ordinal == 2 && date_val != 12) ordinal = 'nd';
		else if (ordinal == 3 && date_val != 13) ordinal = 'rd'; else ordinal = 'th';
		calendar_str += full_months[calendar_date.getMonth()]+' '+date_val+ordinal;
		return calendar_str;
	} return '';
}

function loadFBML(div) {
	FB.XFBML.Host.parseDomElement(div);
}

function fbTagWrap(tag, content, attr) {
	var fbml = '<fb:tag name="'+tag+'">';
	for (var i in attr) {
		fbml += '<fb:tag-attribute name="'+i+'">'+attr[i]+'</fb:tag-attribute>';
	}
	fbml += '<fb:tag-body>'+content+'</fb:tag-body></fb:tag>';
	return fbml;
}

// enable indexOf function for IE
if (!Array.prototype.indexOf) {
	Array.prototype.indexOf = function(elt /*, from*/) {
		var len = this.length;
		
		var from = Number(arguments[1]) || 0;
		from = (from < 0) ? Math.ceil(from) : Math.floor(from);
		if (from < 0) from += len;
		
		for (; from < len; from++) {
			if (from in this && this[from] === elt) return from;
		} return -1;
	}
}

function setLocalTimezone(init, selected_date) {
	var date_timezone = document.getElementById('local_timezone');
	var date_timezone_display = document.getElementById('local_timezone_display');
	var custom_timezone = document.getElementById('new_custom_log_timezone');
	var custom_timezone_display = document.getElementById('new_custom_log_timezone_display');
	var timezoneVal;
	if (init) {
		if (selected_date) timezoneVal = new Date(selected_date).getTimezoneOffset()/-60;
		else timezoneVal = new Date().getTimezoneOffset()/-60;
	} else timezoneVal = date_timezone.value;
	
	localTimezoneIndex = timezoneOptions.indexOf(parseFloat(timezoneVal, 10));
	if (localTimezoneIndex != -1) {
		if (date_timezone) {
			date_timezone.selectedIndex = localTimezoneIndex;
			updateTimezoneDisplay('local_timezone');
		} if (custom_timezone) {
			custom_timezone.selectedIndex = localTimezoneIndex;
			updateTimezoneDisplay('new_custom_log_timezone');
		}
	}
}

function timezoneDetect() {
    var dtDate = new Date('1/1/' + (new Date()).getUTCFullYear());
    var intOffset = 10000; //set initial offset high so it is adjusted on the first attempt
    var intMonth, intHoursUtc, intHours, intDaysMultiplyBy;

    // go through each month to find the lowest offset to account for DST
    for (intMonth = 0; intMonth < 12; intMonth++) {
        // go to the next month
        dtDate.setUTCMonth(dtDate.getUTCMonth() + 1);

        // To ignore daylight saving time look for the lowest offset.
        // Since, during DST, the clock moves forward, it'll be a bigger number.
        if (intOffset > (dtDate.getTimezoneOffset() * (-1))) {
            intOffset = (dtDate.getTimezoneOffset() * (-1));
        }
    }

    return intOffset;
}

//Find start and end of DST
function dstDetect() {
    var dtDstDetect = new Date();
    var dtDstStart = '';
    var dtDstEnd = '';
    var dtDstStartHold = ''; //Temp date hold
    var intYearDayCount = 732; //366 (include leap year) * 2 (for two years)
    var intHourOfYear = 1;
    var intDayOfYear;
    var intOffset = timezoneDetect(); //Custom function. Make sure you include it.

    //Start from a year ago to make sure we include any previously starting DST
    dtDstDetect = new Date()
    dtDstDetect.setUTCFullYear(dtDstDetect.getUTCFullYear() - 1);
    dtDstDetect.setUTCHours(0,0,0,0);

    //Going hour by hour through the year will detect DST with shorter code but that could result in 8760
    //FOR loops and several seconds of script execution time. Longer code narrows this down a little.
    //Go one day at a time and find out approx time of DST and if there even is DST on this computer.
    //Also need to make sure we catch the most current start and end cycle.
    for (intDayOfYear = 1; intDayOfYear <= intYearDayCount; intDayOfYear++) {
        dtDstDetect.setUTCDate(dtDstDetect.getUTCDate() + 1);

        if ((dtDstDetect.getTimezoneOffset() * (-1)) != intOffset && dtDstStartHold == '') {
            dtDstStartHold = new Date(dtDstDetect);
        }
		
        if ((dtDstDetect.getTimezoneOffset() * (-1)) == intOffset && dtDstStartHold != '') {
            dtDstStart = new Date(dtDstStartHold);
            dtDstEnd = new Date(dtDstDetect);
            dtDstStartHold = '';

            //DST is being used in this timezone. Narrow the time down to the exact hour the change happens
            //Remove 48 hours (a few extra to be on safe side) from the start/end date and find the exact change point
            //Go hour by hour until a change in the timezone offset is detected.
            dtDstStart.setUTCHours(dtDstStart.getUTCHours() - 48);
            dtDstEnd.setUTCHours(dtDstEnd.getUTCHours() - 48);

            //First find when DST starts
            for(intHourOfYear=1; intHourOfYear <= 48; intHourOfYear++) {
                dtDstStart.setUTCHours(dtDstStart.getUTCHours() + 1);

                //If we found it then exit the loop. dtDstStart will have the correct value left in it.
                if ((dtDstStart.getTimezoneOffset() * (-1)) != intOffset) {
                    break;
                }
            }

            //Now find out when DST ends
            for (intHourOfYear=1; intHourOfYear <= 48; intHourOfYear++) {
                dtDstEnd.setUTCHours(dtDstEnd.getUTCHours() + 1);

                //If we found it then exit the loop. dtDstEnd will have the correct value left in it.
                if ((dtDstEnd.getTimezoneOffset() * (-1)) != (intOffset + 60)) {
                    break;
                }
            }

            //Check if DST is currently on for this time frame. If it is then return these values.
            //If not then keep going. The function will either return the last values collected
            //or another value that is currently in effect
            if ((new Date()).getTime() >= dtDstStart.getTime() && (new Date()).getTime() <= dtDstEnd.getTime()) {
                return new Array(dtDstStart,dtDstEnd);
            }

        }
    }
	
    return new Array(dtDstStart,dtDstEnd);
}

function createTimezoneDropdown(elemId) {
	document.write(getTimezoneDropdown(elemId));
	document.getElementById(elemId).selectedIndex = localTimezoneIndex;
}

function getTimezoneDropdown(elemId) {
	var idAttr = "", changeAttr = "";
	if (elemId) {
		idAttr = ' id="'+elemId+'"';
		if (elemId == 'local_timezone') changeAttr = ' onChange="timezoneModified()"';
		else changeAttr = ' onChange="confirmTimezone(\''+elemId+'\')"';
	} //return '<select'+idAttr+' class="timeZoneDropdown"'+changeAttr+'><option value="-12">(GMT -12:00) Eniwetok, Kwajalein</option><option value="-11">(GMT -11:00) Midway Island, Samoa</option><option value="-10">(GMT -10:00) Hawaii</option><option value="-9">(GMT -9:00) Alaska</option><option value="-8">(GMT -8:00) Pacific Time (US & Canada)</option><option value="-7">(GMT -7:00) Mountain Time (US & Canada)</option><option value="-6">(GMT -6:00) Central Time (US & Canada), Mexico City</option><option value="-5">(GMT -5:00) Eastern Time (US & Canada), Bogota, Lima</option><option value="-4">(GMT -4:00) Atlantic Time (Canada), Caracas, La Paz</option><option value="-3.5">(GMT -3:30) Newfoundland</option><option value="-3">(GMT -3:00) Brazil, Buenos Aires, Georgetown</option><option value="-2">(GMT -2:00) Mid-Atlantic</option><option value="-1">(GMT -1:00) Azores, Cape Verde Islands</option><option value="0">(GMT) Western Europe Time, London, Lisbon, Casablanca</option><option value="1">(GMT +1:00) Brussels, Copenhagen, Madrid, Paris</option><option value="2">(GMT +2:00) Kaliningrad, South Africa</option><option value="3">(GMT +3:00) Baghdad, Riyadh, Moscow, St. Petersburg</option><option value="3.5">(GMT +3:30) Tehran</option><option value="4">(GMT +4:00) Abu Dhabi, Muscat, Baku, Tbilisi</option><option value="4.5">(GMT +4:30) Kabul</option><option value="5">(GMT +5:00) Ekaterinburg, Islamabad, Karachi, Tashkent</option><option value="5.5">(GMT +5:30) Bombay, Calcutta, Madras, New Delhi</option><option value="5.75">(GMT +5:45) Kathmandu</option><option value="6">(GMT +6:00) Almaty, Dhaka, Colombo</option><option value="7">(GMT +7:00) Bangkok, Hanoi, Jakarta</option><option value="8">(GMT +8:00) Beijing, Perth, Singapore, Hong Kong</option><option value="9">(GMT +9:00) Tokyo, Seoul, Osaka, Sapporo, Yakutsk</option><option value="9.5">(GMT +9:30) Adelaide, Darwin</option><option value="10">(GMT +10:00) Eastern Australia, Guam, Vladivostok</option><option value="11">(GMT +11:00) Magadan, Solomon Islands, New Caledonia</option><option value="12">(GMT +12:00) Auckland, Wellington, Fiji, Kamchatka</option></select>';
	return '<a href="#" onclick="return changeTimezone(\''+elemId+'\')" id="'+elemId+'_display"></a><select'+idAttr+' class="timeZoneDropdown"'+changeAttr+'><option value="-12">(GMT -12:00) Eniwetok, Kwajalein</option><option value="-11">(GMT -11:00) Midway Island, Samoa</option><option value="-10">(GMT -10:00) Hawaii</option><option value="-9">(GMT -9:00) Alaska</option><option value="-8.0">(GMT -8:00) PST, Alaska DT</option><option value="-7.0">(GMT -7:00) MST, PDT</option><option value="-6.0">(GMT -6:00) CST, MDT, Mexico City</option><option value="-5.0">(GMT -5:00) EST, CDT, Bogota</option><option value="-4.0">(GMT -4:00) EDT, Atlantic, Caracas</option><option value="-3.5">(GMT -3:30) Newfoundland, Atlantic DT</option><option value="-3">(GMT -3:00) Brazil, Buenos Aires</option><option value="-2">(GMT -2:00) Mid-Atlantic</option><option value="-1">(GMT -1:00) Azores, Cape Verde Islands</option><option value="0">(GMT) Western Europe, London</option><option value="1">(GMT +1:00) CET, Rome, Paris</option><option value="2">(GMT +2:00) CEST, Israel, South Africa</option><option value="3">(GMT +3:00) Baghdad, Moscow</option><option value="3.5">(GMT +3:30) Tehran</option><option value="4">(GMT +4:00) Abu Dhabi, Tbilisi</option><option value="4.5">(GMT +4:30) Kabul</option><option value="5">(GMT +5:00) Islamabad, Karachi</option><option value="5.5">(GMT +5:30) Bombay, New Delhi</option><option value="5.75">(GMT +5:45) Kathmandu</option><option value="6">(GMT +6:00) Dhaka, Colombo</option><option value="7">(GMT +7:00) Bangkok, Jakarta</option><option value="8">(GMT +8:00) Beijing, Hong Kong</option><option value="9">(GMT +9:00) Tokyo, Seoul</option><option value="9.5">(GMT +9:30) Adelaide, Darwin</option><option value="10">(GMT +10:00) Eastern Australia, Guam</option><option value="11">(GMT +11:00) Magadan, New Caledonia</option><option value="12">(GMT +12:00) Auckland</option><option value="13">(GMT +13:00) Phoenix Island</option><option value="14">(GMT +14:00) Line Islands</option></select>';
}

function timezoneAdjust(timezoneOffset) {
	var selected_date;
	var event_date_field = document.getElementById('event_date');
	if (event_date_field && event_date_field.value) selected_date = Date.parse(event_date_field.value);
	else if (getSts) selected_date = getAdjustedTimeDate();
	
	//timezoneOptions[localTimezoneIndex]
	return (timezoneOffset - new Date(selected_date).getTimezoneOffset()/-60)*60*60*1000;
}

function addFriendPromptText(fbActorId) {
	return '<div class="dottedBorder">You must be connected to <span><fb:name uid="'+fbActorId+'" firstnameonly="true" linked="false" /></span> to view this content. Click <a href="http://www.facebook.com/profile.php?id='+fbActorId+'" target="_blank">here</a> to send a friend request now.</div>';
}

function processMediaId(mediaId, mediaSelectedArray, removeIndex, pointId) {
	if (!in_array(mediaId, highlighted_media)) highlighted_media.push(mediaId);
	
	// highlight or queue media in array
	var mediaObj = document.getElementById('m'+mediaId);
	if (mediaObj && !mediaObj.style.borderColor) {
		var media_removed = 0;
		var media_type = mediaObj.getAttribute('media_type');
		var is_video = (media_type == 2 || media_type == 10)? 1 : null;
		if (is_video && in_array(mediaId, videosRemovedArray)) media_removed = 1;
		else if (in_array(mediaId, photosRemovedArray)) media_removed = 1;
		if (!media_removed) {
			highlightMedia(mediaObj, null, is_video);
			if (pointId) mediaObj.setAttribute('pointId', pointId);
			// if (removeIndex || removeIndex === 0) removeFromArray(mediaId, mediaSelectedArray, 0);
			// if (removeIndex || removeIndex === 0) mediaSelectedArray.splice(removeIndex, 1);
		}
	} else if (!removeIndex && removeIndex !== 0) mediaSelectedArray.push([mediaId, pointId]);
}

function getLinkedProfilePic(fbid) {
	var link_url = location.href.split('?')[0].replace('theconstellations.','')+'?p=f&fid='+fbid;
	var ie_click_hanlder = '';
	if (navigator.userAgent.indexOf("MSIE") != -1) ie_click_hanlder = ' onclick="location.href=\''+link_url+'\'" style="cursor:hand"';
	return '<a href="'+link_url+'"><fb:profile-pic uid="'+fbid+'" size="square" linked="false" class="friend_photo"'+ie_click_hanlder+' /></a>';
	//return '<a href="http://www.facebook.com/profile.php?id='+fbid+'" target="_blank"><fb:profile-pic uid="'+fbid+'" size="square" linked="false" class="friend_photo" /></a>';
}

function addToFriendSuggestions(fbid) {
	if (editNight && fbid != loggedInUser && fbid != getFid && !document.getElementById('suggested_'+fbid)) {
		var friend_suggestions_div = document.getElementById('friend_suggestions');
		friend_suggestions_div.style.display = 'block';
		var fb_friend = document.createElement('div');
		fb_friend.id = 'suggested_'+fbid;
		fb_friend.style.display = 'inline';
		fb_friend.style.marginRight = '3px';
		if (!featured_night) fb_friend.innerHTML = getLinkedProfilePic(fbid);
		else fb_friend.innerHTML = '<a href="#" onClick="return loginToFacebook()"><fb:profile-pic uid="'+fbid+'" size="square" linked="false" class="friend_photo" /></a>';
		loadFBML(fb_friend);
		friend_suggestions_div.appendChild(fb_friend);
	}
}

function toggleDateSelector(enable) {
	var date_field = document.getElementById('event_date');
	var calendar_field = document.getElementById('calendar_field');
	if (date_field) {
		if (enable) {
			$("#event_date").datepicker("enable");
			if (calendar_field) {
				$("#calendar_field").datepicker("enable");
				document.getElementById('night_month').disabled = false;
				document.getElementById('night_day').disabled = false;
				document.getElementById('night_year').disabled = false;
			}
		} else {
			$("#event_date").datepicker("disable");
			if (calendar_field) {
				$("#calendar_field").datepicker("disable");
				document.getElementById('night_month').disabled = true;
				document.getElementById('night_day').disabled = true;
				document.getElementById('night_year').disabled = true;
			}
		}
	}
}

function getDateVal() {
	return $("#full_calendar").datepicker("getDate");
}

function highlightHeaderLink(link_name) {
	if (!link_name) link_name = 'home';
	var home_link = document.getElementById('home_link');
	var recreate_link = document.getElementById('recreate_link');
	if (home_link) home_link.style.color = '';
	if (recreate_link) recreate_link.style.color = '';
	
	var active_link = document.getElementById(link_name+'_link');
	if (active_link) active_link.style.color = '#ffcc00';
}

function showFrame(frame_name, section) {
	var header_bar = document.getElementById('header_bar');
	// highlight specific sections
	if (header_bar) {
		if (frame_name == 'recreate') {
			if (section == 'date') toggleCalendarSelector(1);
			else if (section == 'log') toggleAddLogs(1);
			else if (section == 'friends') toggleFriendSelector(1);
			header_bar.style.backgroundImage = 'url("'+TEMPLATE_VIEW_PATH+'images/flare_top.jpg")';
			highlightHeaderLink(frame_name);
		} else {
			header_bar.style.backgroundImage = 'url("'+TEMPLATE_VIEW_PATH+'images/banner_top.jpg")';
			highlightHeaderLink();
		}
	}
	
	document.getElementById('dashboard_frame').style.display = 'none';
	document.getElementById('recreate_frame').style.display = 'none';
	document.getElementById(frame_name+'_frame').style.display = 'block';
	
	return false;
}

var calendar_date;
function generateCalendarDate(saved_night_date, div_prefix) {
	if (!saved_night_date) {
		var event_date_field = document.getElementById('event_date');
		if (event_date_field && event_date_field.value)
			saved_night_date = Date.parse(event_date_field.value);
		else saved_night_date = getAdjustedTimeDate();
	} saved_night_date = new Date(saved_night_date);
	
	if (!div_prefix) { div_prefix = 'saved_night'; calendar_date = saved_night_date; } // store calendar date
	document.getElementById(div_prefix+'_month').innerHTML = months[saved_night_date.getMonth()]+" "+saved_night_date.getFullYear();
	document.getElementById(div_prefix+'_day').innerHTML = saved_night_date.getDate();
	document.getElementById(div_prefix+'_info').style.display = 'block';
}

function populateDate(dateTime) {
	document.getElementById('event_date').value = getFormattedDate(parseInt(dateTime,10));
	loadLogEntries();
}

function setNewTimeBound(upper) {
	var log_list = document.getElementById('user_news_feed');
	//cleanWhitespace(log_list);
	var log_suggestions = log_list.childNodes;
	if (upper) {
		var last_point;
		night_range_end = null;
		if (log_suggestions.length) last_point = log_suggestions[log_suggestions.length-1];
		if (last_point) setNightTimeRange(last_point.id.split('_')[0]);
		else updateSavedNightInfo('end'); // otherwise clear display
	} else {
		night_range_start = null;
		var first_point = log_suggestions[0];
		if (first_point) setNightTimeRange(first_point.id.split('_')[0]);
		else updateSavedNightInfo('start'); // otherwise clear display
	}
}

function setNightTimeRange(utc_time) {
	if (!night_range_start || utc_time < night_range_start) {
		night_range_start = utc_time;
		updateSavedNightInfo('start');
	} if (!night_range_end || utc_time > night_range_end) {
		night_range_end = utc_time;
		updateSavedNightInfo('end');
	}
}

function formatNightRangeDate(utc_time) {
	utc_time = getAdjustedTimeDate(utc_time*1000);
	var timezoneText = (timezoneOptions[localTimezoneIndex]*-60 == new Date().getTimezoneOffset())? '' : offsetToGMTStr(timezoneOptions[localTimezoneIndex]);
	return getFormattedDay(utc_time) +' '+ getFormattedTime(utc_time) + timezoneText;
}
var i = 0;
function updateSavedNightInfo(div) {
	if (div == 'location') {
		var saved_night_event_thumb = document.getElementById('saved_night_location_thumb');
		//event_suggestions_list[eid] = {'name':name,'desc':desc,'start_time':start_time,'end_time':end_time,'location':location,'thumb':pic};
		var saved_night_location_div = document.getElementById('saved_night_location_text');
		var event_location_field = document.getElementById('event_location');
		saved_night_event_thumb.innerHTML = '';
		if (fbEventId && event_suggestions_list[fbEventId]) {
			var fb_event = event_suggestions_list[fbEventId];
			var location_info = event_location_field.value? event_location_field.value : activeLocation;
			var event_thumb = fb_event['thumb'];
			if (!location_info) location_info = fb_event['location'];
			if (!location_info) location_info = fb_event['name'];
			saved_night_location_div.innerHTML = '<b>'+location_info+'</b>';
			if (event_thumb) saved_night_event_thumb.innerHTML = '<img src="'+event_thumb+'" class="eventThumb" alt="'+fb_event['name']+'" title="'+fb_event['name']+'" style="margin-right:5px">';
		} else if (event_location_field && event_location_field.value) saved_night_location_div.innerHTML = '<b>'+event_location_field.value+'</b>';
		//else if (activeLocation) saved_night_location_div.innerHTML = '<b>'+activeLocation+'</b>';
		else saved_night_location_div.innerHTML = 'No location specified.';
	} if (div == 'start' || !div) {
		var saved_night_start_div = document.getElementById('saved_night_start_text');
		if (night_range_start) saved_night_start_div.innerHTML = 'Start: '+formatNightRangeDate(night_range_start);
		else saved_night_start_div.innerHTML = '';
	} if (div == 'end' || !div) {
		var saved_night_end_div = document.getElementById('saved_night_end_text');
		if (night_range_end) saved_night_end_div.innerHTML = 'End: '+formatNightRangeDate(night_range_end);
		else saved_night_end_div.innerHTML = '';
	}
}

function extractGetParam(param) {
	var re = new RegExp('\\b'+param+'=([^&]+)\\b');
	re.lastIndex = 0; // reset lastIndex for next usage
	var param_val = re.exec(location.href); // extract tab param
	if (param_val) return param_val[1];
	return '';
}

var chronology;
function getChronology() {
	if (chronology) return chronology;
	chronology = 'present';
	var curr_time = parseInt(new Date().getTime()/1000, 10);
	if (curr_time > night_search_end) chronology = 'past';
	else if (curr_time < night_search_start) chronology = 'future';
	return chronology;
}

function updateNightTenseLabels() {
	var tense_str = 'are'; var location_str = 'Where '+tense_str+' you?';
	var tense = getChronology();
	if (tense == 'past') {
		tense_str = "were";
		location_str = 'Where did you go?'
	} else if (tense == 'future') {
		tense_str = "will be";
		location_str = 'Where will you be?'
	} document.getElementById('you_were_with_label').innerHTML = "Friends who "+tense_str+" there";
	
	var friend_selector_title_left = document.getElementById('friend_selector_title_left');
	var friend_selector_title_right = document.getElementById('friend_selector_title_right');
	if (friend_selector_title_left) {
		var question_str = 'Who '+tense_str+' you with?';
		question_str = question_str.replace('be you', 'you be'); // grammatical handling
		friend_selector_title_left.innerHTML = question_str;
		friend_selector_title_right.innerHTML = 'You '+tense_str+' with:';
		document.getElementById('fb_location_title').innerHTML = location_str;
	}
	
}

// cookie operations
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

// --------------------------------------------------------------- END UTILS --------------
