﻿function setReaderEventHandlers() {
    try {
        reader.setOnCompleteEvent(
            function() {
                $("#" + this.parent).jCarouselLite({
                    btnNext: ".thePrev",
                    btnPrev: ".theNext",
                    scroll: 4,
                    speed: 500,
                    visible: 5
                });

                $(".video-bg .prev").mousedown(function() {
                    $(this).addClass("down");
                }).mouseup(function() {
                    $(this).removeClass("down");
                }).mouseout(function() {
                    $(this).removeClass("down");
                });
                $(".video-bg .next").mousedown(function() {
                    $(this).addClass("down");
                }).mouseup(function() {
                    $(this).removeClass("down");
                }).mouseout(function() {
                    $(this).removeClass("down");
                });

            }
        );
    } catch (e) {
	}
}

function YoutubeReader(id) {
	try{
	    if ($(document)) {
			this.init(id);
		}
	}catch(e){
	}finally{
		return;
	}
}

YoutubeReader.prototype = {
    //developerkey: 'ABQIAAAAC8rRiKw0afBQC7SztdFpLBQuIlg1gDbkYCx-GGa57cKkZR4aQBQihI3A3kIh9gdMy1iJtIrbNj1AiA',
    developerkey: 'AI39si50H4mtXJzqXXPzJlrv7kPV3CosEIDtkZXpOuuLDODH_UfW9SUWQF3YbfHBZQ_wLULFG7uO5Xrawo3CQ7ARl2-jsy1mCw',
    maxResults: 4,
    keywords: null,
    feedUrl: "http://gdata.youtube.com/feeds/api/videos/-/{0}/?v=2&max-results={1}&alt=json-in-script&format=5&key={2}&callback=?",
    parent: null,
    entries: 0,
    onCompleteCallBack: null,
    init: function(id) {
        this.parent = id;
    },
    draw: function(data) {
        try {
            var feed = data.feed;
            var entries = feed.entry || [];
            this.entries = entries.length;
            var list = new String();
            list = '<ul>';
            for (var i = 0; i < this.entries; i++) {
                var entry = entries[i];
                var link = entry.link[0].href;

                //Seting up rating:
                if (entry.gd$rating) {
                    var avgRating = entry.gd$rating.average;
                }
                if (entry.yt$statistics) {
                    var viewCount = entry.yt$statistics.viewCount;
                }

                list += '<li>';
                list += '<a href="' + link + '" class="Floaty" target="_blank">';
                list += '<img index="' + i + '" border="0" align="absmiddle" src="' + entry.media$group.media$thumbnail[0].url + '" />';
                //list += '<span>' + entry.title.$t + '</span>';
                list += '</a>';
                list += '<div><i>דירוג: ' + parseInt(avgRating) + '</i><b>צפיות: ' + viewCount + '</b></div>';
                list += '</li>';

            }
            list += '</ul>';
            $('#' + this.parent).html(list);

            var reader = this;
            $('#' + this.parent + ' a').hide();
            $('#' + this.parent + ' img').load(function() {
                if ($(this).attr("index") == (reader.entries - 1)) {
                    reader.onCompleteCallBack();
                    $('#' + reader.parent + ' a').show();
                }
            });

            $('a.Floaty').Floaty({ vWidth: 445, vHeight: 364 });

        } catch (e) {
        }
    },
    setKeywords: function(keywords) {
        this.keywords = keywords;
    },
    setMaxResults: function(results) {
        this.maxResults = results;
    },
    setDeveloperKey: function(key) {
        this.developerkey = key;
    },
    setFeedUrl: function(url) {
        this.feedUrl = url;
    },
    getFeedUrl: function() {
        return this.feedUrl;
    },
    setOnCompleteEvent: function(callBack) {
        try {
            this.onCompleteCallBack = callBack;
        } catch (e) {
        }
    },
    getVideos: function(keywords, results, callBack) {
        this.setKeywords(keywords);
        this.setMaxResults(results);
        if (callBack != null)
            this.setOnCompleteEvent(callBack)
        var url = String.format(this.feedUrl, this.keywords, this.maxResults, this.developerkey);
        var reader = this;
        $.getJSON(url, function(data) {
            reader.draw(data);
        });
    }
};


String.format = function(text) {
	//check if there are two arguments in the arguments list
	if (arguments.length <= 1) {
		//if there are not 2 or more arguments there’s nothing to replace
		//just return the original text
		return text;
	}
	//decrement to move to the second argument in the array
	var tokenCount = arguments.length - 2;
	for (var token = 0; token <= tokenCount; token++) {
		//iterate through the tokens and replace their placeholders from the original text in order
		text = text.replace(new RegExp("\\{" + token + "\\}", "gi"),
                                                arguments[token + 1]);
	}
	return text;
};

