var currentPosition=0;
var $calendarOffset=1; // page break point
var $news = null;
var $events = null;
var $scrollItems = null;
var showingItem = 0;
var $scrollIndicators = null;
var stateVal = stateList.length-1;
// FB variables
var displayedMsgs = 0;
var displayedMsgLimit = 5;
// News Pagination
var newsStart = 0;
var newsIncrement = 15; //number of news articles per page for news.html
var displayedNewsPage = 0; //currently displayed news page
var numberOfNewsPages = 0; //total pages of news

$(document).ready(function() {
	pageSpecificFunctions();
	verticalAlignCopy();
});

function verticalAlignCopy(){
	$(".verticalAlignIt").each( function(){
		var mydifference = Number($(this).parent().height()-$(this).height());
		var adjustment = Number(mydifference/2);
		$(this).css("paddingTop",adjustment+"px");
	});
}

function callNextPage(){
	var i=currentPosition;
	var pageBreakPoint=(i+$calendarOffset+1);
	$events.addClass("dontDisplay");
	$("#pagingController").addClass("dontDisplay");
	$events.slice(i,pageBreakPoint-1).removeClass("dontDisplay");
	if($events.length >= pageBreakPoint){
		currentPosition=pageBreakPoint-1;
		if(pageBreakPoint > $events.length){
			$("#pagingController").addClass("inactiveControl");
		}else{
			$events.eq(currentPosition-1).addClass("dontDisplay");
			currentPosition=currentPosition-1;
		}
		$("#pagingController").removeClass("dontDisplay");
	}
}

function showItem(myIndex){
	if(myIndex==null){myIndex=0;}
	$scrollItems.hide();
	$scrollItems.eq(myIndex).fadeIn(800);
	for(i=0; i<$scrollIndicators.length; i++){
		$scrollIndicators.eq(i).removeClass("itemOn");
	}
	$scrollIndicators.eq(myIndex).addClass("itemOn");
}

function initializeScroller(myType,settings){
	switch(myType){
		case "calendar":  // Calendar style scroller
			$events = $(settings.contentpiece);
			$calendarOffset = settings.pageLimit;
			$(settings.nextPage).click( function(){
				if($(this).hasClass("inactiveControl")==false){
					callNextPage();
				}
				return false;
			});
			callNextPage();
			break;
		case "content": //setup a Content Scroller 
			if($(settings.contentpiece).length>0){
				$scrollItems = $(settings.contentpiece);
				$scrollIndicators = $(settings.indictors);
				showItem(0);
				$scrollIndicators.click( function(e){
					showingItem=$scrollIndicators.index(this);
					showItem(showingItem);
					return false;
				});
				$(settings.nextItem).click( function(){
					showingItem++;
					if(showingItem>=$scrollItems.length){
						showingItem=0;
					}
					showItem(showingItem);
					return false;
				});
				$(settings.PrevItem).click( function(){
					showingItem--;
					if(showingItem<0){
						showingItem=$scrollItems.length-1;
					}
					showItem(showingItem);
					return false;
				});
			}
		break;
	}
}

function formatFBTime(fbDate){
  var arrDateTime = fbDate.split("T"); 
  var arrDateCode = arrDateTime[0].split("-");
  var strTimeCode = arrDateTime[1].substring(0,  arrDateTime[1].indexOf("+")); 
  var arrTimeCode = strTimeCode.split(":"); 
  var valid_date = new Date()
  valid_date.setUTCFullYear(arrDateCode[0]);
  valid_date.setUTCMonth(arrDateCode[1] - 1);
  valid_date.setUTCDate(arrDateCode[2]);
  valid_date.setUTCHours(arrTimeCode[0]);
  valid_date.setUTCMinutes(arrTimeCode[1]);
  valid_date.setUTCSeconds(arrTimeCode[2]);
  return valid_date;
}

function getFacebookWall(settings){
	$.getJSON("https://graph.facebook.com/"+settings.url+"/posts?limit="+settings.postlimit+"&access_token="+settings.accesstoken+"&callback=?", null, function(data,status) {
		if(status == 'success') {
			var mycount = 0;
			displayedMsgs = 0;
			var myPostsString="";
			$(data.data).each(function(e){
				mycount++;
				if(this.message!=undefined){
					if(displayedMsgs<displayedMsgLimit){
						displayedMsgs++;
						if(displayedMsgs == displayedMsgLimit){
							myPostsString=myPostsString+("<div id='fbresponse-"+displayedMsgs+"' class='fbStream lastitem'>");
						}else{
							myPostsString=myPostsString+("<div id='fbresponse-"+displayedMsgs+"' class='fbStream'>");
						}
						myPostsString=myPostsString+("<p class='posterinfo'><span class='postername'>"+this.from.name+"</span><span class='posterdate'>"+formatFBTime(this.updated_time)+"</span></p>");
						myPostsString=myPostsString+("<p class='postermessage'>"+this.message+"</p>");
						myPostsString=myPostsString+("</div>");
					}
				}
			});
			
			if(myPostsString==""){
				//alert("no posts");
			}else{
				$('#fbPostStream').html(myPostsString);
				$(".facebookConditional").addClass("dontDisplay");
			}
		}
	});
}

function pageAppSettingFB(){
   FB.init({
     appId  : '251751658191243',
     status : true, // check login status
     cookie : true, // enable cookies to allow the server to access the session
     xfbml  : true, // parse XFBML
     oauth : true // enables OAuth 2.0
   });
}

function pageFeedLogin(){
   pageAppSettingFB();
   //FB.UIServer.setLoadedNode = function (a, b){FB.UIServer._loadedNodes[a.id] = b; }
   FB.login(function(response) {	
	logBackOnFacebook();
   });
}

function logBackOnFacebook(){   
	var t = setTimeout(function() {
		pageAppSettingFB();
		//FB.UIServer.setLoadedNode = function (a, b){FB.UIServer._loadedNodes[a.id] = b; }
		FB.getLoginStatus(function(response) { 
			if (response.authResponse) {
					var accessToken = response.authResponse.accessToken;
					getFacebookWall({
						url:stateList[stateVal][3],
						postlimit:25,
						accesstoken:accessToken
					});
			} 
		});
		clearInterval(t);
	}, 1000);
}
function wireupCommonElements(){
	// look for email links and wire them up to the email functionality.
	// Currently this is a standard mailto html function.
	//rewriteEmail();
	$(".facebookpagelogin").click(function(){
		pageFeedLogin();
	});
	$("a.seeallfacebook").each(function(){
		var myLink = stateList[stateList.length-1][2];
		if(myLink.length>0){
			$(".facebookConditional").removeClass("dontDisplay");
			$(this).attr("href",myLink);
			$(this).parent().removeClass("dontDisplay");
		}else{
			$(".facebookConditional").addClass("dontDisplay");
			$(this).parent().addClass("dontDisplay");
		}
		for(var x=0; x<stateList.length;x++){
			if(String(stateList[x][0])==$(this).attr("id")){
				stateVal = x;
				myLink = stateList[x][2];
				if(myLink.length>0){
					$(".facebookConditional").removeClass("dontDisplay");
					$(this).attr("href",myLink);
					$(this).parent().removeClass("dontDisplay");
				}else{
					$(".facebookConditional").addClass("dontDisplay");
					$(this).parent().addClass("dontDisplay");
				}
			}
		}			
	});
	// Non page specific functions
	// generic backpage button
	$("a.previousPageLink").click( function(){
		if(document.referrer.length>0){
			location.href = document.referrer;
		}else{
			return true;
		}
		return false;
	});
	// Set up click/reveal boxes if page has them
	/*if($("a.revealQuoteLink").length>0){
		$("a.revealQuoteLink").click( function(){
			var myContainer = $(".graybox").has(this);
			$(".box-quote", myContainer).fadeIn("slow");
			$(".box-info", myContainer).fadeOut("slow");
		});
		$(".box-quote").click( function(){
			var myContainer = $(".graybox").has(this);
			$(".box-quote", myContainer).fadeOut("slow");
			$(".box-info", myContainer).fadeIn("slow");
		});
	}*/
	
	// Setup State Selector
	$("#stateSelectorDD .defaultSelection, #stateSelectorDD ul").mouseover( function(){
		clearTimeout($("#stateSelectorDD ul").data('hoverTimeOut'));
		$("#stateSelectorDD ul").removeClass("dontDisplay");
	}).mouseout( function(){
		var t = setTimeout(function() {
			$("#stateSelectorDD ul").addClass("dontDisplay");
		}, 200);
		$("#stateSelectorDD ul").data('hoverTimeOut', t);
	});
	
	$("#stateSelectorDD ul a").addClass("stateSelectorOff");
	$("#stateSelectorDD ul a").mouseover( function(){
		$(this).addClass("stateSelectorOver");
	}).mouseout( function(){
		$(this).removeClass("stateSelectorOver");
	});
	
	// Setup Overlay Mask - displays value of href.
	if($("a[rel]").size()>0){
		$("#stateNotListedLink a").overlay({
			mask: {
				color: '#000000',
				loadSpeed: 200,
				opacity: 0.92
			},
			top:"20%",
			left:"center",
			onBeforeLoad: function() {
				var wrap = this.getOverlay().find(".contentWrap");
				wrap.load(this.getTrigger().attr("href"));
			},
			onLoad: function() {
				var overlaysetup = setTimeout(function () {
					wireupFooterElements();
					clearInterval(overlaysetup);
				}, 1000);
			}
		});
	}
}

function sortNewsItems(pageElements){
	var mylist = $(pageElements);
	var listitems = $(".newsItem",mylist).get();
	listitems.sort(function(a, b) {
		var compA = String($(a).attr("id"));
	   	var compB = $(b).attr("id");
	    	var myHolder = compA.replace(/-/g,"");
	    	var myHolder1 = compB.replace(/-/g,"");
	    	compA = myHolder.replace(/newsitem/g,"");
	    	compB = myHolder1.replace(/newsitem/g,"");
	   	return (compA < compB) ? 1 : (compA > compB) ? -1 : 0;
	});
	mylist.append(listitems);
	return listitems;
}

(function($) {
  $.fn.outerHTML = function() {
    return $(this).clone().wrap('<div></div>').parent().html();
  }
})(jQuery);

function paginateNews(){
	var controllerHTML ="";
	numberOfNewsPages = Math.ceil($news.size()/newsIncrement);
	//build control area
	controllerHTML ="<div id='newsPaginationControl'>";
	controllerHTML = controllerHTML + "<span class='pageControlLink'><a id='pageLink-prev' href='#' class='pageControlItem'>prev</a></span>";
	for(var x=0; x<numberOfNewsPages; x++){
		controllerHTML = controllerHTML + "<span class='pageControlLink'><a id='pageLink-" + x
		+ "' href='#' class='pageControlItem'>"+ (x+1) + "</a></span>";
	}
	controllerHTML = controllerHTML + "<span class='pageControlLink'><a id='pageLink-next' href='#' class='pageControlItem'>next</a></span>";
	controllerHTML = controllerHTML + "</div>";
	$(".newsStage").after(controllerHTML);
	$("#newsPaginationControl a").click(function(){ 
		var myID = $(this).attr("id").replace('pageLink-','');
		switch(myID){
			case "next":
				switchNewsPage(displayedNewsPage+1);
			break;
			case "prev":
				switchNewsPage(displayedNewsPage-1);
			break;
			default:
				switchNewsPage(Number(myID));
			break;
		}
		return false;
	});
	switchNewsPage(0); // first page
}

function switchNewsPage(currentPageNum){
		if(currentPageNum<0){
			currentPageNum=0;
		}
		if(currentPageNum>numberOfNewsPages-1){
			currentPageNum=numberOfNewsPages-1;
		}
		displayedNewsPage=currentPageNum;
		$("#newsPaginationControl a").removeClass("currentPageNav");
		$("#pageLink-"+currentPageNum).addClass("currentPageNav");
		newsStart = Number(currentPageNum * newsIncrement);
		$news.addClass("dontDisplay");
		$news.slice(newsStart, (newsStart+newsIncrement)).removeClass("dontDisplay");
}

function pageSpecificFunctions(){
	$("ul.StateSelector li a").click(function(){
		if($("a[rel]",$(this).parent()).size()>0){
		}else{
			var myFilePath = String(window.location);
			var myPagePath = myFilePath.split('/');
			var myFileName= myPagePath[myPagePath.length - 1];
			if(String($(this).attr("href")).indexOf(myFileName)==-1){
				$(this).attr("href",$(this).attr("href")+myFileName);
			}
		}
	});
	if($("body.newsHomePage").length>0){
		var sortedNews = sortNewsItems(".newsContainer");
		var myHTMLWrite = '';
		$(sortedNews).each(function(){
			myHTMLWrite = myHTMLWrite+ $(this).outerHTML();
		});
		$(".newsContainer").html(String(myHTMLWrite));
		$news = $(".newsItem");
		if($news.size() > newsIncrement){
			paginateNews();
		}
	}
	if($("body.eventsCalendar").length>0){
		initializeScroller("calendar",{
			contentpiece:".eventItem",
			nextPage:"#nextPageLink",
			pageLimit:12
		});
	}
	if($("body.takeActionHomePage").length>0){
		initializeScroller("content",{
			contentpiece:".contentScrollItem",
			indictors:".circleIndicator",
			nextItem:"#nextItem",
			PrevItem:"#prevItem"
		});
		logBackOnFacebook();
	}
	wireupCommonElements(); // hook up elements based on styles		
	if($("body.takeActionIcons-LP").length>0){
		initializeWallpapers();
	}
}

function initializeWallpapers(){
	$(".wallpaperSizeLinks a").click(function(){
		var myDom = $("li").has($(this));
		var myNewDetails = String($("a.gridlink",myDom).attr("href"));
		
		if($(this).attr("name")=="wplarge"){
			var myLinkHolder = myNewDetails.replace(/1024/g,'1280');
			$("a.wallpaperlinklarge",myDom).addClass("activeLink");
			$("a.wallpaperlinksmall",myDom).removeClass("activeLink");
		}else{
			var myLinkHolder = myNewDetails.replace(/1280/g,'1024');
			$("a.wallpaperlinksmall",myDom).addClass("activeLink");
			$("a.wallpaperlinklarge",myDom).removeClass("activeLink");
		}
		$("li").has($(this)).attr('title', lastTitle);
		$("li").has($(this)).children('div#tooltip').remove();
		$("a.gridlink",myDom).attr("href",myLinkHolder);
		//return false;
							   
	});
	setImagePreview();
}

function setImagePreview() {

	$('li[rel=tooltip]').each(function(){
		$(this).attr("myvalue",$(this).attr('title'));
	});
	//Select all anchor tag with rel set to tooltip
	$('li[rel=tooltip]').mousemove(function (e) {
		if($('#tooltip').length == 0) {
			//Grab the title attribute's value and assign it to a variable
			var tip = $(this).attr('title');
			//lastTitle = tip;
			//Remove the title attribute's to avoid the native tooltip from the browser
			$(this).attr('title', '');
			//Append the tooltip template and its value
			$(this).append('<div id="tooltip"><div class="tipBody">' + tip + '</div></div>');
	
			//Show the tooltip with faceIn effect
			$('#tooltip').fadeIn('500');
			$('#tooltip').fadeTo('10', 1);
			$('#tooltip').css('top', mouseY(e) + 20+"px");
			$('#tooltip').css('left', mouseX(e) + 10+"px");
		}
		//Keep changing the X and Y axis for the tooltip, thus, the tooltip moves along with the mouse
			$('#tooltip').css('top', mouseY(e) + 20+"px");
			$('#tooltip').css('left', mouseX(e) + 10+"px");
		$('#tooltip img').css('width', 299+"px");
		$('#tooltip img').css('height', 224+"px");
	}).mouseout(function () {
		//Put back the title attribute's value
		$(this).attr('title', $(this).attr("myvalue"));

		//Remove the appended tooltip template
		$(this).children('div#tooltip').remove();

	});
}

function mouseX(evt) {
	if (evt.pageX) return evt.pageX;
	else if (evt.clientX)
	   return evt.clientX + (document.documentElement.scrollLeft ?
	   document.documentElement.scrollLeft :
	   document.body.scrollLeft);
	else return null;
}

function mouseY(evt) {
	if (evt.pageY) return evt.pageY;
	else if (evt.clientY)
	   return evt.clientY + (document.documentElement.scrollTop ?
	   document.documentElement.scrollTop :
	   document.body.scrollTop);
	else return null;
}

