
/**
* init.js
* 
* This file contains the initialization routine for the index.php file of the CPR 2.0 Web Interface
* 
* @author mmorrissey@cprmail.org
*/


//=============================================================================================================================================		
// Functions for handling jwplayer events
//=============================================================================================================================================
//GLOBAL VARS
var currentState = "NONE"; 
var previousState = "NONE"; 
var currentPlaylist = new Array();
var currentPlaylistIndex = 0;
var isIdle = true; // a global
var isCommercial = false; //a global
var player = null;
var cleanTitle = '';
var playState = 'kcfr';

function playerReadyCallback(obj) {
	player = document.getElementById(obj['id']);
	addListeners();
	
//	  player.sendEvent("PLAY","true");
//    var firstPadData = $('#scrollText').addEventListener(player.PLAY,insertpadData(playState), false);

}

function addListeners() {
	if (player) { 
		player.addModelListener("STATE", "stateListener");
		player.addViewListener("PLAY", "playListener");
	} else {
		setTimeout("addListeners()",100);
	}
}
 
 
function stateListener(obj) { //IDLE, BUFFERING, PLAYING, PAUSED, COMPLETED
	currentState = obj.newstate; 
	previousState = obj.oldstate; 
 
	//For debug purposes only
//	console.log("State = " + currentState);
	
 switch(currentState)
	{
	case "IDLE":

		if (currentPlaylist.length > 1) {
//			alert(currentPlaylistIndex + ":" + (currentPlaylist.length - 1));
			if (currentPlaylistIndex < (currentPlaylist.length - 1)) {

//				player.sendEvent("LOAD", currentPlaylist[currentPlaylistIndex]);
//				player.sendEvent('PLAY');
				isCommercial = true;
				initPlayer('onDemand', currentPlaylist[currentPlaylistIndex], true);

				
	    	    
				if (interval != ''){
	    			clearInterval(interval);
	    		}
				$('.nowPlaying').html(cleanTitle);
				clearInterval(interval);
				currentPlaylistIndex++;
				return false;

			} else if (currentPlaylistIndex == (currentPlaylist.length - 1) ) {
//				player.sendEvent("LOAD", currentPlaylist[currentPlaylistIndex]);
//				player.sendEvent('PLAY', true);
				isCommercial = false;
				initPlayer('onDemand', currentPlaylist[currentPlaylistIndex], true);
				
				if (interval != ''){
	    			clearInterval(interval);
	    		}
	    	    
				$('.nowPlaying').html(cleanTitle);
				clearInterval(interval);

				currentPlaylist = [];
				currentPlaylistIndex = 0;
				return false;
			}
		}
		return false;
	  break;
	case "PLAYING":
	  
	  break;

	default:
	  return false;
	}
	
}

function playListener(obj) {
	
	if(
			(currentState == "PLAYING" && playState == "kcfr") || 
			(currentState == "PLAYING" && playState == "kvod")
		)  {
//		alert (currentState);
		player.sendEvent("STOP");
	} else if (obj.id == 'player') {
			if (playState == 'kcfr') {
			    beginPlay('kcfr', true);
		
			} else if (playState == 'kvod') {
				beginPlay('kvod', true);
			}
		}

	return false;

}

//=============================================================================================================================================
//first, initialize the rounded corners fix:
//=============================================================================================================================================
DD_roundies.addRule('.ui-button', '5px', 'false');

//=============================================================================================================================================
// Initialize History Management
//=============================================================================================================================================
//this contains just the domains that have been accessed
var domainHistory = Array();
//this contains the full link and is a 2d array with type of link (legacy or localCMS) that we have loaded so far
var articleHistory = Array();
var loadedContentFromStart = false;
var loadedAction = "";
var loadedArticle = "";
var loadedTab = "";
var global_session={};
var comatters = 'comatters_widget';
function showPledgeMessage() {
	var msg = "During our beta test, this site's pledge forms are unavailable.\n\n";
	msg += "If you have questions about your membership, please call 1-800-722-4449.";
	
	alert(msg);
	return false;
}

function showRegisterMessage() {
	var msg = "During our beta test, this site is unable to process new registrations.\n\n";
	msg += "At the close of our testing period, we will allow new users to sign up to use the site.\n\n";
	msg += "Meanwhile, if you have questions about the site, please click the CONTACT US link\n\n";
	msg += "If you have questions about your membership, please call 1-800-722-4449.";
	
	alert(msg);
	return false;
}

// If someone clicks the logo, bring them back to the "My CPR" tab:
function backToMyCPR() {
	$("#mainTabHeader").show();
	$("#tabs").tabs("select", "#mainTab");
	return false;
}

//=============================================================================================================================================
//now register the session in javascript
//=============================================================================================================================================
$(document).ready(function() {
	
	$.post("/lib/profile/loginProcessor.php", 
			{ 
				is_logout: 'false', 
				is_login: 'false' 
			}, 
			function(data, textStatus ) {

				if(textStatus == 'success')
				{	
					global_session = data;
					
					if (global_session.is_first_login == true)
					{
						//we know this is the first login, pop a dialog:
						alert('You may find that during this beta test, some of your profile information is out of date.\n\nIf you\'ve made changes to your contact or payment information lately, those changes may not be reflected here.\n\nIf you have questions about your membership, please call 1-800-722-4449.');
					}	

					if (global_session.member_id > 0) {

						/*
						document.getElementById("session_line_1").innerHTML = global_session.line_1;
						document.getElementById("session_line_2").innerHTML = global_session.line_2;
						document.getElementById("session_city_state_zip_zip4").innerHTML = global_session.city + ", " + global_session.state + "&nbsp;&nbsp;" + global_session.zip + " " + global_session.zip4
						document.getElementById("session_home_phone").innerHTML = global_session.home_phone_formatted;
						document.getElementById("session_work_phone").innerHTML = global_session.work_phone_formatted;
						document.getElementById("session_cell_phone").innerHTML = global_session.cell_phone_formatted;
						document.getElementById("session_email").innerHTML = global_session.email;
						 */	
						$("#profileContentContainer").load("/lib/profile/profileTemplate.php", { profile: data });
						$("#myProfileTabHeader").show();
						//$("#tabs").tabs('select', '#myProfileTab');
						$('#loginLink').html('<a href="#" onclick="logout(); return false;">LOG OUT</a>');
												
					} 
					else if (global_session.member_id < 0) {	// i.e. we're logging out
						$('#loginButton').html('Log in');
						$("#myProfileTabHeader").hide();
						$("#tabs").tabs('select', '#mainTab');
						
					}
				}
				else
				{
					
				}
			},
			"json");
			
		$("#tabs").tabs();
		$("#searchResultsTabHeader").hide();
		$("#myProfileTabHeader").hide();
		$("#contentTabHeader").hide();

		//=============================================================================================================================================		
		// Search form editing to take away logo onBlur
		//=============================================================================================================================================
		
		$('#searchForm').mouseenter(function() {
			$('input[type="text"].gsc-input').focus(function() {
				$(this).css('background','#ffffff');
			})
			//code commented out 05.10.2010 to remove google logo from search
//			$('input[type="text"].gsc-input').blur(function() {
//				if (this.value != '') {
//					$(this).css('background','#ffffff');
//				} else {
//					$(this).css('background','url("http://www.google.com/uds/css/small-logo.png") center right no-repeat #ffffff');
//				} 
//				
//			}) 
		});
		
		//=============================================================================================================================================		
		// start the multiwidgets:
		//=============================================================================================================================================
		/*
		$("#feature-box-slides").cycle({
			fx: 'fade',
			speed: 'slow',
			timeout:8000,
			next: '#feature-box-slides .slide-nav-next',
			prev: '#feature-box-slides .slide-nav-prev'
		});
		$("#feature-box-slides .slide-nav-pause").click(function(){
			$("#feature-box-slides").cycle('pause');
			return false;
		});
		$("#feature-box-slides .slide-nav-play").click(function(){
			$("#feature-box-slides").cycle('resume');
			return false;
		});
		
		$("#billboard-slides").cycle({
			fx: 'fade',
			speed: 'slow',
			timeout:7000,
			next: '#billboard-slides .slide-nav-next',
			prev: '#billboard-slides .slide-nav-prev'
		});
		$("#billboard-slides .slide-nav-pause").click(function(){
			$("#billboard-slides").cycle('pause');
			return false;
		});
		$("#billboard-slides .slide-nav-play").click(function(){
			$("#billboard-slides").cycle('resume');
			return false;
		});
		*/
		//=============================================================================================================================================		
		// create click handlers for all links on the site
		//=============================================================================================================================================
		$("#personalizeButton").fancybox({
			'zoomSpeedIn' : 500,
			'zoomSpeedOut' : 400,
			'easingIn' : 'easeOutBack',
			'easingOut' : 'easeInBack',
			'frameWidth' : 800,
			'frameHeight' : 500,
			'centerOnScroll' : true,
			'hideOnContentClick' : false,
			'callbackOnShow': function()
			{
				//myWidgets = $.cookie()	
				//add click links to the list
				$("a.widgetListName").click(function() {
					$("#add_this_widget_pw").attr("name", $(this).attr("name"));
					$("#widgetTitle").html($(this).html());
					
					$("#widgetPreviewList").load('/lib/uwa/widget_gateway.php',
						{
							action: 'get_widget',
							widget_code: $(this).attr("name")
						},
						function()
						{
							
							$("#add_this_widget_pw").show();

							$("#add_this_widget_pw").unbind("click");

							$("#add_this_widget_pw").click(function() {
								cprWidgets.addWidget($(this).attr("name"));
							});
								
						});
					
				
				});
			}
		});
//		$("#contentTabWrapper a, #leftSideNav a").unbind("click");
	
		
		$('a').live('click', function(event) {
			//make sure page scrolls to top
			//in the case of anchors within a page, don't scroll to top.
			

			var urlToLoad = $(this).attr('href');
			
			cleanTitle = $(this).attr("name");
			
			//BEGIN code for handling .mp3 links
			var href = $(this).attr("href");
			var title = $(this).html();
			var temp = href.split(".");
			var ext = temp[temp.length - 1];
//			var currentPlaylist = {};
			
			//clean up title for PAD display
			var cleanTitle = $(this).attr("title");
			 
			var str = $(this).attr("href").search("^#");
			if ( str === -1){
				if (BrowserDetect.browser != "Explorer") {
					$('html, body').animate({scrollTop:0}, 'fast');
				} 
				
			} 
			
			if (ext == "flv")
				{
					initPlayer('onDemand', href, true);
					$(".nowPlaying").html(title);
					return false;
				}
			
			if (ext == "mp3")
			{
				playState = 'onDemand';
				initPlayer('onDemand', href, true);
//				alert(playState);
				//Now that we've loaded the .mp3, let's clear the selected button classes
				//that power the "listen to" buttons to the left of the player, 
				//So that neither of them will appear to be selected.
				$('#centerHeader').removeClass('kvodSelected');				
	    	    $('#centerHeader').removeClass('kcfrSelected');
	    	    
				if (interval != ''){
	    			clearInterval(interval);
	    		}
				if ($(this).attr("title") == '' || $(this).attr("title") == undefined ) {
					if ($(this).attr("name") == '' || $(this).attr("name") == undefined) {
						cleanTitle = "On Demand Content";
					} else {
						cleanTitle = $(this).attr("name");
					}
				} else {
					cleanTitle = $(this).attr("title");					
				}
				$('.nowPlaying').html(cleanTitle);
				clearInterval(interval);
				return false;				
			}
			
			if (ext == "m3u") {	
				if (urlToLoad.search("audioStreams/bberry_stream_kcfr.m3u") != -1 || urlToLoad.search("http://www.cpr.org/audioStreams/bberry_stream_kvod.m3u") != -1)
				{
					isInternal = false;
					$(this).attr("target", "_blank");
					//alert("streaming bb");
					return true;
				}
				$.post("/lib/curl/curlM3uLink.php", {"href": href}, function(data) {
					currentPlaylistIndex = 0;	
					currentPlaylist = data;
			
					if (currentPlaylist.length > 1) {
						playState = 'onDemand';
						isCommercial = true;
						initPlayer('onDemand', currentPlaylist[currentPlaylistIndex], true);
						//Now that we've loaded the .mp3, let's clear the selected button classes
						//that power the "listen to" buttons to the left of the player, 
						//So that neither of them will appear to be selected.
						$('#centerHeader').removeClass('kvodSelected');				
			    	    $('#centerHeader').removeClass('kcfrSelected');
			    	    
						//After player is initialized, check to see if interval is set for PAD data, if not set it up
						//Setup PAD data for this player
						if (interval != ''){
			    			clearInterval(interval);
			    		}
						interval = setInterval(function(){	
			    			
			    		    //grab parsed xml, display in audioInfo div every "X" seconds
			    		 	
							$('.nowPlaying').text(cleanTitle);
			    	
			    		}, 5000); 
						
						//Increment playlist index 
						currentPlaylistIndex++;

					} else {
						isCommercial = false;
						playState = 'onDemand';
						initPlayer('onDemand', currentPlaylist[currentPlaylistIndex], true);
						
						//Now that we've loaded the .mp3, let's clear the selected button classes
						//that power the "listen to" buttons to the left of the player, 
						//So that neither of them will appear to be selected.
						$('#centerHeader').removeClass('kvodSelected');				
			    	    $('#centerHeader').removeClass('kcfrSelected');

						//Setup PAD data for this player
						if (interval != ''){
			    			clearInterval(interval);
			    		}
						interval = setInterval(function(){	
			    			
			    		    //grab parsed xml, display in audioInfo div every "X" seconds
			    		 	
							$('.nowPlaying').text(cleanTitle);
			    	
			    		}, 5000); 
////						$('.nowPlaying').html(cleanTitle);
						
//						clearInterval(interval);

					}

				
				},"json");	
			return false;
			} //              END .mp3 handler for all a tags
			
			//rss handler
			if (ext == 'rss')
			{
				return true;
			}
			
			//check to make sure that this is an internal link:
			var urlMinusHash = $(this).attr('href').split("#");
			var urlParts = new Array(); 
		 	urlParts = urlMinusHash[0].split("/");
			var thisDomain = window.location.host;
			var isInternal = false;
			var linkAction = "";
			var linkKeyword = "";
			
			if((urlToLoad.search(window.location.host) != "-1") && (urlToLoad.substr(0, 4) == "http") && (urlToLoad.substr(0, 6) != "mailto"))
			{
				//ok this is a fully qualified domain on our site, let's extract the action and the keyword:
				//check to see if this is an article, category,
				if (urlToLoad.search("article") != -1 && urlToLoad.search("tag") != -1 && urlToLoad.search("category") != -1 && urlToLoad.search("profile") != -1)
				{
					
					isInternal = true;
					var tempURLSplit = urlToLoad.split('/');
					linkAction = tempURLSplit[tempURLSplit.length - 2];
					linkKeyword = tempURLSplit[tempURLSplit.length - 1];
				}
				else
				{
					isInternal = false;
				}
			}
			
			if(urlToLoad.charAt(0) == "/")
			{
				//ok this url starts with a /, its local
				isInternal = true;
				$(this).attr("target", "_self");
				var tempURLSplit = urlToLoad.split('/');
				linkAction = tempURLSplit[tempURLSplit.length - 2];
				linkKeyword = tempURLSplit[tempURLSplit.length - 1];
			}
			//more checks to see if this is local
			//if the host is the current one and is in the url of the target url, and load_article, load_category_page, or load_tag_page are in the target, it's internal
			if ( (urlToLoad.search(window.location.host) !== "-1" || urlToLoad.search("www.cpr.org") !== -1) && ( (urlToLoad.search("load_article") !== -1 ) || (urlToLoad.search("load_tag_page") !== -1) || (urlToLoad.search("load_category_page") !== -1) ) ) {
				$(this).attr("target", "_self");
			//	$(this).removeAttr("onclick");
				
				var tempURLSplitHash = urlMinusHash[1].split('|');
				linkAction = tempURLSplitHash[tempURLSplitHash.length - 2];
				linkKeyword = tempURLSplitHash[tempURLSplitHash.length - 1];
				isInternal = true;
			}
			
			if(isInternal)
			{
				
				if (linkAction == "article" || linkAction == 'load_article')
				{
					loadContent("load_article", linkKeyword);
					$("#contentTabHeader").show();	
					$("#tabs").tabs("select", "#contentTab"); 
				}
				if (linkAction == "category" || linkAction == 'load_category_page')
				{
					loadContent("load_category_page", linkKeyword);
					$("#contentTabHeader").show();	
					$("#tabs").tabs("select", "#contentTab"); 
				}
				if (linkAction == "tag" || linkAction == 'load_tag_page')
				{
					
					loadContent("load_tag_page", linkKeyword.replace(" ", "_").toLowerCase());
					$("#contentTabHeader").show();	
					$("#tabs").tabs("select", "#contentTab"); 
				}
				if (linkAction == "profile")
				{
					loadProfile("load_profile_page", linkKeyword);
					$("#myProfileTabHeader").show();	
					$("#tabs").tabs("select", "#myProfileTab"); 
				}
				if (BrowserDetect.browser != "Explorer") {
					$('html, body').animate({scrollTop:0}, 'fast');
				} 
				
				return false;
			}
			else
			{
				if ($(this).attr("target") == "_blank")
				{
					return true;	
				}
				if ( (urlToLoad.search(window.location.host) !== "-1") && ( (urlToLoad.search("load_article") !== -1 ) || (urlToLoad.search("load_tag_page") !== -1) || (urlToLoad.search("load_category_page") !== -1) ) ) {
					$(this).attr("target", "_self");

					return true;
				} else {
					if (urlToLoad.charAt(0) != "#" && urlToLoad != "")
					{
						$(this).attr("target", "_blank");
						return true;
					}
				
				}
				return true;
			}
		});
		
		

		/*
		 * 
		 
		 * 
		 * 
		 
		$('iframe').bind('load', function() {
			$(this).doc().find('a').click(function()
			{
				if($(this).attr("href").search("beta.cpr.org") != -1)
				{
					//ok this is a fully qualified domain on our site, let's extract the action and the keyword:
					isInternal = true;
					var tempURLSplit = urlToLoad.split('/');
					linkAction = tempURLSplit[tempURLSplit.length - 2];
					linkKeyword = tempURLSplit[tempURLSplit.length - 1];
					alert("clicked a cpr link in an iframe");
					return false;
				}
			});
		}); */
		
		//search result binding
		
		
		
		//=============================================================================================================================================		
		// Initiate onload function for underwriterDirectory.php and fancybox for underwriter templates
		//=============================================================================================================================================
	
		
// Most likely obsolete code, but keeping it just in case		
//		$("a#directory").click( function() {
//			alert('hi');
//			$("#contentTab").load("/content_category_templates/underwriterDirectory.php"); 
//			$("#contentTabHeader").show(); 
//			$("#tabs").tabs("select", "#contentTab");//, function() {
//		});					
		
				 
			
		//});
		
		
		//=============================================================================================================================================		
		// Handle initial tab management
		//=============================================================================================================================================
		// setEqualHeight($("#columns > div"));
		// if ((typeof(loadedContentFromStart) != 'undefined') && loadedContentFromStart) // was getting "is not defined" error from the line below.  dl  20091119
		if (loadedContentFromStart)
		{
			$("#contentTabHeader").show();	
			$("#tabs").tabs("select", "#contentTab");
			/* --this is now handled in article.class.php
			 * 
			if($("#articleImages").length > 0)
			{
				if ($(".article_image").length > 1)
				{
					$("#articleImages").after('<ul id="image-nav">').cycle({
						fx: 'fade',
						speed: 'fast',
						timeout: 0,
						pager: '#image-nav',
						pagerAnchorBuilder: 
							function(idx, slide) { 
				        		// return selector string for existing anchor 
				        		return '<li><a href="#"><img src="' + slide.src + '" width="50" height="50" /></a></li>'; 
	
				    		}
				    		
					}); 
				}
			}
			*/
		}
		else
		{
			$("#contentTabHeader").hide();	
			$("#tabs").tabs("select", "#mainTab");

		}

		
		// -----------------------------------------------------------------
		// handle cm and cs archive lookup and pagination
		// -----------------------------------------------------------------		

		//search dates within category pages
		$("#searchDate").live("click", function() {
			
			var thedate = $("#datepicker").val();
			var category_this = $("#category_this").val();	
			var currentHash = dhtmlHistory.getCurrentHash();
			var tempSplit = currentHash.split("|");
			//grab the category name
			var cc_name = tempSplit[1];
			if(cc_name == undefined) {
				var cc_name = category_this;
			}				
			
			$.post("/lib/pagination/cc_search_gateway.php",
				{
					the_date: thedate,
					category: cc_name
				},				
				function(data, textStatus) {
					if (textStatus == 'success')
					{
						$('html, body').animate({scrollTop:0}, 100);
						$("#archiveWrapper").html(data);
					}					
				},
				"html"
			);
			return false;
		});

		
		//search topics within category pages
		$("#searchTopic").live("click", function() {
			
			var thetopic = $("#stopic").val();
			var category_this = $("#category_this").val();	
			var currentHash = dhtmlHistory.getCurrentHash();
			var tempSplit = currentHash.split("|");
			//grab the category name
			var cc_name = tempSplit[1];
			if(cc_name == undefined) {
				var cc_name = category_this;
			}			
                       
			$.post("/lib/pagination/cc_search_gateway.php",
				{
					the_topic: thetopic,
					category: cc_name
				},				
				function(data, textStatus) {
					if (textStatus == 'success')
					{
						$('html, body').animate({scrollTop:0}, 100);
						$("#archiveWrapper").html(data);
					}					
				},
				"html"
			);
			return false;
		});

		
		// "previous" pagination within category pages
		$("#cc_pagination_previous").live("click", function() {
			
			var thedate = $("#date").val();
			var thetopic = $("#topic").val();			
			var currentpage = $("#previous_pagenum").val();
			var category_this = $("#category_this").val();			
			
			var currentHash = dhtmlHistory.getCurrentHash();
			var tempSplit = currentHash.split("|");
			//grab the category name
			var cc_name = tempSplit[1];
			if(cc_name == undefined) {
				var cc_name = category_this;
			}			
			
			$.post("/lib/pagination/cc_search_gateway.php",
				{
					the_date: thedate,
					the_topic: thetopic,
					current_page: currentpage,
					category: cc_name
				},				
				function(data, textStatus) {
					if (textStatus == 'success')
					{
						$('html, body').animate({scrollTop:0}, 100);
						$("#archiveWrapper").html(data);
					}					
				},
				"html"
			);
			return false;
		});

		
		// "next" pagination within category pages
		$("#cc_pagination_next").live("click", function() {
			
			var thedate = $("#date").val();
			var thetopic = $("#topic").val();			
			var currentpage = $("#next_pagenum").val();
			var category_this = $("#category_this").val();
				
			var currentHash = dhtmlHistory.getCurrentHash();
			var tempSplit = currentHash.split("|");
			//grab the category name
			var cc_name = tempSplit[1];
			if(cc_name == undefined) {
				var cc_name = category_this;
			}
			
			$.post("/lib/pagination/cc_search_gateway.php",
				{
					the_date: thedate,
					the_topic: thetopic,
					current_page: currentpage,
					category: cc_name
				},				
				function(data, textStatus) {
					if (textStatus == 'success')
					{
						$('html, body').animate({scrollTop:0}, 100);
						$("#archiveWrapper").html(data);
					}					
				},
				"html"
			);
			return false;
		});		
			
		// -----------------------------------------------------------------
		// end - handle cm and cs archive lookup and pagination
		// -----------------------------------------------------------------
		
		// -----------------------------------------------------------------
		// handle tag pagination
		// -----------------------------------------------------------------
		
		// "next" pagination within tag pages
		$("#tag_pagination_previous").live("click", function() {
			
			var thetag = $("#tag").val();
			var currentpage = $("#previous_pagenum").val();
			
			$.post("/lib/pagination/tag_search_gateway.php",
				{
					tag: thetag,
					current_page: currentpage
				},				
				function(data, textStatus) {
					if (textStatus == 'success')
					{
						$('html, body').animate({scrollTop:0}, 100);
						$("#articleListWrapper").html(data);
					}					
				},
				"html"
			);
			return false;
		});
		
		// "next" pagination within tag pages
		$("#tag_pagination_next").live("click", function() {
			var thetag = $("#tag").val();
			var currentpage = $("#next_pagenum").val();
			
			$.post("/lib/pagination/tag_search_gateway.php",
				{
					tag: thetag,
					current_page: currentpage
				},				
				function(data, textStatus) {
					if (textStatus == 'success')
					{
						$('html, body').animate({scrollTop:0}, 100);
						$("#articleListWrapper").html(data);
					}					
				},
				"html"
			);
			return false;
		});		
		
		// -----------------------------------------------------------------
		// end - handle tag pagination
		// -----------------------------------------------------------------		
		
		// -----------------------------------------------------------------
		// handle php forms post logic
		// -----------------------------------------------------------------			

		$(".phpincludeForm").live("submit", function() {
			
			var str = $(this).serialize();

			/*
			var formDataObject = new Array();

			$("#contentTab input, #contentTab textarea, #contentTab select").map(function() {
				var temp = {};
				temp.name = $(this).attr("name");
				temp.value = $(this).val();
				formDataObject.push(temp);
			});
			
			var thisForm = formDataObject[0].value;
			var formData = 'formData_' +  thisForm;
			historyStorage.put(formData, formDataObject);
			*/
			
			$.post('/lib/forms/form_gateway.php', str, function(data, textStatus) {
					if (textStatus == 'success')
					{
						/*
						var current = dhtmlHistory.getCurrentLocation();
						var page = current.split('|');
						dhtmlHistory.add("form_confirm|"+page[1]);
						
						if((data.search('<!-- confirm response -->')) != -1) {
							$('html, body').animate({scrollTop:0}, 100);
							$("#confirmResponse").html(data);
						}
						else if((data.search('<!-- message success -->')) != -1) {
						*/
						if((data.search('<!-- message success -->')) != -1) {
							/* historyStorage.remove(formData); */
							$('html, body').animate({scrollTop:0}, 100);
							$("#formSuccess").html(data);
						}
						else if((data.search('<!-- redirect success -->')) != -1) {
							/* historyStorage.remove(formData); */
							// this section for membership questions redirect	
							$('html, body').animate({scrollTop:0}, 100);
							loadContent('article', 'legacy-cpr-242');
						}	
						else {
							$("#errorResponse").html(data);
						}
					}
				},
				"html"
			);
			return false;
		});	
		
		// -----------------------------------------------------------------
		// end handle php forms post logic
		// -----------------------------------------------------------------	
		
		// -----------------------------------------------------------------
		// begin profile edit forms post logic
		// -----------------------------------------------------------------			
		
		$(".qasInfo").live("submit", function() {
			
			var str = $(this).serialize();
			
			$.post('/lib/profile/profileEditProcessor.php', str, function(data, textStatus) {

				if (textStatus == 'success')
				{
					if((data.search('information is missing')) != -1) {

						$.post('/lib/profile/session_refresh.php', {}, function(sessionData, textStatus) {
							global_session = sessionData;
							loadProfile('load_profile', 'contactInfoEdit');
						}, 
						"json");	

						alert(data);
						// Below is code intended to print the error message at the top of contactInfoEdit.php instead in 
						// an alert box.
						// $(document).ready(function() {
						// 	$("#errorMessage").html(data);
						// });
					}
					else if(((data.search('Profile update error')) != -1)  ||  (data.search('Profile update succeeded')) != -1)
					{
						
						$.post('/lib/profile/session_refresh.php', {}, function(sessionData, textStatus) {
							global_session = sessionData;
							loadProfile('load_profile', 'profileTemplate');
						}, 
						"json");	

						var theMessage = 'Your changes have been saved.';
						// The line below is intended to print the error message at the top of profileTemplate.php instead in 
						// an alert box.
						// $("#profileEditSuccess").html(theMessage);
						alert(theMessage);
					}
				}
				}
			);
			return false;
		});
		
		// -----------------------------------------------------------------
		// end profile edit forms post logic
		// -----------------------------------------------------------------	
		
		
		//COMMENTED OUT 20100518 by JF
		//handle audio links in legacy content for now possibly open to all contentTabWrapper content
//		$("a").live("click", function() {
//			
//			var href = $(this).attr("href");
//			var title = $(this).html();
//			var temp = href.split(".");
//			var ext = temp[temp.length - 1];
//			if (ext == "mp3")
//			{
//				initPlayer('onDemand', href, true);
//				$('.nowPlaying').html(title);
//				return false;				
//			}
//			else
//			{
//				//do nothing
//			}
//			
//			
//		});
		
		
		//fix any zindex issues
		fixZIndex();
		//here we are going to load the iframes after everything else, then initialize them on the callback
		cprWidgets.setLayout();
		
	});
	// END of document.ready function

//z-index fix for fancy box:

	var zmax = 0 ;
   
   function buildZMax() {
     $('*').each(function() {
       var cur = parseInt($(this).css('zIndex'));
       zmax = cur > zmax ? $(this).css('zIndex') : zmax;
     });
   }

   function fixZIndex() {
     buildZMax();

     // Get all the outermost fancy_wrap id'ed objects built by the FancyBox calls
     // ...then bump the z-index to whatever the highest we found, plus 1
     $('#fancy_wrap').each(function() {
       zmax = zmax + 1 ;
       $(this).css("z-index", zmax);

       // Get the overlay children in each iteration of the outer
       // ...fancy_wrap, bump its z-index up.
       $(this).children("div#fancy_overlay").each(function() {
         zmax = zmax + 1 ;
         $(this).css("z-index", zmax);
       });

       // And again for another major child div
       zmax = zmax + 1 ;
       $(this).children("div#fancy_outer").each(function() {
         zmax = zmax + 1 ;
         $(this).css("z-index", zmax);
       });
     });
   }
     
 



//=============================================================================================================================================
//Handle the IFrame Messaging for UWA
//=============================================================================================================================================	
	/*
	 * 
	 msgHandler = function(message) {
		var id = message.id;
		switch (message.action) {
			case 'resizeHeight':
				var frame = document.getElementById('frame_' + id);
				if (frame) {
					frame.setAttribute('height', message.value);
				}
				break;
			//handle the other cases in netvibes UWA specification
			case "addStar":
				//do nothing here.
			break;
			
			case "setIcon":
				
			break;
			
			case "setSearchResultCount":
			
			break;
			
			case "setTitle":
				
			break;
			
			case "setUnreadCount":
			
			break;
			
			case "setValue":
			
			break;
			
			default:
				//throw an error
				//not handled
			break;
		}
	};
		 
	UWA.MessageHandler = new UWA.iFrameMessaging;
	UWA.MessageHandler.init({
		'eventHandler': msgHandler,
		'trustedOrigin' : 'nvmodules.netvibes.com'

	});
	*/
//=============================================================================================================================================			
//register all CPR links to load in content tab
//=============================================================================================================================================
/* -- taken out we're not using this anymore
		$('#contentLayout a').livequery('click', function(event) {
			//first go through and see if there are links to mp3 files that we could load into the player
			var urlToLoad = $(this).attr('href');
			var tempUrl = $(this).attr('href');
			
			var urlParts = new Array();
			urlParts = $(this).attr('href').split("/");
			var domain = "";
			if (urlToLoad.substr(0, 4) != "http")
			{
				domain = domainHistory[domainHistory.length - 1];
				var filename = urlParts[urlParts.length - 1];
				parts = filename.split('.');
				var fileExt = parts[parts.length - 1];
				//console.log('this was a relative path');
				if (urlToLoad.substr(0,1) == '/')
				{
					urlToLoad = 'http://' + domain + tempUrl;
				}
				else
				{
					urlToLoad = 'http://' + domain + '/' + tempUrl;
				}
			}
			else
			{
				//console.log('this was an absolute path');
				var domain = urlParts[2]; 
				var filename = urlParts[urlParts.length - 1];
				var parts = new Array();
				parts = filename.split('.');
				var fileExt = parts[parts.length - 1];
			}
			
			var urlForCurl = $.URLEncode(urlToLoad);
			
			if (fileExt == "mp3" || fileExt == "m3u")
			{
				// this is an mp3, load it into the player
				if (fileExt == "mp3")
				{
					player.sendEvent("LOAD", $(this).attr('href'));
				
				}
				else
				{
					var theMP3 = $.load(urlToLoad, {},
						function (data, textStatus)
						{
							//TODO: grab the m3u file, parse it to get an mp3 url
							player.sendEvent("LOAD", data);
						},
						"text"
						);
				}
				return false;
			}
			else
			{
				//check to make sure that this gets added to the history manager
				domainHistory.push(domain);
				//console.dir(domainHistory);
				//ok, go through all links, check which domain they are going to
				
				switch(domain)
				{
					case "devmy.cpr.org":
					case "localmy.cpr.org":
					case "my.cpr.org":
						break;
						
					case "":
						//this is a link from our site, do nothing
						return false;
						break;
						
					
					case "kcfr.org":
					case "www.kcfr.org":
					case "kvod.org":
					case "www.kvod.org":	
					case "cpr.org":
					case "www.cpr.org":
						
						
						//TODO: IE CACHES THIS RETURN, INSERT RANDOM QUERY STRING
						$("#contentLayout").load("/lib/legacy/cpr_curl.php?url=" + urlForCurl + " #content_main", { },
							function (responseText, textStatus, XMLHttpRequest)
							{
								//loaded, now we have to get these images sorted out if there are any
								$("#contentLayout img").each(function(i) {
									
									 	var theOldSrc = $(this).attr('src');
									 	//console.log('the old src = ' + theOldSrc);
									 	var urlParts2 = theOldSrc.split("/");
									 	if (theOldSrc.substr(0, 4) != "http")
										{
											if (theOldSrc.substr(0,1) == '/')
											{
										 		//relative path for this image
										 		//build new src string
										 		var theNewSrc = 'http://' + domain + theOldSrc;
										 		//set it to the new one
										 		$(this).attr('src', theNewSrc);
											}
											else
											{
												var theNewSrc = 'http://' + domain + '/' + theOldSrc;
										 		//set it to the new one
										 		$(this).attr('src', theNewSrc);	
											
											}
									 	}
									 	else
									 	{
									 		//don't do anything, the full path is there it should load.
									 	}
									 	
								});
								
								
							});
						//get title
						// To get the title of the search result document, we should be able to use a jquery load(), as above, 
						// and grab just the title from the document at the url specified.  But it's not working.  
						// Hack up some js to extract the title:
							
							 
							 var searchResultTitle = $.get("/lib/legacy/cpr_curl.php?url=" + urlForCurl, function(data) {
								var myMessage = 'Search Result';
								var fullLegacyStoryTitle = 'Loading...';
								var startMessage = data.indexOf("<title>");
								if (startMessage == -1) {
									startMessage = data.indexOf("<TITLE>");
								}

								var endMessage = data.indexOf("</title>");
								if (endMessage == -1) {
									endMessage = data.indexOf("</TITLE>");
								}

								if (startMessage != -1) {
									startMessage += 7;
									
									// Truncate this at 40 characters if necessary:
									var myMessageLength = (endMessage-startMessage);
									fullLegacyStoryTitle = data.substr(startMessage, myMessageLength);
									if (myMessageLength > 40) {
										myMessage = data.substr(startMessage,37) + "...";
									} else {
										//check to see if this is has "Colorado Public Radio" in it
										
										myMessage = data.substr(startMessage, myMessageLength);
									}
								}
								
								
								$("#contentTabHeader").html(myMessage);
								$("#contentTitleH3").html(fullLegacyStoryTitle);
								
								
							});
						$("#tabs").tabs('select', '#contentTab');
						$("#contentTabHeader").show();
						return false;
						break;
						
					default:
						// this is an unknown domain, load it into a new tab/window
						$(this).attr('target', "_blank");
						break;
					
				}
			}
		});	
	*/		
//=============================================================================================================================================		
//livequery to changed the search button text
//=============================================================================================================================================
$('input.gsc-search-button').livequery(function(event) {
			$('input.gsc-search-button').attr('value', 'Search cpr.org');
		}
		);
//=============================================================================================================================================		
// resize column heights
//=============================================================================================================================================
/*function setEqualHeight(columns)
{
	var tallestColumn = 0;
	columns.each(function() {
		currentHeight = $(this).height();
		if (currentHeight > tallestColumn)
		{
			tallestColumn = currentHeight;
		}
	});
	columns.height(tallestColumn);
}
*/



//=============================================================================================================================================		
//
//=============================================================================================================================================




