preloadImages = ['/images/channel/toolbar/light-cb-close-top-right.jpg','/images/channel/toolbar/light-cb-close-top-middle.jpg', '/images/channel/toolbar/light-cb-close-top-left.jpg','/images/channel/toolbar/light-cb-open-top-right.jpg','/images/channel/toolbar/light-cb-open-top-middle.jpg','/images/channel/toolbar/light-cb-open-top-left.jpg']; 
preloadImages.push('/images/channel/toolbar/cb-email.gif');
preloadImages.push('/images/channel/toolbar/cb-email-rollover.gif');
preloadImages.push('/images/channel/toolbar/cb-email-selected.gif');
preloadImages.push('/images/channel/toolbar/cb-followers.gif');
preloadImages.push('/images/channel/toolbar/cb-followers-rollover.gif');
preloadImages.push('/images/channel/toolbar/cb-followers-selected.gif');
preloadImages.push('/images/channel/toolbar/cb-invite.gif');
preloadImages.push('/images/channel/toolbar/cb-invite-rollover.gif');
preloadImages.push('/images/channel/toolbar/cb-invite-selected.gif');
preloadImages.push('/images/channel/toolbar/cb-rss.gif');
preloadImages.push('/images/channel/toolbar/cb-rss-rollover.gif');
preloadImages.push('/images/channel/toolbar/cb-rss-selected.gif');
preloadImages.push('/images/channel/toolbar/cb-twitter.gif');
preloadImages.push('/images/channel/toolbar/cb-twitter-rollover.gif');
preloadImages.push('/images/channel/toolbar/cb-twitter-selected.gif');

/*jslint fninloop:true */
function editChannel(channelId){
	var url=window.location;
	window.location.href=url.protocol + "//" + url.host + "/acct/EditChannel.do?id=" + channelId;
}

function validateEmail(emailField) {
	var isValid = true;
	
	var addrArr = emailField.value.split(",");
	for (i=0; i < addrArr.length; i++) {
		var email = addrArr[i].strip();
		if (!validEmail(email)) {
			isValid = false;
		}
	}	
	
	return isValid;
}

function resetInviteForm(){
	if ($("inviteErrors")) {
		Element.hide("inviteErrors");
	}
	if ($("fromAddr")) {
		$("fromAddr").value = $("fromAddr").defaultValue;
		Element.removeClassName("fromAddr", "error");
	}
	if ($("toAddr")) {
		Field.clear("toAddr");
		Element.removeClassName("toAddr", "error");
	}
	if ($("messagecharcount")) {
		Element.update("messagecharcount", "300");
	}
	if ($("message")) {
		Field.clear("message");
	}
	if ($("ccSender")) {
		$("ccSender").checked = false;
	}
}

function closeInviteForm(){
	oChannelToolbar.close();
	resetInviteForm();
	if ($('inviteConfirmation')) {
		Element.hide('inviteConfirmation');
	}
	if ($('inviteContent')) {
		Element.show('inviteContent');
	}
}

/**
 * Functionality to send channel invitation mail to friends.
 *
 * @param {HTMLFormElement} form object used to specify channel invitation mail contents.
 * @param {Boolean} showResendRegEmailPop, boolean value indicating whether to show re send register invitation pop up or not, 
 * 		if user in temporary registration session trying to access channel invitation mail functionality.
 */
function sendInvites(form, showResendRegEmailPop){
	if($('fromAddr') && $('toAddr')){
		var validTo = validateEmail($('toAddr'));
		var validFrom = validateEmail($('fromAddr'));
		
		if (validTo && validFrom){
		    
			var url = "/EmailChannel.do";
				
			var myAjax = new Ajax.Request(
				url, 
				{
				method: 'post', 
				parameters: Form.serialize(form), 
				onComplete: function(request){
					if(request.responseText == MyGlobals.ajaxSuccess){
						if($('inviteConfirmationText')){
							var confText = "An invitation to join this channel has been sent to "; 
							var sentEmails = $('toAddr').value.split(",");
							
							for (i=0; i < sentEmails.length; i++) {
								if (i > 0) {
									confText += ",";
								}
								var email = sentEmails[i].strip();
								confText += email;
							}	
			
							$('inviteConfirmationText').innerHTML = confText + ".";
						}		
						if ($('inviteContent')) {
							Element.hide('inviteContent');
						}
						if ($('inviteConfirmation')) {
							Element.show('inviteConfirmation');
						}
						resetInviteForm();
						
						// Story-3379, show email confirmation required pop up
						if (showResendRegEmailPop) {
							popUpWidget.showPopUp("registerEmailConfirmRequiredPopUp", false, true);
						}
					} else {
						alert(request.responseText);
					}
				}
				});
		} else {
			if(!validTo){
				Element.addClassName("toAddr", "error");
			} else {
				Element.removeClassName("toAddr", "error");
			}
			if(!validFrom){
				Element.addClassName("fromAddr", "error");
			} else {
				Element.removeClassName("fromAddr", "error");
			}
			if ($("inviteErrors")) {
				Element.show("inviteErrors");
			}
		}
	}
}

/**
 * Modify email settings of user going for channel subscribe or un subscribe.
 *
 * @param {HTMLFormElement} form object used to specify channel email settings.
 * @param {Boolean} showResendRegEmailPop, boolean value indicating whether to show re send register invitation pop up or not, 
 * 		if user in temporary registration session trying to access channel subscription functionality.
 */
function modifyEmailSettings(form, showResendRegEmailPop){
	if($('channelId')){
		var chId = $('channelId').value;
		
		for(var i=0; i<form.emailDelivery.length; i++){
			if(form.emailDelivery[i].checked){
				if(form.emailDelivery[i].value == "off"){
					ChannelController.unsubscribeFromEmail(chId, function(data){
						if(data !="0"){
							alert(data);
						} else {
							if ($('emailClosed')) {
								$('emailClosed').src = "/images/channel/toolbar/email-no.jpg";
							}
							if ($('emailSelected')) {
								$('emailSelected').src = "/images/channel/toolbar/email-no-selected.jpg";
							}
							if ($('emailOpen')) {
								$('emailOpen').src = "/images/channel/toolbar/email-no-open.jpg";
							}
							if (typeof form.emailDeliverySet != 'undefined') {
								form.emailDeliverySet.value = 'off';
							}
							oChannelToolbar.swapEmailSettings('no');
						}
					});
				} else if (form.emailDelivery[i].value == "weekly") {
					ChannelController.subscribeToEmail(chId, form.dayOfWeek.value, form.ampmHour.value, form.ampm.value, form.timezone.value, function(data){
						if(data != "0"){
							alert(data);
						} else {
							if ($('emailClosed')) {
								$('emailClosed').src = "/images/channel/toolbar/email-yes.jpg";
							}
							if ($('emailSelected')) {
								$('emailSelected').src = "/images/channel/toolbar/email-yes-selected.jpg";
							}
							if ($('emailOpen')) {
								$('emailOpen').src = "/images/channel/toolbar/email-yes-open.jpg";
							}
							if (typeof form.emailDeliverySet != 'undefined') {
								form.emailDeliverySet.value = 'weekly';
							}
							if (typeof form.dayOfWeekSet != 'undefined' && typeof form.dayOfWeek != 'undefined') {
								form.dayOfWeekSet.value = form.dayOfWeek.value;
							}
							if(typeof form.ampmHourSet != 'undefined' && typeof form.ampmHour != 'undefined') {
								form.ampmHourSet.value = form.ampmHour.value;
							}
							if (typeof form.ampmSet != 'undefined' && typeof form.ampm != 'undefined') {
								form.ampmSet.value = form.ampm.value;
							}
							if(typeof form.timezoneSet != 'undefined' && typeof form.timezone != 'undefined') {
								form.timezoneSet.value = form.timezone.value;
							}
							oChannelToolbar.swapEmailSettings('yes');
							// Story-3379, show email confirmation required pop up
							if (showResendRegEmailPop) {
								popUpWidget.showPopUp("registerEmailConfirmRequiredPopUp", false, true);
							}
						}
					});
				}
			}
		}
	
		oChannelToolbar.close();
	}
}

function activateEmail(form){
	form.emailDelivery[0].checked = true;
}

function closeEmailForm(form){
	oChannelToolbar.close();
	if(typeof form.emailDeliverySet != 'undefined' && typeof form.emailDelivery != 'undefined'){
		for(var i=0; i<form.emailDelivery.length; i++){
			if (form.emailDelivery[i].value == form.emailDeliverySet.value) {
				form.emailDelivery[i].checked = 'true';
			}
		}
	}
	if (typeof form.dayOfWeekSet != 'undefined' && typeof form.dayOfWeek != 'undefined') {
		form.dayOfWeek.value = form.dayOfWeekSet.value;
	}
	if (typeof form.ampmHourSet != 'undefined' && typeof form.ampmHour != 'undefined') {
		form.ampmHour.value = form.ampmHourSet.value;
	}
	if (typeof form.ampmSet != 'undefined' && typeof form.ampm != 'undefined') {
		form.ampm.value = form.ampmSet.value;
	}
	if (typeof form.timezoneSet != 'undefined' && typeof form.timezone != 'undefined') {
		form.timezone.value = form.timezoneSet.value;
	}
}

function showInviteForm(){
	var charCountContainer = $('charCountContainer');
	Element.hide('inviteConfirmation');
	Element.show('inviteContent');
	if (charCountContainer) {
		charCountContainer.update('300');
	}
}

function removeChannel(channelId, forwardTo){
	ChannelController.removeChannel(channelId, function(data){
		if(isNaN(data)){
			//error message returned
			alert(data);
		} else if (forwardTo == 'channelList') {
			var url=window.location;
			window.location.href=url.protocol + "//" + url.host + "/acct/ChannelsList.do";
		} else if (forwardTo == 'previousPage') {
			history.go(-1);
		} else {
			hidePop("confirmDelete", "backdrop");
		}
	});
}

function deleteChannelConfirm(chId,forwardTo){
	if ($('yesRemoveChannel')) {
		$('yesRemoveChannel').onclick = function(){
			removeChannel(chId, forwardTo);
		};
	}	
	if ($('confirmDelete')) {
		showPop('confirmDelete', 'backdrop');
	}
}

/**
 * Modify "View All" URL on 'News Only' page.
 * 
 * @param selectedTab Current Channel toolbox selected tab value
 */
function modifyViewAllLink(selectedTab){
	if($('primaryTool')){
		var primaryToolDiv = $$('#primaryTool a');
		if(primaryToolDiv[0]){
			var ele = primaryToolDiv[0].href;
			ele = ele.substring(0,ele.lastIndexOf('/')+1) +'?showChannelToolboxTab='+selectedTab;
			// Append existing View All link with current selected showChannelToolboxTab value.
			$$('#primaryTool a')[0].href = ele;
		}
	}
}

/**
 * Modify Pagination URL on 'News Only' page as well as Channel detail Main page.
 * 
 * @param selectedTab Current Channel toolbox selected tab value
 */
function modifiyPaginationLink(selectedTab){
	if($('pagination')){
		var paginationDiv = $$('#pagination a');
		var ele = '';
		if(paginationDiv[0]){
			// Loop to modify href of pagination link by appending current selected channel toolbox tab value.
			for(var i=0; i<paginationDiv.length; i++){
				ele = paginationDiv[i].href;
				// If link already have showChannelToolboxTab value then replace it with new showChannelToolboxTab value otherwise append showChannelToolboxTab with existing link URL.
				ele = ele.lastIndexOf('&showChannelToolboxTab') > 0 ? ele.substring(0,ele.lastIndexOf('&showChannelToolboxTab')) : ele.substring(0,ele.length);
				ele = ele +'&showChannelToolboxTab='+selectedTab;
				$$('#pagination a')[i].href = ele;
			}
		}
	}	
}

// CHANNEL TOOLBAR
var ChannelToolbar = Class.create();

ChannelToolbar.prototype =
{
	initialize: function(showTuneMsg)
	{
		this.links = $$('#msgBoxHeaderMid > a');
		this.container = $('msgBox');
		this.msgContainer = $('msgBoxBody');
		
		this.images = [];
		this.contents = [];
		this.imageContentOpen = [];
		this.imageContentSelected = [];
		this.imageContentClosed = [];
		this.current = false;
		this.selected = false;
		this.open = false;
		
		this.links.each(function(x, i) {
			var thisImg = this.links[i].getElementsByTagName('img')[0]; 
			this.images[i] = this.image(thisImg);	
			this.contents[i] = this.content(thisImg, 'Content');
			this.imageContentOpen[i] = this.content(thisImg, 'Open');
			this.imageContentSelected[i] = this.content(thisImg, 'Selected');
			this.imageContentClosed[i] = this.content(thisImg, 'Closed');
			this.preload(i);
			Event.observe(this.links[i], 'mouseover', function() { this.hover(i); }.bindAsEventListener(this));
			Event.observe(this.links[i], 'mouseout', function() { this.unhover(); }.bindAsEventListener(this));
			if(this.contents[i] != 'tuneContent' || showTuneMsg) {
				Event.observe(this.links[i], 'click', function() { this.select(i); }.bindAsEventListener(this));			
			}
		}.bind(this));
	},
	
	image: function(x)
	{
		var img = {};
		img.elm = x;
		
		var matches = x.src.match(/(.*)\.(.*)/);
		if (matches && matches[1] && matches[2]){			
			img.img = x.src;
			img.open = matches[1]+'-open.'+matches[2];
			img.openRollover = matches[1]+'-open-rollover.'+matches[2];
			img.rollover = matches[1]+'-rollover.'+matches[2];
			img.selected = matches[1]+'-selected.'+matches[2];
			return img;			
		}
		return false;
	},
	
	content: function(x, divType)
	{
		var matches = x.src.match(/(.*)\/(.*)\.(.*)/);
		if (matches && matches[2]){		
			var imgName = matches[2];
			if (imgName.indexOf('-yes') != -1) {
				imgName = imgName.substring(0, imgName.indexOf('-yes'));
			}
			if (imgName.indexOf('-no') != -1) {
				imgName = imgName.substring(0, imgName.indexOf('-no'));
			}
			return(imgName+divType);		
		}
		return false;
	},
	
	preload: function(k)
	{
		var img = new Image();
		img.src = this.images[k].img;
		
		var open = new Image();		
		open.src = this.images[k].open;

		var openRollover = new Image();
		openRollover.src = this.images[k].openRollover;
		
		var rollover = new Image();
		rollover.src = this.images[k].rollover;
		
		var selected = new Image();
		selected.src = this.images[k].selected;
	},
	
	
	hover: function(m)
	{
		if (this.selected && m == this.selected) {
			return;
		}
		
		if(this.open){
			this.images[m].elm.src=this.images[m].openRollover;
			if ($(this.imageContentOpen[m])) {
				$(this.imageContentOpen[m]).src = this.images[m].openRollover;
			}
		} else {
			this.images[m].elm.src=this.images[m].rollover;
			if ($(this.imageContentClosed[m])) {
				$(this.imageContentClosed[m]).src = this.images[m].rollover;
			}
		}
		this.current = m;
	},
	
	unhover: function()
	{
		// Added new condition to fixed DEV-12728.
		if (this.current || this.current === 0)
		{
			if(this.open){
				this.images[this.current].elm.src=this.images[this.current].open;
				if ($(this.imageContentOpen[this.current])) {
					$(this.imageContentOpen[this.current]).src = this.images[this.current].open;
				}
			} else {
				this.images[this.current].elm.src=this.images[this.current].img;
				if ($(this.imageContentClosed[this.current])) {
					$(this.imageContentClosed[this.current]).src = this.images[this.current].img;
				}
			}
		}
		this.current = false;	
	},
	
	select: function(n)
	{
		this.unhover();
		this.selected = n;
		this.open = true;
		Element.addClassName(this.container, 'on');
		Element.removeClassName(this.container, 'off');
		
		if ($('inviteConfirmation')) {
			Element.hide('inviteConfirmation');
		}
		if($('showChannelToolboxTab')){
			$('showChannelToolboxTab').value = this.selected;
		}
		modifyViewAllLink(this.selected);
		modifiyPaginationLink(this.selected);
		for(var j=0; j<this.contents.length; j++){
			if(j == this.selected){
				if ($(this.contents[j])) {
					Element.show(this.contents[j]);
				}
				if ($(this.imageContentOpen[j])) {
					Element.hide(this.imageContentOpen[j]);
				}
				if ($(this.imageContentClosed[j])) {
					Element.hide(this.imageContentClosed[j]);
				}
				if ($(this.imageContentSelected[j])) {
					Element.show(this.imageContentSelected[j]);
				}
			} else {
				if ($(this.contents[j])) {
					Element.hide(this.contents[j]);
				}
				if ($(this.imageContentOpen[j])) {
					Element.show(this.imageContentOpen[j]);
				}
				if ($(this.imageContentClosed[j])) {
					Element.hide(this.imageContentClosed[j]);
				}
				if ($(this.imageContentSelected[j])) {
					Element.hide(this.imageContentSelected[j]);
				}
			}
		}
		
		if ($('msgBoxHeaderRightClosed')) {
			Element.hide('msgBoxHeaderRightClosed');
		}
		if ($('msgBoxHeaderRightOpen')) {
			Element.show('msgBoxHeaderRightOpen');
		}
		
		if ($('msgBoxHeaderLeftClosed')) {
			Element.hide('msgBoxHeaderLeftClosed');
		}
		if ($('msgBoxHeaderLeftOpen')) {
			Element.show('msgBoxHeaderLeftOpen');
		}
		
		Element.show(this.msgContainer);
		
		for(var i=0; i<this.links.length; i++){
			var thisImg = this.links[i].getElementsByTagName('img')[0];
			if(i == this.selected){
				thisImg.src = this.images[i].selected;
			} else {
				thisImg.src = this.images[i].open;
			}
		}
		
		var itemDivs = $$('.inDepthCols');
		if(itemDivs.length > 0) {
			Element.addClassName(itemDivs[0], 'belowMsg');
		}
	},
	
	close: function()
	{
		Element.addClassName(this.container, 'off');
		Element.removeClassName(this.container, 'on');
		Element.hide(this.contents[this.selected]);
		Element.hide(this.msgContainer);
		
		for(var i=0; i<this.links.length; i++){
			var thisImg = this.links[i].getElementsByTagName('img')[0];
			thisImg.src = this.images[i].img;
		}
		
		for(var j=0; j<this.imageContentOpen.length; j++){
			if ($(this.imageContentOpen[j])) {
				Element.hide(this.imageContentOpen[j]);
			}
			if ($(this.imageContentSelected[j])) {
				Element.hide(this.imageContentSelected[j]);
			}
			if($(this.imageContentClosed[j])) {
				Element.show(this.imageContentClosed[j]);
			}
		}
		
		if ($('msgBoxHeaderRightOpen')) {
			Element.hide('msgBoxHeaderRightOpen');
		}
		if ($('msgBoxHeaderRightClosed')) {
			Element.show('msgBoxHeaderRightClosed');
		}
		
		if ($('msgBoxHeaderLeftOpen')) {
			Element.hide('msgBoxHeaderLeftOpen');
		}
		if ($('msgBoxHeaderLeftClosed')) {
			Element.show('msgBoxHeaderLeftClosed');
		}
		
		if ($('msgBoxHeaderMidOpen')) {
			Element.hide('msgBoxHeaderMidOpen');
		}
		if ($('msgBoxHeaderMidClosed')) {
			Element.show('msgBoxHeaderMidClosed');
		}
		
		this.selected = false;
		this.open = false;
		
		var itemDivs = $$('.inDepthCols');
		if(itemDivs.length > 0) {
			Element.removeClassName(itemDivs[0], 'belowMsg');
		}
	},
	
	swapEmailSettings: function(yesNo)
	{
		var original = yesNo == "yes" ? "-no" : "-yes"; 
		var updated = yesNo == "yes" ? "-yes" : "-no";
		
		var emailImg = this.images[0];

		emailImg.img = emailImg.img.replace(original, updated);
		emailImg.open = emailImg.open.replace(original, updated);
		emailImg.openRollover = emailImg.openRollover.replace(original, updated);
		emailImg.rollover = emailImg.rollover.replace(original, updated);
		emailImg.selected = emailImg.selected.replace(original, updated);
	}
};

/**
 * Reset all the error boxes and sub navigation buttons.
 * @param {String} selectedOption contaning navigation id.
 */
function resetFollowingOptions(selectedOption){
	var resetErrorBlock = $('inviteErrors');
	var inviteMainContent = $('inviteMainContent');
	var followingContent = $('followingContent');
	// Reset error container.
	if (resetErrorBlock) {
		resetErrorBlock.hide();
		$('toAddr').removeClassName('error');
	}
	// Reset sub navigation container.
	if(selectedOption === followingContent.id){
		inviteMainContent.hide();
		followingContent.show();
	}else{
		followingContent.hide();
		inviteMainContent.show();
	}
	//In case other tab option is selected
	if(selectedOption === 'remove' || selectedOption === 'tune'){
		followingContent.hide();
		inviteMainContent.hide();
	}
}

/**
 * Showing following's navigation options
 * @param {String} selectedOption
 */
function showFollowingOptions(selectedOption){
	var showIt = $(selectedOption+'Content');
	// Array of options container which will be shown on click of link(button).
	var followingContainer =['cbEmailContent', 'cbTwitterContent', 'cbRssContent'];
	var inviteContainer =['cbFollowerContent', 'cbInviteContent', 'inviteConfirmation'];
	var tempArr;
	
	if($(selectedOption).parentNode.id === 'followingNavContainer'){
		tempArr = followingContainer;
	}else{
		tempArr = inviteContainer;
	}
	
	 for(i=0; i<tempArr.length; i++){
		 if ($(tempArr[i])){
			 $(tempArr[i]).hide();
			 // Getting buttons's id to reset the navigation's buttons
			 var linkId = tempArr[i].substr(0, tempArr[i].indexOf('Content'));
			 if ($(linkId)) {
			 	$(linkId).className = linkId;
			 }
		 }
	 }
	
	// Showing selected link's container 
	if (showIt) {
		showIt.show();
	}
	if(showIt.id === 'cbInviteContent'){
		$('inviteContent').show();
	}
	//Reset active image of button's background.
	$(selectedOption).className = selectedOption+'Selected';
}
