/*--------------------------------------------------------------------------
 *  calmcp.js, version 0.0.24
 *  doug sparling - 2007
 *--------------------------------------------------------------------------*/
var Cal = Class.create();
var version = '0.0.24';
var author = 'dsparling';

Cal.prototype = {
    initialize: function(options) {
        this.year = options.year;
        this.month = options.month;
        this.day = options.day;
        this.featureCode = options.featureCode;
        this.classCalendarTable = options.classCalendarTable;
        this.classCalendarDate = options.classCalendarDate;
        this.classCalendarDaysOfWeek = options.classCalendarDaysOfWeek;
        this.classCalendarDayNotValid = options.classCalendarDayNotValid;
        this.classCalendarDayValidCurrent = options.classCalendarDayValidCurrent;
        this.classCalendarDayValidNotCurrent = options.classCalendarDayValidNotCurrent;
        this.src = options.src || 'page'; // (image or page)
        if (this.month.length == 1) {
            this.month = '0' + this.month;
        }
        this.oldCurrentDay = this.day;
        this.oldCurrentMonth = this.month;
        this.oldCurrentYear = this.year;
        //this.showOptions();
        this.getCal();

			this.root = options.baseURI;
    },

    showOptions: function() {
        alert('Year: ' + this.year +
              '\nmonth: ' + this.month +
              '\nday: ' + this.day +
              '\nfeatureCode: ' + this.featureCode +
              '\nsrc: ' + this.src);
    },

    getCal: function (direction) {
        if(!document.getElementById) {
            return false;
        }
        if(!$('calDiv')) { 
            return false;
        }
        var params;
        var calDiv = $('calDiv');
        calDiv.update('Loading...');
        var calUrl = '/archive/' + this.featureCode + '/' + this.year + '/' + this.month; 
        if(direction) {
            calUrl += '/' + direction; // prev or next
        }

        var dateInfoUrl = '/featuredateinfo/'; 

        var myAjax = new Ajax.Request(
            calUrl,
            {
                 method: 'get',
                 //parameters: params,
                 onComplete: this.showResponse.bind(this),
                 onFailure: this.reportError
            }
        ); 
    },

    showResponse: function (originalRequest) {
        var data = eval('(' + originalRequest.responseText + ')');
        this.featureCode = data.calendar.feature_code;
        this.featureDirectory = data.calendar.feature_directory;
        this.year = data.calendar.year;
        this.month = data.calendar.month;
        this.monthName = data.calendar.month_name;
        var daysInMonthText = data.calendar.days_in_month;
        var dayOffsetText = data.calendar.day_offset;
        var prevFeatureYearText = data.calendar.prev_feature_year;
        var nextFeatureYearText = data.calendar.next_feature_year;
        this.dayNodes = data.calendar.valid_days;

        // Reset links
        this.prevYear = '';
        this.nextYear = '';
        this.prevMonth = '';
        this.nextMonth = '';
        this.prevFeatureYear = prevFeatureYearText;
        this.nextFeatureYear = nextFeatureYearText;

        // previous month
        try {
            this.prevYear      = data.calendar.previous.year;
            this.prevMonth     = data.calendar.previous.month;
        } catch(e1) {
            // no prev info
        }

        // next month
        try {
            this.nextYear      = data.calendar.next.year;
            this.nextMonth     = data.calendar.next.month;
        } catch(e2) {
            // no next info
        }
        
        this.makeCal(daysInMonthText,dayOffsetText);
    },

    reportError: function (resp) {
        alert('ERROR: ' + resp.responseText);
    },

    showResponseDateInfo: function (originalRequest) {
        var xmlDoc = originalRequest.responseXML;
        var previousDateNode = xmlDoc.getElementsByTagName('previous_date')[0];
        previousDateText = previousDateNode.childNodes[0].nodeValue;
        var nextDateNode = xmlDoc.getElementsByTagName('next_date')[0];
        nextDateText = nextDateNode.childNodes[0].nodeValue;
        var prevDate;
        var nextDate;

        if($('previousDateSpan'))  {
            if(previousDateText) {
//                prevDate =  '<a href="/feature/' + this.featureDirectory + '/?date=' + previousDateText + '">previous</a> |';
                prevDate =  '<a href="' + this.featureDirectory + '/?date=' + previousDateText + '">previous</a> |';
                $('previousDateSpan').update(prevDate);
            } else {
                prevDate =  'previous |';
            }
        }
        if($('nextDateSpan'))  {

            if(nextDateText) {
//                nextDate =  '<a href="/feature/' + this.featureDirectory + '/?date=' + nextDateText + '">next</a> |';
                nextDate =  '<a href="' + this.featureDirectory + '/?date=' + nextDateText + '">next</a> |';
                $('nextDateSpan').update(nextDate);
            } else {
                nextDate =  'next |';
            }
        }
    },

    updateImgDiv: function(el,dayNodeArray) {
        if(!document.getElementById) {
            return false;
        }
        if(!$('comicDiv')) {
            return false;
        }

        // el.toString will give absolute link
        // href will give what's exactly in href
        var href = el.getAttribute('href');

        var dayLink = el.getAttribute('id'); // ie,dayLink1, dayLink9, dayLink14

        // get the day (integer) from dayLink
        var dayInt = dayLink.match(/\d+$/);

        //** make selected day the valid current day **//
        //  1) update class
        var dayCellNew = 'dayCell' + dayInt;
        var dayCellNewCurrent = $(dayCellNew);
        dayCellNewCurrent.setAttribute('class',this.classCalendarDayValidCurrent);
        dayCellNewCurrent.setAttribute('className',this.classCalendarDayValidCurrent);

        // 2) remove link from new current day

        // id of anchor
        var dayLinkNew = 'dayLink' + dayInt;
        var dayLinkNewCurrent = $(dayLinkNew);

        // remove anchor from cell
        dayCellNewCurrent.removeChild(dayLinkNewCurrent);

        // create new text node (no anchor)
        var newDayText = document.createTextNode(dayInt); 
        // add the non-link day
        dayCellNewCurrent.appendChild(newDayText);

        // update object 
        var oldCurrentDay = this.oldCurrentDay;
        this.oldCurrentDay = dayInt; 
        this.oldCurrentMonth = this.month;
        this.oldCurrentYear = this.year;
 
        //** make old current day a non-current valid day **//

        // 1) update class
        var dayCellOld = 'dayCell' + oldCurrentDay;
        if( $(dayCellOld) ) {
            var dayCellNewNotCurrent = $(dayCellOld);
            dayCellNewNotCurrent.setAttribute('class',this.classCalendarDayValidNotCurrent);
            dayCellNewNotCurrent.setAttribute('className',this.classCalendarDayValidNotCurrent);

            // 2) add link to old current day
            var dayLinkOld = 'dayLink' + oldCurrentDay;

            var Anchor = document.createElement('a');
            // TODO
            var dayLink2; // TODO: name conflicts with dayLink in this sub
            var dayNodes = this.dayNodes;

            var Idx = dayNodeArray[oldCurrentDay];
            if(this.src == 'image') {
                dayLink2 = dayNodes[Idx].image_url;
            } else {
                dayLink2 = dayNodes[oldCurrentDay-1].page_url;
//                dayLink2 = 'feature/' + dayLink2;
//                dayLink2 = dayLink2;
            }
            Anchor.setAttribute('href',dayLink2);
            Anchor.setAttribute('id',dayLinkOld);
            var myCal = this;
            if(this.src == 'image') {
                Anchor.onclick = function () {
                    // update the image (this=link)
                    myCal.updateImgDiv(this,dayNodeArray); 
                    return false;
                };
            }
            var AnchorText = document.createTextNode(oldCurrentDay); 
            Anchor.appendChild(AnchorText);

            var childNode = dayCellNewNotCurrent.firstChild;
            dayCellNewNotCurrent.removeChild(childNode);
            dayCellNewNotCurrent.appendChild(Anchor);
        }

        // ad/2007/ad070803.gif
        // hrefVals[0]=ad hrefVals[1]=2007 hrefVals[2]=ad070803.gif
        var hrefVals = href.split('/');
        var fc = hrefVals[0];
        var date = hrefVals[2].match(/\d+/);
        if(hrefVals[1] >= 2000) {
            date = '20' + date;
        } else {
            date = '19' + date;
        }
        // feature_code (fc) also in this.featureCode
     
        //** Update the comic **//
        href = 'http://picayune.uclick.com/comics/' + href;
        $('comicDiv').update('<img src= ' + href + '>');

        //** Update the Postcard link **//
        if($('postcardSpan'))  {
            var postcard = '<a href="http://postcards.ucomics.com/send/?uc_comic=' + fc + '&uc_full_date=' + date + '&site_ref=mycomic">';
            postcard += '<img src="http://images.gocomics.com/images/mcp/mycollection_tools/postcard.gif" width="50" height="36" border="0"</a>';
            $('postcardSpan').update(postcard);
        }

        //** Update the Buy Print link **//
        if($('buyprintSpan'))  {
            var buyprint = '<a href="http://shop.ucomics.com/options/?site=mcp&uc_full_date=' + date + '&uc_comic=' + fc + '" target="_new">';
            buyprint += '<img src="http://images.gocomics.com/images/mcp/mycollection_tools/buy.gif" width="50" height="36" border="0"></a>';
            $('buyprintSpan').update(buyprint);
        }

        //** Update the Print link **//
        if($('printSpan'))  {
            var print = '<a href="/print/?date=' + date + '&feature=' + this.featureDirectory + '" target="_new">';
            print += '<img src="http://images.gocomics.com/images/mcp/mycollection_tools/print.gif" width="45" height="36" border="0"></a>';
            $('printSpan').update(print);
        }

        //** Update the Collect link **//
        if($('collectSpan'))  {
            var collect = '<a href="/admin/addcollection.tt?fc=' + fc + '&date=' + date + '">';
            collect += '<img src="http://images.gocomics.com/images/mcp/mycollection_tools/collect.gif" width="44" height="36" border="0"></a>';
            $('collectSpan').update(collect);
        }

        // Ajax call to update prev/next date
        //hrefVals[2] ga080807.gif
        if(hrefVals[2]) {
            var dateInfoUrl = '/featuredateinfo/' + hrefVals[2]; 

            var myAjax = new Ajax.Request(
                dateInfoUrl,
                {
                     method: 'get',
                     //parameters: params,
                     onComplete: this.showResponseDateInfo.bind(this),
                     onFailure: this.reportError
                }
            );
        }
    },

    makeCal: function (days_in_month,day_offset) {
        if(!document.createDocumentFragment) {
            return false;
        }
        if(!document.createElement) {
            return false;
        }
        if(!document.createTextNode) {
            return false;
        }

        // 7 1 2 3 4 5 6 - WebService
        // S M T W R F S 
        // 0 1 2 3 4 5 6 - Cal
        if(day_offset == 7) {
            day_offset = 0;
        }

        // Calendar header
        var fragment = document.createDocumentFragment();

        // prev month arrow (if needed) 
        var anchorPrev = document.createElement('a');
        var prevLink = '#';
        if(this.prevYear) {
            anchorPrev.setAttribute('href',prevLink);
            anchorPrev.onclick = function () {
                this.year = this.prevYear;
                this.month = this.prevMonth;
                this.getCal('prev');
                return false;
            }.bind(this);
            var leftArrowPrev = document.createElement('img');
            var leftArrow = 'http://images.gocomics.com/images/gc1/arrow_left.gif';
            leftArrowPrev.setAttribute('src',leftArrow);
            leftArrowPrev.setAttribute('border',0);
            anchorPrev.appendChild(leftArrowPrev);
            fragment.appendChild(anchorPrev);
            var spacerText = document.createTextNode(' ');
            fragment.appendChild(spacerText);
        }

        // Calendar Month
        var span = document.createElement('span');
        span.setAttribute('class',this.classCalendarDate);
        span.setAttribute('className',this.classCalendarDate);
        var txt1 = this.monthName;
        var spanText = document.createTextNode(txt1);
        span.appendChild(spanText);
        fragment.appendChild(span);

        // next month arrow (if needed)
        spacerText = document.createTextNode(' ');
        fragment.appendChild(spacerText);
        var anchorNext = document.createElement('a');
        var nextLink = '#'; 
        if(this.nextYear > 0) {
            anchorNext.setAttribute('href',nextLink);
            anchorNext.onclick = function () {
                this.year = this.nextYear;
                this.month = this.nextMonth;
                this.getCal('next');
                return false;
            }.bind(this);
            var rightArrowNext = document.createElement('img');
            var rightArrow = 'http://images.gocomics.com/images/gc1/arrow_right.gif';
            rightArrowNext.setAttribute('src',rightArrow);
            rightArrowNext.setAttribute('border',0);
            anchorNext.appendChild(rightArrowNext);
            fragment.appendChild(anchorNext);
        }

        // Equivalent to &amp;#0160; or &amp;nbsp;
        spacerText = document.createTextNode('\u00a0\u00a0');
        fragment.appendChild(spacerText);

        // prev year arrow (if needed) 
        var anchorPrevYear = document.createElement('a');
        var prevLink = '#';
        if(this.prevFeatureYear) {
            anchorPrevYear.setAttribute('href',prevLink);
            anchorPrevYear.onclick = function () {
                this.year = this.prevFeatureYear;
                this.getCal('prev');
                return false;
            }.bind(this);
            var leftArrowPrevYear = document.createElement('img');
            var leftArrowYear = 'http://images.gocomics.com/images/gc1/arrow_left.gif';
            leftArrowPrevYear.setAttribute('src',leftArrowYear);
            leftArrowPrevYear.setAttribute('border',0);
            anchorPrevYear.appendChild(leftArrowPrevYear);
            fragment.appendChild(anchorPrevYear);
            var spacerText = document.createTextNode(' ');
            fragment.appendChild(spacerText);
        }

        // Calendar Year
        var span = document.createElement('span');
        span.setAttribute('class',this.classCalendarDate);
        span.setAttribute('className',this.classCalendarDate);
        var txt1 = this.year;
        var spanText = document.createTextNode(txt1);
        span.appendChild(spanText);
        fragment.appendChild(span);

        // next year arrow (if needed)
        spacerText = document.createTextNode(' ');
        fragment.appendChild(spacerText);
        var anchorNext = document.createElement('a');
        var nextLink = '#'; 
        if(this.nextFeatureYear > 0) {
            anchorNext.setAttribute('href',nextLink);
            anchorNext.onclick = function () {
                this.year = this.nextFeatureYear;
                this.getCal('next');
                return false;
            }.bind(this);
            var rightArrowNext = document.createElement('img');
            var rightArrow = 'http://images.gocomics.com/images/gc1/arrow_right.gif';
            rightArrowNext.setAttribute('src',rightArrow);
            rightArrowNext.setAttribute('border',0);
            anchorNext.appendChild(rightArrowNext);
            fragment.appendChild(anchorNext);
        }


        // table
        var table = document.createElement('table');
        table.setAttribute('class',this.classCalendarTable);
        table.setAttribute('className',this.classCalendarTable);

        // body
        var tBody = document.createElement('tbody');
        table.appendChild(tBody);

        // row 2 (Days of Week)
        //var daysOfWeek = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'];
        var TR1 = document.createElement('tr');
        tBody.appendChild(TR1);
        $w('Su Mo Tu We Th Fr Sa').each(function(dayOfWeek) {
            var TD1 = document.createElement('td'); 
            TD1.setAttribute('align','center');
            TD1.setAttribute('class',this.classCalendarDaysOfWeek);
            TD1.setAttribute('className',this.classCalendarDaysOfWeek);
            var TDText1 = document.createTextNode(dayOfWeek);
            TD1.appendChild(TDText1);
            TR1.appendChild(TD1);
        }.bind(this));

        // row 2
        var TR2 = document.createElement('tr');
        tBody.appendChild(TR2);
        // If first day of month is not 'Su', pad with blank cells
        if(day_offset > 0) {
            for(var i = 0; i < day_offset; i++) {
                var TD2 = document.createElement('td');
                var TDText2 = document.createTextNode('');
                TD2.appendChild(TDText2);
                TR2.appendChild(TD2);
            }
        }
  
        var dayNodes = this.dayNodes;
        // Keep track of days in xml file
        var dayNodeArray = new Array();
        for(var dayNode = 0; dayNode < dayNodes.length; dayNode++) {
            var dayNum;
            try {
                dayNum = dayNodes[dayNode].num;
                dayNodeArray[dayNum] = dayNode;
            }  catch(e) {
            }
        }

        var day = 1;
        for(var idx = 1; idx <= days_in_month; idx++) {

            // Check if this day exists in xml
            var dayNodeIdx = dayNodeArray[idx];
            var dayExists = 0;
            if(typeof(dayNodeIdx) == 'number') {
                dayExists = 1;
            } else {
               dayExists = 0;
            }

            // If day (attribute num) exists in xml, then set link
            var dayLink = 0;
            if(dayExists) {
                if(this.src == 'image') {
                    dayLink = dayNodes[dayNodeIdx].image_url;
                } else {
                    dayLink = dayNodes[dayNodeIdx].page_url;
//                    dayLink = 'feature/' + dayLink;
							dayLink = this.root + '/' + dayLink;
                }
            }

            if(dayLink) {
                // valid day
                var TD3 = document.createElement('td');
                TD3.setAttribute('align','center');
                TD3.setAttribute('id','dayCell'+day);
                //if(this.day == day) {
                if(this.oldCurrentDay == day &&
                   this.oldCurrentMonth == this.month &&
                   this.oldCurrentYear == this.year) {
                    // valid date: current day - black, no link
                    TD3.setAttribute('class',this.classCalendarDayValidCurrent);
                    TD3.setAttribute('className',this.classCalendarDayValidCurrent);
                    var noAnchorText = document.createTextNode(day); 
                    TD3.appendChild(noAnchorText);
                } else {
                    // valid date: not current day, link
                    TD3.setAttribute('class',this.classCalendarDayValidNotCurrent);
                    TD3.setAttribute('className',this.classCalendarDayValidNotCurrent);
                    var Anchor = document.createElement('a');
                    Anchor.setAttribute('href',dayLink);
                    Anchor.setAttribute('id','dayLink'+day);
                    var myCal = this;

                    if(this.src == 'image') {
                        Anchor.onclick = function () {
                            // update the image (this=link)
                            myCal.updateImgDiv(this,dayNodeArray); 
                            return false;
                        };
                    }
                    var AnchorText = document.createTextNode(day); 
                    Anchor.appendChild(AnchorText);
                    TD3.appendChild(Anchor);
                }
                TR2.appendChild(TD3);
            } else {
                // not a valid day
                var TD4 = document.createElement('td');
                TD4.setAttribute('align','center'); 
                TD4.setAttribute('class',this.classCalendarDayNotValid);
                TD4.setAttribute('className',this.classCalendarDayNotValid);
                TDText4 = document.createTextNode(day);
                TD4.appendChild(TDText4);
                TR2.appendChild(TD4);
            }

            day_offset++;

            // End row if this is seventh cell
            if(day_offset == 7) {
                day_offset = 0;
                // Start new row if more days left
                if(day < days_in_month) {
                    TR2 = document.createElement('tr');
                    tBody.appendChild(TR2);
                }
            }
            day++;
        }
        
        // If there are still empty days left, add them
        while(day <= days_in_month) {
            var TD5 = document.createElement('td'); 
            TD5.setAttribute('align','center'); 
            TD5.setAttribute('class',this.classCalendarDayNotValid);
            TD5.setAttribute('className',this.classCalendarDayNotValid);
            TDText5 = document.createTextNode(day); 
            TD5.appendChild(TDText5);
            TR2.appendChild(TD5);

            day_offset++;
            // End row if this is seventh cell
            if(day_offset == 7) {
                day_offset = 0;
                // Start new row if more days left
                if(day < days_in_month) {
                    TR2 = document.createElement('tr');
                    tBody.appendChild(TR2);
                }
            }
            day++;
        }

        // Finish calendar
        // If last day not a Saturday, then pad with blank cells at end of row
        if(day_offset > 0) {
            for(var i = day_offset; i < 7; i++) {
                var TD6 = document.createElement('td');
                TDText6 = document.createTextNode('');
                TD6.appendChild(TDText6);
                TR2.appendChild(TD6);
            }   
        }       
                
        // clear Loading message
        if(!$('calDiv')) {
            return false;
        }
        var calDiv = $('calDiv');
        var html = calDiv.firstChild;
        calDiv.removeChild(html);

        // Add calendar table
        fragment.appendChild(table);
        calDiv.appendChild(fragment);
    }

}; // end Cal
