//
// This page and website code are 'trade secret',
// (c) CouchSurfing International, Inc. All rights reserved.
//

function createCSChannelBox(channelContainerName, feedUrl, channelName, channelTitle, channelUrl, showSubscribe, showFeed, showPaging, showNrTopics, channel_id, subscription_preference) {
	var box = document.createElement('div');
	box.className = 'channel-box';
	box.id = channelName;
	var el = $(channelContainerName);
	el.appendChild(box);
	//title box
	var titlebox = document.createElement('div');
	titlebox.className = "channel-title-box";

	Element.addClassName(titlebox, channelName);
	var titletext = document.createElement('div');
	titletext.className = "channel-title";
	var titlelink = document.createElement('a');
	titlelink.href = channelUrl;
	titlelink.appendChild(document.createTextNode(channelTitle));
	titletext.appendChild(titlelink);
	titlebox.appendChild(titletext);
	box.appendChild(titlebox);

	var borderdiv = document.createElement('div');
	borderdiv.className = "channel-border";

	if (showPaging) {
		var pagingBox = document.createElement('div');
		pagingBox.className = "channel-paging-box";

		numberOfItems = '10';
		numberOfPages = Math.floor(numberOfItems/showNrTopics);
		for (var i = numberOfPages; i>=0; i--) {
		var pagingButton = document.createElement('span');
		var pagingButtonLink = document.createElement('a');
		pagingButtonLink.id = "page"+i;
		if (i == 0){
			pagingButtonLink.className = "channel-paging-button active";
		}else{
			pagingButtonLink.className = "channel-paging-button";
		}
		Element.addClassName(pagingButtonLink, channelName);
		pagingButtonLink.href = "javascript:showPosts('"+channelName+"',"+(i*showNrTopics)+","+showNrTopics+", 'page"+i+"')";
		pagingButtonLink.appendChild(document.createTextNode(i+1));
		pagingButton.appendChild(pagingButtonLink);
		pagingBox.appendChild(pagingButton);
		}
		borderdiv.appendChild(pagingBox);
	}
	//info box
	var infoBox = document.createElement('div');
	infoBox.id = "channel-info-box";
	infoBox.className = "channel-info-box";
	borderdiv.appendChild(infoBox);
	//footer
	if(showFeed){
		var footerBox = document.createElement('div');
		footerBox.className = "channel-footer";

		var subscribeText = document.createElement('a');
		subscribeText.className = "channel-info-desc";
		subscribeText.href = '/group_edit.html';
		subscribeText.appendChild(document.createTextNode("Subscription Setting:"));
		footerBox.appendChild(subscribeText);
		footerBox.appendChild(createSubscriptionBox(channel_id, subscription_preference));

		if (showFeed) {
			var rssBox = document.createElement('div');
			rssBox.className = 'channel-rss';
			var rssLink = document.createElement('a');
			rssLink.href = feedUrl;
			var rssImage = document.createElement('img');
			rssImage.src = "/images/rss16.png";
			rssImage.border = "0";
			rssImage.alt = "RSS";
			rssImage.title = "RSS";
			rssLink.appendChild(rssImage);
			rssBox.appendChild(rssLink);
			footerBox.appendChild(rssBox);
		}
		borderdiv.appendChild(footerBox);
	}
	box.appendChild(borderdiv);

}
//I make this one nice and beautifull later when I have time :)
function createFeedLayout(hXML, targetBox, showNrTopics, titleonly) {
	try {

		var xmlChannel = hXML.getElementsByTagName('channel').item(0);
		var xmlTitle = hXML.getElementsByTagName('title').item(1);
		if (!xmlChannel || !xmlTitle) {
			return showChannelError("Sorry, no news yet. Please check back soon.", targetBox);
			//return showError("Sorry, invalid news channel!", targetBox);
		}
		if(!xmlTitle.childNodes.length){
			return showChannelError("Sorry, no news yet! Please check back soon.", targetBox);
			}else {
			var hChildren = xmlChannel.getElementsByTagName('item');
			var info = "", text, vNode;
			var box = document.createElement('div');
			box.className = 'channel-info-box';
			if(hChildren.length > 0){;
				for (var i = 0; i<hChildren.length; i++) {
					hItem = hChildren.item(i);
					if (hItem.nodeType == 1) {
						if (hItem.nodeName == "item") {
							var titleNode = hItem.getElementsByTagName('title');
							var linkNode = hItem.getElementsByTagName('link');
							var dateNode = hItem.getElementsByTagName('pubDate');
							var descriptionNode = hItem.getElementsByTagName('description');
							var rssInfo = document.createElement('div');
							rssInfo.className = "channel-info";
							rssInfo.id = i;
							var rssInfoTitle = document.createElement('div');
							rssInfoTitle.className = "channel-info-title";
							var rssLink = document.createElement('a');
							rssLink.href = linkNode[0].firstChild.nodeValue;
							rssLink.appendChild(document.createTextNode(titleNode[0].firstChild.nodeValue));
							rssInfoTitle.appendChild(rssLink);
							var rssInfoDate = document.createElement('div');

							rssInfoDate.className = "channel-info-date";
							var dateText = dateNode[0].firstChild.nodeValue;
							dateText = dateText.slice(0, dateText.length-14);
							feedDate = document.createTextNode(dateText);
							rssInfoDate.appendChild(feedDate);

							rssInfo.appendChild(rssInfoTitle);
							rssInfo.appendChild(rssInfoDate);

							if (titleonly!="true"){
								var rssInfoDesc = document.createElement('div');
								rssInfoDesc.className = "channel-info-desc";
								var rssLink2 = document.createElement('a');
								rssLink2.href = linkNode[0].firstChild.nodeValue;
								text = new String(descriptionNode[0].firstChild.nodeValue);
								text = text.stripScripts().stripTags();
								vNode = document.createElement('span');
								vNode.innerHTML = text;
								rssLink2.appendChild(vNode);
								rssInfoDesc.appendChild(rssLink2);
								rssInfo.appendChild(rssInfoDesc);
							}

							//hide the other posts
							if (i >= showNrTopics){
								rssInfo.style.display="none";
							}
							box.appendChild(rssInfo);
						}
					}
				}
			}else{
				return showChannelError("RSS file is empty :(", targetBox);
			}
		}return box;
	} catch (e) {
		return showException(e);
	}
}
function showChannelLoading(ex) {
	var targetbox = ex.request.parameters.targetBox;
	var box = document.createElement('div');
	box.className = 'channel-info-box';
	var loading = document.createElement('div');
	loading.className = "channel-loading";
	var loadingImg = document.createElement('img');
	loadingImg.src = "images/ajax-loader.gif";
	loadingImg.border = "0";
	loadingImg.alt = "loading";
	loadingImg.title = "loading";
	loadingImg.align = "left";
	loading.appendChild(loadingImg);
	var loadingText = document.createElement('div');
	loadingText.className = "channel-loading-text";
	loadingText.appendChild(document.createTextNode("loading channel"));
	loading.appendChild(loadingText);
	box.appendChild(loading);
	var infoTarget = $(targetbox).select('[class="channel-info-box"]');
	infoTarget[0].replace(box);
}
function showChannelError(ex, targetbox) {
	try{
		theTargetArray  = $$('#'+targetbox+' .channel-paging-box');
		theTargetArray[0].hide();
		theTargetArray  = $$('#'+targetbox+' .channel-footer');
		theTargetArray[0].hide();
	}catch(e){
		//alert(e);
	}
	var box = document.createElement('div');
	box.className = 'channel-info-box';
	var errorBox = document.createElement('div');
	errorBox.className = "channel-error-box";
	var errorText = document.createElement('div');
	errorText.className = "channel-error-text";
	errorText.appendChild(document.createTextNode(ex));
	errorBox.appendChild(errorText);
	box.appendChild(errorBox);
	return box;
}
function showChannelException(ex) {
	var box = document.createElement('div');
	box.className = 'channel-info-box';
	var errorBox = document.createElement('div');
	errorBox.className = "channel-error-box";
	var errorText = document.createElement('div');
	errorText.className = "channel-error-text";
	errorText.appendChild(document.createTextNode("Sorry, no news yet!  Please check back soon. Error:\n "+ex ));
	errorBox.appendChild(errorText);
	box.appendChild(errorBox);
	return box;
}
function showChannelResponse(originalRequest) {
	//put returned XML in the textarea
	var targetbox = originalRequest.request.parameters.targetBox;
	var showNrTopics = originalRequest.request.parameters.showNrTopics;
	var showTitleOnly = originalRequest.request.parameters.titleonly;
	box = document.getElementById(targetbox);
	infoTarget = $$('#'+targetbox+' .channel-info-box');
	var infoBox = createFeedLayout(originalRequest.responseXML, targetbox, showNrTopics, showTitleOnly);
	infoTarget[0].replace(infoBox);
}
function createSubscriptionBox(channel, selection) {
	selectBox = document.createElement('select');
	selectBox.className = "subscription-box";
	selectBox.onchange = function(){update_com_alert(channel, this.value)}; // VALUE DOES NOT WORK IN IE (2 places use this)
	var optionsArray = new Array('none', 'instant'); //, 'daily', 'weekly');  // COMMENTING THIS OUT AS WE WILL ONLY ALLOW INSTANT SUBSCRIPTIONS
	optionsArray.each(function (s) {
		optionItem = document.createElement('option');
		optionItem.appendChild(document.createTextNode(s));
		optionItem.value = s;
		if(s == selection){
			optionItem.selected = true;
		}
		selectBox.appendChild(optionItem);
	});
	return selectBox;
}
function showPosts(channelName, starting, items, reflink){

	itemArray = $$("#"+channelName+" .channel-info");
	for(var i=0; i < itemArray.length; i++){
		if(i>=starting && i<(starting+items)){
			itemArray[i].show();
		}else{
			itemArray[i].hide();
		}
	}
	itemArray = $$("#"+channelName+" .channel-paging-button");
	for(var i=0; i < itemArray.length; i++){

		if(itemArray[i].id == reflink){
			//Element.addClassName(pagingButtonLink, channelName);
			itemArray[i].addClassName('active');
		}else{
			itemArray[i].removeClassName('active');
		}
	}


}

function fetchRss(targetdiv, rssfeed, boxname, boxtitle, weburl, showsubscribe, showfeed, showpaging, shownrtopics, titleonly, channel_id, subscription_preference)
	{
		if (boxname != null){
			var feed = rssfeed;
			var url = 'ajax/rssproxy.php';
			var pars = 'feed='+escape(rssfeed)+"&targetBox="+boxname+"&showNrTopics="+shownrtopics+"&titleonly="+titleonly;

			createCSChannelBox(targetdiv, rssfeed, boxname, boxtitle, weburl, showsubscribe, showfeed, showpaging, shownrtopics, channel_id, subscription_preference)

			var myAjaxChannel = new Ajax.Request(
				url,
				{
					method: 'post',
					parameters: pars,
					onCreate : showChannelLoading,
					onFailure:showChannelError,
					onComplete: showChannelResponse
				});
		}
	}
function update_com(obj, gid, target_div){
	var url = 'ajax/set_group_settings.php';
	var pars = 'type='+obj.value+"&gid="+gid;
	$(target_div).show();
	$(target_div).update("saving...");
	new Ajax.Updater(target_div, url, {
  			parameters: pars
			});
}
function update_com_alert(gid, type){
	var url = 'ajax/set_group_settings.php';
	var pars = 'type='+type+"&gid="+gid;
	var myAjax = new Ajax.Request(
				url,
				{
					method: 'post',
					parameters: pars,
					onFailure: showAlertFail,
					onComplete: showAlertResponse
				});
}
function showAlertResponse(response){
	alert("Your preference has been saved.");
}
function showAlertFail(response){
	alert("There was an error contacting the server. Please try again.");
}

function show_default_channel(channel_id, title, target_div, div_name, posts, loggedin, subscription_preference){
	//fetchRss(targetdiv, rssfeed, boxname, boxtitle, weburl, showsubscribe, showfeed, showpaging, shownrtopics, channelid)
		fetchRss(target_div, "http://www.couchsurfing.org/feeds/group_rss.php?gid="+channel_id, div_name, title, "channel.html?gid="+channel_id, loggedin, true, false, posts, false, channel_id, subscription_preference);
}
