/////////////////////////////////
// Scroll Div
/////////////////////////////////
var DEFAULT_WIDTH = 31; // Pixel width of default calendar item
var EVENT_WIDTH = 91;   // Pixel width of calendar item which has events
var IX_EVENT_COUNT = 7; // Index of the returned event count

///////////////
// Constructor for link object
///////////////
function link(id,position,cellWidth,day,month,year,textDisplay,image,eventCount){

    this.id = id;
    this.HTMLE = document.getElementById(id);
    this.position = position;
    this.cellWidth = cellWidth;
    this.day = day;
    this.month = month;
    this.year = year;
    this.textDisplay = textDisplay;
    this.image = image;
    this.eventCount = eventCount;
   
    ///////////////////
    // Update the link and move the html element
    ///////////////////
    function scroll(distance){
        var newPosition = this.position + distance;
        this.HTMLE.style.left = newPosition + 'px';
        this.position = newPosition;
    }
    
    this.scroll = scroll;
}

//////////////
//Constructor
//////////////
function linklist(){

    this.links = new Array();
    
    ////////////////////
    // Adds a new link to the linked list & creates the HTML element
    //////
    // Also checks to make sure that there is not already a link in the same position (AJAX problem)
    //////////////////////
    function addLink(id,position,cellWidth,weekend,day,month,year,textDisplay,image,eventCount,whichside){
    
        /*alert("id: " +id + "position: " + position + "cellwidth: " + cellWidth + "weekend: " + weekend + "day: " + day + 
        "month: " + month + "year: " + year + "textDisplay: " + textDisplay + "image: " + image + "eventCount: " + eventCount +
        "whichside: " + whichside); */
        
        var ok = 1;
        for (var l in this.links){
            if (this.links[l].position == position){
            ok = 0;
            }
        }
        
        if (ok == 1){
            var newHTML = document.createElement('div');
            newHTML.id = id;
            newHTML.style.left = position+'px';
            newHTML.style.width = cellWidth+'px';

            var html = '';
            ///////////////////////
            // Set style of the HTML element
            ///////////////////////
            if (eventCount == 0){
            
                if(weekend == 1){
                    newHTML.className = 'day_weekend';  
                }
                else{
                     newHTML.className = 'day_normal';   
                }
                            
                if (day==1){
                    html = getMonthName(month);
                }
                else{
                    html = '&nbsp;';
                }
                html += '<p>'+day+'</p>';
            
            }
            else{
                newHTML.className = 'day_large';
                
                if(weekend == 1){
                    newHTML.style.background = 'url(images/background_calendaritem_scroller_weekend.gif)';
                }
                else{
                     newHTML.style.background = 'url(images/background_calendaritem_scroller.gif)';   
                }
                
                
                
                if (day==1 ){
                    
                    var classString = "";
                    if(image != '')
                        classString = " class = \"high_month_name\" ";
                    
                    html = '<p ' + classString + '>'+day+' '+getMonthName(month)+'</p>';
                }
                else{
                    html = '<p class=scroller_redday>'+day+'</p>';    
                }
                
                if (image!='') {
                    
                    html += '<img class=scroller_image src='+image+'>';
                }
                
                html += '<p class=scroller_text>'+textDisplay+'</p>';
                
                if (eventCount > 1){
                    html += '<p class=scroller_text>more..</p>'; 
                }
            }
            var dateForUrl = getUrlDate(day, month, year);
            
            tooltipText = getTooltipText(textDisplay,day,month,year,eventCount);
            
            html = "<a class='day_link' href='Reminders.aspx?dt="+dateForUrl+"' >" + html +"</a>";
            //html = "<a class='day_link' href='Reminders.aspx?dt="+dateForUrl+"' onmouseover='javascript:ddrivetip(\""+tooltipText+"\");' onmouseout='javascript:hideddrivetip();'>" + html +"</a>";
            
            newHTML.innerHTML = html;
            
            scrollDiv.appendChild(newHTML);
            
            
            var newLink = new link(id,position,cellWidth,day,month,year,textDisplay,image,eventCount);
            
            if (whichside == 'right'){this.links.push(newLink);}
            else {this.links.unshift(newLink);}
        }
    }
   
    function getTooltipText(textDisplay, day, month, year, eventCount){
        var tooltipText = textDisplay;
        var date = getFormattedDate(day,month,year);
                    
        if (tooltipText != "") {
            tooltipText = tooltipText.replace("'", "");
        }
        if (tooltipText != ""){
            if (eventCount > 1){
                tooltipText += ' + '+(eventCount-1)+((eventCount==2) ? ' event' : 'events');
            }
            tooltipText += "<br/>"+date;
        }
        else{
            tooltipText = date;
        }
        return tooltipText;
    }
            
    function getUrlDate(day,month,year){
        return day+"/"+month+"/"+year;
    }
    function getFormattedDate(day,month,year){
        return day+' '+getMonthName(month)+' '+year;
    }
    function getMonthName(month){
        if (month == 1) {return 'Jan'};
        if (month == 2) {return 'Feb'};
        if (month == 3) {return 'Mar'};
        if (month == 4) {return 'Apr'};
        if (month == 5) {return 'May'};
        if (month == 6) {return 'Jun'};
        if (month == 7) {return 'Jul'};
        if (month == 8) {return 'Aug'};
        if (month == 9) {return 'Sep'};
        if (month == 10) {return 'Oct'};
        if (month == 11) {return 'Nov'};
        if (month == 12) {return 'Dec'};
    }
    
    /////////////////
    // Removes 10 links from the page and the linklist if one of the sides goes past the threshold.
    // Pop off the right, shift off the left
    /////////////////
    function removeLink(whichside){
        for (var count = 0;count < 10;count++){
            if (whichside == 'right'){
                var removedLink = this.links.shift();
                scrollDiv.removeChild(removedLink.HTMLE);
            }
            else {
                var removedLink = this.links.pop();
                scrollDiv.removeChild(removedLink.HTMLE);
            }
        }
    }
    
    //////////////////
    // Create new Links and call AJAX
    //////////////////
    function createLinks(direction,distance){
        if (direction > 0){
            var leftLink = this.findFarLeftLink();
            getNewLinks(leftLink,-1,0,distance);
        }
        else {
            var rightLink = this.findFarRightLink();
            getNewLinks(rightLink,1,1,distance);
        }
    }
    
    /////////////////
    // AJAX to get new links
    /////////////////
    function getNewLinks(link,whichway,skiplinks,distance){
    
        gettingAJAX = 1;
    
        var da = link.day;
        var mo = link.month;
        var ye = link.year;
        if (mo == 0){mo = 12;ye--;}
        
        var ajax_request = createXMLHttp();
        if (ajax_request){
            var url = 'ScrollerAjax.ashx?direction='+whichway+'&day='+da+'&month='+mo+'&year='+ye;
            if (lastAJAX != url){
                try {
                    ajax_request.onreadystatechange = function (){return ajaxComplete(ajax_request,link,whichway,skiplinks,distance);}
                    var bustcache = '&'+new Date().getTime();
                    ajax_request.open('GET',url+bustcache, true);
                    ajax_request.send(null);
                }
                catch (e){
                    alert("Error connecting to server:\n"+e.toString());
                }
                lastAJAX = url;
            }
        }
    }
    
    ///////////////
    // returns the right most link or an empty link object
    ///////////////
    function findFarRightLink(){
        if (this.links.length == 0){
            return new link(-1,0,0,startingDay,startingMonth,startingYear,'','','');
        }
        else {
            return this.links[this.links.length - 1];
        }
    }

    ////////////////
    // returns the left most link or an empty link object
    ////////////////
    function findFarLeftLink(){
        if (this.links.length == 0){
            return new link(0,0,0,startingDay,startingMonth,startingYear,'','','');
        }
        else {
            return this.links[0];
        }
    }
    
    function scroll(direction){
        
        var leftPos = this.findFarLeftLink().position;
        var rightPos = this.findFarRightLink().position;
        
        /////////////
        // Only move the scroller if there is big enough buffers.
        // This is where you would include a loading icon and stall it to allow AJAX to load.
        // At the moment it just waits as long as it takes.
        /////////////
        if ((leftPos < -50 && direction > 0) || (rightPos > 800 && direction < 0)){ 
            for (l in this.links){  this.links[l].scroll(direction);}
        }
        else {
            ///////////////////
            // Loading Ajax Code goes here
            //////////////////
        }
        
        /////////////
        // Get New Links AJAX to go here
        /////////////
        if (leftPos > leftTrigger && direction > 0){
            this.createLinks(direction, distNew);
        }
        else if (rightPos < rightTrigger && direction < 0){
            this.createLinks(direction, distNew);
        }
        
        //////////////
        // Clear Older links
        //////////////
        if (leftPos < leftLimit){
            this.removeLink('right');
        }
        else if (rightPos > rightLimit){
            this.removeLink('left');
        }
    }
    
    ////////////////////
    // Initialize the scroller from the left side of the screen.
    // LeftDist and rightDist are the distances to fill with links.
    // Also wipes all previous links before re-initializing
    ////////////////////
    function populateLinkList(leftDist,rightDist){

        while (this.links.length > 0){
            var removedLink = this.links.pop();
            scrollDiv.removeChild(removedLink.HTMLE);
        }
        
        var leftLink = this.findFarLeftLink();
        getNewLinks(leftLink,-1,0,leftDist);
        
        var rightLink = this.findFarRightLink();
        getNewLinks(rightLink,1,0,rightDist);
    }
    
    this.getNewLinks = getNewLinks;
    this.populateLinkList = populateLinkList;
    this.createLinks = createLinks;
    this.scroll = scroll;
    this.addLink = addLink;
    this.removeLink = removeLink;
    this.findFarLeftLink = findFarLeftLink;
    this.findFarRightLink = findFarRightLink;
}

////////////////////////
// Recursively call this function to animate the scroller.
////////////////////////
function scroll(direction){    
    
    stopScroll();
    linkList.scroll(direction);
    scrollTimeout = setTimeout("scroll("+direction+");",scrollInterval);
}

///////////////////////
// Self explanatory really
//////////////////////
function stopScroll(){
    try {
        clearTimeout(scrollTimeout);
    }
    catch(e)
    {}
}

/////////////////////////
// Function to cope with the reply from the AJAX call
/////////////////////////
// Takes the response text, cuts it up and creates new links from it.
// responseText = ~hour#day#month#year#text#image#eventCount~
///////////////////////////
function ajaxComplete(ajax_request,link,whichway,skiplinks,distance){
    var newDistance = 0;
    if (ajax_request.readyState == 4 && (ajax_request.status == 200 || window.location.href.indexOf("http")==-1)){
        var newLinks = ajax_request.responseText.split('~');

        if (whichway > 0){
        /////// RIGHT ///////
            for (l in newLinks){
                if (newDistance < distance){
                    if (l + 1 > skiplinks){
                        var theLink = newLinks[l].split('#');
                        
                        ////////////////////////////////
                        // Depending on the event count of the link set the size here
                        ///////////////////////////////
                        var dist = DEFAULT_WIDTH;
                        if (theLink[IX_EVENT_COUNT] > 0){ dist = EVENT_WIDTH; }
                        
                        newDistance = newDistance + dist;
                        var newID = link.id++;
                        var newPosition = link.position + link.cellWidth + newDistance - dist;
                        linkList.addLink(++newID,newPosition,dist,theLink[0],theLink[2],theLink[3],theLink[4],theLink[5],theLink[6],theLink[7],'right');
                    }
                }
            }
        }
        else {
        /////// LEFT ////////
            for (l in newLinks){
                if (newDistance < distance){
                    if (l > skiplinks){
                        var theLink = newLinks[l].split('#');
                        var dist = DEFAULT_WIDTH;
                        if (theLink[IX_EVENT_COUNT] > 0){ dist = EVENT_WIDTH; }
                        
                        newDistance = newDistance + dist;
                        var newID = --link.id;
                        var newPosition = link.position - newDistance;
                        linkList.addLink(newID,newPosition,dist,theLink[0],theLink[2],theLink[3],theLink[4],theLink[5],theLink[6],theLink[7],'left');
                    }
                }
            }
        }
    }
}

