var promos = new Array(); 
/* // Uncomment this to add multiple random promos
// For each random promo, add one of these: 
promos.push(new Array(
	'Shine a Light', // Headline
	'For a world in need of hope, love, and peace, our work is essential. So is your support.', // Promo text
	'Donate Today', // Content of button
	'https://commerce.cathedral.org/exec/cathedral/donation', // URL to go to when button is clicked
	'red' // Promo color: possible values 'red', 'purple', 'yellow'
));
random = Math.round(Math.random()*(promos.length-1)); */

$(document).ready(function(){
	$('#new-billboard').addClass('active');
	$('#new-billboard ul').cycle().css('position','static');
	if( $('#promo').length > 0 ){
		if(promos.length > 0){
			$('#promo')
				.addClass( promos[random][4] )
				.find('h2')
					.html( promos[random][0] )
					.end()
				.find('p')
					.html( promos[random][1] + ' <a href="' + promos[random][3] + '">' + promos[random][2] + '</a>' );
		} 
		var height = $('#new-billboard').height();
		$('#new-billboard').css('height',height+'px');
		$('#new-billboard #promo').css({
			'position': 'absolute',
			'top': '0',
			'right': '0',
			'z-index': 100
		});
		$('#new-billboard li').css('height', ($('#new-billboard #promo').height()+30)+'px');
	}else{
		$('#new-billboard').css('height','245px');
	}
	if($("form input")) {
		var storeVal = $("form input").val();
		$("form input").focus(function(){
			$(this).attr("rel", this.value);
			this.value = "";
		});
		$("form input").blur(function(){
			if($(this).val() == ""){
				this.value = $(this).attr("rel");
			}
		});
	}
	if($("#events")) { //eventList to show and hide extra info for events.
		var evList = new EventList({
			'list' : "#sidebar #events",
			'eventHolder' : 'div',
			'selector' : "#form-events",
			'selectionHeadline' : "#sidebar h4",
			'eventHeadline' : "#sidebar ul h4",
			'noEvents' : "<div style=\"text-align:center; font:12px/18px Georgia, Times, serif;\">There are no scheduled events.</div>",
			'showText' : "more",
			'hideText' : "collapse"
		});
		evList.setChange("#form-events #elm-events");
		evList.start();
	}


	if($("#form-calendar").length >= 1) {
		var calendar = new Calendar({
			'calendar' : '.calendar table',
			'eventSilo' : '#cal-list',
			'monthClass' : '.in_month',
			'weekClass' : '.in_week',
			'defaultView' : 'week',
			'changeView' : '#elm-cal_view',
			'selectionHeadline' : '#cal-list h2',
			'noEvents' : '<div class="cal-event2"><h3>There are no scheduled events.</h3></div>',
			'noEventsClass' : '.cal-event2',
			'stickyEvent' : '#cal-list .ongoing',
			'eventElem' : '.cal-event ul li',
			'stepForward' : '#cal-list .next a',
			'stepBackward' : '#cal-list .prev a',
			'filters' : '.filter',
			'filterMaster' : '#elm-cal_all',
			'filterBtn' : '#btn_filter'
		});
		calendar.start();
	}
	if($("#form-tour_cal").length >= 1) {
		var calendar = new MonthlyCal();
		calendar.setCalendar(calendar);
			//set events
			$("#elm-tour_months").change( function(){ calendar.setCalendar(calendar); });
	}
	if($("#gallery-photo").length >=1) {
		var gallery = new Gallery( {
			'elm': $(".gallery-post div ul"),
			'show': 6
		} );
			gallery.setNext($(".gallery-post a.next"));
			gallery.setPrev($(".gallery-post a.prev"));
			gallery.start();
	}
	if($("#webcast").length >=1) {
		var gallery = new Gallery( {
			'elm': $(".spot-post div ul"),
			'show': 1,
			'speed': 2500
		} );
			gallery.setNext($(".spot-post a.next"));
			gallery.setPrev($(".spot-post a.prev"));
			gallery.start();
	}

});

Calendar = function(data) {

//private required variables ---
	var cal = $(data['calendar']); //calendar control
	cal.eventSilo = $(data['eventSilo']); //where the events load up
	cal.monthClass = data['monthClass']; //class given to those dates in the month
	cal.weekClass = data['weekClass']; //class given to those dates in present week
	cal.noEvents = data['noEvents']; //content to display if no events present
	cal.noEventsClass = data['noEventsClass']; //class to give noEvents element
	cal.eventElem = $(data['eventElem']); //this is the event element that holds individual information
	cal.eventDay = $( String( data['eventElem'].split(" ", 1) ) );
	cal.startDay;
	cal.endDay;
	cal.curView;

	cal.each(function(){ if(this.tagName.toLowerCase() == "table"){ cal.stepDay = $(data['calendar'] + " td a"); } });

//private optionals
	if(data['changeView']) cal.changeView = $(data['changeView']);
	(!data['defaultView']) ? cal.defaultView = "week" : cal.defaultView = data['defaultView'];
	if(data['selectionHeadline']) cal.selectionHeadline = $(data['selectionHeadline']);
	if(data['stepBackward']) cal.stepBackward = $(data['stepBackward']);
	if(data['stepForward']) cal.stepForward = $(data['stepForward']);
	if(data['stickyEvent']) cal.stickyEvent = $(data['stickyEvent']);

	//filters set up at end
	if(data['filters']) cal.filters = $(data['filters']);
	if(data['filterMaster']) cal.filterMaster = $(data['filterMaster']);
	if(data['filterBtn']) cal.filterBtn = $(data['filterBtn']);

//private methods
	var allFilters = function() {
		//alert(cal.filterMaster.attr("checked"));
		if(!cal.filterMaster.attr("checked")){
			cal.filters.each(function(){ $(this).removeAttr("checked"); });
		}else{
			cal.filters.each(function(){ $(this).attr("checked", "checked"); });
		}
	}
	var checkMaster = function() {
		if(cal.filterMaster) {
			if(!$(this).attr("checked")) {  cal.filterMaster.removeAttr("checked"); }
		}
	}
	var createNoEvent = function(){
		if( $(cal.noEventsClass).length == 0 ) {
			(cal.stickyEvent && $(cal.stickyEvent).length > 0) ?
				$(cal.stickyEvent).after(cal.noEvents)
			:
				$(cal.selectionHeadline).after(cal.noEvents);
		}
	}
	var getView = function(){
		(cal.changeView)? view = $(cal.changeView).val() : view = cal.defaultView;
		return view;
	}
	var getWeek = function() {
		cal.curWeek = $(cal.weekClass).length;
		cal.startDay = 0;
		$(cal.weekClass).each(function(){
			if (cal.startDay == 0) { cal.startDay = $(this).children().html(); }
			cal.endDay = $(this).children().html();
		});
	}
	var hideAllEvents = function(){
		if(cal.filters) cal.eventElem.hide(); //<- for filters
		cal.eventDay.hide();
	}
	var setCalendar = function() {
		getWeek();
		cal.curView = getView();
		setCalHeading();
		// create a no events warning
		createNoEvent();
		hideAllEvents();
		showCurEvents();
		setStates();
	}
	var setCalHeading = function() {
		if(cal.selectionHeadline){
			headline = cal.selectionHeadline.text();
			headline = headline.split(" ", 1);
			(cal.curView == "week") ?
				heading = headline[0] + " " + cal.startDay + " &ndash; " + cal.endDay
			:
				heading = headline[0] + " " + cal.startDay;
			cal.selectionHeadline.html(heading);
		}
	}
	var setFilters = function() {
		if(cal.filters){
			var checked = new Array;
			cal.filters.each(function(){
				if($(this).attr("id") != "elm-cal_all"){
			   		if( ($(this).attr("checked")) ) { //&& $(this).attr("id") != "elm-cal_all"
						checked.push( $(this).val() );
					}

				}
			});
			return checked;
		}
	}
	var setNewView = function(event) {

		$(cal.weekClass).each( function(){ $(this).removeClass( (cal.weekClass.slice(1)) ).addClass( (cal.monthClass.slice(1)) ); } );
		$(cal.monthClass).each( function(){ lastDay =  $(this).children().html(); } );

		if(event != "view") {
			switch(event.data) {
				case 1:
					(cal.curView == "week") ?
						dateCheck = parseInt(cal.startDay) + 7
					:
						dateCheck = parseInt(cal.startDay) + 1;

					(dateCheck) > lastDay ?
						cal.startDay = lastDay
					:
						cal.startDay = dateCheck;

				break;
				case 0:
					cal.startDay = $(event.target).text();
				break;
				case -1:
					(cal.curView == "week") ?
						dateCheck = parseInt(cal.startDay) - 7
					:
						dateCheck = parseInt(cal.startDay) - 1;

					(dateCheck) < 1 ?
						cal.startDay = 1
					:
						cal.startDay = dateCheck;

				break;
			}
		}

		$(cal.monthClass).each(function(){
				if($(this).children().html() == cal.startDay) {
					day = $(this);
					$(this).removeClass( (cal.monthClass.slice(1)) ).addClass( (cal.weekClass.slice(1)) );
				};
		});

		if(cal.curView == "week") {
			$(day).siblings().each( function(){
				if($(this).children().length >= 1){
					$(this).removeClass( (cal.monthClass.slice(1)) ).addClass( (cal.weekClass.slice(1)) );
				}
			});
		}

		setCalendar();

		return false;
	}
	var setStates = function() {
		if(data['stepForward'] && data['stepBackward']){
			$(cal.weekClass).each( function(){ lastDay1 =  parseInt($(this).children().html()); } );
			$(cal.monthClass).each( function(){ lastDay2 =  parseInt($(this).children().html()); } );
			lastDay1 > lastDay2 ? lastDay = lastDay1 : lastDay = lastDay2;

			$(cal.weekClass).each( function(){
				if(lastDay != $(this).children().html()) { $(data['stepForward']).removeClass("off"); }
				if($(this).children().html() != 1){	$(data['stepBackward']).removeClass("off"); }
			});
			$(cal.weekClass).each( function(){
				if(lastDay == $(this).children().html()) { $(data['stepForward']).addClass("off"); }
				if($(this).children().html() == 1){	$(data['stepBackward']).addClass("off"); }
			});
		}
	}
	var showCurEvents = function() {

		showFilteredEvents(setFilters());

		cal.eventDay.each(function(){
			date = this.id;
			date = parseInt(date.slice(4));
			var show = 0;

			if( (date >= cal.startDay) && (date <= cal.endDay) ) {
				$(this).children().children().filter(data['eventElem']).each(function(){
					//alert($(this).html());
					if( ($(this).css("display") == "list-item") || ($(this).css("display") == "block")){
						show = 1;
					}
				});
				if(show == 1){
					$(cal.noEventsClass).remove(); //if there are events, remove no events "warning"
					toggleEvent(this);
				}
			}
		});
	}
	var showFilteredEvents = function(filtered) {
		if(cal.filters){
			for(i=0;i < filtered.length; i++) {
				classPiece = "." + filtered[i];
				//alert(classPiece);
				cal.eventElem.filter(classPiece).show();
			}
		}
	}
	var switchView =  function() {
		cal.curView = getView();
		getWeek();
		setNewView("view");
	}
	var toggleEvent = function(elm) { $(elm).toggle(); }


//return public methods ---
	return {
		getEndDay: function(){ return cal.endDay; },
		getStartDay: function(){ return cal.startDay; },
		setControls: function(){
			if(cal.stepForward) cal.stepForward.bind("click",1,setNewView);
			if(cal.stepBackward) cal.stepBackward.bind("click",-1,setNewView);
			if(cal.stepDay) cal.stepDay.bind("click",0,setNewView);
			if(cal.changeView) cal.changeView.bind("change", switchView);
			if(cal.filters) cal.filters.bind("click", checkMaster);
			if(cal.filterMaster) cal.filterMaster.unbind("click").bind("click", allFilters);
			if(cal.filterBtn) { cal.filterBtn.bind("click", setCalendar); cal.filterBtn.click(function(){ return false;});}
		},
		start: function(){ this.setControls(); setCalendar(); },
		setHeading: function(){ setCalHeading(); }
	};

}

EventList = function(data) {

//private required variables ---
		var list = $(data['list']);
		list.noEvents = data['noEvents'];
		list.showText = data['showText'];
		list.hideText = data['hideText'];
		list.moreLink = "<a href=\"\" class=\"lnk_more\">" + list.showText  + "</a>";

//private optionals ---
		if (data['selector']) {
			list.selector = $(data['selector']);
			list.selector.toggle(); //should be hidden by default
		}
		//hide progressive enhancement main headlines
		if(data['selectionHeadline']){ $(data['selectionHeadline']).toggle(); }
		//if headlines are the same tag type as above, lets show these
		if(data['eventHeadline'] && $(data['eventHeadline']).css('display') == "none" ){
			$(data['eventHeadline']).toggle();
		}

//private methods ---
		//round about way of getting correct children
		var setKids = function(){
			list.kids = list.add(data['list']+" "+data['eventHolder']).not(".info");
			list.kids = list.kids.not(":first");
		}
		//hide the extra info
		var hideMoreInfo = function(init) {
			var $events = $("#sidebar #events ul li").children();
			$events.each(function(){
				if( $(this).attr("class") == "info" ) {
					if(init){ $(this).before(list.moreLink); }
					else {$(".lnk_more").each(function(){$(this).text("more")});}

					$(this).css({display: "none"})
							.parent().removeClass("on");
				};
			});
		}
		//collapse all events
		var closeOtherEvents = function(selection) {
			selection.parent().parent().children().each(function(){
				if($(this).attr("class") == "on"){
					$(this).removeClass("on");
					$(this).children(".info").toggle();
					$(this).children(".lnk_more").text("more");
				}
			});
		}


//return public methods ---
		return {
			setChange: function(elm) {
				$(elm).change(function(){
					var eventlist = "#" + $(this).val();
					setKids();
					list.kids.hide();
					hideMoreInfo();
					$(eventlist).length > 0 ? $(eventlist).show() : $(list.selector).after(list.noEvents);
				});
			},
			start: function(){
				setKids();
				//hide all events except for the first
				list.kids.each(function(){ if (!$(this).is("#events1")) { $(this).toggle(); }	} );
				hideMoreInfo(1);
				//"more" link functionality
				$(".lnk_more").click(function(){
					//check to see if you are trying to collapse the same event or open a new one
					if($(this).parent().attr("class") == "on") {
						closeOtherEvents($(this));
					} else {
						closeOtherEvents($(this));
						$(this)
							.text(list.hideText)
							.siblings(".info").toggle()
							.parent().toggleClass("on");
					}
					return false;
				});
			}
		};

	}

function MonthlyCal() { }
	MonthlyCal.prototype.noEvents = "<div class=\"cal-event2\"><h4>No scheduled events.</h4></div>";

	MonthlyCal.prototype.setCalendar = function(obj) {

		//set up Heading
		obj.setCalHeading();
		startDay = obj.getView();

		// create a no - events warning
		if( $(".cal-event2").length == 0 ) { $("#tour-cal .tour-register").after(obj.noEvents); }

		$(".cal-event").each(function(){
			$(this).hide();	//hide any event days

			date = this.id;
			date = parseInt(date.slice(6));
			if( (date == startDay) ) {
				$(".cal-event2").remove(); //if there are events, remove no events "warning"
				obj.toggleEvent(this);
			}

		});

	}
	MonthlyCal.prototype.getView = function() { return $("#elm-tour_months").val(); }
	MonthlyCal.prototype.setCalHeading = function() {
		heading = $("#elm-tour_months").val();
		$("#elm-tour_months option").each(function() {
			if ($(this).val() == heading ) {
				heading = $(this).text();
			}
		});
	}
	MonthlyCal.prototype.toggleEvent = function(elm){ $(elm).toggle(); }

Gallery = function(data) {

	//private variables
	var gallery = data['elm'];
	gallery.shown = data['show'];

	if(!data['speed']){
		gallery.speed = "slow";
	} else {
		gallery.speed = data['speed'];
	}

	//variables init on instantation
	gallery.kids = $(gallery).children();
	gallery.size = $(gallery).children().length;
	gallery.presentView = $(gallery).children(":first"); //who is the leftmost child shown in viewport?
	gallery.css({position: "relative"});  //set the gallery to be able to move it
	gallery.css({left: "0px"});  //set the gallery to be able to move it

	//give it a width that will be much larger than actually needed
	gallery.css({width: (gallery.size * 1000) + "px"});

	var getElmSize = function(elm) {
		size = parseInt(elm.css("width"))
				+ parseInt(elm.css("padding-right"))
				+ parseInt(elm.css("padding-left"))
				+ parseInt(elm.css("border-left-width"))
				+ parseInt(elm.css("border-right-width"));
		return size;
	};
	var move = function(event) {

		$(event.target).unbind("click",move);

		presentPos = parseInt(gallery.css("left"));
		switch(event.data) {
			case 1:
				if(gallery.presentView.next().length > 0) {
					presentPos -=  getElmSize(gallery.presentView);
					gallery.presentView = gallery.presentView.next();
					gallery.prev.fadeIn("slow");

					if(isLastElm()) { gallery.next.fadeOut("slow"); }
				}
			break;

			case -1:
				if(gallery.presentView.prev().length > 0) {
					presentPos +=  getElmSize(gallery.presentView.prev());
					gallery.presentView = gallery.presentView.prev();
					gallery.next.fadeIn("slow");

					if(isFirstElm()) { gallery.prev.fadeOut("slow"); }
				}
			break;
		}

		var eVdata = event.data;
		var eVtarget = event.target;

		gallery.animate({left: presentPos+"px"}, gallery.speed, function(){ takeAction($(eVtarget), eVdata); } ); //move gallery

	};
	var isLastElm = function() {
		for(i=0;i<gallery.size;i++){
			if(gallery.kids.eq(i).html() == gallery.presentView.html()) {
				if( (i + gallery.shown) == gallery.size){ return true; }
			}
		}
	};
	var isFirstElm = function() {
		if(gallery.presentView.prev().length == 0) return true;
	};

	var takeAction = function(elm, dir) {
		elm.bind("click", dir, move);
		elm.click(function(){ return false; });
	}

	//public var / methods
	return {
		setNext : function(elm) { gallery.next = elm; },
		setPrev : function(elm) { gallery.prev = elm; },
		start: function(){
			gallery.prev.toggle();
			takeAction(gallery.next, 1);
			takeAction(gallery.prev, -1);
		}
	};
}	