schmap[userinfo.screen_name] = true;
var alreadyThere = false;
// NPF [EN]

var bThereCount = attendees.length;  // NPF5

function outputEncodedHashtag(hashtag){
    hashtag = hashtag || resource.hashtag;
	if(hashtag){
	    hashtag = '+%23' + hashtag.replace(/#/g, '').replace(/\|/g, '+%23');
	}
	return hashtag;
}
function outputHashtag(hashtags){
	var hashtagContainer = $('hashtagContainer');
	if(hashtags){
	    var hashes = hashtags.split('|'), prefix = 'http://search.twitter.com/search?q=%23';
		for(var i=0, l=hashes.length, arr=[]; i < l; i++){
		    var hash = hashes[i].replace(/%23|#/g,'');
			arr[arr.length] = '<a class="func hash-link" target="_blank" href="';
			arr[arr.length] = prefix + hash;
			arr[arr.length] = '">#';
			arr[arr.length] = hash;
			arr[arr.length] = '</a> ';
		}
		hashtagContainer.innerHTML = arr.join('');
		showElement(hashtagContainer);
	}else{
		hideElement(hashtagContainer);
	}
}

function setupUserinfo(){
	$('direction').href = 'http://www.google.com/maps?daddr=' + resource.latitude + ',' + resource.longitude;
	outputHashtag(resource.hashtag);
}

// NPF6 [BEGIN]

// NPF6 [END]
function setMeTooText() {
    var text, link = $('metoo');
	if(alreadyThere){
	    text = 'Remove me';
	}else{
		if (bThereCount > 1) { 
			text = 'Me too!';
		} else {
			text = 'Add me';
		}
	}
	link.innerHTML = text;
}

function createRetweetLink(){
    var hashtag = outputEncodedHashtag(),
	    maxLength = 140 - hashtag.length,
		a = document.location,
	    link = 'http://' + a.host + a.pathname,
	    screenname = 'RT+@' + userinfo.screen_name + '+',
	    l = maxLength - 1 - (screenname + link).length,// 1 is a space add after the text
		text = resource.text;
	if(text){
	    text = text.trim().replace(/\n/g,' ');
		text = truncatelink(text,l) + '+';
	}else{
	    text = '';
	}
	var string = screenname + text + link + hashtag;
	var elm = $('retweetButton');
    elm.href = 'http://twitter.com/home/?status=' + string;
	showElement(elm);
}


(function(window){
	function addMe(){
	    comment.doSubmit({bethere:"y"});
	}
    var ibt = {
	    checkBeThere: function(nodeName){
			if(nodeName === 'A'){
				if(loggedin_username){
					if(alreadyThere){
						topAlert.call("You are already in the I\'ll be there!");
					}else{
						addMe();
					}
				}else{
					comment.showForm("bethere");
				}
			}
		},
		handleAddBeThere: function(e){
			e = e || window.event;
			var target = e.target || e.srcElement;
			ibt.checkBeThere(target.nodeName);
		}
	};
	window.ibt = ibt;
})(window);
function setRsvp(){
    buildIllBeInList();
	$('profile_images').onclick = ibt.handleAddBeThere;
	var link = $('metoo');
	link.onclick = function(){
	    if(alreadyThere){
		    comment.doSubmit({bethere:"n"});return false;
		}else{
		    if(loggedin_username){
				comment.doSubmit({bethere:"y"});return false;
			 }else{
				comment.showForm("bethere");return false;
			 }
		}
	}
	setMeTooText();
	cssjs('add',document.body,'show-rsvp');
}
var comment = function(){
    var inited = false, form ,text, beThere, 
	    eventid = addressable.id, 
	    screen_name, profile_image_url, name, id,
		customeTextarea, connect, parentElm, tweetText, bethereValue,
		pathname = document.location.pathname,
		emptyCommentMsg = 'You haven\'t write any comment yet!',
		info;
	function check(){
	    if(!inited){
		    screen_name = cookie.get('s_u_s');
			profile_image_url = cookie.get('s_u_img');
			name = cookie.get('s_u_n');
			id = cookie.get('s_u_xid');
			info = {
				eventid: eventid, 
				screen_name: screen_name,
				profile_image_url: profile_image_url, 
				name: name,
				id: id
			};
		    parentElm = $('popupContent');
			form = document.commentform;
			text = form.commentText;
			customeTextarea = new FormElement(text);
			beThere = form.bethere;
			connect = $('comment_connect');
			new Checkbox(beThere);
		    inited = true;
		} 
	}
	function submitError(response){
		hideElement('workingSection');
		topAlert.call('We\'re sorry, we were unable to process your request now. Please try again later.');
	}
	function handleSubmitSuccess(resp){
	    var errorMsg = 'We\'re sorry, we were unable to process your request now. Please try again later.';
		if(!resp){
		    topAlert.call(errorMsg);
		    return;
		}
		var addedComment;
		if (resp && resp.status == '200') {
			hideForm();
			addedComment = false;
			var addedBThere = false;
			var removedBThere = false;
			// Success! If the user indicated 'be there', then need to add their image to the list of profile images...
			if(+resource.display_rsvp === 1){
				if (bethereValue === 'y') {
					addedBThere = addProfileImageAtEnd (profile_image_url, name, id, screen_name);
					if(addedBThere){bThereCount++;}
					alreadyThere = true;
				}else if(bethereValue === 'n'){
					removedBThere = removeProfileImage (screen_name); 
					if(removedBThere){bThereCount--;}
					alreadyThere =false;
				}
				if (addedBThere || removedBThere) {
					var l = bThereCount;
					if (l > 1) {
						$('illbethere_count').innerHTML = '<b>' + l + '</b>' + ' say...';
					}
					else {
						$('illbethere_count').innerHTML = '';
					}
					setMeTooText();
				}
			}
			if(+resource.display_comment === 1){
				if (tweetText) {
				    var commentinfo = cloneObj(info);
					commentinfo.createtime = new Date().toString1();
					commentinfo.comment = tweetText;
					addComment(commentinfo);
					addedComment = true;
					outputCommentsCount();
				}
			}
			var displayMsg;
			if (addedComment) {
				if (addedBThere){
					displayMsg = 'Thanks! Your comment has been added and the "I\'ll be there" section updated with your profile image.';
				} else if (removedBThere) {
					displayMsg = 'Thanks! Your comment has been added and you have been removed from the "I\'ll be there" section.';
				} else {
					displayMsg = "Thanks! Your comment has been added.";
				}
			} else {
				if (addedBThere) {
					displayMsg = 'You have been successfully added to the "I\'ll be there" section!'; 
				} else if (removedBThere) {
					displayMsg = 'You have been removed from the "I\'ll be there" section.';
				}
			}
			if (displayMsg) {
				topAlert.call (displayMsg);
			}
		}else {
			topAlert.call (errorMsg);
		}
		hideElement('workingSection');
	}
	function doSubmit(o){log(o);
	    check();
		var commentinfo = cloneObj(info);
		if(o.comment){
		    commentinfo.comment = o.comment;
		}
		if(o.bethere){
		    commentinfo.bethere = bethereValue = o.bethere;
		}else{
		    bethereValue = null;
		}
		tweetText = commentinfo.comment;
		var params = 'tweetuser=' + convertJsonToString (commentinfo);
		var options  = {
			method:'post',
			type:'post',
			url:'/sapp/authenticate',
			onSuccess: handleSubmitSuccess,
			onError: submitError,
			data: params,
			timeout: 40000,
			formData: true
		};
		ajax(options);
	}
	function handleSubmit(e){
	    var v = customeTextarea.getValue();
		if(!v){
		    topAlert.call(emptyCommentMsg);
		}else{
		    showElement('workingSection');
			var o = {comment: v};
			if(!alreadyThere){o.bethere = beThere.checked ? 'y' : 'n';}
			doSubmit(o);
		}
		if(e){e.preventDefault();}
	}
	function add(){
	    
	}
	function checkPostComment(){
	    var a = cookie.get('comment'),
		    b = cookie.get('bethere');
		if(a || b){
		    check();
			if(loggedin_username){
				doSubmit({comment: a, bethere: b});
				cookie.unset('comment');
				cookie.unset('bethere');
			}
		}
	}
	function storeComment(){
		var v = customeTextarea.getValue();
		if(v){
			removeAllCookie();
			cookie.set('comment', encodeURIComponent(v), 365);
		    cookie.set('bethere', beThere.checked ? 1 : 0, 365);
		    oauth.getTokenNew('T-SM-COM', null, addressable.url);
		}else{
		    topAlert.call(emptyCommentMsg);
		}
		return false;
	}
	function storeBethere(){
	    removeAllCookie();
		cookie.set('bethere', 'y', 365);
		oauth.getTokenNew('T-SM-RSVP', null, addressable.url);
		return false;
	}
	function hideForm(){
	    overlay.hide();
	    Handler.remove(form, 'submit', handleSubmit);
	}
	function showForm(flag){
	    check();
		beThere.checked = 'checked';
		if(alreadyThere){
			cssjs('add', parentElm, 'no-rsvp');
		}else{
		    cssjs('remove', parentElm, 'no-rsvp');
		}
		var defaultHintText;
		if(loggedin_username){
			Handler.add(form, 'submit', handleSubmit);
			defaultHintText = 'Add your comment here, then click the button below to post: this will also tweet a "just added a comment" message from your Twitter account, with a link to this page.';
		}else{
		    defaultHintText = 'Add your comment here, then connect via Twitter to post: this will also tweet a "just added a comment" message from your Twitter account, with a link to this page.';
		    var title;
			if(flag === 'bethere'){
				cssjs('add', parentElm, 'bethere');
				connect.onclick = storeBethere;
				title = 'I\'ll be there!';
			}else{
				cssjs('remove', parentElm, 'bethere');
				connect.onclick = storeComment;
				title = 'Add a comment';
			}
		    $('comment_title').innerHTML = title;
		}
		form.commentText.defaultValue = defaultHintText;
		if(flag !== 'bethere'){customeTextarea.restore();}
		overlay.show({elm:$('ov_popup')});
	}
	function addCommentRow (commentElem, convertDate) {
		var arr = [];
		arr[arr.length] = '<li class="commentsRow"><a href="http://www.twitter.com/';
		arr[arr.length] = commentElem.screen_name;
		arr[arr.length] = '" target="_blank"><img id="profile-img-comm-';
		arr[arr.length] = commentElem.screen_name;
		arr[arr.length] = '" class="commentProfileImage" src="';
		arr[arr.length] = commentElem.profile_image_url || commentElem.profile_background_image_url;//this is the server side bug. it should return profile_image_url instead of profile_background_image_url
		arr[arr.length] = '"';
		arr[arr.length] = ' onerror="getCommProfleImgFromTwitter(\'';
		arr[arr.length] = commentElem.screen_name;
		arr[arr.length] = "'";
		arr[arr.length] = ')"></a>';
		arr[arr.length] = '<h3 class="commentNameAndDate"><a class="commentName" href="http://www.twitter.com/';
		arr[arr.length] = commentElem.screen_name;
		arr[arr.length] = '" target="_blank">';
		arr[arr.length] = commentElem.name;
		arr[arr.length] = '</a><span class="dateTimeStr">&nbsp;on&nbsp;';
		var dateTimeStr = commentElem.createtime;
		if (convertDate) {
			dateTimeStr = dateTimeStr.toDateString();
		}
		arr[arr.length] = dateTimeStr;		
		if (commentElem && commentElem.comment){
			arr[arr.length] = '</span></h3><p class="commentText">';
			arr[arr.length] = commentElem.comment.replace(/\n/g,'<br />');
			arr[arr.length] = '</p>';
		}
		arr[arr.length] = 	'</li>';
		return arr.join('');
	}
	function addComment (json) {
		var temp = document.createElement('ul'),
			p = $('commentsDiv'),
			firstLi = p.getElementsByTagName('li')[0];
		temp.innerHTML = addCommentRow(json, false);
		var newLi = temp.getElementsByTagName('li')[0];
		if(firstLi){
			p.insertBefore(newLi,firstLi);
		}else{
			p.appendChild(newLi);
		}
	}
	function outputCommentsCount() {
		var l = tn('li', $('commentsDiv')).length,
		    addLink = $('addComment'),
			addMineSection = $('addMineSection');
		if(l > 0){
			if(addLink.parentNode !== addMineSection){
		        addLink.innerHTML = 'Add mine!';
			    addMineSection.appendChild(addLink);
			}
			$('commentsCount').innerHTML = '<span class="bold">' + l + (l > 1 ? '</span> comments' : '</span> comment');
			showElement(addMineSection);
		}
		addLink.onclick = showOverlay;
		addLink.style.display = 'inline';
	}
	function build(){
		if(window.comments && comments.length > 0){
			for(var i=0, l=comments.length, arr=[]; i<l; i++){
				arr[arr.length] = addCommentRow(comments[i], true);
			}
			$('commentsDiv').innerHTML = arr.join('');
			comments = null;
		}
		outputCommentsCount();
		cssjs('add',document.body,'show-comment');
	}
	return {showForm: showForm, checkPostComment: checkPostComment, doSubmit: doSubmit, build: build};
}();
var readyToPostComment;
function setup() {
	readyToPostComment = singlepagecallback;
	createRetweetLink();
    Handler.add($('retweetButton'), 'click', submitRetweet);
    $('profileImg').onerror = getMainProfleImgFromTwitter; 
    var mapType =  resource.maptype || 'm',
	    lat = resource.latitude,
		lng = resource.longitude;
	var iconObj = marker.getIconData(resource.iconcode);
	if(lat && lng){
		var mapicon =  PNG_html({src: '/image/mapicons/' + iconObj.bigiconpath,
			width: iconObj.bigiconwidth,  height: iconObj.bigiconheight});
		$('mapicon').innerHTML = mapicon;
		$('mapicon').style.top = (101 - iconObj.bigiconheight*iconObj.bigiconanchory/100) + 'px';
		$('mapicon').style.left = (123  - iconObj.bigiconwidth*iconObj.bigiconanchorx/100) + 'px';
		var staticmap = $('staticmap');
		Handler.add(staticmap, 'mousedown', handleMouseDown);
		Handler.add(staticmap, 'dragstart', handleDragStart);
		Handler.add(staticmap, 'mousemove', handleMouseMove);
		Handler.add(staticmap, 'mouseup', handleDragEnd);
		Handler.add(staticmap, 'dragend', handleDragEndIE);
		Handler.add(staticmap, 'dragexit', handleDragEnd);
		initMapButton();
		var eventType;
		if (staticmap.addEventListener){
			eventType = 'DOMMouseScroll';
		}else {
			eventType = 'mousewheel';
		}
		Handler.add(staticmap, eventType, getMWheelDelta);
	}
}

function showOverlay(e) {
	var c = '';
	if(resource.display_rsvp && +resource.display_rsvp){
		$('bethere').checked = 'checked';
	}else {
	    c += 'no-rsvp';
	}
	cssjs('add', $('popupContent'), c);
	comment.showForm();
    var img = $('workngHand'),
	    h1 = 60,//image's height
	    h2 = $('ov_popup').clientHeight,
		offset = 10;//this is the offset of the text below the loading image, half of the the text's height .
	img.parentNode.style.height = h2 + 'px';
	img.style.marginTop = (h2 - h1)/2 -offset + 'px';
	if(e){e.preventDefault();}
}

function submitRetweet() {
    var count = $('retweetCount').innerHTML;
	count = parseInt(count, 10);
	count = isNaN(count) ? 1 : count + 1;
    $('retweetCount').innerHTML = count;
}

/* NPF5 [BEGIN] */
function findUserInIllBeThere (username) {
    var foundNode = null,
	    nodeIdToFind = 'profile-a-' + username,
		as = $('profile_images').getElementsByTagName('a'),
		l = as.length;
    for(var i=0; i < l; i++) {
        var currA = as[i];
        if(currA.id === nodeIdToFind){
		    foundNode = currA;
			break;
		}
    }
    return foundNode;
}
/* NPF5 [END] */

function changeProfileImg (imageUrl, type) {
    var underscorePos = imageUrl.lastIndexOf('_');
    if (underscorePos > 0) {
        var periodIndex = imageUrl.indexOf ('.', underscorePos);
        if (periodIndex > underscorePos) {
            var startStr = imageUrl.substring (0, underscorePos);
            var endStr = imageUrl.substring(periodIndex);
            imageUrl = startStr + '_' + type + endStr;
        }
    }
    return imageUrl;
}

function buildProfileImage (username, imageUrl,name) {
    var arr = [];
    arr[arr.length] = '<a target="_blank" href="http://www.twitter.com/';
    arr[arr.length] = username;
    arr[arr.length] = '" id="profile-a-';
	arr[arr.length] = username;
	arr[arr.length] = '" title="';
	arr[arr.length] = name;
	arr[arr.length] = '"><img class="profileImage" src="';
    arr[arr.length] = imageUrl;
	arr[arr.length] = '" id="profile-img-';
	arr[arr.length] = username;
    arr[arr.length] = '" onerror="getProfleImgFromTwitter(\'';
    arr[arr.length] = username;
    arr[arr.length] = "'";
    arr[arr.length] = ')"></a>';
    return arr.join('');
}
var emptyProfile = [];
function addEmptyProfileImg(l,container){
    var a = container || $('profile_images');
    while(l){
	    l--;
	    var newElem = document.createElement('a');
		newElem.className = 'profileImage';
		newElem.title = 'Click to add yourself!';
		a.appendChild(newElem);
		emptyProfile.push(newElem);
	}
}
function addProfileImageAtEnd (imgUrl, name, xid, username) {
    var found = false,  // NPF5
	    b = bThereCount,
    // First, se if the user is already in the "I'll be there" section
        existingNode = findUserInIllBeThere (username);  // NPF5
    if (b >= 999999) {  //  Change this to 27 later!! 
        // The array is 'full'
    } else if (existingNode === null) {  // NPF5
	    found = true;
        var imageUrl = changeProfileImg (imgUrl, 'mini'),
		    p = $('profile_images'),
		    as = p.getElementsByTagName('a'),
			l = as.length,
			m = p.getElementsByTagName('img').length,
			temp = document.createElement('span');
		temp.innerHTML = buildProfileImage(username,imgUrl,name);
		var newNode = temp.getElementsByTagName('a')[0];
		if(l === m){
		    p.appendChild(newNode);
		}else{
		    var old = as[m];		    
			old.parentNode.replaceChild(newNode,old);
		}
		if((b+1)%9 === 0){
		    addEmptyProfileImg(9);
		}
    }
    return (found); // NPF5
}
              
// NPF5 [BEGIN]
function removeProfileImage (username) {
    var removed = false;
    var existingNode = findUserInIllBeThere (username);
    if (existingNode) {
		var p = existingNode.parentNode;
		var b = bThereCount;
		p.removeChild(existingNode);
		if(b%9 === 0){
		    var a = p.getElementsByTagName('a')[b-1],
			    b = a.parentNode;
			while(a.nextSibling){
			    b.removeChild(a.nextSibling);
			}
		}else{
		    addEmptyProfileImg(1);
		}
        removed = true;
    }
    return (removed);
}
// NPF5 [END]
function setAlreadyBeThere(){
    var as = tn('a', $('profile_images'));
	for(var i=0, l=as.length; i<l; i++){
	    if(as[i].id === 'profile-a-'+loggedin_username){
		    alreadyThere = true;
			break;
		}
	}
}
function buildIllBeInList() {
    if(!attendees){return;}
    var l = attendees.length,
		numPerRow = 9,
		emptyNum = numPerRow - l%numPerRow;
    if (l > 1) {   // NPF5
        $('illbethere_count').innerHTML = '<b>' + l + '</b>' + ' say...';  // NPF5
    }
	var arr = [];
    while(l--) {
        var a = attendees[l];
		var screen_name = a.screen_name.toLowerCase();
		if(screen_name === loggedin_username){
		    alreadyThere = true;
		}
        arr[arr.length] = buildProfileImage(screen_name,changeProfileImg (a.profile_background_image_url, 'mini'),a.name);
    }
    $('profile_images').innerHTML = arr.reverse().join('');
	addEmptyProfileImg(emptyNum);
	attendees = null;
	return alreadyThere;
}

function setCommentAndRsvp(){
    var action;
	if(+resource.display_comment){
		action = 'add';
		comment.build();
	}else{
		action = 'remove';
	}
	cssjs(action,document.body,'show-comment');
	if(+resource.display_rsvp){
		action = 'add';
		setRsvp();
	}else{
		action = 'remove';
	}
	cssjs(action,document.body,'show-rsvp');
}
function singlepageUpdateCallback(){
    schmap.editable = schmap.editing = false;
	ss.medium = resource.photos && (resource.photos.indexOf('@') !== -1);log('ss.medium is ' + ss.medium);
	cssjs('remove',$('wrapper'),'editing');
	var postfix = '_content';
	var inputs = schmap.inputs,
		l = inputs.length,
		i = 0;
	for(var i=0, l=inputs.length; i < l; i++){
		var id = inputs[i],
		    elm = $(id + postfix);
		if(resource[id]){
		    if(id === 'text'){
			    elm.innerHTML = resource.decorated_text;
			}else{
			    elm.innerHTML = resource[id];
			}
			showElement(elm);
		}else{
		    hideElement(elm);
		}
	}
    setCommentAndRsvp();
	outputHashtag(resource.hashtag);
	goBackToNormal();
	edit.showSearch();
}
function cancelOwnEditing(){
    cssjs('remove',document.body,'changing-location');
	$('overlayparent').className = 'final-stage';
	cssjs('remove',$('re_search_box'),'at-search-result');
	edit.cancel();
}
(function(){
	if(resource.photos){
	    var arr = resource.photos.replace('@','').split(',');
		ss.medium = resource.photos.indexOf('@') !== -1;
		if(arr && arr.length > 0){
		    for(var i=0; i < arr.length; i++){
			    if(arr[i]){
					ss.init(arr, 'singlepage');
					break;
				}
			}
		}
	}
	var ownstaff = cookie.get('ownstaff');
	if(document.location.search === '?edit' && ownstaff){
	    gotoEdit();
		edit.showEditing();
	}
	setCommentAndRsvp();
	setupUserinfo();
	setup();
	if(document.location.search==='?a' && !ownstaff){
		var c = +resource.reachNum;
		if(c >= 0){
			if(isNaN(c)){c = 1;}
			c = c?(+c)+1 : 1;
			updateReachNum(c);
		}
	}
	document.re_search.onsubmit = function(){
		schmap.searchValue = this.elements.r_address.value;
		schmap.editable = true;
		schmap.finalStage = true;
		cssjs('add',document.body,'changing-location');
		$('cancel_search_1').onclick = cancelOwnEditing;
		doSearch(1);
		return false;
	};
})();
function preloadImages(){
    var url = document.location.pathname,
	    photos = resource.photos;
	if(photos){
	    photos = photos.replace('@','').split(',');
		var l = photos.length;
		while(l--){
		    if(photos[l]){
			    new Image().src = '/home2' + url.substring(0,3) + url + '/photos/' + photos[l];
			}
		}
	}
}
function singlepagecallback(){
    comment.checkPostComment();
	setAlreadyBeThere();
	setMeTooText();
}
window.onload = function(){
    if(ss.length>1 && !ss.medium){
	    preloadImages();
	}
	
	if (typeof justLoggedIn != 'undefined' && justLoggedIn) {
	    setupCrossDomainCookies();
	    if (typeof tcode != 'undefined') {
	    
	        if (tcode == 'T-SM-COM' || tcode == 'T-SM-RSVP') {
	            comment.checkPostComment();
	            setAlreadyBeThere();
	            setMeTooText();
	        }
	        else if (tcode == 'T-EDU') {
                    gotoEdit();
                    edit.showEditing();
	        }
	        else if (tcode == 'T-EDU-TWEET') {
	            posttweet.tweetFromCookie();
	        }
	    }
	}
};



