var columnwidth;
var firstcoloffset;
var numcols;
var numrows;
var rowsheight;
var bodywidth;
var bodyheight;
var nonarticleheight;
var photosheight;
var prevpage;
var nextpage;
var cols;
var pagecount;
var currentpage;
var isIE;
var smallScreen = false;

//Significant chunks of the page
var masthead;
var navleft;
var maincontent;
var bodycopy;
var footer;
var copyparent;
var bottomnav;
var elempagecount;
var elemcurrentpage;
var byline;
var photoarray;
var photoparent;
var pagesizes;
var coloffsets;
var singleswitch;
var headline;

//settings
var prefnocolumns = false;

function initpage(){
    //useful variables
    photoarray = new Array();
    pagesizes = new Array();
    pagesizes[0] = 0;
    isIE = window.navigator.appVersion.indexOf("MSIE") != -1;
    isSafari = window.navigator.appVersion.indexOf("Safari") != -1;
    isMAC = window.navigator.appVersion.indexOf("Macintosh") != -1;

    //Significant chunks of the page
    masthead   = document.getElementById('masthead');
    navleft   = document.getElementById('nav-left');
    maincontent   = document.getElementById('main-content');
    bodycopy = document.getElementById('body-copy');
    copyparent = document.getElementById('copy-parent');
    footer = document.getElementById('footer');
    bottomnav = document.getElementById('bottomnav');
    prevpage = document.getElementById('prevpage');
    nextpage = document.getElementById('nextpage');
    elempagecount= document.getElementById('totalpages');
    elemcurrentpage= document.getElementById('currentpage');
    byline = document.getElementById('byline');
    singleswitch = document.getElementById('singleswitch');
    headline = document.getElementById('headline');
    //I wanted to do a simple getElementsByName. Can I? No, IE win's
    //implementation is broken, so I have to do this. IE sucks.
    //photoarray = document.getElementsByName('photo');
    photoparent = document.getElementById('photoparent');
    if(photoparent){
	var temp = photoparent.childNodes;
	for(var j = 0; j < temp.length; j++){
	    if(temp[j].nodeType == 1){
		photoarray[photoarray.length] = temp[j];
	    }
	}
    }

    //allow switching to columns from single
    singleswitch.style.visibility = 'visible';
    singleswitch.onclick = toColumns;

    //snag the line height
    if(isIE && isMAC) return; //Too many issues for it to be worthwhile
    if(document.defaultView && document.defaultView.getComputedStyle){
        lineheight = parseFloat(document.defaultView.getComputedStyle(bodycopy,'').getPropertyValue('line-height'));
    }else if(bodycopy.currentStyle){
        lineheight = parseInt(bodycopy.currentStyle.lineHeight);
    }else{
        return; //too much trouble to support safari and whatever else
    }

    readPrefs();

    setupPageDimensions();

    if(copyparent){
        columnwidth = 290; //px
        colcopywidth= 270; //px
        firstcoloffset = 10; //px
        initArticle();
    }

    setupSidebar();
    setupMasthead();
}

function initArticle(){
    if(prefnocolumns){
        return;
    }
    copyparent.style.visibility = 'hidden';
    currentpage = 1;

    byline.style.textAlign = "center";
    byline.style.paddingLeft = "0px";
    bottomnav.style.display = "none";


    setupHeadline()
    setupImages();
    setupColumns();

    //set the article parent's attributes
    copyparent.style.height = rowsheight+"px";
    copyparent.style.width  = numcols * columnwidth + firstcoloffset + "px";
    //copyparent.style.overflow = "visible"; //uncomment for debugging

    singleswitch.setAttribute("src","/images/single.png");
    singleswitch.setAttribute("title","Switch to single column");
    singleswitch.onclick = fromColumns;
    copyparent.style.visibility = 'visible';

    setupMasthead();
    document.onkeypress = keyPressHandler;
}

//get the screen width and height
//Props to http://www.howtocreate.co.uk/tutorials/index.php?tut=0&part=16
//for the detection code.
//Stupid IE.
function setupPageDimensions(){
    if( typeof( window.innerWidth ) == 'number' ) {
        //Non-IE
        bodywidth = window.innerWidth;
        bodyheight = window.innerHeight;
    } else {
        if( document.documentElement &&
                ( document.documentElement.clientWidth
                  || document.documentElement.clientHeight )
          ) {
            //IE 6+ in 'standards compliant mode'
            bodywidth = document.documentElement.clientWidth;
            bodyheight = document.documentElement.clientHeight;
        } else {
            if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
                //IE 4 compatible
                bodywidth = document.body.clientWidth;
                bodyheight = document.body.clientHeight;
            }
        }
    }
    // handle the left sidebar
    bodywidth = bodywidth - 25;

    //Enable/disable small screen mode
    if(bodyheight <= 600){
        smallScreen = true;
    }
}

function setupHeadline(){
    if(!isMAC){
    if (window.getComputedStyle){
        var height = window.getComputedStyle(headline,null).getPropertyValue("height");
        var lineheight = window.getComputedStyle(headline,null).getPropertyValue("font-size");
        headline.style.fontSize = lineheight;
        while (parseInt(height) > (2 * parseInt(lineheight))){
            headline.style.fontSize = parseInt(headline.style.fontSize) - 1 + "px";
            height = window.getComputedStyle(headline,null).getPropertyValue("height");
            lineheight = window.getComputedStyle(headline,null).getPropertyValue("font-size");
        }
    }else if(headline.currentStyle){
        var height = headline.offsetHeight;
        var lineheight = parseInt(headline.currentStyle.fontSize) * parseInt(document.body.currentStyle.fontSize);
        headline.style.fontSize = lineheight+"px";
        while (parseInt(height) > (2 * parseInt(lineheight))){
            headline.style.fontSize = parseInt(headline.style.fontSize) - 1 +"px";
            height = headline.offsetHeight;
            lineheight = parseInt(headline.style.fontSize);
        }
    }
    headline.style.whiteSpace = "nowrap";
    }
}

function setupSidebar(){
    //get the sidebar to work right in IE
    navleft.style.height = bodyheight+"px";

    //Enable/disable small screen mode
    if(smallScreen){
        document.getElementById("news-left").style.marginTop = "0px";
    }
}

function setupMasthead(){
    //get the masthead to be right in general
    if(columnwidth && numcols){
    maincontent.style.width = (numcols * columnwidth + firstcoloffset)+'px';
    masthead.style.width = "100%";
    }
    if(columnwidth && numcols && bodywidth > 880){
    masthead.style.width = (numcols * columnwidth + firstcoloffset)+'px';
    footer.style.width= (numcols * columnwidth + firstcoloffset)+'px';
    }else{
    masthead.style.width = "100%";
    }
}

function setupImages(){
    photosheight = 0;
    for(var i = 0; photo = photoarray[i]; i++){
        //Figure out the width, the .firstChilds get the actual IMG element
        var imgelem = photo.firstChild.firstChild;
        if(!smallScreen)
            imgelem.style.width = 'auto';
        photo.width = parseFloat(imgelem.offsetWidth);
        if(photo.width > columnwidth){
            photo.colcount = Math.ceil(photo.width/columnwidth)
        }else{
            photo.colcount = 1;
        }
        photo.style.width = (photo.colcount * columnwidth)+'px';
        //the height has to come after the width due to the text reflow
        //when changing width
        photo.height = parseFloat(photo.offsetHeight);
        var pad = lineheight - (photo.height % lineheight);
        photo.height += pad;
        photo.style.paddingBottom = pad + "px";
        photosheight = photosheight + photo.colcount * photo.height;

        //other style details
        photo.style.position = "absolute";
        photo.style.zIndex = "2";
        photo.style.marginLeft = '-5px';
        copyparent.appendChild(photo);
    }
}

function setupColumns(){
    //get number of cols to make a full screen
    numcols = Math.floor(bodywidth/columnwidth);

    //finding available height for article body
    if(masthead.offsetHeight){
        nonarticleheight = masthead.offsetHeight +
                           (maincontent.offsetHeight - copyparent.offsetHeight)
                           + footer.offsetHeight;
    }
    numrows = Math.floor((bodyheight-nonarticleheight)/lineheight);
    rowsheight = Math.ceil(numrows*lineheight);

    //this is a hack, if it's not in the footer falls off the screen for
    //certain browser sizes
    if(bodyheight-(rowsheight+nonarticleheight) < 7){
        numrows--;
        rowsheight = Math.ceil(numrows*lineheight);
    }

    //Column building process
    cols = new Array(numcols);
    cols[0] = bodycopy;

    //set styles applicable to all columns
    bodycopy.style.top = "0px";
    bodycopy.style.left = "0px";
    bodycopy.style.marginLeft = "0px";
    bodycopy.style.width = colcopywidth+"px";
    bodycopy.style.textAlign = "justify";
    //bodycopy.style.cssFloat = "none"; //note the css rule is float: none

    //kill the paragraph margins
    if (!document.styleSheets) return;
    var theRules = new Array();
    if(isMAC && isIE){
        var elements = document.getElementsByTagName('p');
        for(var i = 0; i < elements.length; i++) {
            elements.item(i).style["marginBottom"] = '0px';
        }
    }else{
        for(kk in document.styleSheets){
            theSheet = document.styleSheets[kk];
            if(theSheet.insertRule){
                theSheet.insertRule("P{margin-bottom: 0px;}", theSheet.cssRules.length -1);
            }else if(theSheet.addRule){
                theSheet.addRule("P","margin-bottom: 0px");
            }else continue;
        }
    }

    //actually clone and position the columns
    for(i=1; i < numcols; i++){
        //clone
        var newclone = bodycopy.cloneNode(true);
        copyparent.appendChild(newclone);
        newclone.setAttribute("id","col"+i);
        //position
        newclone.style.position = isIE && isMAC ? "absolute" : "relative";//stupid Mac
        newclone.style.top = -(newclone.offsetTop-bodycopy.offsetTop)+"px";
        newclone.style.left = ((columnwidth*i)+firstcoloffset+(isIE && isMAC ? 15 : 0))+"px";//stupid IEMac
        newclone.style.height = rowsheight+"px";
        cols[i] = newclone;
    }
    //get the first column off the edge of the screen (doesn't apply to other col)
    bodycopy.style.marginLeft = firstcoloffset+"px";
    bodycopy.style.position = 'relative';

    //handle the previous/next page business
    //cols[0].style.cursor = "e-resize"; //turned off unless needed
    cols[0].onclick = decrementPage;
    cols[0].onmouseover = prevOn;
    cols[0].onmouseout  = prevOff;
    prevpage.onclick    = decrementPage;
    prevpage.onmouseover= prevOn;
    prevpage.onmouseout = prevOff

    cols[numcols-1].onclick = incrementPage;
    cols[numcols-1].onmouseover = nextOn;
    cols[numcols-1].onmouseout = nextOff;
    nextpage.onclick = incrementPage;
    nextpage.onmouseover= nextOn;
    nextpage.onmouseout = nextOff

    setupPageCount();
    positionPageParts(1);
}


function setupPageCount(){
    pagecount = Math.floor((bodycopy.offsetHeight + photosheight) / (rowsheight * numcols))+1;
    if(pagecount > 1){
        nextpage.style.visibility = "visible";
        cols[numcols-1].style.cursor = isIE ? "hand" :"pointer";//"w-resize";
        elempagecount.innerHTML = pagecount;
    }
}

function positionPageParts(pagenumber){
    var numphotos = photoarray.length;
    var photocoverage;
    var photoheight = 0;
    var initialoffset = 0;
    if(!coloffsets){
        coloffsets = new Array();
        for(i=0; i < numcols; i++){
            coloffsets[i] = parseInt(cols[i].style.top)
        }
    }
    for(i=0; i < pagenumber; i++)
        initialoffset += pagesizes[i];
    photocoverage = positionPhoto(pagenumber);
    for(i=0; i < numcols; i++){
        photoheight += photocoverage[i] > rowsheight ? rowsheight : photocoverage[i];
        cols[i].style.top = (coloffsets[i] + photoheight - rowsheight*i - initialoffset)+"px"
    }
    pagesizes[pagenumber] = rowsheight * numcols - photoheight;
}

function positionPhoto(pagenumber){
    var currentphoto;
    var photocoverage = new Array(numcols);
    var numphotos = photoarray.length;
    for(var i = 0; i < numcols; i++)
        photocoverage[i] = 0;
    //hide all the photos, show the appropriate ones later
    for(var i = 0; i < numphotos; i++)
        photoarray[i].style.visibility = 'hidden';
    if(numphotos > pagecount && pagenumber == pagecount){//unusual case
        for(i=pagenumber-1; i < numphotos; i++){
            photocoverage = photoPositionHelper(photoarray[i],photocoverage);
        }
    }else{//common case
        currentphoto = photoarray[pagenumber-1];
        if(currentphoto){
            photocoverage = photoPositionHelper(currentphoto,photocoverage);
        }
    }
    return photocoverage;
}

function photoPositionHelper(currentphoto,photocoverage){
    var startcol;
    var isOffsetFromCopy = (currentphoto.offsetParent == copyparent);
    currentphoto.linesheight = Math.floor(currentphoto.height/lineheight)*lineheight;
    if(currentphoto.colcount > 1){
        startcol = numcols - currentphoto.colcount > 0 ? 1 :0;
    }else{
        startcol = numcols - (numcols > 3 ? 3 : 2);
    }
    while(photocoverage[startcol] != 0 && startcol < numcols){
        if(rowsheight > (photocoverage[startcol] + currentphoto.linesheight)){
            break; //both photos fit in startcol
        }else{
            if(startcol >= numcols){
                return photocoverage; //can't fit photo
            }else{
                startcol+= (numcols > (startcol+2) ? 2: 1);
            }
        }
    }
    startcol = startcol < 0 ? 0 : startcol;
    for(var i = 0; i < currentphoto.colcount; i++){
        photocoverage[startcol+i] += currentphoto.linesheight
    }
    var topoffset  = (isOffsetFromCopy ? 0 : copyparent.offsetTop);
    topoffset += (photocoverage[startcol] - currentphoto.linesheight)
    topoffset += 'px'
    var leftoffset = ((columnwidth*startcol) + firstcoloffset
                              + (isIE && isMAC ? 15 : 0));
    leftoffset += (isOffsetFromCopy ? 0 : navleft.offsetWidth);
    leftoffset += 'px'
    currentphoto.style.top = topoffset;
    currentphoto.style.left = leftoffset;
    currentphoto.style.visibility = 'visible';
    return photocoverage;
}

function prevNextHandler(isPrev,isOn){
    var target;
    var onoff= (isOn ? 1 : 0);

    if(isPrev){
        target = prevpage.childNodes[0];
    }else{
        target = nextpage.childNodes[0];
    }

    if(isOn){
        target.style.backgroundColor = "gold";
        target.style.borderColor = "#123980";
    }else{
        target.style.backgroundColor = "white";
        target.style.borderColor = "white";
    }
}

//Prev/Next Page MouseOver Event Handlers
function prevOn(e){
    prevNextHandler(true,true);
}

function prevOff(e){
    prevNextHandler(true,false);
}
function nextOn(e){
    prevNextHandler(false,true);
}

function nextOff(e){
    prevNextHandler(false,false);
}


//Actually increment and decrement the pages
function incrementPage(){
    if(currentpage != pagecount){
        currentpage = currentpage + 1;
        elemcurrentpage.innerHTML = currentpage;
        positionPageParts(currentpage);
    }
    if(currentpage == pagecount){
        nextpage.style.visibility = "hidden";
        cols[numcols - 1].style.cursor = "auto";
    }
    if(currentpage > 1){
        prevpage.style.visibility = "visible";
        cols[0].style.cursor = isIE ? "hand" :"pointer";//"e-resize";
    }
}

function decrementPage(){
    if(currentpage != 1){
        currentpage = currentpage - 1;
        elemcurrentpage.innerHTML = currentpage;
        positionPageParts(currentpage);
    }
    if(currentpage == 1){
        prevpage.style.visibility = "hidden";
        cols[0].style.cursor = "auto";
    }
    if(currentpage < pagecount){
        nextpage.style.visibility = "visible";
        cols[numcols - 1].style.cursor = isIE ? "hand" :"pointer";//"w-resize";
    }
}

function setPref(pref,value){
    var d = new Date();
    d.setTime(d.getTime() + (86400000 * 30 * 6)); //date in six months
    var cookie = pref + '=' + escape(value) + 
                 '; expires=' + d.toGMTString() + 
                 '; path=/';
    document.cookie = cookie;
}

function readPrefs(){
    var doccookie = document.cookie;
    var cookieExp = /^\s*(\w+)\s*=\s*(\d+|true|false)\s*$/
    var parts = doccookie.split(';');
    for(var i = 0; i < parts.length; i++){
        parts[i] = parts[i].replace(cookieExp, 'pref$1=$2;');
	try{
        eval(parts[i]);
	}catch(e){}//ignore errors
    }
}

function toColumns(){
    setPref('nocolumns','false');
    prefnocolumns = false;
    initArticle();
}

function fromColumns(){
    setPref('nocolumns','true');
    window.location.reload();
}

function keyPressHandler(e){
    if(!e && window.event) e = window.event;
    if(e.type == 'keypress' && (e.keyCode == '32' || (e.which && e.which == '32'))){
	if(e.shiftKey){
	    if(currentpage > 1)
		decrementPage();
	    else
		goToNodeHref(document.getElementById('prevartlink'));
	}else{
	    if(currentpage < pagecount)
		incrementPage();
	    else
		goToNodeHref(document.getElementById('nextartlink'));
	}
    }
}

function goToNodeHref(node){
    if(node)
	window.location = node.getAttribute('href');
}
