var ts = new Date();

// Ads by RBC
var adInterval = 7;
var adNumber = 3;
var adCurrentIndex = 0;
var boxCounter = 0;
var boxID;

$(document).ready(
	function () {

		// Header
		$("div.home div#header").css({height:'80px',color:'#fff',background:'#848453 url(http://rbccafe.org/images/header.gif) repeat-x 0 0'});

		// Logo
		$("div#logo img").attr('src','http://rbccafe.org/images/rbclogo_sm.gif');
		$("div#logo").css({position:'absolute',top:"10px",left:"15px",padding:"0pt"});

		// Site Navigation
		$('div.home #menu').css({backgroundColor:'transparent',height:"24px",overflow:"hidden",position:"absolute",width:'540px',left:"285px",top:"55px",zIndex:"15"});

		// Top Right Navigation
		var links = '';
		links += $('div#sleeve span.h1:eq(0)').html();
		links += ' | ';
		links += $('div#sleeve span.h1:eq(1)').html();
		$("div.home div#banner").html(links);
		$("div.home div#banner").css({right:'20px',left:'auto'});
		$("div.home div#banner a").css({color:'#fff',textDecoration:'none',padding:'0pt 5px'});

		// Tagline
		$("div#tagline").html('From the Publishers of "Our Daily Bread"');
		$("div.home div#tagline").css({right:'auto',left:'15px',top:'60px',textAlign:'left'});

		// Browse By Topic
		$('div#header').append('<div id="rbc-searchDrop">'+$('div#searchDrop').html()+'</div>');
		$("div#header div#rbc-searchDrop").css({position:'absolute',left:'630px',top:'30px'});

		// Search
		$('div#header').append('<div id="rbc-search">'+$('div#search').html()+'</div>');
		$("div#header div#rbc-search").css({position:'absolute',left:'755px',top:'28px',width:'200px',textAlign:'right'});

		$('div#cells').before('<div id="rbc-edit"><div class="edit-options"><a href="?edit">Edit<span class="hide"> settings</span></a></div></div>');

		// Main Columns
		$("div#cells").css({width:'960px',overflow:'visible'});
		$("div#cell-left").css({marginTop:'15px',float:'left',width:'306px',marginLeft:'10px',fontSize:'10pt'});
		$("div#cell-middle").css({marginTop:'-188px',float:'left',width:'306px',marginLeft:'11px',fontSize:'10pt'});
		$("div#cell-right").css({marginTop:'15px',float:'left',width:'306px',marginLeft:'11px',fontSize:'10pt'});

		// Create ads box
		$("div#cells").prepend('<div id="cell-top"><p>Welcome to RBC Ministries! Throughout our history, we have been teaching the Word of God so as to lead people of all nations to personal faith and maturity in Christ. And as you will see in the pages of this Web site, we try to achieve our goal through every method and medium available... <a href="http://www.rbc.org/about/introduction.aspx"><span>More</span>&nbsp;&#187;</a></p></div>');
		$("div#cell-top").css({marginTop:'15px',width:'623px',height:'188px',float:'left',position:'relative',marginRight:'320px',marginLeft:'10px',fontSize:'10pt'});

		// Get ads
		$("div#cell-top").append(getAd(0,"http://www.rbc.org/bible_study/answers_to_tough_questions/home.page","Answers to Tough Questions","ad_atq_main.jpg"));
		$("div#cell-top").append(getAd(1,"http://www.rbc.org/odb/odb.shtml","Our Daily Bread Radio","ad_odbr_main.jpg"));
		$("div#cell-top").append(getAd(2,"http://www.getmorestrength.org","Strength for the Journey","ad_sftj_main.jpg"));
		//$("div#cell-top").append('<div id="ad_3" style="display:none;float:left">'+$('div.ads:eq(1)').html()+'</div>');

		// Start rotating ads
		setInterval("nextAd()",adInterval * 1000);

		// Recovery
			// Get bookcover before it is deleted
			var bookcover = $('div#ctl00_pnlTodaysDevotional p:first').html();
    	var features = $('div.features').html();

		// RSS Feed to ODB
		// Add Book Cover
		//var odbContainer = 'div#'+boxID+' div.box_data';
		//$(odbContainer).html('<div class="text">'+bookcover+'</div>');

		// Clear the columns
		$("div#cell-right").html('');
		$("div#cell-middle").html('');
    $("div#cell-left").html('');

    // if cookies set, read in cookie array, otherwise read in default array...
    // add a feed manually
    $("div#cell-middle").movableparts({
				id: 'box_1',
        title: 'Our Daily Bread',
        link: 'http://www.odb.org',
				feed_url: 'http://www.rbc.org/rss.ashx?id=50398',
				item_count: 1,
				show_date: true
    });
    
    $("div#cell-left").movableparts({
				id: 'box_2',
        title: 'My Utmost For His Highest',
        link: 'http://www.utmost.org',
				feed_url: 'http://www.rbc.org/rss.ashx?id=50400',
				item_count: 1,
				show_date: false
    });

    $("div#cell-middle").movableparts({
				id: 'box_3',
        title: 'Daily Strength',
        link: 'http://www.getmorestrength.org',
				feed_url: 'http://www.rbc.org/rss.ashx?id=50452',
				item_count: 1
    });

    $("div#cell-left").movableparts({
				id: 'box_4',
        title: 'Words to Live By',
        link: 'http://www.words.net',
				feed_url: 'http://www.rbc.org/rss.ashx?id=50458',
				item_count: 4,
				desc_length: 0,
				show_date: false
    });
    
		// RSS feed on a timer
    window.setTimeout(function() {
	    $("div#cell-right").movableparts({
					id: 'box_5',
	        title: 'Discover the Word',
	        link: 'http://www.discovertheword.org/',
					feed_url: 'http://www.rbc.org/rss.ashx?id=50454',
					item_count: 3,
					desc_length: 0,
					show_date: false
			});
    }, 2500);
    
    $("div#cell-right").movableparts({
				id: 'box_6',
        title: 'Been Thinking About Blog',
        link: 'http://www.beenthinking.org',
				feed_url: 'http://beenthinking.org/wp-json.php?callback=?',
				feed_type: 'json',
				item_count: 1,
				desc_length: 50,
				show_date: false
    });

		$('div#cells').after('<div id="features">'+features+'</div>');

		// Functional Footer
		var functional = '<div id="functional" class="text">';
		functional += '<h3>RBC Ministries Online Resource:</h3>';
		functional += '<table>';
		functional += '<thead>';
		functional += '<tr>';
		functional += '<th>Devotionals</th>';
		functional += '<th>Radio &amp; TV</th>';
		functional += '<th>Bible Study</th>';
		functional += '<th>About RBC</th>';
		functional += '</tr>';
		functional += '</thead>';
		functional += '<tbody>';
		functional += '<tr>';
		functional += '<td style="vertical-align: top;"><ul>';
		functional += '<li><a href="/odb/odb.shtml">Our Daily Bread</a></li>';
		functional += '<li><a href="/utmost/index.php">My Utmost For His Highest</a></li>';
		functional += '<li><a href="/bible-study/strength-for-the-journey/daily-strength.aspx">Daily Strength</a></li>';
		functional += '</ul>';
		functional += '</td>';
		functional += '<td style="vertical-align: top;"><ul>';
		functional += '<li><a href="/radio-tv/day-of-discovery/home.aspx">Day Of Discovery</a></li>';
		functional += '<li><a href="/radio-tv/discover-the-word/home.aspx">Discover The Word</a></li>';
		functional += '<li><a href="/radio-tv/words-to-live-by/home.aspx">Words To Live By</a></li>';
		functional += '<li><a href="/radio-tv/sports-spectrum/home.aspx">Sports Spectrum</a></li>';
		functional += '</ul>';
		functional += '</td>';
		functional += '<td style="vertical-align: top;"><ul>';
		functional += '<li><a href="/bible-study/ten-reasons-to-believe/home.aspx">10 Reasons To Believe</a></li>';
		functional += '<li><a href="/bible-study/answers-to-tough-questions/home.aspx">Answers To Tough Questions</a></li>';
		functional += '<li><a href="/bible-study/been-thinking-about/home.aspx">Been Thinking About</a></li>';
		functional += '<li><a href="/bible-study/discovery-series/home.aspx">Discovery Series</a></li>';
		functional += '<li><a href="/personal-relationship-with-god.aspx">Personal Relationship With God</a></li>';
		functional += '<li><a href="/bible-study/strength-for-the-journey/home.aspx">Strength For The Journey</a></li>';
		functional += '</ul>';
		functional += '</td>';
		functional += '<td style="vertical-align: top;"><ul>';
		functional += '<li><a href="/about/introduction.aspx">Introduction</a></li>';
		functional += '<li><a href="/about/mission-and-vision.aspx">Mission And Vision</a></li>';
		functional += '<li><a href="/about/history.aspx">History</a></li>';
		functional += '<li><a href="/about/principles.aspx">Principles</a></li>';
		functional += '<li><a href="/about/service-opportunities/jobs.aspx">Employment Opportunities</a></li>';
		functional += '<li><a href="/about/service-opportunities/volunteer-opportunities.aspx">Volunteer Opportunities</a></li>';
		functional += '<li><a href="/info/contact-us.aspx">FAQs</a></li>';
		functional += '</ul>';
		functional += '</td>';
		functional += '</tr>';
		functional += '</tbody>';
		functional += '</table>';
		functional += '</div>';

		$('div#features').after(functional);

		// Footer
		$("div.home div#footer").css({backgroundColor:'#848453',width:'960px'});

		// Final Cleanup
		$('div#sleeve').remove();
		$('div#tools').remove();
		$('div.header').remove();
		$('#footer .line:last').remove();
		$('#pageBottom').remove();

		// Add Event Listeners
		$('div.collapse a').livequery('click', toggleBox);

		var els = ['#cell-left', '#cell-right', '#cell-middle'];
		var $els = $(els.toString());
	
		$els.sortable({
			items: 'div.movable',
			handle: 'div.movable h2',
			cursor: 'move',
			//cursorAt: { top: 2, left: 2 },
			//opacity: 0.8,
			//helper: 'clone',
			appendTo: 'body',
			//placeholder: 'clone',
			//placeholder: 'placeholder',
			connectWith: els,
			start: sortableStart,
			change: sortableChange,
			update: sortableUpdate
		});
	}
);

var getAd = function(ad_index,ad_url,ad_title,ad_image) {
	if(ad_index==0){
		var displayStatus = 'block';
	} else {
		var displayStatus = 'none';
	}
	return '<div id="ad_'+ad_index+'" style="display:'+displayStatus+';float:left"><a href="'+ad_url+'" title="'+ad_title+'"><img width="360" height="188" border="0" src="/uploadedImages/Site-Wide_Promotions/Resources_For_Everyone/'+ad_image+'" alt="'+ad_title+'" title="'+ad_title+'"/></a></div>';
};

var nextAd = function() {
	$('div#ad_'+adCurrentIndex).hide();
	adCurrentIndex = (adCurrentIndex + 1) % adNumber;
	$('div#ad_'+adCurrentIndex).fadeIn();
};

var toggleBox = function(e)
{
	var parentContainer = this.parentNode.parentNode.parentNode;
	var targetContent = $('div.box_state', this.parentNode.parentNode.parentNode);

	if (targetContent.css('display') == 'none') {
		targetContent.slideDown(300);
		$(parentContainer).removeClass('box_collapsed');
		setCookie('state_'+$(this).attr('title'),'opened',365);
	} else {
		targetContent.slideUp(300);
		$(parentContainer).addClass('box_collapsed');
		setCookie('state_'+$(this).attr('title'),'closed',365);
	}

	return false;
};

var sortableStart = function(e, ui){

};

var sortableChange = function(e, ui){

};

var sortableUpdate = function(e, ui){
	//console.log( $(this).sortable('serialize') );
	//function(e, ui){alert( $els.sortable('serialize')+' hello')}
};

function setCookie(name,value,days) {
  var expires = "";
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		expires = "; expires="+date.toGMTString();
	}
	document.cookie = name+"="+value+expires+"; path=/";
}

function getCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function deleteCookie(name) {
	setCookie(name,"",-1);
}
