g_CTDragStarted = false;

/********* XPI events *********/

function sendNewCTCancelEvent( _short_url ) {
	sendEvent( "GSCTNewCTCancelEvent", _short_url );
}

function sendAddNewTabEvent( _short_url ) {
	sendEvent( "GSCTAddNewTabEvent", _short_url );
}

function sendCancelNewTabEvent( _short_url ) {
	sendEvent( "GSCTCancelNewTabEvent", _short_url );
}

function sendEditCTTitleEvent( _short_url, _title ) {
	sendEvent( "GSCTEditCTTitleEvent", _short_url, "title", _title );
}

function sendClickTabEvent( _short_url, _url, _id ) {
	if ( g_CTDragStarted == false ) {
		sendEvent( "GSCTClickTabEvent", _short_url, "url", _url, "id", _id );
	}
	g_CTDragStarted = false;
}

function sendEvent( _event_name,  _short_url, _extra_key1, _extra_value1, _extra_key2, _extra_value2 ) {
	var el = createPlaceHolderElement();
	el.setAttribute( "short_url", _short_url );
	if ( _extra_key1 !== undefined ) { 
		el.setAttribute( _extra_key1, encodeURIComponent(_extra_value1) ); 
	}
	if ( _extra_key2 !== undefined ) { 
		el.setAttribute( _extra_key2, encodeURIComponent(_extra_value2) ); 
	}
	el.setAttribute( "event_name", _event_name ); 
	document.documentElement.appendChild( el );
  var evt = document.createEvent( "Events" );
	evt.initEvent( _event_name, true, false );
	el.dispatchEvent( evt );
}

function createPlaceHolderElement() {
	var el = $( "XPIPlaceholderElement" );
	if ( el != null ) { el.parentNode.removeChild( el ); }
	el = document.createElement( "XPIPlaceholderElement" );
	return( el );
}

/********* Cluster Index page => Edit title *********/

function observeTitleField( _short_url, _form_authenticity_token ) {
	$('title_cancel_button').observe('click', function(event) {
		Event.stop(event);
		makeAjaxCall( _short_url, "cancel_title_edit", _form_authenticity_token );
	});	
	$('title_ok_button').observe('click', function(event) {
		Event.stop(event);
		makeAjaxCall( _short_url, "save_title_edit", _form_authenticity_token );
	});	
	$('title').observe('keypress', function(event) {
  	if( event.keyCode == Event.KEY_RETURN ) {
      Event.stop(event);
			makeAjaxCall( _short_url, "save_title_edit", _form_authenticity_token );
    }
	});	
}

function makeAjaxCall( _short_url, _path, _form_authenticity_token ) {
	new Ajax.Request( "/" + _short_url + "/" + _path, 
		{ asynchronous:true, 
			evalScripts:true,
			parameters:'authenticity_token=' + encodeURIComponent(_form_authenticity_token) + "&title=" + encodeURIComponent($('title').value)
		} );
}

/********* Cluster Index page => Edit description *********/

function observeDescriptionField() {
	$('description').observe('keyup', function(event) {
		updateCharacterCounter();
	});	
}

function updateCharacterCounter() {
	var nr_chars = 150 - $('description').value.length;
	var msg;
	if ( nr_chars < 0 ) {
		msg = "<span style='color:red'>" + nr_chars + "</span>";
		$('desc_save_disabled').show();
		$('desc_save_enabled').hide();
	} else {
		msg = nr_chars;
		$('desc_save_disabled').hide();
		$('desc_save_enabled').show();
	}
	$('charactercounter').innerHTML = msg; 
}

/********* Cluster Index page *********/

function observeTabClick( _short_url, _url, _id ) {
	$('link_'+_id).observe('click', function(event) {
		sendClickTabEvent( _short_url, _url, _id );
	});	
}

function observeBigPlusClick( _short_url ) {
	$('bigplus').observe('click', function(event) {
		sendAddNewTabEvent( _short_url ); 
	});	
}

function pollForThumbnails( _short_url, _form_authenticity_token, _link_ids, _link_indices ) {
	var thumbs = $$("img.thumbnailimage");
	// Iterate all thumbnail images
	var linkIDs = "";
	var linkIndices = "";
	thumbs.each( function(thumb) {
		thumb.src.sub(/throbber/, function(match) {
			// Get link ID
			linkIDs += thumb.readAttribute("id").gsub("thumbnail_","") + " ";
			// Get link index
			var idx = thumb.readAttribute("rel");
			if (idx==null || idx=='image_src') { idx=1; }
			linkIndices += idx + " ";
		} );
	} );
	// Still thumb(s) needing refreshing?
	if ( linkIDs != "" ) {
		new Ajax.Request( "/" + _short_url + "/update_thumbnails", 
											{ asynchronous:true, 
												evalScripts:true,
												parameters:'authenticity_token=' + encodeURIComponent(_form_authenticity_token) + 
												"&short_url=" + _short_url + 
												"&link_ids=" + linkIDs + "&link_indices=" + linkIndices } );
	}
	setTimeout( "pollForThumbnails('"+_short_url+"','"+_form_authenticity_token+"')", 2000 );
}

function sendRefreshThumbnailEvent( _short_url, _form_authenticity_token, _url, _link_id ) {
	$('refresh_thumb_'+_link_id).hide();
	$('refresh_thumb_pending_'+_link_id).show();
	new Ajax.Request( "/" + _short_url + "/set_thumbnail_to_zzz", 
										{ asynchronous:true, 
											evalScripts:true,
											parameters:'authenticity_token=' + encodeURIComponent(_form_authenticity_token) + 
											"&short_url=" + _short_url + 
											"&link_id=" + _link_id,
											onComplete:sendRefreshThumbnailEventToXPI(_short_url,_url,_link_id) } );
}

function sendRefreshThumbnailEventToXPI( _short_url, _url, _link_id ) {
	$('thumbnail_'+_link_id).src = "http://clusterthumbs.s3.amazonaws.com/throbber_zzz.jpg";
	sendEvent( "GSCTRefreshThumbnailEvent", 
						 _short_url, 
						 "url", encodeURIComponent( _url ), 
						 "link_id", _link_id );
}

function sendRefreshThumbnailsEvent( _short_url, _urls, _link_ids ) {
	sendEvent( "GSCTRefreshThumbnailsEvent", _short_url, "urls", _urls, "link_id", _link_ids );
}
 
function observeDeleteButton( _short_url, _form_authenticity_token, _link_id, _title ) {
	$('delete_link_'+_link_id).observe('click', function(event) {
		Event.stop(event);
		if ( confirm('Are you sure you want to delete '+decodeURIComponent(_title)+'?') ) {
			new Ajax.Request( "/" + _short_url + "/delete_link", 
				{ asynchronous:true, 
					evalScripts:true,
					parameters:'authenticity_token=' + encodeURIComponent(_form_authenticity_token) + "&link_id=" + _link_id,
					onComplete:sendEvent( "GSCTRemoveTabEvent", _short_url, "link_id", _link_id )
				} );
		}
	});	
}

function showServicePanel( _short_url, _serviceName ) {
	sendEvent( "GSCTShowServiceEvent", _short_url, "service", _serviceName );
}

/********* Prototips *********/

function bigPlusTip() {
	//Event.observe( window, 'load', function() {
		new Tip( 'bigplus', 
						 $('tip_bigplus'),
						 { stem: 'topLeft',  
						   hook: { tip: 'topLeft', mouse: true }, 
						   offset: { x: 0, y: 10 }, 
						   width: 75, 
						   hideOthers: true } 
					 );
	//} );
}

function deleteLinkTip( _link_id ) {
	//Event.observe( window, 'load', function() {
		new Tip( 'delete_link_'+_link_id, 
						 $('tip_delete_link_'+_link_id),  
						 { stem: 'topLeft', 
							 hook: { tip: 'topLeft', mouse: true }, 
							 offset: { x: 0, y: 10 }, 
							 width: 75, 
							 hideOthers: true } 
					  );	
	//} );
}

function tabTip( _link_id ) {
	//Event.observe( window, 'load', function() {
		new Tip( 'clickable_'+_link_id, 
						 $('tip_click_link_'+_link_id),  
						 { 
							 stem: 'topLeft', 
							 offset: { x: 100, y: 100 },
							 hideAfter: 2,
							 hideOn: 'click',
							 fixed: true,
							 hideOthers: true } 
					 );	
	//} );
}

/********* Tag hints *********/

function showTagHint( _hint ) {
	var e = $('tags');
	e.style.color = '#000000';
	if ( e.value==_hint ) { e.value=''; };
}
function hideTagHint( _hint ) {
	var e = $('tags');
	if ( e.value=='' ) { 
		e.style.color = '#999999';
		e.value = _hint; 
	}
}

/********* Home Page *********/

function homePageScreenshot() {
	var e = $('home_screenshot');
	e.observe('mouseover', function(event) {
		e.src = "https://clustercms.s3.amazonaws.com/screenshot_hover.jpg";
	});	
	e.observe('mouseout', function(event) {
		e.src = "https://clustercms.s3.amazonaws.com/screenshot.jpg";
	});	
}

/********* Submit Page *********/

function observeEnterKey() {
	Event.observe( window, 'load', function() {
		$('url').observe('keypress', function(event) {
	  	if( event.keyCode == Event.KEY_RETURN ) {
	      Event.stop(event);
				$('add_button').click();
	    }
		});	
		$('title').observe('keypress', function(event) {
	  	if( event.keyCode == Event.KEY_RETURN ) {
	      Event.stop(event);
	    }
		});	
	});
}

function enableAddButton() {
	if ( $('url').value.length != 0 ) {
		$('add_button').enable();
	} else {
		$('add_button').disable();
	}
}

function enablePublishButton() {
	if ( $('title').value.length!=0 && $('has_links').value=="true" ) {
		$('publish_button').enable();
	} else {
		$('publish_button').disable();
	}	
}

function bookmark(short_url){
	var title = 'clusterURL';
	var url = 'http://clusterURL.com/' + short_url;

   if (document.all)
     window.external.AddFavorite(url, title);
   else if (window.sidebar)
     window.sidebar.addPanel(title, url, "")
   else if (window.sidebar&&window.sidebar.addPanel)
     window.sidebar.addPanel(title,url,"");
}


