﻿
var mouseX,mouseY;
var browser = navigator.userAgent.toLowerCase();
var _isIE=/msie/.test(browser) && !/opera/.test(browser);
var xTable = null;
var loadTimer = null;
var tmrFinalMouse = null;
var found = false;
var elDebug = null;
var fnCallBack = null;
var bObserveFinalMouse = false;
var bFinalMouseObserved = false;
var tmrRepositionInstructions = null;

getStyle = function(oElm, strCssRule){
	var strValue = "";
	if(document.defaultView && document.defaultView.getComputedStyle){
		strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
	}
	else if(oElm.currentStyle){
		strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
			return p1.toUpperCase();
		});
		strValue = oElm.currentStyle[strCssRule];
	}
	return strValue;
}

getRealCoords = function(ele,axis)
{
	if ( ele == null )
	{
		return 0;
	}

	axis = axis.toLowerCase();
		
	// handle the absolute position case of cranks	
	if ( axis == "y" && ele && ele.style && ele.style.position == 'absolute' &&  ele.style.top != 'undefined' )
		return parseInt(ele.style.top.toString().replace('px', ""));
	
	if ( axis == "x" && ele && ele.style && ele.style.position == 'absolute' && ele.style.left != 'undefined' )
		return parseInt(ele.style.left.toString().replace('px', ""));
		
	// handle the relative position case
	elePos = (axis=="x") ?  ele.offsetLeft : ele.offsetTop;
	tempEle = ele.offsetParent;
	while(tempEle != null)
	{
		elePos += (axis=="x") ? tempEle.offsetLeft : tempEle.offsetTop;
	    if (_isIE){
	    
	        var bordLeft = parseInt(getStyle(tempEle, "border-left-width"))
	            ,bordTop = parseInt(getStyle(tempEle, "border-top-width"))
	            ;
            bordLeft = isNaN(bordLeft)?0:bordLeft;
            bordTop = isNaN(bordTop)?0:bordTop;
            
	        elePos += (axis=="x") ? bordLeft : bordTop;
	    }
	    
		tempEle = tempEle.offsetParent;
	}
	return elePos;
}


XBrowserRemoveHandler = function (target,eventName,handlerName) {
	if(!target) return;
	 
	if (target.addEventListener) { 
			target.removeEventListener(eventName, function(e){eval(handlerName)(e);}, false);
	} else if (target.attachEvent) { 
			target.detachEvent("on" + eventName, function(e){eval(handlerName)(e);});
	}
}


XBrowserAddHandler = function(target,eventName,fnHandler) { 
	var originalHandler = target["on" + eventName]; 
	if ( originalHandler ) { 
		target["on" + eventName] = function(e){ 
			XBrowserApplyHandler(this, originalHandler, e); 
			XBrowserApplyHandler(this, fnHandler, e); 
		}
	} else { 
		target["on" + eventName] = function(e) { 
		    XBrowserApplyHandler(this, fnHandler, e);
	    }
	}
}



XBrowserApplyHandler = function(target, fn, e) { 
	if (!e) e = window.event; 
		

	if (Function.prototype.call) { 
		fn.call(target, e); 
	} else { 
		target.__XBrowserElementApply = fn;  // but never checked to see if it works in netscape
		target.__XBrowserElementApply(e); 
	} 
} 

getMouse = function(e)
    {
    if (bFinalMouseObserved) return true;
    if (!e) var e = window.event;

    if (e.pageX || e.pageY) 	{
		    mouseX = e.pageX;
		    mouseY = e.pageY;
	    }
	    else if (e.clientX || e.clientY) 	{
		    mouseX = e.clientX + document.body.scrollLeft
			    + document.documentElement.scrollLeft;
		    mouseY = e.clientY + document.body.scrollTop
			    + document.documentElement.scrollTop;
	    }

        if (bObserveFinalMouse) {
            bFinalMouseObserved = true;
            //XBrowserRemoveHandler(document, "mousemove", getMouse);
               
        }
    
    elDebug = document.getElementById('displayDIV');
        if (elDebug){
            //elDebug.innerHTML = mouseX + ',' + mouseY + ':' + (mouseX-xTable);
        }
        
return true;

        if (_isIE) { // grab the x-y pos.s if browser is IE
            
            mouseX = event.clientX;// + pA.wu.getScrollPos().scrlX;
            mouseY = event.clientY;// + pA.wu.getScrollPos().scrlY;
        } else {  // grab the x-y pos.s if browser is NS
            
            mouseX = e.pageX;// + pA.wu.getScrollPos().scrlX;
            mouseY = e.pageY;// + pA.wu.getScrollPos().scrlY;
        }  
        if (mouseX < 0){mouseX = 0;}
        if (mouseY < 0){mouseY = 0;}  

        
        //if (elDebug && xTable!=null){
        
        elDebug = document.getElementById('displayDIV');
        if (elDebug){
           // elDebug.innerHTML = mouseX + ',' + mouseY + ':' + (mouseX-xTable);
        }
        
        
        return true;
    }


XBrowserAddHandler(document, "mousemove", getMouse);
//XBrowserAddHandler(window, "scroll", getMouse);



function done(){
    bObserveFinalMouse = true;
    //window.scrollBy(0,1);
    tmrFinalMouse = setInterval(CheckForPublish, 20);
}

function CheckForPublish(){
    if (!bFinalMouseObserved) return;
    clearInterval(tmrFinalMouse);
    var s;
    var dx = mouseX-xTable;
   // alert('dx:' + dx);
    if (elDebug && xTable!=null){
          s =  mouseX + ',' + mouseY + ':' + (dx);
          elDebug.innerHTML = s;
        }
    //var dX = mouseX - xTable;
    //alert(s);

      fnCallBack();
/*    
    if (dx>430 && dx<507){
        fnCallBack();
    }
*/    
}
//function showFeedDialog(){
//    alert('logged in');
//}

//function showLoginBox(){
//    alert('need to login');
//    
//    FB.ensureInit(function() {
//        var template_data = {"images":[{'src':'http://69.181.82.139/bikinibands/images/templates/templateimage1.png', 'href':'http://www.bikinibands.com'}]}
//        FB.Connect.showFeedDialog(feedbundle, template_data);


//    });
//}

function PublishToFeed(siteUrl, donePublish, discount){
    fnCallBack = donePublish;
    FB_RequireFeatures(["XFBML"], function()
        {
        
        FB.Facebook.init(apikey, receiverurl);
        var user_message_prompt = "What do you think of BikiniBands?";
        var user_message = {value: "I'm so excited about this product!"}; 
        var template_data = {"discount":discount,"images":[{'src':siteUrl + 'images/templates/templateimage1.png', 'href':siteUrl}]}
        //var x = FB.Connect.showFeedDialog(feedbundle, template_data, null, null, null, FB.RequireConnect.promptConnect, done);
        var x = FB.Connect.showFeedDialog(feedbundle, template_data, null, null, null, FB.RequireConnect.promptConnect, donePublish, user_message_prompt, user_message);
        
        
        //loadTimer = setInterval(findButton, 500);
        
        
       
      
       
       });
}

function PublishToFeed_experiment(donePublish){
    fnCallBack = donePublish;
    FB_RequireFeatures(["XFBML"], function()
        {
        FB.Facebook.init(apikey, receiverurl, {"ifUserConnected":showFeedDialog,"ifUserNotConnected":showLoginBox});
        
       });
}



getElementsByAttribute = function(attr,val,container){ 
	container = container||document;
	var all = container.all||container.getElementsByTagName('*')
	    ,arr = [];
	for(var k=0;k<all.length;k++)
		if(all[k].getAttribute(attr) == val) 
			arr[arr.length] = all[k];
	
	return arr;
}
/*
<input type="button" value="Publish" name="publish" id="publish" onclick="return wait_for_load(this, event, function() { window.feedForm.handleButton(this);this.disabled = true; });" class="inputbutton"/>
*/


function findButton() {
/*
    if (elDebug == null){
        elDebug = document.getElementById('displayDIV');
    }
  */  
    var elTitle = document.getElementById('fb_dialog_header');

    if (elTitle!=null && elTitle.innerHTML.indexOf('Publish this story')<0) return;


/*<span id="fb_dialog_header" class="fb_dialog_header">Publish this story to your Facebook profile?</span>*/

    var el = document.getElementById('RES_ID_fb_pop_dialog_table');
    if (el == null) return;



   //var els = getElementsByAttribute('name', 'fb_feedIFrame_1', document.body);
   
   //var els = getElementsByAttribute('name', 'publish', el);
 //  var iframe = els[0];
//   XBrowserAddHandler(iframe, "click", function(){alert('click');});       
  // alert(els[0].name);
   
    //if (els && els[0] && !found){
    // found = true;
     //alert('found');
    //XBrowserAddHandler(els[0], "mousemove", OnMouseMove);       
    //}
    //var left = parseInt(el.style.left);

   // if (left!=xTable) {
        xTable = parseInt(el.style.left);
        if (xTable > 100) {

                        
            //XBrowserAddHandler(el, "blur", function(){alert('table moved');});            
            clearInterval(loadTimer);  
            
//            setTimeout(function(){

//                var els = getElementsByAttribute('name', 'fb_feedIFrame_1', document.body);
//                   
//                   
//                   //var els = getElementsByAttribute('name', 'publish', el);
//                   var iframe = els[0];
//                  // theiframebody = (iframe.contentDocument)?iframe.contentDocument.body:iframe.Document.body;
//                   //theiframebody = (iframe.document)?iframe.document.body:iframe.Document.body;
//                   //alert(theiframebody);
//                   //XBrowserAddHandler(theiframebody, "click", function(){alert('click');});   
//                   //alert(iframe.name);


//                var elfb = document.getElementById('fb_dialog_content');
//           
//                var div = document.createElement('div');
//                div.style.width = el.style.width;
//                div.style.height = '200px';//el.style.height;
//                div.style.border = '1px solid red';
//                div.style.background = 'none';//Color = 'transparent';
//                
//                /*
//                div.style.position = 'absolute';
//                div.style.top = getRealCoords(el, 'y') + 'px';
//                div.style.left = getRealCoords(el, 'x') + 'px';
//                */
//                div.style.position = 'relative';
//                div.style.top = '0px';
//                div.style.left = '0px';
//                div.style.zIndex = 2000000;
//                //alert(el.style.height);
//                //document.body.appendChild(div);
//                elfb.appendChild(div);
//            }, 2000);
            
            //alert('tblmoved');
            //elDebug.innerHTML = 'X Table:' + xTable;
 //           alert(xTable);
        }
    //    return;
    //}
    
/*<iframe class="fb_feedIFrame" scrolling="no" frameborder="0" src="http://69.181.82.139/BikiniBands/xd_receiver.htm" name="fb_feedIFrame_1" style="height: 195px;">    */


    
  //  alert(xTable);
   
}






function InitRepositionInstructions(elTargetName){
    tmrRepositionInstructions = setInterval(
        function(){
            var el = document.getElementById('RES_ID_fb_pop_dialog_table');
            if (el == null) return;
            //clearInterval(tmrRepositionInstructions);
            //alert('found it');
            
            var elTarget = document.getElementById(elTargetName);        
            //elTarget.style.position = 'absolute';
            elTarget.style.top = (getRealCoords(el, 'y') - 100) + 'px';
            elTarget.style.left = getRealCoords(el, 'x') + 'px';
            //elTarget.style.visibility = 'visible';
//            elTarget.style.display = 'block';
            /*
            div.style.position = 'relative';
            div.style.top = '0px';
            div.style.left = '0px';        
            */
        }
    , 50);
}

