/* STATIONFINDER.JS LOCAl*************************************************************/
/**
 * @Add an online show finder search box provided by Tribune Media Services
 * @implemented by Yufang Chang
 */

if (typeof MAGNET.stationFinder == "undefined") {
    MAGNET.stationFinder = {};
}

MAGNET.stationFinder.findListings = new (function() {
var oThis = this;

var TVListings = {
    providerTypes : {
        'cab' : 'Cable Providers',
        'sat' : 'Satellite Providers',
        'brd' : 'Local Broadcast'
    },
    errorMsgs : {
        zip : 'No Show times available for this provider.',
        request : 'The page you requested encountered an error. Please try again.'
    },
    successMsgs : {
        providers : function(zipCode) {
            return 'Select one of the following service providers for zip code <strong>' + zipCode + '</strong>:';
        },
        programs : function(provider) {
            return 'Program results for <strong>' + provider + '</strong>:';
        }

    },
    errorDiv : document.getElementById('errorDiv'),
    providerText : document.getElementById('providerText'),
    providerLink : document.getElementById('providerLink'),
    serviceProviders : document.getElementById('serviceProviders'),
    listingContent : document.getElementById('listingContent'),
    loadingGif : document.getElementById('loadingGif'),
    zipCodeInput : document.getElementById('tvZip')
};


// attach action to submit button;
oThis.search = function() {

if (document.getElementById('zipSearch')) {
    jQuery("#stationListings").css("display","block");
    jQuery("#zipSearch").submit(function () {
          var zipVal = TVListings.zipCodeInput.value;
        if(zipVal) {
        for(var o in TVListings) {
            var obj = TVListings[o];
            if(obj.tagName && obj.tagName == 'DIV') {
                obj.innerHTML = '';
                obj.style.display = 'block';
           }
        }
            getProviderList(zipVal);
        } else {
            displayError(TVListings.errorMsgs.zip);
        }

      return false;
      });
}
}


/**
*  @private getProviderList function
*  return List
*/

function getProviderList(zipCode) {
    TVListings.loadingGif.style.display = 'block';
    var currentDate = new Date();
    var url = 'http://api.zap2it.com/tvlistings/ZCShowFinder.do?zipcode=' + zipCode + '&localize=true&aid=zap2it&sId=EP01186394&rType=json';
    jQuery.getScript(url, function(){
                try {
                if(resultStr) {
                    var results = eval('(' + resultStr + ')');
                    if(results && results[0].providers && results[0].providers.length>0) {
                        parseProviders(zipCode, results[0].providers);
                        displayError();
                    }
                    else {
                        displayError(TVListings.errorMsgs.zip);
                    }
                }
                else {
                    displayError(TVListings.errorMsgs.request);
                }
            }
            catch(err) {
                displayError(TVListings.errorMsgs.request);
            }
            finally {
                TVListings.loadingGif.style.display = 'none';
            }


     });
} // getProviderList


/**
*  @private getShowTimes function
*  return ShowTimes
*/

function getShowTimes(zipCode, lineupID) {
    makeProviderLink(zipCode);
    TVListings.providerText.style.display = 'none';
    TVListings.serviceProviders.style.display = 'none';
    TVListings.loadingGif.style.display = 'block';

    var currentDate = new Date();
    var url = 'http://api.zap2it.com/tvlistings/ZCShowFinder.do?localize=false&aid=zap2it&zipcode=' + zipCode + '&lineupId=' + lineupID + '&sId=EP01186394&rType=json';
    jQuery.getScript(url, function(){
                try {
                if(resultStr) {
                    var results = eval('(' + resultStr + ')');
                    if(results && results[0].programs && results[0].programs.length>0) {

                        parseShowTimes(zipCode, results[0].programs);
                        displayError();
                    }
                    else {
                        displayError(TVListings.errorMsgs.zip);
                    }
                }
                else {
                    displayError(TVListings.errorMsgs.request);
                }
            }
            catch(err) {
                displayError(TVListings.errorMsgs.request);
            }
            finally {
                TVListings.loadingGif.style.display = 'none';
            }

     });
} // getShowTimes

/**
*  @private parseProviders function
*  parse providers
*/

function parseProviders(zipCode, providers){

    if(providers.length>0) {
        for(var pt in TVListings.providerTypes) {
            var providerList = document.createElement('ul');
            providerList.className = 'providerList';
            providerList.innerHTML = '<li class="providerType">' + TVListings.providerTypes[pt] + '</li>';
            for(var i=0; i<providers.length; i++) {
                if(providers[i].deviceType==pt) {
                    providerList.appendChild(makeProviderItem(zipCode, providers[i]));
                }
            }
            if(providerList.childNodes.length>1) {
                TVListings.serviceProviders.appendChild(providerList);
            }
        }
        TVListings.providerText.innerHTML = TVListings.successMsgs.providers(zipCode);
    }
    return false;
} // parseProviders

/**
*  @private parseShowTimes function
*  parse showtime
*/

function parseShowTimes(zipCode, programs) {
var CC, episodeURL, episodeTitle, episodeId, airings, channelStations, channelNumber, channelTime, channelDate, stereo, tvData, channelNumberCS, channelTimeCS, channelDateCS, channelStationsCS;

if(programs!=undefined) {

   var showTimeListingUL = document.createElement('ul');
   showTimeListingUL.setAttribute('id', 'showTimes');

   for(i=0; i<programs.length; i++) {

        var showTimeListingUL = document.createElement('ul');
        showTimeListingUL.setAttribute('id', 'showTimes');

        var showTimeListingLi = document.createElement('li');
        showTimeListingLi.className = 'showTimeListingLi';

        var showHeader = document.createElement('h3');
        showHeader.innerHTML = programs[i].title;

        showTimeListingLi.appendChild(showHeader);

        for(j=0; j<programs[i].schedules.length; j++) {









          var showTimesUL = document.createElement('ul');
          showTimeListingLi.appendChild(showTimesUL);

          for(k=0; k<programs[i].schedules[j].airings.length; k++) {
              var timeLineDiv = document.createElement('li');
              timeLineDiv.className = 'tvTimeLine';

              CC = programs[i].schedules[j].isCC ? ' [CC]' : '';
              stereo = programs[i].schedules[j].isStereo ? ' [Stereo]' : '';
              episodeURL = programs[i].schedules[j].link;
              episodeTitle = programs[i].schedules[j].episodeTitle;
              episodeId = programs[i].showId;
              channelStations = programs[i].schedules[j].airings[k].callsign;
              channelNumber = programs[i].schedules[j].airings[k].channel;
              channelTime = programs[i].schedules[j].airings[k].time;
              channelDate = programs[i].schedules[j].airings[k].date;
              //channelMinor = (programs[i].schedules[j].airings[k].channelMinor !=undefined) ? '.' + programs[i].schedules[j].airings[k].channelMinor : '';

              var gridRow = '<div class="episode"><div class="episodeInformation">';
                gridRow += '<span class="date">' + episodeTitle + '</span>, ';
                gridRow += '<span class="date">' + channelDate + '</span>, ';
                gridRow += '<span class="time">' + channelTime + '</span>, ';
                gridRow += '<span class="tvStationChannel">' + channelStations + ', Channel ' + channelNumber +  '</span>';
                gridRow += '</div></div>';

                timeLineDiv.innerHTML = gridRow;
                showTimesUL.appendChild(timeLineDiv);
          }

       }

       showTimeListingUL.appendChild(showTimeListingLi);

   }

   TVListings.listingContent.appendChild(showTimeListingUL);
   makeProviderLink(zipCode);

}
} // parseShowTimes

/**
*  @private makeProviderLink function
*/

function makeProviderLink(zipCode) {
    TVListings.providerLink.innerHTML = '<a href="#">Click here</a> to return to the service providers list for zip code <strong>' + zipCode + '</strong>.';
    TVListings.providerLink.style.display = 'block';
    TVListings.providerLink.onclick = function() {
        TVListings.listingContent.innerHTML = '';
        TVListings.providerLink.style.display = 'none';
        TVListings.providerText.innerHTML = TVListings.successMsgs.providers(zipCode);
        TVListings.serviceProviders.style.display = 'block';
        TVListings.errorDiv.style.display = 'none';
        return false;
    };
} // makeProviderLink

/**
*  @private getShowHeader function
*/

function getShowHeader(showTitle) {
    var showHeader = document.createElement('h3');
    showHeader.innerHTML = showTitle;
    return showHeader;
} // getShowHeader

/**
*  @private makeProviderItem function
*/

function makeProviderItem(zipCode, provider) {
    var a = document.createElement("a");
    var providerInfo = provider.providerName + ' - ' + provider.deviceName + ' (' + provider.providerLocation + ')';
    a.href = "#";
    a.innerHTML = providerInfo;
    a.onclick = function() {
        getShowTimes(zipCode, provider.lineupId);
        TVListings.providerText.innerHTML = TVListings.successMsgs.programs(providerInfo);
        return false;
    };
    var li = document.createElement('li');
    li.className = 'providerName';
    li.appendChild(a);
    return li;
} // makeProviderItem

/**
*  @private displayError function
*/

function displayError(msg) {
    if(msg) {
        TVListings.errorDiv.innerHTML = msg;
        TVListings.errorDiv.style.display = 'block';
    }
    else {
        TVListings.errorDiv.innerHTML = '';
        TVListings.errorDiv.style.display = 'none';
    }
} // displayError

});

jQuery(function(){
    MAGNET.stationFinder.findListings.search();
});


/* END SHOWFINDER.JS *************************************************************/



