/**
 * Plugin: jquery.content
 * 
 * Version: 1.1.0
 * (c) Copyright 2010-2011, Igor
 **/

(function ($) {
    $.fn.content = function (options, fn) {
        var defaults = {
            limit: 10,
            header: false,
            titletag: "h4",
            date: false,
            content: false,
            snippet: false,
            showerror: true,
			videotitle: false,
			videodescription: false,
			videothumbnailwidth: "140px",
            errormsg: "",
			orientation: "vertical",
            key: null,
            ssl: false,
            linktarget: "_self",
            type: "videos",
			wrapped: true,
            url: null,
            title: "No title",
            width: "300px",
            bordercolor: "#ccc",
            backgroundcolor: "#ccc",
            titlecolor: "#000",
            linkcolor: "#142DE3",
            contentcolor: "#333",
            titlefont: "normal 12px arial",
            linkfont: "normal 12px arial",
            contentfont: "normal 12px arial"
        };
        var options = $.extend(defaults, options);

        return this.each(function (i, e) {
            var $e = $(e);
            var s = '';

            if (options.ssl) s = 's';			

            var url = options.url;
            if (url == null) return false;

            var api = "http" + s + "://ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?&q=" + encodeURIComponent(url);
            if (options.limit != null) api += "&num=" + options.limit;
            if (options.key != null) api += "&key=" + options.key;
            api += "&output=json_xml"

            $.getJSON(api, function (data) {                
                if (data.responseStatus == 200) {                    
                    processhtml(e, data.responseData, options);                    
                    if ($.isFunction(fn)) fn.call(this, $e);
                } else {                   
                    if (options.showerror)
                        if (options.errormsg != '') {
                            var msg = options.errormsg;
                        } else {
                            var msg = data.responseDetails;
                        };					
                    $(e).html('<div style=\"font:normal 12px arial\"><p>' + msg + '</p></div>');
                };
            });
        });
    };
    
    var processhtml = function (e, data, options) {
        var feeds = data.feed;        
        if (!feeds) {
            return false;
        }
        var html = '';
        var row = 'odd';
        
        var xml = getXMLDocument(data.xmlString);
        var xmlEntries = xml.getElementsByTagName('item');

        if (options.header)
            html += '<div class="rssHeader">' +
				'<a href="' + feeds.link + '" title="' + feeds.description + '">test' + feeds.title + '</a>' +
				'</div>';

        // widget styles
        html += "<style>";
        html += "h4.widget{ padding:6px; font:" + options.titlefont + "; margin:0px }";
        html += "div.widget{ font:normal 12px arial; color:#333 }";
        html += "a.widget:link{ font:" + options.linkfont + "; color:" + options.linkcolor + "; text-decoration:none }";
        html += "a.widget:active{ font:" + options.linkfont + "; color:" + options.linkcolor + "; text-decoration:none }";
        html += "a.widget:hover{ font:" + options.linkfont + "; color:" + options.linkcolor + "; text-decoration:underline }";
        html += "a.widget:visited{ font:" + options.linkfont + "; color:" + options.linkcolor + "; text-decoration:none }";
        html += "div.widget-content{ margin-top:3px; margin-bottom:10px; color:" + options.contentcolor + "; font:" + options.contentfont + " }";
        html += "div.widget-content a:link{ font:normal 12px arial; color:green; text-decoration:none }";
        html += "</style>";

		var withpadding = "";
        // content proper
		var actualwidth = options.width;
		if(options.wrapped){
			html += "<div class=\"widget\" style=\"clear:both;border:1px solid " + options.bordercolor + ";";
			html += "width:" + options.width + "\"><h4 class=\"widget\" style=\"color:" + options.titlecolor + ";";
			html += "background-color:" + options.backgroundcolor + ";\">" + options.title + "</h4>";
			withpadding = "padding-top:8px;padding-left:8px;padding-right:8px";			
			actualwidth = "100%";
		}
		
        html += "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" ";
        html += "style=\"clear:both;margin:0px;width:" + actualwidth + ";" + withpadding + "\">";		
		
		if(options.orientation == "horizontal"){
			html += "<tr>";
		}
		
        for (var i = 0; i < feeds.entries.length; i++) {            
            var entry = feeds.entries[i];
            
			var hasContent = false;
            var entryDate = new Date(entry.publishedDate);
            var pubDate = entryDate.toLocaleDateString() + ' ' + entryDate.toLocaleTimeString();
            
            var videolink = "";
            var relLink = "";
            var contentLink = entry.link;
            if (options.type == "video") {
                relLink = "shadowbox;width=505;height=400;player=swf";
                videolink = "video-link";
                contentLink = getVideo(entry.link);
				
				switch(options.orientation){
					case "vertical":
							html += "<tr><td>";
							html += "<a id=\"image\" rel=\"" + relLink + "\" href=\"" + getVideo(entry.link) + "\" title=\"" + entry.title + "\">";
							html += "<img id=\"image-display\" src=\"" + getScreen(entry.link, "small") + "\" alt=\"" + entry.title + "\" ";
							html += "style=\"cursor:pointer;width:" + options.videothumbnailwidth +  ";";
							html += "padding:2px;border:1px solid #ccc\" /></a>";
							html += "</td></tr>";
						
							if(options.videotitle || options.videodescription){								
								if(options.videotitle){
									html += "<tr>";
									html += "<td style=\"";
									html += "color:" + options.titlecolor + ";font:normal 12px arial;";
									html += "padding-bottom:3px;\">";
									html += "<div style=\"clear:both;width:" + options.videothumbnailwidth + ";\">";
									html += "<a id=\"image\" href=\"" + getVideo(entry.link) + "\" ";
									html += "class=\"widget\">" + entry.title + "</a></div></td>";
									html += "</tr>";
								}								
								if(options.videodescription){
									html += "<tr>";
									html += "<td style=\"clear:both;width:" + options.videothumbnailwidth + ";";
									html += "color:" + options.titlecolor + ";font:normal 12px arial;";
									html += "padding-bottom:10px;\"><div style=\"clear:both;width:" + options.videothumbnailwidth + ";\">";
									html += entry.content + "</div></td>";
									html += "</tr>";
								}								
							}
							break;
					default:		
							html += "<td valign=\"top\" style=\"padding-right:4px;\">";
							html += "<a id=\"image\" rel=\"" + relLink + "\" ";
							html += "href=\"" + getVideo(entry.link) + "\" title=\"" + entry.title + "\">";
							html += "<img id=\"image-display\" src=\"" + getScreen(entry.link, "small") + "\" alt=\"" + entry.title + "\" ";
							html += "style=\"cursor:pointer;padding:2px;border:1px solid #ccc;";
							html += "width:" + options.videothumbnailwidth + "\" /></a>";					
							
							if(options.videotitle || options.videodescription){								
								html += "<div style=\"clear:both;width:" + options.videothumbnailwidth + ";\">";
								if(options.videotitle){
									html += "<div style=\"color:" + options.titlecolor + ";padding-bottom:3px;font:normal 12px arial;\">";
									html += "<a id=\"image\" href=\"" + getVideo(entry.link) + "\" class=\"widget\">" + entry.title + "</a></div>";
								}
								if(options.videodescription){
									html += "<div style=\"color:" + options.titlecolor + ";font:normal 12px arial;\">" + entry.content + "</div>";
								}				
								html += "</div>";
							}
							
							html += "</td>";
							break;
				}
            }
            else if (options.type == "shopping") {
                html += "<tr><img src=\"\" /></tr>";								
            }
            else if (options.type == "news-content") {
                html += '<tr><td style=\"margin-bottom:10px;\"><a rel=\"' + relLink + '\" href="' + contentLink + '" class=\"normal-link\">' + entry.title + '</a>';
                html += '<div style=\"margin-top:3px;margin-bottom:7px\">' + entry.content + '</div></td></tr>';
            }
            else {
                html += '<tr><td style=\"margin-bottom:10px;\"><a class=\"widget\" rel=\"' + relLink + '\" href="' + contentLink + '" class=\"video-link\">' + entry.title + '</a>';
                html += '<div class=\"widget-content\">' + entry.content + '</div></td></tr>';
            }
        }

		if(options.orientation == "horizontal"){
			html += "</tr>";
		}
		
        html += "</table>";
		
		if(options.wrapped){
			html += "</div>";
		}
		
        $(e).html((feeds.entries.length > 0) ? html : "");
    };

    function getScreen(url, size) {
        if (url === null) { return ""; }

        size = (size === null) ? "big" : size;
        var vid;
        var results;

        results = url.match("[\\?&]v=([^&#]*)");

        vid = (results === null) ? url : results[1];

        if (size == "small") {
            return "http://img.youtube.com/vi/" + vid + "/2.jpg";
        } else {
            return "http://img.youtube.com/vi/" + vid + "/0.jpg";
        }
    }

    function getVideo(url) {
        if (url === null) { return ""; }

        var vid;
        var results;

        results = url.match("[\\?&]v=([^&#]*)");

        vid = (results === null) ? url : results[1];

        return "http://www.youtube.com/v/" + vid + "&amp;hl=en&amp;fs=1&amp;rel=0&amp;autoplay=1";
    }

    function formatFilesize(bytes) {
        var s = ['bytes', 'kb', 'MB', 'GB', 'TB', 'PB'];
        var e = Math.floor(Math.log(bytes) / Math.log(1024));
        return (bytes / Math.pow(1024, Math.floor(e))).toFixed(2) + " " + s[e];
    }

    function getXMLDocument(string) {
        var browser = navigator.appName;
        var xml;
        if (browser == 'Microsoft Internet Explorer') {
            xml = new ActiveXObject('Microsoft.XMLDOM');
            xml.async = 'false'
            xml.loadXML(string);
        } else {
            xml = (new DOMParser()).parseFromString(string, 'text/xml');
        }
        return xml;
    }
	
	function getUrlParam(name) {
		name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
		var regexS = "[\\?&]" + name + "=([^&#]*)";
		var regex = new RegExp(regexS);
		var results = regex.exec(window.location.href);
		if (results == null)
			return "";
		else
			return results[1];
	}
})(jQuery);

