/*
 * Copyright 2011 1fb.net Financial Services. This document may not be reproduced, distributed or used in any manner
 * whatsoever without the expressed written permission of 1st Financial Bank USA.
 */

/**
 * @fileOverview Define the NewsFeed function.
 * @author Vincent Cai, Kevin Shen
 * @version 1.5, 2011-08-25
 * @since 4.70, 2008-2-28 
 */

//News Feed In Which Page
var NEWSFEED_IN_WHICH_PAGE = null;
//News Feed Item Quantity
var NEWSFEED_ITEM_QUANTITY = null;
//Newsfeed item Display Interval
var NEWSFEED_ITEM_DISPLAY_INTERVAL = null;
//Newsfeed Transition Speed
var NEWSFEED_TRANSITION_SPEED = null;
var FADE_OUT_DELAY = null;
var ONE_MIN = 60 * 1000;
var ADD_TYPE = 1;
var UPDATE_TYPE = 2;
var STATUS_TYPE = 3;
var ITEM_CATEGORY = "newsfeedItemCategory";
var COUNT_CATEGORY = "newsfeedCounterCategory";
var PROMO_CATEGORY = "newsfeedPromoCategory";
var POSITION_ITEM = "newsfeedPositionCategory";
var showLightBox = null;

var STATUS_MESSAGE = ["", "has decided to attend", "was accepted at", "was deferred at", "was denied at", "", "was wait-listed at", "has withdrawn an application to", "applied to", ""];

/**
 * Create a Class of Newsfeed
 * @constructor NewsFeed
 * @this {NewsFeed}
 * @param {Object}		ele				Dom object which will contain the Newsfeed items
 * @param {Boolean}		isStandalone	the param to decide the type of Newsfeed is standalone or not   
 *
 */

var NewsFeed = new Class({
	initialize: function(ele, isStandalone){
		this.wrap = $(ele);
		this.hasPromo = false;
		this.replace = false;
		this.items = this.wrap.getElements("li");
		this.position = 0;
		this.isStandalone = isStandalone || false;
		this.bound = {			
			"updateItem": this.updateItem.bind(this)
		};
		this.serverTime = parseFloat($('serverTime').getText());
		this.profileHref = $('profileHref').getText().trim();
		this.resultHref = $('resultHref').getText().trim();
		this.trackerfeed = $('trackerfeed');
		this.trackerfeed.setStyle('display', 'block');
		
		try {
			NEWSFEED_IN_WHICH_PAGE = $('newsfeed_config').getElement('.newsfeed_in_which_page').getText();
		}
		catch(e) {
			NEWSFEED_IN_WHICH_PAGE = 'admission_tracker_form';
		}
		try {
			NEWSFEED_ITEM_QUANTITY = parseInt($('newsfeed_config').getElement('.newsfeed_item_quantity').getText());
		}
		catch(e) {
			NEWSFEED_ITEM_QUANTITY = 10;
		}
		try {
			NEWSFEED_ITEM_DISPLAY_INTERVAL = parseInt($('newsfeed_config').getElement('.newsfeed_item_display_interval').getText());
		}
		catch(e) {
			NEWSFEED_ITEM_DISPLAY_INTERVAL = 4;
		}
		try {
			NEWSFEED_TRANSITION_SPEED = parseInt($('newsfeed_config').getElement('.newsfeed_transition_speed').getText());
		}
		catch(e) {
			NEWSFEED_TRANSITION_SPEED = 2;
		}
		FADE_OUT_DELAY = NEWSFEED_TRANSITION_SPEED * 1000 / 2;
		
		this.initItems();		
	},	
	
	/**
	 * initialize NewsFeed items
	 * @this {NewsFeed}
	 */	
	initItems: function(){
		this.items = this.wrap.getElements("li");
		if(this.items.length > 0) {
			//already initialize newsfeed items
			return;
		}
		AdmissionNewsFeedService.getInitialItems(NEWSFEED_ITEM_QUANTITY, 
			dwrCallback(null, {callback: this.addItems.bind(this)})
		);
	},	
	
	/**
	 * Update NewsFeed item
	 * @this {NewsFeed}
	 */	
	updateItem: function(){
		if(this.beReplace()){	
			this.setPromoFlag(this.position);
			var cb = dwrCallback(null, {callback: function(result) {this.nextRequest(this.replaceItem.bind(this), result)}.bind(this), 
					errorHandler: function(err) {this.updateItem.delay(NEWSFEED_ITEM_DISPLAY_INTERVAL, this)}.bind(this)});
			if(window.navigator.userAgent.indexOf('MSIE') > 0) {
				DWREngine.setRpcType(3);
				delete cb['timeout'];
				AdmissionNewsFeedService.getNextItem(this.hasPromo, this.position, cb);
				DWREngine.setRpcType(1);
			}
			else {
				AdmissionNewsFeedService.getNextItem(this.hasPromo, this.position, cb);
			}
		}
		else {
			var cb = dwrCallback(null, {callback: function(result) {this.nextRequest(this.addItem.bind(this), result)}.bind(this), 
					errorHandler: function(err) {this.updateItem.delay(NEWSFEED_ITEM_DISPLAY_INTERVAL, this)}.bind(this)});
			if(window.navigator.userAgent.indexOf('MSIE') > 0) {
				DWREngine.setRpcType(3);
				delete cb['timeout'];
				AdmissionNewsFeedService.getNextItem(this.hasPromo, this.position, cb);
				DWREngine.setRpcType(1);
			}
			else {
				AdmissionNewsFeedService.getNextItem(this.hasPromo, this.position, cb);
			}
		}		
	},
	
	/**
	 * Judge whether NewsFeed item can start update action according to the actual newsfeed number
	 * @this {NewsFeed}
	 */	
	beReplace: function(){
		if(!this.replace){
			this.items = this.wrap.getElements("li");
			if(NEWSFEED_ITEM_QUANTITY == this.items.length) {
				this.replace = true;
			}
			else {
				this.position = this.items.length;
			}
		}
		return this.replace;
	},
	
	/**
	 * the fade in effect of newItem
	 * @this {NewsFeed}
	 * @param {Object}		newItemElement	object of each new newsfeed item
	 * @param {Function}	fn				the function called during fade in
	 * @param {Int}			delayTime		the delay time after fade out
	 */	
	fadein: function(newItemElement, fn, delayTime){
		(function(){
			fn();
			var fadein = new Fx.Style(newItemElement, 'opacity',{duration:FADE_OUT_DELAY});
			fadein.start('1');
		}).delay(delayTime, this);
	},	
	
	/**
	 * set Promo Flag
	 * @this {NewsFeed}
	 * @param {Int}		position	the current position of each newsfeed item
	 */	
	setPromoFlag: function(position){
		try {
			if(this.items[position] && this.items[position].getElement && this.items[position].getElement("a")) {
				if(this.items[position].getElement("a").getText() == "Admissions Profile") {
					this.hasPromo = false;
				}
				for(var i = 0; i < this.items.length; i ++) {
					if(i == position) continue;
					var item = this.items[i];
					if(item.getElement("a").getText() == "Admissions Profile") {
						this.hasPromo = true;
						break;
					}
				}
			}
		} catch(e) {}
	},
	
	/**
	 * Replace newsfeed item
	 * @this {NewsFeed}
	 * @param {Int}		position	the position of newsfeed item
	 */
	replaceItem: function(newsfeedItem){
		if(newsfeedItem && newsfeedItem != null){
			// fade out the existed item.				
			var fadeout = new Fx.Style(this.items[this.position], 'opacity',{duration:FADE_OUT_DELAY});
			fadeout.start('0');
			var tempPosition = this.position;			
			// set the position
			this.position = this.position + 1;
			if(this.position >= NEWSFEED_ITEM_QUANTITY) {
				this.position = 0;
			}
			try {
				if(this.items[tempPosition]) {
					this.fadein(this.items[tempPosition], function(){
						//replace the new item to the existed item.
						if(this.items[tempPosition].hasClass('btmclear')){
							this.items[tempPosition].addClass('btmclear');
						}				
						this.items[tempPosition].empty();		
						this.fillNewItemElement(this.items[tempPosition], newsfeedItem);
						this.updateItem();
					}.bind(this), FADE_OUT_DELAY);
				}
			}
			catch(e) {}
		}
		else {
			this.updateItem();
		}
	},
	
	/**
	 * Add newsfeed item
	 * @this {NewsFeed}
	 * @param {Object}	newsfeedItem	Object of newsfeedItem
	 */
	addItem: function(newsfeedItem){
		if(newsfeedItem && newsfeedItem != null){
			if(this.items.length > 0 && this.items[this.items.length - 1]) {
				this.items[this.items.length - 1].removeClass('btmclear');
			}
			// create the new item
			var newItemElement=new Element('li');	
			newItemElement.injectInside(this.wrap);
			this.fillNewItemElement(newItemElement, newsfeedItem);	
			// add the item to the bottom of the newsfeed.
			newItemElement.addClass('btmclear');
			this.fadein(newItemElement, function(){
				this.updateItem();
			}.bind(this), FADE_OUT_DELAY);			
		}
		else {
			this.updateItem();
		}
		if(this.position == NEWSFEED_ITEM_QUANTITY - 1) {
			this.position = 0;
		}
	},
	
	/**
	 * Add NewsFeed items
	 * @this {NewsFeed}
	 * @param {Object}	newsFeedItems	the object containing all the newsFeedItems
	 */	
	addItems: function(newsFeedItems){
		if(newsFeedItems.length > 0) {
			var lastItem = newsFeedItems[newsFeedItems.length - 1];
			if(lastItem.categoryType == POSITION_ITEM) {
				this.position = lastItem.itemId;
				if(this.position >= NEWSFEED_ITEM_QUANTITY) {
					this.position = 0;
				}
				newsFeedItems = newsFeedItems.slice(0, -1);
			}
			
			for(var i = 0; i < newsFeedItems.length; i ++) {
				var newsfeedItem = newsFeedItems[i];
				if(newsfeedItem != null) {					
					var newItemElement=new Element('li');
					if(this.items.length == newsFeedItems.length - 1){
						newItemElement.addClass('btmclear');
					}
					newItemElement.injectInside(this.wrap);
					this.fillNewItemElement(newItemElement, newsfeedItem);
					this.items = this.wrap.getElements("li");
				}
			}
			for(var j=0; j< newsFeedItems.length; j++){
				if(this.items[j]) this.items[j].setStyle('opacity','1');
			}
		}
		
		//adjust the size of the newsfeed pop-up window
		if(this.isStandalone) {
			var newsfeedwrap = $$('.newsfeed')[0];
			var height = window.newsfeedPopupHeight ? window.newsfeedPopupHeight : (680 > window.screen.availHeight ? window.screen.availHeight : 680);
			var offsetY = 0;
			offsetY = newsfeedwrap.offsetHeight + 40 - height;
			var newHeight = height + offsetY;
			var miniHeight = 600;
			if(window.screen.height < 800) miniHeight = 650;			
			if(window.navigator.userAgent.indexOf('MSIE') != -1) miniHeight = 600;
			if(newHeight < miniHeight && this.items.length > 9) {
				offsetY = miniHeight - height;
			}					
			var left_p = (window.screenLeft) ? window.screenLeft : window.screenX;
			var top_p = (window.screenTop) ? window.screenTop : window.screenY;
			var offsetYM = top_p - offsetY / 2;
			top_p = top_p - offsetY / 2;
			if(top_p < 0) top_p = 0;
			window.moveTo(left_p, top_p);
			window.resizeBy(0, offsetY);
		}
		
		this.startTiming();
		this.updateItem();
	},	
	
	/**
	 * Fill each of new newsFeed item into Dom element
	 * @this {NewsFeed}
	 * @param {Dom Object}	newItemElement	each placeholder of Dom Object
	 * @param {Object}	newsfeedItem	object of each newsFeedItem
	 */	
	fillNewItemElement: function(newItemElement, newsfeedItem){		
		switch (newsfeedItem.categoryType) {
			case ITEM_CATEGORY:
				this.generateItemElement(newItemElement, newsfeedItem);
				break;
			case COUNT_CATEGORY:
				this.generateCounterElement(newItemElement, newsfeedItem);
				break;
			case PROMO_CATEGORY:
				this.generatePromoElement(newItemElement);
				break;
		}
		newItemElement.setStyle('opacity','0');
		return newItemElement;
	},	
	
	/**
	 * generate item element which belongs to ITEM_CATEGORY
	 * @this {NewsFeed}
	 * @param {Dom Object}	newItemElement	each placeholder of Dom Object
	 * @param {Object}	newsfeedItem	object of each newsFeedItem
	 */
	generateItemElement: function(newItemElement, newsfeedItem){
		var htmlString = '';
		var chars = newsfeedItem.profileName.trim().split("");				
		var newTxt = chars.join("<wbr></wbr>");
		var profileLink = this.composeTheLink(this.profileHref+'?profileName='+newsfeedItem.profileName, newTxt, newsfeedItem.profileName);
		var classYear = newsfeedItem.collegeClass;
		if(newsfeedItem.collegeClass == '99'){
			classYear = "Other"
		}
		var classYearLink = DEFAULT_YEAR;
		if(newsfeedItem.collegeClass != null && newsfeedItem.collegeClass != "" && newsfeedItem.collegeClass != '99' && newsfeedItem.countType != STATUS_TYPE){
			classYearLink = newsfeedItem.collegeClass
		}
		var collegeLink = this.composeTheLink(this.resultHref+'?schoolId='+newsfeedItem.schoolId+'&classYear='+classYearLink, newsfeedItem.schoolName);
		switch (newsfeedItem.countType) {
			// ADD Type
			case ADD_TYPE:				
				htmlString = profileLink + " added " + collegeLink + " for class of " + classYear;
				break;
			// Status Type
			case STATUS_TYPE:
				var statusMessage = STATUS_MESSAGE[parseInt(newsfeedItem.statusId)]			
				htmlString = profileLink + " "+ statusMessage + " " + collegeLink;
				break;
			// Update Type				
			case UPDATE_TYPE:			
				htmlString = profileLink + " updated their profile for " + collegeLink + " class of " + classYear;
				break;
		}
		var timeDescription = this.getTimeDescription(newsfeedItem.mins);
		htmlString = htmlString + '<ins>'+timeDescription+'</ins>';		
		newItemElement.setHTML(htmlString);
	},
	
	/**
	 * generate item element which belongs to COUNT_CATEGORY
	 * @this {NewsFeed}
	 * @param {Dom Object}	newItemElement	each placeholder of Dom Object
	 * @param {Object}	newsfeedItem	object of each newsFeedItem
	 */
	generateCounterElement: function(newItemElement, newsfeedItem){
		var htmlString = '';
		var collegeLink = this.composeTheLink(this.resultHref+'?schoolId='+newsfeedItem.schoolId+'&classYear='+newsfeedItem.collegeClass, newsfeedItem.schoolName + ' ' + newsfeedItem.collegeClass);		
		switch (newsfeedItem.countType) {
			// ADD Type			
			case 1:			
				if(newsfeedItem.profileCount > 1) {
		        	htmlString = newsfeedItem.profileCount + " Admissions Profiles were added to " + collegeLink + " today";
		        }
				else {
		        	htmlString = newsfeedItem.profileCount + " Admissions Profile was added to " + collegeLink + " today";
		        }
				break;
			// Update Type				
			case 2:				
				if(newsfeedItem.profileCount > 1) {
		        	htmlString = newsfeedItem.profileCount + " Admissions Profiles for " + collegeLink + " were updated today";
		        }
				else {
		        	htmlString = newsfeedItem.profileCount + " Admissions Profile for " + collegeLink + " was updated today";
		        }
				break;
			// Status Type
			case 3:				
				if(newsfeedItem.profileCount > 1) {
					switch(newsfeedItem.statusId) {
						case 1:
						case 2:
							htmlString = newsfeedItem.profileCount + " Admissions Profiles were accepted to " + collegeLink + " today";
							break;
						case 3:
							htmlString = newsfeedItem.profileCount + " Admissions Profiles were deferred at " + collegeLink + " today";
							break;
						case 4:
							htmlString = newsfeedItem.profileCount + " Admissions Profiles were denied at " + collegeLink + " today";
							break;
						case 6:
							htmlString = newsfeedItem.profileCount + " Admissions Profiles were wait-listed at " + collegeLink + " today";
							break;
						case 7:
							htmlString = newsfeedItem.profileCount + " Admissions Profiles have withdrawn applications to " + collegeLink + " today";
							break;
						case 8:
							htmlString = newsfeedItem.profileCount + " Admissions Profiles applied to " + collegeLink + " today";
							break;
					}
		        }
				else {
					switch(newsfeedItem.statusId) {
						case 1:
						case 2:
							htmlString = newsfeedItem.profileCount + " Admissions Profile was accepted to " + collegeLink + " today";
							break;
						case 3:
							htmlString = newsfeedItem.profileCount + " Admissions Profile was deferred at " + collegeLink + " today";
							break;
						case 4:
							htmlString = newsfeedItem.profileCount + " Admissions Profile was denied at " + collegeLink + " today";
							break;
						case 6:
							htmlString = newsfeedItem.profileCount + " Admissions Profile was wait-listed at " + collegeLink + " today";
							break;
						case 7:
							htmlString = newsfeedItem.profileCount + " Admissions Profile has withdrawn an application to " + collegeLink + " today";
							break;
						case 8:
							htmlString = newsfeedItem.profileCount + " Admissions Profile applied to " + collegeLink + " today";
							break;
					}
		        }
				break;
		}
		newItemElement.setHTML(htmlString);
	},
	
	/**
	 * generate item element which belongs to PROMO_CATEGORY
	 * @this {NewsFeed}
	 * @param {Dom Object}	newItemElement	each placeholder of Dom Object
	 */
	generatePromoElement: function(newItemElement){
		var htmlString = "Start your own <a href='javascript:";
		if(this.isStandalone) htmlString += "gotoSurveyFromNewsfeedPopup()";
		else htmlString += "gotoSurveyFromNewsfeed()";
		htmlString += "'>Admissions Profile</a> today";
		newItemElement.setHTML(htmlString);
		this.hasPromo = true;
	},
	
	/**
	 * get time description for each newsfeed item
	 * @this {NewsFeed}
	 * @param {Int}	mins 	the living time of each newsfeed
	 */
	getTimeDescription: function(mins){
		var desc = "";
		var hours = parseInt(mins/60);
		var hyphenStr = "";
		
		if(NEWSFEED_IN_WHICH_PAGE == 'home_page'){
			hyphenStr = "<span> - </span>"
		}
		if(hours > 0){
			desc = hyphenStr + '<em>' + hours + '</em> ' + ((hours == 1) ? 'hour' : 'hours') + ' ago'
		}else{
			desc = hyphenStr + '<em>' + mins + '</em> ' + (mins == 1 ? 'minute' : 'minutes') + ' ago'
		}
		return desc;
	},
	calculateMins: function(time){
		var mins = parseInt((this.serverTime-parseFloat(time))/60000);
		if(mins < 0){
			mins = 0;
		}
		return mins;
	},
	
	/**
	 * generate the link of profile in each newsfeed item 
	 * @this {NewsFeed}
	 * @param {String}	url 			the url of link
	 * @param {String}	content 		the link text
	 * @param {String}	profileName 	the profile name of newsfeed
	 */
	composeTheLink: function(url, content, profileName) {
	 	var	link;
		if(profileName)
		{
			link = '<a href="#" onclick="javascript:isValidProfileName(\''+profileName+'\');';
		}
		else
		{
	 		link = '<a href="#" onclick="javascript:setCookie(\'previousPageSection\',\'page_admissions_tracker\');';
	 		if(this.isStandalone) {
	 			if(window.opener) link += 'window.opener.location.href=\'' + url + '\';';
	 			else link += 'window.location.href=\'' + url + '\';';	 		
	 		}else{
	 			link += 'window.location.href=\'' + url + '\';';
	 		}
		}
		link += '">' + content + '</a>';
		return link;
	 },
	 startTiming: function() {
		$clear(this.currentTiming);
		this.currentTime = 0;
		this.currentTiming = function() {
			this.currentTime = this.currentTime + 200;
		}.periodical(200, this);
	 },
	 nextRequest: function() {		
		var delay_time = NEWSFEED_ITEM_DISPLAY_INTERVAL * 1000 - this.currentTime;
		if(delay_time < 0) delay_time = 0;
		var params = arguments;
		if(this.nextReq) $clear(this.nextReq);
		this.nextReq = this.runFn.delay(delay_time, this, params);
	 },
	 runFn: function() {
		 var params = arguments[0];
		 var fn = params[0];
		 var param = null;
		 if(params.length > 1) param = params[1];
		 if(fn && typeof(fn) == 'function') {
			 fn.call(this, param);
		 }
		 this.startTiming();
	 },
	 pause: function() {
		$clear(this.nextReq);
		this.trackerfeed.setStyle('display', 'none');
		window.newsfeedInstance = null;
	 }
 });
function isValidProfileName(name) {
	AdmissionNewsFeedService.isValidProfileName(name,linkToProfile);
};
function linkToProfile(result) {
	if(result[0]=='true') {
	 	setCookie('previousPageSection','page_admissions_tracker');
	 	if(window.opener) {
	 		window.opener.location.href=$('profileHref').getText().trim()+'?profileName='+result[1];
	 	}
	 	else {
	 		window.location.href=$('profileHref').getText().trim()+'?profileName='+result[1];
	 	}
	}
	else {
		if(window.opener)
		{
			newsfeedLightbox = new NewsfeedLightbox({
				htmlcont:'',
				minwidth:50,
				minheight:50,
				maxwidth:210,
				maxheight:89,
				left:10,
				top:43
			});
		}
		else
		{
			newsfeedLightbox = new NewsfeedLightbox({
				htmlcont:'',
				minwidth:50,
				minheight:50,
				maxwidth:210,
				maxheight:89,
				left:11,
				top:241
			});
		}			
		newsfeedLightbox.showmodal("Sorry, we can't find that Admissions Profile. The owner may have changed the Profile Name or deleted the account.");
		if(showLightBox)
		{
			clearTimeout(showLightBox);
		}
		showLightBox = setTimeout(function() {
			LOADING_BOX.close();
		}, 10000);
	}
};
