var visitorCode;
var xmlHttp;

//getCode();
function checkStats( ) //checks the db if the user name exists
{
	//alert("cheking name");
  //if (response != ''){ 
    // Response mode
   // message   = document.getElementById('nameCheckFailed');
    //if (response == '1'){ // if responce == 1 name exists
		//alert ("name exists");
     // message.className = 'error';
    //}else{ // else name is free cont
		//alert ("name new");
     // message.className = 'hidden';
    //} 
 // }else{
  	var browser = find_browser();
	var referrer = find_referrer();
	referrer = encodeURI(referrer);
	var resolution = find_resolution();
	var returnv = find_returnv();
	var current = find_current(); 
	current = escape(current);
	var op = find_op();
	var key = find_key();
	//storeIp();
	
//   alert('test='+current);
    url  = 'http://www.alfastats.com/resp.php?browser=' + browser +'&referrer=' + referrer +'&resolution=' + resolution+'&opsystem='+op+'&returnv='+returnv+'&site='+site+'&cur='+current+'&key='+key+'&visitorCode='+visitorCode+'';
//   	document.write(key);
	image = '<img src=\"'+ url + '\">';
	document.write(image);
   // loadXMLDoc(url);
  //}

}
//cookie funcs
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function eraseCookie(name) {
	createCookie(name,"",-1);
}
// end cookie funcs

//save ip in cookie
function storeIp(){
	var ip = new java.net.InetAddress.getLocalHost();
	var ipStr = new java.lang.String(ip);
//	document.writeln(ipStr.substring(ipStr.indexOf("/")+1));
	var fip = ipStr.substring(ipStr.indexOf("/")+1);
	createCookie('ipaddr',fip,'30');
}
//find browser
function find_browser(){
	if(navigator.appName)
		var browser=navigator.appName ;
	if(navigator.appVersion)
		var b_version=navigator.appVersion;
	var version=parseFloat(b_version)

	return "Browser name: "+ browser + "Browser version: "+ version;
}
//and find browser
//find current page
function find_current(){
	if(location.href == ""){
		return 'what is current page?';
	}
	else{
		return location.href;
	}
}
//and find current
//find keywords
 /**
 * Search Engine Keyword Highlight (http://fucoder.com/code/se-hilite/)
 *
 * This module can be imported by any HTML page, and it would analyse the
 * referrer for search engine keywords, and then highlight those keywords on
 * the page, by wrapping them around <span class="hilite">...</span> tags.
 * Document can then define styles else where to provide visual feedbacks.
 *
 * Usage:
 *
 *   In HTML. Add the following line towards the end of the document.
 *
 *     <script type="text/javascript" src="se_hilite.js"></script>
 *
 *   In CSS, define the following style:
 *
 *     .hilite { background-color: #ff0; }
 *
 *   If Hilite.style_name_suffix is true, then define the follow styles:
 *
 *     .hilite1 { background-color: #ff0; }
 *     .hilite2 { background-color: #f0f; }
 *     .hilite3 { background-color: #0ff; }
 *     .hilite4 ...
 *
 * @author Scott Yang <http://scott.yang.id.au/>
 * @version 1.5
 */

// Configuration:
Hilite = {
    /**
     * Element ID to be highlighted. If set, then only content inside this DOM
     * element will be highlighted, otherwise everything inside document.body
     * will be searched.
     */
    elementid: 'content',
    
    /**
     * Whether we are matching an exact word. For example, searching for
     * "highlight" will only match "highlight" but not "highlighting" if exact
     * is set to true.
     */
    exact: true,

    /**
     * Maximum number of DOM nodes to test, before handing the control back to
     * the GUI thread. This prevents locking up the UI when parsing and
     * replacing inside a large document.
     */
    max_nodes: 1000,

    /**
     * Whether to automatically hilite a section of the HTML document, by
     * binding the "Hilite.hilite()" to window.onload() event. If this
     * attribute is set to false, you can still manually trigger the hilite by
     * calling Hilite.hilite() in Javascript after document has been fully
     * loaded.
     */
    onload: true,

    /**
     * Name of the style to be used. Default to 'hilite'.
     */
    style_name: 'hilite',
    
    /**
     * Whether to use different style names for different search keywords by
     * appending a number starting from 1, i.e. hilite1, hilite2, etc.
     */
    style_name_suffix: true,

    /**
     * Set it to override the document.referrer string. Used for debugging
     * only.
     */
    debug_referrer: ''
};

Hilite.search_engines = [
    ['google\\.', 'q'],                             // Google
    ['search\\.yahoo\\.', 'p'],                     // Yahoo
    ['search\\.msn\\.', 'q'],                       // MSN
    ['search\\.live\\.', 'query'],                  // MSN Live
    ['search\\.aol\\.', 'userQuery'],               // AOL
    ['ask\\.com', 'q'],                             // Ask.com
    ['altavista\\.', 'q'],                          // AltaVista
    ['feedster\\.', 'q'],                           // Feedster
    ['search\\.lycos\\.', 'q'],                     // Lycos
    ['alltheweb\\.', 'q'],                          // AllTheWeb
    ['technorati\\.com/search/([^\\?/]+)', 1],      // Technorati
    ['dogpile\\.com/info\\.dogpl/search/web/([^\\?/]+)', 1, true] // DogPile
];

/**
 * Decode the referrer string and return a list of search keywords.
 */
Hilite.decodeReferrer = function(referrer) {
    var query = null;
    var regex = new RegExp('');

    for (var i = 0; i < Hilite.search_engines.length; i ++) {
        var se = Hilite.search_engines[i];
        regex.compile('^http://(www\\.)?' + se[0], 'i');
        var match = referrer.match(regex);
        if (match) {
            var result;
            if (isNaN(se[1])) {
                result = Hilite.decodeReferrerQS(referrer, se[1]);
            } else {
                result = match[se[1] + 1];
            }
            if (result) {
                result = decodeURIComponent(result);
                // XXX: DogPile's URI requires decoding twice.
                if (se.length > 2 && se[2])
                    result = decodeURIComponent(result);
                result = result.replace(/\'|"/g, '');
                result = result.split(/[\s,\+\.]+/);
                return result;
            }
            break;
        }
    }
    return null;
};

Hilite.decodeReferrerQS = function(referrer, match) {
    var idx = referrer.indexOf('?');
    var idx2;
    if (idx >= 0) {
        var qs = new String(referrer.substring(idx + 1));
        idx  = 0;
        idx2 = 0;
        while ((idx >= 0) && ((idx2 = qs.indexOf('=', idx)) >= 0)) {
            var key, val;
            key = qs.substring(idx, idx2);
            idx = qs.indexOf('&', idx2) + 1;
            if (key == match) {
                if (idx <= 0) {
                    return qs.substring(idx2+1);
                } else {
                    return qs.substring(idx2+1, idx - 1);
                }
            }
        }
    }
    return null;
};

/**
 * Highlight a HTML document using keywords extracted from document.referrer.
 * This is the main function to be called to perform search engine highlight
 * on a document.
 *
 * Currently it would check for DOM element 'content', element 'container' and
 * then document.body in that order, so it only highlights appropriate section
 * on WordPress and Movable Type pages.
 */
//Hilite.hilite = function() {
function find_key() {
    // If 'debug_referrer' then we will use that as our referrer string
    // instead.
    var q = Hilite.debug_referrer ? Hilite.debug_referrer : document.referrer;
    var e = null;
    q = Hilite.decodeReferrer(q);
	return q;
   // if (q && ((Hilite.elementid && 
    //           (e = document.getElementById(Hilite.elementid))) || 
    //          (e = document.body)))
    //{
	//Hilite.hiliteElement(e, q);
    //}
};
// end find ketwords
//find operating system
function find_op(){
	if(navigator.appVersion)
		res = navigator.appVersion;
	else
		res = "no navigator.appVersion support"
	return res;
}
//end find op system
//find refferer
function find_referrer(){
	//if(!document.referrer)
		//return 'old browser no ref support';
	if (document.referrer != '') 
		return document.referrer;
	else
		return 'direct link no ref';
}
//end find referrer

//find resolution
function find_resolution(){  

	if (self.screen) {     // for NN4 and IE4
			width = screen.width
			height = screen.height
	// Testing this first prevents firing the slow Java of NN4
	}
	else if (self.java) {   // for NN3 with enabled Java
		   var jkit = java.awt.Toolkit.getDefaultToolkit();
		   var scrsize = jkit.getScreenSize();       
		   width = scrsize.width; 
		   height = scrsize.height; 
	}
	else{
	 width = height = '?' // N2, E3, N3 w/Java off, probably Opera and WebTV
	
	}
	res = width +"x"+ height;
	return res;
	//or whatever based on the above results
}
//end find resolution

//find return visitor
function find_returnv(){
//	createCookie('counter2','1','-1');
//	return -1;
	counter = readCookie("counter2");
	//document.write('couter='+counter+'lala');

	if((counter == "")||(counter == null)||(counter == 'NaN')){ //
		var minutes = 1000*60;
		var d = new Date();
		var t = d.getTime();
		var m = t/minutes;
		createCookie('counter2','1','30');
		createCookie('last_visit2', m ,'30');
		//document.write('dif='+min_dif+'m='+m+'count='+count+'counter ='+counter+'return = 1');
		return 1;
	}
	else{
		var count = 0;
		 
		count = parseInt(counter) +1;
		//alert(count);
		var minutes = 1000*60;
		var d = new Date();
		var t = d.getTime();
		var m = t/minutes;
		m = parseInt(m);
		var last_v = readCookie("last_visit2");
		last_visit = parseInt(last_v);
		var min_dif = m - last_visit;
		//document.write('dif='+min_dif+'m='+m+'last='+last_visit+'count='+count+'counter ='+counter);
		if(min_dif > 60){
			createCookie('counter2',count,'30');
			createCookie('last_visit2', m ,'30');
			//document.write('dif='+min_dif+'m='+m+'last='+last_visit+'count='+count+'counter ='+counter+'return = '+count);
			return count;
		}
		else{
			createCookie('last_visit2', m ,'30');
			//document.write('dif='+min_dif+'m='+m+'last='+last_visit+'count='+count+'counter ='+counter+'return = -1');
			return -1;
		}
		
	}
}

//end find return visitor
checkStats();
// no use ajax functions
function getCode()
{
	
	xmlHttp=GetXmlHttpObject()
	url  = 'http://www.alfastats.com/noajax.php?ajaxx=';
	if (xmlHttp==null){
		url = url+'noajax';
	}
	else{
		url = url+'ajax';
	}
	image = '<img src=\"'+ url + '\">';
		
	
	//make request
	var visitorCode = readCookie("visitorCode");
	if((visitorCode == "")||(visitorCode == null)||(visitorCode == 'NaN')){
		//document.write(image);
		var url="http://www.alfastats.com/visitorCode.php"
		url=url+"?&site="+site;
		//alert(url);
		xmlHttp.onreadystatechange=stateChanged 
		xmlHttp.open("GET",url,true);
		xmlHttp.send(null);
	}
	else{ // ok i have the code no need for anything else here
		
		;
	}
	
	
}

function stateChanged() { 
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){ 
		//document.getElementById("txtHint").innerHTML=xmlHttp.responseText 
		visitorCode = xmlHttp.responseText ;
		alert (visitorCode);
		createCookie('visitorCode',visitorCode,'30');
	} 
}
function GetXmlHttpObject(){

	var xmlHttp=null;
	try
	{
 	// Firefox, Opera 8.0+, Safari
 	xmlHttp=new XMLHttpRequest();
 	}
	catch (e)
 	{
 	//Internet Explorer
 		try
  		{
  		xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  		}
 		catch (e)
  		{
  		xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  	}
 }
return xmlHttp;
}



