jQuery.noConflict();
/// <reference path="jquery-1.2.6-vsdoc.js" />
jQuery.fn.fadeIn = function(speed, callback) { 
    return this.animate({opacity: 'show'}, speed, function() { 
        if (jQuery.browser.msie)  
            this.style.removeAttribute('filter');  
        if (jQuery.isFunction(callback)) 
            callback();  
    }); 
}; 
 
jQuery.fn.fadeOut = function(speed, callback) { 
    return this.animate({opacity: 'hide'}, speed, function() { 
        if (jQuery.browser.msie)  
            this.style.removeAttribute('filter');  
        if (jQuery.isFunction(callback)) 
            callback();  
    }); 
};

var scheduleXML;
var activeWeek;
var tempDate = new Date();
var currentDate = new Date();
var startDate = new Date();
var endDate = new Date();
var loaded = false;


//Orientation
//Developer specified values
var schedule_width = 0; //0 for 100%
var rowsPerView = 7; // Number of rows to show up in a view
var rowHeight = 25; // Height of each row
var topBorder = 0; // 0 if no border given in css
var bottomBorder = 0; // 0 if no border given in css
var scrollSpeed = 800; // Speed of animation when the schedule is scrolling
var webservicePath = "/ScheduleService.asmx/GetSchedule";//"/BIMWeekXML/?Week="
var clubIdenticalShows = false;
var preloadCurrentWeekSchedule = false;

//Computed values
var totalBorder = (topBorder + bottomBorder) * rowsPerView;
var scheduleScroll_FF = (rowHeight * rowsPerView) + totalBorder;
var scheduleScroll_IE = (rowHeight * rowsPerView) + totalBorder;
var columnWidth = 60;

//Array for time
var arrTime = new Array('12:00','12:30','01:00','01:30','02:00','02:30','03:00','03:30','04:00','04:30','05:00','05:30','06:00','06:30','07:00','07:30','08:00','08:30','09:00','09:30','10:00','10:30','11:00','11:30');

//Array for Days
var arrDays = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');

jQuery(function() {
    var widthToRender;
    var location;
    
    if (schedule_width <= 0) {
        widthToRender = "100%";
    } else {
        widthToRender = schedule_width + "px";
    }
    
    jQuery('#schedule').width(widthToRender);
    
    jQuery("#dropdown-schedule-container").show();
    widthToRender = jQuery('#schedule').width();
    jQuery("#dropdown-schedule-container").hide();
   
    //set height & width of container
    if (jQuery.browser.msie) {
        jQuery('#schedule-inner-body').height(scheduleScroll_IE);
        jQuery('.schedule-inner-body-container').height(jQuery('#schedule-inner-body').height());
        jQuery('#customschedule-body').height(scheduleScroll_IE);
    } else {
        jQuery('#schedule-inner-body').height(scheduleScroll_FF);
        jQuery('.schedule-inner-body-container').height(jQuery('#schedule-inner-body').height());
        jQuery('#customschedule-body').height(scheduleScroll_FF);
    }
    
    //position spinner
    location = jQuery('#customschedule-body').position();
    jQuery('#loading-zone')
        .css({
            'width' : jQuery('#schedule-inner-body').width() + 'px',
            'margin' : '0 auto'
        });
        
    jQuery("#schedule-content").width(widthToRender);
    jQuery(".scheduleweekview-body").width(widthToRender);
    
    columnWidth = (widthToRender - 60)/7;
    

    jQuery('.scheduleweekview-body-time')
        .width(60)
        .height(rowHeight);
    

    jQuery('.scheduleweekview-body-day')
        .width(columnWidth)
        .height(rowHeight);    
    
    jQuery('#schedule').hide();
    
    jQuery('#loading-zone')
        .hide()  // hide it initially
        .ajaxStart(function() {
            positionSpinner();
            jQuery(this).show();
        })
        .ajaxStop(function() {            
            jQuery(this).hide();
        });
        
    jQuery('#menu54').one('mouseover',function(){
        jQuery("#dropdown-schedule-container").show();
        jQuery('#schedule').slideDown('slow',function(){
            requestSchedule(currentDate.getWeek());    
        });
    });
        
    jQuery('#schedule-close').click(function(){
        jQuery('#schedule').slideUp('slow',function(){
            buildScheduleFrame();
            
            jQuery('#menu54').one('mouseover',function(){
                jQuery('#schedule').slideDown('slow',function(){
                    requestSchedule(currentDate.getWeek());    
                });
            });
        });
    });
    
    jQuery('#schedule-timezoneselector').change(function() {
        requestSchedule(activeWeek);
    });
    //Add scroll    
    jQuery("#customschedule-down")
        .attr('title','Scroll down')
        .click(function() {
        scrollDown();
    });

    jQuery("#customschedule-up")
        .attr('title','Scroll up')
        .click(function() {
        scrollUp();
    });

    //Add click events for previous and next week
    jQuery(".scheduleweekview-head-prev")
        .attr('title','Previous week')
        .click(function() {
        getSchedule(false);
    });
    jQuery(".scheduleweekview-head-next")
        .attr('title','Next week')
        .click(function() {
        getSchedule(true);
    });
    //requestSchedule(currentDate.getWeek());
    if(preloadCurrentWeekSchedule){
        cacheCurrentWeek(currentDate.getWeek());
    }
});

function positionSpinner(){
    jQuery('#loading-zone')
        .css({
            'width' : jQuery('#schedule-inner-body').width() + 'px',                         
            'margin' : '0 auto'
        });
}

function getSchedule(nextWeek){
    if(nextWeek){
        currentDate.setDate(currentDate.getDate() + 7);
    }else{
        currentDate.setDate(currentDate.getDate() - 7);
    }    
    requestSchedule(currentDate.getWeek());
}

function requestSchedule(weekno){
    var parameters = "WeekNo=" + weekno;
    buildScheduleFrame();
    if(activeWeek != weekno){
    jQuery.ajax({
            type: "POST",
            url: webservicePath,
            data: parameters,
            dataType: "xml",
            success: function(xml) {
                loaded = true;
                scheduleXML = xml;
                displaySchedule(scheduleXML);
            },
            error: function(e){
                //TODO: Handle error
            }
        });
    }else{
        displaySchedule(scheduleXML);
    }
    activeWeek = weekno;
}
function cacheCurrentWeek(weekno){
    var parameters = "WeekNo=" + weekno;
    jQuery.ajax({
        type: "POST",
        url: webservicePath,
        data: parameters,
        dataType: "xml",
        success: function(xml) {
            loaded = true;
            scheduleXML = xml;            
        },
        error: function(e){
            //TODO: Handle error
        }
    });
    activeWeek = weekno;
}
/*
function requestSchedule(weekno) {
    var parameters = "WeekNo=" + weekno;
    buildScheduleFrame();
    if(activeWeek != weekno){        
        jQuery.ajax({
            type: "GET",
            url: "rssschedule.xml",
            dataType: "xml",
            success: function(xml) {
                loaded = true;
                displaySchedule(xml);
            }
        });
    }else{
        displaySchedule(scheduleXML);
    }
    activeWeek = weekno;
}
*/

function getTime(isoDateTime){
    var newDate = getDateTime(isoDateTime);
    return newDate.toLocaleString()
}

function scrollDown(){
    if(jQuery.browser.msie){
        jQuery("#schedule-inner-body").scrollTo({top:'+=' + scheduleScroll_IE + 'px'},scrollSpeed);
    }else{
        jQuery("#customschedule-body").scrollTo({top:'+=' + scheduleScroll_FF + 'px'},scrollSpeed);
    }
}
function scrollUp(){
    if(jQuery.browser.msie){
        jQuery("#schedule-inner-body").scrollTo({top:'-=' + scheduleScroll_IE + 'px'},scrollSpeed);
    }else{
        jQuery("#customschedule-body").scrollTo({top:'-=' + scheduleScroll_FF + 'px'},scrollSpeed);
    }
}



function buildScheduleFrame(){    
    //Clear Schedule
    jQuery('#customschedule-body').empty();
    
    //Add rows for AM
    var rowId = 0;   
    for(var counter = 0; counter < arrTime.length; counter++){
        //Draw row skeleton
        jQuery('<tr>')
            .attr('id','time_' + rowId)
            .height(rowHeight)
            .html('')            
            .appendTo('#customschedule-body');
        rowId++;
    }
    
    //Add rows for PM    
    for(var counter = 0; counter < arrTime.length; counter++){
        jQuery('<tr>')
            .attr('id','time_' + rowId)
            .height(rowHeight)
            .html('')            
            .appendTo('#customschedule-body');        
        rowId++;
    }
    
    //Add class
    jQuery('#customschedule-body tr:even').addClass('row0');
    jQuery('#customschedule-body tr:odd').addClass('row1');
    
    renderScheduleBody();
}

function renderScheduleBody(){    
    //Clear all rows
    jQuery('#customschedule-body tr').empty();
    
    //Add tds from Sunday thru Saturday for each row
    jQuery('#customschedule-body tr').each(function(index){
        var arrayIndex = index;
        var currentMedian = "AM";
        if(arrayIndex > 23){
            arrayIndex -= 24;
            currentMedian = "PM";
        }
        jQuery('<td>')
            .width(60)
            .height(rowHeight)
            .css('overflow','hidden')
            .addClass('scheduleweekview-body-time')
            .addClass('scheduleweekview-body-title')
            .html(arrTime[arrayIndex] + ' ' + currentMedian)
            .appendTo(this);
        
        for(var days = 1; days <= 7; days++){
            var td = jQuery('<td>')
                .attr('id','time_' + index + '_' + days)
                .width(columnWidth)
                .height(rowHeight)
                .css('overflow','hidden')
                .addClass('scheduleweekview-body-day')
                .addClass('scheduleweekview-body-title')
                .html('')
                .appendTo(this);
                
            if(days == 7){
                jQuery(td).addClass('scheduleweekview-body-day6');
            }   
        }
    });
}

function displaySchedule(xml) {    
    renderScheduleBody();    
    
    //Here we traverse through the XML and fill data in the appropriate td    
    var firstDay = getDateTime(jQuery(xml).find('Table')
                            .eq(0)
                            .find('ShowDateTime')
                            .text());
    var lastDay = new Date(firstDay);
    lastDay.setDate(firstDay.getDate() + 7);
    
    
    startDate= new Date(firstDay);
    endDate = new Date(lastDay);
    endDate.setDate(endDate.getDate() - 1);
    jQuery('#schedule-date').html("Week of " + formatDateForDisplay(startDate) + " to " + formatDateForDisplay(endDate));
    
    //Traverse through the filtered xml and fill the appropriate td
    jQuery(xml).find('Table')
        .filter(function(){
            var tempCurrentDate = getDateTime(jQuery(this).find('ShowDateTime').text());
            if(tempCurrentDate >= firstDay && tempCurrentDate <= lastDay){
                return true;
            }else{
                return false;
            }
        })
        .each(function(index){
            fillShowTimings(jQuery(this), false);
        });
    
    var arrayEmpty = "";
    var matchCount = 0;
    
    //Adjust rowspans according to show timings already rendered.
    jQuery('#customschedule-body td').each(function(index){
                                var currentId = jQuery(this).attr('id');
                                if(currentId != '' && jQuery(this).text() == ''){
                                    matchCount++;
                                    arrayEmpty += " " + currentId;      
                                    fillWithPreviousProgram(jQuery(this));
                                }
                            });
    if(clubIdenticalShows){
        for(var column = 1; column <= 7; column++){
            var prefix = "time";
            for(var rowIndex = 0; rowIndex <= 47; rowIndex++){
                var currentElemId = "time_" + rowIndex + "_" + column
                var elementValue = jQuery("#" + currentElemId).html();
            }
        }
        
        var elements = [];
        var rowspans = [];
        
        //Logic to traverse through the schedule and club programs which show up in tandom
        for(var j=1; j<=7; j++){
            var prevText = "";
            var currentText = "";
            var repeatCounter = 0;
            var elementId = "";
            
            var firstElement = true;
            
            for(var i=0; i <= 47; i++){
                var currentElementId = "time_" + i + "_" + j;
                currentText = jQuery("#" + currentElementId).html();
                
                if(firstElement){
                    elementId = currentElementId;
                    repeatCounter = 1;
                }else{
                    if(currentText == prevText){
                        repeatCounter++;
                        jQuery("#" + currentElementId).remove();
                    }else{
                        //Push previous details to array
                        elements.push(elementId);
                        rowspans.push(repeatCounter);
                        
                        elementId = currentElementId;
                        repeatCounter = 1;
                    }    
                }
                
                prevText = currentText;
                
                firstElement = false;
            }
        }
        
        var arrElements = [];
        var arrRowSpans = [];
        
        jQuery.each(rowspans, function(i){
            if(this > 1){            
                arrElements.push(elements[i]);
                arrRowSpans.push(rowspans[i]);
            }
        });
        
        jQuery(arrElements).each(function(i){
            jQuery("#" + this).attr("rowSpan", arrRowSpans[i]);
        });
    }
}

function fillWithPreviousProgram(elem){
    var currentElementId;
    currentElementId = jQuery(elem).attr('id');
    
    //Get prefix, row index and column index
    var arrElement = currentElementId.split('_');
    var prefix = arrElement[0];
    var rowIndex = arrElement[1];    
    var colIndex = arrElement[2];
    
    //Get the previous element for which we need to increase the row span
    var previousElement = getPreviousElement(prefix, rowIndex, colIndex);
    
    //If previous program is found, get the program name for the same and fill the current element
    if(jQuery(previousElement)){
        jQuery("#" + currentElementId).html(jQuery(previousElement).html());
    }
}

function getPreviousElement(prefix, rowIndex, colIndex){    
    var previousRowIndex = rowIndex-1    
    var newElementId = prefix + '_' + previousRowIndex + '_' + colIndex
    if(previousRowIndex < 0){
        return null;
    }else{
        return jQuery('#' + newElementId);
    }
}

function fillShowTimings(currentTable, isDebug){
    var date;
    var currentDate;
    var stringDate;
    var day;
    var currentHour;
    var currentMinute;
    var rowIndex;
    var colIndex;
    
    //Get date from XML
    date = jQuery(currentTable)
                    .find('ShowDateTime')
                    .text();

    //Convert data to dateTime
    currentDate = getDateTime(date);    
    
    //Get current hour and minute
    var currentHour = "";
    currentHour = currentDate.getHours();
    if(currentHour.length == 1){currentHour = '0' + '' + currentHour;}
    var currentMinute = "";
    currentMinute = currentDate.getMinutes();
    if(currentMinute.length == 1){currentMinute = '0' + '' + currentMinute;}
    
    var tempHour;    
    if(currentHour == 0){
        tempHour = 12;
    }else if(currentHour > 12){
        tempHour = currentHour - 12;
    }else{
        tempHour = currentHour;
    }
    
    var tempCurrentHour = tempHour + "";
    if(tempCurrentHour.length == 1){tempCurrentHour = '0' + '' + tempCurrentHour;}
    var tempCurrentMinute = currentMinute + "";
    if(tempCurrentMinute.length == 1){tempCurrentMinute = '0' + '' + tempCurrentMinute;}
    
    //Convert date to locale string
    stringDate = getTime(date);
    
    //Get name of the day
    day = stringDate.split(',')[0];
    
    //Get index of day array
    colIndex = jQuery.inArray(day, arrDays);
    colIndex++;
    
    //Get time based on the time string    
    rowIndex = jQuery.inArray(tempCurrentHour + ":" + tempCurrentMinute, arrTime);
    
    //Build the target TD id reference
    var temporaryTdId = "time_";
    if(parseInt(currentHour) >= 12){
        rowIndex = rowIndex + 24;
    }
    
    temporaryTdId  += rowIndex + "_" + colIndex;
    
    if(document.getElementById(temporaryTdId)){
        var programName = jQuery(currentTable)
                    .find("ProgramName")
                    .text();
        jQuery("#" + temporaryTdId).html(programName);
    }
}

function getDateTime(isoDateTime) {

    dateTime = isoDateTime.split("T");
    date = dateTime[0].split("-");

    timeOffset = dateTime[1].split("-");
    time = timeOffset[0].split(":");
    offset = timeOffset[1].split(":");

    tempDate.setFullYear(date[0], (date[1] - 1), date[2]);
    tempDate.setHours((time[0]), time[1], time[2]);

    utc = tempDate.getTime() + 18000000;

    newDate = new Date(utc + (3600000 * jQuery('#schedule-timezoneselector').val()));

    return newDate;  
}

function getHourMinute(isoDateTime){
    var dateTime = "";
    dateTime = getTime(isoDateTime);
    arrDateTime = dateTime.split(",");
    var arrActualDate = arrDateTime[2].split(" ");
    var tempTime = arrActualDate[2];
    var tempMedian = arrActualDate[3];
    tempTime = tempTime.replace(' ', '');
    finalTime = tempTime.substring(0,5);
    if(finalTime.charAt(4) == ":"){
        finalTime = '0' + '' + tempTime.substring(0,4);
    }
    return finalTime + " " + tempMedian;
}

function getDay(isoDateTime){
    var day = getTime(isoDateTime);
    var arrDay = day.split(',');
    return arrDay[0];
}

function getProgramName(xml, minuteHour, day){
    var programName = jQuery(xml).find('Table')
        .filter(function(){
            var minHour = getHourMinute(jQuery(this).find('ShowDateTime').text());
            var currentDay = getDay(jQuery(this).find('ShowDateTime').text());
            if((minuteHour == minHour) && (currentDay == day)){
                return true;
            }else{
                return false;
            }
        }).eq(0).find('ProgramName').text();
    return programName
}

function formatDateForDisplay(date){
    var strDate = date.toLocaleDateString();
    var arrDate = strDate.split(',');
    return arrDate[1] + ", " + arrDate[2];
}

//Date getWeek extension function
Date.prototype.getWeek = function() {
    var newYear = new Date(this.getFullYear(), 0, 1);
    return Math.ceil((((this - newYear) / 86400000) + newYear.getDay()) / 7);
}
jQuery(document).ready(function(){
    buildScheduleFrame();
});