/* Override stupid convio timeout... */
window['keepAlive'] = function() { console.log('overridden keep alive... should not show alert statement anymore!'); return true; }


function get_param(name) {
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );
	return (results != null) ? results[1] : '';
}
	
function iclMediaMeasure(ajaxData) {
	// Ajax Proxy
	var paramObj = {};
	var params = ajaxData.data.split('&');
	var paramObj = {};
	for(var i=0; i<params.length; i++) {
		var line = params[i].split('=');
		if(line.length>1) {
			paramObj[line[0]] = line[1];
		}
	}
	paramObj['cnv_url'] = ajaxData.url;
	ajax_proxy(paramObj, { dataType: "text", success: ajaxData['success'], error: ajaxData['error'], type: "POST" });

	// Non- ajax proxy
	/* $.ajax({
		type: "GET",
		url: ajaxData.url,
		data: ajaxData.data,
		success: ajaxData.success,
		error: ajaxData.error
	});*/
}

// Update this function for production
function hashFormSubmit(searchValue, searchPage) {
//	development
//	if(typeof(searchPage) != "string") searchPage = "media";
//	production
	if(typeof(searchPage) != "string") searchPage = "PageServer?pagename=media";
	
	var pos = window.location.href.lastIndexOf('/');
	window.location.href = window.location.href.substr(0,pos+1) + searchPage + "#page:search;searchString:" + escape(searchValue.replace(/:/, " ")) + ";tab:All";
	return false;
}

function searchFocusBlur() {
	$('#searchForm #search_field, #searchForm #searchField').focus(function(){
		$(this).css({backgroundColor:"#e5f0f9"});
	});
	$('#searchForm #search_field, #searchForm #searchField').blur(function(){
		$(this).css({backgroundColor:"#d2e2ef"});
	});
	
	$('#tell_a_friend input,#tell_a_friend textarea, input#zip_code_church_finder').focus(function(){
		$(this).css({backgroundColor:"#ebebe1"});
	});
	$('#tell_a_friend input,#tell_a_friend textarea, input#zip_code_church_finder').blur(function(){
		$(this).css({backgroundColor:"#dbdbcf"});
	});
	
	$('#get_in_touch input, #get_in_touch textarea').focus(function(){
		$(this).css({backgroundColor:"#f4f4ec"});
	});
	$('#get_in_touch input, #get_in_touch textarea').blur(function(){
		$(this).css({backgroundColor:"#e9e9de"});
	});
};




function convioFormCleanup() {
	if ($("form[id^='survey_']").length == 1) {
		//alert('hi');
	}
}

function submit_ajax_form_1(e) {
	var fields = {
		email: {
			selector: "#ajax_form input#email",
			validationRegex: "^([A-Za-z0-9_.-])+\@([A-Za-z0-9_.-])+\.([A-Za-z]{2,4})$",
			errorCallback: function() {$("label#email_error").show();},
			validationCallback: function () {return true;}
		},
		subject: {
			selector: "#ajax_form input#subject",
			validationRegex: "^.+$",
			errorCallback: function() {
				$("label#subject_error").show();
				$("input#subject").focus();
			},
			validationCallback: function () {return true;}
		},
		comment: {
			selector: "#ajax_form input#comment",
			validationRegex: "^.+$",
			errorCallback: function() {
				$("label#comment_error").show();
				$("textearea#comment").focus();
			},
			validationCallback: function () {return true;}		
		}
	};
	
	$('.error').hide();

	submit_ajax_form(fields, "json/ajax-form/bin/process.php", function() {
			$('#contact').html("<div id='message'></div>");
			$('#message').html("<h2>Contact Form Submitted!</h2>")
			.append("<p>We'll be in touch soon.</p>")
			.hide()
			.fadeIn(1000, function() {
				$('#message').append("<img id='checkmark' src='images/check.png' />");
			});
		});
	return false;
}

function submit_ajax_form(fields, postURL, successCallback) {
	// validate and process form
	var dataString = "";
	var dataObj = {};
	for(var i in fields) {
		var error = false;
		var fieldVal = $(fields[i].selector).val();
		if(fields[i].validationRegex != "") {
			var regex = new RegExp(fields[i].validationRegex);
			if(regex.test(fieldVal) == false) {
				error = true;	
			}
		}
		if(error == false) {
			error = fields[i].validationCallback();
		}
		if(error == true) {
			fields[i].errorCallback();
			return false;
		} else {
			if(dataString != "") dataString += "&";
			dataString += i + "=" + (fieldVal);
			dataObj[i] = (fieldVal);
		}
	}
/*	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	var email = $("input#email").val();
	if(reg.test(email) == false) {
		var errorMessage = 'Please use proper e-mail format (e.g. joe@example.com)';
		$("label#email_error").show();
		return false;
	};	
	
	var subject = $("input#subject").val();
	if (email == "") {
		$("label#subject_error").show();
		$("input#subject").focus();
		return false;
	}
	
	var comment = $("textearea#comment").val();
	if (comment == "") {
		$("label#comment_error").show();
		$("textearea#comment").focus();
		return false;
	}
	var dataString = 'email='+ email + '&subject=' + subject + '&comment=' + comment;
	//alert (dataString);return false;
*/	
	dataObj['cnv_url'] = postURL;
	//ajax_proxy(dataObj, { dataType: "text", url: "http://www.gmodev2.com/sandboxes/mikeweimer/ajax_proxy.php", type: "POST", success: successCallback });		// Comment out this line for production
	// Uncomment this section for production
	$.ajax({
		type: "POST",
		url: postURL,
		data: dataString,
		success: successCallback
	});
	return false;
}

function ajax_proxy(fields, ajaxExtend, ajax_proxy_form_selector) {
	// Can set ajaxExtend to {success: someCallbackFunction} to provide a callback
	if(typeof(ajax_proxy_form_selector) != "string") {
		ajax_proxy_form_selector = "#ajax_id_proxy";
	}
	// Extract the information for the Convio ajax proxy form
	var post_url = $(ajax_proxy_form_selector).attr("action");
	var method = $(ajax_proxy_form_selector).attr("method");
	var attr = {};
	attr["cnv_url"] = $(ajax_proxy_form_selector + " input[name=cnv_url]").val();
	attr["auth"] = $(ajax_proxy_form_selector + " input[name=auth]").val();
	// Merge in any extra parameters you want to send
	$.extend(true, attr, fields);
	var ajaxParams = {
		type: method,
		url: post_url,
		data: attr
	};
	$.extend(true, ajaxParams, ajaxExtend);
	// Do the ajax call
	$.ajax(ajaxParams);
}

function ajaxForm(name) {
	$('#ajax_form .NetscapeFix').next().remove();
	$('#ajax_form .NetscapeFix').next().remove();
	$('#ajax_form .Explicit').next().remove();
	$('#ajax_form .Explicit').remove();
	$('.error').hide();
	$('#foot form#survey_2880 input#1290_2880_1_3881, #foot form#survey_2880 input#1290_2880_2_3882, #foot form#survey_2880 textarea').css({backgroundColor:"#44443d"});
	$('#foot form#survey_2880 input#1290_2880_1_3881, #foot form#survey_2880 input#1290_2880_2_3882, #foot form#survey_2880 textarea').focus(function(){
		$(this).css({backgroundColor:"#818174"});
	});
	$('#foot form#survey_2880 input#1290_2880_1_3881, #foot form#survey_2880 input#1290_2880_2_3882, #foot form#survey_2880 textarea').blur(function(){
		$(this).css({backgroundColor:"#44443d"});
	});
	
	//document.getElementById("ACTION_SUBMIT_SURVEY_RESPONSE").onclick= submit_ajax_form_1;
	//$("#ajax_form input[name='ACTION_SUBMIT_SURVEY_RESPONSE']").click(submit_ajax_form_1);
	//document.getElementById("survey_2880").onsubmit= submit_ajax_form_1;
};

/*function loginPanel(){
	$("#login").click(function(){
		if ($('#panel').hasClass('open')) {
			//$(".main_frame").animate({marginTop:"30px"}, 500);
			$("#panel,#overflow").animate({height:0, backgroundPosition: '(0 -354px)'}, 500);
			$('#panel').removeClass('open'); 
		} else {
			$("#panel,#overflow").animate({height:360, backgroundPosition: '(0 0)'}, 500); 
			//$(".panel_content").css('margin-top','10px');
			//$(".main_frame").animate({marginTop:"370px"}, 500);
			$('#panel').addClass('open'); 
		}
		return false;
	});
};

function loginPanel(){
	$("#login").click(function(){
		if ($('#panel_bg').hasClass('open')) {
			//$(".main_frame").animate({marginTop:"30px"}, 500);
			$("#login_bg").animate({top: -130}, 500);
			$("#panel_bg").animate({height: 160, backgroundPosition: '(0 -210px)'}, 500);
			$('#panel_bg').removeClass('open'); 
		} else {
			$("#login_bg").show().animate({top: 315}, 500);
			$("#panel_bg").animate({height: 510, backgroundPosition: '(0 148px)'}, 500); 
			//$(".panel_content").css('margin-top','10px');
			//$(".main_frame").animate({marginTop:"370px"}, 500);
			$('#panel_bg').addClass('open'); 
		}
		return false;
	});
};*/


/*function switchFormFieldState(elementId, newColor, newState){
	var element = document.getElementById(elementId);
	element.className=newColor;
	element.value=newState;
}

function stickySwitchFormFieldState(elementId, newColor, newState, expectedState){
	var element = document.getElementById(elementId);
	if(element.value == expectedState) {
		element.className=newColor;
		element.value=newState;
	}
}*/

function hover() {
	$('.hoverable').hover(
	  function() {
		 $(this).addClass('hovered');
	  }, function() {
		 $(this).removeClass('hovered');
	  }
   );
}

function equalHeight(group) {
	tallest = 0;
	group.each(function() {
		thisHeight = $(this).height();
		//alert(thisHeight);
		if ($('.col3').hasClass('.double')) {
			thisHeight = thisHeight - 31;
		} 
		if(thisHeight > tallest) {
			tallest = thisHeight;
		}
	});
	group.height(tallest);
}


function setPage() {
	var currentTitle = '';
	var indexLast = null;
	currentTitle = document.title;
	indexLast = currentTitle.lastIndexOf(':');
	currentTitle = currentTitle.substring('16',indexLast);
	
	function sidebarImageKnowGod() { return [      
		['../images/icl3/promo_small_nbg.jpg','http://www.ichristianlife.com/site/PageServer?pagename=gmo__action__believers_guide'],  
		['../images/icl3/promo_small_jesusfilm.jpg','http://www.ichristianlife.com/site/PageServer?pagename=media#page:search;searchString:;tab:AuthorDrilldown;p:1;oth.aut:jesus_film_project'],
		['../images/icl3/promo_small_holy_spirit_guide.jpg','http://www.ichristianlife.com/site/PageServer?pagename=gmo__action__holy_spirit_guide'],
		['../images/icl3/promo_small_30_day_guide.jpg','http://www.ichristianlife.com/site/PageServer?pagename=gmo__action__30_day_guide'],
		['../images/icl3/promo_small_prayer_partner.jpg','http://www.ichristianlife.com/site/PageServer?pagename=gmo__action__partner_in_prayer'],
		['../images/icl3/promo_small_study_the_bible.jpg','http://www.ichristianlife.com/site/PageServer?pagename=media#page:search;searchString:;tab:AlbumDrilldown;p:1;oth.alb:introductory_bible_study'],
		['../images/icl3/promo_small_share_faith.jpg','http://www.ichristianlife.com/site/PageServer?pagename=gmo__action__share_an_email']
	 ];}
	 
	 function sidebarImageNewLife() { return [   
		['../images/icl3/promo_small_join_team.jpg','../connect_volunteer'], 
		['../images/icl3/promo_small_30_day_guide.jpg','../30_day_guide'],
		['../images/icl3/promo_small_share_faith.jpg','../share_email']
	 ];}
	 
	 function sidebarImagePrayer() { return [   
		['../images/icl3/promo_small_join_team.jpg','../connect_volunteer'], 
		['../images/icl3/promo_small_join_team.jpg','../connect_volunteer'], 
		['../images/icl3/promo_small_30_day_guide.jpg','../30_day_guide'], 
		['../images/icl3/promo_small_share_faith.jpg','../share_email']
	 ];}
	 
	 function sidebarImageBible() { return [   
		['../images/icl3/promo_small_join_team.jpg','../connect_volunteer'], 
		['../images/icl3/promo_small_study_the_bible.jpg','../bible_study'],
		['../images/icl3/promo_small_30_day_guide.jpg','../30_day_guide'],
		['../images/icl3/promo_small_share_faith.jpg','../share_email']
	 ];}
	 
	 function sidebarImageCommunity() { return [     
		['../images/icl3/promo_small_join_team.jpg','../connect_volunteer'], 
		['../images/icl3/promo_small_30_day_guide.jpg','../30_day_guide'], 
		['../images/icl3/promo_small_share_faith.jpg','../share_email']
	 ];}
	 
	 function sidebarImageShare() { return [   
		['../images/icl3/promo_small_join_team.jpg','../connect_volunteer'], 
		['../images/icl3/promo_small_30_day_guide.jpg','../30_day_guide'],
		['../images/icl3/promo_small_share_faith.jpg','../share_email']
	 ];}
	
	function sidebarText() { return [      
		['Know God Home','Search Know God','Knowing God'],  
		['New Life Home','Search New Life','Holy Spirit Guide','New Believers Guide'], 
		['Prayer Home','Search Prayer','Prayer & Worship Opportunities'], 
		['Bible Home','Search the Bible','Read and Listen to the Bible','Study the Bible'], 
		['Community Home','Search Community','Find a Church','Connect with Others'], 
		['Share Home','Search Share','Share your Faith','Become a Volunteer']
	 ];}
	 
	 function sidebarLink() { return [      
		['../know_god',
		 'http://www.ichristianlife.com/site/PageServer?pagename=media&cat=god',
		 '../gmo__action__knowing_god'],
		['../new_life',
		 'http://www.ichristianlife.com/site/PageServer?pagename=media&cat=new life',
		 '../gmo__action__holy_spirit_guide',
		 '../gmo__action__believers_guide'],
		['http://www.ichristianlife.com/site/PageServer?pagename=prayer',
		 'http://www.ichristianlife.com/site/PageServer?pagename=media&cat=prayer',
		 '../prayer_opportunities'],
		['../bible',
		 'http://www.ichristianlife.com/site/PageServer?pagename=media&cat=bible',
		 '../read_listen_bible',
		 '../bible_study_index'],
		['../community',
		 'http://www.ichristianlife.com/site/PageServer?pagename=media&cat=community',
		 '../gmo__action__find_a_church',
		 '../connect_with_others'],  
		['../share',
		 'http://www.ichristianlife.com/site/PageServer?pagename=media&cat=share',
		 '../gmo__action__share_an_email',
		 '../gmo__action__volunteer_online']
	 ];}
	
	
	//var randomNumber1 = Math.ceil(Math.random() * 2);
	//alert(randomNumber1);
	  
	var sidebarImageKnowGod = sidebarImageKnowGod();
	var sidebarImageNewLife = sidebarImageNewLife();
	var sidebarImagePrayer = sidebarImagePrayer();
	var sidebarImageBible = sidebarImageBible();
	var sidebarImageCommunity = sidebarImageCommunity();
	var sidebarImageShare = sidebarImageShare();
	
	var sidebarText = sidebarText();
	var sidebarLink = sidebarLink();
	$('#menu li a').removeClass('current');
	//empty all the text, href, and src attributes
	
	if (currentTitle == 'know god') {
		for (i=0;i<3;i++) {
			$('#sidebar_list' + [i] + '').text('' + sidebarText[0][i] + '').attr("href",'' + sidebarLink[0][i] + '');
		}
		$('#hdr_section_list').html('know god');
		var randomNumberKnowGod = Math.floor(Math.random() * 6);
		$('#sidebar_promo img').attr("src",'' + sidebarImageKnowGod[randomNumberKnowGod][0] + '');
		$('#sidebar_promo').attr("href",'' + sidebarImageKnowGod[randomNumberKnowGod][1] + '');
		$('#menu_know_god').addClass('current');
	} else if (currentTitle == 'new life') {
		for (i=0;i<4;i++) {
			$('#sidebar_list' + [i] + '').text('' + sidebarText[1][i] + '').attr("href",'' + sidebarLink[1][i] + '');
		}
		$('#hdr_section_list').html('new life');
		var randomNumberNewLife = Math.floor(Math.random() * 6);
		$('#sidebar_promo img').attr("src",'' + sidebarImageKnowGod[randomNumberNewLife][0] + '');
		$('#sidebar_promo').attr("href",'' + sidebarImageKnowGod[randomNumberNewLife][1] + '');
		$('#menu_new_life').addClass('current');
	} else if (currentTitle == 'prayer') { 
		for (i=0;i<3;i++) {
			$('#sidebar_list' + [i] + '').text('' + sidebarText[2][i] + '').attr("href",'' + sidebarLink[2][i] + '');
		}
		$('#hdr_section_list').html('prayer');
		var randomNumberPrayer = Math.floor(Math.random() * 6);
		$('#sidebar_promo img').attr("src",'' + sidebarImageKnowGod[randomNumberPrayer][0] + '');
		$('#sidebar_promo').attr("href",'' + sidebarImageKnowGod[randomNumberPrayer][1] + '');
		$('#menu_prayer').addClass('current');
	} else if (currentTitle == 'bible') {
		for (i=0;i<4;i++) {
			$('#sidebar_list' + [i] + '').text('' + sidebarText[3][i] + '').attr("href",'' + sidebarLink[3][i] + '');
		}
		$('#hdr_section_list').html('bible');
		var randomNumberBible = Math.floor(Math.random() * 6);
		$('#sidebar_promo img').attr("src",'' + sidebarImageKnowGod[randomNumberBible][0] + '');
		$('#sidebar_promo').attr("href",'' + sidebarImageKnowGod[randomNumberBible][1] + '');
		$('#menu_bible').addClass('current');
	} else if (currentTitle == 'community') {
		for (i=0;i<4;i++) {
			$('#sidebar_list' + [i] + '').text('' + sidebarText[4][i] + '').attr("href",'' + sidebarLink[4][i] + '');
		}
		$('#hdr_section_list').html('community');
		var randomNumberCommunity = Math.floor(Math.random() * 6);
		$('#sidebar_promo img').attr("src",'' + sidebarImageKnowGod[randomNumberCommunity][0] + '');
		$('#sidebar_promo').attr("href",'' + sidebarImageKnowGod[randomNumberCommunity][1] + '');
		$('#menu_community').addClass('current');
	} else if (currentTitle == 'share') {
		for (i=0;i<4;i++) {
			$('#sidebar_list' + [i] + '').text('' + sidebarText[5][i] + '').attr("href",'' + sidebarLink[5][i] + '');
		}
		$('#hdr_section_list').html('share');
		var randomNumberShare = Math.floor(Math.random() * 6);
		$('#sidebar_promo img').attr("src",'' + sidebarImageKnowGod[randomNumberShare][0] + '');
		$('#sidebar_promo').attr("href",'' + sidebarImageKnowGod[randomNumberShare][1] + '');
		$('#menu_share').addClass('current');
	} else if (currentTitle == 'home') {
		$('.sidebar').hide();
		$('#menu_home').addClass('current');
	}
};

function setSubmenuCurrentState() {
	var pageName = get_param('pagename');
	$('.sidebar_container ul li a').removeClass('sidebar_current');
	var currentURL = window.location.href;
	var loc = currentURL.indexOf('?pagename=') + 10;
	
	// Loop over sidebar links, highlight selected one
	$('.sidebar_container ul li a').each(function() {
		var currentLink = $(this).attr('href');
//		alert('checking link href: ' + currentLink.substr(loc, pageName.length) + ' against pageName: ' + pageName);
		
		if (currentLink.substr(loc, pageName.length) == pageName) {
			
			// If page name is media, make sure we have a matching category as well
			if (pageName == 'media') {
				var loc2 = currentURL.indexOf('&cat=') + 5;
				var catName = get_param('cat');
				if (currentURL.substr(loc2, catName.length) == catName) {
					$(this).addClass('sidebar_current');
				}
			} else {
				$(this).addClass('sidebar_current');
			}
		}
		var loc3 = currentURL.lastIndexOf('/') + 1;
		if ($(this).attr('href').substr(loc3, pageName.length) == pageName) {
			$(this).addClass('sidebar_current');
		}
	});
}

/*
var featuredMediaObj = {
	container: '#featured_media div',
	wordList: ['love','learn','hope','great','power','faith','life','peace','love','learn','hope','great','power','faith','life','peace','god','happiness','people','jesus','believe','help','comfort','disciple','judge','prayer','share','great','sin','death','heaven','kindness','worry','resurrection','peter','john','salvation','grow','life','beauty','sing','powerful','strength','tempted','holy','spirit','cope','righteous','children','parents','woman','home','lonely','forgiveness','community','teaches'],
	commonWords: {'the': 'the','of': 'of','and': 'and','a': 'a','to': 'to','in': 'in','is': 'is','you': 'you','that': 'that','it': 'it','he': 'he','was': 'was','for': 'for','on': 'on','are': 'are','as': 'as','with': 'with','his': 'his','they': 'they','i': 'i','at': 'at','be': 'be','this': 'this','have': 'have','from': 'from','or': 'or','one': 'one','had': 'had','by': 'by','word': 'word','but': 'but','not': 'not','what': 'what','all': 'all','were': 'were','we': 'we','when': 'when','your': 'your','can': 'can','said': 'said','there': 'there','use': 'use','an': 'an','each': 'each','which': 'which','she': 'she','do': 'do','how': 'how','their': 'their','if': 'if','will': 'will','up': 'up','other': 'other','about': 'about','out': 'out','many': 'many','then': 'then','them': 'them','these': 'these','so': 'so','some': 'some','her': 'her','would': 'would','make': 'make','like': 'like','him': 'him','into': 'into','time': 'time','has': 'has','look': 'look','two': 'two','more': 'more','write': 'write','go': 'go','see': 'see','number': 'number','no': 'no','way': 'way','could': 'could','people': 'people','my': 'my','than': 'than','first': 'first','water': 'water','been': 'been','call': 'call','who': 'who','oil': 'oil','its': 'its','now': 'now','find': 'find','long': 'long','down': 'down','day': 'day','did': 'did','get': 'get','come': 'come','made': 'made','may': 'may','part': 'part'},
	jsonURLForWordListGeneration: 'http://service.ichristianlife.com/media/search/?t=jn2',
	keywordIndex: 0,
	wordlistOffset: 0,
	timeForKeyword: Date.UTC((new Date()).getUTCFullYear(), (new Date()).getUTCMonth(), (new Date()).getUTCDate(), 0,0,0,0),
	generateWordListCallback: null,
	getFeaturedMediaCallback: null,
	mediaItemsReturned: 3,
	jsonURLForFeaturedMedia: 'http://service.ichristianlife.com/media/search/?t=jn2&r=3',
	ajaxProxyURL: "http://www.gmodev2.com/sandboxes/mikeweimer/ajax_proxy.php?url=",
	generateWordList: function() {
		// Grab a JSON feed,
		if(featuredMediaObj.jsonURLForWordListGeneration == null) return false;
		ajax_proxy({cnv_url: featuredMediaObj.jsonURLForWordListGeneration}, { dataType: "json", success: function(data, textStatus) {
//		$.getJSON((featuredMediaObj.ajaxProxyURL + escape(featuredMediaObj.jsonURLForWordListGeneration)), function(data) {
			var wordArrays = [];
			var importFields = { 'author':true, 'author_ls':true, 'name':true, 'description':true, 'album':true };
			for(var itemNumber in data.items) {
				var entry = data.items[itemNumber];
				for(var i in importFields) {
					if(typeof(entry[i]) != "undefined") {
						wordArrays.push(featuredMediaObj.removeCommonWords(entry[i].replace(/[.!?:;&'"_]/g, '').split(" ")));
					}
				}
			}
			featuredMediaObj.wordList = [];
			var wordObj = {};
			for(var i=0; i<wordArrays.length; i++) {
				for(var j=0; j<wordArrays[i].length; j++) {
					wordObj[wordArrays[i][j].toLowerCase()] = wordArrays[i][j].toLowerCase();
				}
			}
			for(var i in wordObj) {
				featuredMediaObj.wordList.push(wordObj[i]);
			}
			if(typeof(featuredMediaObj.generateWordListCallback) == 'function') {
				featuredMediaObj.generateWordListCallback();
			}
//		});
	    }});
	},
	removeCommonWords: function(wordArray) {
		var returnArray = [];
		for(var i=0; i<wordArray.length; i++) {
			if(this.commonWords[wordArray[i].toLowerCase()] == null) {
				returnArray.push(wordArray[i]);	
			}
		}
		return returnArray;
	},
	generateWordlistAndGetFeaturedMedia: function() {
		this.generateWordListCallback = this.getFeaturedMedia;
		this.generateWordList();
	},
	featuredMediaTemplate: '<a href="PageServer?pagename=media#page=player/media={name|escape}" class="tab_item"><img src="{thumbnail}" /><h2>{name|uppercase}</h2><p>{description}</p><img src="../images/icl3/icon_{media_type}.gif" class="media_type" /><h3>by {author|uppercase}</h3></a>',
	getFeaturedMedia: function() {
		var jsonURL = featuredMediaObj.jsonURLForFeaturedMedia;
		var intForModulo = featuredMediaObj.timeForKeyword;
		//alert(featuredMediaObj.timeForKeyword);
		while(intForModulo % 10 == 0) intForModulo = intForModulo / 10;
		var chosenWord = featuredMediaObj.wordList[((intForModulo+featuredMediaObj.wordlistOffset) % featuredMediaObj.wordList.length)];
		jsonURL = jsonURL + '&s=' + chosenWord;
		jsonURL = escape(jsonURL);
		$.getJSON((featuredMediaObj.ajaxProxyURL + jsonURL), function(data) {
			var i=0;
			var mediaOutput = '';
			for(var j in data.items) {
				// Extract replacement variables from the template
				var variables = new RegExp("\{([^}]+)\}", "g");
				var entry = data.items[j];
				var tmpTemplate = featuredMediaObj.featuredMediaTemplate;
				var matches = null;
				var replacements = [];
				while((matches = variables.exec(tmpTemplate)) != null) {
					replacements.push(matches[1]);
				}
				// Extract operations from the variable
				for(var k=0; k<replacements.length; k++) {
					var variable = replacements[k];
					var operation = null;
					var spos = replacements[k].indexOf("|");
					if(spos > 0) {
						variable = replacements[k].substring(0, spos);
						operation = replacements[k].substring(spos+1, replacements[k].length);
					}
					var replData = entry[variable];
					var replVariable = "{" + variable + "|" + operation + "}";
					if(operation == 'uppercase') {
						replData = replData.toUpperCase();
					} else if(operation == 'lowercase') {
						replData = replData.toLowerCase();	
					} else if(operation == 'escape') {
						replData = escape(replData);
					} else if(operation == 'lstodash') {
						replData = replData.replace(/_/g,'-');;
					} else {
						replVariable = "{" + variable + "}";
					}
					tmpTemplate = tmpTemplate.replace(replVariable, replData);
				}
				mediaOutput += tmpTemplate;
				//$(featuredMediaObj.container).append(tmpTemplate).fadeIn();
				i++;
				if(i == featuredMediaObj.mediaItemsReturned) break;
			}
			$(featuredMediaObj.container).html(mediaOutput).fadeIn();			
			if(typeof(featuredMediaObj.getFeaturedMediaCallback) == 'function') {
				featuredMediaObj.getFeaturedMediaCallback();
			}
		});
	}
};

function featuredMedia() {
	featuredMediaObj.generateWordlistAndGetFeaturedMedia();
}
function featuredMedia(container, params, category) {
	if(typeof(category) == "undefined" || category == null) {
		category = 'all';	
	}
	if($('#featured_media').length == 0) { return false; }
	var randomWordList = ['love','learn','hope','great','power','faith','life','peace','love','learn','hope','great','power','faith','life','peace','god','happiness','people','jesus','believe','help','comfort','disciple','judge','prayer','share','great','sin','death','heaven','kindness','worry','resurrection','peter','john','salvation','grow','life','beauty','sing','powerful','strength','tempted','holy','spirit','cope','righteous','children','parents','woman','home','lonely','forgiveness','community','teaches'];
	var today = Date();
	var keywordIndex = (Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate(), 0,0,0,0)) % randomWordList.length;
	var chosenWord = randomWordList[keywordIndex];
	var jsonURL = 'http://service.ichristianlife.com/media/search/?t=jn2&r=3';
	jsonURL = jsonURL + '&s=' + chosenWord;
	jsonURL = escape(jsonURL);
	var ajaxProxyURL = "http://www.gmodev2.com/sandboxes/mikeweimer/ajax_proxy.php?url=" + jsonURL;
	$.getJSON(ajaxProxyURL, function(data) {
		$.each(data.items, function(entryIndex, entry) {
				var html = '<a href="http://www.gmodev1and1.com/sandboxes/mikeweimer/www.ichristianlife_v3.com/j/media_player.html&ttl=' + entry.name + '&alb=' + entry.collection + '&aut=' + entry.author + '&typ=' + entry.media_type + '&dsc=' + entry.description + '&trk=' + entry.track + '" class="tab_item">';
				html += '<img src="' + entry.thumbnail + '" />';
				html += '<h1>' + entry.name.toUpperCase() + '</h1>';
				html += '<p>' + entry.description + '</p>';
				html += '<img src="../images/icl3/icon_' + entry.media_type + '.gif" class="media_type" />';
				html += '<h2>' + entry.author.toUpperCase()  + '</h2>';
				html += '</a>';
				$('#featured_media').append($(html)).fadeIn();
		});
	});
}
*/


function equalWidth() {
	var col1Width = 0; //reset
	var col2Width = 0; //reset
	var containerWidth = 0; //reset 
	col1Width = $('.col1').width(); //get the width of #col1
	col1Width = col1Width + 134; //add 94 to account for the borders and margin and padding
	containerWidth = $('#wrap').width(); //get the width of #wrap (the container)
	col2Width = containerWidth - col1Width;
	$('.col2').width(col2Width); //set the width of #col2
	
	
	var col3Width = 0; //reset
	var col4Width = 0; //reset
	var containerWidth2 = 0; //reset
	col3Width = $('.col3').width(); //get the width of #col1
	if ($('.col3').hasClass('.double')) {
		col3Width = col3Width + 72; //add 94 to account for the borders and margin and padding
	} else {
		col3Width = col3Width + 134; //add 94 to account for the borders and margin and padding
	}
	containerWidth2 = $('#wrap2').width(); //get the width of #wrap (the container)
	col4Width = containerWidth2 - col3Width;
	$('.col4').width(col4Width); //set the width of #col2
}

function stickySwitchFormFieldState(elementId, newState, expectedState){
	var element = document.getElementById(elementId);
	if(element.value == expectedState) {
		element.value=newState;
	}
}

function switchField() {
	$(".switch_field_email").focus(function() { stickySwitchFormFieldState($(this).attr("id"), '', 'Email'); });
	$(".switch_field_email").blur(function () { stickySwitchFormFieldState($(this).attr("id"), 'Email', ''); });
	
	$(".switch_field_name").focus(function() { stickySwitchFormFieldState($(this).attr("id"), '', 'Name'); });
	$(".switch_field_name").blur(function () { stickySwitchFormFieldState($(this).attr("id"), 'Name', ''); });
	
	$(".switch_field_comment").focus(function() { stickySwitchFormFieldState($(this).attr("id"), '', 'Comment'); });
	$(".switch_field_comment").blur(function () { stickySwitchFormFieldState($(this).attr("id"), 'Comment', ''); });
	
	$(".switch_field_zip").focus(function() { stickySwitchFormFieldState($(this).attr("id"), '', 'Enter your zip code here...'); });
	$(".switch_field_zip").blur(function () { stickySwitchFormFieldState($(this).attr("id"), 'Enter your zip code here...', ''); });
	
	$(".switch_field_your_email").focus(function() { stickySwitchFormFieldState($(this).attr("id"), '', 'Your email'); });
	$(".switch_field_your_email").blur(function () { stickySwitchFormFieldState($(this).attr("id"), 'Your email', ''); });
	
	$(".switch_field_send_to").focus(function() { stickySwitchFormFieldState($(this).attr("id"), "", "Friend's email"); });
	$(".switch_field_send_to").blur(function () { stickySwitchFormFieldState($(this).attr("id"), "Friend's email", ""); });
	
	$(".switch_field_message").focus(function() { stickySwitchFormFieldState($(this).attr("id"), "", "Message"); });
	$(".switch_field_message").blur(function () { stickySwitchFormFieldState($(this).attr("id"), "Message", ""); });
	
	$(".switch_field_subject").focus(function() { stickySwitchFormFieldState($(this).attr("id"), "", "Subject"); });
	$(".switch_field_subject").blur(function () { stickySwitchFormFieldState($(this).attr("id"), "Subject", ""); });
	
	$(".switch_field_keyword").focus(function() { stickySwitchFormFieldState($(this).attr("id"), "", "Enter keyword here..."); });
	$(".switch_field_keyword").blur(function () { stickySwitchFormFieldState($(this).attr("id"), "Enter keyword here...", ""); });
}

function tab() {
	if ($('.case').length != 0) {
		var tabContainers = $('.case');
		$(tabContainers).hide();
		$('.tab_btn').click(function(){
			$('.tab_btn').removeClass("selected");
			$(tabContainers).hide();
			$('.c' + $(this).attr('id').substr(1,1)).show();
			$(this).addClass("selected");
			return false;
		}).filter(':first').click();
	}
}

function chatNav() {
	var openChatItems = $('.c1 li').length;
	//alert(openChatItems);
}

function formSetup() {
	$(".grid tr:nth-child(2),.grid tr:nth-child(4),.grid tr:nth-child(8),.grid tr:nth-child(5) .Explicit,input[value='Reset']").addClass("hide_item");
	$(".grid #sendtoemail").replaceWith("<input id=\"sendtoemail\" class=\"switch_field_send_to\" name=\"sendtoemail\" type=\"text\" maxlength=\"255\" size=\"40\" value=\"Friend's email\" />");
	$(".grid #message").attr("rows","4");
	$(".grid #subject").attr("value","");
	$("#tell_a_friend #taf_send").after('<div id=\"btn_facebook\">Facebook</div><div id=\"btn_digg\">Digg</div>');
	
	$('#1290_2820_1_3841').attr('value','Email').addClass('switch_field_email');
	$('#1290_2820_2_3842').attr('value','Name').addClass('switch_field_name');
	$('#1290_2820_3_3844').text('Comment').addClass('switch_field_comment');
	$(".grid #message").attr("value","Message").addClass('switch_field_message');
	$(".grid #subject").attr("value","Subject").addClass('switch_field_subject');
	$(".grid #youremail").attr("value","Your email").addClass('switch_field_your_email');
}


/*function tab() {
	var tabContainers = $('.case');
	//$(tabContainers).hide();
	$('.tab_btn').click(function(){
		$('.tab_btn').removeClass("selected");
		$(tabContainers).fadeOut(1000, function () {
			alert('hip');
			//$('.c' + $(this).attr('id').substr(1,1)).show();
			$('.c' + $(this).attr('id').substr(1,1)).fadeIn();
		});
		$(this).addClass("selected");
		return false;
	})//.filter(':first').click();
}*/

$(document).ready(function() {	
	formSetup();
	tab();	
	searchFocusBlur();
	switchField();				   
	hover();
	//loginPanel();
	//equalWidth();
	setPage();
	ajaxForm();
	equalHeight($("#wrap .column"));
	equalHeight($("#wrap2 .column"));
	convioFormCleanup();
	
	
	// Style all input buttons
	/*$('input[type=submit], input[type=reset]').css({
		'float'			: 'none',
		'border'		: '1px solid #000',
		'background'	: '#E5E5DB',
		'padding'		: '5px 8px'
	});*/
	
	// Fix TellAFriend CSS styles
	$('#taf_send').parent('td').css('padding-left', '194px');
	
	// Fix login form styles
	/*$('form[action$=/site/UserLogin] input').css({
		'float'			: 'none',
		'border'		: '1px solid #2C2C27',
		//'background'	: '#E5E5DB',
		'padding'		: '5px 8px'
	});*/
	
	$("#utility td[width='1%']").hide();
	$("#utility td[width='29%']").addClass('sidebar_info');
	$("#utility td[width='70%']").addClass('utility_container');
	$("#utility td[width='3%']").addClass('cell_3');
	$("#utility td[width='20%']").addClass('cell_20');
	$("#utility td[width='73%']").addClass('cell_73');
	$("#utility label[for='RememberMe']").addClass('label_remember_me');
	
	// Force user redirect to profile page after they login
	$('form[action$=/site/UserLogin] input#NEXTURL').val('ConsProfileUser?dispMode=edit');
	
	// Fix user profile styles
	$('form#EditCons').parent().parent().prev('div').hide();
	$('form#EditCons').parent('div').parent('div').prev('div').prev('div').hide();
	$('form#EditCons').parent().parent().next('div').hide();
	$('form#EditCons input#op\\.cnclEditCons').hide();
	$('form#EditCons input#op\\.saveCons').css('margin', 0);
	
	// Fix user profile styles -- "special interests" page
	$('form#ConsConfigInterests').parent().prev('div').hide();
	$('form#ConsConfigInterests .PaddedListHeadings').width('inherit');
	$('form#ConsConfigInterests input.hide_item').hide();
	$('form#ConsConfigInterests input[type=submit]').css('margin', 0);
	
});

function loadFeaturedMedia(cat) {
	ajax_proxy({'cnv_url':'http://service.ichristianlife.com/media/search/', 't':'jn2', 'nd': '', 'r':'300', 'cat':cat}, {
		dataType: 'json',
		type: 'POST',
		success: function(data) {
			if (data != null && data.items.length > 0) {
				var html = '';
				var d = new Date();
//				var randomIndex = 100 * d.getMonth() + 3 * d.getDate();
				var randomIndex = 31 * d.getMonth() + d.getDate();
				
				// Display 3 randomly selected featured media items
				for (var i=0; i<3; i++) {
//					var e = data.items[(randomIndex + i) % data.items.length];
					console.log('featured item id: ' + (23 * randomIndex + 79 * i) % data.items.length);
					
					var e = data.items[(23 * randomIndex + 79 * i) % data.items.length];
					if (e.media_type == "text") {
						var auth = e.author.substr(0,15).replace(/ /gi,"_");
						var alb = e.collection.substr(0,15).replace(/ /gi,"_");
						var title = e.name.substr(0,20).replace(/ /gi,"_");
						html += (e.collection == 'Action') ?
							'<a class="tab_item" href="http://www.ichristianlife.com/' + auth + '__' + alb + '__' + title + '">' :
							'<a class="tab_item" href="http://www.ichristianlife.com/t__' + auth + '__' + alb + '__' + title + '">';
					} else {
						html += '<a class="tab_item" href="PageServer?pagename=media#page:player;media:' + escape(e.name) + '">';
					}
					html += '<img src="' + e.thumbnail + '" alt="' + e.author + '" />';
					html += '<h5>' + e.name + '</h5>';
					html += '<p>' + e.description + '</p>';
					html += '<div class="media_type_' + e.media_type + '"></div>';
					html += '<h3>by ' + e.author  + '</h3>';
					html += '</a>';
					$('#featured_media div.container_relative').html(html).fadeIn();
				}
			}
		}
	});
}

function loadFeaturedAlbum(cat) {
	ajax_proxy({'cnv_url':'http://service.ichristianlife.com/album/search/', 't':'jsn', 'r':'300', 'cat':cat}, {
		dataType: 'json',
		type: 'POST',
		success: function(data) {
			if (data != null && data.items.length > 0) {
				var d = new Date();
				var e = data.items[(33 * d.getMonth() + d.getDate()) % data.items.length];
				var albumDashes = e.album.replace(/ /gi,"-").toLowerCase();
				var html = '<a class="tab_item" href="PageServer?pagename=media#page:search;searchString:;tab:AlbumDrilldown;p:1;oth.alb:' + escape(e.album) + '">';
				var type = (e.video == 'true') ? 'video' : (e.audio == 'true') ? 'audio' : 'text';
				html += '<div class="media_type_' + type + '"></div>';
				html += '<img src="http://www.ichristianlife.com/images/icl2/english/' + e.author_ls + '/' + e.album_ls + '/thumbnail/' + albumDashes + '.jpg" alt="' + e.author_ls + '" />';
				html += '<h5>' + e.album + '</h5>';
				html += '<p>' + e.description + '</p></a>';
				$('#featured_album div.container_relative').html(html).fadeIn();
			}
		}
	});
}
