var firstRun = true;
var MAX_FIELDS = 5;
var domain = "";
var objs = [];
var done = 0;
var numOfFields = 0;
var ajaxManager = $.manageAjax({manageType: 'sync', maxReq: 0, blockSameRequest: true});
var prs = []; var googles = []; var yahoos = []; var lives = []; var urls=[];
$(document).ready(function() {
   // $("#domainInfoBody").empty();
   $("#domainReset").click(function() {
        $("#domainInfoBody").empty();
        $("#domainInfoDiv").unblock();
        $("#domainInfoForm input[type=text]").each(function() {
        	$(this).val("");
        });
        objs = [];
        numOfFields = 0;
        done = 0;
        prs = [];
        googles = [];
        yahoos = [];
        lives = [];
        urls = [];
    });
});

function domainFormSubmit() {

	if (firstRun == true) {
		firstRun = false;
		$("#domainInfo").show("slow");
	}
	done = 0;
	objs = [];
	prs = [];
	googles = [];
	yahoos = [];
	lives = [];
	urls = [];
	$("#domainInfoBody").empty();
    $("#domainInfoDiv").block({
        css: {
            border: '0px solid #e6e6e6',
            padding: '5px',
            backgroundColor: '#ffffff',
            opacity: '.9',
            filter: 'alpha(opacity = 90)',
            zoom: '1',
            color: '#000000',
            width: '400px',
            textAlign: 'left'
        },
        overlayCSS: {
            border: '0px solid #e6e6e6',
            backgroundColor: '#000000',
            opacity: '.5',
            filter: 'alpha(opacity = 50)',
            zoom: '1'
        },
        message: '<div style="line-height:50px;" class="domainTitle"><img src="/images/ajax-loader.gif" style="float:left; padding-right:10px;" />Gathering Domain Statistics...</div>'
    });

    re = /(http\:\/\/)?\w+([\.\-]?\w+)*(\.\w{2,3})(\/)?$/;
 	
    $("#domainInfoForm input[type=text]").each(function() {
    	numOfFields++;
        if (re.test($(this).val())) {
            if ($(this).val().indexOf('http://') >= 0) {
                domain = jQuery.trim($(this).val());
            }
            else {
                domain = 'http://' + jQuery.trim($(this).val());
            }
            
            if (domain.substr(domain.length-1,1) != "/") {
                domain = domain + "/";
            }
            //objs.push(new objDomain(domain));
        	urls.push(domain);
        }
        else if ($(this).val() == "") {
        	//blank entry, decrease numOfFields
        	numOfFields--;
        }
        else {
            //invalid URL -- notify with blockUI
            errorMsg = "Invalid Domain. Please enter a valid URL and try again.";
            $("#domainInfoDiv").unblock().block({
                css: {
                    border: '0px solid #e6e6e6',
    				padding: '5px',
    				backgroundColor: '#ffffff',
    				opacity: '1',
    				filter: 'alpha(opacity = 90)',
    				zoom: '1',
    				color: '#000000',
    				width: '400px',
    				textAlign: 'left'
                },
                message: '<div class="domainTitle">'+errorMsg+' <input type="button" id="domainInvalid" value="OK" /></div>'
            });
       		$("#domainInvalid").click(function() {
    			$("#domainInfoDiv").unblock();
    			return false;
            });
            
            return false;
        }
    });
    if (numOfFields > 0) {
    	getData();
    } else {
    	//no inputs specified
    	errorMsg = "No domains specified. Please enter a domain and try again.";
        $("#domainInfoDiv").unblock().block({
            css: {
                border: '0px solid #e6e6e6',
				padding: '5px',
				backgroundColor: '#ffffff',
				opacity: '1',
				filter: 'alpha(opacity = 90)',
				zoom: '1',
				color: '#000000',
				width: '400px',
				textAlign: 'left'
            },
            message: '<div class="domainTitle">'+errorMsg+' <input type="button" id="domainInvalid" value="OK" /></div>'
        });
   		$("#domainInvalid").click(function() {
			$("#domainInfoDiv").unblock();
			return false;
        });
        
        return false;
	}
} 

function getData() {

		for (var i in urls) {
			domain = urls[i];
			proxy = "/cgi-bin/proxy.pl?url="
            // proxy = "http://www.bruceclay-wip.com/cgi-bin/proxy.pl?url=" //use when page is on bruceclay-wip.com
            //proxy = "http://www.bruceclay.com/cgi-bin/proxy.pl?url=" //use when page is on bruceclay.com
            //proxy = "" //use when page is on seotoolset.com
        	url1 = "http://www.seotoolset.com/cgi-bin/semToolbar.pl?type=stats&page=" + domain + "&engine=google&stat=0|1";
            url2 = "http://www.seotoolset.com/cgi-bin/semToolbar.pl?type=stats&page=" + domain + "&engine=yahoo&stat=1";
            url3 = "http://www.seotoolset.com/cgi-bin/semToolbar.pl?type=stats&page=" + domain + "&engine=live&stat=1";
          	ajaxManager.add({
        		url: proxy + escape(url1),
	        	dataType: 'xml',
	    		success: function(xml) {
		            $("stat",xml).each(function() {
	                   if ($(this).attr('id') == 0) {
	                       prs.push($(this).text());
	                   }
	                   else {
	                       googles.push($(this).text())
	                   }
	                });
	                done++;
	                displayDomainInfo();
	    		}
			});
			ajaxManager.add({
				url: proxy + escape(url2),
				dataType: 'xml',
				success: function(xml) {
				   $("stat",xml).each(function() {
				       yahoos.push($(this).text());
				   });
				   done++;
				   displayDomainInfo();
				}
				});
			ajaxManager.add({
			   url: proxy + escape(url3),
			   dataType: 'xml',
			   success: function(xml) {
			       $("stat",xml).each(function() {
			           lives.push($(this).text());
			       });
			       done++;
			       displayDomainInfo();
			   }
			});
		}
	   
}
function displayDomainInfo() {
	if (numOfFields * 3 == done) {
		for (var i in urls) {
			
    		google = googles[i] * 1;
    		yahoo = yahoos[i] * 1;
    		live = lives[i] * 1;
    		pr = prs[i] * 1;
    		url = urls[i];
    		total = (google * 1) + (yahoo * 1) + (live * 1); //multiply by 1 to convert to number
            
            //build chart with Google Chart API 
                
            //get the maximum rounded to nearest significant number                           
            datamax = Math.max(google,yahoo,live);
            digits = parseInt((Math.log(datamax)/Math.log(10))) + 1;
            fact = Math.pow(10,digits-1);
            max = Math.round(datamax/fact)*fact;
            if (max < datamax ) {
                max += fact;
            }
            
            chartURI = "http://chart.apis.google.com/chart?chs=180x75&cht=bhs&chco=0060ae|ae3900|3c8a33&chxt=x,y&chxs=0,,10|1,,,1,10,1,t&chbh=a&chf=c,lg,90,ffffff,0,e0e8f1,0.6|bg,s,e0e8f1";
            chartURI += "&chxl=0:|0|"+max/2+"|"+max+"|1:|Bing|Yahoo|Google";
            chartURI += "&chd=t:" + google + "," + yahoo + "," + live;
            chartURI += "&chxr=0,0," + max
            chartURI += "&chds=0," + max
            
            function addCommas( sValue ) {
                sValue = "" + sValue;
                var sRegExp = new RegExp('(-?[0-9]+)([0-9]{3})');                        
                while(sRegExp.test(sValue)) {
                    sValue = sValue.replace(sRegExp, '$1,$2');
                }
                return sValue;
            }
            replacement = "<tr>";
            replacement += "<td style=\"text-align:left;\"><a href=\"" + url + "\">"+url+"</a></td>";
            replacement += "<td>" + pr + "</td>";
            replacement += "<td><b>" + addCommas(total) + "</b></td>";
            replacement += "<td><a href=\"http://www.google.com/search?hl=en&lr=&ie=ISO-8859-1&safe=off&q=site%3A"+url+"\">" + addCommas(google) + "</a></td>";
            replacement += "<td><a href=\"http://siteexplorer.search.yahoo.com/search?p="+url+"&bwm=p&bwms=p&fr=sfp&fr2=seo-rd-se\">" + addCommas(yahoo) + "</a></td>";
            replacement += "<td><a href=\"http://search.msn.com/results.aspx?q=site%3A"+url+"&FORM=QBNO\">" + addCommas(live) + "</a></td>";
            replacement += "<td><img src=\"" + chartURI + "\"></td>";
            replacement += "</tr>"
            
            $("#domainInfoBody").append(replacement);
        }
        done = 0;
        numOfFields = 0;
        $("#domainInfoDiv").unblock();
        //report errors
	}
}
