var assocArrayLength = 0;

// This function will just run.
(function () {
    var theTable = document.getElementById("ticklist"),
        summaryTable = document.getElementById("totals"),
        yearTable = document.getElementById("years"),
        r,
        rte,
        c,
        i,
        links,
        cfg,
        count,
        limit,
        dt,
        offset = 0,
        yearData = [{year: 1981, count: 0},
                      {year: 1982, count: 0},
                      {year: 1983, count: 0},
                      {year: 1984, count: 0},
                      {year: 1985, count: 0},
                      {year: 1986, count: 0},
                      {year: 1987, count: 0},
                      {year: 1988, count: 0},
                      {year: 1989, count: 0},
                      {year: 1990, count: 0},
                      {year: 1991, count: 0},
                      {year: 1992, count: 0},
                      {year: 1993, count: 0},
                      {year: 1994, count: 0},
                      {year: 1995, count: 0},
                      {year: 1996, count: 0},
                      {year: 1997, count: 0},
                      {year: 1998, count: 0},
                      {year: 1999, count: 0},
                      {year: 2000, count: 0},
                      {year: 2001, count: 0},
                      {year: 2002, count: 0},
                      {year: 2003, count: 0},
                      {year: 2004, count: 0},
                      {year: 2005, count: 0},
                      {year: 2006, count: 0},
                      {year: 2007, count: 0},
                      {year: 2008, count: 0},
                      {year: 2009, count: 0},
                      {year: 2010, count: 0},
                      {year: 2011, count: 0}];

    cfg = ticklistOpts;
    count = cfg.routes.length;

    function UNIXday (D) {
        return Date.UTC(D[0], D[1] - 1, D[2]) / 86400000;
    }

    function DiffYD (S1, S2) {
        var D1 = ReadISO8601date(S1),
            D2 = ReadISO8601date(S2),
            DY;
        if (D1 < 0) {
            return "Date 1 bad";
        }
        if (D2 < 0) {
            return "Date 2 bad";
        }
        DY = D1[0] - D2[0];
        if (D1[1] < D2[1] || D1[1] === D2[1] && D1[2] < D2[2]) {
            DY--;
        }
        D2[0] += DY;
        return [DY, UNIXday(D1) - UNIXday(D2)];
    }

    function diffYearAndDate (D1, D2) {
        var dt, 
            over, 
            Y1;
        dt = new Date(+ D2);
        dt.setFullYear(Y1 = D1.getFullYear());
        over = dt > D1;
        dt = new Date(+ D2);
        dt.setFullYear(Y1 - over);
        return [dt.getFullYear() - D2.getFullYear(), Math.round((D1 - dt) / 86400000)];
    }

    function showTotalTime () {
        var elem = document.getElementById("totalTime"),
            dt,
            nt;

        if (elem) {
            if (cfg.endTime !== "") {
                dt = diffYearAndDate(new Date(endTime), new Date(cfg.startTime));
                nt = document.createTextNode("Took a total of " + dt[0] + " years, " + dt[1] + " days to complete the list.");
            } else  {
                dt = diffYearAndDate(new Date(), new Date(cfg.startTime));
                nt = document.createTextNode("So far, since " + cfg.startTime + ", I have taken " + dt[0] + " years, " + dt[1] + " days in trying to complete the list.");
            }
            elem.appendChild(nt);
        }
    }

    function loadMap (Eastings, Northings, ZoomScale) {
        var intX,
            intY,
            strURL;

        if (screen.width) {
            intX = (screen.width / 2) - 390;
            intY = (screen.height / 2) - 300; 
        } else {
            intX = 20;  
            intY = 20;  
        }
        strURL = "http:\/\/www.streetmap.co.uk\/streetmap.dll?G2M?X=" + Eastings  +"&Y="  + Northings + "&A=Y&Z=" + ZoomScale;
        ZoomWin = window.open(strURL, "MapWin", "height=600,width=780,screenX=" + intX + ",screenY=" + intY + ",top=" + intY + ",left=" + intX + ",scrollbars");
    }

    function showphotopopup (index) {
        var pf = document.getElementById('picture_frame'),
            cp = document.getElementById('crag_pic');

        if (pf === null) {
            alert("no picture frame");
            return;
        }
        pf.style.display = 'inline';
        pf.style.top = '150px';
        pf.style.zIndex = '200';

        cp.src = cfg.routes[index].image;
    }

    function hidephotopopup() {
      document.getElementById('picture_frame').style.display = 'none';
    }

    theTable.tBodies[0].deleteRow(0);
    summaryTable.tBodies[0].deleteRow(0);
    if (yearTable) {
        yearTable.tBodies[0].deleteRow(0);
    }
    if (cfg.C2) {
        offset = 1;
    }
  
    for (i = 0; i < count; i += 1) {
        rte = cfg.routes[i];

        r = theTable.tBodies[0].insertRow(-1);
	      c = r.insertCell(0);
        c.innerHTML = "<a name='" + i + "'><\/a>" + rte.chap;

        if (offset > 0) {
            c = r.insertCell(1);
            c.innerHTML = "<a name='" + i + "'><\/a>" + rte.C2;
        }
        c = r.insertCell(1 + offset);
        if (rte.east && rte.east.length > 0) {
            links = "<a href='info.php?b=" + ticklistOpts.book + "&n=" + i + "' title='Click for info on this route'>" + rte.route + "<\/a>";
            c.innerHTML = links;
            r.cells[1].className = "linkit";
        } else {
	          c.innerHTML = rte.route;
        }
	      c = r.insertCell(2 + offset);
	      c.innerHTML = rte.grade;
	      c = r.insertCell(3 + offset);
	      c.innerHTML = rte.date;
	      c = r.insertCell(4 + offset);
	      c.innerHTML = rte.notes;

        cfg.areaCount[rte.area].count += 1;
        if (rte.flags & 0x01) {
	          r.className = (i % 2) ? "doneRouteDark" : "doneRoute";
	          cfg.areaCount[rte.area].done += 1;
	      }
	      if (rte.flags & 0x02) {
	          r.className ="triedRoute";
	      }
      	if (rte.flags & 0x04) {
      	    r.className ="donesome";
      	}
        if (rte.flags & 0x20) {
      	    r.cells[4].className = "linkit";
      	}
      	// Now do a year by year summary
        if (rte.date) {
            ymd = rte.date.split("-");
            cYear = parseInt(ymd[0], 10);
            yearLength = yearData.length;
            
            for (y = 0; y < yearLength; y += 1) {
                if (cYear === yearData[y].year) {
                    yearData[y].count += 1;
                }
            }
        }
    }
  
    var limit =  cfg.areaCount.length - 1;
    for (i = 0; i < limit; ++i) {
        r = summaryTable.tBodies[0].insertRow(-1);
        c = r.insertCell(0);
        c.innerHTML = cfg.areaCount[i].name;
        c = r.insertCell(1);
        c.innerHTML = cfg.areaCount[i].count;
        c = r.insertCell(2);
        c.innerHTML = cfg.areaCount[i].done;
        c = r.insertCell(3);
        c.innerHTML = cfg.areaCount[i].count - cfg.areaCount[i].done;
        cfg.areaCount[limit].count += cfg.areaCount[i].count;
        cfg.areaCount[limit].done += cfg.areaCount[i].done;
        if ((cfg.areaCount[i].count - cfg.areaCount[i].done) === 0) {
            r.className = (i % 2) ? "doneRouteDark" : "doneRoute";
        }
    }
    r = summaryTable.tBodies[0].insertRow(-1);
    c = r.insertCell(0);
    c.innerHTML = cfg.areaCount[limit].name;
    c = r.insertCell(1);
    c.innerHTML = cfg.areaCount[limit].count;
    c = r.insertCell(2);
    c.innerHTML = cfg.areaCount[limit].done;
    c = r.insertCell(3);
    c.innerHTML = cfg.areaCount[limit].count - cfg.areaCount[limit].done;
    r.className="totals";

    if (yearTable) {
        for (i = 0; i < yearData.length; i += 1) {
            if (yearData[i].count > 0) {
                r = yearTable.tBodies[0].insertRow(-1);
                c = r.insertCell(0);
                c.innerHTML = yearData[i].year;
                c = r.insertCell(1);
                c.innerHTML = yearData[i].count;
            }
        }
    }
    // Creates and fills a two column table with a graph from the data from the array.
    (function () {
        var theTable = document.getElementById("spreadtable"),
            theTableBody = theTable.tBodies[0],
            count = 0,
            total = 0,
            limit,
            grLen = ticklistOpts.grades.length,
            count = new Array(grLen),
            personal = new Array(grLen),
            i,
            j,
            rte,
            multiplier = ticklistOpts.multiplier;

        limit = ticklistOpts.routes.length;

        for( i = 0; i < grLen; i += 1) {
            count[i] = 0;
            personal[i] = 0;
        }

        for (i = 0; i < limit; i += 1) {
            rte = ticklistOpts.routes[i];
            for(j = grLen - 1; j > -1; j -= 1) {
                if (rte.grade.indexOf(ticklistOpts.grades[j]) === 0) {
                    count[j] += 1;
                    if (rte.flags & 0x01) {
                        personal[j] += 1;
                    }
                    break;
                }
            }
        }

        // To get the page to validate there needs to be a row in the table body, however it is 
        // not needed by the viewer of the page, so delete it before adding the real content.
        theTableBody.deleteRow(0);
        for (i = 0; i < grLen; i += 1) {
            var newRow = theTableBody.insertRow(-1),
                innerText = (i % 2) ? "<b>" + ticklistOpts.grades[i] + "<\/b>" : ticklistOpts.grades[i] ;

            if(count[i] > 0) {
                innerText += " (" + personal[i] + "/" + count[i] + ")";
            }
            newRow.insertCell(0).innerHTML = innerText;
            if (count[i] > 0) {
                if(personal[i] > 0) {
                    newRow.insertCell(1).innerHTML = "<img src='..\/graphics\/green.gif' height='15' width='" + personal[i] * multiplier + "'><img src='..\/pictures\/red.gif' height='15' width='" + (count[i]-personal[i]) * multiplier + "' alt=''\/>";
                } else {
                    newRow.insertCell(1).innerHTML = "<img src='..\/pictures\/red.gif' height='15' width='" + count[i] * multiplier + "' alt=''\/>";
                }
            } else {
                newRow.insertCell(1).innerHTML = "<b>&nbsp;<\/b>";
            }
        }
    }());

    showTotalTime();
} (ticklistOpts));

// End of file
