function _ib_fixLinks(doc, element) {
  var anchors = element.getElementsByTagName('a');
  for(var i=0;i<anchors.length;i++) {
    var anchor = anchors[i];
    if (anchor.getAttribute('skip') == '1') continue;
    if (anchor.getAttribute('post') == '1') {
      var href=anchor.getAttribute('href');
      href = href.replace(/http[s]?:\/\/[^\/]+/,'');
      __ibAddEventHandler(anchor, 'click', function(ev){
        _ibPostToServer(doc, href);
        if (!ev) ev = window.event;
        if(ev.preventDefault){ev.stopPropagation();ev.preventDefault();}
        ev.returnValue = false;
        return false;
      });
    } else {
      if (anchor.getAttribute('script') == '1') {
          var scriptAnchr = anchor;
	      __ibAddEventHandler(anchor, 'click', function(ev) {
	        var x = doc;
	        url = scriptAnchr.getAttribute('hrefx'); 
	    	url = url.replace(/http[s]?:\/\/[^\/]+/,'');
  		    if (__ibIsPlugin()) {
		      var ibHttp = new IB_HTTP();
		      ibHttp.getAsync(url, function(response) {eval(response);});    
		    } else {
			  new Ajax.Request(url, {method: 'get', onSuccess: function(transport) {eval(transport.responseText);}});		  
		    }
            var params = '';
		   	scriptAnchr.setAttribute('href', 'http://'+_ib_domain+scriptAnchr.getAttribute('href').replace(/http[s]?:\/\/[^\/]+/,'')+params);
		    scriptAnchr.setAttribute('target', '_blank');
		  });
      } else {
        var anchr = anchor;
        __ibAddEventHandler(anchor, 'click', function(){return _ibNavigateToServer(doc, anchr);});
      } 
    }
  }
};

function _ib_closeStatus(doc, manual) {
  if (manual)
  	__ibSetDomainCookie(doc, 'ibShown', '1', 30);
  _ib_scroll(doc, doc.getElementById('ibTracking'), 0, -1, 200, 10); 
};

function _ibPostToServer(doc, url) {
  if (__ibIsPlugin()) {
    var ibHttp = new IB_HTTP();
    if (doc.getElementById('_ibwatchlink'))
      doc.getElementById('_ibwatchlink').innerHTML = 'saving....';
    ibHttp.getAsync(url, function(response) {
      if (doc.getElementById('_ibwatchlink'))
        doc.getElementById('_ibwatchlink').innerHTML = response;
      if (response.indexOf('watching="n"') != -1) {
        __ibSetDomainCookie(doc, 'ibw', 'n', 365);
      } else {
        __ibSetDomainCookie(doc, 'ibw', 'y', 365);
      }
      if (doc.getElementById('_ibwatchlink'))
        _ib_fixLinks(doc, doc.getElementById('_ibwatchlink'));
    });    
  } else {
    new Ajax.Updater('_ibwatchlink', url, {asynchronous:true, evalScripts:true, onLoading:function(request, json){showProgress('_ibwatchlist')}, onComplete:function(transport){_ib_fixLinks(doc, doc.getElementById('_ibwatchlink'));}});
  }
  return false;
};

function _ibNavigateToServer(doc, anchor) {
  if (__ibIsPlugin()) {
    var params = '';
    if (doc.all) { params="?ibPluginRd=1"; }
   	anchor.setAttribute('href', 'http://'+_ib_domain+anchor.getAttribute('href').replace(/http[s]?:\/\/[^\/]+/,'')+params);
  	anchor.setAttribute('target', '_blank');
  } 
  return true;
};

function _ib_adjustHeight(doc) {
  var statusAnchor = doc.getElementById('_ibStatusTitle');
  var ibStatusDiv = doc.getElementById('ibTrackingContent');
  var div = doc.getElementById('ibTracking');
  div.style.height = (ibStatusDiv.offsetHeight+statusAnchor.offsetHeight+10)+"px";  
}

function _ib_refreshWatchedMessage(doc, id, cname) {
  var relationType = __ibGetDomainCookie(doc, 'ibw', 'n');
  var status = doc.getElementById('_ibStatusText').innerHTML;
  var hostName = cname;
  if (hostName == '') {
    hostName = doc.location.host;
    hostName = hostName.replace(/(\.com$)|(\.net$)|(\.org$)/, '');
    hostName = hostName.replace(/(www\.)|(www[0-9]+\.)/, '');
  }
  var watchDiv = doc.getElementById('_ibwatchmessage');
  if (watchDiv && (relationType == 'n' || status == 'Safe')) {
    var url = '/plugin/watch?id='+id+'&domain='+hostName;
    watchDiv.innerHTML = '<div style="background-color:eeffee;color:black;"><span id="_ibwatchlink">Monitor this site on <a href="'+url+'" post="1">my list &gt;</a></span></div>';
    _ib_fixLinks(doc, doc.getElementById('_ibwatchlink'));
  }
  var msgDiv = doc.getElementById('_ibbreachmessage');
  if (watchDiv && msgDiv && relationType != 'n' && status != 'Safe') {
    var relation = 'have an account';
    if (relationType == 'u') relation = 'are a customer';
    if (relationType == 'v') relation = 'are a visitor';
    var url = '/breach/index?id='+id;
    msgDiv.innerHTML = '<b>'+hostName+'</b>, where you '+relation+':<br/><b>Has had a breach of <span class="ib'+status+'" >'+status+'</span> risk to you. <span id="_ibmorelink"><a href="'+url+'">Find out more &gt;</a></span></div>';
    _ib_fixLinks(doc, msgDiv);
  }
  _ib_adjustHeight(doc);
};

function _ibAddCss(doc, cssCode) {
  var styleElement = doc.createElement("style");
  styleElement.type = "text/css";
  if (styleElement.styleSheet) {
    styleElement.styleSheet.cssText = cssCode;
  } else {
    styleElement.appendChild(doc.createTextNode(cssCode));
  }
  doc.getElementsByTagName("head")[0].appendChild(styleElement);
}

function _ib_scroll(doc, div, diff, min, max, incr) {
  if (diff <= min || diff >= max) {
    if (diff >= max)
      div.style.display = 'none';
    if (doc.all) div.style.top = "";
    return;
  }
  if (doc.all) {
    div.style.top = (-10 +diff - div.offsetHeight + ( doc.documentElement.clientHeight ? doc.documentElement.clientHeight : doc.body.clientHeight ) + ( ignoreMe = doc.documentElement.scrollTop ? doc.documentElement.scrollTop : doc.body.scrollTop )) + 'px' ;
  } else {
    div.style.bottom = (20-diff)+"px";
  }
  setTimeout(function(){_ib_scroll(doc, div, diff+incr, min, max, incr);}, 20);
}

function showIBMessage(doc, status, id, msg, autoHide, cname) {
  doc._ibUid = id; 
  if (status == 'Safe' && IB_GetCookie('safe') == 'y') return;
  if (msg.indexOf('_ibwatchmessage') == -1) {
  	msg += '<div id="_ibwatchmessage"></div>';
  	if (status == 'Safe') {
  	  msg += '<div><a href="http://'+_ib_domain+'/plugin/setting?stopSafe=1" target="_blank" skip="1">Turn off</a> safe messages?</div>'
  	}
  }
  var protocol = (("https:" == doc.location.protocol) ? "https://" : "http://");
  var msgHtml = '<div class="ib'+status+'" style="clear:both;text-align:center;font-size:9pt;"><img src="'+protocol+_ib_domain+'/images/plugin/shield_'+status.toLowerCase()+'.gif" width=34 height=34 border=0 style="vertical-align:middle;margin:2px;"/>&nbsp;Identity Theft Risk: <b id="_ibStatusText">'+status+'</b></div>';
  msgHtml += '<div id="_ibbreachmessage" style="clear:both;font-size:9pt;">'+msg+'</div>';
  _ib_showTracking(doc, msgHtml, false, true);
  _ib_refreshWatchedMessage(doc, id, cname);
  var ibTracking = doc.getElementById('ibTracking');
  ibTracking.style.display = '';
  _ib_scroll(doc, ibTracking, 200, 0, 300, -10);
  if (autoHide > 0) {
	__ibSetDomainCookie(doc, 'ibShown', '1', 30);
    setTimeout(function(){_ib_closeStatus(doc, true);}, autoHide*1000);
  }
};

function _ib_showTracking(doc, msg, animate, flash) {
   var div = doc.getElementById('ibTracking');
   if (!div && doc.body) {
        _ibAddCss(doc, ".ibSafe {color: green;} .ibLow {color: orange;} .ibMedium {color: deeppink;} .ibHigh {color: red;}");
		_ibAddCss(doc, ".ibShadow1 {position:absolute; left:0px; top:0px; border:1px solid #eeeeee; width:100%; height:100%;}");
		_ibAddCss(doc, ".ibShadow2 {position:absolute; left:-1px; top:-1px; border:1px solid #dddddd; width:100%; height:100%;}");
		_ibAddCss(doc, ".ibShadow3 {position:absolute; left:-2px; top:-2px; border:1px solid #cccccc; width:100%; height:100%;}");
		_ibAddCss(doc, ".ibShadow4 {position:absolute; left:-3px; top:-3px; border:1px solid #aaaaaa; width:100%; height:100%;}");
		_ibAddCss(doc, ".ibTrackingBody {position:absolute; left:-4px; top:-4px; border:1px solid #7777aa; background:white; width:100%; height:100%;text-align:left;}");
		_ibAddCss(doc, ".ibStatusTitle {clear:both;height:12pt;border-bottom: 1px solid #7777aa;font-weight:bold;padding:0px 2px 1px 2px;}");
		_ibAddCss(doc, "#ibTracking {clear:both;position:absolute; right:10px; bottom:10px; width:200px; height:150px; font-family:Arial,sans-serif; font-size:10pt;z-index:9999;}");
		_ibAddCss(doc, "body > div#ibTracking {position:fixed;}");
		if (doc.all) {
		  if (!doc.getElementById('usmap1'))
		    _ibAddCss(doc, "div#ibTracking {right:auto; bottom:auto; left:expression( ( -10 - ibTracking.offsetWidth + ( document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth ) + ( ignoreMe2 = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ) ) + 'px' ); top:expression( ( -10 - ibTracking.offsetHeight + ( document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight ) + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ) ) + 'px' );}");
		}
		
	    var protocol = (("https:" == doc.location.protocol) ? "https://" : "http://");
		var html = '<iframe width=104% height=104% frameborder=0 style="position:absolute;left:-4px;top:-4px;"></iframe>';
		html += '<div class="ibShadow1"></div><div class="ibShadow2"></div><div class="ibShadow3"></div><div class="ibShadow4"></div>';
		html += '<div class="ibTrackingBody">';
		html += ' <div style="clear:both;padding:2px;">';
		html += '  <div id="_ibStatusTitle" class="ibStatusTitle">';
		html += '   <span style="float:left;color:blue;text-decoration:none;font-size:10pt;cursor:pointer;" id="_ibStatusTitleAnchor">IdentityBreach.com</span>';
		html += '   <img id="_ibStatusClose" src="'+protocol+_ib_domain+'/images/plugin/close.gif" border=0 width=10 height=10 style="margin-top:3px;float:right;cursor:pointer;" title="Close" />';
		html += '  </div>';
		html += '  <div id="ibTrackingContent">';
		html += '  </div>';
		html += ' </div>';
		html += '</div>';
        
        div = doc.createElement("div");
        div.id = 'ibTracking';
        doc.body.appendChild(div);
        div.innerHTML = html;
   
	    __ibAddEventHandler(doc.getElementById('_ibStatusClose'), 'click', function(ev){if (!ev) ev=window.event;_ib_closeStatus(doc, true);if(ev.preventDefault){ev.stopPropagation();ev.preventDefault();}ev.returnValue = false;return false;});
        __ibAddEventHandler(doc.getElementById('_ibStatusTitleAnchor'), 'click', function() {
            sendToIBWindow('*', ';', true, function(success){if (success==0)window.open('http://'+_ib_domain)});
            return false;
          });
   }
   if (animate) {
     div.setAttribute("animate", "1");
   } else {
     div.setAttribute("animate", "0");
   }
   var statusAnchor = doc.getElementById('_ibStatusTitle');
   if (msg != '') {
       var ibStatusDiv = doc.getElementById('ibTrackingContent');
	   ibStatusDiv.innerHTML = msg;
	   _ib_adjustHeight(doc);
   }
   if (flash) {
     _ib_flash(statusAnchor, 10);
   }
};

function _ib_flash(element, times) {
  if(times<=0) return;
  element.style.backgroundColor = times%2==0?"yellow":"white";
  setTimeout(function(){_ib_flash(element, times-1);}, 500);
}

