// - ///////////////////////////////////////////////////////////////////////
// - PD FORUM MODULE
// - ///////////////////////////////////////////////////////////////////////
pdForumModule.prototype._user;
pdForumModule.prototype._transport;
pdForumModule.prototype._channelId = 'site.forums';
pdForumModule.prototype._editorId = '';
pdForumModule.prototype._postId = '';

function pdForumModule() {}

pdForumModule.prototype.initialize = function(transport, user){
  	//this function is called back during module registration
	this._transport = transport;
	this._user = user;
	
	var me = this;
	
	//observe clicks on all reply/quote links, submit / cancel buttons, etc.
    $$('a.post-reply-link', 'a.post-quote-link').each(function(link){link.observe('click', me.onReplyQuoteClick.bind(me));});	
    $$('button.post-reply-submit').each(function(button){button.observe('click', me.onPostSaveClick.bind(me));});
    $$('button.post-reply-cancel').each(function(button){button.observe('click', me.onPostCancelClick.bind(me));});
    $$('.post-sub-header-actions-share a').each(function(link){link.observe('click', me.onPostShareClick.bind(me));});
    
    //observe follow twitter link clicks
    $$('.post-sub-header-author-twitter').each(function(link){link.observe('click', me.onOpenTwitterFeedClick.bind(me));});
    $$('.post-options-twitter-close').each(function(link){
		link.observe('click', me.onCloseTwitterFeedClick.bind(me));
    });

	//add voting
	$$('.post-vote-body').each(function(div){
		var voteResponse = new Element('span');
		var voteReportTxt = new Element('span', {style : 'margin-right:10px;'}).update('Report offensive post!');
		var voteReport = new Element('a', {href:'#', title:'Report this post as offensive'});
		voteReport.className = 'post-vote-report';
		var postId = me.getPostIdFromElementId(div.identify());
		voteReport.observe('click', me.onVoteClick.bindAsEventListener(me,-1, postId));		

		div.appendChild(voteResponse);		
		div.appendChild(voteReport);
		div.appendChild(voteReportTxt);				
	});
	
	//configure user in the sidebar
	if(user.isLoggedIn()){
		$('user-name').update('Welcome back ' + user.getDisplayName());
		$('user-profile').href = user.getProfileEditUrl() + '#personal';
		$('user-image').src = user.getAvatar();
		$('user-profile-edit').href = user.getProfileEditUrl() + '#personal';		
		$('user-logged-in').show();
	}else{
		$('user-logged-out').show();
	}
	
	//initialize phonedogs editors carousel if available
	if($('phonedogs-wrapper')){
		new Carousel($('phonedogs-scroller'),
			$$('#phonedogs-scroller .carousel-phonedogs-slide'),
			$$('#phonedogs-wrapper a.carousel-jumper','#phonedogs-wrapper a.carousel-control'),	{duration: 1,frequency: 5,selectedClassName: 'selected',auto: true}
		);	
	}	
}

pdForumModule.prototype.onOpenTwitterFeedClick = function(event){
	Event.stop(event);
	var link = Event.element(event);
	var postId = this.getPostIdFromElementId(link.identify());
	var pane = $('post-share-twitter-' + postId);
	
	if(pane.style.display == 'none'){		
		pane.show();	
		var username = $('post-options-tweets-' + postId).readAttribute('username');
	
		getTwitters('post-options-tweets-' + postId, { 
			id: username, 
			count: 10, 
			enableLinks: true, 
			ignoreReplies: true, 
			clearContents: true,
			template: '"%text%" <a class="post-options-tweets-time" target="_blank" href="http://twitter.com/%user_screen_name%/statuses/%id%/">%time%</a>'
		});
		
		pd_globalSiteFramework.trackEvent('Posts', 'Twitter - open', username);
	}			
}

pdForumModule.prototype.onCloseTwitterFeedClick = function(event){
	Event.stop(event);
	var link = Event.element(event);
	var postId = this.getPostIdFromElementId(link.identify());
	var pane = $('post-share-twitter-' + postId);
	pane.hide();
}

pdForumModule.prototype.onReplyQuoteClick = function(event){
    Event.stop(event);    
    var linkId = Event.element(event).identify();
    var parentId = this.getPostIdFromElementId(linkId);
    var isQuote = (linkId.split('-')[0] == 'quote') ? true : false;
    var referrer = window.location.pathname
    var pane = $('post-reply-' + parentId); 
    var user = $('post-reply-user-' + parentId);
    
    //store quoting in hidden input
    $('post-reply-isquote-' + parentId).value = isQuote;
    
    //if we have a previous post form shown (e.g. we have a postid)
    //then hide the previous form first before continuing
    if(this._postId != ''){
        this.hidePostForm(this._postId);
    }
    
    //keep reference to current post we're working with
    this._postId = parentId;
	
    // build the user login / registration information 
	// if we have a user that is currently not logged in	
	if(!this._user.isLoggedIn()){		
		user.update();
		
		var userNewWrapper = new Element('div', {'class':'post-reply-userinfo clearfix', id:'post-reply-userinfo-new'});			
		var userNewInfoTxt = new Element('div', {'class':'post-reply-userinfotxt'}).update('First time posting? A confirmation e-mail will be sent to you after submitting.');

		var userNewInfo1 = new Element('div', {'class':'post-reply-userinfo1'});
		userNewInfo1.appendChild(new Element('b').update('Display name:'));
		userNewInfo1.appendChild(new Element('input', {type:'text', id:'user_new_name', maxlength:20}));
		
		var userNewInfo2 = new Element('div', {'class':'post-reply-userinfo2'});
		userNewInfo2.appendChild(new Element('b').update('Email:'));
		userNewInfo2.appendChild(new Element('input', {type:'text', id:'user_new_email', maxlength:80}));
		
		var userNewInfoToggle = new Element('div', {'class':'post-reply-userinfo-toggle'});
		userNewInfoToggle.appendChild(new Element('span').update('Posted before or have a PhoneDog account? '));
		userNewInfoToggle.appendChild(new Element('a', {href : '#', id:'post-reply-userinfo-linknew', style:'font-weight:bold;'}).update('Sign in here')).observe('click',this.onSigninClick.bindAsEventListener(this));			
		userNewWrapper.appendChild(userNewInfoTxt);
		userNewWrapper.appendChild(userNewInfo1);
		userNewWrapper.appendChild(userNewInfo2);
		userNewWrapper.appendChild(userNewInfoToggle);			

		var userExistingWrapper = new Element('div', {'class':'post-reply-userinfo clearfix', id:'post-reply-userinfo-existing', style:'display:none;' });
		var userExistingInfoTxt = new Element('div', {'class':'post-reply-userinfotxt'}).update('Returning members, please enter your username and password.');

		var userExistingInfo1 = new Element('div', {'class':'post-reply-userinfo1'});
		userExistingInfo1.appendChild(new Element('b').update('Username:'));
		userExistingInfo1.appendChild(new Element('input', {type:'text', id:'user_existing_username', maxlength:20}));
		
		var userExistingInfo2 = new Element('div', {'class':'post-reply-userinfo2'});
		userExistingInfo2.appendChild(new Element('b').update('Password:'));
		userExistingInfo2.appendChild(new Element('input', {type:'password', id:'user_existing_password', maxlength:20}));			
		
		var userExistingInfoToggle = new Element('div', {'class':'post-reply-userinfo-toggle'});
		userExistingInfoToggle.appendChild(new Element('span').update('Posted before or have a PhoneDog account? '));
		userExistingInfoToggle.appendChild(new Element('a', {href : '#', id:'post-reply-userinfo-linkexisting', style:'font-weight:bold;'}).update('First-time poster')).observe('click',this.onSigninClick.bindAsEventListener(this));
		userExistingInfoToggle.appendChild(new Element('span').update(', or '));
		userExistingInfoToggle.appendChild(new Element('a', {id:'post-reply-userinf-forgot', href:'/community/login.aspx'}).update('forgot your login?'));												
		userExistingWrapper.appendChild(userExistingInfoTxt);
		userExistingWrapper.appendChild(userExistingInfo1);
		userExistingWrapper.appendChild(userExistingInfo2);
		userExistingWrapper.appendChild(userExistingInfoToggle);
		
		user.appendChild(userNewWrapper);
		user.appendChild(userExistingWrapper);
	}
	
	if(typeof(tinyMCE) == 'object'){
        if (this._editorId.length > 0){
            tinyMCE.execCommand('mceFocus', false, this._editorId);
            tinyMCE.execCommand('mceRemoveControl', false, this._editorId);        
        }
	
	    //save the new editor id
	    this._editorId = 'post-reply-body-' + parentId;
	    
        tinyMCE.init({
            mode : 'none', 
            theme : 'advanced',
            width: '100%',
            height: '300px',
            plugins : '',
            theme_advanced_buttons1 : 'link,unlink,bold,italic,justifyright,bullist,numlist,undo,redo',
            theme_advanced_buttons2 : '',
            theme_advanced_buttons3 : '',
            theme_advanced_buttons4 : '',
            theme_advanced_toolbar_location : 'top',
            theme_advanced_toolbar_align : 'left',
            theme_advanced_resizing : true,
            relative_urls: false,
            media_use_script: true,
            spellchecker_rpc_url: pd_spellcheckURL
        });
        
        tinyMCE.execCommand('mceAddControl', false, this._editorId);        
    }    
    
    pane.show();
    pane.scrollTo();
    pd_globalSiteFramework.trackEvent('Posts', 'Post form - show');
}

pdForumModule.prototype.isEmail = function(s){
	var good="@_-.:/ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	var upper=s.toUpperCase()
	var valid=true;	
	for(x=0; x>s.length; x++){c=upper.charAt(x);for(y=0; y<good.length; y++){if(c==good.charAt(y)){break;}}if(y==good.length){valid=false;break;}}	
	if (!valid || s.length < 7 || s.indexOf("@") == "-1" || s.indexOf(".") == "-1" || s.indexOf("@") != s.lastIndexOf("@")) {return (false);}else{return (true);}
}

pdForumModule.prototype.isValidUsername = function(s){
	var goodCharacters = ['@','_','-','.','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9'];
	var usernameUpper = s.toUpperCase();
	var isValid = true;
	for(var x=0; x<usernameUpper.length; x++){if(goodCharacters.indexOf(usernameUpper.charAt(x)) == -1){isValid = false;}}
	return isValid;
}

pdForumModule.prototype.showError = function(msg){
	$('post-reply-errors-' + this._postId).update(msg);
	$('post-reply-errors-' + this._postId).show();
	pd_globalSiteFramework.trackEvent('Posts', 'Error', msg);
}

pdForumModule.prototype.onSigninClick = function(event){
    Event.stop(event);
	var element = Event.element(event);
	var id = element.identify();	

	//reset all fields
	$('user_new_name').value = '';
	$('user_new_email').value = '';
	$('user_existing_username').value = '';
	$('user_existing_password').value = '';	

	if(id == 'post-reply-userinfo-linknew'){
		$('post-reply-userinfo-new').hide();
		$('post-reply-userinfo-existing').show();
		pd_globalSiteFramework.trackEvent('Posts', 'Toggle signin - existing');
	}else{
		$('post-reply-userinfo-existing').hide();	
		$('post-reply-userinfo-new').show();
		pd_globalSiteFramework.trackEvent('Posts', 'Toggle signin - new');
	}
}

pdForumModule.prototype.onPostSaveClick = function(event){
    Event.stop(event);
    
    //these are always available
	var submit = Event.element(event);
	var comment = tinyMCE.get(this._editorId).getContent();
	var isnewuser = ($('post-reply-userinfo-new') && $('post-reply-userinfo-new').style.display == 'none') ? false : true;
	var isQuote = $('post-reply-isquote-' + this._postId).value;
	var sectionId = $('post-reply-sectionid-' + this._postId).value;
	var parentId = $('post-reply-parentid-' + this._postId).value;
	var threadId = $('post-reply-threadid-' + this._postId).value;	
	var subscriptionId = $('post-reply-subscription-sel-' + this._postId).value;
	
	var postName = ($('post-reply-name-' + this._postId)) ? $('post-reply-name-' + this._postId).value : '';
	var name = '';
	var email = '';
	var username = '';
	var password = '';
	var isLive = false;
	
	// these are only available if we are not logged in
	if(!this._user.isLoggedIn()){
		var new_name = $('user_new_name');
		var new_email = $('user_new_email');
		var existing_username = $('user_existing_username');
		var existing_password = $('user_existing_password');
	
		if(isnewuser){
			if(new_name.value==''){this.showError('Please enter your desired display / user name');new_name.focus();return false;}
			if(new_email.value==''){this.showError('Please enter your email address');new_email.focus();return false;}
			if(new_name.value.length<6){this.showError('Your display name must be a minimum of 6 characters');new_name.focus();return false;}
			if(!this.isValidUsername(new_name.value)){this.showError('Display name contains invalid characters - please use only a combination of letters, numbers, and the characters @._ but no spaces');new_name.focus();return false;}
			if(!this.isEmail(new_email.value)){this.showError('Your email address appears to be invalid - Please double-check it and try again.');new_email.focus();return false;}
			
			username = '';
			password = '';
			name = new_name.value;
			email = new_email.value;
		}else{
			if(existing_username.value==''){this.showError('Please enter your username');existing_username.focus();return false;}
			if(existing_password.value==''){this.showError('Please enter your password');existing_password.focus();return false;}		
			
			name = '';
			email = '';
			isLive = true;
			username = existing_username.value;
			password = existing_password.value;					
		}
	}else{
		isLive = true;
	}
	
	//if we dont' have a threadid (e.g. starting a new thread)
	//then also validate that we have a name entered for this thread
	if(threadId == 0 && postName == ''){
	    this.showError('Please enter a name');
	    return false;
	}
	
	//validate entering a proper comment	
	if(comment==''){
	    this.showError('Please enter your post');
	    return false;
	}	
	
	submit.update('Submitting');
	submit.disabled = true;
	
	var request = {
		userNewName:name,
		userNewEmail:email,
		userExistingUsername:username,
		userExistingPassword:password,		
		pageTitle:postName,
		isQuote:isQuote,
		forumId:sectionId,
		parentId:parentId,
		threadId:threadId,
		subscriptionId:subscriptionId,
		text:comment	
	};
	
	this._transport.transmitRequest(this._channelId, 'setpost', request, this.postSaved.bindAsEventListener(this, submit, isLive, username, password));        
    
}

pdForumModule.prototype.postSaved = function(objResponse, submit, isLive, username, password){
	// Present user error here based on whether we have a result that's "Ok"
	// or a possible error wich would indicate a user registration or signin problem
	if(objResponse.result == 'Ok'){
		$('post-reply-errors-' + this._postId).update();
		$('post-reply-errors-' + this._postId).hide();
		this.hidePostForm();		
		
		if(isLive == true){
			$('post-reply-success-' + this._postId).update('<b>Thanks for submitting your post.</b><p/>Your post should appear momentarily!');
			$('post-reply-success-' + this._postId).show();
			pd_globalSiteFramework.trackEvent('Posts', 'Saved - existing user');
			
			//if we have a username/password then also log in the user - no callback needed
			if(username.length > 0 && password.length > 0){
				pd_globalSiteFramework.login(username, password, null);
			}
		}else{		
			$('post-reply-success-' + this._postId).update('<b>Thanks for submitting your post.</b> Please check your email inbox for instructions on how to activate your account and post.');
			$('post-reply-success-' + this._postId).show();
			pd_globalSiteFramework.trackEvent('Posts', 'Saved - new user');
		}
	}else{
		//show the error message and enable the submit button again
		$('post-reply-errors-' + this._postId).update(objResponse.errorMessage);	
		$('post-reply-errors-' + this._postId).show();
		submit.update('Submit');
		submit.disabled = false;
		
		pd_globalSiteFramework.trackEvent('Posts', 'Error', objResponse.errorMessage);			
	}    
}

pdForumModule.prototype.onPostCancelClick = function(event){
    Event.stop(event);
    this.hidePostForm();
}

pdForumModule.prototype.hidePostForm = function(){
    $('post-reply-' + this._postId).hide();
    pd_globalSiteFramework.trackEvent('Posts', 'Post form - hide');
}

pdForumModule.prototype.onPostShareClick = function(event){
    Event.stop(event);
    var element = Event.element(event);
    var id = this.getPostIdFromElementId(element.identify());
    var pane = $('post-share-header-' + id);
    
    //save the post id
    this._postId = id;
    
    if(pane.style.display == 'none'){
        if(pane.childElements().length == 0){
            var title = escape(window.document.title);
            var link = escape($('permalink-' + id).href);
        
            var shareLinks = new Element('div').addClassName('post-share-links');
            shareLinks.appendChild(new Element('h4').update('Share with your friends on:'));
            var links = new Element('ul');
            var linkMySpace = new Element('a', {target : '_blank', href : 'http://www.myspace.com/Modules/PostTo/Pages/?t=' + title + '&u=' + link + '&l=1'}).update('MySpace');
            var linkFacebook = new Element('a', {target : '_blank', href : 'http://www.facebook.com/sharer.php?u=' + link + '&t=' + title}).update('Facebook');
            var linkTwitter = new Element('a', {target : '_blank', href : 'http://twitter.com/home?status=Check%20this%post%20out%20--%20' + title + '%20' + link + ''}).update('Twitter');
            var linkLive = new Element('a', {target : '_blank', href : 'http://spaces.live.com/BlogIt.aspx?Title=PhoneDog.com%20-%20' + title + '&amp;SourceURL=' + link}).update('Live Spaces');
            var linkBebo = new Element('a', {target : '_blank', href : 'http://www.bebo.com/c/share?Url=' + link + '&amp;Title=' + title}).update('Bebo');
            var linkHi5 = new Element('a', {target : '_blank', href : 'http://www.hi5.com/friend/checkViewedVideo.do?t=' + title + '&amp;url=' + link + '&amp;embeddable=true&amp;simple=true'}).update('hi5');
            links.appendChild(new Element('li')).appendChild(linkMySpace);
            links.appendChild(new Element('li')).appendChild(linkFacebook);
            links.appendChild(new Element('li')).appendChild(linkTwitter);
            links.appendChild(new Element('li')).appendChild(linkLive);
            links.appendChild(new Element('li')).appendChild(linkBebo);
            links.appendChild(new Element('li')).appendChild(linkHi5);
            shareLinks.appendChild(links);        
            pane.appendChild(shareLinks);
            
            var shareEmail = new Element('div').addClassName('post-options-share-email');
            shareEmail.appendChild(new Element('h4').update('E-mail this post to someone:'));
            
            var loggedIn = new Element('div', {id : 'shareEmailLoggedIn-' + id, 'style' : 'display:none;'});
            var form = new Element('form', {id : 'shareEmailForm-' + id});
            form.appendChild(new Element('input', {type : 'hidden', id : 'shareContentId-' + id, value : id}));
            
            var col1 = new Element('div').addClassName('post-share-email-col');
            var emailLbl = new Element('label').update('E-mail address');
            var email = new Element('input', {type : 'text', maxlength : 50, id : 'shareEmailTo-' + id, tabindex : 1});
            var button = new Element('button', {id : 'shareEmailSend-' + id, tabindex : 3}).update('Send email');
            button.observe('click', this.onPostEmailClick.bind(this));
            col1.appendChild(emailLbl);
            col1.appendChild(email);
            col1.appendChild(button);
            form.appendChild(col1);
            
            var col2 = new Element('div').addClassName('post-share-email-col');
            var msgLbl = new Element('label').update('Message (optional)');
            var msg = new Element('textarea', {id : 'shareEmailMessage-' + id, tabindex : 2});
            col2.appendChild(msgLbl);
            col2.appendChild(msg);        
            form.appendChild(col2);
            
            loggedIn.appendChild(form);
            shareEmail.appendChild(loggedIn);
            pane.appendChild(shareEmail);
            
            var notLoggedIn = new Element('div', {id : 'shareEmailNotLoggedIn-' + id, 'style' : 'display:none;margin-bottom:10px;'}).update('Please log in to email this post');
            var emailsent = new Element('div', {id : 'shareEmailSent-' + id,'style' : 'display:none;margin-bottom:10px;'}).update('Thanks for sharing!');
            shareEmail.appendChild(notLoggedIn);
            shareEmail.appendChild(emailsent);            
            
            var bDiv = new Element('div').addClassName('post-share-close');
            var bBase = new Element('div').addClassName('button-base post-share-close clearfix').setStyle({width: '100px'});
            var bOuter = new Element('div').addClassName('button-base-outer-box');
            var bInner = new Element('div').addClassName('button-base-inner-box');
            var bPos = new Element('div').addClassName('button-base-pos');
            var bShadow = new Element('div').addClassName('button-base-top-shadow');
            var bContent = new Element('div').addClassName('button-base-content').setStyle({width: '100px'});
            var bContentSpan = new Element('span');
            
            var closeLink = new Element('a', {href : '#', id : 'post-close-' + id}).update('Close');
            closeLink.observe('click', this.onPostShareCancelClick.bind(this));
            
            bContentSpan.appendChild(closeLink);
            bContent.appendChild(bContentSpan);
            bPos.appendChild(bShadow);
            bPos.appendChild(bContent);
            bInner.appendChild(bPos);
            bOuter.appendChild(bInner);
            bBase.appendChild(bOuter);
            bDiv.appendChild(bBase);
            
            pane.appendChild(bDiv);
            
            //if the user is logged in then show the email form
            //otherwise show the message letting them know they should log in
            if(this._user.isLoggedIn()){
                $('shareEmailLoggedIn-' + id).show();
            }else{
                $('shareEmailNotLoggedIn-' + id).show();
            }
        }
    
        pane.show();
    }    
}

pdForumModule.prototype.onPostShareCancelClick = function(event){
    Event.stop(event);
    var link = Event.element(event);
    var id = this.getPostIdFromElementId(link.identify());
    $('post-share-header-' + id).hide();
}

pdForumModule.prototype.onPostEmailClick = function(event){
	Event.stop(event);
	var email = $('shareEmailTo-' + this._postId);
	var message = $('shareEmailMessage-' + this._postId);
	
	if(email.value.length == 0){
		alert('Please enter an email address');
		email.focus();
	}else if(!this.isEmail(email.value)){
		alert('The e-mail address appears to be invalid\n\nPlease double-check it and try again');
		email.focus();
	}else{
		$('shareEmailSend-' + this._postId).disabled = true;
		var request = {
			contentId : this._postId,
			email : email.value,
			message : message.value.stripScripts().stripTags()
		};
		this._transport.transmitRequest('site.shared', 'shareemailpost', request, this.postEmailed.bind(this));	
	}
}

pdForumModule.prototype.postEmailed = function(objResponse){
	$('shareEmailLoggedIn-' + this._postId).hide();
	$('shareEmailSent-' + this._postId).show();
	pd_globalSiteFramework.trackEvent('Posts', 'Email - sent');
}

pdForumModule.prototype.onVoteClick = function(event, vote, postId){
	Event.stop(event);
	var element = Event.element(event);
	var indicator = element.up().down('span');
	var saveVote = true;
	var request = {
		contentId : postId,
		rating : vote
		//referrerUrl : $('cmt_referrerurl').value
	};
	
	// make the user confirm reporting a comment
	if(vote == -1 && !confirm('Are you sure you want to report this post?')){saveVote = false;}	
	if(saveVote){	
		this._transport.transmitRequest('site.shared', 'setrating', request, this.onVoteSaveCompleted.bindAsEventListener(this, element, vote, indicator));			
	}
}

pdForumModule.prototype.onVoteSaveCompleted = function(objResponse, element, vote, indicator){
	// -1 = indicates comment was reported
	// 0 = indicates previously voted
	// otherwise returns new rating of comment
	if(objResponse.rating == -1){
		indicator.update('Post reported!');
	}else if(objResponse.rating == 0){
		indicator.update('You already voted');
	}else{
		if(vote == 1){
			indicator.update('You voted down');
		}else{
			indicator.update('You voted up');
		}		
		pd_globalSiteFramework.trackEvent('Posts', 'Voted', vote);
		window.setTimeout(function() {indicator.update('Thanks for voting') }, 2000);
	}
	
	//hide the voting links
	element.up().select('a').each(function(link){link.hide();});
}

//id of the post we're working with is always the last item
//in the id string given that they are split on the dash
pdForumModule.prototype.getPostIdFromElementId = function(id){
    var split = id.split('-');
    return split[split.length - 1];
}

