var gsif = {
	pageArray: [],
	menuHTML: null,
	menuBar: null,
	currentImage: 0,
	slideshowImages:[]
};

$(function() {
			
			createMenuBar();
			gsif.menuHTML = $('#nav_div').html();  // set the menu HTML
			
			registerSlideshow();

			showHideScripture();

			if($('#header_div_text').html() != 'Member Profiles')
			{
				getContent();
			} else {
				memberProfiles();
			}
			
		    formatPagesDiv();			
			addPageBlocks();
			setToPage(1);
			
			getSlideshowContent();
			
			
		   });

function showHideScripture()
{
  var contents = $('#scripture_div').html();
  if(contents == '')
    $('#scripture_div').css('display', 'none');
}

function memberProfiles()
{
	var content = $('#content_div').html();
	content = "<p class='spacer'>&nbsp;</p>" + content;
	
	$('#content_div').html(content);
}

function updatedPreviousState()
{
  var pageBlockDivSelected = $('#pages_div .page_block_div_selected');
  var curPage = parseInt(pageBlockDivSelected.html());
  
  setPageSelected(-1);

  var pageBlockDivs = $('#pages_div .page_block_div');
  $.each(pageBlockDivs, function(index, pageBlockDiv) {
								 	$(this).click(function() { 
												setTimeout(function() { 
																	setToPage(index+1); 
																	}, 500);
										});
								 });
  
  setPageSelected(curPage);
}

function registerSlideshow()
{
	$('#thumb_img1').click(function() { showSlideshow(0); });
	$('#thumb_img2').click(function() { showSlideshow(1); });
	$('#thumb_img3').click(function() { showSlideshow(2); });
	$('#thumb_img4').click(function() { showSlideshow(3); });
	
	$('#thumb_img1').css('cursor', 'hand');
	$('#thumb_img2').css('cursor', 'hand');
	$('#thumb_img3').css('cursor', 'hand');
	$('#thumb_img4').css('cursor', 'hand');	
	
	$('#left_arrow').click(function() { changePicture("left"); });
	$('#right_arrow').click(function() { changePicture("right"); });
	$('#close_slideshow').click(function() { $('#overlay').css('display', 'none'); });
	
}

function changePicture(arrowClicked)
{
	if(arrowClicked == "left")
	{
		gsif.currentImage--;
		if(gsif.currentImage < 0)
			gsif.currentImage = gsif.slideshowImages.length - 1;
	}
	else
	{
		gsif.currentImage++;
		if(gsif.currentImage >= gsif.slideshowImages.length)
			gsif.currentImage = 0;
	}
	
	
	$('#image_div').css('background-image', "url(" + gsif.slideshowImages[gsif.currentImage] + ")");		

//	alert(gsif.currentImage);
}

function showSlideshow(startIndex)
{
	$('#overlay').css('display', 'block');
	$('#image_div').css('background-image', "url(" + gsif.slideshowImages[startIndex] + ")");
	
	gsif.currentImage = startIndex;
	
	// load all images now
	for(var i = 0; i < gsif.slideshowImages.length; i++)
	{
		curPic = new Image(350, 350);
		curPic.src = gsif.slideshowImages[i];
	}
	
//	alert(gsif.slideshowImages[startIndex]);
}

function createMenuBar()
{
	gsif.menuBar = new Spry.Widget.MenuBar("MenuBar1", {imgRight:"../SpryAssets/SpryMenuBarRightHover.gif"});		   
}

/*function registerNav()
{

	$('#nav_div a').click(function() { 

								   	if($(this).attr('href') == '#')
									{
										return false;
									}

									var postUrl = $(this).attr('href');
									
//									top.location.href = $(this).attr('href');
									
									$.post(postUrl, { json: 1 }, function(jsonData) {
																			var newData = eval("(" + jsonData + ")");
																			changePage(newData);
																		  });
									
									return false;
								   });	
}*/

// breaks down content_div down into gsif.pageArray
function getContent(content)
{
  if(content == undefined)
    content = $('#content_div').html();

//  var contentArray = content.split("!ep!");//content.split("\n");
    var contentArray = $('#content_div p').get();

//  var contentArray = content.split('<br />');

  var currentPage = '';
  
  for(var i = 0; i < contentArray.length; i++)
  {
	  var pClass = $(contentArray[i]).attr('class');
	  
	  if(pClass != undefined)
	  	currentPage += '<p class="' + pClass + '">';
	  else
		  currentPage += '<p>' 
	
	  currentPage += contentArray[i].innerHTML + '</p>';

      if(currentPage.length >= 1000 || currentPage.indexOf('!np!') > -1)//currentPage.indexOf('<newpage />') > -1 || currentPage.indexOf('<NEWPAGE />') > -1) 
	  {
		  currentPage = filterContent(currentPage);

		  if(currentPage != '')
			  gsif.pageArray.push(currentPage);
		  currentPage = '';
	  }
  }
  
  if(currentPage != '') {
	  if(currentPage != '')	  
	  {
		  currentPage = filterContent(currentPage);
	  }
	  gsif.pageArray.push(currentPage);
  }
  
}

function filterContent(currentPage)
{
   if($('#header_div_text').html() == 'Member Profiles')
   {
 	   currentPage = currentPage.replace(/!nl!/g, "");	   
	   return currentPage;
   }
  // take out break at beginning
  if(currentPage.indexOf('<br />') == 0)
  {
	  currentPage = currentPage.substring(6, currentPage.length);
  }
  
  // take out break at end
  if(currentPage.lastIndexOf('<br />') == currentPage.length - 7)
  {
	  currentPage = currentPage.substring(0, currentPage.length - 7);
  }
  
/*  currentPage = currentPage.replace('<newpage />', '');
  currentPage = currentPage.replace('<newpage>', '');  
  currentPage = currentPage.replace('</newpage>', '');    
  currentPage = currentPage.replace('<NEWPAGE />', '');  */
  currentPage = currentPage.replace(/!np!/g, '');
  currentPage = currentPage.replace(/!nl!/g, "<pre>\n</pre>");

  return currentPage;

}


function setToPage(num)
{
  if(num > gsif.pageArray.length) return;
  
  // perhaps put a wait of one-second in here
  
  $('#content_div').empty();
  $('#page_id_div').html("&nbsp;");  
  
  $('#content_div').append(gsif.pageArray[num-1]);
  
  // add listeners if it is the profile's page
  if($('#header_div_text').html() == 'Member Profiles')
  {
	  addProfileListeners();
  }
  
  if(num > 1)
  {
	  $('#page_id_div').html('page ' + (num));
  }
  
  setPageSelected(num);
  
  if(typeof resizeRect == 'function')
	 resizeRect();
  
  scroll(0, 0);  // to the top!
  
}

function getSlideshowContent()
{
	var thumbs_string = $('#slideshow_thumbs').html();
	var main_string = $('#slideshow_main').html();
	
	thumbs_string = thumbs_string.replace(/^\s+|\s+$/g, '') ;
	
	if(thumbs_string != "")
	{
		var thumbs_array = thumbs_string.split(',');
		gsif.slideshowImages = main_string.split(',');

		$('#slideshow_text_div').css('display', 'block');
		$('#slideshow_thumbnails_div').css('display', 'block');
		$('#slideshow_text_div').html("");
		$('#thumb_img1').attr('src', thumbs_array[0]);
		$('#thumb_img2').attr('src', thumbs_array[1]);
		$('#thumb_img3').attr('src', thumbs_array[2]);
		$('#thumb_img4').attr('src', thumbs_array[3]);
	} else {
		$('#slideshow_text_div').css('display', 'none');		
		$('#slideshow_thumbnails_div').css('display', 'none');
	}
}

function addProfileListeners()
{
	$('#content_div a').click(function() { 
									   
									var postUrl = $(this).attr('href');
									
//									top.location.href = $(this).attr('href');
									
									$.post(postUrl, { json: 1 }, function(jsonData) {
																			var newData = eval("(" + jsonData + ")");
																			changePage(newData);
																		  });
									
									return false;
									   
									   
									   });
}

function addPageBlocks()
{
  $('#pages_div').empty();	
  
  if(gsif.pageArray.length <= 1) return;

  for(var i = 1; i <= gsif.pageArray.length; i++)
  {
	$('#pages_div').append('<div class="page_block_div">' + i + '</div>');
  }
  
  var pageBlockDivs = $('#pages_div .page_block_div');
  $.each(pageBlockDivs, function(index, pageBlockDiv) {
								 	$(this).click(function() { 
												setTimeout(function() { 
																	setToPage(index+1); 
																	}, 500);
										});
								 });
  
}

function formatPagesDiv()
{
	var numPages = gsif.pageArray.length;
	var blockRowHeight = 30;

	if(numPages <= 1)
	{
		$('#pages_div_container').css('display', 'none');
		return;
	}
	
	$('#pages_div_container').css('display', 'block');
	
	var newHeight = (Math.ceil(numPages / 18) * blockRowHeight);
	
	$('#pages_div_container').css('height', newHeight + 'px'); // 18 per row
	
}

function setPageSelected(page)
{
  $('#pages_div div').each(function(i) {
									   if(i == page-1)
									   {
										   $(this).attr('class', 'page_block_div_selected');
									   } else {
										   $(this).attr('class', 'page_block_div');
									   }
									   
									 });
}

function changePage(jsonData)
{
//	alert(jsonData.slideshow_thumbs[0]);
//	alert(jsonData.slideshow_main[1]);
	$('#header_div_text').html(jsonData.header);

	alert('' + jsonData.scripture + '');
	if(jsonData.scripture != '')
	{
		$('#scripture_div').css('display', 'block');
		$('#scripture_div').html(jsonData.scripture);
	} else {
		$('#scripture_div').css('display', 'none');
	}

	$('#thumb_img1').attr('src', '');
	$('#thumb_img2').attr('src', '');
	$('#thumb_img3').attr('src', '');
	$('#thumb_img4').attr('src', '');

	$('#overlay').css('display', 'none');		

	// show slideshow
	if(jsonData.slideshow_thumbs[0] != undefined)
	{
		$('#slideshow_text_div').css('display', 'block');
		$('#slideshow_thumbnails_div').css('display', 'block');
		$('#slideshow_text_div').html("");
		$('#thumb_img1').attr('src', jsonData.slideshow_thumbs[0]);
		$('#thumb_img2').attr('src', jsonData.slideshow_thumbs[1]);
		$('#thumb_img3').attr('src', jsonData.slideshow_thumbs[2]);
		$('#thumb_img4').attr('src', jsonData.slideshow_thumbs[3]);
		
		gsif.slideshowImages = jsonData.slideshow_main;
		
		
	} else {
		$('#slideshow_text_div').css('display', 'none');		
		$('#slideshow_thumbnails_div').css('display', 'none');
	}

	gsif.pageArray = [];
    getContent(jsonData.content);
	addPageBlocks();

	// close menu
	$('#nav_div').empty();
	$('#nav_div').html(gsif.menuHTML);
	createMenuBar();
	registerNav();
	
	// show page
	setToPage(1);

//	alert(jsonData.header);
}
