/**********************************************************************************************
* ~License~ This portion should accompany the Script for Legal usage and Proper Credits
* author: Swashata
* email: admin@intechgrity.com
* ProjectPage: http://code.google.com/p/recent-filtered-posts-using-jquery-blogspot/
* Blog: http://www.inTechgrity.com
* Instruction at Blog: http://www.intechgrity.com/2009/08/jquery-recent-post-widget-for.html
* 
* Copyright, 2009 inTechgrity
* Licensed under the GNU General Public License v3
*     This program is free software: you can redistribute it and/or modify
*     it under the terms of the GNU General Public License as published by
*     the Free Software Foundation, either version 3 of the License, or
*    (at your option) any later version.
*
*     This program is distributed in the hope that it will be useful,
*     but WITHOUT ANY WARRANTY; without even the implied warranty of
*     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*     GNU General Public License for more details.
*
*     You should have received a copy of the GNU General Public License
*     along with this program.  If not, see <http://www.gnu.org/licenses/>.
* ~End of License | Now enjoy~
***********************************************************************************************/

function RecentFilteredPost(userOp) {
    var self = this;
    //Set default options
    var op = {
        'BlogURL':'http://www.intechgrity.com', //URL of the blog
        'tag':[], //Set to null for recent or specify to filter
        'maxPost':10, //Set the number of maximum posts per tag or as a whole
        'containerId':'', //The div where the parent ul is going to be appended
        'thumbH':50, //Thumbnaiil width
        'thumbW':50, //Thumbnail height
        'ulClass':'itg', //Class of the appended ul
        'aClass':'', //Class of the a element if you want
        'onLoad':false, //True for window(onload) or false for (document).ready
        'defImg':'http://i29.tinypic.com/2namq9h.png', //Img URL if no image is found on the script
        'imgEna':true, //Whether Thumbnail formation is enabled or not!
        'imgClass':'recent-image', //Class of the image
        'aPermaTitle':'' //Tooltip of the a appended The title of the post will be appended after this like : "Permanent Link to"+postTitle
    };
    
    //Extend it using the jQuery extend option
    op=$.extend({}, op, userOp);
    
    //If we dont have containerId then we append one container and reset the container option
    if(!op.containerId) {
        op.containerId='#recent-post';
        document.write('<div id="recent-post"></div>');
    }
    //A variable to be used a Global [For this function, but actually local] jQuery selector
    var div = $(op.containerId);
    
    //Storing the content of the Selector to use this as AJAX style loader
    var loadContent = div.html();
    
    //Count for removing the loader image properly After trying so many things I thought of making Global variable here so that every internal funtion can have access on it and then increase it inside the AJAX Loop for tags
    var count = 0;
    
    
    //Main speedLoader function thanks to Pyrotechnicpixie (my co-blogger and best friend) for this cool name :)
    var speedLoader = function(json,status,c,s){
        var loadRemove = c;
        var ajaxLooper = s;
        var entry = json.feed.entry;
        //Check whether the API has given the feed content or not
        if(entry){
            for(var i=0; i<entry.length; i++){
                var newentry = entry[i];
                //First we fetch the link with attr rel=alternate
                var newlink = newentry.link;
                var url = '';
                for(var k=0; k<newlink.length; k++){
                    if(newlink[k].rel=='alternate') {
                        url = newlink[k].href; //Done locating the URL
                        break;
                    }
                }
                //Now we fetch the title
                var title = newentry.title.$t;
				
				//Fetch date (NC addition)
				var date = newentry.published.$t;
                
                //Now its time to get the first image of the post
                var newcontent=('content'in newentry)?newentry.content.$t:newentry.summary.$t; //To use this having full post feed enabled is recommended! Also using summary (which is to by default to be done when thumbnail is disabled) will not fetch any image and the default one will be used instead!
                a=newcontent.indexOf("<img");
                b=newcontent.indexOf("src=\"",a);
                c=newcontent.indexOf("\"", b+5);
                d=newcontent.substr(b+5,c-b-5); //5 is the character count of the src=" We need to have subsrt after this and upto the first occurance of " which has an index c and character length c-b-5! Now that was cool isn't it ;)
                var newimage = (a!=-1 && b!=-1 && c!=-1 && d!="") ? d : op.defImg; //If the indexOf does not return -1 and the image string is not null then we make that image URL else we use the default image
                
                //Call the append function to append the element inside the mainUl
                mainUlappender(title,date,url,newimage);
                if(loadRemove=="recent" && i==entry.length-1){
                    $('#iTgSwashata',div).remove(); //We remove the loading div when the entries become equal!
                }
                else if(loadRemove=='filtered' && ajaxLooper==op.tag.length-1 && i==entry.length-1) {
                    $('#iTgSwashata',div).remove(); //For the AJAX Loop
                }
            }
        }
    }
    
    //Appender Function called from inside the SpeedLoader
    var mainUlappender = function(title,date,url,image) {
        //We shall first get the all the li elements inside of our mainUl and match the URL to check for pre-existance
        var checkList = $('li',mainUl);
        for(var j=0;j<checkList.length;j++) {
            var a = $('a', checkList.eq(j) );
            if (a.attr('href')==url) { //Does the URL exist before?
                return; //YES: So Gives a null value to this function and appending stops!
            }
        }
        //If not returned a null value then continue to 
        var insider = '<li><a'+(op.aClass?' class="'+op.aClass+'"':'')+' href="'+url+'" title="'+op.aPermaTitle+' '+title+'">'+(op.imgEna? '<img class="'+op.imgClass+'" height="'+op.thumbH+'" width="'+op.thumbW+'" src="'+image+'" />':'')+'<span class = "title_link">'+title+'<br /><span class = "date" title = "'+date+'">'+date+'</span></span></a></li>';
        mainUl.append(insider); //And the insiderLi adppended to the mainUl
    }
    
    //Function initiator! We shall call this through the document.ready or windows.load
    var initSpeedLoader = function() {
        
        //I shall remove the container innerHTML and will append another div with that content! Then will remove that when the execution is finished!
        div.html('');
        $('<div id="iTgSwashata">'+loadContent+'</div>').appendTo(div); //The advantage is when looping for Tags the loader will be appended and removed for each loop!
        
        //Append the ul to the div
        mainUl = $('<ul class="'+op.ulClass+'"/>').appendTo(div);
		
		blogLink = $('<span><a href = "' + op.BlogURL + '">Visit our blog</a></span>').appendTo(div);
        
        //If image thumbnail is enabled then we will use Default feed option, else we shall be using summary to speed things up and save bandwidth
        var FeedURL=(op.imgEna)? '/feeds/posts/default':'/feeds/posts/summary';
        
        //Recent posts
        if(op.tag.length==0) {
            $.ajax({
                url:op.BlogURL+FeedURL,
                data:{'max-results':op.maxPost,'alt':'json-in-script'},
                success:function(data,status){speedLoader(data,status,'recent',0);},
                dataType:'jsonp',
                cache:true
                });
        }
        //Filter posts using Tags
        else {
            for(var s=0; s<op.tag.length; s++) {
                $.ajax({
                    url:op.BlogURL+FeedURL,
                    data:{'category':op.tag[s],'max-results':op.maxPost,'alt':'json-in-script'},
                    dataType:'jsonp',
                    success:function(data,status){speedLoader(data,status,'filtered',count);count++},
                    cache:true
                });
            }
        }
    }
    
    //Finally call the function according to the options set
    if(op.onLoad) $(window).load(initSpeedLoader);
    else $(document).ready(initSpeedLoader);
    
}

