// =======================================
// = Heardable.com javascript namespace  =
// =======================================
if (typeof window.HH == 'undefined') window.HH = {};
if (typeof window.HH.fn == 'undefined') window.HH.fn = {};
if (typeof window.HH.globals == 'undefined') window.HH.globals = {};

// ============================================================
// = console.log is handy, but some browsers don't support it =
// ============================================================
// to log using javascript, use HH.fn.log('some message')
// if console.log exists, it will be used, otherwise messages will be stored in HH.custom_logger
// to retrieve messages, use HH.fn.log() without an argument
if (typeof console != 'undefined' && typeof console.log == 'function')
HH.fn.log = function(message){
	console.log(message);
}
else {
	HH.custom_logger = [];
	HH.fn.log = function(message){
		if (typeof message == 'undefined')
		var returner = HH.custom_logger;
		else{
			HH.custom_logger.push(message);
			var returner = HH.custom_logger[HH.custom_logger.length - 1];
		}	
		return returner;
	}
}

// =============
// = AJAX URLS =
// =============
HH.globals.urls = { 'comparison' 	: '/ajax_comparison_rev5.php',
'initialize' 	: '/ajax_initialize_rev.php',
'result'			: '/ajax_result_rev.php',
'stats'				: '/ajax_stats_rev.php',
'validate'		: '/ajax_check_url.php'
};

// =========================================================
// = Global variable & functions for total heardable grade =
// =========================================================
HH.globals.subscores = {};
// ========================================================
// = DO NOT SET THIS DIRECTLY, USE THE FUNCTION BELOW !!! =
// ========================================================
HH.globals.grade = 0;

// IMPORTANT TO MONITOR THIS TO PREVENT DOUBLE EVENT OBSERVERS
HH.globals.modal_launched = false;

var portTitle2=''; 
var actiontype = "";
// ===================================================
// = Grade getter/setter - USE THIS TO ACCESS GRADES =
// ===================================================
HH.fn.grade = function(new_grade){
	if (typeof(new_grade) != 'undefined') HH.globals.grade = parseInt(new_grade);
	return HH.globals.grade;
}

// ================================
// = USE THIS TO ADD TO THE GRADE =
// ================================
HH.fn.increment_grade = function(increment){
	HH.globals.grade += parseInt(increment);
	HH.fn.grade();
}

// ================================
// = USE THIS TO UPDATE THE GRADE =
// ================================
HH.fn.update_grade = function(){
	var returner = 0;
	jQuery.each(HH.globals.subscores, function(k,v){
		// subscores are stored as strings--ugh--so check to make sure the parse returned a number
		if (typeof parseFloat(v) == 'number'){
			var numeric = parseFloat(v);
		}
		else {
			var numeric = 0;
		} 
		returner += numeric;
		HH.globals.subscores[k] = numeric;
	});
	HH.fn.grade(returner);
}


HH.globals.is_blocked = false;

// ==============================
// = Block/unblock the whole UI =
// ==============================
HH.fn.toggle_block = function(msg){
	if (HH.globals.is_blocked) { //unblock
		jQuery.unblockUI();
	}
	else {
		if (typeof msg == 'undefined') var msg = null;
		jQuery.blockUI({message: msg});
	}
	HH.globals.is_blocked = ! HH.globals.is_blocked;
}

// ================================================================
// = Update the block message (do nothing if no block is present) =
// ================================================================
HH.fn.update_block = function(msg){	
	// be careful here, passing a null message is a valid way of calling blockUI!
	if (typeof msg == 'undefined') var msg = '<h1>Contacting site. Please wait...</h1>';
	if (HH.globals.is_blocked) jQuery.blockUI({message: msg});	
}

// ===============================================
// = Function to (asynchronously) validate a url =
// ===============================================
HH.fn.validate_domain = function(domain, valid_domain_callback, invalid_domain_callback){
	HH.fn.toggle_block();
	
	// show a message if the block is there for over 2 seconds
	setTimeout(	function(){ if (HH.globals.bad_domain == false) HH.fn.update_block(); },	2000);
	
	if (typeof invalid_domain_callback == 'undefined') {
		var invalid_domain_callback = function(){	
			var text = 'Oops! "' + domain + '" is not responding. Please check the domain name or try a different extension, such as ".net". ';
			var link = jQuery('<a>').attr('href', '#').addClass('unblkr').text('X');
			var html = jQuery('<h1>').text(text).append(link);
			HH.globals.bad_domain = true;
			jQuery('.unblkr').live('click', function(e){
				e.preventDefault();
				HH.fn.toggle_block();
				HH.globals.bad_domain = false;
				return false;
			})
			
			HH.fn.update_block(html);
		}
	}

	if (typeof valid_domain_callback == 'undefined') {
		var valid_domain_callback = function(){	
			HH.fn.log(domain + ' is valid.');
		}
	}

	if (domain == "yourwebsite.com" || domain == '') {

	}
	else {
		jQuery.getJSON( 
			HH.globals.urls.validate, 
			{'domain': domain},
			function(data){
				// run the appropriate callback function based on the value of data
				if (data == true) {
					HH.fn.toggle_block();							
					valid_domain_callback();
				}
				else invalid_domain_callback();
			}
		);			
	}
}


	HH.fn.reset_display = function() {
		// make sure the grade is reset
		HH.fn.grade(0);
		HH.globals.subscores = {};
		// initializeBarChart();
		jQuery(".score2").html('');
		jQuery(".score2").css("width", "0%") ;
		jQuery(".score2").append('<span class="score" style="width: 0%"></span>');
		
		var reset_funcs = ['CompletedComponent', 'Portable', 'Shareable', 'Measurable', 'Actionable', 'Sociable', 'Searchable'];
		jQuery.each(reset_funcs, function(){
			var func = eval('reset' + this);
			func();
		})

		var elms_to_hide = ['mainWrapper', 'mainResults', 'socialResults', 'portableResults', 
		'trackableResults', 'shareableResults', 'actionableResults'
		]

		jQuery.each(elms_to_hide, function(){
			jQuery('#' + this).hide();
			jQuery('#' + this + 'ButtonCont').hide();		
		})
	}

	// ====================================
	// = Function to initiate a site scan =
	// ====================================
	HH.fn.launch_scan = function(event, element, callback){
		event.preventDefault();

		if (jQuery(".scan_value", element).length > 0)	{
			var url = jQuery(".scan_value", element).val();

			// validate domain and then launch the crawler if the domain is valid
			HH.fn.validate_domain(url, function(){
				HH.fn.reset_display();
				if (callback) callback();
				jQuery('#ex2').jqmShow();			
				executeSearch();

			});
		}

		return false;	
	}

	String.prototype.trim = function() {
		// Strip leading and trailing white-space
		return this.replace(/^\s*|\s*jQuery/g, "");
	}

	// getStats
	function getStats() {

		jQuery.post(HH.globals.urls.stats, {id: sit }, function(xml) {
			// format and output result
			if (jQuery("page_crawl_count", xml).text().length > 0)
				jQuery(".lastpagecrawled").html( jQuery("page_crawl_count", xml).text() 	);	 
			
			actiontype = jQuery("site1_rescan", xml).text() ; 
		});

	}
	// /getStats


	// getSingleScanData
	function getSingleScanData() {
		// see if site has already been scanned
		jQuery.ajax({
			type: "POST",
			url: HH.globals.urls.stats,
			async: "false",
			data: {id: sit},
			success: function(msg){

				actiontype = jQuery("site1_rescan", msg).text() ; 
 
				/*jQuery.post(HH.globals.urls.comparison, {action: actiontype, id1: sit, subscore: 'portable'}, function(xml) {
					format_and_output(xml);
					jQuery.post(HH.globals.urls.comparison, {action: actiontype, id1: sit, subscore: 'sociable'}, function(xml) {
						format_and_output(xml);
						jQuery.post(HH.globals.urls.comparison, {action: actiontype, id1: sit, subscore: 'four'}, function(xml) {
							format_and_output(xml);
						}, 'xml');											
					}, 'xml');						
				}, 'xml');*/
				
 
						jQuery.post(HH.globals.urls.comparison, {action: actiontype, id1: sit, subscore: 'poll'}, function(xml) {
							format_and_output(xml);
						}, 'xml');											
 

			}
		});
	}	// /getSingleScanData


function format_and_output(xml){
	// format and output result
	jQuery(xml).find("xml").each(function(){

	 if (jQuery(this).find("error", xml).text().length > 0){

 			var elms_to_hide = [ 'mobile', 'trackable', 'shareableWrapper', 'actionableWrapper', 'socialWrapper', 'searchableWrapper']

			jQuery.each(elms_to_hide, function(){
				jQuery('#' + this).hide();
			})
			

			var portTitle2=siteurl.split("."); 
			var searchstring=siteurl.split("."); 

			jQuery("#mainContentBox").html("<h3><span style='color:#79BE26'>" + portTitle2[0].substr(0, 1) + portTitle2[0].substr(1) + "</span>." + portTitle2[1] + " <span class='smalltext' style='font-weight:normal;'></span></h3>An error was reported: " + jQuery(this).find("error", xml).text());
			jQuery(".tc-status-title").html("Error detected");
			jQuery("#leftContentBox").css("display","none");
			
 			jQuery("#mainWrapper").show();
 			
 			
 
	}
	else
	{

		jQuery(this).find("actionable").each(function(){
			jQuery("#actionableResults").html(jQuery(this).find("modal_inc_results", xml).text() );
			if (jQuery(this).find("percentage", xml).text() >= 50){
				var new_html = 	"<div id='scoreLabel'>Actionable Subscore:</div><div id='actionablePoints' ></div>" +
				"<div style='clear:both;'></div><div id='scoreSubText'>Your website scored highly." + 
				" Review your summary below for an overview of your results. </div>";
				jQuery("#actionableScoreWrapper").html(new_html);
				jQuery("#actionablePoints").css("color","#82c234");
			}
			else{
				var new_html =  "<div id='scoreLabel'>Actionable Subscore:</div><div id='actionablePoints' ></div>" + 
				"<div style='clear:both;'></div>" + 
				"<div id='scoreSubText'>Your website scored in the red! Review your summary below" + 
				" for tips on improving your score. </div>";
				jQuery("#actionableScoreWrapper").html(new_html);				
			}
			jQuery("#actionablePoints").html( jQuery(this).find("points", xml).text() + "<span style='font-size:22px'></span>" );
			jQuery("#actionableScoreBoard").html( jQuery(this).find("percentage", xml).text() );

			HH.globals.subscores['actionable'] = jQuery(this).find("points", xml).text();

			calcHeardableScore(jQuery(this).find("points", xml).text());
			addCompletedComponent () ;
			jQuery("#actionableProgressBar").css( "background", "url()" );
			jQuery(".actionable-progress-title").css("background" , "url(/dev/images/toolcontainer-topmiddle-c.gif)") ;
			jQuery(".actionable-status-title").css("color" , "#363737") ;
			jQuery(".actionable-status-title").html("Actionable scan results") ;
			jQuery('#actionableResultsButton').css("color","#4C92D4");				
			jQuery('#actionableResultsButton').html('<span style="height:30px;width:22px; background:url(/images/downarrow_trans.gif) no-repeat;margin-top:10px;border:0;line-height:30px;padding-right:25px;padding-left:0;"/>View Details');
			jQuery("#actionableProgressBar").css( "background", "url()" );
			var t = setTimeout("jQuery('#actionableResultsButtonCont').show();jQuery('#actionableProgressWrapper').html('');jQuery('#actionableScan').html('Actionable scan complete');", 500);
		});

		jQuery(this).find("measurable").each(function()
		{

			jQuery("#trackableResults").html(jQuery(this).find("modal_inc_results", xml).text() );         	    
			measurableGrade = jQuery(this).find("points", xml).text();
			HH.globals.subscores['measurable'] = measurableGrade;
			if (measurableGrade >= 50)
			{
				jQuery("#trackableScoreWrapper").html( " <div id='scoreLabel'>Measurable Subscore:</div><div id='trackablePoints' ></div><div style='clear:both;'></div><div id='scoreSubText'>Your website scored highly. Review your summary below for an overview of your results. </div>");
				jQuery("#trackablePoints").css("color","#82c234");
			}
			else
			jQuery("#trackableScoreWrapper").html( " <div id='scoreLabel'>Measurable Subscore:</div><div id='trackablePoints' ></div><div style='clear:both;'></div><div id='scoreSubText'>Your website scored in the red! Review your summary below for tips on improving your score.</div>");

			calcHeardableScore(measurableGrade);
			addCompletedComponent () ;
			jQuery("#measurableScoreBoard").html( measurableGrade  );
			jQuery("#trackablePoints").html( jQuery(this).find("points", xml).text() + "<span style='font-size:22px'></span>" );
			jQuery("#trackableProgressBar").css( "background", "url()" );
			jQuery(".trackable-progress-title").css("background" , "url(/dev/images/toolcontainer-topmiddle-c.gif)") ;
			jQuery(".trackable-status-title").css("color" , "#363737") ;
			jQuery(".trackable-status-title").html("Measurable scan results") ;
			jQuery('#trackableResultsButton').css("color","#4C92D4");
			jQuery('#trackableResultsButton').html('<span style="height:30px;width:22px; background:url(/images/downarrow_trans.gif) no-repeat;margin-top:10px;border:0;line-height:30px;padding-right:25px;padding-left:0;"/>View Details');

			jQuery("#trackableProgressBar").css( "background", "url()" );
			var t = setTimeout("jQuery('#trackableResultsButtonCont').show();jQuery('#trackableProgressWrapper').html('');jQuery('#trackableScan').html('Trackable scan complete');", 500);

		});

		jQuery(this).find("sociable").each(function()
		{
 
			jQuery("#socialResults").html(jQuery(this).find("modal_inc_results", xml).text() );   
			socialPercentage = jQuery(this).find("percentage", xml).text();
			socialPoints = jQuery(this).find("points", xml).text();
			HH.globals.subscores['sociable'] = socialPoints;										
			if (socialPercentage != parseInt(socialPercentage))
			socialPercentage = 0;
			if (jQuery(this).find("points", xml).text() != parseInt(jQuery(this).find("points", xml).text()))
			{
				socialPoints = 0
			}
			jQuery("#socialScoreWrapper").css("padding","15px 0 0 60px");
			jQuery("#socialScoreWrapper").css("width","350px");	

			if (socialPercentage >= 50)
			{
				jQuery("#socialScoreWrapper").html( " <div id='scoreLabel'>Sociable Subscore:</div><div id='socialPoints' ></div><div style='clear:both;'></div><div id='scoreSubText'>Your website scored highly. Review your summary below for an overview of your results. </div>");	
				jQuery("#socialPoints").css("color","#82c234");
			}
			else
			{
				jQuery("#socialScoreWrapper").html( " <div id='scoreLabel'>Sociable Subscore:</div><div id='socialPoints' ></div><div style='clear:both;'></div><div id='scoreSubText'>Your website scored in the red! Review your summary below for tips on improving your score. </div>");	
			}

			calcHeardableScore(socialPoints);
			addCompletedComponent () ;
			jQuery("#sociableScoreBoard").html(socialPoints);
			jQuery("#socialPoints").html( socialPoints + "<span style='font-size:22px'></span>" );
			jQuery("#socialProgressBar").css( "background", "url()" );       
			jQuery(".social-progress-title").css("background" , "url(/dev/images/toolcontainer-topmiddle-c.gif)") ;
			jQuery(".social-status-title").css("color" , "#363737") ;
			jQuery(".social-status-title").html("Sociable scan results") ;
			jQuery('#SocialResultsButton').css("color","#4C92D4");
			jQuery('#SocialResultsButton').html('<span style="height:30px;width:22px; background:url(/images/downarrow_trans.gif) no-repeat;margin-top:10px;border:0;line-height:30px;padding-right:25px;padding-left:0;"/>View Details');

			});

		jQuery(this).find("portable").each(function()
		{
			// format and output result
			jQuery("#portableResults").html( jQuery(this).find("modal_inc_results", xml).text() );	

			if (jQuery(this).find("percentage", xml).text() >= 50)
			{
				jQuery("#portableScoreWrapper").html( " <div id='scoreLabel'>Portable Subscore:</div><div id='portablePoints' ></div><div style='clear:both;'></div><div id='scoreSubText'>Your website scored highly. Review your summary below for an overview of your results. </div>");
				jQuery("#portablePoints").css("color","#82c234");
			}
			else
			{
				jQuery("#portableScoreWrapper").html( " <div id='scoreLabel'>Portable Subscore:</div><div id='portablePoints' ></div><div style='clear:both;'></div><div id='scoreSubText'>Your website scored in the red! Review your summary below for tips on improving your score. </div>");
			}

			jQuery("#portablePoints").html( jQuery(this).find("points", xml).text() + "<span style='font-size:22px'></span>" );
			HH.globals.subscores['portable'] = jQuery(this).find("points", xml).text();
			calcHeardableScore(jQuery(this).find("points", xml).text() );
			addCompletedComponent () ;
			jQuery("#portableScoreBoard").html( jQuery(this).find("points", xml).text() );     			

			jQuery("#portableProgressBar").css( "background", "url()" );
			var t = setTimeout("jQuery('#portableResultsButtonCont').show();jQuery('#portableProgressWrapper').html('');jQuery('#portableScan').html('Portable scan complete') ;  ", 500);
			jQuery(".portable-progress-title").css("background" , "url(/dev/images/toolcontainer-topmiddle-c.gif)") ;
			jQuery(".portable-status-title").css("color" , "#363737") ;
			jQuery(".portable-status-title").html("Portable scan results") ;
			jQuery('#portableResultsButton').html('<span style="height:30px;width:22px; background:url(/images/downarrow_trans.gif) no-repeat;margin-top:10px;border:0;line-height:30px;padding-right:25px;padding-left:0;"/>View Details');
			jQuery('#portableResultsButton').css("color","#4C92D4");
			
		

		});  

		jQuery(this).find("shareable").each(function()
		{
 
			if (jQuery(this).find("points", xml).text() >= 75)
			{
				jQuery("#shareableScoreWrapper").html( " <div id='scoreLabel'>Shareable Subscore:</div><div id='shareablePoints' ></div><div style='clear:both;'></div><div id='scoreSubText'>Your website scored highly. Review your summary below for an overview of your results. </div>");
				jQuery("#shareablePoints").css("color","#82c234");
			}
			else
			{
				jQuery("#shareableScoreWrapper").html( " <div id='scoreLabel'>Shareable Subscore:</div><div id='shareablePoints' ></div><div style='clear:both;'></div><div id='scoreSubText'>Your website scored in the red! Review your summary below for tips on improving your score.  </div>");
			}

			HH.globals.subscores['shareable'] = jQuery(this).find("points", xml).text();
			calcHeardableScore(jQuery(this).find("points", xml).text());
			addCompletedComponent () ;
			jQuery("#shareableScoreBoard").html( jQuery(this).find("points", xml).text()  );
			jQuery("#shareablePoints").html( jQuery(this).find("points", xml).text() + "<span style='font-size:22px'></span>" );
			jQuery("#shareableResults").html( jQuery(this).find("modal_inc_results", xml).text()  );
			jQuery("#shareableProgressBar").css( "background", "url()" );
			jQuery(".shareable-progress-title").css("background" , "url(/dev/images/toolcontainer-topmiddle-c.gif)") ;
			jQuery(".shareable-status-title").css("color" , "#363737") ;
			jQuery(".shareable-status-title").html("Shareable scan results") ;
			jQuery('#shareableResultsButton').css("color","#4C92D4");

			jQuery('#shareableResultsButton').html('<span style="height:30px;width:22px; background:url(/images/downarrow_trans.gif) no-repeat;margin-top:10px;border:0;line-height:30px;padding-right:25px;padding-left:0;"/>View Details');

			var t = setTimeout("jQuery('#shareableResultsButtonCont').show();jQuery('#shareableProgressWrapper').html('');jQuery('#shareableScan').html('Shareable scan complete');", 500);
		});

		jQuery(this).find("searchable").each(function()
		{

			jQuery("#searchableResults").html(jQuery(this).find("modal_inc_results", xml).text() );
			jQuery("#searchableScoreWrapper").css("padding","15px 0 0 60px");
			jQuery("#searchableScoreWrapper").css("width","350px");

			if (jQuery(this).find("percentage", xml).text() >= 75)
			{
				jQuery("#searchableScoreWrapper").html( " <div id='scoreLabel'>Searchable Subscore:</div><div id='searchablePoints' ></div><div style='clear:both;'></div><div id='scoreSubText'>Your website scored highly. Review your summary below for an overview of your results. </div>");
				jQuery("#searchablePoints").css("color","#82c234");
			}
			else
			{
				jQuery("#searchableScoreWrapper").html( " <div id='scoreLabel'>Searchable Subscore:</div><div id='searchablePoints' ></div><div style='clear:both;'></div><div id='scoreSubText'>Your website scored in the red! Review your summary below for tips on improving your score.</div>");
			}
			searchableGrade = jQuery(this).find("percentage", xml).text();
			jQuery("#searchableScoreBoard").html( jQuery(this).find("points", xml).text() );
			HH.globals.subscores['searchable'] = jQuery(this).find("points", xml).text();
			calcHeardableScore(jQuery(this).find("points", xml).text());
			addCompletedComponent() ;

			jQuery("#searchablePoints").html( jQuery(this).find("points", xml).text() + "<span style='font-size:22px'></span>" );
			jQuery("#searchableProgressBar").css( "background", "url()" );
			jQuery(".searchable-progress-title").css("background" , "url(/dev/images/toolcontainer-topmiddle-c.gif)") ;
			jQuery(".searchable-status-title").css("color" , "#363737") ;
			jQuery(".searchable-status-title").html("Searchable scan results") ;
			jQuery('#searchableResultsButton').css("color","#4C92D4");
			jQuery('#searchableResultsButton').html('<span style="height:30px;width:22px; background:url(/images/downarrow_trans.gif) no-repeat;margin-top:10px;border:0;line-height:30px;padding-right:25px;padding-left:0;"/>View Details');

			var t = setTimeout("jQuery('#searchableResultsButtonCont').show();jQuery('#searchableProgressWrapper').html('');jQuery('#searchableScan').html('Searchable scan complete');", 500);

			

		});
		
	}
		
		jQuery(".resultsWindow").show();
	});	
	
	
	
}


					function calcHeardableScore(componentScore) {
						HH.fn.update_grade();
						// HH.fn.increment_grade(componentScore);
						jQuery("#mainScore").html(HH.fn.grade() + '/1000');
						return HH.fn.grade();
					}

					function addCompletedComponent () {

						componentCounter++;  

						if (componentCounter == 1) {
						
						jQuery("#progress_almost").css("background", "url(/images/loader_black.gif)") ;
						jQuery("#progress_almost").css("background-repeat", "no-repeat") ;
						jQuery("#progress_almost").css("width", "206px") ;
						jQuery("#progress_almost").css("height", "16px") ;	
						jQuery("#progress_almost").css("color", "#ffffff") ;
						jQuery("#progress_almost").css("margin-left", "20px") ;
						jQuery("#progress_almost").css("padding-left", "20px") ;
						jQuery("#progress_almost").css("padding-bottom", "20px") ;	
						jQuery("#progress_almost").html("Calculating final Heardable Score...") ;
						
						}
//alert(componentCounter);
						jQuery("#mainScore").html(HH.fn.grade() + '/1000');
					 
						//jQuery("#scoreBoardTotal").html(HH.fn.grade + '/1000');

						if (componentCounter == 6) {
						
							jQuery("#progress_almost").css("height", "0px") ;	
							jQuery("#progress_almost").css("display", "none") ;	
							jQuery("#progress_almost").css("background", "url()") ;
							jQuery("#progress_almost").html("") ;

							// jQuery("#heardableScoreBox").css("display", "block");	
							scoreresult = calcHeardableScore (0);
							var portTitle2=siteurl.split("."); 
							var searchstring=siteurl.split("."); 

			
							jQuery("#mainContentBox").html("<h3><span style='color:#79BE26'>" + portTitle2[0].substr(0, 1) + portTitle2[0].substr(1) + "</span>." + portTitle2[1] + " <span class='smalltext' style='font-weight:normal;'><a href='/brand_directory.php?domain=" + siteurl + "'>view brand profile</a></span></h3>The Heardable.com brand effectiveness evaluation engine has calculated that this brand's website, affiliate network and other online assets are performing at a level of " + HH.fn.grade() + " out of a possible 1000 points. ");


							if (HH.fn.grade() < 201) {
								jQuery("#chartlist200 .score2").prepend('<a href="#">' + HH.fn.grade() + '</a> ');
								jQuery("#chartlist200 .score2").css("width", HH.fn.grade()/10 + "%") ;
								jQuery("#chartlist200 .score2").append('<span class="score" style="width: ' + HH.fn.grade()/10 + '%"></span>');
							}
							else
							{
 
								jQuery("#chartlist200 .score2").prepend('<a href="#">&nbsp;</a> ');
							}
							if (HH.fn.grade() > 200 && HH.fn.grade() < 401) {
								jQuery("#chartlist400 .score2").prepend('<a href="#">' + HH.fn.grade() + '</a> ');
								jQuery("#chartlist400 .score2").css("width", HH.fn.grade()/10 + "%") ;
								jQuery("#chartlist400 .score2").append('<span class="score" style="width: ' + HH.fn.grade()/10 + '%"></span>');
							}
							else
							{
								jQuery("#chartlist400 .score2").prepend('<a href="#">&nbsp;</a> ');
							}
							if (HH.fn.grade() > 400 && HH.fn.grade() < 601) {
								jQuery("#chartlist600 .score2").prepend('<a href="#">' + HH.fn.grade() + '</a> ');
								jQuery("#chartlist600 .score2").css("width", HH.fn.grade()/10 + "%") ;
								jQuery("#chartlist600 .score2").append('<span class="score" style="width: ' + HH.fn.grade()/10 + '%"></span>');
							}
							else
							{
								jQuery("#chartlist600 .score2").prepend('<a href="#">&nbsp;</a> ');
							}
							if (HH.fn.grade() > 600 && HH.fn.grade() < 801) {
								jQuery("#chartlist800 .score2").prepend('<a href="#">' + HH.fn.grade() + '</a> ');
								jQuery("#chartlist800 .score2").css("width", HH.fn.grade()/10 + "%") ;
								jQuery("#chartlist800 .score2").append('<span class="score" style="width: ' + HH.fn.grade()/10 + '%"></span>');
							}
							else
							{
								jQuery("#chartlist800 .score2").prepend('<a href="#">&nbsp;</a> ');
							}
							if (HH.fn.grade() > 800) {
								jQuery("#chartlist1000 .score2").prepend('<a href="#">' + HH.fn.grade() + '</a> ');
								jQuery("#chartlist1000 .score2").css("width", HH.fn.grade()/10 + "%") ;
								jQuery("#chartlist1000 .score2").append('<span class="score" style="width: ' + HH.fn.grade()/10 + '%"></span>');
							}
							else
							{
								jQuery("#chartlist1000 .score2").prepend('<a href="#">&nbsp;</a> ');
							}

							if (HH.fn.grade() < 200)
							jQuery("#mainContentBox").append("<p><br />From an online marketing perspective, this brand is performing <b>poorly</b>.</p>");
							if (HH.fn.grade() >= 200 && HH.fn.grade() < 400)
							jQuery("#mainContentBox").append("<p><br />From an online marketing perspective, this brand is performing <b>about average</b>. </p>");
							if (HH.fn.grade() >= 400 && HH.fn.grade() < 600)
							jQuery("#mainContentBox").append("<p><br />From an online marketing perspective, this brand is performing <b>better than average</b>.</p>");
							if (HH.fn.grade() >= 600 && HH.fn.grade() < 800)
							jQuery("#mainContentBox").append("<p><br />From an online marketing perspective, this brand is performing like a <b>category leader</b>.</p>");
							if (HH.fn.grade() >= 800)
							jQuery("#mainContentBox").append("<p><br />From an online marketing perspective, this brand is a <b>champion performer</b>.</p>");

							jQuery('.scroll').animate({scrollTop:0}, 'slow');
							jQuery("#mainWrapper").slideToggle('slow');

						}
					}


					//start crawl
					function crawl(){

					jQuery.ajax({
						type: "POST",
						url: HH.globals.urls.stats,
						async: "false",
						data: {id: sit},
						success: function(msg){
	  
								getSingleScanData();

								// Update results 
								jQuery("#page_crawl_count").html("Crawl complete");
								jQuery("#searchableProgressBar").css( "background", "url()" );
								jQuery('#searchableResultsButtonCont').show();
								jQuery("#actionableProgressBar").css( "background", "url()" );
								jQuery('#actionableResultsButtonCont').show();
								jQuery("#shareableProgressBar").css( "background", "url()" );

								// stop polling
								clearInterval(stats_interval);
 
					
					}
					});

					}
					
					// /crawl

					var randomnumber=Math.floor(Math.random()*1100)

					//formats domain name for screen
					function cleanedDomain(domainname) {
						if (domainname == undefined){
							return domainname;
						}
						else {
							searchstring = domainname.split(".");
							if (searchstring.length ==3)
							cleanedstring = searchstring[1] + '.' + searchstring[2];
							else
							cleanedstring = domainname;
							return cleanedstring;
						}
					}



					function resetPortable() {
						jQuery("#portableResults").html( '' );	
						jQuery("#portableScoreWrapper").html( "");
						jQuery("#portablePoints").html( "" );
						jQuery("#portableScoreBoard").html( "");
						jQuery(".portable-progress-title").css("background" , "url(/dev/images/toolcontainer-topmiddle.gif)") ;
						jQuery(".portable-status-title").html("Scanning") ;
						jQuery(".portable-status-title").css("color", "#ffffff") ;
						jQuery('#portableResultsButton').html('');
						jQuery("#portableProgressBar").css("background", "url(/dev/images/refresh-animated.gif)") ;
						jQuery("#portableProgressBar").css("background-repeat", "no-repeat") ;
						jQuery("#portableProgressBar").css("width", "16px") ;
						jQuery("#portableProgressBar").css("height", "16px") ;

					}

					function resetShareable() {
						jQuery("#shareableResults").html( '' );	
						jQuery("#shareableScoreWrapper").html( "");
						jQuery("#shareablePoints").html( "" );
						jQuery("#shareableScoreBoard").html( "");
						jQuery(".shareable-progress-title").css("background" , "url(/dev/images/toolcontainer-topmiddle.gif)") ;
						jQuery(".shareable-status-title").html("Scanning") ;
						jQuery(".shareable-status-title").css("color", "#ffffff") ;
						jQuery('#shareableResultsButton').html('');
						jQuery("#shareableProgressBar").css("background", "url(/dev/images/refresh-animated.gif)") ;
						jQuery("#shareableProgressBar").css("background-repeat", "no-repeat") ;
						jQuery("#shareableProgressBar").css("width", "16px") ;
						jQuery("#shareableProgressBar").css("height", "16px") ;
					}

					function resetMeasurable() {
						jQuery("#trackableResults").html( '' );	
						jQuery("#trackableScoreWrapper").html( "");
						jQuery("#trackablePoints").html( "" );
						jQuery("#measurableScoreBoard").html( "");
						jQuery(".trackable-progress-title").css("background" , "url(/dev/images/toolcontainer-topmiddle.gif)") ;
						jQuery(".trackable-status-title").html("Scanning") ;
						jQuery(".trackable-status-title").css("color", "#ffffff") ;
						jQuery('#trackableResultsButton').html('');
						jQuery("#trackableProgressBar").css("background", "url(/dev/images/refresh-animated.gif)") ;
						jQuery("#trackableProgressBar").css("background-repeat", "no-repeat") ;
						jQuery("#trackableProgressBar").css("width", "16px") ;
						jQuery("#trackableProgressBar").css("height", "16px") ;

					}

					function resetActionable() {
						jQuery("#actionableResults").html( '' );	
						jQuery("#actionableScoreWrapper").html( "");
						jQuery("#actionablePoints").html( "" );
						jQuery("#actionableScoreBoard").html( "");
						jQuery(".actionable-progress-title").css("background" , "url(/dev/images/toolcontainer-topmiddle.gif)") ;
						jQuery(".actionable-status-title").html("Scanning") ;
						jQuery(".actionable-status-title").css("color", "#ffffff") ;
						jQuery('#actionableResultsButton').html('');
						jQuery("#actionableProgressBar").css("background", "url(/dev/images/refresh-animated.gif)") ;
						jQuery("#actionableProgressBar").css("background-repeat", "no-repeat") ;
						jQuery("#actionableProgressBar").css("width", "16px") ;
						jQuery("#actionableProgressBar").css("height", "16px") ;
					}
					function resetSociable() {
						jQuery("#socialResults").html( '' );	
						jQuery("#socialScoreWrapper").html( "");
						jQuery("#socialPoints").html( "" );
						jQuery("#sociableScoreBoard").html( "");
						jQuery(".social-progress-title").css("background" , "url(/dev/images/toolcontainer-topmiddle.gif)") ;
						jQuery(".social-status-title").html("Scanning") ;
						jQuery(".social-status-title").css("color", "#ffffff") ;
						jQuery('#SociableResultsButton').html('');
						jQuery("#socialProgressBar").css("background", "url(/dev/images/refresh-animated.gif)") ;
						jQuery("#socialProgressBar").css("background-repeat", "no-repeat") ;
						jQuery("#socialProgressBar").css("width", "16px") ;
						jQuery("#socialProgressBar").css("height", "16px") ;
					}
					function resetSearchable() {
						jQuery("#searchableResults").html( '' );	
						jQuery("#searchableScoreWrapper").html( "");
						jQuery("#searchablePoints").html( "" );
						jQuery("#searchableScoreBoard").html( "");
						jQuery(".searchable-progress-title").css("background" , "url(/dev/images/toolcontainer-topmiddle.gif)") ;
						jQuery(".searchable-status-title").html("Scanning") ;
						jQuery(".searchable-status-title").css("color", "#ffffff") ;
						jQuery('#searchableResultsButton').html('');
						jQuery("#searchableProgressBar").css("background", "url(/dev/images/progress-indicator.gif)") ;
						jQuery("#searchableProgressBar").css("background-repeat", "no-repeat") ;
						jQuery("#searchableProgressBar").css("width", "32px") ;
						jQuery("#searchableProgressBar").css("height", "22px") ;
					}



					function resetCompletedComponent () {
						componentCounter = 0 ;   
					
						jQuery("#mainContentBox").append("");
						jQuery("#mainScore").html("0/1000");

					}


					function executeSearch() {
				 
					



						
						

						if (jQuery("input.scan_value").length > 0) {
							searchstring = jQuery("input.scan_value").val().split(".");
							if (searchstring.length ==3){
								
								if (searchstring[0] == "www"){
									cleanedstring = searchstring[1] + '.' + searchstring[2];
			 						portTitle2[0] = searchstring[1];
			 						portTitle2[1] = searchstring[2];
								}
								else{
									cleanedstring = searchstring[0] + '.' + searchstring[1] + '.' + searchstring[2];
									portTitle2[0] = searchstring[0];
			 						portTitle2[1] = searchstring[1] + '.' + searchstring[2];
					 
								}
								//cleanedstring = searchstring[1] + '.' + searchstring[2];
							}
							else
							cleanedstring = jQuery("input.scan_value").val();
							siteurl = cleanedstring;		
						}
				 
						if (jQuery("input#search4").length > 0) {
							searchstring = jQuery("input#search4").val().split(".");
							if (searchstring.length ==3)
							cleanedstring = searchstring[1] + '.' + searchstring[2];
							else
							cleanedstring = jQuery("input#search4").val();
							siteurl = cleanedstring;		

						}


						// get site id
						jQuery.ajax({
							type: "POST",
							url: HH.globals.urls.initialize,
							data: "url=" + siteurl,
							async: false,
							success: function(xml){

								if (jQuery("siteid", xml).text().length > 0){
									sit = jQuery("siteid", xml).text();
								}

								// initiate site crawl
								crawl(); // crawl initiates crawler and starts getMeasurable, getSearchable, getActionable and getShareable

								// Collect progress stats
								statsValue = '';
								stats_interval = setInterval(getStats,3000);

								// clear grade
								measurableGrade = "";

							}
						});
					}
					
					
					
/*
					function initializeBarChart() {
						jQuery("#scorebar .portable_bar").css( "width",  "2px"	);	
						jQuery("#scorebar .shareable_bar").css( "width",  "2px"	);	
						jQuery("#scorebar .measurable_bar").css( "width",  "2px"	);	
						jQuery("#scorebar .actionable_bar").css( "width",  "2px"	);	
						jQuery("#scorebar .sociable_bar").css( "width",  "2px"	);	
						jQuery("#scorebar .searchable_bar").css( "width",  "2px"	);	
						jQuery('#scorebar .portable_bar a').simpletip({ fixed: false, position: 'top' , content: 'Portable: 0' ,offset: [-55, -70]  });
						jQuery('#scorebar .shareable_bar a').simpletip({ fixed: false, position: 'top' , content: 'Shareable: 0' ,offset: [-55, -70]  });
						jQuery('#scorebar .measurable_bar a').simpletip({ fixed: false, position: 'top' , content: 'Measurable: 0' ,offset: [-55, -70]  });
						jQuery('#scorebar .actionable_bar a').simpletip({ fixed: false, position: 'top' , content: 'Actionable: 0',offset: [-55, -70]  });
						jQuery('#scorebar .sociable_bar a').simpletip({ fixed: false, position: 'top' , content: 'Sociable: 0',offset: [-55, -70]  });
						jQuery('#scorebar .searchable_bar a').simpletip({ fixed: false, position: 'top' , content: 'Searchable: 0',offset: [-55, -70]  });
					}

					function updateBarChart() {

						// display each score length within its appropriate space. 
						// max actionable points = 200. this represents 1/5 of 600 pixel wide score bar. which is 120 pixels. 
						// ( actionable score / 200 ) * 120 = width
						// ( shareable score / 150 ) * 90 = width
						// ( Searchable score / 150 ) * 90 = width
						// ( Sociable score / 200 ) * 120 = width
						// ( Portable score / 200 ) * 120 = width
						// ( Measurable score / 100 ) * 60 = width

						// only update if there is a value. 
						var margin = 2;		
						var ratio = 3/5;
						
						String.prototype.capitalize = function(){
						    return this.replace(/\S+/g, function(a){
						        return a.charAt(0).toUpperCase() + a.slice(1).toLowerCase();
						    });
						};
						
						jQuery.each(HH.globals.subscores, function(key,value){
							var score = parseFloat(value);
							if (score > 0 ){
								var bar_width = (score * ratio) + margin + "px";
								jQuery('#scorebar .'+ key +'_bar').css( "width",  bar_width	);	
								jQuery('#scorebar .'+ key +'_bar a').simpletip(); // Access the API of a previously initatied simpletip 
								var api = jQuery('#scorebar .'+ key +'_bar a').eq(0).simpletip(); // Perform a simple API call to update tooltip contents
								api.update(key.capitalize() + ': ' + score);
							}
						});
					}
*/
					var portTitle = "";
					var componentCounter = 0;
					var sit = '';




					jQuery.noConflict();  

					jQuery(document).ready(function(){ 
						//jQuery.blockUI.defaults.css = {};

						jQuery('.siteTitle1').ajaxError(function(event, request, settings){
							HH.fn.log("Error requesting page " + settings.url + "");
						});
//jQuery('#ex2').jqmShow({onShow: jQuery(".siteTitle1").html('aaa' )});	
						// load modal - ONLY DO THIS ONCE!
						/*
						jQuery('#ex2').jqm({ajax: HH.globals.urls.result, trigger: false, onLoad: function(){
							if (! HH.globals.modal_launched){
								jQuery("#searchform").bind('submit', function(e) {
									var that = this;
									var callback = function(){
										var searchval = jQuery('.scan_value', that).val();
										jQuery('.scroll').animate({scrollTop:0}, 'slow');
										jQuery("#mainWrapper").hide('slow');


 if (searchval.length > 0) {
			searchstring = searchval.split(".");
 
			if (searchstring.length ==3){
					jQuery(".siteTitle1").html(searchstring[0] );
					jQuery(".siteTitle2").html("." + searchstring[1] + '.' + searchstring[2]);
			}
			else {
					jQuery(".siteTitle1").html(searchstring[0] );
					jQuery(".siteTitle2").html("." + searchstring[1] );
			}
}	
			
										//var searchstring = searchval.split(".");
										//if (searchstring.length ==3)
										//var portTitle = searchstring[1] + '.' + searchstring[2];
										//else
										//var portTitle = searchval;

										//if ( portTitle.length > 0 ) 
										//{
										//	var portTitle2=portTitle.split("."); 
										//	jQuery(".siteTitle1").html(portTitle2[0] );
										//	jQuery(".siteTitle2").html("." + portTitle2[1] );
										//}
									}
									HH.fn.launch_scan(e, that, callback);
								});
								HH.globals.modal_launched = true;				
							}		
							}});
		*/
							jQuery(".scan_form").bind('submit', function(e) {
								HH.fn.launch_scan(e, this);
							});

							// preload images
							//jQuery.preloadCssImages();

							var componentCounter = 0;
							var sit = '';
						});
				