var tabList = new Array();		//array of tabs
var postList = new Array();		//array of posts

var tabWidthOffset = 0;			//used to position tabs evenly
var currentTab = "";			//marker that indicates the tab the user is currently on
var totalWidth = 0;				//total width of a post element includingg spacing and borders etc
var numberOfPosts = 0;			//number of loaded into the element under a tab
var currentSlidePosition = 0;	//current position of slider, used to grey out arrows and stop user going off the edge
var postLimit = 4;				//how many posts can be seen? currently its 4

//animations for sliding left and right
var timerID = new Array();
var obj = new Array();
var moving = new Array();

//var used to check if we are holding down an arrow
var cruise = false;

//add a tab from the php tablist to the javascript tablist
function addTab(a_Tab,a_Desc)
{
	var tab = new Object();
	tab.name = a_Tab;
	tab.description = unescape(a_Desc);		//decode the html as it has been encoded using rawurlencode
	tabList[tabList.length] = tab;
}

//add a post image from the post's images array in php to the post images array in javascript
function addPostImage(a_TypeIndex,a_PostImage)
{
	postList[a_TypeIndex][numberOfPosts].content.addImageToGallery(a_PostImage);
}

//add a post flash from the post's flash array in php to the post flash array in javascript
function addPostFlash(a_TypeIndex, a_PostFlash)
{
	postList[a_TypeIndex][numberOfPosts].content.addFlashToGallery(a_PostFlash);
}

//basically converts php array of posts into javascript array
function addPost(a_TypeIndex,a_PostTitle,a_PostHeadline,a_PostShortText,a_ID,a_Slug,a_Link,a_Date,a_Content,a_TextContent,isGallery,isDemo,thumbSrc)
{
	var numberOfTypes = postList.length;
	
	if(postList[a_TypeIndex] == undefined)
	{
		postList[a_TypeIndex] = new Array();	//2D array, for each post tab -> post elements
	}
	
	numberOfPosts = postList[a_TypeIndex].length;
	
	var post = new Object();	//internal object to hold all of posts information, later to be displayed
	post.title = a_PostTitle;
	post.headline = a_PostHeadline;
	post.shortText = unescape(a_PostShortText);
	post.postID = a_ID;
	post.postSlug = a_Slug;
	post.postLink = a_Link;
	post.postDate = a_Date;
	post.fullContent = unescape(a_Content);
	post.content = new GalleryPage(a_TextContent);
	post.isGallery = isGallery;
	post.isDemo = isDemo;
	post.thumb = thumbSrc;
	
	//alert("title: " + post.title + " image: " + post.image);
	
	postList[a_TypeIndex][numberOfPosts] = post;	//add the the 2D array
}

//once the tabs have been added into internal tablist, this actually creates them
function createTabs()
{
	//get the tab list div from the html page (the 1 is becuase there used to be to rows of tabs, now only 1 is used)
	var tabsDiv = document.getElementById('slider-mod-tabs-1');

	var i = 0;
	var currentTabWidth = 0;	//used to create second line of tabs if the width goes over limit) : unstable
	var currentLeft = 0;		//used to attach tabs evenly from the beginning
	var tempHTML = "";
	var secondFlag = false;		//marks whether it should start using second row
	var leftOffset = 5;			//how far apart the tabs are from each other
	
	for(i=0;i<tabList.length;i++)	//go through all tabs
	{	
		if((currentTabWidth + estimateTabWidth(tabList[i].name.length)) < tabsDiv.offsetWidth)	//if it doesnt need to create a new tabline
		{
			createTab(tabsDiv,i,currentLeft,secondFlag);	//call create tab to create and attach the element
			var tabWidth = getTabWidth("slider-tab-"+i);	//sort out its width so the next tab can be added at the correct distance form it
			currentTabWidth += tabWidth + leftOffset;
			currentLeft += tabWidth + leftOffset;
		}
		else if(!secondFlag)	//create a line tabrow, not actually needed at the moment and not sure if it still works if it does wrap
		{
			secondFlag = true;
			tempHTML = tabsDiv.innerHTML;
			tabsDiv = document.getElementById('slider-mod-tabs-2');
			currentTabWidth = 0;
			currentLeft = leftOffset;
			createTab(tabsDiv,i,currentLeft,secondFlag);
			var tabWidth = getTabWidth("slider-tab-"+i);
			currentTabWidth += tabWidth + leftOffset;
			currentLeft += tabWidth + leftOffset;
		}
	}

	if(tempHTML != "")	//a bit of switching between tab rows
	{
		var tempSecondHTML = tabsDiv.innerHTML;
		tabsDiv.innerHTML = tempHTML;
		document.getElementById('slider-mod-tabs-1').innerHTML = tempSecondHTML;
	}else
	{
		document.getElementById('slider-mod-tabs-2').style.display = "none";
	}
	
}

//creates a tab element and adds it to the page
function createTab(tabDiv,index,currentLeft,secondFlag)
{
	tabDiv.innerHTML += "<div onclick='showType("+ index +" )' onmouseover='tabHover("+index+",true)' onmouseout='tabHover("+index+",false)' id='slider-tab-"+index+"' class='slider-mod-tab'>" + tabList[index].name + "</div>";
	//tabDiv.innerHTML += "<div onclick='setUrl(\"" + tabList[index].name +"\")' onmouseover='tabHover("+index+",true)' onmouseout='tabHover("+index+",false)' id='slider-tab-"+index+"' class='slider-mod-tab'>" + tabList[index].name + "</div>";
	var tempTab = document.getElementById("slider-tab-"+index);
	tempTab.style.left += currentLeft +"px";
	
	if(secondFlag)	//used for second tab row
	{
		tempTab.style.height += "41px";
	}
	
}

//setUrl sets url for bookmarking straight to tabs
function setUrl(tabName)
{
	if(tabName=="sitecapacity.com")tabName="sitecapacity";
	//window.location = "/?tab=" + tabName.toLowerCase();
	window.location.search = "tab=" + tabName.toLowerCase();
}

//so when a tab is clicked, showType is called to show that type of post
//need to attach all the posts from that type into the slider module
function showType(a_TypeIndex)
{
	endAllSlides();
	var bodyDiv = document.getElementById('slider-mod-inner');
	var tabDescDiv = document.getElementById('cat-description');	//area to describe current tab/short summary
	
	var elementWidth = 164;		//width of a post in pixels
	var elementSpacing = 20;	//space between posts
	var elementBorder = 0;		//border: none
	var innerWidth = 0;			//width of the inner block in the module
	
	totalWidth = elementWidth + elementSpacing + (elementBorder*2);
	
	var coverWidth = elementWidth;	//cover is the overlay that appears on mouse over
	var titleWidth = elementWidth;	//title is the title overlay
	
	bodyDiv.innerHTML = "";			//clear current body
	
	if(tabList[a_TypeIndex].name == "News" && postList[a_TypeIndex])
	{
		tabDescDiv.innerHTML = "<i>Latest News:</i> "+postList[a_TypeIndex][0].shortText;	//set the description oft he cat (category description)
	}
	else
	{
		tabDescDiv.innerHTML = tabList[a_TypeIndex].description;	//set the description oft he cat (category description)
	}
	
	bodyDiv.style.left = "50px";	//space from far left of module (including space for left arrow)
	currentSlidePosition = 0;		//reset the current slide to the beginning (far left)
	
	if(currentTab != "")
	{
		currentTab.className = " slider-mod-tab";
	}
	
	currentTab = document.getElementById("slider-tab-"+a_TypeIndex);	//get the currrent tab
	currentTab.className = " slider-mod-tab-current";	//current tab is highlighted white in css
	
	var i = 0;
	
	if(postList[a_TypeIndex] != undefined)	//if there are posts to display
	{
		numberOfPosts = postList[a_TypeIndex].length;	//update the number on display, used for arrow limits
		
		checkArrowUse();	//grey the arrows out if not needed
		
		for(i=0;i<numberOfPosts;i++)	//for all posts
		{
			var postID = postList[a_TypeIndex][i].postID;
			var idString = '"elmID_' + postID + '"';
			var idStringCover = '"cover_elmID_' + postID + '"';
			var idStringTitle = '"title_elmID_' + postID + '"';
			
			var thumbImageSrc = "";
			
			if(postList[a_TypeIndex][i].thumb != "")	//optional thumbnail
			{
				thumbImageSrc = postList[a_TypeIndex][i].thumb;
			}
			else
			{
				thumbImageSrc = postList[a_TypeIndex][i].content.images[0];
			}
			
			var titleString = "";
			
			if(postList[a_TypeIndex][i].headline != "")	//optional headline
			{
				titleString = postList[a_TypeIndex][i].headline;
			}
			else
			{
				titleString = postList[a_TypeIndex][i].title;
			}
			
			//create and attach element
			bodyDiv.innerHTML += "<div id="+idString+" class='slider-mod-element' style='width:"+elementWidth+"px;margin-left:"+elementSpacing+"px;border: #666666 solid "+elementBorder+"px;' onclick='selectPost("+a_TypeIndex+","+i+")' onmouseover='changeOverlay("+idString+",true)' onmouseout='changeOverlay("+idString+",false)'><div id="+idStringCover+" class='cover' style='width:"+coverWidth+"px;'><p>" + postList[a_TypeIndex][i].shortText  + "</p><p>Date: " + postList[a_TypeIndex][i].postDate + "</p></div><span id="+idStringTitle+" class='slider-mod-element-title' style='width:"+titleWidth+"px;'><p>" + titleString  + "</p></span><img src='" + thumbImageSrc + "' height=130 width="+elementWidth+" /></div>";
			innerWidth += totalWidth;
		}
		
		bodyDiv.style.width = innerWidth + "px";

	}
	else	//tab doesnt contain any posts
	{
		numberOfPosts = 0;
		checkArrowUse();	//grey the arrows out if not needed
	}
		
}

//on mouse over, need to display the overlay and describe post using post excerpt
function changeOverlay(elementID,toggle)
{
	var coverDiv = document.getElementById("cover_"+elementID);
	var titleSpan = document.getElementById("title_"+elementID);

	if(toggle)
	{
		coverDiv.style.display = "inline";
		//titleSpan.style.display = "none";
	}
	else
	{
		coverDiv.style.display = "none";
		//titleSpan.style.display = "inline";
	}
	
}

//change the tab using css on mouse over
function tabHover(index,toggle)
{

	var tempTab = document.getElementById("slider-tab-"+index);
	
	if(currentTab != tempTab)
	{
		if(toggle)
		{
			tempTab.className += " slider-mod-tab-hover";
		}
		else
		{
			tempTab.className = "slider-mod-tab";
		}
	}
}

//on mouse click when clicking on post element
function selectPost(typeIndex,elementIndex)
{
	postList[typeIndex][elementIndex].content.currentImageIndex = 0;	//reset current image to beginning
	showShadowBox(postList[typeIndex],elementIndex);					//shadow box with the post element
}

//internal function to help evenly spread tabs, could have made them relative however
//if sure to be only using a single tab row
function getTabWidth(elmID) 
{
	var elmWidth, elmMargin, elmPadding;
	if(document.all) 
	{ // IE
		elmWidth=document.getElementById(elmID).offsetWidth;
		tabWidthOffset = -2;	//stupid IE, need to offset the border
	}
	else 
	{ // Mozilla
		elmWidth=parseInt(document.defaultView.getComputedStyle(document.getElementById(elmID), '').getPropertyValue('width'));
		
		if(tabWidthOffset == 0)
		{
			elmMargin=parseInt(document.defaultView.getComputedStyle(document.getElementById(elmID), '').getPropertyValue('margin-left'))+parseInt(document.defaultView.getComputedStyle(document.getElementById(elmID), '').getPropertyValue('margin-right'));
			elmPadding=parseInt(document.defaultView.getComputedStyle(document.getElementById(elmID), '').getPropertyValue('padding-left'))+parseInt(document.defaultView.getComputedStyle(document.getElementById(elmID), '').getPropertyValue('padding-right'));
			tabWidthOffset = elmMargin + elmPadding;
		}
	}
	
	//some issues with Chrome and Safari, width is not constant, probably the way it renders the div.
	//update: issues seem to have stopped?
	return tabWidthOffset + elmWidth;
}

//used to go to far end of far beginning of posts
function getInnerPosition(elm) 
{
	var pixels;
	if(document.all) 
	{ // IE
		var pixels=parseInt(elm.currentStyle.left);
	}
	else 
	{ // Mozilla
		var pixels = parseInt(document.defaultView.getComputedStyle(elm,'').getPropertyValue('left'));
	}
	return pixels;
}

//used to go to far end of far beginning of posts
function getInnerWidth(elm)
{
	var pixels;
	if(document.all) 
	{ // IE
		pixels=parseInt(elm.currentStyle.width);
	}
	else 
	{ // Mozilla

		pixels=parseInt(document.defaultView.getComputedStyle(elm, '').getPropertyValue('width'));

	}
	return pixels;
}

//accessor functions for the styles - gets style.left
function getLeft(elm)
{
	var pixels;
	if(document.all) 
	{ // IE
		pixels=parseInt(elm.currentStyle.left);
	}
	else 
	{ // Mozilla

		pixels=parseInt(document.defaultView.getComputedStyle(elm, '').getPropertyValue('left'));

	}
	return pixels;
}

//accessor functions for the styles - gets style.right
function getRight(elm)
{
	var pixels;
	if(document.all) 
	{ // IE
		pixels=parseInt(elm.currentStyle.right);
	}
	else 
	{ // Mozilla

		pixels=parseInt(document.defaultView.getComputedStyle(elm, '').getPropertyValue('right'));

	}
	return pixels;
}

//need to estimate the tab width based on characters
function estimateTabWidth(charLength)
{
	var estWidth = (charLength * 8) + tabWidthOffset;
	
	return estWidth;

}

//when one of the arrows are pressed
//dir is the direction (left,right)
//full is whether to go far right or far left
//if full is true slides will be ignored
//if slides = 0, full will be true
function sliderSlide(dir,slides)
{
	var full = false;
	var innerBox = document.getElementById('slider-mod-inner');
	var currentLeft = getInnerPosition(innerBox,dir);
	var currentInnerWidth = getInnerWidth(innerBox);
	var leftArrow = document.getElementById('slider-mod-leftarrow');
	var rightArrow = document.getElementById('slider-mod-rightarrow');
	var okToMove = checkArrowLimit(dir);	//am I at the end of beginning? is it ok to move?

	if (slides == 0) full = true;
	
	if(dir == "left")
	{
		arrowDiv = document.getElementById('slider-mod-leftarrow');
	
		if(okToMove)	//yes you can move left
		{
			if(full)	//want to go far left?
			{
				innerBox.style.left = "50px";	//go the beginning
				currentSlidePosition = 0;		//reset currentslideposition
			}
			else		//go left
			{

				if(!moving[innerBox])
				{
					//lets make this slide across!
					moving[innerBox] = true;
					obj[innerBox] = new Object();
					obj[innerBox].div = innerBox;
					obj[innerBox].counter = 0;
					obj[innerBox].dir = dir;
					obj[innerBox].currentLeft = currentLeft;
					obj[innerBox].aim = obj[innerBox].currentLeft + totalWidth;
					//make sure we're not moving too far
					if (currentSlidePosition < slides) slides = currentSlidePosition;
					//start sliding
					timerID[innerBox] = setInterval('slideTick(\'' + innerBox + '\',' + slides + ');',25);	//start a timer interval
				}
				
			}
		}
		checkArrowUse();	//update arrow grey out if at far left
	}
	else	//right
	{
		if(okToMove)	//yes you can move right
		{
			if(full)	//want to go full right?
			{
				/*same effect as below, however could lag if many posts were being iterated through
				while(checkArrowLimit(dir))	//basically applies "1 right" many times
				{
					innerBox.style.left = currentLeft - totalWidth + "px";
					currentSlidePosition ++;
					currentLeft = getInnerPosition(innerBox,dir);
				}*/
				
				//this is perhaps better but more hardcoded to the inner width
				innerBox.style.left = -currentInnerWidth + 782 + "px";
				currentSlidePosition = numberOfPosts-postLimit;
			}
			else	//go right
			{
				if(!moving[innerBox])
				{
					//lets make this slide across!
					moving[innerBox] = true;
					obj[innerBox] = new Object();
					obj[innerBox].div = innerBox;
					obj[innerBox].counter = 0;
					obj[innerBox].dir = dir;
					obj[innerBox].currentLeft = currentLeft;
					obj[innerBox].aim = obj[innerBox].currentLeft - totalWidth;
					//make sure we don't go to far right
					if (currentSlidePosition + slides > numberOfPosts-postLimit) slides = numberOfPosts-postLimit-currentSlidePosition;
					//start sliding
					timerID[innerBox] = setInterval('slideTick(\'' + innerBox + '\',' + slides + ');',25);
				}
			}
			
		}
		
		checkArrowUse();	//update arrow grey out if at far left
	}
}

function sliderToLeft()
{
		sliderSlide("left",numberOfPosts);
}

function startCruise(dir)
{
	cruise = true;
	sliderSlide(dir,4);
}

function endCruise()
{
	cruise = false;
}

function slideTick(objname, slides)	//called every interval tick
{
	innerBox = document.getElementById('slider-mod-inner');
	speed = 46;	//this value was chosen so that 46 divides nicely into the posts width (164 + 20 spacing), otherwise you need to offset the speed on each tick
	if(obj[objname].counter < slides)
	{
		aim = obj[innerBox].aim;	//the pixel left position the next post wants to be
		if(obj[innerBox].dir == "right")	//direction right
		{
			if(getLeft(innerBox) - speed - speed >= aim)	//check if next time will be last time
			{
				innerBox.style.left = getLeft(innerBox) - speed + "px";	//move by the speed
				obj[innerBox].currentLeft = getInnerPosition(innerBox);	//update currentleft for next post to move
			}
			else	//last tick of each
			{
				
				innerBox.style.left = getLeft(innerBox) - speed + "px";	//last time we need to move for this post, makes the sliding more smooth
				obj[innerBox].currentLeft = getInnerPosition(innerBox);
				obj[innerBox].counter ++;	//update the number moved
				currentSlidePosition ++;	//current number of posts slided through
				obj[innerBox].aim = obj[innerBox].currentLeft - totalWidth;
			}
		}
		else
		{
			if(getLeft(innerBox) + speed + speed <= aim)
			{
				innerBox.style.left = getLeft(innerBox) + speed + "px";
				obj[innerBox].currentLeft = getInnerPosition(innerBox);
			}
			else
			{
				innerBox.style.left = getLeft(innerBox) + speed + "px";
				obj[innerBox].currentLeft = getInnerPosition(innerBox);
				obj[innerBox].counter ++;
				currentSlidePosition --;
				obj[innerBox].aim = obj[innerBox].currentLeft + totalWidth;
			}
		}
	}
	else
	{
		if(cruise) tmp_dir = obj[innerBox].dir;
			
		endSlide(innerBox);	//stop the sliding
			
		if(cruise) sliderSlide(tmp_dir,1)	
	}
}

function endSlide(objname)
{
	clearInterval(timerID[objname]);	//stop the timer
	
	//clean up
	delete(moving[objname]);
	delete(timerID[objname]);
	delete(obj[objname]);
	
	checkArrowUse();	//update arrow grey out if at far left
}

//used when changing tabs, want to make sure no animations are still going
function endAllSlides()
{
	for(i in timerID)
	{
		clearInterval(timerID[i]);
		delete(moving[i]);
		delete(timerID[i]);
		delete(obj[i]);
	}
}

//greys out arrows if at full left of full right
function checkArrowUse()
{	
	var leftArrow = document.getElementById('left-image');
	var rightArrow = document.getElementById('right-image');
	if(leftArrow != null && rightArrow != null)
	{
		path = leftArrow.src.substring(0,leftArrow.src.lastIndexOf('/'))+'/';
		if(currentSlidePosition <= 0)
		{
			leftArrow.src = path+"beginning_button.png";
		}else
		{
			leftArrow.src = path+"previous_button.png";
		}
		
		if((currentSlidePosition+postLimit) < numberOfPosts)
		{
			rightArrow.src = path+"next_button.png";
		}else
		{
			rightArrow.src = path+"end_button.png";
		}
	}
}

//check if it is ok to move in that direction
function checkArrowLimit(dir)
{
	var okToMove = false;

	if(dir == "right")
	{
		if((currentSlidePosition+postLimit) < numberOfPosts)
		{
			okToMove =  true;
		}
	}
	else if(dir == "left")
	{
		if(currentSlidePosition > 0)
		{
			okToMove = true;
		}
	}
	
	return okToMove;

}


/*START GALLERY CLASS*/
/* used for gallery type posts*/

function GalleryPage(text)
{
	this.text = text;				//text of the gallery (left side)
	this.images = new Array();		//array of images
	this.currentImageIndex = 0;		//currently looking at image index
}

//this is how you add functions a javascript object to act like a class
GalleryPage.prototype.addImageToGallery = addImageToGallery;
GalleryPage.prototype.addFlashToGallery = addFlashToGallery;
GalleryPage.prototype.changeGalleryImage = changeGalleryImage;
GalleryPage.prototype.resetCurrentImage = resetCurrentImage;
GalleryPage.prototype.getImageIndex = getImageIndex;
GalleryPage.prototype.checkEnd = checkEnd;
GalleryPage.prototype.getImagesSize = getImagesSize;

function addImageToGallery(image)
{
	this.images[this.images.length] = image;
}

function addFlashToGallery(flash)
{
	this.images[this.images.length] = flash;
}

function resetCurrentImage()
{
	this.currentImageIndex = 0;
}

function getImageIndex()
{
	return this.currentImageIndex;
}

function getImagesSize()
{
	return this.images.length;
}

function checkEnd()
{
	//alert(this.currentImageIndex);
	if(this.currentImageIndex < this.images.length-1)
	{
		return false;
	}
	else
	{
		return true;
	}
}

//left and right change of gallery images
function changeGalleryImage(content,dir)
{
	var imageDiv = document.getElementById('gallery-image');
	var prev = document.getElementById('gallery-prev');
	var next = document.getElementById('gallery-next');

	if((dir == "next") && (content.currentImageIndex+1 < content.images.length))
	{
		content.currentImageIndex ++;
		if(content.images[content.currentImageIndex][0] == '%' )
		{
			imageDiv.innerHTML = unescape(content.images[content.currentImageIndex]);
		}
		else
		{
			imageDiv.innerHTML = "<img src="+content.images[content.currentImageIndex]+" />";
		}
		
		prev.style.display = "inline";
		
		if(content.currentImageIndex+2 > content.images.length)
		{
			next.style.display = "none";
		}
		
		document.getElementById('gallery-indexOf').innerHTML = (content.currentImageIndex+1) + " of " + (content.images.length);
		
	}
	else if(dir == "prev" && (content.currentImageIndex > 0))
	{
		content.currentImageIndex --;
		
		if(content.images[content.currentImageIndex][0] == '%' )
		{
			imageDiv.innerHTML = unescape(content.images[content.currentImageIndex]);
		}
		else
		{
			imageDiv.innerHTML = "<img src="+content.images[content.currentImageIndex]+" />";
		}
		
		next.style.display = "inline";
		
		if(content.currentImageIndex <= 0)
		{
			prev.style.display = "none";
		}
		
		document.getElementById('gallery-indexOf').innerHTML = (content.currentImageIndex+1) + " of " + (content.images.length);
	}
}

//switch from text version to js version
function switchOn() {
	plaintext_ver = document.getElementById('plaintext-module');
	javascript_ver = document.getElementById('javascript-module');
	plaintext_ver.style.display = 'none';
	javascript_ver.style.display = 'block';
}