/* 
 This file was generated by Dashcode.  
 You may edit this file to customize your widget or web page 
 according to the license.txt file included in the project.
 */

//
// Function: parseDate(dateToParse)
// Parse a date string in several formats into a Date object
//
// dateToParse: String containing a date.
//
// Returns a Date object containing the parsed date.
//
function parseDate(dateToParse)
{
    var returnDate = null;
    if (!dateToParse || dateToParse.length < 1) {
        return null;
    }
    
    // try to parse as date string
    returnDate = new Date(dateToParse);
    
    // if no success, try other formats
    if ((!returnDate || isNaN(returnDate.valueOf()))) {
        var dateTimeSeparator = null;
        var monthIndex = null;
        var dayIndex = null;
        var yearIndex = null;
        // try ISO 8601 format (YYYY-MM-DDTHH:MM:SS+OO:OO)
        if (dateToParse.match(/^\d\d\d\d-\d\d-\d\d/)) {
            dateTimeSeparator = "T";
            monthIndex = 1;
            dayIndex = 2;
            yearIndex = 0;
        }
        // try other format (MM-DD-YYYY HH:MM:SS)
        else if (dateToParse.match(/^\d\d-\d\d-\d\d\d\d/)) {
            dateTimeSeparator = " ";
            monthIndex = 0;
            dayIndex = 1;
            yearIndex = 2;
        }
        
        // if the date format was recognized, parse it
        if (dateTimeSeparator) {
            returnDate = new Date();
            // separate date and time
            var dateTime=dateToParse.split(dateTimeSeparator);
            
            // set the date
            var dateArray = dateTime[0].split("-");
            if (dateArray[monthIndex]) returnDate.setMonth(dateArray[monthIndex]-1);
            if (dateArray[dayIndex]) returnDate.setDate(dateArray[dayIndex]);
            if (dateArray[yearIndex]) returnDate.setYear(dateArray[yearIndex]);
            
            // split time and offset
            var timeArray = null;
            if (dateTime[1]) timeArray = dateTime[1].match(/(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:([+-])(\d\d):(\d\d))?/);
            if (timeArray) {
                // set the time
                if (timeArray[1]) returnDate.setHours(timeArray[1]);
                if (timeArray[2]) returnDate.setMinutes(timeArray[2]);
                if (timeArray[3]) returnDate.setSeconds(timeArray[3]);
                
                // add the offset
                if (timeArray[4] && timeArray[5]) {
                    var time = returnDate.getTime() - returnDate.getTimezoneOffset() * 60000;
                    if (timeArray[4] == "+")
                        time -= timeArray[5] * 3600000;
                    else
                        time += timeArray[5] * 3600000;
                    returnDate.setTime(time);
                }
            }
        }
    }
    
    // if no success, return null
    if (returnDate && isNaN(returnDate.valueOf())) {
        returnDate = null;
    }
    
    return returnDate;
}

//
// Function: createDateStr(date)
// Generate a date label from a JavaScript date.
//
// date: JavaScript date object
//
// Returns a string containing the short date.
//
function createDateStr(date)
{
    var day;
    switch (date.getDay()) {
        case 0: day = "dimanche"; break;
        case 1: day = "lundi"; break;
        case 2: day = "mardi"; break;
        case 3: day = "mercredi"; break;
        case 4: day = "jeudi"; break;
        case 5: day = "vendredi"; break;
        case 6: day = "samedi"; break;
    }
    var month;
    switch (date.getMonth()) {
        case 0: month = "janvier"; break;
        case 1: month = "février"; break;
        case 2: month = "mars"; break;
        case 3: month = "avril"; break;
        case 4: month = "mai"; break;
        case 5: month = "juin"; break;
        case 6: month = "juillet"; break;
        case 7: month = "août"; break;
        case 8: month = "septembre"; break;
        case 9: month = "octobre"; break;
        case 10: month = "novembre"; break;
        case 11: month = "décembre"; break;
    }
    return day + " " + date.getDate() + " " + month + " " + date.getFullYear() ;
}

//
// Function: firstValidProperty(object,propertiesArray)
// Returns the value for the first property in propertiesArray that exists.
//
// object: A DC.KVO object
// propertiesArray: An array of property names (strings)
//
// Returns the value of the first property that exists
//
function firstValidProperty(object,propertiesArray)
{
    var value = null;
    
    for(var i = 0; i < propertiesArray.length; i++){
        var property = propertiesArray[i];
        var value = object.valueForKey(property);
        
        if (value) {
            break;
        }
    }
    
    return value;
}

//
// Function: getDateFromArticle(article)
// Returns a date object from an RSS or ATOM feed article.
//
// article: An entry or item from an RSS or ATOM feed
//
// Returns a date object, checking properties by key for both RSS and ATOM type feeds
//
function getDateFromArticle(article)
{
    var dateString = this.firstValidProperty(article,['pubDate','dc:date','updated','issued','modified','created']);
                
    if (dateString) {
        return parseDate(dateString);
    }
    
    return null;
}

//
// Function: setupFilters(list,headlineCount,isHeadline)
// Creates filters on the article list
//
// list: id for the list's data source
//
// Returns nothing
//
function setupFilters(list)
{
    var listDataSource = dashcode.getDataSource(list);
    var numItemsToShow = +attributes.numItemsToShow;
    var maxAgeToShow = +attributes.maxAgeToShow;
    var cutoffDate = new Date();
    var filteredArticles = 0;
    
    if (!list) {
        return;
    }
    
    if (maxAgeToShow > 0) {
        cutoffDate.setTime(cutoffDate.getTime() - maxAgeToShow * 24 * 60 * 60 * 1000);
    } else {
        cutoffDate.setHours(0, 0, 0, 0)
    }
    
    listDataSource.setFilterPredicate(function(object){
        var date = getDateFromArticle(object);
        
        filteredArticles++;
        
        // If we are over our limit...Stop (-1 = unlimited)
        if ((numItemsToShow >= 0) && filteredArticles > numItemsToShow){
            return false;
        }
        
        if (!date) {
            date = new Date();
        }
        
        if ((maxAgeToShow >= 0) && (cutoffDate > date)) {
            return false;
        }
        
        return true;
    });
}

//
// Function: extractText(content)
// Pulls text out of div elements
//
// content: string or element containing an entry
//
function extractText(content)
{
    var extractedString;
    
    if (typeof content == "string") {
        extractedString = content;
    }
    else {
        extractedString = content.innerText;
    }
    extractedString = extractedString.replace(/\n/g," ");
    extractedString = extractedString.replace(/<[^>]*>/g, "");
    
    return extractedString;
}

//
// Function: handleCommonErrors(dataSourceName)
// Handles common errors with a feed data source.  Will display an error in these cases.
//
// dataSourceName: name of the main feed data source
//
//
function handleCommonErrors(dataSourceName,errorHandler)
{
    var feedDataSource = dashcode.getDataSource(dataSourceName);
    
    // Is the data source not defined. Only happens if developer deletes the data source manually.
    if (!feedDataSource) {
        errorHandler("The RSS feed data source cannot be found");
        
        return false;
    }
    
    if (!feedDataSource.valueForKey('url')) {
        errorHandler("No RSS feed specified\nProvide a Feed URL in Application Attributes");
        
        return false;
    }
    
    // Watch the errorMessage property of the data source, if it changes, check the error
    // and display something.
    feedDataSource.addObserverForKeyPath({}, function(changeNotification, keyPath){
        var errorStatus = feedDataSource.valueForKey('statusCode');
        var errorMessage = feedDataSource.valueForKey('errorMessage');
        
        if (errorMessage) {
            if (errorStatus < 0) { 
                errorHandler("Feed not available: " + errorMessage);
            } else {
                errorHandler("Error status " + errorStatus);
            }
        }
    }, "errorMessage", null);

    // Check to make sure this is RSS or ATOM and that there is at least one article
    feedDataSource.addObserverForKeyPath({}, function(changeNotification, keyPath){
        var atomEntries = feedDataSource.valueForKeyPath('content.entry');
        var rssEntries = feedDataSource.valueForKeyPath('content.channel.item');
        var foundCount = 0;
        
        if (atomEntries && (DC.typeOf(atomEntries) == 'array')) {
            foundCount = atomEntries.length;
        } else if (rssEntries && (DC.typeOf(rssEntries) == 'array')) {
            foundCount = rssEntries.length;
        } else {
            errorHandler(feedDataSource.fullURL() + ' does not appear to be a valid RSS or Atom feed');
            return;
        }
        
        if (!foundCount) {
            errorHandler("No articles found in feed");
        }
        
    }, "content", null);    
    
    return true;
}


//
// Function: showError(errorString)
// Show an error in a red box
//
// errorString: string to be displayed
//
function showError(errorString)
{
    var errorDiv;
    errorDiv = document.createElement("div");
    errorDiv.innerText = errorString;
    errorDiv.setAttribute("style", "position: absolute; border-style: solid; border-width: 1px; right: 10px; left: 10px; top: 120px; background-color: rgb(32, 32, 32); border-color: rgb(0, 0, 0); -webkit-border-radius: 10px; -moz-border-radius: 10px; text-align: center; padding: 15px; font-family: Helvetica; font-weight: bold; color: rgb(255, 255, 255); font-size: 15px; text-shadow: rgb(0, 0, 0) 0px -1px 0px;");
    document.getElementById("content").appendChild(errorDiv);
}

//
// Transformer: htmlToTextTransformer
// Transforms an HTML string or DOM element to textual string
//
//  value: HTML string or HTML DOM element
//
//
htmlToTextTransformer = Class.create(DC.ValueTransformer,{
    transformedValue: function(value){
        return extractText(value);
    }
});

//
// Transformer: articleDateTransformer
// Extracts the date from a RSS or ATOM item or entry
//
//  value: RSS or Atom article object
//
//
articleDateTransformer = Class.create(DC.ValueTransformer,{
    transformedValue: function(value){
        var string = "Publié le ";
        var dateString = null;
        var date = getDateFromArticle(value);
                        
        if (date) {
            string += createDateStr(date);
        } else {
            string = "Unknown Date";
        } 
        
		return string;
    }
});
