//Please contact atgroom@atgroom.com before ripping off this function.


var DomYes=(document.getElementById)?true:false;

if(DomYes) {window.onresize=triggerResize;}
var fheight = getCookie('fheight',12);
var lheight = getCookie('lheight',16);
var linesPerCol = 10;
var totalLines;
//Number of lines we have already rendered. Of course we will lose some lines if the screen is shrunk on "page 2+" and we may run off the end of the article if the screen is expanded on the last "page"
var prevLines = 0;
var artTop;

var cw; //ClientWidth
var ch; //ClientHeight


var availHeight = lheight * linesPerCol;
var cols = getCookie('cols',setBrowserSizeDefaults());
var defaultWidth = 150;
var defaultHeight = 230;
var availWidth;
var size = 2;
var gutter = 20;
var headline = '';
//var images = '';
var minusactive = '';
var minusdisabled = '';
var plusactive = '';
var plusdisabled ='';
var fontmax = 18;
var fontmin = 8;
var trigger;
var triggerTimeout = 90;
cols = cols++;
cols = cols--;
fheight = fheight++;
fheight = fheight--;
lheight = lheight++;
lheight = lheight--;

function load() {

	
	cw = document.body.clientWidth;
	ch = document.body.clientHeight;
	
    
	if (DomYes) {
		var obj;
	
		//Loop through the columns.
		for (var xx=0;xx<6;xx++) {
			obj = document.getElementById('d' + (xx));
			//Set the font sizes
			//obj.style.fontSize = fheight + 'px';
			//obj.style.lineHeight = lheight + 'px';
			obj.style.fontSize = '12px';
			obj.style.lineHeight = '16px';



			//Write the story to the div
			tmp = story
			for (yy = 1;yy <= placeholders;yy++) {
				tmp = tmp.replace('art_img' + yy,'art_img' + yy + 'col' + xx)
			}
			
			tmp = tmp.replace('art_body_end','art_body_endcol' + xx)
			tmp = tmp.replace('art_full_end','art_full_endcol' + xx)
			obj.innerHTML = tmp;
			//if (xx==0) alert(tmp);
		}	
		mccol(cols);
		
		//I'm running resize again here because for some reason it is about 10px off the first time you run it.
		resize();
	} else {
		document.write(story);
	}
}

//This function should superseed MCCol as the column changing function. 
//At the moment it is hardcoded to assume that 243 pixels is the ideal size for a column.
function setBrowserSizeMaxes(cols) {
debug(',2');
	cw = document.body.clientWidth;
	if (cw < 615) {
			cols = 1;
			bustacol(1);
	} else if (cw <= 725) {
			cols = 2;
			bustacol(2);
	} else if (cw <= 809) {
			cols = 3;
			bustacol(3);
	} else if (cw <= 1072) {
			cols = 4;
			bustacol(4);
	} else if (cw <= 1335) {
			cols = 5;
			bustacol(5);
	} else if (cw >= 1600) {
			cols = 6;
			bustacol(6);
	} else {
		cols = cols;
	}
	for (var xx=cols;xx<6;xx++) {
		document.getElementById('d' + xx).style.display='none';
	}
	for (xx=(cols-1);xx>=0;xx--) {
		document.getElementById('d' + xx).style.display='';
	}
	return cols
	
}

//Sets the default number of columns for people who don't yet have a cookie.
function setBrowserSizeDefaults() {
debug(',3');
	//var cols;
	
	
	cw = document.body.clientWidth;



	if (cw <= 600) {
		cols = 1;
	} else if (cw <= 725) {
		cols = 2;
	} else if (cw <= 800) {
		cols = 3;
	} else if (cw <= 1024) {
		cols = 4;
	} else if (cw <= 1280) {
		cols = 5;
	} else if (cw <= 1400) {
		cols = 5;
	} else if (cw <= 2048) {
		cols = 6;
	} else {
		cols = 6;
	}

	return cols
}

function goToURL() {
debug(',7');
  	var i, args=goToURL.arguments; document.returnValue = false;
 	for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}

function swap(){
if (document.images){
for (var x=0;
x<swap.arguments.length;
x+=2) {
document[swap.arguments[x]].src = eval(swap.arguments[x+1] + ".src");
}
}
}


function scroll(lines) {
debug(',8');
	prevLines += lines;
	//if someone has resized then click "back" then the size of all previous pages have changed, therefore page 1 probably won't be full any more. So we make sure prevlines is >= 0.
	if (prevLines < 0) prevLines = 0;	
		var rect = 'rect(top right bottom left)';
		//Loop through the columns.
		for (var xx=0;xx<cols;xx++) {
			obj = document.getElementById('d' + (xx));
			//Move the article up until we get to the line we want
			obj.style.top = artTop-(xx*linesPerCol*lheight)-(prevLines*lheight);
			//Is the last line of the article visible?
			if ((cols*lheight*linesPerCol) < obj.offsetHeight) {
				showNext = true
			}
			//Clip off all the parts of the div that aren't meant to be seen (The top and the bottom)
			rect = 'rect(' + ((xx*linesPerCol*lheight)+(prevLines*lheight)) + ' ' + Math.round(availWidth/cols) + ' ' + (((xx+1)*linesPerCol*lheight)+(prevLines*lheight)) + ' 0)';
			obj.style.clip = rect;
		}
	//Is the first line of the article visible?
	showPrev=(prevLines>0)?true:false;
	//Is the last line of the article visible?
	showNext=(((prevLines*lheight)+(cols*lheight*linesPerCol)) < obj.offsetHeight)?true:false;
	//Paging Stuff
	showNav(showPrev,showNext);
}

function triggerResize() {
debug(',9');
	window.clearTimeout(trigger);
	prevLines = 0;
	trigger = window.setTimeout('resize()',triggerTimeout);
}

//This old school function changes collumns to the number you pass it, if you want to go down the user chooses rather than the program chooses road.
function mccol(numbiv) {
debug(',10');
    cols = numbiv
//	cols = setBrowserSizeMaxes(numbiv);
	bustacol(cols);

//	alert(cols);
//	alert(cw);
	
	//Hide the columns that the user doesn't want to see. Note: "Empty" columns will still display but will be positioned/clipped off screen.
	for (var xx=cols;xx<6;xx++) {
		document.getElementById('d' + xx).style.display='none';
	}
	for (xx=(cols-1);xx>=0;xx--) {
		document.getElementById('d' + xx).style.display='';
	}
	document.title=headline;
	resize()
	//setCookie('cols', cols);
}


function bustacol (cols){
debug(',11');
	if (cols  == 1) {
		gutter = (cw*0.15);
	} else if (cols  == 2) {
		gutter = 20;
	} else if (cols  == 3) {
		gutter = 20;
	} else if (cols  == 4) {
		gutter = 20;
	} else if (cols  == 5) {
		gutter = 20;
	} else {
		gutter = 20;
	}
	
	//WHEN INCLUDED, THESE MAKE THE GAP BETWEEN THE HEADING AND THE EDGE
	//I WOULD LIKE A BETTER SOLOUTION THAT A SPACER IMAGE
	
	//document.getElementById('dategap').width=gutter;
	document.getElementById('headgap').width=gutter;
//	document.getElementById('endlinegap').width=gutter;
	//document.getElementById('linegap').width=gutter;
	//document.getElementById('dategap').height=1;
	//document.getElementById('headgap').height=1;
	//document.getElementById('linegap').height=1;
	//document.getElementById('endlinegap').height=1;
}




function resize() {


//if story.length > 0 {
	debug(',12');
	//this lot deals with the hight and width of the screen, sets mins and maxes and scoots around a few errors.
	cw = document.body.clientWidth;
	//the 108 refured to here and two places later on is a hack for AOC, being the hight of the top header, excluded from the preArt as being in a div
	//as interfearing with its menus many divs.
	ch = document.body.clientHeight;
	if (cw > 1) {
		if (cw <750) {
			cw = 750;
		}
	}
	if (ch > 1) {
		if (ch < 301) {
			ch = 301;
		}
	}
	if(cw>749&&ch>300){
		cols = setBrowserSizeMaxes(cols);
		var rect = 'rect(top right bottom left)';
		var showPrev = false;
		var showNext = false;
		//get the bottom of the element immediately before the display section.
		var obj = document.getElementById('preArt');
		artTop = obj.offsetHeight ;
		availHeight = ch - artTop  -document.getElementById('paging').offsetHeight - document.getElementById('postArt').offsetHeight;
		linesPerCol = ((availHeight/lheight)>10)?(availHeight/lheight):10;
		linesPerCol = linesPerCol-linesPerCol%1;
		availWidth = cw - ((cols+1)*gutter);
		
		//Loop through the columns.
		for (var xx=0;xx<6;xx++) {
			obj = document.getElementById('d' + (xx));
			//Move the article up until we get to the line we want	
			obj.style.top = artTop-(prevLines*lheight)-(xx*linesPerCol*lheight);
			//Set the left of the article to the of the width of the page divided by the number of columns
			//obj.style.left = (xx*cw/cols);
			//Set the width of each div to be part the width of the page with a 5px buffer
			obj.style.left = (xx*availWidth/cols)+(xx*gutter)+(gutter);
			//Set the width of each div to be 1/3 the width of the page with a 5px buffer
			obj.style.width = (availWidth/cols);
			//Clip off all the parts of the div that aren't meant to be seen (The top and the bottom)
			rect = 'rect(' + ((xx*linesPerCol*lheight)+(prevLines*lheight)) + ' ' + Math.round(availWidth/cols) + ' ' + (((xx+1)*linesPerCol*lheight)+(prevLines*lheight)) + ' 0)';
			obj.style.clip = rect;
		}
		//images
		var ii;
		var jj;
		var ob;
		var curImage = 0;
		var divHeight = document.getElementById('d0').offsetHeight;
		var prevHeight;	//Height of all previous divs
		var visHeight;	//Height of this col
		var divTop;		//Distance between the div container and the top of the div (including the invisible bits)
		var totalCols = Math.ceil(divHeight/linesPerCol/lheight);	//Total columns for this article
		var imgheight;
		var imgcolwidth = (availWidth/cols);
		var imgwidth;
		var imgratio;
	
		// Remove all images
		for (ii = 1;ii <= placeholders; ii++) {
			updateAllPlaceHolders(ii,'','')
		}
	
		// Place images
		for (ii = 1;ii <= placeholders; ii++) {	//image placeholders
			for (jj = 0;jj <= totalCols; jj++) {	//cols
				imgheight = (images[curImage][2]-(images[curImage][2]%lheight)-6);
		//		imgheight = (images[curImage][2]);	
		//		alert(imgheight);
				imgwidth = (images[curImage][1]);
				imgratio= (imgcolwidth/imgwidth);
				imgheight=(imgheight*imgratio)
		//		alert(imgheight);
				ob = document.getElementById('art_img' + ii + 'col0');
					
				prevHeight = ((jj*linesPerCol*lheight)+(prevLines*lheight));
				visHeight = lheight * linesPerCol;
				divTop = ob.offsetTop;
				ob.className = ('');
				//document.getElementById('debug').innerHTML += '<br>Place ' + ii + ' col ' + (jj+1) + ' prevHeight=' + prevHeight + '\nvisHeight=' + visHeight + '\ndivTop=' + divTop;
				if ((divTop > prevHeight) && (visHeight - (divTop - prevHeight)) >= imgheight) {
					//document.getElementById('debug').innerHTML += ('<BR>img ' + ob.id + ' fits on col ' + (jj+1) + '\n' + divTop + '\n' + prevHeight + '\n' + visHeight + '\ndiff:' + (visHeight - (divTop - prevHeight)))
			//		ob.className = ('shadowbox')
			//		alert('CURRENT' + curImage);
			//		alert('II' + ii)
			//		alert('JJ' + jj)
					if (shadow > "") {
						updateAllPlaceHolders(ii,'<img src="' + images[curImage][0] + '" height="' + (images[curImage][2]-(images[curImage][2]%lheight)-12) + '" align="center" name="resize1" hspace="0" border="0">','shadowbox');
					} else {
			//			alert(availWidth/cols-gutter);
						updateAllPlaceHolders(ii,'<img src="' + images[curImage][0] + '" height="' + (imgheight-(imgheight%lheight)-6) + '" width="' + (availWidth/cols) + '" align="center" name="resize1" vspace="3" hspace="0" border="0">','');
			//		height="' + (images[curImage][2]-(images[curImage][2]%lheight)-12) + '"
					}
					curImage++;
					if (curImage >= images.length) ii = (placeholders + 1);
					jj = totalCols + 1;
				}
			}
		}
		
		
	//Make sure that the rel links are not split between cols
       updateEndBodies('');
       var o1 = document.getElementById('art_body_endcol0');
   	   var o2 = document.getElementById('art_full_endcol0');
   	   var c1 = Math.ceil(o1.offsetTop/linesPerCol/lheight);
   	   var c2 = Math.ceil(o2.offsetTop/linesPerCol/lheight);
   	   if (c1 != c2) updateEndBodies('<img src="webi/space.gif" height="' + ((c1*linesPerCol*lheight) - (o1.offsetTop)) + '" width="1">');
		var artBottom = artTop + (lheight*linesPerCol)
		//Show next\previous buttons
		//Is the first line of the article visible?
		showPrev=(prevLines>0)?true:false;
		//Is the last line of the article visible?
		showNext=(((prevLines*lheight)+(cols*lheight*linesPerCol)) < document.getElementById('d0').offsetHeight)?true:false;
		//Paging Stuff
		showNav(showPrev,showNext);
		obj = document.getElementById('paging');
		obj.style.top = artBottom;
		//obj.style.top = artBottom + 108;
		artBottom += obj.offsetHeight;
		//Move everything below the display section so it's butted up against the bottom of the display section.
		obj = document.getElementById('postArt');
		obj.style.top = artBottom;
			//obj.style.top = artBottom + 108;
	}
}


function updateAllPlaceHolders(img,src,style) {
debug(',13');
	for (var jj = 0;jj <= 5; jj++) {	//cols
		//document.getElementById('debug').innerHTML += '<BR>' + img + ' ' + jj;
		document.getElementById('art_img' + img + 'col' + jj).className = style;
		document.getElementById('art_img' + img + 'col' + jj).innerHTML = src
	}
}

function updateEndBodies(src) {
debug(',14');
        for (var jj = 0;jj <= 5; jj++) {        //cols
			//document.getElementById('debug').innerHTML += '<BR>' + jj;
            document.getElementById('art_body_endcol' + jj).innerHTML = src
        }
} 


// name - name of the cookie
// value - value of the cookie
// [expires] - expiration date of the cookie (defaults to end of current session)
// [path] - path for which the cookie is valid (defaults to path of calling document)
// [domain] - domain for which the cookie is valid (defaults to domain of calling document)
// [secure] - Boolean value indicating if the cookie transmission requires a secure transmission
// * an argument defaults when it is assigned null as a placeholder
// * a null placeholder is not required for trailing omitted arguments
function setCookie(name, value, expires, path, domain) {
	var curCookie = name + "=" + escape(value) +
		((expires) ? "; expires=" + expires.toGMTString() : "") +
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "");
	document.cookie = curCookie;
}

// name - name of the desired cookie
// def - default if there is no cookie
// * return string containing value of specified cookie or null if cookie does not exist
function getCookie(name,def) {
	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);
	var val;
	if (begin == -1) {
		begin = dc.indexOf(prefix);
		//alert(dc + '\n' + name + ' here\n' + begin);
		if (begin != 0) return def;
	} else
		begin += 2;
	var end = document.cookie.indexOf(";", begin);
	if (end == -1)
		end = dc.length;
	val = unescape(dc.substring(begin + prefix.length, end));
	//alert(name + ' = ' + val);
	if (val=='NaN') val = def;
	return val;
}

// name - name of the cookie
// [path] - path of the cookie (must be same as path used to create cookie)
// [domain] - domain of the cookie (must be same as domain used to create cookie)
// * path and domain default if assigned null or omitted if no explicit argument proceeds
function deleteCookie(name, path, domain) {
	if (getCookie(name)) {
		document.cookie = name + "=" + 
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		"; expires=Thu, 01-Jan-70 00:00:01 GMT";
	}
}



//Our friend here deals with sizing images up and down to fit.
//Issues incude: some eratic sizing when changing down numbers of columns
//Top/bottom overlap

function sizeIt(){
debug(',15');
//this sets a maximum size images will size too. idealy, this would be the inital size of the image, but that aint //working. The idea is
//that if the image is smaller than the collumn, it goes down. If bigger, it enlarges itself up to a maximum size.

	for (i=1;i<document.images.length;i++)
	{
	if (document.images[i].id.substr(0,6) == 'resize')
	{
		if (document.images[i].width > ((availWidth/cols)-gutter))
		{
			document.images[i].width = (availWidth/cols)-(gutter-1);
			//if (document.images[i].height > (linesPerCol*lheight)-14)
			//{
			//document.images[i].height = (linesPerCol*lheight)-20
			//}	
		} else {
			if (document.images[i].width < defaultWidth) 
			{

				//at the moment, this will jump to default, then size down when you stop resizing. Not really an issue, but not very pretty
				document.images[i].width = (availWidth/cols)-gutter;
				//document.images[i].height = defaultHeight;

				//} else {
				//this bit of code will make the images size up to the column width as well as down (stupid)
			//	document.images[i].width = (cw/cols)-gutter;
			}
		}
		}
	}
}

function showNav(showPrev,showNext) {
debug(',16');
	obj = document.getElementById('paging');
	if(showPrev||showNext) {
		obj.style.display='';
		document.getElementById('pagePrev').style.display=(showPrev)?'':'none';
		document.getElementById('pageNext').style.display=(showNext)?'':'none';
	} else {
	obj.style.display='none';
	}
}

function changefontsize(newsize) {
debug(',17');
	lheight += newsize;
	fheight += newsize;
	for (var ii = 0;ii<6;ii++) {
		document.getElementById('d' + ii).style.fontSize = fheight + 'px';
		document.getElementById('d' + ii).style.lineHeight = lheight + 'px';
	}
	resize();
	//document.f1.fontup.disabled=(fheight>=18)?true:false;
	//document.f1.fontdown.disabled=(fheight<=6)?true:false;
	setCookie('fheight', fheight,'','','');
	setCookie('lheight', lheight,'','','');
	document.getElementById('fontupimg').src=(fheight>=fontmax)?plusdisabled:plusactive;
	document.getElementById('fontdownimg').src=(fheight<=fontmin)?minusdisabled:minusactive;
	//document.f1.fontup.disabled=(fheight>=18)?true:false;
	//document.f1.fontdown.disabled=(fheight<=6)?true:false;
}

function debug(mess) {
//	alert(mess);
//	document.getElementById('debug').innerHTML += '<br>' + mess;
}

