editIcon = '';
hideIcon = '';
showIcon = '';
rvrtIcon = '';
deleIcon = '';
Icones = new Array();

function form_submit() {

	location.href='/'+$('#search-user').val();
	return false;

}

function fallback() {
	renderProfiles();
	jQuery('#searching').css({'display' : 'none'});
	jQuery('#search-heading').css({'display' : 'none'});
	loadContent();
}

function endless(id,duration,val1,val2){

    	if (dis[id]) {
    		val = val1
    		dis[id]=0;
    	} else {
    		val = val2
    		dis[id]=1;
	}
	
	
	
	$(id).animate({
		left:val,
	},{
		easing: "linear",
		duration: duration,
		complete: function() {
			endless(id,duration,val1,val2);
		}
	});
};
dis = new Array();
dis['#cloud1']=0;
dis['#cloud2']=0;
dis['#cloud3']=0;

var days = 60; 

var doc = jQuery(document);
doc.ready(function () {
	endless('#cloud1',20000,'-=400px','+=400px');
	endless('#cloud2',13000,'-=200px','+=200px');
	endless('#cloud3',14000,'+=400px','-=400px');
	
	$('#bubble-tw').show();
	
	$('#twhois').bind('mouseover',function() {
		$("#main").stop();
		$('#main').animate({'marginTop':120},1000);
	});
	$('#twhois').bind('mouseout',function() {
		$("#main").stop();
		$('#main').animate({'marginTop':65},1000);
	});
	
	doc.bind('ident:update', statusUpdate);
	doc.bind('ident:update', headingUpdate);
	doc.bind('ident:error', displayError);

	//webAddress.elt = "#webaddress";
	//webAddress.startAnimate();
});  
 
		 
function startDemo(){
	ident.reset();
	$('.hidden').show();
	resetAllContent();
	//webAddress.stopAnimate();    

	jQuery('<h2 id="search-heading">Looking for social profiles</h2>').appendTo('#results');
	jQuery('<div id="searching"><img class="spinner" src="/img/loading.gif" alt="Loading" /></div>').appendTo('#results');
	rem = setTimeout('fallback()',15000);

	ident.search(url);
}
		 
function headingUpdate(){
	jQuery('#search-heading').html("Looking for social profiles - Found " + ident.identities.length);
}
		
var alertTimerId;


function statusUpdate(e, type) {
	if(type != null){
	    if(type == 'content-added')
		renderContent();
		    
	}
	clearTimeout (alertTimerId);
	alertTimerId = setTimeout ("delayedStatusUpdate()", 500);
} 
		
asd=0;		
csd=0;
function delayedStatusUpdate(){
	if(ident.isSearching()){
		if (csd == 0) {
			jQuery('#searching').html('<img class="spinner" src="/img/loading.gif" alt="Loading" />');
			csd ++
		}
	}else{
		
		renderProfiles();
		jQuery('#searching').css({'display' : 'none'});
		jQuery('#search-heading').css({'display' : 'none'});
		loadContent();
		if (asd==0){
			jQuery.post("/ajax/cache.php", { content:  jQuery('#profiles').html(), username : stored, nonce : time_nonce, type:1 } );
			clearTimeout(rem);
			asd=1;
		} else if (asd == 1) {
			jQuery.post("/ajax/cache.php", { content:  jQuery('#stream').html(), username : stored, nonce : time_nonce2, type:2 } );
			asd =2;
			if (function_exists('twEdit'))
				twEdit();
		}
	}
}

function loadContent(){ 
	ident.findContent('twitter.com', 'Status', 'hAtom' );
	ident.findContent('ident.ca', 'Status', 'hAtom' );  
	ident.findContent('flickr.com', 'Images', 'Atom' ); 
	ident.findContent('picasaweb.google.com', 'Images', 'Rss' );
	ident.findContent('del.icio.us', 'Bookmarks', 'Rss'); 
	ident.findContent('upcoming.yahoo.com', 'Events', 'Rss' );
	ident.findContent('last.fm', 'Activity', 'Rss' );
	ident.findContent('ffffound.com', 'Images', 'Rss' );
	ident.findContent('tumblr.com', 'Lifestream', 'Rss' );
	ident.findContent('backtype.com', 'Activity', 'Rss' );
	ident.findContent('vimeo.com', 'Video', 'Rss' );
}

		
		 
		function renderProfiles(){
		
		 
		    jQuery('#profiles').html('');  
		        
		    var hCard = ident.combinedProfile;

		    var profile = jQuery('<div class="profile"></div>').appendTo('#profiles');
		    var titlegroup = jQuery('<div class="title-group"></div>').appendTo(profile); 
		    
		    if( hCard.photo ) 
		        if(hCard.photo.length > 0 )
		            renderPhoto(profile,hCard.photo[0].value); 
		    
		    if(preHide['fn']) {
		    	Iconz = editIcon+showIcon+rvrtIcon;
		    	Icones['fn'] = editIcon+showIcon+rvrtIcon;
		    } else {
		    	Iconz = editIcon+hideIcon+rvrtIcon;
		    	Icones['fn'] = editIcon+hideIcon+rvrtIcon;
		    }
		    if (preEdit['fn']) {
		  	  jQuery('<div class="fn">' + preEdit['fn'] +   Iconz+'</div>').appendTo(titlegroup);
		    } else {
			    if(ident.topFormattedName() != '')
				jQuery('<div class="fn">' + ident.topFormattedName() +   Iconz+'</div>').appendTo(titlegroup);
			    else 
			    	if (typeof(hCard.fn)=='object')
					jQuery('<div class="fn">' + hCard.fn.value +   Iconz+'</div>').appendTo(titlegroup); 
				else
					jQuery('<div class="fn">' + hCard.fn +   Iconz+'</div>').appendTo(titlegroup); 
		    }
		    
		    if(preHide['title']) {
		    	Iconz = editIcon+showIcon+rvrtIcon;
		    	Icones['title'] = editIcon+showIcon+rvrtIcon;
		    } else {
		    	Iconz = editIcon+hideIcon+rvrtIcon;
		    	Icones['title'] = editIcon+hideIcon+rvrtIcon;
		    }
		    if (preEdit['title']) {
		  	   jQuery('<div class="title">' + preEdit['title'] +   Iconz+'</div>').appendTo(titlegroup)
		    } else {                
			    if( hCard.title ) 
			       if(hCard.title.length > 0 )
				        jQuery('<div class="title">' + hCard.title[0].value +   Iconz+'</div>').appendTo(titlegroup)
		    }
		        
		    /*if( hCard.role )
		        jQuery('<div class="role">' + hCard.role.value +  '</div>').appendTo(titlegroup); */
		    
		    if(preHide['organization-name']) {
		    	Iconz = editIcon+showIcon+rvrtIcon;
		    	Icones['organization-name'] = editIcon+showIcon+rvrtIcon;
		    } else {
		    	Iconz = editIcon+hideIcon+rvrtIcon;
		    	Icones['organization-name'] = editIcon+hideIcon+rvrtIcon;
		    }   
		    if (preEdit['organization-name']) {
		  	  jQuery('<div class="organization-name">' + preEdit['organization-name'] +  Iconz+'</div>').appendTo(titlegroup); 
		    } else {                
			    if( hCard.org ) 
				if(hCard.org.length > 0 )
				    if(hCard.org[0]['organization-name'])
				        jQuery('<div class="organization-name">' + hCard.org[0]['organization-name'] +   Iconz+'</div>').appendTo(titlegroup); 

		    }
		    
		    if(preHide['note']) {
		    	Iconz = editIcon+showIcon+rvrtIcon;
		    	Icones['note'] = editIcon+showIcon+rvrtIcon;
		    } else {
		    	Iconz = editIcon+hideIcon+rvrtIcon;
		    	Icones['note'] = editIcon+hideIcon+rvrtIcon;
		    }
		    	
		    if (preEdit['note']) {
		    	if (preEdit['note'].toString().length > 200) {
		  	 		jQuery('<div class="note">' + ident.sentenceTruncate(preEdit['note'],5).substr(0,200)+' <span id="tipped">[...]</span> ' +  Iconz+'</div>').appendTo(titlegroup);  
		  	 		$('#tipped').qtip({
					   content: ident.sentenceTruncate(preEdit['note'],5).substr(0,400),
					   show: 'mouseover',
					   hide: 'mouseout',
					   position: {
						  corner: {
						 target: 'topRight',
						 tooltip: 'bottomLeft'
						  }
					   },
					   style: { 
					     width:300,
						 textAlign:'left',
						 name:'twhois'
					 	}
					})
		  	 	} else {
		  	 		jQuery('<div class="note">' + ident.sentenceTruncate(preEdit['note'],5).substr(0,200)+  Iconz+'</div>').appendTo(titlegroup);  
		  	 	}
		  	 	
		    } else {
			    if( hCard.note ){  
			      if( hCard.note.length > 0 ){
			      	if (hCard.note[0].value.toString().length > 200) { 
				   		jQuery('<div class="note">' + ident.sentenceTruncate(hCard.note[0].value,5).substr(0,200)+' <span id="tipped">[...]</span> ' + Iconz+'</div>').appendTo(titlegroup);  
				   		$('#tipped').qtip({
						   content: ident.sentenceTruncate(hCard.note[0].value,5).substr(0,400),
						   show: 'mouseover',
						   hide: 'mouseout',
						   position: {
							  corner: {
							 target: 'topRight',
							 tooltip: 'bottomLeft'
							  }
						   },
						   style: { 
						    width:300,
						    textAlign:'left',
							name:'twhois'
							   }
						})
				   	} else {
				  		jQuery('<div class="note">' + ident.sentenceTruncate(hCard.note[0].value,5).substr(0,200)+ Iconz+'</div>').appendTo(titlegroup);
				  	}
			      }
			    }
		    }
		      
		    if( hCard.adr ) 
		    {
		        var adr = jQuery('<div class="adr"></div>').appendTo('#right-profile');                
		        for (var x = 0; x < hCard.adr.length; x++) {
		            var address = hCard.adr[x];
		            if( address['extended-address'] )
		                renderArray(adr,address['extended-address']);
		                
		            if( address['street-address'] )
		                renderArray(adr,address['street-address']);
		                
		            if(preHide['locality']) {
			    	Iconz = editIcon+showIcon+rvrtIcon;
			    	Icones['locality'] = editIcon+showIcon+rvrtIcon;
			    } else {
			    	Iconz = editIcon+hideIcon+rvrtIcon;
			    	Icones['locality'] = editIcon+hideIcon+rvrtIcon;
			    }
		            if (preEdit['locality']) {
				  	   jQuery('<div class="locality">' +preEdit['locality']  +  Iconz+'</div>').appendTo(adr); 
					} else {   
				        if( address.locality )
				            jQuery('<div class="locality">' + address.locality  +  Iconz+'</div>').appendTo(adr); 
				    }
		                
		            if( address.region )
		                jQuery('<div class="region">' + address.region +  '</div>').appendTo(adr); 
		                
		            if( address['postal-code'] )
		                jQuery('<div class="postal-code">' + address['postal-code'] +  '</div>').appendTo(adr); 
		            
		           if(preHide['country-name']) {
			    	Iconz = editIcon+showIcon+rvrtIcon;
			    	Icones['country-name'] = editIcon+showIcon+rvrtIcon;
			    } else {
			    	Iconz = editIcon+hideIcon+rvrtIcon;
			    	Icones['country-name'] = editIcon+hideIcon+rvrtIcon;
			    }
		            if (preEdit['country-name']) {
				  	  jQuery('<div class="country-name">' + preEdit['country-name']  +  Iconz+'</div>').appendTo(adr);         
					} else {      
				        if( address['country-name'] )
				            jQuery('<div class="country-name">' + address['country-name']  +  Iconz+'</div>').appendTo(adr);         
				    }         
		        }
		    }  
		          
	   
		    if( hCard.tel )
		        renderItemArray(profile,hCard.tel);   
		                   
		    if( hCard.email != '' )
		        renderItemArray(titlegroup,hCard.email,'','email'); 
		   
		    if(preHide['url']) {
		    	Iconz = editIcon+showIcon+rvrtIcon;
		    	Icones['url'] = editIcon+showIcon+rvrtIcon;
		    } else {
		    	Iconz = editIcon+hideIcon+rvrtIcon;
		    	Icones['url'] = editIcon+hideIcon+rvrtIcon;
		    }
		    if (preEdit['url']) {
		  	 jQuery('<div class="url"><a href="' + preEdit['url'] +  '" rel="nofollow">' + preEdit['url'] +  '</a>'+Iconz+'</div>').appendTo(titlegroup); 
		    } else {      
			    if(ident.topDeclaredProfileUrl() != '')
				jQuery('<div class="url"><a href="' + ident.topDeclaredProfileUrl() +  '" rel="nofollow">' + ident.topDeclaredProfileUrl() +  '</a>'+Iconz+'</div>').appendTo(titlegroup); 
			    else 
				renderItemArray(profile,hCard.url);
		    }
		                  
	  
		    if(ident.identities.length > 0){

		    	 var div = jQuery('<div class="profile-lists"></div>').appendTo('.profile'); 
		         var ul = jQuery('<ul class="profile-list"></ul>').appendTo(div); 
		         initX = 0;
		         for (var y = 0; y < preServices.length; y++) {
					 if (y>18)
						continue;
					
					 if (y == 10)
		         		var ul = jQuery('<ul class="profile-list"></ul>').appendTo(div); 
					 
					 if(preServices[y].username != '')
		                jQuery('<li class="db" id="linkdb_'+y+'"><a href="' + preServices[y].profileUrl  + '" rel="nofollow"><img width="16" class="icon" src="' + preServices[y].iconUrl.toLowerCase() +  '" alt="' + preServices[y].name +  '" />' + preServices[y].name + '</a> <span class="username">(' + preServices[y].username + ')</span>'+deleIcon+'</li>').appendTo(ul);   
		             else
		                jQuery('<li class="db" id="linkdb_'+y+'"><a href="' + preServices[y].profileUrl  + '" rel="nofollow"><img width="16" class="icon" src="' + preServices[y].iconUrl.toLowerCase() +  '" alt="' + preServices[y].name +  '" />' + preServices[y].domain + '</a>'+deleIcon+'</li>').appendTo(ul); 
		         
					 	
					 initX++;
				 }
		         for (var c = initX; c < ident.identities.length; c++) {
					x=(c-initX);
		         	if (c>18)
		         		continue
		         	if (c == 10)
		         		var ul = jQuery('<ul class="profile-list"></ul>').appendTo(div); 
		            if(ident.identities[x].name != '')
		                jQuery('<li><a href="' + ident.identities[x].profileUrl  + '" rel="nofollow"><img width="16" class="icon" src="/ident/' + ident.identities[x].iconUrl.toLowerCase() +  '" alt="' + ident.identities[x].iconUrl.toLowerCase() +  '" />' + ident.identities[x].name + '</a> <span class="username">(' + ident.identities[x].username + ')</span></li>').appendTo(ul);   
		            else
		                jQuery('<li><a href="' + ident.identities[x].profileUrl  + '" rel="nofollow"><img width="16" class="icon" src="/ident/' + ident.identities[x].iconUrl.toLowerCase() +  '" alt="' + ident.identities[x].iconUrl.toLowerCase() +  '" />' + ident.identities[x].domain + '</a></li>').appendTo(ul); 
		         }
		     } 
		             
		}
		
		
		// Sorts objects into order using the name property
		    function sortByDate (a, b) {
			var x = a['published-datetime'];
			var y = b['published-datetime'];
			return ((x > y) ? -1 : ((x < y) ? 1 : 0));
		    };
		
		
		function renderContent(){
	   
		    jQuery('#results').html('');
		    jQuery('#searching').css({'display' : 'none'});
		    jQuery('#search-heading').css({'display' : 'none'});
		    
		    /*
		    // Refresh button for content - needs more work
		    
		    var refresh = jQuery('<input id="refresh" type="button" value="Refresh lifestream" />').appendTo('#results');
		    jQuery(refresh).click(function () {
		        // Forced clear down of content data
		        jQuery('#results').html('');
		        ident.entries = new Array();
		        ident.events = new Array();
		        ident.relCollection = new Array();
		        ident.history = new Array();

		    });
		    */

		 // Sort the collection of domains into order  
        	ident.entries.sort(sortByDate);   

		    // Create of cutoff date
		    var cutoff = new Date();
		    cutoff.setDate(cutoff.getDate()-days);
		     for (var i = 0; i < ident.entries.length; i++) {			if ($('#stream > .item').length < 5) {
		         if(ident.entries[i]['published-datetime'] > cutoff)
		         {

		            var div = jQuery('<div class="item"></div>').appendTo('#stream');
		            jQuery('<img width="16" alt="' + ident.entries[i].name + '" class="icon" src="/ident/ident/icons/' + ident.entries[i].name.replace(/[.,-, ]/g,'').toLowerCase()  +  '.png" />').appendTo(div);   
		            var item = ident.entries[i];


		            switch (item.type){
		                case 'Status':
		                    renderStatus( item, div );
		                    break;
		                case 'Images':
		                    renderItem( item, div );
		                    break;
		                case 'Bookmarks':
		                    renderBookmarks( item, div );
		                    break;    
		                case 'Events':
		                    renderEvents( item, div );
		                    break;
		               case 'Activity':
		                    renderActivity( item, div );
		                    break;

		                default:
		                    renderItem( item, div )    
		            }
		        }}
		    }
		}
		
		
		// Renders a standard feed item
		function renderItem( item, div ){
		    jQuery(div).addClass( 'standard' );
		
		    if(item['entry-title']){
		        if(item.link)
		            jQuery('<div class="entry-title"><a href="' + item.link + '"  rel="nofollow">' + item['entry-title'] + '</a></div>').appendTo( div );
		        else
		            jQuery('<div class="entry-title">' + item['entry-title'] + '</div>').appendTo( div );
		    }
		    
		    /*if(item['entry-content']){
		        if(item['entry-title'] != item['entry-content'])
		            jQuery('<div class="entry-content">' + addHyperlinks(item['entry-content']) + '</div>').appendTo( div );
		    }*/
		    
		    /*if(item['published-datetime'])
		        jQuery('<div class="published">' + item['published-datetime'].toLocaleDateString() + ' - ' + item['published-datetime'].toLocaleTimeString() + '</div>').appendTo(div);*/
		     
		}
		
		 
		// Renders a status item Twitter / Identi.ca etc
		function renderStatus( item, div ){
		    jQuery(div).addClass( 'status' );
		
		    var body = '' 
		    if(item['entry-title'])
		        body = item['entry-title'];
		    else
		       body = item['entry-content'];    
		    
		    body = addHyperlinks( body );   
		    body = addStatusAccountLinks( body, 'http://' + item.domain + '/' );
		      
		    
		    jQuery('<div class="entry-title">' + body + '</div>').appendTo( div );
		   
		    /*if(item['published-datetime'])
		        jQuery('<div><a class="published" href="' + item.bookmark.link + '">' + item['published-datetime'].toLocaleDateString() + ' - ' + item['published-datetime'].toLocaleTimeString() + '</a></div>').appendTo(div);*/
		     
		}
		
		
		function renderBookmarks( item, div ){
		    renderItem( item, div );
		    jQuery(div).addClass( 'bookmark' );
		}
		
		
		function renderEvents( item, div ){
		    renderItem( item, div );
		    jQuery(div).addClass( 'event' );
		}
		
		
	   function renderActivity( item, div ){
		    renderItem( item, div );
		    jQuery(div).addClass( 'activity' );
		}
		   

		function addHyperlinks( text ){
		    if(ident.isArray(text)){
		        if(text.length > 0){
		            text = text[0];
		        }else{
		            text= '';
		        }
		    }
		       
		    if( text != ''){
		        parts = text.split(' ');
		        for(var x = 0; x <= parts.length-1; x++){
		            if(parts[x].indexOf('http://') == 0)
		                parts[x] = '<a href="' + parts[x] + '"  rel="nofollow">' + parts[x] + '</a>';
		        }
		        text = parts.join(' ');
		    }
		    return text;
		}
		
		
		function addStatusAccountLinks( text, url ){
		    if(ident.isArray(text))
		        text = text[0];
		        
		    if( text != ''){
		        parts = text.split(' ');
		        for(var x = 0; x <= parts.length-1; x++){
		            if(parts[x].indexOf('@') == 0){
		                if( parts.length > x ){
		                    parts[x+1] = '<a href="'+ url + parts[x+1] + '"  rel="nofollow">' + parts[x] + parts[x+1] + '</a>';
		                    parts[x] = '';
		                }
		            }
		        }
		        text = parts.join(' ');
		    }
		    return text;
		}
		
		
		function renderArray( element, array, prefix, classname ){
		    if(ident.isArray(array)){
		        for (var i = 0; i < array.length; i++) {
		            if( prefix )
		                jQuery('<div class="' + classname +'">' + prefix + ': ' + array[i] +  '</div>').appendTo(element); 
		            else
		                jQuery('<div class="' + classname +'">' + array[i] +  '</div>').appendTo(element);   
		        }
		    }
		 }
		 
		 
		 function renderItemArray( element, array, prefix, classname ){
		    for (var i = 0; i < array.length; i++) {
		        var type = '';
		        if(array[i].type != '')
		            type = ' (' + array[i].type + ')';
		        if (classname != 'email') {
				if( prefix )
				        jQuery('<div class="' + classname +'">' + prefix + ': ' + array[i].value  + type + '</div>').appendTo(element); 
				else
					jQuery('<div class="' + classname +'">' + array[i].value + '</div>').appendTo(jQuery('.title-group'));  
			} else {
				jQuery('<div class="' + classname +'"><a href="mailto:spam_'+array[i].value+'>"'+array[i].value+'</a></div>').appendTo(element); 
			}
		             
		    }
		 }
		 
		 
		function renderPhoto( element, url ){
			jQuery('<div id="follow-on-twitter" onclick="location.href=\'http://twitter.com/'+TWuser+'\'">Follow on Twitter</div>').appendTo(element); 
		    jQuery('<div id="right-profile"><img class="photo prof" src="' + url +  '" alt="Avatar"/></div>').appendTo(element); 

		}
		
		
		function displayError(e, type){
		    resetAllContent();
		    jQuery('<h2 id="search-heading"></h2>').appendTo('#results');
		    jQuery('<div id="searching"></div>').appendTo('#results');
		    
		    jQuery('#searching').html('<h2 class="error">' + type + '</h2>');
		    jQuery('#searching').css({'display' : 'block'});
		    jQuery('#search-heading').css({'display' : 'none'});
		 }

		 

		// Clear the debug html
		function resetContent(){
		    //jQuery('#results').html('');
		}
		
		    // Clear the debug html
		function resetAllContent(){
		    jQuery('#profiles').html('');
		    jQuery('#results').html('');
		    jQuery('#stream').html('');
		}
		
function function_exists (function_name) {
    if (typeof function_name == 'string'){
        return (typeof this.window[function_name] == 'function');
    } else{
        return (function_name instanceof Function);
    }
}
		
