function addBrandClear () {
	if ($('BrandName').value == "Create New Brand...") {
		$('BrandName').value="";
	};
}

function addKeywordClear () {
	if ($('KeywordKeyword').value == "New Variation...") {
		$('KeywordKeyword').value="";
	};
}

function addProfileUsernameClear () {
	if ($('ProfileUsername').value == "Username") {
		$('ProfileUsername').value="";
	};
}

function addProfilePasswordClear () {
	if ($('ProfilePassword').value == "Password") {
		$('ProfilePassword').value="";
	};
}

function addCoConspiratorClear () {
	if ($('CoConspiratorEmail').value == "Email Address") {
		$('CoConspiratorEmail').value="";
	};
}

function itemSearchClear () {
	if ($('ItemsSearch').value == "Keyword Search...") {
		$('ItemsSearch').value="";
	};
}

function demoBrandName () {
	if ($('DemoBrandName').value == "search for your brand") {
		$('DemoBrandName').value="";
	};
}

function demoGoButton () {
	if ($('DemoBrandName').value != "search for your brand" && $('DemoBrandName').value != "") {
		window.location = base_url + "brands/demo/" + urlencode($F("DemoBrandName"));
	} else {
		alert('Please enter your brand before hitting go. Thanks!');
	}
}

function demoBrandNameKeypress(event) {
  var key = event.which || event.keyCode;
  if (key == Event.KEY_RETURN){
	if ($('DemoBrandName').value != "search for your brand" && $('DemoBrandName').value != "") {
		window.location = base_url + "brands/demo/" + urlencode($F("DemoBrandName"));
	} else {
		alert('Please enter your brand before hitting go. Thanks!');
	}
  }	
}


function keywordAddAction (new_id) {
	new_id = new_id.replace(" ", "_");
	new Effect.Highlight(new_id); 
	$('KeywordKeyword').value="";
}

function profileAddAction (new_id) {
	new_id = new_id.replace(" ", "_");
	new Effect.Highlight(new_id); 
	$('ProfileUsername').value="";
	$('ProfilePassword').value="";
}

function ajaxRemove (id) {
	new Effect.Highlight(id, { startcolor: '#EB9284', endcolor: '#fffffff' });
	new Effect.Fade(id, {duration:0.5});
}

function ajaxCancel (id) {
	new Effect.Highlight(id, { startcolor: '#EB9284', endcolor: '#fffffff' });
	$(id+'_status').update('cancelled');
	$(id+'_resend').hide();
	$(id+'_cancel').hide();
}

function ajaxReSend (id) {
	new Effect.Highlight(id);
	$(id+'_resend').update('re-sent!');
}

function ajaxActivate (id) {
	new Effect.Highlight(id);
	$(id+'_activate').update('re-activated!');
}

function calculateCharacters (spanId, inputId) {
 	current = $(inputId).value.length;
	left = 140-current;
	$(spanId).update(left);
}

function highlightSave(elementId) {
	new Effect.Highlight(elementId);
}

function closeModalbox() {
	if ($('closeModalbox')) {
		// hide the modal box
		Modalbox.hide()
		// refresh the current page
		location.reload(true);
	} else {
		// resize to content (in case of validation error messages)
		Modalbox.resizeToContent();
	}
	return true;
}

function helptips() {
	if ($$("span.helptip")) {
		$$("span.helptip").each( function(span) {
			new Tooltip(span, {opacity: .95});
		});
	};
}

function demotips() {
	if ($$("a.demotips")) {
		$$("a.demotips").each( function(a) {
			new Tooltip(a, {opacity: .95, delay: 0, mouseFollow: false});
		});
	};
}

function showHidePaymentOption(option) {
	if (option == 'credit-form') {
		$('credit-form').show();
		$('paypal-help').hide();
	};
	
	if (option == 'paypal-help') {
		$('credit-form').hide();
		$('paypal-help').show();
	};
}

function faceboxLoading () {
	$('facebox_content').insert({bottom: '<div class="loading"><img src="'+base_url+'js/loading.gif"/></div>'});;
}

function faceboxReplyOnSite (url) {
	fbros  = new Facebox();
	url = 'http://localhost'+url;
	new Ajax.Request(url, {
		method		: 'get',
		onFailure	: function(transport){
			fbros.reveal(transport.responseText);
		},
		onSuccess	: function(transport){
			fbros.reveal(transport.responseText);
		}
	});
    new Effect.Appear(fbros);
}

document.observe("dom:loaded", function() {
   // attach all event handlers...
	if ($('BrandName')) {
		$('BrandName').observe('click', addBrandClear);
	};
	if ($('KeywordKeyword')) {
		$('KeywordKeyword').observe('click', addKeywordClear);
	};
	if ($('ProfileUsername')) {
		$('ProfileUsername').observe('focus', addProfileUsernameClear);
	};
	if ($('ProfilePassword')) {
		$('ProfilePassword').observe('focus', addProfilePasswordClear);
	};
	if ($('CoConspiratorEmail')) {
		$('CoConspiratorEmail').observe('click', addCoConspiratorClear);
	};	
	if ($('ItemsSearch')) {
		$('ItemsSearch').observe('click', itemSearchClear);
	};
	if ($('DemoBrandName')) {
		$('DemoBrandName').observe('click', demoBrandName);
	};
	if ($('brandsubmit')) {
		$('brandsubmit').observe('click', demoGoButton);
	};
	if ($('DemoBrandName')) { 
		$('DemoBrandName').observe('keypress', demoBrandNameKeypress); 
	};
		
	helptips();
	demotips();

	if (refresh == true) {
	  	document.observe('lightview:loaded', function() {
			Lightview.show({
				href: '#progress-bar-wrapper',
				title: 'Updating ' + brand_keyword,
				caption: 'Scouring millions of conversations for mentions...',
				options: {
			    	width: 350,
			 		height: 200,
			    	topclose: false,
			 		closeButton: false,
			 		overlayClose: false
			  	}
			});
			startDemoProgress(keyword_hash);
		});
	}
	
	
	if (refresh_hash != false) {
	  	document.observe('lightview:loaded', function() {
			Lightview.show({
				href: '#progress-bar-wrapper',
				title: 'Updating your brands',
				caption: 'Scouring millions of conversations for mentions...',
				options: {
			    	width: 350,
			 		height: 200,
			    	topclose: false,
			 		closeButton: false,
			 		overlayClose: false
			  	}
			});
			startDashboardProgress(refresh_hash);
		});
	}
	
	if (refresh_brand != false) {
	  	document.observe('lightview:loaded', function() {
			Lightview.show({
				href: '#progress-bar-wrapper',
				title: 'Updating your brand',
				caption: 'Scouring millions of conversations for mentions...',
				options: {
			    	width: 350,
			 		height: 200,
			    	topclose: false,
			 		closeButton: false,
			 		overlayClose: false
			  	}
			});
			startDashboardProgress(refresh_brand);
		});
	}
});



function startDashboardProgress(refresh_hash) {
	refresh_url = base_url + 'progress/' + refresh_hash + '.json';
	call_number = 0;							
    $('brand-refresh-status').update('initiating refresh');
	window.setTimeout(function() {
		refreshDashboardProgress(); 
		}
		, 1000
	);
}


function refreshDashboardProgress() {
	call_number++;
	
	new Ajax.Request(refresh_url, {
		method: 'get',
		onSuccess: function(transport) {
			var progress = transport.responseJSON;
			// something went wrong...delay for 2 seconds, then try again
			if (progress == null) {
				window.setTimeout(function() {
					refreshDemoProgress(); }
					, 2000	// delay for 1 seconds, then kick off another request
				);
			}
			if (progress.step != 'complete' && call_number < 200) {
				if (progress.logo != null) {
					$('refresh-logo').setAttribute('src', base_url + 'img/logos/' + progress.logo);
				}
				$('brand-refresh-status').update(progress.text);
				myJsProgressBarHandler.setPercentage('refresh-progress-bar', (progress.step * Math.ceil(100/progress.total_steps)));
				window.setTimeout(function() {
					refreshDashboardProgress(); }
					, 500	// delay for half a second, then kick off another request
				);
			} else if (progress.step == 'complete') {
				myJsProgressBarHandler.setPercentage('refresh-progress-bar', 100);
				$('brand-refresh-status').update(progress.text);
				window.setTimeout(function() {
					if (progress.new_items > 0) {
						$('brand-refresh-status').update(progress.new_items + " new items found.</a>");
						window.setTimeout(function() {
								window.location.reload();
							}, 3000
						);
					} else {
						$('refresh-logo').setAttribute('src', base_url + 'img/icons/home_alert.png');
						$('brand-refresh-status').update("No new items found.");
						window.setTimeout(function() {
							Lightview.hide();
							myJsProgressBarHandler.setPercentage('refresh-progress-bar', 0);
							$('brand-refresh-status').hide();
							$('brand-refresh-status').update(" ");
							}, 3000
						);
					}
					new Effect.Highlight('brand-refresh-status');
					}, 1000
				);
			} else {  // the refresh hit 200 refreshes total...too much
				//reset and hide everything
				$('refresh-logo').setAttribute('src', base_url + 'img/icons/home_alert.png');
				$('brand-refresh-status').update('The refresh is taking too long...try again later.');
				window.setTimeout(function() {
					Lightview.hide();
					myJsProgressBarHandler.setPercentage('refresh-progress-bar', 0);
					$('brand-refresh-status').hide();
					$('brand-refresh-status').update(" ");
					}, 6000
				);
				
			}
		},
		onFailure: function(transport) {
			//reset and hide everything
			$('refresh-logo').setAttribute('src', base_url + 'img/icons/home_alert.png');
			$('brand-refresh-status').update('The refresh failed...try again later.');
			window.setTimeout(function() {
				Lightview.hide();
				myJsProgressBarHandler.setPercentage('refresh-progress-bar', 0);
				$('brand-refresh-status').hide();
				$('brand-refresh-status').update(" ");
				}, 6000
			);
		}
	});
}




function startDemoProgress(keyword_hash) {
	refresh_url = base_url + 'progress/' + keyword_hash + '.json';
	call_number = 0;
    $('brand-refresh-status').update('initiating refresh');
	window.setTimeout(function() {
		refreshDemoProgress(); 
		}
		, 1000
	);
}


function refreshDemoProgress() {
	call_number++;
	
	new Ajax.Request(refresh_url, {
		method: 'get',
		onSuccess: function(transport) {
			var progress = transport.responseJSON;
			// something went wrong...delay for 2 seconds, then try again
			if (progress == null) {
				window.setTimeout(function() {
					refreshDemoProgress(); }
					, 2000	// delay for 1 seconds, then kick off another request
				);
			}
			if (progress.step != 'complete' && call_number < 300) {
				if (progress.logo != null) {
					$('refresh-logo').setAttribute('src', base_url + 'img/logos/' + progress.logo);
				}
				$('brand-refresh-status').update(progress.text);
				myJsProgressBarHandler.setPercentage('refresh-progress-bar', (progress.step * Math.ceil(100/progress.total_steps)));
				window.setTimeout(function() {
					refreshDemoProgress(); }
					, 500	// delay for 1 seconds, then kick off another request
				);
			} else if (progress.step == 'complete') {
				myJsProgressBarHandler.setPercentage('refresh-progress-bar', 100);
				$('brand-refresh-status').update(progress.text);
				window.setTimeout(function() {
						if (progress.new_items > 0) {
							window.location.reload();
						} else {
							$('refresh-logo').setAttribute('src', base_url + 'img/icons/home_alert.png');
							$('brand-refresh-status').update("No items found. Try another term.");
							window.setTimeout(function() {
								// redirect back to home page...eventually we'll want to present a form inside the lightbox instead
								window.location = base_url;
								}, 3000
							);
						}
					}, 1000
				);
			} else {  // the refresh hit 200 refreshes total...too much
				//reset and hide everything
				$('refresh-logo').setAttribute('src', base_url + 'img/icons/home_alert.png');
				$('refresh-progress-bar').hide();
				$('brand-refresh-status').update('The refresh is taking too long...try again later.');
				window.setTimeout(function() {
					window.location = base_url;
					}, 3000
				);
			}
		},
		onFailure: function(transport) {
			//reset and hide everything
			$('refresh-logo').setAttribute('src', base_url + 'img/icons/home_alert.png');
			$('refresh-progress-bar').hide();
			$('brand-refresh-status').update('The refresh failed...try again later.');
			window.setTimeout(function() {
				window.location = base_url;
				}, 3000
			);
		}
	});
}





function startRefreshProgress(brand_id) {
	refresh_url = base_url + 'progress/' + brand_id + '.json';
	call_number = 0;
	$('refresh-logo').setAttribute('src', base_url + 'img/lightview/loading.gif');
	$('brand-refresh-link').hide();
	$('refresh-progress-bar').show();
	$('brand-refresh-status').show();						
    $('brand-refresh-status').update('initiating refresh');
	myJsProgressBarHandler.setPercentage('refresh-progress-bar', 0);
	
	Lightview.show({
		href: '#progress-bar-wrapper',
		title: 'Updating ' + brand_name,
		caption: 'Scouring millions of conversations for mentions...',
		options: {
	    	width: 350,
	 		height: 200,
	    	topclose: false,
	 		closeButton: false,
	 		overlayClose: false,
	  	}
	});

	new Ajax.Request(base_url + 'brands/manual_refresh/' + brand_id , {
		method: 'get',
		onSuccess: function(transport) {
			refreshProgress();
		},
		onFailure: function(transport) {
			$('brand-refresh').update('The refresh failed...try again in a few minutes.');
		}
	});	
}

function refreshProgress() {
	call_number++;
	
	new Ajax.Request(refresh_url, {
		method: 'get',
		onSuccess: function(transport) {
			var progress = transport.responseJSON;
			// something went wrong...delay for 2 seconds, then try again
			if (progress == null) {
				window.setTimeout(function() {
					refreshDemoProgress(); }
					, 2000	// delay for 1 seconds, then kick off another request
				);
			}
			if (progress.step != 'complete' && call_number < 200) {
				if (progress.logo != null) {
					$('refresh-logo').setAttribute('src', base_url + 'img/logos/' + progress.logo);
				}
				$('brand-refresh-status').update(progress.text);
				myJsProgressBarHandler.setPercentage('refresh-progress-bar', (progress.step * Math.ceil(100/progress.total_steps)));
				window.setTimeout(function() {
					refreshProgress(); }
					, 500	// delay for half a second, then kick off another request
				);
			} else if (progress.step == 'complete') {
				myJsProgressBarHandler.setPercentage('refresh-progress-bar', 100);
				$('brand-refresh-status').update(progress.text);
				window.setTimeout(function() {
					if (progress.new_items > 0) {
						$('brand-refresh-status').update(progress.new_items + " new items found.</a>");
						window.setTimeout(function() {
								window.location.reload();
							}, 3000
						);
					} else {
						$('refresh-logo').setAttribute('src', base_url + 'img/icons/home_alert.png');
						$('brand-refresh-status').update("No new items found.");
						window.setTimeout(function() {
							Lightview.hide();
							myJsProgressBarHandler.setPercentage('refresh-progress-bar', 0);
							$('brand-refresh-status').hide();
							$('brand-refresh-status').update(" ");
							$('brand-refresh-link').show();
							}, 3000
						);
					}
					new Effect.Highlight('brand-refresh-status');
					}, 1000
				);
			} else {  // the refresh hit 200 refreshes total...too much
				//reset and hide everything
				$('refresh-logo').setAttribute('src', base_url + 'img/icons/home_alert.png');
				$('brand-refresh-status').update('The refresh is taking too long...try again later.');
				window.setTimeout(function() {
					Lightview.hide();
					myJsProgressBarHandler.setPercentage('refresh-progress-bar', 0);
					$('brand-refresh-status').hide();
					$('brand-refresh-status').update(" ");
					$('brand-refresh-link').show();
					}, 6000
				);
				
			}
		},
		onFailure: function(transport) {
			//reset and hide everything
			$('refresh-logo').setAttribute('src', base_url + 'img/icons/home_alert.png');
			$('brand-refresh-status').update('The refresh failed...try again later.');
			window.setTimeout(function() {
				Lightview.hide();
				myJsProgressBarHandler.setPercentage('refresh-progress-bar', 0);
				$('brand-refresh-status').hide();
				$('brand-refresh-status').update(" ");
				$('brand-refresh-link').show();
				}, 6000
			);
		}
	});
}


function urlencode(str) {
	str = escape(str);
	str = str.replace('+', '%2B');
	str = str.replace(/%20/g, '+');
	str = str.replace('*', '%2A');
	str = str.replace('/', '%2F');
	str = str.replace('@', '%40');
	return str;
}

function urldecode(str) {
	str = str.replace('+', ' ');
	str = unescape(str);
	return str;
}