
var m_loadMethod = "";
// var m_loadMethod = "loadDirect";
var m_loopAnswerHandle ;
var m_method ;
var m_parameters ;
var m_requestId ;
var m_intervalLoop = 50 ;
var m_nbrTentativesMax = 200 ;
var m_nbrTentativesFaites = 0 ;
var IE4 = (document.all);
var YuanCC = new Object();		// define namespace

// YuanCC.parser = new DOMParser();
// YuanCC.dom = YuanCC.parser.parseFromString(xml, "application/xml");
YuanCC.divId = 'Yahoo_Site_Explorer';
YuanCC.start = 1;
YuanCC.results = 10;
YuanCC.flag = true;
YuanCC.testCount = 0;
YuanCC.compaTestDone = 0;

function testJSAJAXCompatibility() {
    if(!document.getElementById) return ;
    YuanCC.compaTestDone = 1;

    loadDirect("http://webdev.yuan.cc/ajax/js.php?method=testcompatibility&id=1");
    loadCreateInnerHTML("http://webdev.yuan.cc/ajax/js.php?method=testcompatibility&id=2");
    loadCreateEl("http://webdev.yuan.cc/ajax/js.php?method=testcompatibility&id=3");

    m_loopAnswerHandle = setInterval("validationLoop()", m_intervalLoop) ;
}

function validationLoop() {

    if( false ) {
	document.getElementById(YuanCC.divId).innerHTML += '#1 ' + typeof(_1) + '<br />';
	document.getElementById(YuanCC.divId).innerHTML += '#2 ' + typeof(_2) + '<br />';
	document.getElementById(YuanCC.divId).innerHTML += '#3 ' + typeof(_3) + '<br />';
    }
    if(typeof(_1) != "undefined" || typeof(_2) != "undefined" || typeof(_3) != "undefined") {
	clearInterval(m_loopAnswerHandle) ;
	if(typeof(_1) != "undefined") {
	    m_loadMethod = "loadDirect" ;
	} else if(typeof(_3) != "undefined") {
	    m_loadMethod = "loadCreateEl" ;
	} else {
	    m_loadMethod = "loadCreateInnerHTML" ;
	}
    } else if(m_nbrTentativesFaites < m_nbrTentativesMax) {
	m_nbrTentativesFaites++ ;
	return ;
    } else {
	clearInterval(m_loopAnswerHandle) ;
//	alert("Your browser doesn't seem to support any of the techniques or the connexion with the server failed.") ;
	if( IE4 ) m_loadMethod = 'loadDirect';
	else m_loadMethod = 'loadCreateEl' ;
    }
    YuanCC.compaTestDone = 2;
}

function loadDirect(jssrc) {
    js = document.getElementById("jsajax") ;
    js.src = jssrc ;
}

function loadCreateInnerHTML(jssrc) {
    div = document.getElementById("divajax") ;
    div.innerHTML = '<scr' + 'ipt type="text/javascript" id="jsajax2"></sc' + 'ript>' ;
    js = document.getElementById("jsajax2") ;
    if(js) js.src = jssrc ;
}

function loadCreateEl(jssrc) {
    divj = document.getElementById('divajax2');
    var newEl = document.createElement('script');
    newEl.setAttribute("src", jssrc);
    divj.appendChild(newEl);
}

function loadjs(jssrc) {
    if(m_loadMethod == "") return ;
    eval(m_loadMethod + "('" + jssrc + "') ;") ;
}

YuanCC.XMLHttpRequest = function(req) {
    var re = /http:\/\/([^\/]+)\//;
    var m = re.exec(document.location);
    var n = re.exec(req.url);
    if( m[1] == n[1] ) {
	var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
	    if (xmlhttp.readyState==4) {
		if (xmlhttp.status==200) req.onload(xmlhttp);
	    }
	}
	xmlhttp.open(req.method, req.url, true);
	xmlhttp.send(null);
    } else {
	delete YuanCC.xmlhttpproxy;
	var jssrc = 'http://webdev.yuan.cc/search/xml_proxy.php?' + req.url;
	if(IE4) {
	    loadjs(jssrc);
	} else {
	    var js = document.createElement('script');
	    js.language = 'javascript';
	    js.src = jssrc;
	    document.getElementById(YuanCC.divId).appendChild(js);
	}

	YuanCC.xmlproxy = function() {
	    if( !YuanCC.xmlhttpproxy && m_nbrTentativesFaites < m_nbrTentativesMax ) {
		m_nbrTentativesFaites++ ;
		return ;
	    } else if( !YuanCC.xmlhttpproxy ) {
		clearInterval(m_loopAnswerHandle);
		alert( "No answer received. Maybe m_nbrTentativesMax should be greater. Please try again.");
		YuanCC.xmlhttpproxy = new Object();
		YuanCC.xmlhttpproxy.readyState = 4;
		YuanCC.xmlhttpproxy.status = 404;
		YuanCC.xmlhttpproxy.responseText = '';
		req.onload(YuanCC.xmlhttpproxy);
		return;
	    } else {
	    }
	    clearInterval(m_loopAnswerHandle);
	    document.getElementById(YuanCC.divId).innerHTML = '';
	    req.onload(YuanCC.xmlhttpproxy);
	}

	m_loopAnswerHandle = setInterval("YuanCC.xmlproxy()", m_intervalLoop) ;

/*
            YuanCC.xmlcount = 0;
            YuanCC.xmlproxy = function() {
                if( YuanCC.xmlcount++ > 20 ) {
                    YuanCC.xmlhttpproxy = new Object();
                    YuanCC.xmlhttpproxy.readyState = 4;
                    YuanCC.xmlhttpproxy.status = 404;
                    YuanCC.xmlhttpproxy.responseText = '';
                    req.onload(YuanCC.xmlhttpproxy);
                    return;
                }
                YuanCC.xmlcount++;
                if( YuanCC.xmlhttpproxy ) {
		    document.getElementById(YuanCC.divId).innerHTML = '';
		    req.onload(YuanCC.xmlhttpproxy);
		}
                else window.setTimeout('YuanCC.xmlproxy()', 500);
            }
            window.setTimeout('YuanCC.xmlproxy()', 500);
*/
    }
}


YuanCC.search = function() {
    if( YuanCC.compaTestDone == 0 ) testJSAJAXCompatibility();
    if( m_loadMethod == "" ) {
	YuanCC.testCount++;
	if( YuanCC.testCount < m_nbrTentativesMax+5 ) window.setTimeout('YuanCC.search()', m_intervalLoop);
	return;
    }
    m_nbrTentativesFaites = 0;
    var query = '';
    if( query == '' ) query = '' + document.location;
    var url = 'http://api.search.yahoo.com/SiteExplorerService/V1/inlinkData?appid=Yuan.CC_Web_Experiments&query=' +query+ '&results='+YuanCC.results + '&start=' + YuanCC.start;
    if( IE4 ) {
//	window.open('http://siteexplorer.search.yahoo.com/search?p=' +query+ '&bwm=i&bwms=p');
//	return;
    }
    YuanCC.XMLHttpRequest({
        method: 'GET',
        url: url,
        headers: {
            'User-agent': 'Mozilla/4.0 (compatible) Yuan.CC Web Experiments',
            'Accept': 'application/atom+xml,application/xml,text/xml'
        },
        onload: function(result) {
	    if( result.status != 200 ) { 
		return; 
	    }
	    var yahoo = document.getElementById(YuanCC.divId);
	    yahoo.innerHTML = '';
//            var parser = new DOMParser();
//            var dom = parser.parseFromString(result.responseText, "application/xml");
            var dom = YuanCC.DOMParser(result.responseText);
	    var res = dom.getElementsByTagName('Result');
	    for(var i=0; i<res.length; i++) {
		title = res[i].getElementsByTagName('Title')[0].firstChild.data;
		url = res[i].getElementsByTagName('Url')[0].firstChild.data;
		click = res[i].getElementsByTagName('ClickUrl')[0].firstChild.data;
		yahoo.innerHTML += '<a href="' + click + '">' + title+'</a><br />';
	    }
	    if( 1*dom.getElementsByTagName('ResultSet')[0].getAttribute('totalResultsAvailable') > YuanCC.start + 1*dom.getElementsByTagName('ResultSet')[0].getAttribute('totalResultsReturned') )
		yahoo.innerHTML += '<p align=left><span onclick="YuanCC.start+=YuanCC.results;YuanCC.search();">Search More...</span></p>';
	}
    });
}

YuanCC.toggle = function() {
    if( YuanCC.flag ) {
	testJSAJAXCompatibility();
	YuanCC.start=1;
	YuanCC.search();
    }
    YuanCC.flag = false;
}

YuanCC.DOMParser = function(a) {
    try{
        if(typeof ActiveXObject!="undefined"&&typeof GetObject!="undefined") {
            var b=new ActiveXObject("Microsoft.XMLDOM");
            b.loadXML(a);
            return b
        } else if(typeof DOMParser!="undefined") {
            return(new DOMParser()).parseFromString(a,"text/xml")
        } else {
            return zb(a)
        }
    } catch(c) {
        y.write(c.toString());
        y.incompatible("xmlparse")
    }
    try {
        y.write("XML xmlParse catch");
        return zb(a)
    } catch(c) {
        y.write(c.toString());
        y.incompatible("xmlparse");
        return document.createElement("div")
    }
}

document.write('<div id="divajax" style="display:none;"></div>');
document.write('<div id="divajax2" style="display:none;"></div>');
document.write('<script type="text/javascript"  id="jsajax"></script>');
document.write('<div id="' +YuanCC.divId+ '"><span onclick="YuanCC.search();">Click to Search via Yahoo Site Explorer...</span></div>');
