
var tsec = new Date().getTime();

function writeSWFTag(){
	var swf_url = "http://www.questioning.jp/swf/bpbase.swf";
	//var swf_url = "http://projects.dynalogue.com/dev/audi/swf/bpbase.swf";
	
	var color_str = "#ffffff";
	if(questioningBlogpartsType == "black") color_str = "#000000";
	
	var html = '<div id="questioningDiv"><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="150" height="284" id="qexternal" align="middle">'
	         + '<param name="FlashVars" value="c='+questioningBlogpartsType+'&ts='+tsec+'" />'
	         + '<param name="allowScriptAccess" value="always" />'
	         + '<param name="movie" value="' + swf_url + '" />'
	         + '<param name="quality" value="high" />'
	         + '<param name="bgcolor" value="#ffffff" />'
	         + '<embed src="' + swf_url + '" FlashVars="c='+questioningBlogpartsType+'&ts='+tsec+'" quality="high" bgcolor="#ffffff" width="150" height="284" name="qexternal" align="middle" '
	         + ' type="application/x-shockwave-flash" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer" />'
	         + '</object></div>';
	document.write(html);
}

// ExternalInterface
if(checkBrowser() == "MSIE") {
	document.write('<div id="Kuru2_float" style="position:absolute;z-index:1;"> </div>');
}
else {
	var pm_dl = document.createElement('div');
	pm_dl.setAttribute('id','Kuru2_float');
	pm_dl.style.position = 'absolute';
	pm_dl.style.zIndex = this.zIndex;
	document.body.appendChild(pm_dl);
}

writeSWFTag();



var oKuru2SampleLayer = "";
var Kuru2Sample_flashvars_labels = ["rssurl", "ts"];
var Kuru2Sample_flashvars_values = [questioningBlogURL, tsec];
var Kuru2Sample_zIndex = 1;
var Kuru2SampleInited = false;

function loadKuru2Sample(){

	oKuru2SampleLayer = new SWFLayer();
	oKuru2SampleLayer.zIndex = Kuru2Sample_zIndex;
	oKuru2SampleLayer.swf_url = "http://www.questioning.jp/swf/AudiQuestioningMan.swf";
	//oKuru2SampleLayer.swf_url = "http://projects.dynalogue.com/dev/audi/swf/AudiQuestioningMan.swf";
	oKuru2SampleLayer.layer_name = "Kuru2_float";
	
	oKuru2SampleLayer.flashvars_labels = Kuru2Sample_flashvars_labels;
	oKuru2SampleLayer.flashvars_values = Kuru2Sample_flashvars_values;
	
	oKuru2SampleLayer.create();
	oKuru2SampleLayer.setSize("full","full");
	oKuru2SampleLayer.setWindowAlign('left');
	oKuru2SampleLayer.setWindowValign('top');

	if(checkBrowser() == "Safari"){
		window.resizeBy(1,0);
	}
	this.hideKuru2Sample();
	
	qm_updateFlag();
	
	setTimeout('qm_updateFlag()', 4000);
}
eventObserve(window, 'load', loadKuru2Sample, false);


function resizeKuru2Sample(){
	if(Kuru2SampleInited) {
		oKuru2SampleLayer.correctWindowSize();
		oKuru2SampleLayer.setWindowAlign('left');
		oKuru2SampleLayer.setWindowValign('top');
	}
}
eventObserve(window, 'resize', resizeKuru2Sample, false);


function scrollKuru2Sample(){
	if(Kuru2SampleInited) {
		oKuru2SampleLayer.setWindowAlign('left');
		oKuru2SampleLayer.setWindowValign('top');
		thisMovie("aexternal").updateWindowScroll(qm_setQDivDPos());
	}
	
	qm_updateFlag();

}
eventObserve(window, 'scroll', scrollKuru2Sample, false);


function checkBrowser(){
	var uName = navigator.userAgent;
	if (uName.indexOf("Safari") > -1) return "Safari";
	if (uName.indexOf("MSIE") > -1){
		return "MSIE";
	}
	return "Netscape";
}

if(checkBrowser() != "Safari"){
	document.getElementsByTagName("html")[0].style.overflow = "scroll";

}


function hideKuru2Sample(){
//	oKuru2SampleLayer.setVisible("hidden");
	oKuru2SampleLayer.setSize(1,1);
	oKuru2SampleLayer.setWindowAlign('right');
	oKuru2SampleLayer.setWindowValign('bottom');
}

function showKuru2Sample(){
	Kuru2SampleInited = true;
	
//	oKuru2SampleLayer.setVisible("visible");
	oKuru2SampleLayer.setSize("full","full");
	oKuru2SampleLayer.setWindowAlign('left');
	oKuru2SampleLayer.setWindowValign('top');
}


function qm_setQDivDPos() {
	var sx = window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0;
	var sy = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
	
	var p = qm_setQDivPos();
	p.x = p.x - sx;
	p.y = p.y - sy;
	
	return p;
}


function qm_setQDivPos() {
	var p = { x:0, y:0 };
	/*
	var ret = YAHOO.util.Dom.getXY('questioningDiv');
	
	p.x = ret[0];
	p.y = ret[1];
	*/
	
	p = getPosition(document.getElementById('questioningDiv'));
	
	return p;
}

function qm_getWindowSize() {
	var r = { w:0, h:0}
	if( typeof( window.innerWidth ) == 'number' ) { // Non-IE
		r.w = window.innerWidth;
		r.h = window.innerHeight;
	}
	else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) { // IE 6+ in 'standards compliant mode'
		r.w = document.documentElement.clientWidth;
		r.h = document.documentElement.clientHeight;
	}
	else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) { //IE 4 compatible
		r.w = document.body.clientWidth;
		r.h = document.body.clientHeight;
	}
	return r;
}

function qm_isStartAnimate() {
	var divDPosition = qm_setQDivDPos();
	if(divDPosition.y + 284 >= 0) {
		var windowSize = qm_getWindowSize();
		if(divDPosition.y <= windowSize.h) {
			return true;
		}
		else {
			return false;
		}
	}
	else {
		return false;
	}
}

var qm_updateFlagID;
function qm_updateFlag() {
	if(thisMovie("qexternal").updateStartingAnimationFlag) {
		thisMovie("qexternal").updateStartingAnimationFlag(qm_isStartAnimate());
	}
	else {
		if(qm_updateFlagID != null) {
			clearTimeout(qm_updateFlagID);
		}
		qm_updateFlagID = setTimeout("qm_updateFlag()", 500);
	}
}

function thisMovie(movieName) {
	if (navigator.appName.indexOf("Microsoft") != -1) {
		return window[movieName];
	} else {
		return document[movieName];
	}
}



var agt = navigator.userAgent.toLowerCase();
var is_ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
var is_gecko = (agt.indexOf('gecko') != -1);
var is_opera = (agt.indexOf("opera") != -1);

function getElementStyle(targetElm,IEStyleProp,CSSStyleProp) {
	var elem = targetElm;
	if (elem.currentStyle) {
		return elem.currentStyle[IEStyleProp];
	} else if (window.getComputedStyle) {
		var compStyle = window.getComputedStyle(elem,"");
		return compStyle.getPropertyValue(CSSStyleProp);
	}
}

function getPosition(that) {
	var targetEle = that;
	var pos = new function(){ this.x = 0; this.y = 0; }
	while( targetEle ){
		pos.x += targetEle.offsetLeft; 
		pos.y += targetEle.offsetTop; 
		targetEle = targetEle.offsetParent;
		if ((targetEle) && (is_ie)) {
			pos.x += (parseInt(getElementStyle(targetEle,"borderLeftWidth","border-left-width")) || 0);
			pos.y += (parseInt(getElementStyle(targetEle,"borderTopWidth","border-top-width")) || 0);
		}
	}
	if (is_gecko) {
		var bd = document.getElementsByTagName("BODY")[0];
		pos.x += 2*(parseInt(getElementStyle(bd,"borderLeftWidth","border-left-width")) || 0);
		pos.y += 2*(parseInt(getElementStyle(bd,"borderTopWidth","border-top-width")) || 0);
	}
	return pos;
}


var qm_keyword = "";

function qm_setKeyword(str) {
	qm_keyword = str;
	Hilite.debug_referrer = "http://www.google.com/search?q=" + str;
	Hilite.hilite(str);
}

function qm_getKeywordPosition() {
	if(qm_keyword != "") {
		if(document.getElementById("qh0") != null) {
			var p = getPosition(document.getElementById("qh0"));
			return p;
		}
		else {
			return null;
		}
	}
	else {
		return null;
	}
}

function qm_getKeywordDPosition() {
	var p = qm_getKeywordPosition();
	
	if(p == null) {
		return {x:0,y:0};
	}
	else {
		var sx = window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0;
		var sy = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
		
		p.x = p.x - sx;
		p.y = p.y - sy;
		
		return p;
	}
}


/**
 * 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
 */

var qm_cnt = 0;

// 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: '',
    
    /**
     * 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: false,

    /**
     * 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: false,

    /**
     * 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
];

/**
 * 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 DOM element with a list of keywords.
 */
Hilite.hiliteElement = function(elm, query) {
    if (!query || elm.childNodes.length == 0)
	return;

    qre = new RegExp(query, "ig");

    var textproc = function(node) {
        var match = qre.exec(node.data);
        if (match) {
       //	alert("node.data : " + node.data)
       // 	console.debug("node.data : " + node.data);
            var val = match[0];
            var node2 = node.splitText(match.index);
       // 	alert("node2.data : " + node2.data)
       // 	console.debug("node2.data : " + node2.data);
            var node3 = node2.splitText(val.length);
      // 	alert("node2.data after : " + node2.data)
      // 	alert("node3.data : " + node3.data)
        //	console.debug("node2.data after : " + node2.data);
        //	console.debug("node3.data : " + node3.data);
        	
            var span = node.ownerDocument.createElement('SPAN');
            node.parentNode.replaceChild(span, node2);
            span.setAttribute('id', 'qh'+qm_cnt);
        //    span.appendChild(node2);
            span.innerHTML = node2.data;
            
            qm_cnt++;
            return span;
        } else {
            return node;
        }
    };
    Hilite.walkElements(elm.childNodes[0], 1, textproc);
};

/**
 * 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(str) {
	var q = str;
    var e = null;
    if (q && (e = document.body)) {
		Hilite.hiliteElement(e, q);
    }
};

Hilite.walkElements = function(node, depth, textproc) {
    var skipre = /^(script|style|textarea)/i;
    var count = 0;
    while (node && depth > 0) {
        count ++;
        if (count >= Hilite.max_nodes) {
            var handler = function() {
                Hilite.walkElements(node, depth, textproc);
            };
            setTimeout(handler, 50);
            return;
        }

        if (node.nodeType == 1) { // ELEMENT_NODE
            if (!skipre.test(node.tagName) && node.childNodes.length > 0) {
                node = node.childNodes[0];
                depth ++;
                continue;
            }
        } else if (node.nodeType == 3) { // TEXT_NODE
            node = textproc(node);
        }

        if (node.nextSibling) {
            node = node.nextSibling;
        } else {
            while (depth > 0) {
                node = node.parentNode;
                depth --;
                if (node.nextSibling) {
                    node = node.nextSibling;
                    break;
                }
            }
        }
    }
};

// Trigger the highlight using the onload handler.
if (Hilite.onload) {
    if (window.attachEvent) {
        window.attachEvent('onload', Hilite.hilite);
    } else if (window.addEventListener) {
        window.addEventListener('load', Hilite.hilite, false);
    } else {
        var __onload = window.onload;
        window.onload = function() {
            Hilite.hilite();
            __onload();
        };
    }
}
