//Author: Steve Tomlin
//Date: 2009 07 29
//v:1
//requires
    //pjquery
    //document.domain = 'handbag.com'
    //var serverUrl = "http://community.handbag.com/ver1.0/Direct/Process";
    //script src="http://community.handbag.hearststaging.co.uk/ver1.0/Direct/DirectProxy"

    //html

//var $j = ($j)?$j:$;
function ClassPluckMostRecent(objContainer,intOutputCount,strDivClass,isDate){
    this.objContainer = objContainer;
    this.intOutputCount = intOutputCount;
    this.arrContentTypes = ['Discussion','BlogPost','Persona','UserPhoto'];
    this.arrPluckObj = new Array();
	this.arrContentTypeReturned = new Array();
    this.strDivClass = strDivClass;
    this.isDate = isDate;
    this.objTimer = null;
    this.isLockAdd = false;
    this.init = function(){
        for(var i=0; i < this.arrContentTypes.length;++i){
            this.insertFromPluck(this.arrContentTypes[i]);
        }
    }
    this.insertFromPluck = function(strContentType){
        var objInst = this;
        var requestBatch = new RequestBatch();
        var intDayAge = 15;
        var intCountPerContentType = 2;//(this.intOutputCount - 2);//3
        var discoveryAction = new DiscoverContentAction([ ],[ ],[ ],new Activity("Recent"), new ContentType(strContentType), intDayAge,intCountPerContentType);
        requestBatch.AddToRequest(discoveryAction);
		if(typeof console!='undefined'){if(typeof console.debug!='undefined'){console.debug('requestBatch.BeginRequest('+serverUrl+', function(ResponseBatch)');}};        
		requestBatch.BeginRequest(serverUrl, function(responseBatch){
            if(typeof console!='undefined'){if(typeof console.debug!='undefined'){console.debug('strContentType = ' + strContentType);console.debug(responseBatch);}}
            objInst.add(strContentType,responseBatch.Responses[0].DiscoverContentAction.DiscoveredContent);
        });
    }
    this.add = function(strContentType,arr){
        if(!this.isLockAdd){//prevent further looping and adding to array if the maxium count has already been reached.
            //this.arrPluckObj.concat(arr);
            //convert emulated array into an actual array so that we can use the sort method
			this.arrContentTypeReturned[this.arrContentTypeReturned.length] = strContentType;
            for(i = 0; i < arr.length;++i){
				arr[i].contentType = strContentType;
                this.arrPluckObj[this.arrPluckObj.length + i] = arr[i];
            }
            if(this.arrContentTypeReturned.length == this.arrContentTypes.length){
                this.isLockAdd = true;
                this.output();
            }
        }
    }
    this.output = function(){
        //if(typeof console!='undefined'){
         //   console.debug('array before being ordered = ');
          //  console.debug({arr:this.arrPluckObj});
        //}

        var arrObj = this.orderByDate([].concat(this.arrPluckObj),false,new Array('LastUpdated','PostDate','CreatedOn'));

        if(typeof console!='undefined'){
            console.debug('order by date in desc order =');
            console.debug({'arrObj':arrObj});
        }
        //if(typeof console!='undefined'){		
		//	console.debug('typeof arrObj = '+typeof arrObj);
		//	console.debug('arrObj.length = '+arrObj.length);
		//	console.debug('arrObj[0] = '+arrObj[0]);			
		//	console.debug('arrObj[0].contentType = ' + arrObj[0].contentType+'\nthis.intOutputCount = ' + this.intOutputCount);
		//}		
		var strHtmlOutput = this.objContainer.innerHTML;
		var intMod =0;
		for(var i=0; !(intMod >= this.intOutputCount) && i < arrObj.length;++i){
			//console.debug('i = '+i);				
			if(arrObj[i]){	//due to the nature of ajax, the array items
                if(this.strDivClass==''){
                    strClass=((intMod%2)==0)?"onelement":"secondlement";
                }else{
                    strClass = ''+this.strDivClass;
                }
				switch(arrObj[i].contentType){
					case 'Discussion':	
						strUserUrl = arrObj[i].LastPostBy.PersonaUrl;
						strUserImg = arrObj[i].LastPostBy.ImageUrl
						strUserId = arrObj[i].LastPostBy.DisplayName;
						strContentTypeText = 'posted a new discussion in';
						strItemTitle = arrObj[i].DiscussionTitle;
						strItemUrl = arrObj[i].DiscussionUrl;					
						strDate = arrObj[i].LastUpdated;										
						break;
					case 'BlogPost':	
						strUserUrl = arrObj[i].PostAuthor.PersonaUrl;
						strUserImg = arrObj[i].PostAuthor.ImageUrl;
						strUserId = arrObj[i].PostAuthor.DisplayName;	
						strContentTypeText = 'blogged about';	
						strItemTitle = arrObj[i].PostTitle;
						strItemUrl = arrObj[i].Url;					
						strDate = arrObj[i].PostDate;						
						break;
					case 'Persona':	
						strUserUrl = arrObj[i].PersonaUrl;
						strUserImg = arrObj[i].ImageUrl
						strUserId = arrObj[i].DisplayName;
						strContentTypeText = 'updated their profile';
						strItemTitle = '';
						strItemUrl = '';					
						strDate = arrObj[i].LastUpdated;					
						break;	
					case 'UserPhoto':	
						strUserUrl = arrObj[i].Author.PersonaUrl;
						strUserImg = arrObj[i].Author.ImageUrl;
						strUserId = arrObj[i].Author.DisplayName;
						strContentTypeText = 'updated their photo gallery with';
						strItemTitle = arrObj[i].Title;
						strItemUrl = arrObj[i].PhotoUrl;
						strDate = arrObj[i].CreatedOn;			
						break;						
				}			
				strHtmlOutput +=this.buildHTML(strClass,strUserUrl,strUserImg,strUserId,strItemUrl,strItemTitle,strDate,strContentTypeText);
				++intMod;
			}
		}
		this.objContainer.innerHTML += strHtmlOutput;				
    }
	this.buildHTML = function(strClass,strUserUrl,strUserImg,strUserId,strItemUrl,strItemTitle,strDate,strContentTypeText){
		var strHtmlOutput = '';
		strHtmlOutput+='<div class="'+strClass+'">\n';
			strHtmlOutput+='\t<div class="avatar">\n';
				strHtmlOutput+='\t\t<a href="'+strUserUrl+']"><img src="'+strUserImg+'"/></a>\n';
			strHtmlOutput+='\t</div>\n';
			strHtmlOutput+='\t<p class="wrap">\n';
				strHtmlOutput+='\t\t<span class="author"><a href="'+strUserUrl +'">'+strUserId+'</a></span>\n'
				strHtmlOutput+='\t\t<span class="action"> '+strContentTypeText+' </span>\n';
				if(strItemTitle!='' && strItemUrl!=''){strHtmlOutput+='\t\t<span class="subject"><a href="'+strItemUrl+'">'+strItemTitle+'</a></span>\n';}
			strHtmlOutput+='\t</p>\n';
            if(this.isDate){strHtmlOutput+='\t<div class="date">'+this.convertToUKDate(strDate)+'</div>\n';}
		strHtmlOutput+='</div>\n';
		return strHtmlOutput;
	}
	this.convertToUKDate = function(strDate){
		return strDate.replace(/^(\d+)(\/)(\d+)(\/.+)$/,'$3'+'$2'+'$1'+'$4');
	}
    this.orderByDate = function(arrOfObjects,isAsc,arrSortKeys){
        //if(typeof console!='undefined'){console.debug('orderByDate');}
        function prefixZero(){
		var arg = arguments;
            //if(typeof console!='undefined'){if(console.debug!='undefined'){
	//	    console.debug('arguments='+arg[0]+','+arg[1]+','+arg[2]+','+arg[3]+','+arg[4]+','+arg[5]);
	    //}}
            var str = '';
            for(var i=0; i < arg.length;++i){
	            str+=((''+arg[i]).length < 2)?'0' + arg[i]:arg[i];
	    }
            //convert to number so it can be sorted as number not string.
            //can't precede with a zero, or parseInt will return a complete 0
            if(str.indexOf('0')==0){
                str = '1' + str;
            }
            return parseInt(str);
        }
        function replaceDateToNumber($0,$1,$2,$3,$4,$5,$6,$7){
            //if(typeof console!='undefined'){
                //console.debug('$0 = ' + $0);
            //}
            var hr = ((''+$4) == '12' && $7 =='AM')?0:parseInt($4);//convert 12am to 0;
            hr = ($7=='PM')?(hr+12):hr;//convert 2pm to 14;
            hr = (hr)?hr:'0';
            // if number is a single number like 7, then prefix a 0 - 07.
                            //y,  m, d,hr, m, s
            //if(typeof console!='undefined'){
                //console.debug('($3,$1,$2,hr,$5,$6) = ' + $3+$1+$2+hr+$5+$6);
            //}
            return prefixZero($3,$1,$2,hr,$5,$6);
        }
        function compareDate(a,b){
            //if(typeof console!='undefined'){
               // console.debug('compareDate');
            //}
            //Test if SortKey exists or match first sortKey even if others exist in arrSortKeys
            var strSortKeyA = '';
            var strSortKeyB = '';
            for(i=0; i < arrSortKeys.length;++i){
                if(typeof a[arrSortKeys[i]]!='undefined'){
                    strSortKeyA = arrSortKeys[i];
                }
                if(typeof b[arrSortKeys[i]]!='undefined'){
                    strSortKeyB = arrSortKeys[i];
                }
            }
            //if(typeof console!='undefined'){
               // console.debug('strSortKey = ' + strSortKey);
            //}
            //replace date into a number 20090711185121
            // month, date, year, hr determined by am pm, min, sec, am or pm
            var regDateToNumber = /(\d+)\/(\d+)\/(\d+)\s*(\d+)\:(\d+)\:(\d+)\s*(\w{2})/;
            var aD = (''+a[strSortKeyA]).replace(regDateToNumber,function($0,$1,$2,$3,$4,$5,$6,$7){return replaceDateToNumber($0,$1,$2,$3,$4,$5,$6,$7)});
            var bD = (''+b[strSortKeyB]).replace(regDateToNumber,function($0,$1,$2,$3,$4,$5,$6,$7){return replaceDateToNumber($0,$1,$2,$3,$4,$5,$6,$7)});
            if(typeof console!='undefined'){
                if(console.debug!='undefined'){
                    console.debug('aD = ' + aD);
                    console.debug('bD = ' + bD);
                }
            }
            //number sort
            if(isAsc){
                return aD - bD;
            }else{
                return bD - aD;
            }
        }
        arrOfObjects.sort(compareDate);
        return arrOfObjects;
    }
    this.init();
}
