// JavaScript Document
jQuery.noConflict();

jQuery(document).ready(function(){
    initNewsLibrary();
});

var jsonResponse;

function initNewsLibrary(){
    var libraries = jQuery("#selection input[type='checkbox']:checked");
    jsonResponse = "";
    getNewsLibraries(libraries, true);
    
    jQuery("#selection input[type='checkbox']").click(function(){
        getNewsLibraries(jQuery("#selection input[type='checkbox']:checked"), false);
    });
}

function getNewsLibraries(libraries, firstCall){
    var libraryString = '';
    
    for(var i = 0; i < libraries.length; i++){
        if(i > 0)
            libraryString += ',';
        libraryString += jQuery(libraries[i]).attr("value");
    }
    
    retrieveNewsItems(libraryString, firstCall);
}


/* Retrieves the data  */
function retrieveNewsItems(newsLibraryIds, firstCall){
/*    var searchUrl = "NewsService.aspx?callback=?&nid=" + newsLibraryIds; */
    var searchUrl = "/NewsService.aspx?callback=?&nid=" + newsLibraryIds;

        jQuery.getJSON(searchUrl, {}, function(data){
            var resultHtml = '';
            
            data.items.sort(function(objFirst, objSecond){
                return (createDateObject(objSecond.date).getTime() - createDateObject(objFirst.date).getTime())
            });
            
            jQuery.each(data.items, function(i,item){
                if(i < 9){
                    if(i % 3 == 0) {
                        resultHtml += "<div class='row'>";
                    }
                    resultHtml += "<div class='element";
                
                    if(i % 3 == 2)
                        resultHtml += " last";
                
                    resultHtml += "' onclick=\"location.href='" + item.newsUrl + "';\" style=\"cursor: pointer;\"><div class='date'>" + outputDate(item.date) + "</div><div class='category'><h3 class='whiteLink'>" + item.category + "</h3></div>";
                    if(item.imageUrl != ""){
                        
                        var height;
                        var width;
                        
                        resultHtml += "<div class='teaserImage'><img src='" + item.imageUrl + "' alt='teaser' class='image' ";
                        
                        if(item.imageHeight != null && item.imageWidth != null){
                            var scaleFactor = item.imageWidth / 212;
                            height = Math.floor(item.imageHeight / scaleFactor);
                            resultHtml += "style='width:212px; height:" + height + "px'";
                        }
                        resultHtml += " /><img src='/images/ImageMask_212.png' class='mask' alt=''/></div>";
                    }
                    resultHtml += "<div class='teaserContent'><h3>" + item.header + "</h3>" + outputTeaserText(item.text, item.imageUrl);
                    resultHtml += "<div class='more'><a href='" + item.newsUrl + "' class='teaserElement'>Læs mere</a></div></div><!--END:teaserContent --></div><!--END:element -->";

                    if(i % 3 == 2)
                        resultHtml += "</div>";
                }
            });
            resultHtml += "<div class='clear'></div>";
            
            jQuery("#teaserContainer").empty();
            jQuery("#teaserContainer").append(resultHtml);
            
            if(firstCall == true)
                generateLatest(data);
        });
}

/* Generates the list of latest news in the menu  */
function generateLatest(data){
    var resultHtml = "<li class='menuLevel-2-act-subpage'><div class='shadow'><div class='activeBG'><a>Seneste Nyheder</a></div></div></li><li class='menu-next-level-3'><ul class='menuLevel-3'>";
    
    jQuery.each(data.items, function(i,item){
        if(i < 4){
            resultHtml += "<li class='menuLevel-3'><a href='" + item.newsUrl + "'><span class='date'>(" + outputDate(item.date) + "<br />" + item.category + ")</span><span class='header'>" + item.header + "</span></a></li>";
        }
    });
    
    resultHtml += "</ul></li>";
    jQuery("#leftContainer ul.menuLevel-2").prepend(resultHtml);
}

/* Creates a date object based on the database date string representation */
function createDateObject(dateString){
    var arr = dateString.split("T");
    var date = arr[0].split("-");
    var time = arr[1].split(":");
    return new Date(date[0], date[1], date[2], time[0], time[1], time[2]);   
}

/* Creates a date string based on the database date string representation */
function outputDate(dateString){
    var arr = dateString.split("T");
    var date = arr[0].split("-");
    return date[2] + "-" +  date[1] + "-" + date[0];
}

/* Returns the correctly formatted teaser string depending on weather there is an image assigned the news story */
function outputTeaserText(teaserText, imageUrl){
    if(teaserText.length > 0){
        if(imageUrl.length > 0){
            if(teaserText.length > 100){
                if(teaserText.indexOf(" ", 100) > -1)
                teaserText = teaserText.substr(0, teaserText.indexOf(" ", 100)) + "...</p>";
            }
        }
        else{
            if(teaserText.length > 200){
                if(teaserText.indexOf(" ", 200) > -1)
                    teaserText = teaserText.substr(0, teaserText.indexOf(" ", 200)) + "...</p>";
            }
        }
        return teaserText;
    }
    else
        return "";
}

