function clickclear(thisfield, defaulttext) {
	if (thisfield.value == defaulttext) {
		thisfield.value = "";
	}
}
function clickrecall(thisfield, defaulttext) {
	if (thisfield.value == "") {
		thisfield.value = defaulttext;
	}
}
// Tracks the path in google anayltics if active
var hasTracked = false;
function trackThis(type, url) {
  if(pageTracker) {
    if(!hasTracked) {
      pageTracker._setAllowLinker = true;
      pageTracker._trackTrans();
      hasTracked = true;
    }
    url = url.replace(/https\:\/\/|http\:\/\//g, "");
    url = url.replace(/\?/g, "%3F");
    url = url.replace(/\&/g, "%26");
    url = url.replace(/\=/g, "%3D");
    /*if(encodeURIComponent) {
    	url = encodeURIComponent(url);
    }
    else if(escape) {
    	url = escape(url);
    }*/
    pageTracker._trackPageview("/tracking/"+type+"/"+url);
  }
}

function doToolTipCheck() {
	if(typeof(Prototip) != 'undefined') {
		$$('.tooltip').each(function(ele){
			if(ele.hasToolTipAdded) {
				return;
			}
			var width = false;
			var stem = 'leftTop';
			$w(ele.className).each(function(className) {
				if(className == 'tooltipwide') {
					width = 300;
					//stem = 'bottomLeft';
				}
			});
			var msg = ele.title;
			ele.title="";
			new Tip(ele, msg, {
			  style: 'protoblue',
			  width : width,
			  stem: stem,
			  delay: 0.03,
			  hideOthers: true,
			  hideOn: 'mouseout',
			  showOn: 'mousemove',			  
			  hook: { tip: 'leftTop', mouse: true },
			  offset: { x: 4, y: -8 }
			});
			ele.hasToolTipAdded = true;
		});
	}
}

document.observe("dom:loaded", function(){
    // Setup any tool tips
	doToolTipCheck();
	
	var isSafariMac = /Safari/.test(navigator.userAgent) && /Mac/.test(navigator.platform);

	if(!isSafariMac && typeof(myLightWindow) != "undefined") {
		$$('a.signup').each(function(ele){
			ele.onclick = function() {
				myLightWindow.activateWindow({
					type: 'external',
					href: 'signup.php?simple=1', 
					title: 'Try spellr.us with a free trial', 
					width: 650, 
					height: 400
				});
				return false;
			};
		});
	}
});

// Remote scan controller
var spellrus = {
	dev: false,
	firstScan: true,
	currentUrl: "",
	ajaxURL: spellrusRoot+"app/remote/",
	jobRunning: false,
	siteId: 0,
	site: {},
	timer: false,
	locationTimer: false,
	lazyLoaded: false,
	myLightWindow: false,
	lastStatusChange: false,
	messages: {
		invalidUrl : "That url does not appear to be valid. Please check the url and try again.",
		noErrorsSnarky : "No errors found! What were you expecting? ;)",
		starting : "Starting up...",
		queued : "Your site has been queued. Please wait...",
		progress : "We're checking your site now! This will take about 30-60 seconds. Hold tight...",
		completing : "Finalising your results...",
		complete : "Check Complete",
		error : "We had a problem checking your site. Please try again later.",
		overloaded : "<img src='images/over-capacity.gif' /><br /><br/ ><b>It's no good, Captain - she aint got the power!</b><br /><br />Due to an overload of instant scan requests (probably from the latest awesome review being re-tweeted on Twitter), our instant scan tool has hit its peak usage.<br /><br />Please try again in a few minutes - or <a href='signup.php'>register for a full account now</a> to get access to the super-scan-server and not worry about peak loads like this one."
	},
	didYouKnow : [
		"The word 'queue' is the only word in the English language that is still pronounced the same way when the last four letters are removed!",
		"The six official languages of the United Nations are: English, French, Arabic, Chinese, Russian and Spanish!",
		"The average lead pencil will draw a line 35 miles long or write approximately 50,000 English words!",
		"'Almost' is the longest word in the English language with all the letters in alphabetical order!",
		"Of all the words in the English language, the word 'set' has the most definitions!",
		"More than 80% of home pages on the Web are in English, while the next greatest, German, has only 4.5% and Japanese 3.1%!",
		"English has the most diverse vocabulary out of all the world's languages: 616,500 words!",
		"The average native speaker uses only a tenth of his vocabulary in everyday speech, about 1200-2000 words!",
		"The longest English word is'pneumonoultramicroscopicsilicovolcanoconiosis', meaning a lung disease caused by inhalation of silica!",
		"'Screeched' and 'strengths' are the two longest monosyllabic words in the English language!",
		"No word in the English language rhymes with month, orange, silver or purple!",
		"Of all the words in the English language, the word 'set' has the most definitions!",
		"'Ough' can be pronounced in eight different ways: 'A rough-coated, dough-faced ploughman strode through the streets of Scarborough, coughing and hiccoughing thoughtfully'!",
		"The 'y' in 'ye olde' is actually pronounced 'th'!",
		"The last thing to happen is the ultimate. The next-to-last is the penultimate, and the second-to-last is the antepenultimate!",
		"Shakespeare invented the term 'Assassination', which appears in his play Macbeth!",
		"'Underground' is the only word in the English language that begins and ends with the letters 'und'!",
		"'Stewardesses' is the longest word that is typed with only the left hand!",
		"The only 15 letter word that can be spelled without repeating a letter is 'uncopyrightable'!",
		"English has borrowed words from over 350 other languages!",
		"According to Illinois state law, it is illegal to teach English in schools. The officially recognised language is 'American'!",
		"The dot over the letter 'i' is called a 'tittle'!",
		"'Rhythms' and 'syzygy' are the longest English words without vowels!",
		"The only four words in the English language to beginning with DW are Dwarf, Dwell, Dweeb and Dwindle!",
		"'I am' is the shortest complete sentence in the English language!",
		"The oldest word in the English language is 'town'!",
		"'Overlook' and 'oversee' are opposites!",
		"'Quite a lot' and 'quite a few' mean the same thing!",
		"The only word in the English language that has 4 sets of double letters in a row is balloonneer!",
		"Previous accepted definitions of the word 'nice': silly, lazy, lecherous and strange!",
		"A pregnant goldfish is called a twit!",
		"Only three words have entered English from Czech:  polka, pilsner, and robot!",
		"The highest scoring word in Scrabble is 'Quartzy', for a maximum of 164 points!",
		"The word 'girl' appears only once in the Bible!",
		"'Freelance' comes from a knight whose lance was free for hire, i.e. not pledged to one master!",
		"Shakespeare invented over 1700 commonly used English words, including 'eyeball', 'skim milk', and 'advertising'!"	              
	],
	getDYK: function() {
		var index = Math.floor(Math.random()*spellrus.didYouKnow.length);
		if(index == spellrus.didYouKnow.length) --index;
		return "<i><b>Did You Know?</b></i><br />"+spellrus.didYouKnow[index];
	},
	docHead: null,
	quickJSON: function(url, callback) {
	  if(!spellrus.docHead) spellrus.docHead = document.getElementsByTagName('head')[0];

	  var uId = "s_"+spellrus.getNow();
	  var oScript = document.createElement("script");
	  oScript.type = 'text/javascript';
	  oScript.src = url+'&callback='+callback+'&t='+uId;
	  oScript.charset = 'windows-1252';
	  oScript.id = uId;
	  spellrus.docHead.appendChild(oScript);
	},
	noErrorsSnarky: function() {
		spellrus.jobRunning = false;
		spellrus.msg(spellrus.messages.noErrorsSnarky);		
	},
	beginScan: function() {
		if(spellrus.jobRunning) {
			alert("Please wait for your current scan to complete.");
			return;
		}
		if(spellrus.firstScan) {
			$$('.hideOnScan').each(function(item){
				item.fade({
					duration: 2.0,
					from: 1,
					to: 0.1,
					afterFinish: function() {
						item.slideUp({ duration: 2.0 }); 
					}
				});
			});
			spellrus.firstScan = false;
		}
		spellrus.showScan();
		spellrus.msg(spellrus.messages.starting, true);
		spellrus.currentUrl = $("urlInput").value;
		var urlTest = new RegExp("[\.]");
		if(!urlTest.test(spellrus.currentUrl)) {
			// That ain't no url you're checking!
			if(spellrus.currentUrl.match("^http://")=="http://") {
				// Looks like they just entered the original url
				spellrus.msg("Please enter a valid url or word in the url box above.");
				$("scanInfo").highlight();
				return;
			}
			
			var inputType = "a word";
			if(/\s/.test(spellrus.currentUrl)) {
				inputType = "some text";
			}
			var msg = "It looks like you're trying to spell check "+inputType+". <i>You will be redirected our word spell checker in 4 seconds.</i> <a href='javascript:spellrus.cancelLocationChange();'>Click here to cancel.</a>";
			spellrus.locationTimer = window.setTimeout(function() {
				location.href = "http://spellr.us/spell-check/&text="+spellrus.currentUrl;
			}, 4000);
			spellrus.msg(msg);
			return;
		}
		spellrus.currentUrl = spellrus.currentUrl.replace(/^\s+|\s+$/g, ''); // trim
		trackThis("quickScan", spellrus.currentUrl);
		// Check if they're trying to scan us
		if(/^(http\:\/\/)?(www\.)?spellr\.us$/i.test(spellrus.currentUrl)) {
			spellrus.timer = window.setTimeout(function() {
				spellrus.noErrorsSnarky();
			}, 1500);
		}
		else {
			spellrus.quickJSON(spellrus.ajaxURL+"createScan/?url="+spellrus.currentUrl, "spellrus.beginScanReceived");
		}
	},
	
	cancelLocationChange: function() {
		spellrus.jobRunning = false;
		if(spellrus.locationTimer) {
			window.clearTimeout(spellrus.locationTimer);
		}
		spellrus.msg("Please enter a url above to start a new scan.");
	},
	
	beginScanReceived: function(data) {
		if(!data.is_valid) {
			spellrus.jobRunning = false;
			spellrus.msg(spellrus.messages.invalidUrl);
		}
		else if(data.overloaded) {
			spellrus.jobRunning = false;
			spellrus.msg(spellrus.messages.overloaded);
		}
		else {
			spellrus.msg(spellrus.messages.queued, true);
			spellrus.siteId = data.site_id;
			spellrus.jobRunning = true;
			spellrus.site = {};
			spellrus.checkStatus();
		}
	},
	checkStatus: function() {
		if(spellrus.timer) {
			window.clearTimeout(spellrus.timer);
			timer = false;
		}
		spellrus.quickJSON(spellrus.ajaxURL+"siteStatus/?siteId="+spellrus.siteId, "spellrus.statusReceived");	
	},
	statusReceived: function(data) {
		var maxPossible = data.maxHits;
		var site = spellrus.site;
		site.maxHits = data.maxHits;
		site.lastFound = data.found;
		site.lastScanned = data.scanned;
		data.eta = data.eta*2;
		if(site.etaSet != data.eta) {
			site.eta = data.eta;
			site.etaSet = data.eta;
			site.etaSetAt = spellrus.getNow();
			if(!site.progress)
				site.progress = 0;
			site.etaSetProgress = site.progress;
		}
		if(site.progress == 100 && data.status == "BUSY") {
			data.status = "COMPLETING";
		}

		//Check current status of scan
		site.scanDone = false;
		if(site.status != data.status) {
			var msg = '';
			spellrus.lastStatusChange = false;
			if(data.status == "NEW") {
				msg += spellrus.messages.queued;
			}
			else if(data.status == "BUSY") {
				spellrus.lastStatusChange = spellrus.getNow(); 
				msg += spellrus.messages.progress;
				msg += "<div id='didYouKnow' style='padding:5px 0;margin:12px 0 5px 0;border:5px solid #eee;font-size:90%;'>"+spellrus.getDYK()+"</div>";
			}
			else if(data.status == "COMPLETING") {
				msg += spellrus.messages.completing;
			}
			else if(data.status == "CANCELLING") {
				msg += spellrus.messages.progress;
			}
			else if(data.status == "DONE") {
				msg += spellrus.messages.complete;
				site.scanDone = true;
			}
			else {
				msg += spellrus.messages.error;
				site.scanDone = true;
			}
			spellrus.msg(msg, true);
		}
		else if(spellrus.lastStatusChange && (spellrus.getNow() - spellrus.lastStatusChange > 8000)) {
			// Change message after 5 seconds
			spellrus.lastStatusChange = spellrus.getNow(); 
			//$("didYouKnow").hide();
			$("didYouKnow").appear({ from: 0.1, to: 1.0 });
			$("didYouKnow").update(spellrus.getDYK());

		}
		site.status = data.status;

		if(!site.progressBar) {
			// This is run on first pass through
			var div = $("loading_progress");
			site.progressBar = new JS_BRAMUS.jsProgressBar(div, site.progress, {
				boxImage: spellrusRoot+'images/progressBar/percentImage.png',
				barImage: spellrusRoot+'images/progressBar/percentImage_back1.png'
			});
			
			// Launch time display
			site.startedAt = spellrus.getNow();
			spellrus.startProgressDisplay(site);		
		}
		
		// Check if scan is complete or if we should schedule polling the server again
		spellrus.site = site;	
		
		if(!spellrus.lazyLoaded) {
			spellrus.lazyLoaded = true;
			/*
			// Dynamically load lightbox JS & CSS
			var headID = document.getElementsByTagName("head")[0];         
			var cssNode = document.createElement('link');
			cssNode.type = 'text/css';
			cssNode.rel = 'stylesheet';
			cssNode.href = 'scripts/lightwindow/css/lightwindow.css'+(spellrus.dev ? '?t='+spellrus.getNow() : '');
			cssNode.media = 'screen';
			headID.appendChild(cssNode);	       
			var newScript = document.createElement('script');
			newScript.type = 'text/javascript';
			newScript.src = 'scripts/lightwindow/javascript/lightwindow.js'+(spellrus.dev ? '?t='+spellrus.getNow() : '');
			headID.appendChild(newScript);	
			//alert("lazyLoaded");		
			*/
			var headID = document.getElementsByTagName("head")[0];         
			var cssNode = document.createElement('link');
			cssNode.type = 'text/css';
			cssNode.rel = 'stylesheet';
			cssNode.href = spellrusRoot+'library/prototip2.0.4/css/prototip.css';
			cssNode.media = 'screen';
			headID.appendChild(cssNode);	
			var newScript = document.createElement('script');
			newScript.type = 'text/javascript';
			newScript.src = spellrusRoot+'library/prototip2.0.4/js/prototip.js';
			headID.appendChild(newScript);			
		}
		
		if(site.scanDone) {
			spellrus.getScanResults();
		}
		else {
			// Queue next check
			spellrus.timer = setTimeout(function(){
				spellrus.checkStatus();
			},2000);
		}
	},
	getScanResults: function() {
		spellrus.quickJSON(spellrus.ajaxURL+"siteResults/?siteId="+spellrus.siteId, "spellrus.scanResultsReceived");
	},
	scanResultsReceived: function(data) {
		spellrus.jobRunning = false;
		trackThis("scanComplete", spellrus.currentUrl);
		var currentColour = "";
		var seenOne = false;
		if(data.errors.length > 0) {
			var error = data.errors[0];
			$("errorWord").update('<span style="font-weight: bold; color: '+error.colour+';">'+error.word+'</span>');	
			$("errorWordSuggestions").update('<span style="font-style: italic;">Suggestions: '+error.suggestions+'</span>');	
			$("sampleUrlHere").update('<a href="'+error.originalUrl+'" target="_blank">'+error.originalUrl.truncate(55)+'</a>');	
			$("screenshotBox").update('<iframe src="'+error.url+'" scrolling=no style="margin-top:3px;border:3px solid '+error.colour+';width:590px;height:200px;"></iframe>');	
		}
		
		var otherResults = "";
		for(var i = 1; i < data.errors.length; ++i) {
			var error = data.errors[i];
			if(!error.word) continue;
			if(otherResults != "") otherResults += ", ";
			otherResults += '<span style="color:'+error.colour+';">'+error.word+'</span>';
		}
		if(otherResults != "") {
			var more = data.number_likely + data.number_possible + data.number_unlikely - 5;
			if(more > 0) {
				otherResults += ", <a href='#' style='color:#74B7C0;' onclick='spellrus.highlightEmail();return false;'>"+more+" more...</a>";
			}
			$("otherErrorsUrl").update(spellrus.currentUrl);
			$("otherScanResults").update(otherResults);
		}

		//var topScanDesc = data.number_pages+" pages of your website have been successfully checked.";
		//$("topScanDesc").update(topScanDesc);
		$("scanDescPages").update(data.number_pages);
		$("scanDescDetails").update("<span style='color:#EF1D1D;'>"+data.number_likely+" likely</span>, <span style='color:#EF9D00;'>"+data.number_possible+" possible</span> & <span style='color:#2F8DD3;'>"+data.number_unlikely+" unlikely</span>");
		
		if($("initial_scan")) $("initial_scan").value = spellrus.currentUrl;
		
		spellrus.showResults();
		/*
		var links = $$('.lightwindow_iframe_link');
		links.each(function(link) {
			Event.observe(link, 'click', function() {
				myLightWindow.activate(null, link);
			}, false);
			link.onclick = function() {return false;};
		});		
		*/
		//doToolTipCheck();
	},
	highlightEmail: function() {
		new Effect.Highlight("signUpQuickScan", { startcolor: '#ffff99', endcolor: '#ffffff' });
	},
	getNow: function() {
		var now = new Date();
		return now.getTime();
	},
	showNewProgress: function(site) {
		if(site.lastScanned > 0) {
			var secsPassedLastSet = (site.etaSetAt-site.startedAt)/1000;
			var secsPerPage = secsPassedLastSet/site.lastScanned;
			var secsPassed = (spellrus.getNow()-site.startedAt)/1000;
			var eta = site.maxHits*secsPerPage;
			var newProgress = Math.floor((secsPassed/eta)*100);
			if(newProgress > site.progress) {
				site.progress = newProgress;
			}
		}
		if(site.progress < 0) site.progress = 0;
		if(site.progress > 100 || site.scanDone) {
			site.progress = 100;
			if(site.interval) {
				window.clearInterval(site.interval);
			}
		}		
		site.progressBar.setPercentage(site.progress);
	},
	startProgressDisplay: function(site) {
		if(site.interval) {
			window.clearInterval(site.interval);
		}
		spellrus.showNewProgress(site);
		site.interval = window.setInterval(function() {
			spellrus.showNewProgress(site);
		}, 1500);
	},
	showResults: function() {
		$("scanBox").hide();
		$("resultsBox").show();
		if(spellrus.site.interval) {
			window.clearInterval(spellrus.site.interval);
		}			
		$("loading_progress").update("");
	},
	showScan: function() {
		$("resultsBox").hide();
		$("scanBox").show();
	},
	hide: function() {
		$("resultsBox").hide();
		$("scanBox").hide();
	},
	msg: function(msg, showLoading) {
		if(showLoading) msg = '<img src="'+spellrusRoot+'images/ajax-loader-small.gif" style="vertical-align:middle;" /> '+msg;
		$("scanInfo").update(msg);
	}
};

/**
 * @author 	Maxime Haineault (max@centdessin.com)
 * @version	0.3
 * @desc 	JavaScript cookie manipulation class
 * 
 */
Cookie = {	

	/** Get a cookie's value
	 *
	 *  @param integer	key		The token used to create the cookie
	 *  @return void
	 */
	get: function(key) {
		// Still not sure that "[a-zA-Z0-9.()=|%/]+($|;)" match *all* allowed characters in cookies
		tmp =  document.cookie.match((new RegExp(key +'=[a-zA-Z0-9.()=|%/]+($|;)','g')));
		if(!tmp || !tmp[0]) return null;
		else return unescape(tmp[0].substring(key.length+1,tmp[0].length).replace(';','')) || null;
		
	},	
	
	/** Set a cookie
	 *
	 *  @param integer	key		The token that will be used to retrieve the cookie
	 *  @param string	value	The string to be stored
	 *  @param integer	ttl		Time To Live (hours)
	 *  @param string	path	Path in which the cookie is effective, default is "/" (optional)
	 *  @param string	domain	Domain where the cookie is effective, default is window.location.hostname (optional)
	 *  @param boolean 	secure	Use SSL or not, default false (optional)
	 * 
	 *  @return setted cookie
	 */
	set: function(key, value, ttl, path, domain, secure) {
		cookie = [key+'='+    escape(value),
		 		  'path='+    ((!path   || path=='')  ? '/' : path),
		 		  'domain='+  ((!domain || domain=='')?  window.location.hostname : domain)];
		
		if (ttl)         cookie.push(Cookie.hoursToExpireDate(ttl));
		if (secure)      cookie.push('secure');
		return document.cookie = cookie.join('; ');
	},
	
	/** Unset a cookie
	 *
	 *  @param integer	key		The token that will be used to retrieve the cookie
	 *  @param string	path	Path used to create the cookie (optional)
	 *  @param string	domain	Domain used to create the cookie, default is null (optional)
	 *  @return void
	 */
	unset: function(key, path, domain) {
		path   = (!path   || typeof path   != 'string') ? '' : path;
        domain = (!domain || typeof domain != 'string') ? '' : domain;
		if (Cookie.get(key)) Cookie.set(key, '', 'Thu, 01-Jan-70 00:00:01 GMT', path, domain);
	},

	/** Return GTM date string of "now" + time to live
	 *
	 *  @param integer	ttl		Time To Live (hours)
	 *  @return string
	 */
	hoursToExpireDate: function(ttl) {
		if (parseInt(ttl) == 'NaN' ) return '';
		else {
			now = new Date();
			now.setTime(now.getTime() + (parseInt(ttl) * 60 * 60 * 1000));
			return now.toGMTString();			
		}
	},

	/** Return true if cookie functionnalities are available
	 *
	 *  @return boolean
	 */
	test: function() {
		Cookie.set('b49f729efde9b2578ea9f00563d06e57', 'true');
		if (Cookie.get('b49f729efde9b2578ea9f00563d06e57') == 'true') {
			Cookie.unset('b49f729efde9b2578ea9f00563d06e57');
			return true;
		}
		return false;
	},
	
	/** If Firebug JavaScript console is present, it will dump cookie string to console.
	 * 
	 *  @return void
	 */
	dump: function() {
		if (typeof console != 'undefined') {
			console.log(document.cookie.split(';'));
		}
	}
}

if(Cookie.get('refRecord') == null) {
	var referrer = document.referrer;
	if(!referrer) {
		referrer = "Direct";
	}
	Cookie.set('refRecord', referrer, 168);	
}
if($('add_referrer')) {
	$('add_referrer').value = Cookie.get('refRecord') || document.referrer || "";
}