urlInputText = new Array();
imageSelectors = new Array();

var locked = false;
var statusBucket = "";
var currentpercent = 0;
var startprogress = 30;
var lastprogval = 0;
var samecount = 0;
var errmsg = false;
var retest = false;
var isHomepage = false;
var progressUrls = new Array();
var retestUrl = "";
var testUrl = "";
var normTestId = "";
var runningReports = new Array();
var mouseon = false;

var currenttab = "";

var selectedclaimoption = false;

var tables = new Array();

var addthis_config =
{
   pubid: 'silktide'
}

var addthis_share = {
   url_transforms: {
	   clean: true,
	   remove: ['fbsign', 'claimdeleted']
    },
	templates: {
        twitter: '{{title}} {{url}} via @silktide'
	}
}

function loader()
{
	setupUrlBoxes();
	if($('.activityfeed').length >= 1)
	{
		setupProfile();
	}
	if($('#backgroundimage-element').length >= 1)
	{
		setupProfileEdit();
	}

	if($('#scorestable').length >= 1)
	{
		setupClaimedScreen();
	}

	setupRetest();
	setupTest();
	setupClaim();
	setupUsermenu();
	setupLoginForm();
	setupFacebookLoginForm();
	setupHomepage();
	setupRunningReports();
	setupBadges();
	setupProgressbar();
	setupSideBar();
	setupModal();
	setupAddThisXmasCompetition();
	if($('#reason').length >= 1)
	{
		setupReportUser();
	}
	$('#report').each(setupReport);
	updateStatuses();
}

oldscore = 0;
newscore = 0;
startdifference = 0;

function setupClaimedScreen()
{
	oldscore = parseInt($('#oldscore').html());
	newscore = parseInt($('#newscore').html());
	startdifference = newscore - oldscore;
	$('#newscore').html(oldscore);
	setTimeout(countUpScore, 2000);
	$("#scorestable").after('<div class="claim-sharing-buttons"><p></p></div>');

	$('.claim-sharing-buttons p').append('<a class="addthis_button_facebook" addthis:title="'+shareTitle+'" addthis:url="'+shareAddress+'"><span>Post to Facebook</span></a>');
	$('.claim-sharing-buttons p').append('<a class="addthis_button_twitter" addthis:title="'+shareTitle+'" addthis:url="'+shareAddress+'"><span>Tweet this</span></a>');

}

oldcolor = '#222222';

function countUpScore()
{
	if(oldscore != newscore)
	{
		difference = newscore - oldscore;
		if(difference <= 1 && difference >= -1)
		{
			oldscore = newscore;
		} else {
			differencepercent = (100 / startdifference) * difference;
			differenceroot = Math.sqrt(differencepercent);
			countupby = Math.ceil((differenceroot/100) * difference);
			if(countupby > difference)
			{
				countupby = difference;
			}
			oldscore += countupby;
		}
		newdifference =  newscore - oldscore;
		if(newdifference == 0)
		{
			oldcolor = $('#newscore').css('color');
			$('#newscore').animate({ color: "#2690F6" }, 400, function(){
				$('#newscore').animate({ color: oldcolor }, 400, function(){});
			});
		}
		//$('#newpoints .points').html(newdifference);
		$('#newscore').html(oldscore);
		setTimeout(countUpScore, 50);
	}
}

function setupSideBar()
{
	$('#defaultsidecol .padding').append('<iframe src="//www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2Fsilktide&amp;width=305&amp;colorscheme=light&amp;show_faces=true&amp;border_color&amp;stream=false&amp;header=false&amp;height=258" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:305px; height:258px;" allowTransparency="true"></iframe>');
}

function setupFacebookLoginForm()
{
	$('.fb-signup-userdata').each(function()
	{
		$('#importdata-label label').prepend($(this));
	});
}

function setupProgressbar()
{
	$('#nojsp').each(function(){
		if(isIE())
		{
			elem = $("#nojsp").get(0);
			elem.innerHTML = "We'll take you to your report when it's ready";
		} else {
			$("#nojsp").html("We'll take you to your report when it's ready");
		}
		isprogscreen = true;
	});
	$("#progressinner").fadeIn(1000);
}

function setupUsermenu()
{
	$('#usermenuActivate').click(clickUsermenu);
	$('#usermenuActivate').mouseenter(mouseonUsermenu);
	$('#usermenuActivate').mouseleave(mouseoffUsermenu);
}

function mouseonUsermenu(event)
{
	mouseon = event.timeStamp;
}

function mouseoffUsermenu()
{
	mouseon = false;
}

function clickUsermenu(event)
{
	if(mouseon)
	{
		if(event.timeStamp -80 > mouseon)
		{
			return true;
		}
	}
	
	$(this).parent().addClass('selected');
	$(this).blur(blurUsermenu);
	$(this).mouseout(blurUsermenu);
	return false;
}

function blurUsermenu()
{
	$(this).parent().removeClass('selected');
}


function setupHelp()
{
	$('.report-help-link a').click(doHelp);
}

function setupBadges()
{
	$('#profile-badges a').click(clickBadge);
	$('#users-badges a').click(clickBadge);
	$('#profile-badges a').removeAttr('title');
	$('#users-badges a').removeAttr('title');
	if($('#profile-badges li').size() > 12)
	{
		$('#profile-badges li').slice(12).addClass('hidebadge');
		$('#profile-badges li.hidebadge').hide();
		$('#profile-badges').parents('#sidecol').find('h2').after('<a href="#" class="rightcoltitlelink">See all</a>');
		$('.rightcoltitlelink').click(expandBadges);
	}
}

function setupModal()
{
	$('body').append('<div id="modaldialog"><div class="contentheadermenu"><h2 id="modaltitle"></h2><a class="rightcoltitlelink" href="#" id="modalclose">Close</a></div><div id="modalcontent"></div></div>');
	$('#modaldialog').hide();
	$('body').append('<div id="fade"></div>');
	$('#modalclose').click(hideModal);
	$('#fade').click(hideModal);
}

function showModal()
{
	$('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn(300);
	$('#modaldialog').fadeIn(300);
	return false;
}

function hideModal()
{
	$('#fade').fadeOut(300);
	$('#modaldialog').fadeOut(300, clearModal);

	return false;
}

function clearModal()
{
	$('#modalcontent').html('');
}

function expandBadges()
{
	clearModal();
	$('#modaltitle').html($('#sidecol h2').html());
	$('#modalcontent').append('<div id="modalbadges"></div>');
	$('#modalbadges').append($('#profile-badges ul').clone());
	$('#modalbadges li.hidebadge').show();
	showModal();
	return false;
}

function clickBadge()
{
	$(this).addClass('selected');
	$(this).blur(blurBadge);
	$(this).mouseout(blurBadge);
	return false;
}

function blurBadge()
{
	$(this).removeClass('selected');
}

function doHelp()
{
	$.ajax({
		  url: $(this).attr("href"),
		  context: this,
		  success: function(data){
			$(this).parent().after('<div class="report-help-popup"><div class="report-help-popup-inner">'+data+'<p class="closehelp"><a href="#"><span>Close help</span></a></p></div></div>');
			$(this).parent().siblings('.report-help-popup').find('.closehelp a').click(closeHelp);
			$(this).parent().siblings('.report-help-popup').slideDown();
		  }
		});
	$(this).unbind();
	$(this).click(switchHelp);
	return false;
}

function closeHelp()
{
	$(this).parents('.report-help-popup').slideToggle();
	return false;
}

function switchHelp()
{
	$(this).parent().siblings('.report-help-popup').slideToggle();
	return false;
}

function setupRunningReports()
{
	$('#usermenu ul li').prepend('<div id="umrunningreports"></div>');
	for(i = 0; i < runningReports.length; i++)
	{
		addRunningReport(runningReports[i]);
	}
}

function addRunningReport(object)
{
	object.lastprogval = 0;
	object.samecount = 0;
	object.startprogress = 0;
	object.currentpercent = 0;
	object.currentprogval = 0;
	progressUrls.push(object);
	$('#usermenu ul ul').prepend('<li class="reportrun">'+object.id+'<div class="usermenu-progress-container"><div class="usermenu-progress-background"><div class="usermenu-progress-bar" id="'+object.id.replace(/\./g,"X")+'-progressbr"><div class="usermenu-progress-bar-leftend"></div></div></div></div></li>');
}

function setupTest()
{
	$('#reportrequest').prepend('<div id="spinnerpreload"></div>');
	$("#reportrequest").submit(startTest);

	$('#reportrequestinner').prepend('<div id="spinnerpreload"></div>');
	$("#reportrequestinner").submit(startTestInner);
}

function setupReportUser()
{
	$('#username-label').html('Username');
	$('#username-element').html($('#username').attr('value'));
}

function setupHomepage()
{
	getTwitters('twitter_update_list', {
	  id: 'silktide',
	  count: 1,
	  enableLinks: true,
	  ignoreReplies: true,
	  clearContents: true,
	  template: '<span class="headline">%text%</span> <p class="info">Tweeted <a class="date" href="http://twitter.com/%user_screen_name%/statuses/%id%/">%time%</a></p>'
	});
}

var selectedReportTab = "";

function setupReport()
{
	setupAddThisReport();
	$('.report-tab').hide();
	shownhash = false;
	if(window.location.hash)
	{
		if($(window.location.hash+'.report-tab').length >= 1)
		{
			selectedReportTab = window.location.hash;
			shownhash = true;

		}
	}
	if(!shownhash)
	{
		selectedReportTab = "#summary";
	}

	currenttab = selectedReportTab;

	$('.reportablink').click(changeReportTab);
	
	$('#report-navigation li a').click(changeReportTab).each(function(){
			if($(this).attr("href") == selectedReportTab)
			{
				$(this).parent().addClass('selectedoption');
			}
		});

	$(selectedReportTab).show();

	makeTables();
	$('.report-tab ul ul li .datatable').each(function()
	{
		$(this).before(' <span class="report-showsolution link-expand">Extra detail</a>');
		$(this).parent().find('.report-showsolution').click(expandDatatable);
		$(this).hide();
	});
	setupHelp();
}

function expandDatatable()
{
	if($(this).hasClass('link-expand'))
	{
		$(this).siblings('.datatable').slideDown();
		$(this).html('Close detail');
		$(this).removeClass('link-expand');
		$(this).addClass('link-collapse');
	} else {
		$(this).siblings('.datatable').slideUp();
		$(this).html('Extra detail');
		$(this).removeClass('link-collapse');
		$(this).addClass('link-expand');
	}
}

function expandRecommendations()
{
	$(this).parent().children('li ul').parent().each(hideRecommendations);
	$(this).unbind('click').click(hideRecommendations).children('ul').slideDown();
	$(this).animate({backgroundColor: '#EEEEEE'});
	$(this).children('.report-showsolution').html('Hide solution');
	return false;
}
function hideRecommendations()
{
	$(this).unbind('click').click(expandRecommendations).children('ul').slideUp();
	$(this).animate({backgroundColor: '#FFFFFF'});
	$(this).children('.report-showsolution').html('Show solution');
}

function changeReportTab()
{
	oldtab = currenttab;
	currenttab = $(this).attr('href');
	if(currenttab == oldtab)
	{
		return false;
	}
	$(oldtab).fadeOut(80, function(){
		$(currenttab).find('.report-help-popup').hide();
		$(currenttab).fadeIn(80);
	});
	$('#report-navigation li').removeClass('selectedoption');
	$(this).parent().addClass('selectedoption');
	return false;
}

function setupLoginForm()
{
	
}

function setupClaim()
{
	$("#claimreport-instructions").each(function()
	{
		$(".claimreport-panel").each(function(){
			$("#claimreport-instructions").append("<div class=\"claimbutton\" id=\""+$(this).attr("id")+"-button\"><h3>"+$(this).children("h3").html()+"</h3><p class=\"description\">"+$(this).children("p.description").hide().html()+"</p></div>");
			$(this).children("h3").html("Instructions");
			$(this).hide();
		});
		$("#claimreport-instructions div.claimbutton").click(claimSwitch);
	});
}

function claimSwitch()
{
	newvalue = $(this).attr("id");
	$('.claimbutton').removeClass('selectedclaim');
	$(this).addClass('selectedclaim');
	nvparts = newvalue.split("-");
	newvalue = nvparts[0]+"-"+nvparts[1];
	if(newvalue != selectedclaimoption)
	{
		if(selectedclaimoption)
		{
			$("#"+selectedclaimoption).slideUp(100, claimDown);
		}
		selectedclaimoption = newvalue;
		$("#"+newvalue).slideDown();
	}
}

function claimDown()
{
	$("#"+selectedclaimoption).slideDown(100);
}

function setupRetest()
{
	if(retest)
	{
		setupRetestHTML();
		startProgressBar();
	} else {
		$('#retestNotification a').click(startRetest);
	}

}

function startProgressBar()
{
	$('#retestNotification').append('<div id="retest-progress-container"><div id="retest-progress-background"><div id="retest-progress-bar"><div id="retest-progress-bar-leftend"></div></div></div></div>');
	$('#retest-progress-background').fadeIn(1000, function() {
		$('#retest-progress-bar ').fadeIn(500);
	});
}

function startProgressBarHome()
{
	testingurl = $('#url').val();
	$('#testbox input[type=submit]').fadeOut(500, function() {
		//$('#testbox form').remove();
		$('#testbox').append('<div id="hptest-progress-container"><div id="hptest-progress-background"><div id="hptest-progress-bar"></div><div id="hptest-progress-bar-textainer"></div></div></div>');
		$('#url').css('backgroundColor', 'transparent').css('zIndex', '10').css('position', 'absolute').css('borderColor', 'transparent');
		$('#hptest-progress-bar').fadeIn(500);
	});
}

function setupRetestHTML()
{
	$('#retestNotification img').attr('src', '/theme/nibbler/templatefiles/retest-animated.gif');
	$('#retestNotification img').unwrap();
	$('#retestNotification span').html('Retesting').unwrap();
}

function startTest()
{
	isHomepage = true;
	$('.errors').fadeOut().remove();
	$("#url").animate({ backgroundColor: "#888888", borderColor: "#888888", color: "#000" }, 'slow');
	$(this).find('input.button').fadeOut();
	$('#testbox').prepend('<img id="hpspinner" src="/theme/nibbler/templatefiles/test-animated.gif" width="32" height="32" />');
	$('#hpspinner').fadeIn();
	$(this).find("input").attr('disabled', 'disabled');
	testingurl = encodeURIComponent($('#url').val());
	testingurl = testingurl.replace("http://", '').replace('https://', '');
	if(!isIE7())
	{
	    var request = YAHOO.util.Connect.asyncRequest('GET', '/toolbar/submit/?id='+testingurl+'&format=json', callbackTest);
		return false;
    }
	return true;
}

function startTestInner()
{
	isHomepage = false;
	$('.errors').fadeOut().remove();
	$("#headerurlinput").animate({ backgroundColor: "#888888", borderColor: "#888888", color: "#000" }, 'slow');
	$(this).find('input.button').fadeOut();
	$('#search').prepend('<img id="innerspinner" src="/theme/nibbler/templatefiles/inner-test-animated.gif" width="32" height="32" />');
	$('#innerspinner').fadeIn();
	$(this).find("input").attr('disabled', 'disabled');
	testingurl = encodeURIComponent($('#headerurlinput').val());
	testingurl = testingurl.replace("http://", '').replace('https://', '');
	if(!isIE7())
	{
	    var request = YAHOO.util.Connect.asyncRequest('GET', '/toolbar/submit/?id='+testingurl+'&format=json', callbackTestInner);
		return false;
    }
	return true;
}


function startRetest()
{
	if(!isIE7())
    {
	    setupRetestHTML();
	    var request = YAHOO.util.Connect.asyncRequest('GET', '/report/retest/'+turl+'/format/json', callbackRetest);
		return false;
    }
	return true;
}

var handleSuccessRetest = function(o)
{
    //setTimeout("makeRequest()", 1000);
}

var handleFailureRetest = function(o)
{

}

var handleSuccessTest = function(o)
{
    //setTimeout("makeRequest()", 1000);
}

var handleFailureTest = function(o)
{

}

var handleSuccessTestInner = function(o)
{
    //setTimeout("makeRequest()", 1000);
}

var handleFailureTestInner = function(o)
{

}

var transactionObjectTest = {
	start:function(type, args){
	},

	complete:function(type, args){
	},

	success:function(type, args){
		if(args[0].responseText !== undefined){
			var json = args[0].responseText;
			var data = eval('(' + json + ')');
		}

		if(data.error)
		{
			$('#hpspinner').fadeOut().remove();
			$("#url").animate({ backgroundColor: "#fff", borderColor: "#fff", color: "#222222" }, 'slow');
			$("#reportrequest").find('input.button').fadeTo('slow', 1);
			$("#reportrequest").find("input").removeAttr('disabled');
			if(data.url)
			{
				$("#url").val(data.url);
			}
			$("#url").focus();
			$('#url').after('<ul class="errors"><li>'+data.error+'</li></ul>');
			$('.errors').fadeIn();
			return;
		}
		if(data.redirect)
		{
			window.location = data.redirect;
		}
		if(data.status)
		{
		    if(data.status == "running")
		    {
			    statusBucket = data.bucket;
				statusId = data.statusId;
				timeStamp = data.requestTime;
				fetchedReportUrl = data.reportUrl;
			    testUrl = data.reportId;
			    nr = { "id": testUrl, "url": testUrl, "requested": timeStamp, "progresskey": statusId };
			    addRunningReport(nr);
			    startProgressBarHome();
		    }
		}
	},

	failure:function(type, args){

	},

	abort:function(type, args){

	}
};

var transactionObjectTestInner = {
	start:function(type, args){
	},

	complete:function(type, args){
	},

	success:function(type, args){
		if(args[0].responseText !== undefined){
			var json = args[0].responseText;
			var data = eval('(' + json + ')');
		}

		if(data.error)
		{
			$('#innerspinner').fadeOut().remove();
			$("#headerurlinput").animate({ backgroundColor: "#fff", borderColor: "#fff", color: "#222222" }, 'slow');
			$("#reportrequestinner").find('input.button').fadeTo('slow', 1);
			$("#reportrequestinner").find("input").removeAttr('disabled');
			if(data.url)
			{
				$("#headerurlinput").val(data.url);
			}
			$("#headerurlinput").focus();
			$('#headerurlinput').after('<ul class="errors"><li>'+data.error+'</li></ul>');
			$('.errors').fadeIn();
			return;
		}
		if(data.redirect)
		{
			window.location = data.redirect;
		}
		if(data.status)
		{
		    if(data.status == "running")
		    {
			    window.location = data.progressurl;
//			    statusBucket = data.bucket;
//				statusId = data.statusId;
//				timeStamp = data.requestTime;
//				fetchedReportUrl = data.reportUrl;
//			    testUrl = data.reportId;
//			    nr = { "id": testUrl, "url": testUrl, "requested": timeStamp, "progresskey": statusId };
//			    addRunningReport(nr);
//			    startProgressBarHome();
		    }
		}
	},

	failure:function(type, args){

	},

	abort:function(type, args){

	}
};


var transactionObjectRetest = {
	start:function(type, args){
	},

	complete:function(type, args){
	},

	success:function(type, args){
		if(args[0].responseText !== undefined){
			var json = args[0].responseText;
			var data = eval('(' + json + ')');
		}

		if(data.error)
		{
			return;
		    $('.rerunMessageNormal').each(function()
			    {
				this.style.background = 'none';
				this.style.border = 'none';
				this.style.display = 'none';
				this.style.position = 'fixed';
				this.style.top = '17%';
				this.style.left = '50%';
				this.style.marginLeft = '-300px';
				this.style.width = '600px';
				$(this).html('<div class="narrow_content"><div class="narrow_content_top"><p><a href="#" onclick="noredirect = true; return(false);" class="jqmClose"><img src="/templatefiles/fancy_closebox.png" width="30" height="30" alt="Close" /></a></p></div><div class="narrow_content_middle"><h2>Cannot retest this website</h2><p>'+data.error+'</p><p><a href="#" onclick="closeProgress(); return false;">See the old report.</a></p></div><div class="narrow_content_bottom"><span></span></div></div>');
			  }).jqm({onHide:closeProgress2}).jqmShow();
		}
		if(data.status)
		{
		    if(data.status == "running")
		    {
			    statusBucket = data.bucket;
				statusId = data.statusId;
				timeStamp = data.requestTime;
				fetchedReportUrl = data.reportUrl;
			    retestUrl = data.reportId;
			    nr = { id: retestUrl, url: retestUrl, requested: timeStamp, progresskey: statusId };
			    addRunningReport(nr);
			    startProgressBar();
		    }
		}
	},

	failure:function(type, args){

	},

	abort:function(type, args){

	}
};

var callbackTest = {
	success:handleSuccessTest,
	failure:handleFailureTest,
	customevents:{
		onStart:transactionObjectTest.start,
		onComplete:transactionObjectTest.complete,
		onSuccess:transactionObjectTest.success,
		onFailure:transactionObjectTest.failure,
		onAbort:transactionObjectTest.abort
	}
};

var callbackTestInner = {
	success:handleSuccessTestInner,
	failure:handleFailureTestInner,
	customevents:{
		onStart:transactionObjectTestInner.start,
		onComplete:transactionObjectTestInner.complete,
		onSuccess:transactionObjectTestInner.success,
		onFailure:transactionObjectTestInner.failure,
		onAbort:transactionObjectTestInner.abort
	}
};


var callbackRetest = {
	success:handleSuccessRetest,
	failure:handleFailureRetest,
	customevents:{
		onStart:transactionObjectRetest.start,
		onComplete:transactionObjectRetest.complete,
		onSuccess:transactionObjectRetest.success,
		onFailure:transactionObjectRetest.failure,
		onAbort:transactionObjectRetest.abort
	}
};

function updateStatuses()
{
	for(i = 0; i < progressUrls.length; i++)
	{
		purl = "http://"+statusBucket+".s3.amazonaws.com/"+progressUrls[i].progresskey+"?callback=?";
		$.jsonp({
			context: progressUrls[i],
			url: purl,
			complete: onCompleteStatus,
			error: onErrorStatus,
			callbackParameter: "callback"
			
		});
	}
	setTimeout(updateStatuses, 3500);
}

function onCompleteStatus()
{
	
}

function onErrorStatus()
{
	thisobject = false;
	thisobjaid = 0;
	objremoved = false;
	for(i = 0; i < progressUrls.length; i++)
	{
		if(progressUrls[i].id == this.id)
		{
			thisobjaid = i;
			thisobject = progressUrls[i];
		}
	}
	
	if(!thisobject)
	{
		return;
	}


	if(thisobject.startprogress < 100)
	{
		thisobject.startprogress += 5;
	}
	progval = Math.round((thisobject.currentpercent * 0.8) + (thisobject.startprogress * 0.2));
	if(thisobject.currentprogval == progval)
	{
	    thisobject.samecount++;
	} else {
		thisobject.currentprogval = progval;
		showStatusUserMenu(progval, thisobject.id);
		if(thisobject.id == testUrl)
		{
			showStatusHome(progval);
		}
		if(thisobject.id == retestUrl)
		{
			showStatusRetest(progval);
		}
		if(thisobject.id == normTestId)
		{
			showStatusProgbar(progval);
		}
		thisobject.samecount = 0;
		if(errmsg)
		{
			errmsg = false;

		}
	}
	if(thisobject.samecount == 36)
	{
		errmsg = true;
	}
	progressUrls[thisobjaid] = thisobject;
	return true;
}

var isprogscreen = false;

function showStatus(data)
{
	if(data.id)
	{
		updateProgress(data);
	}
}

function updateProgress(data)
{
	doit = false;
	thisobject = false;
	thisobjaid = 0;
	objremoved = false;
	for(i = 0; i < progressUrls.length; i++)
	{
		if(progressUrls[i].id == data.id)
		{
			thisobjaid = i;
			thisobject = progressUrls[i];
		}
	}

	if(!thisobject)
	{
		return;
	}


	if(thisobject.startprogress < 100)
	{
		thisobject.startprogress += 5;
	}
	percentage = parseInt(data.percentage);

	if(parseInt(data.startTs) >= thisobject.requested)
	{
	    doit = true;
	}
	if(doit && percentage)
	{
		thisobject.currentpercent = percentage;
	    if(percentage > 0 && thisobject.startprogress < 100)
	    {
			thisobject.startprogress = 100;
	    }
	    progval = Math.round((percentage * 0.8) + (thisobject.startprogress * 0.2));
	} else {
	    progval = Math.round(thisobject.startprogress * 0.2);
	}
	if(progval < thisobject.lastprogval)
	{
	    progval = thisobject.lastprogval;
	}
	else
	{
	    thisobject.lastprogval = progval;
	}
	if(thisobject.currentprogval == progval)
	{
	    thisobject.samecount++;
	} else {
		showStatusUserMenu(progval, thisobject.id);
		if(doit && percentage==100)
		{
			progressUrls.splice(thisobjaid, 1);
			objremoved = true;
		}
		if(thisobject.id == testUrl)
		{
			if(doit && percentage==100)
			{
				window.location = fetchedReportUrl;
			}
			showStatusHome(progval);
		}
		if(thisobject.id == retestUrl)
		{
			if(doit && percentage==100)
			{
				window.location = fetchedReportUrl;
			}
			showStatusRetest(progval);
		}
		if(thisobject.id == normTestId)
		{
			if(doit && percentage==100)
			{
				window.location = reportUrl;
			}
			showStatusProgbar(progval);
		}
	    thisobject.samecount = 0;
	    if(errmsg)
	    {
			errmsg = false;
			
	    }
	}
	if(thisobject.samecount == 36)
	{
	    errmsg = true;

	}
	if(!objremoved)
	{
		progressUrls[thisobjaid] = thisobject;
	}
	thisobject.currentprogval = progval;
}

function showStatusProgbar(percent)
{
	width = Math.round(601*(percent/100));
	$("#progressinner").animate({ width: width },950,"swing");
}

function showStatusHome(percent)
{
	width = Math.round(455*(percent/100));
	$("#hptest-progress-bar").animate({ width: width },950,"swing");
}

function showStatusRetest(percent)
{
	width = Math.round(319*(percent/100));
	$("#retest-progress-bar").animate({ width: width },950);
}

function showStatusUserMenu(percent, id)
{
	width = Math.round(145*(percent/100));
	oldid = id;
	id = id.replace(/\./g,"X");
	$("#"+id+"-progressbr").animate({ width: width },950);
	if(percent == 100)
	{
		$("#"+id+"-progressbr").parent().parent().html('<a href="/reports/'+oldid+'">View report</a>');
	}
}


function setupProfileEdit()
{
	$('#username-label').html('Username');
	$('#username-element').html($('#username').attr('value') + " (you cannot change this)");
	currentuserpic = $('#currentuserimage').val();
	profhtml = '';
	if(currentuserpic != '')
	{
		profhtml = profhtml + '<div class="userpicture-upload-own selected"><img src="http://'+currentuserpic+'" /><p class="userpicture-upload-changepicture"><span>Change picture</span></p></div><p id="userpicture-upload-delete" class="pseudolink">Delete current picture</p>';
	} else {
		profhtml = profhtml + '<div class="userpicture-upload-own selected"><img src="/theme/nibbler/templatefiles/user-default-160.jpg" /><p class="userpicture-upload-changepicture"><span>Change picture</span></p></div>';
	}
	$('#userimage').before('<div id="userpicture-upload">'+profhtml+'<div class="clear"></div></div>').wrap('<div id="userpicture-upload-input-container" />');
	$('#userpicture-upload-input-container').hide().prepend('<p>New profile picture:</p>').append('<span id="userpicture-upload-cancel" class="pseudolink">Cancel</span>');
	if($('#userimage-element ul.errors').length > 0)
	{
		$('#userimage-element ul.errors').appendTo('#userpicture-upload-input-container');
		$('#userpicture-upload-input-container').show();
	}
	$('#userpicture-upload .userpicture-upload-changepicture').click(replaceUserImage);
	$('#userpicture-upload-cancel').click(cancelReplaceUserImage);
	$('#userpicture-upload-delete').click(deleteUserPicture);
	if(currentuserpic == '')
	{
		$('#userpicture-upload-delete').hide();
	}


	currentimgpath = $('#currentbackgroundimage').val();
	imageshtml = '';
	for(i = 0; i < stockBackgrounds.length; i++)
	{
		thumbaddr = stockBackgrounds[i].thumb;
		if(currentimgpath == stockBackgrounds[i].path || (i == 0 && currentimgpath == ""))
		{
			imageshtml = imageshtml + '<div class="background-upload-stock selected"><img src="http://'+thumbaddr+'" /></div>';
		} else {
			imageshtml = imageshtml + '<div class="background-upload-stock"><img src="http://'+thumbaddr+'" /></div>';
		}
	}
	if(uploadedBg)
	{
		if($('#tiling').is(':checked'))
		{
			thumbaddr = uploadedBg.tiled;
		} else {
			thumbaddr = uploadedBg.thumb;
		}
		if(currentimgpath == uploadedBg.path)
		{
			imageshtml = imageshtml + '<div class="background-upload-own selected"><img src="http://'+thumbaddr+'" /><p class="background-upload-changepicture"><span>Change picture</span></p></div>';
		} else {
			imageshtml = imageshtml + '<div class="background-upload-own"><img src="http://'+thumbaddr+'" /><p class="background-upload-changepicture"><span>Change picture</span></p></div>';
		}
	} else {
		imageshtml = imageshtml + '<div class="background-upload-ownbox">Upload your own background image</div>';
	}
	$('#backgroundimage').before('<div id="background-upload">'+imageshtml+'<div class="clear"></div></div>').wrap('<div id="background-upload-input-container" />');
	$('#background-upload-input-container').hide().prepend('<p>New background image:</p>').append('<span id="background-upload-cancel" class="pseudolink">Cancel</span>');
	if($('#backgroundimage-element ul.errors').length > 0)
	{
		$('#backgroundimage-element ul.errors').appendTo('#background-upload-input-container');
		$('#background-upload-input-container').show();
	}
	$('#background-upload .background-upload-stock').click(chooseBackgroundImage);
	$('#background-upload .background-upload-own').click(chooseBackgroundImage);
	$('#background-upload .background-upload-ownbox').click(uploadNewBackgroundImage);
	$('#background-upload .background-upload-changepicture').click(replaceBackgroundImage);
	$('#background-upload-cancel').click(cancelBackgroundUpload);
	$('#tiling').change(changeBackgroundTiling);
	if(currentimgpath == '')
	{
		$('#background-upload-delete').hide();
	}
}

function deleteUserPicture()
{
	$('#userpicture-upload-delete').hide();
	$('.userpicture-upload-own img').attr('src', '/theme/nibbler/templatefiles/user-default-160.jpg');
	$('#deleteuserimage').val('delete');
	return false;
}

function cancelReplaceUserImage()
{
	$('#currentuserimage').val('cancelled');
	$('#userpicture-upload-input-container').slideUp();
}

function replaceUserImage(e)
{
	e.stopPropagation();
	$('#currentuserimage').val('');
	$('#userpicture-upload-input-container').slideDown();
}

function cancelBackgroundUpload()
{
	$('#canceluploadbackground').val('cancel');
	$('#background-upload-input-container').slideUp();
	currentimgpath = $('#currentbackgroundimage').val();
	$('.background-upload-ownbox').removeClass('selected');
	if(currentimgpath == uploadedBg.path)
	{
		$('.background-upload-own').addClass('selected');
	} else {
		for(i = 0; i < stockBackgrounds.length; i++)
		{
			if(currentimgpath == stockBackgrounds[i].path || (currentimgpath == '' && i ==0))
			{
				$('.background-upload-stock img[src="http://'+stockBackgrounds[i].thumb+'"]').parent().addClass('selected');
			}
		}
	}
}

function changeBackgroundTiling()
{
	if($(this).is(':checked'))
	{
		$('.background-upload-own img').attr('src', 'http://'+uploadedBg.tiled);
	} else {
		$('.background-upload-own img').attr('src', 'http://'+uploadedBg.thumb);
	}
}

function chooseBackgroundImage()
{
	$(this).siblings().removeClass('selected');
	selecteditem = '';
	imgsrc = $(this).find('img').attr('src').replace('http://', '');
	if(uploadedBg)
	{
		thumbaddr = uploadedBg.thumb;
		tiledaddr = uploadedBg.tiled;
		if(imgsrc == thumbaddr || imgsrc == tiledaddr)
		{
			selecteditem = uploadedBg.path;
		}
	}
	for(i = 0; i < stockBackgrounds.length; i++)
	{
		thumbaddr = stockBackgrounds[i].thumb;
		if(imgsrc == thumbaddr)
		{
			selecteditem = stockBackgrounds[i].path;
		}
	}
	$('#currentbackgroundimage').val(selecteditem);
	$('#canceluploadbackground').val('cancel');
	$('#background-upload-input-container').slideUp();
	$(this).addClass('selected');
}

function replaceBackgroundImage(e)
{
	e.stopPropagation();
	$(this).parent().removeClass('selected').siblings().removeClass('selected');
	$('#canceluploadbackground').val('');
	$('#background-upload-input-container').slideDown();
}

function uploadNewBackgroundImage()
{

	$(this).siblings().removeClass('selected');
	$('#canceluploadbackground').val('');
	$('#background-upload-input-container').slideDown();
	$(this).addClass('selected');
}

function setupProfile()
{
	setupActivityFeed();
	setupAddThis();
}

function setupAddThis()
{
    if(profileConfirmed)
    {
	    $(".col2 h1").after('<div class="sharing-buttons"><p></p></div>');

    	$('.sharing-buttons p').append('<a class="addthis_button_twitter" addthis:url="'+shareAddress+'"><img src="/theme/nibbler/templatefiles/tweet.png" alt="Tweet this profile" /></a>');
	    $('.sharing-buttons p').append('<a class="addthis_button_facebook" addthis:url="'+shareAddress+'"><img src="/theme/nibbler/templatefiles/like.png" alt="Like this profile" /></a>');
    }
}

function setupAddThisReport()
{
	$("#summmaryTop").append('<div class="sharing-buttons-report"><p></p></div>');

	$('.sharing-buttons-report p').append('<a class="addthis_button_twitter" addthis:url="'+shareAddress+'"><img src="/theme/nibbler/templatefiles/tweet.png" alt="Tweet this profile" /></a>');
	$('.sharing-buttons-report p').append('<a class="addthis_button_facebook" addthis:url="'+shareAddress+'"><img src="/theme/nibbler/templatefiles/like.png" alt="Like this profile" /></a>');
}

function setupAddThisXmasCompetition()
{
	$("#amazon-vouchers").before('<div class="sharing-buttons-competition"><p></p></div>');

	$('.sharing-buttons-competition p').append('<a class="addthis_button_twitter" addthis:url="'+shareAddress+'" addthis:title="This December, Nibbler\'s giving away $300 to the top user"><img src="/theme/nibbler/templatefiles/tweet.png" alt="Tweet this profile" /></a>');
	$('.sharing-buttons-competition p').append('<a class="addthis_button_facebook" addthis:url="'+shareAddress+'" addthis:title="This December, Nibbler\'s giving away $300 to the top user"><img src="/theme/nibbler/templatefiles/like.png" alt="Like this profile" /></a>');
}

function setupActivityFeed()
{
	$(".activityfeed").each(function()
	{
         $(".activityfeed ul ul").each(function()
		 {
            $(this).before('<a href="#" title="See all" class=\"expandlink\">[+]</a>');
			$(this).parent().find("span.expandlink").wrap("<a href=\"#\" class=\"expandlink\" />")
            $(this).parent().find("a.expandlink").click(function()
			{
                $(this).parent().find("ul").slideToggle();
                return false;
            });
        }).hide();
    });
}

function setupUrlBoxes()
{
	$("#url").each(function(){
		urlInputText[$(this).attr("id")] = $(this).keyup(trimHttp).bind('input paste', trimHttp).val();
	});
	$("#headerurlinput").each(function(){
		urlInputText[$(this).attr("id")] = $(this).keyup(trimHttp).bind('input paste', trimHttp).val();
	});
}

function makeTables()
{
	$(".multiUrl").each(
		function(i)
		{
			conts = $(this).html();
			urls = conts.split(",");
			newcontent = "";
			for(x = 0; x < urls.length; x++)
			{
				if(x != 0)
				{
					newcontent = newcontent + "<br />";
				}
				newcontent = newcontent + "<a class=\"url\" href=\"" +urls[x]+ "\">"+shortenURL(urls[x])+"</a>";
			}
			$(this).html(newcontent);
		}
	);
	
	$(".data").each(function(i)
	{
		id = $(this).attr("id");
        parnt2 = id;
		tables[tables.length] = new Array(id, parnt2, makeTable(id));
	});

}

function makeTable(tableId)
{

	//Get the headers from the table
	hdrs = $("#"+tableId+" thead tr td").get();
	myColumnDefs = new Array();

	myDataSource = new YAHOO.util.DataSource(YAHOO.util.Dom.get(tableId));
	myDataSource.responseType = YAHOO.util.DataSource.TYPE_HTMLTABLE;
	myDataSource.responseSchema = new Object();
	myDataSource.responseSchema.fields = new Array();
	sortBy = "";
	len = hdrs.length;

	for(var i = 0; i < len; i++)
	{
		hdr = hdrs[i];
		cntnt = $(hdr).html();
		if(tableId != "testsTable")
		{
			myColumnDefs[i] = {
				key:cntnt,
				label:cntnt,
				sortable:true
			};
		}
		else {
			myColumnDefs[i] = {
				key:cntnt,
				label:cntnt,
				sortable:false
			};
		}
		myDataSource.responseSchema.fields[i] = {
			key:cntnt
		};
		if(i == hdrs.length -1)
		{
			sortBy = cntnt;
		}
	}

	if(tableId != "testsTable")
	{
		var pag = new YAHOO.widget.Paginator(
		{
			rowsPerPage: 10
		}
		);
		oConfigs = {
			paginator: pag
		};
	}
	else
	{
		oConfigs = {};
	}

	myDataTable = new YAHOO.widget.DataView("c"+tableId, myColumnDefs, myDataSource, oConfigs);

	myDataTable.subscribe('renderEvent', function () {

		$(".url").each(
			function(i)
			{
//				$(this).tooltip({
//					track: true,
//					bodyHandler: function() {
//						return $(this).attr("href");
//					},
//					showURL: false
//
//				});
			});

		$(".testDesc").each(
			function(i)
			{

				ttl = $(this).attr("title");
				if(ttl != "")
				{
//					$(this).tooltip({
//						track: true,
//						bodyHandler: function() {
//							return $(this).find(".testDescSpan").html();
//						},
//						showURL: false
//					});
				}
			});

		$(".imgCol").each(
			function(i)
			{
//				$(this).tooltip({
//					track: true,
//					bodyHandler: function() {
//						return "<img src=\""+$(this).attr("href")+"\" alt=\"Preview\" style=\"width: 200px;\" />";
//					},
//					showURL: false
//				});
			}
			);
	});

	return myDataTable;
}

function shortenURL(url)
{
    //return url;
    myregexp = new RegExp(/(https?):\/\/([-\w\.]+)+(:\d+)?(\/(([\w\/_\-\.]*)(\?\S+)?)?)?/gi);
    matches = myregexp.exec(url);
    prefix = ".../";
    thisurl = $("#reporturl").attr("href");

    if(matches != null)
    {

	if(thisurl == matches[1] + "://" +  matches[2])
	{
	    prefix = "/";
	} else {
	    prefix = matches[2] + "/";
	}

	if(matches[7] != null)
	{
	    paramstring = matches[7];
	} else {
	    paramstring = "";
	}
	if(matches[6] != null)
	{
	    pathstring = matches[6];
	} else {
	    pathstring = "";
	}
	newstr = prefix + pathstring + paramstring;
	if(newstr.length == 0)
	{
	    return url;
	}
	if(newstr.length <= 30)
	{
	    return newstr;// + "1";
	}

	if(pathstring.substr(pathstring.length-1, 1) == "/")
	{
	    //oldpathstring = pathstring;
	    pathstring = pathstring.substr(0, pathstring.length-1);
	    //$(".summary").html(oldpathstring + ", " +pathstring);
	}

	newparamstring = firstandlast(paramstring, "&");
	newpathstring = firstandlast(pathstring, "/");

	newstr = prefix + newpathstring +  newparamstring;
	if(newstr.length <= 40)
	{
	    return newstr;// + "2";
	}

	newparamstring = justlast(paramstring, "&");
	newpathstring = justlast(pathstring, "/");

	newstr = prefix + newpathstring +  newparamstring;
	return newstr;// + "3";

    }
}

function firstandlast(string, seperator)
{
    parts = string.split(seperator);

    if(parts.length >= 3)
    {
	return parts[0]+seperator+"..."+seperator+parts[parts.length-1];
    } else {
	return string;
    }
}

function justlast(string, seperator)
{
    parts = string.split(seperator);

    if(parts.length >= 3)
    {
	return "..."+seperator+parts[parts.length-1];
    } else {
	return string;
    }
}

function trimHttp()
{
    currentText = $(this).val();
    if(currentText.substr(0, 14) == "http://http://")
    {
		$(this).val(currentText.substr(7, currentText.length-7));
    }
    urlInputText[$(this).attr("id")] = currentText;
}

function isIE7()
{
    return ie7;
}
function isIE()
{
  return /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);
}

$(document).ready(loader);
