var Putpat = {  
    offset: 0,
    clips: []
};

Putpat.initPlayLink = function() {
    
    var quest = window.location.search;
    
    if (quest == null || quest.length == 0) {
        quest = "?"
    }
    
    $("#playbutton").attr("href", Putpat.uri + quest + "&player=true");
}

Putpat.initTime = function(callback) {
    $.getJSON('/ws.json?method=Channel.time', function(data) {
        Putpat.offset = new Date().getTime() - data["time"]["milliseconds"]
        callback();
    });
}

Putpat.getCurrentClip = function() {
    var current = new Date().getTime() - Putpat.offset;
    
    for (i in Putpat.clips) {
        clip = Putpat.clips[i];
        
        if (current < (clip["clip"]["absolute_start_time"] + clip["clip"]["duration"]) * 1000 / 25) {
            return clip["clip"];
        }
    }
    
    return null;
}

Putpat.getClip = function(callback) {
    var currentclip = Putpat.getCurrentClip();
    
    if (currentclip == null) {
        $.getJSON('/ws.json?method=Channel.clips&channelId=' + Putpat.channel, function(data) {
            Putpat.clips = data;
            currentclip = Putpat.getCurrentClip();
            callback(currentclip);
        });
    } else {
        callback(currentclip);
    }
    
}

Putpat.getPathFor= function(id, prefix) {
    str = ""+id;
    
    while (str.length < 7) {
        str = "0" + str;
    }
    
    return str.substring(0,5) + "/" + str + "/" + prefix + str;
}

Putpat.updateClip = function() {
    Putpat.getClip(function(clip){
        if (clip != null) {
            $("#showtitle").empty().append(clip["clip_container"]["title"]);
            
            if (clip["asset"]["artist"] != null) {
                $("#artist").empty().append(clip["asset"]["artist"]["title"]);
            } else {
                $("#artist").empty();
            }
            
            $("#title").empty().append(clip["asset"]["title"]);
            $("#preview").replaceWith("<img height='163' id='preview' src='http://files.putpat.tv/artwork/posterframes/" + Putpat.getPathFor(clip["video_file_id"], "v") + "_posterframe_putpat_small.jpg'/>")

            setTimeout('Putpat.updateClip()', ((clip["absolute_start_time"] + clip["duration"]) * 1000 / 25) - new Date().getTime());
        }
    });
}

Putpat.startShow = function () {
    Putpat.initTime(function() {
        Putpat.updateClip();
    });
}

$(function() {
    Putpat.initPlayLink();
    Putpat.startShow();
});