﻿/* injectANC  -  ADDnCLICK  injection javascscript to enable anc bubble
 * included:
 * - hml 2.0 inerpreter
 * - flash swf bubble view logic
 * - ajax crossframe comunication with server
 */

var DOMAIN_PREFIX = "http://www.addnclick.com";
var FIREFOX_MODE = false;
var HMLDOC = window.document;
var HMLVARS = [];
var HMLICONS = [];
var LAST_HML = "";
var HMLWRAPPER = null;
var FRAMES_CASE = false;

var COMMANDS = [];
var CMD_INDEX = 0;
var CMD_BREAK = false;
var REQUEST_VAR = "";
var ANCHORS_COUNT = 0;

var CURR_BUBBLE = null; // current SWF bubble

var CURR_CONTENT_ELEMENT = null;
var CURR_ICON_TARGET = null;

var CURR_TITLE = "";
var CURR_POSITION = "";
var CURR_TIMEOUT = "";
var CURR_NAMESOURCE = "";
var CURR_LOCATION = "";
var CURR_ROOMID = ""; // opening from portal using roomID
var ANC_DISABLED = false;
var CURR_TYPE = ""; //contenttype : 0-anchor, 1-image, 2-youtube(video)

var bcounter = 0;
var BUBBLE_INSERTED = false; 

// ANC ICON SETTINGS
var MOUSE_IN_TIMEOUT = 200;
var ICON_HEIGHT = 29;
var ICON_WIDTH = 29;

var INSIDE = false;
var ICON_WAITING = false;
var timeoutID;
var timeoutID2; // timeout to mouse over (in)

var LastMouseX;
var LastMouseY
var WORD_WRAPPING_TOLLERANCE = 70;  // constant for detecting anchor word-wrapping 

// AJAX object
var xmlHttp = null;

// param idents
var pDomain = "dn";
var pTitle = "tit";
var pIdRoom = "idr";
var pNameSource = "nsc";
var pLocation = "loc";
var pContentType = "ct";

function initVars() {
   HMLVARS = [];
   HMLWRAPPER = null;
   REPEAT_DELAY = 0;
}

function clearIcons() {
   HMLICONS = [];
}

String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

function metaCheck() {
   HMLDOC = window.document;
   var metatags = HMLDOC.getElementsByTagName("meta");	
    for (index=0; index < metatags.length; index++)
    {
	    var name = metatags[index].getAttribute("name");
	    if (name == "ADDnCLICK") {	   
	       var context = metatags[index].getAttribute("content");	       	       
	       if (context == "DISABLED" || context == "PORTAL") {
	         // icon is disabled for this page
	         return false;
	       }	       	       	       	     	                        
	    }	   
    }
           
    return true;
}

function ExecScript(script) {   
    script = script.replace(/^\s*\;/,""); // remove leading comma      
    script = script.replace(/\;\s*$/,""); // remove tailing coma 
    initVars();
    COMMANDS = script.split(";");   
    CMD_INDEX = 0;
    ExecCommands();
}

function ExecCommands() {
    CMD_BREAK = false;
    while (CMD_INDEX < COMMANDS.length && !CMD_BREAK) {
        ExecCmd(COMMANDS[CMD_INDEX]);
        CMD_INDEX++;
    }
}

function ExecCmd(cmd) {
    var first_word = new RegExp("^\\s*(\\w+)");
    
    // hml Request (asynchronous assigment) TODO maybe remove
    var hmlRequest = new RegExp("^\\s*\\$(\\w+)\\s*\\=\\s*Request\\(\\s*\\'(.+)\\'\\s*\\,(.+)\\)","i");     
    var match = hmlRequest.exec(cmd);
    if (match) {
        // hml request
        HmlRequest(match[1],match[2],EvalExp(match[3]));
        return;                
    }
    
    //priradenie =
    var assigment = new RegExp("^\\s*\\$(\\w+)(\\.\\@(\\w+)+)?\\s*\\=\\s*(.*)");   //$=...     
    var match = assigment.exec(cmd)
    if (match) { // 
        if(match[3] == null || match[3] == "") { //normalne priradenie
            HMLVARS[match[1]] = EvalExp(match[4]);
        } else {
            SetAttr(HMLVARS[match[1]], match[3], EvalExp(match[4]));
        }        
        return;
    }    
    
    //prikazy: $node.cmd();  todo: priame volanie prikazov /div/img.putIcon();
    var regex = new RegExp("^\\s*\\$(\\w+)\\.(\\w+)\\((.*)\\)");   
    var match = regex.exec(cmd);        
    if (match) {
      switch (match[2]) {            
        case "putIcon":        
            PutIcons(HMLVARS[match[1]], match[3]);
            break;           
        case "tooltip":   // TODO maybe remove      
            ShowTooltips(HMLVARS[match[1]], match[3]);
            break;
        case "setWrapper":
            SetWrapper(HMLVARS[match[1]]);
            break;
        case "regex":
            //todo: regex priradenim + mozno vseobecnejsie
            EvalRegex(HMLVARS[match[1]], match[3]);
            break;   
        case "show":
            var tmp = HMLVARS[match[1]];
            var msg = "";
            for(var i=0; i<tmp.length; i++) {
                msg += (typeof(tmp[i]) == "object" ? tmp[i].id : tmp[i]) + (i < tmp.length-1 ? "|" : "");
            }
            alert(msg);
            break;
       }
    }
}



function EvalRegex(vars, pattern) {          
    var regex = new RegExp(pattern.substring(1, pattern.length - 1));  
   
    for (var i=0; i<vars.length; i++) {            
        var match = regex.exec(vars[i]);
        if (match) {
          vars[i] = match[1];
        }               
    }
}    

function EvalExp(expr) {
    var string_pattern = new RegExp("^\\s*\\'(.*)\\'\\s*$"); // expression with simple string
    var match = string_pattern.exec(expr); 
    if (match) {
        var varregex = new RegExp("\\$(\\w+)");
        var varmatch;       
        var param = match[1];
        var res = [];
        res.push(match[1]);
                 
        while (varmatch = varregex.exec(param)) {
                if (match.index == varregex.lastIndex) 
                varregex.lastIndex++;          
                
            // match processinx=]\[=
            var tmp = HMLVARS[varmatch[1]];
            
            //todo: pozor nerovnake dimenzie
            while (res.length < tmp.length) {
                res.push(res[res.length-1]);
            }
             
            for(var i=0; i<tmp.length; i++) {
                res[i] = res[i].replace(varmatch[0], tmp[i]);
            }
          
            // regex iteration
            var start = varmatch.index;
            var len = varmatch[0].length;
            var pos = start + len;          
            var param = param.substring(pos);
        }
        
        return res;
    }
    
    // expression with attributes    
    var attrreg = new RegExp("(.*)\\.\\@(\\w+)", "i");  
    match = attrreg.exec(expr); // 
    if (match) {             
       return SearchAttr(match[1], match[2]);       
    }            
   
    // expression with cmd (innerHTML);
    var cmdreg = new RegExp("(.*)\\.(\\w+)","i");      
    match = cmdreg.exec(expr); // start match  
    if (match) {             
       return SearchCmd(match[1], match[2]);       
    }   
        
    return Search(expr);                                
}

function SetWrapper(nodes) {
   if (nodes != null && nodes[0] != null) {
     HMLWRAPPER = nodes[0];
   }
}

function PutIcons(nodes,args) {    
   var params = new RegExp("(\\d+)\\s*\\,\\s*(\\d+)");
   var match = params.exec(args);
   
    if (match) {
        var position = match[1];
        var timeout = match[2];
        for (var i=0; i<nodes.length;i++) {
          if (isANCContent(nodes[i]) ) {
              HMLICONS.push(nodes[i]);      
              nodes[i].setAttribute('anc_content',position);
              nodes[i].setAttribute('anc_timeout',timeout);
              if (FIREFOX_MODE) {
                 HookElement(nodes[i]);
              } else {
                 HookElementIE(nodes[i]);
              }
          }
        }         
    }
}

function GetIcons() {
  return HMLICONS;
}

function SetAttr(nodes, attrname, attrval) {
    if(attrval.length == 0) {
        return;
    }
    
    var tmp = attrval;
    while(attrval.length < nodes.length) {
        attrval.push(attrval[attrval.length - 1]);
    }
    
    for(var i=0; i<nodes.length; i++) {
         nodes[i].setAttribute(attrname, attrval[i]);
   }    
}

function Search(expr) {
  var trexp = expr.trim();
  var found = [];
  
  if(trexp.indexOf("$") == 0) { //if the first ex is a variable
  
    var slash = trexp.indexOf("/");    
    if(slash > 0) {
        var varname = trexp.substring(1, slash);
        var next = trexp.substring(slash + 1);
        
        if(varname.length == 0 || HMLVARS[varname] == null || HMLVARS[varname].length ==0) {
            //todo: rozlisit error and ne-error :)
            return [];
        }
        
        var tmp = HMLVARS[varname];
        for(var i=0; i<tmp.length; i++) {
            SearchRec(next, tmp[i], found);
        }
        
    } else { //single variable
        found = HMLVARS[trexp.substring(1)];
    }
 
  } else { //normal expression (without variable at the begining)
    SearchRec(trexp, null, found);
  }
  
  return found;
}
  
function SearchRec(expr, crnt, found) {
   if(expr.length == 0) return;
   
   if(expr.indexOf("/") == 0) {
      crnt = HMLDOC.documentElement;
      expr = expr.substring(1);
   }

   // extract what to look for
   pind = expr.indexOf("/");

   if(pind >= 0 ) {
      var search = expr.substring(0, pind);
      var nxt = expr.substring(pind + 1);
      var res = FilterChildren(search, crnt, nxt, false)
	  
      for(var i = 0; i < res.length; i++) {
         SearchRec(nxt, res[i], found);
      }
      
   } else {
   	  var children = FilterChildren(expr, crnt, null, false);

   	  for(var j = 0; j < children.length; j++) {
	   	  found.push(children[j]);
	  } 
   }
}

function FilterChildren(taginfo, crnt, nxt, isWild) {
    var outnodes = [];
    var res = []; 
    
    var paramPattern = new RegExp("(.*)\\[(.*)\\]","i"); // patern for matching whole attribute params [ ]   
    var match = paramPattern.exec(taginfo); // start match    
    var tag = match ? match[1] : taginfo;

    if(crnt == null) {
      // todo : add id search
      res = HMLDOC.getElementsByTagName(tag);
      
    } else {
      if(tag == "*") { 
        pind = nxt.indexOf("/");
        var nexttag = pind >= 0 ? nxt.substring(0, pind) : nxt;
        res = crnt.getElementsByTagName(nexttag);  
        
        for(var j = 0; j < res.length; j++ ) {
                if(outnodes.length == 0 || outnodes[outnodes.length-1] != res[j].parentNode) {
                    outnodes.push(res[j].parentNode);
                }
        }
        return outnodes;
        
      } else {
        res = crnt.childNodes;
      }
    }
      
   for(var j = 0; j < res.length; j ++ ){
      //add wildcard handler here!!! - check whether 
   	  if(res[j].nodeType == 1 && res[j].tagName.toUpperCase() == tag.toUpperCase() && (crnt == null || res[j].parentNode == crnt)) {
   	    if(match) {
      	    var myexp = match[2].replace(/\@/g, "res[j].getAttribute('");
      	    //litle hack!!! :)
      	    myexp = myexp.replace(/\==/g, "')==");  
      	    myexp = myexp.replace(/\!=/g, "')!="); 
      	    myexp = myexp.replace(/\>/g, "')>");  
      	    myexp = myexp.replace(/\</g, "')<"); 
      	    myexp = myexp.replace(/\>=/g, "')>=");  
      	    myexp = myexp.replace(/\<=/g, "')<="); 
          	
            if(eval(myexp)) {
      	        outnodes.push(res[j]);
      	    }
      	    
      	 } else {
      	    outnodes.push(res[j]);
      	 }
      }
   }

   return outnodes;
}

function SearchAttr(expr, attr) {
  var res = [];
  var found = Search(expr);
  
  for(var i=0; i<found.length; i++) {
  	 res.push(found[i].getAttribute(attr));
  }
  
  return res;
}

function SearchCmd(expr, cmd) {
  var res = [];
  var found = Search(expr);
  
  for(var i=0; i<found.length; i++) {
    if (cmd == "innerText") {
        res.push(getInnerText(found[i]));
    } else if(cmd == "innerHTML") {
        res.push(found[i].innerHTML);
    }
  }
  
  return res;
}

function getInnerText(o) {
    var txt='';
    for (var i=0; i<o.childNodes.length; i++) {
        switch(o.childNodes[i].nodeType) {
            case 1 :    txt += getInnerText(o.childNodes[i]);   break
            case 3 :    txt += o.childNodes[i].nodeValue.toString();   break
            case 8 :    txt += "\n";   break   
        }
    }
    return txt;
}

function JSONRequest(strURL, strData) {  
	var req = strURL + '?' + strData + '&callback=JSONResponse'; //TODO		
	bObj = new JSONscriptRequest(req);
	bObj.buildScriptTag(  );
	bObj.addScriptTag(  );	 
	
}

function JSONResponse(jsonData) {    
    parsePage(jsonData); // TODO
}



function GetFramesCount() {
  try {
      if (FIREFOX_MODE) {
        return window._content.frames.length;
      } else {
        // IE
        return window.frames.length;
      }
  } catch(err) {
     return 0;
  }
}

function GetFrameDocument(index) {
  try {
      if (FIREFOX_MODE) {
        return window._content.frames[index].document;
      } else {
        // IE
        return window.frames[index].document;
      }
  } catch(err) {
     // alert('error getting ' + index);
     return null;
  }
}

function SetHMLDOC() {
   HMLDOC = (FIREFOX_MODE ?  window._content.document : window.document);
}

function GetFrameDocumentUnsecure(index) {
  if (FIREFOX_MODE) {
    return window._content.frames[index].document;
  } else {
    // IE
    return window.parent.frames[index].document;
  } 
}


function AfterCheck() {
   var newCount = GetAnchorsCount();  
    if (newCount > ANCHORS_COUNT) {
      // page was changed -> run parsing again
       FixResize();
    }
}

function GetAnchorsCount() {
    SetHMLDOC();
    var anchors = HMLDOC.getElementsByTagName("a"); 
    return anchors.length;                      
}

function SetPluginUnsupported() { 
      changeStatus("unsupported");
      disableMenuItemEmpty();
      DOC_URL = "";
}

function Positioning(x,y,pos,offsetWidth,offsetHeight,elemWidth,elemHeight,out) {
      var b = [4];
      var position = parseInt(pos, 10);
      for (var i=3;i>=0;i--) {
          b[i] = position % 2;
          position = parseInt(position / 2, 10);
      }                                
      x += b[0]*(elemWidth-offsetWidth) - !b[0]*!b[2]*offsetWidth + b[0]*b[2]*offsetWidth;
      y += b[1]*(elemHeight-offsetHeight) - !b[1]*!b[3]*offsetHeight + b[1]*b[3]*offsetHeight;                 
      
      out.x = x;
      out.y = y;
}

function ConvertToUrlString(_inputString) {
    return encodeURIComponent(_inputString);   
}

function isStrEmpty(str) {   
    if (str != null &&  str != "") {
      return false; // non empty string
    } else {
      return true; // empty string
    }   
}

//-----------------------------------------------------------------

function isValidAnchor(element) {
   // link
   var href = element.getAttribute("href");
      
   if (href == null || href == "" || href.length < 2) {
       return false;
   }
   // script
   var jsprefix = "javascript:";     
   if (href.substr(0,jsprefix.length) == jsprefix ) {
      return false;
   } 
   // mailto
   var mailprefix = "mailto:";
        if (href.substr(0,mailprefix.length) == mailprefix ) {
      return false;
   }   
   
   return true; // Anchor is valid
}

function isValidImage(element) {
  var w = element.offsetWidth;
  var h = element.offsetHeight;
       
  //if ( element.parentNode.tagName != "A" &&  element.parentNode.tagName != "a" && (w<50 || h<50) ) return false; // too small                
  if  (w<50 || h<50) return false; // too small
  
  
  return true; // Image is valid
}

function isANCContent(element) {
   var tag = element.tagName;
      
   switch (tag) {
     case "A":
     case "a":
       return isValidAnchor(element);
     case "IMG":
     case "img":
       return isValidImage(element);
   }
         
   return true;
}

function HookElement(element) {
   element.removeEventListener("mouseover", AddIcon, true)
   element.addEventListener("mouseover", AddIcon, true);
   element.removeEventListener("mouseout", RemoveIcon, true)
   element.addEventListener("mouseout",RemoveIcon,true); 
   element.removeEventListener("mousemove", UpdateMousePosition, true)
   element.addEventListener("mousemove", UpdateMousePosition, true);
   //element.removeEventListener("mousedown", RemoveIconProcess, true)
   //element.addEventListener("mousedown", RemoveIconProcess, true);
}

function HookElementIE(element) {
     // element.detachEvent("onmouseover", AddIcon);
    element.attachEvent("onmouseover", AddIcon);
     // element.detachEvent("onmouseout",RemoveIcon);
    element.attachEvent("onmouseout",RemoveIcon);
    element.attachEvent("mousemove",UpdateMousePosition);
}
 
function GetTail(str, _length) {
   return str.substr(str.length - _length,_length);
}

function MakeURLPrefix(str) {
   var domain = HMLDOC.domain;
       
   if ( str.substr(0,7) == "http://" ) {
      return str;
   } else {
     if ( str.substr(0,1) == "/" ) {
        // root level, prefix is domain
        return  "http://" + domain + str;               
     } else {     
         var urlprefix = HMLDOC.URL;
         var range = HMLDOC.URL.indexOf("?");
         if (range > 0) {
            urlprefix = HMLDOC.URL.substr(0,range); // from begining to url params  (?)                  
         }
         var pos = urlprefix.lastIndexOf("/");                         
         var url = urlprefix.substr(0,pos);
         if (str.substr(0,1) != "/" ) url += "/";
         url += str;            
         return url;
      }
   }
}

//--------------------------------------------------------------------------------------------------
//----------------------------------chat opening----------------------------------------------------
//--------------------------------------------------------------------------------------------------

function ConstructChatUrl() {
  var chatUrl = "";     
  
  //alert('ConstructChatUrl, ROOMID:' +CURR_ROOMID);
  if (CURR_ROOMID != "" ) {
     // opening win chat using romId
     return DOMAIN_PREFIX + "/chat/Default.aspx?" + pIdRoom + "=" + CURR_ROOMID;
  }
  
  if (CURR_TYPE != "" ) {   
         // make params
         var chatUrl = DOMAIN_PREFIX + "/chat/Default.aspx?";    
        // sent url
        chatUrl += pNameSource + "=" + ConvertToUrlString(CURR_NAMESOURCE);
        // title
        if (!isStrEmpty(CURR_TITLE)) {
           chatUrl += "&" + pTitle + "=" + ConvertToUrlString(CURR_TITLE.trim());
        }        
        // location
        if (!isStrEmpty(CURR_LOCATION)) {
           chatUrl += "&" + pLocation + "=" + ConvertToUrlString(CURR_LOCATION);
        } 
        // anc content type
        chatUrl += "&" + pContentType + "=" + CURR_TYPE;                                       
  }  
  return chatUrl;
}

function IEsendPageToANC() { // IE only
    processCurrentPage();
    return ConstructChatUrl(); // send chat URL to IE
}

//--------------------------------------------------------------------------------------------------
//----------------------------------page processing----------------------------------------------------
//--------------------------------------------------------------------------------------------------

function processCurrentPage() {
    // set ANC params for current page
    CURR_ROOMID = "";
    CURR_TYPE = "0";
    SetHMLDOC();
    CURR_NAMESOURCE = HMLDOC.URL;   
    CURR_LOCATION = HMLDOC.URL;  
    CURR_TITLE =  HMLDOC.title; 
}

function processHREF(node) {
   var href = MakeURLPrefix(node.getAttribute("href"));                   
   CURR_TYPE = "0";
   CURR_NAMESOURCE = href;   
   CURR_LOCATION = HMLDOC.URL;  
   CURR_TITLE = getInnerText(node);         
}

function getTitleFromIMG(imgNode) {
   var attr = imgNode.getAttribute("alt");
   CURR_TITLE = (attr == undefined ? "" : attr);
   if (CURR_TITLE == "") {
     attr = imgNode.getAttribute("title");
    CURR_TITLE = (attr == undefined ? "" : attr);
   }
}

function LastSlash() {
  var pos = CURR_NAMESOURCE.lastIndexOf("/");   
  if (pos == CURR_NAMESOURCE.length - 1) {
     CURR_NAMESOURCE = CURR_NAMESOURCE.substr(0,pos)    
  }  
}

function processIMG(node) {
   var src =  node.getAttribute("src"); 
   CURR_TYPE = "1"; 
   getTitleFromIMG(node); 
   CURR_NAMESOURCE = MakeURLPrefix(src);
   CURR_LOCATION = HMLDOC.URL;
}

function InitNodesInfo() {
  CURR_ROOMID = "";
  CURR_TITLE = "";  
  CURR_LOCATION = "";
  CURR_NAMESOURCE =  HMLDOC.URL;   
}

function SetNodeInfo(node) {
      
   InitNodesInfo();

   if ( (node == null) || (node.attributes == null) ) return false;
   var attr;
   attr = node.getAttribute("anc_content");   
   CURR_POSITION = (attr == undefined ? "" : attr);
   if (CURR_POSITION == "") return false;
   
   attr = node.getAttribute("anc_timeout");   
   CURR_TIMEOUT = (attr == undefined ? "" : attr);
   
  
   attr = node.getAttribute("anc_title"); 
   CURR_TITLE = (attr == undefined ? "" : attr);    
   
   if (CURR_TITLE != "" ) {
       // hml marked case  (only youtube)
       CURR_TYPE = "2";  
       return true; // OK      
   } else {
     // get info manually     
      switch (node.tagName) {
        case "IMG" :
        case "img" :                                               
          var parent = node.parentNode;              
          if (parent.tagName == "A" &&  isValidAnchor(parent) ) {
             // href image case
               processHREF(parent);  
               if (CURR_TITLE == "") getTitleFromIMG(node);               
          } else {
               // single image case
               processIMG(node);
            }                               
        return true; // OK
        case "a" :
        case "A" :
             // href case
             processHREF(node); 
         return true; // OK
      }
   }
   
   
  
}

// --------------------------------------------------------------------------------------------------
// ------------------------------------ icon logic --------------------------------------------------
// --------------------------------------------------------------------------------------------------

function getScrollTop(element) { 
      var spos = 0;
      while (element && element.tagName != "BODY" && element.tagName != "body") {
        if (element.scrollTop) {
          spos += element.scrollTop;                             
        }           
        element = element.parentNode;
      }  
     return spos;
}

function getTop(element) {
   var y = 0 - getScrollTop(element);
   while (element && element.offsetParent) {   
     // add offset and move to parent
     y += element.offsetTop;                   
     element = element.offsetParent;     
   }      
   return y;
}

function getLeft(element) {
   var x = 0;
   while (element && element.offsetParent) {  
     // add offset and move to parent
     x += element.offsetLeft;
     element = element.offsetParent;      
   }   
   return x;
}

function ShowIconFromNode(node) {           
    if (CURR_POSITION == "16" ) {
       ShowIconFromNodeByMouse(node);
       return;
    }
            
    // obtain coordinates, and append to body (or hml wrapper)  marker1
    var x = getLeft(node);
    var y = getTop(node);             
    var elemWidth = node.offsetWidth;
    var elemHeight = node.offsetHeight;        
    var out = {x:0, y:0};     
    Positioning(x,y,CURR_POSITION,ICON_WIDTH,ICON_HEIGHT,elemWidth,elemHeight,out); 
    ShowIcon( out.x, out.y);         
}

function ShowIconFromNodeByMouse(node) {    
    ShowIcon(LastMouseX + 15,LastMouseY - ICON_HEIGHT);
}

function AddIcon(e) { 
  if (ANC_DISABLED) return;     
  CURR_ICON_TARGET = (FIREFOX_MODE ? e.target : e.srcElement);
  if (CURR_ICON_TARGET.id == "anc_icon"){      
      //alert('strange error!');
      return; // TODO treba nejako odstranit tento event od anc_icon by sem nemal dojst!  
   }
  
  if ( (timeoutID2 != undefined)&&(timeoutID2 !=null) ) {           
             clearTimeout(timeoutID2);
     }     
  // store mouse position  
  UpdateMousePosition(e);
  timeoutID2 = setTimeout("ProcessIcon();",MOUSE_IN_TIMEOUT); 
  ICON_WAITING = true; 
}

function UpdateMousePosition(e) {
  // store mouse position
  if (FIREFOX_MODE) {
     LastMouseX = e.pageX;
     LastMouseY = e.pageY;
  } else {
    // ie mode
    var scrollX = window.document.documentElement.scrollLeft;
    if (scrollX == 0) {
        scrollX = document.body.scrollLeft;
    }
    var scrollY = window.document.documentElement.scrollTop;
    if (scrollY == 0) {
        scrollY = document.body.scrollTop;
    }    
    LastMouseX = e.clientX + scrollX;
    LastMouseY = e.clientY + scrollY;
  }     
}

function ProcessIcon() {      
    if (!ICON_WAITING) {
        return;
     }
    ICON_WAITING = false;
    var target = CURR_ICON_TARGET;              
    if (FRAMES_CASE) HMLDOC = target.ownerDocument;
                              
    INSIDE = true;  // TODO dobre miesto?
             
    var node =  target;   
    CURR_CONTENT_ELEMENT = node;          
    var nodeOK = SetNodeInfo(node);        
    while( (node != null) && !nodeOK ) {            
        node = node.parentNode;
        nodeOK = SetNodeInfo(node);
    }                       
    LastSlash(); // removing tailing forward slash in CURR_NAMESOURCE  
                    
    if ( (node != null) && nodeOK ) {                                                                       
       ShowIconFromNode(node);                     
    } 
}

function Inside() {
  INSIDE = true;
}

function ShowIcon(X,Y) {
 var obj = getAncObject(); 
 var ready = obj.isReady();
 if (ready == true) {
     var bubble = getAncBubble();
      if (bubble != null) {   
          bubble.style.left = X + "px";
          bubble.style.top = Y + "px";      
          // push parameters to flash icon   
          //alert(ConstructChatUrl());     
          obj.setURL(ConstructChatUrl()); 
      } else {
      //  LOG('bubble is null error!');
      }
  }
}

function RemoveIcon(e) {    
    if (ICON_WAITING) {
        ICON_WAITING = false; 
        return;
    }
    var posX = (FIREFOX_MODE ? e.pageX : e.clientX);
    var posY = (FIREFOX_MODE ? e.pageY : e.clientY);    
    
    if (CURR_CONTENT_ELEMENT) {
        if( (posX <= getLeft(CURR_CONTENT_ELEMENT)) || 
            (posX >= getLeft(CURR_CONTENT_ELEMENT)+CURR_CONTENT_ELEMENT.offsetWidth)||
            (posY <= getTop(CURR_CONTENT_ELEMENT))+1 || 
            (posY >= getTop(CURR_CONTENT_ELEMENT)+CURR_CONTENT_ELEMENT.offsetHeight) ) {            
            INSIDE = false;          
            if ( (timeoutID != undefined)&&(timeoutID !=null) ) {           
               clearTimeout(timeoutID);
            }
            timeoutID =  setTimeout("RemoveIconRequest();",parseInt(CURR_TIMEOUT, 10));            
        }     
    }
}

function RemoveIconRequest() {   
     if (!INSIDE) {
        if (FRAMES_CASE) {
           RemoveFramesIcon();        
        } else {
           RemoveIconProcess();
        }
     }           
}

function RemoveIconProcess() {
  var bubble = getAncBubble();
  if (bubble != null) {
     bubble.style.left = "0px";
     bubble.style.top = "-25px"; 
  }
}

function RemoveFramesIcon() {
   // search in all frames
    SetHMLDOC();
    RemoveIconProcess();
    var framesCount = GetFramesCount();
    for (var i=0; i<framesCount; i++) {
           HMLDOC = GetFrameDocument(i);
           if (HMLDOC != null) {
             RemoveIconProcess();
           }
    } 
}
  
function FixResize() {
   if (isStrEmpty(LAST_HML) ) return;
   if (ANC_DISABLED) return;
   if ( (timeoutID != undefined)&&(timeoutID !=null) ) {           
      clearTimeout(timeoutID);
   }
   //CURR_ICON =  GetANCIcon();  TODO ???
   RemoveIconProcess();
   // parse again
   ResponseParse(LAST_HML);   
}

// ---------------------------------------------------------------
// ----------------------------- SWF BUBBLE ---------------------
// --------------------------------------------------------------



function getAncBubble()
{
   var movieName = "ancBubble";
   return document.getElementById(movieName);
}

function getAncObject()
{
    var movieName = "ancBubble";
    if (document.embeds && document.embeds[movieName]) { // netscape types
      return document.embeds[movieName];
    } else if (window.document[movieName])  {  // ie         
      return window.document[movieName];
  } 
  
  // other cases
  return document.getElementById(movieName);
}       


function insertAncBubble() {
    var el = HMLDOC.getElementById("ancBubbleDiv");
    if (el == null) {
    var placeDiv = HMLDOC.createElement("div");
        placeDiv.id = "ancBubbleDiv";  
        HMLDOC.body.appendChild(placeDiv);                
        placeDiv.innerHTML = bubbleHTML();         
        CURR_BUBBLE = getAncBubble();
         if (CURR_BUBBLE != null) {                   
           // add events  
           if (FIREFOX_MODE) {
             CURR_BUBBLE.addEventListener("mouseout", RemoveIcon, false);
             CURR_BUBBLE.addEventListener("mouseover", Inside, false);    
           } else {                      
             CURR_BUBBLE.attachEvent("onmouseout",RemoveIcon);
             CURR_BUBBLE.attachEvent("onmouseover", Inside);  
           } 
             
         }                       
    }    
    BUBBLE_INSERTED = true;
}  
      
function bubbleHTML() {
     return '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="ancBubble" width="29" ' +
    'height="29" codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab " ' +
    'style="position: absolute; left: 0px; top: -25px; z-index: 9999999; display:;" >' +
    '<param name="movie" value="' + DOMAIN_PREFIX + '/images/Bubble.swf" />' +
    '<param name="quality" value="high" />' +
    '<param name="bgcolor" value="#ffffff" />' +
    '<param name="allowScriptAccess" value="always" />' +
    '<param name="wmode" value="transparent">' +
    '<embed src="' + DOMAIN_PREFIX + '/images/Bubble.swf" quality="high" bgcolor="#ffffff" width="29" height="29" id="ancBubble" name="ancBubble"' +
    ' align="middle" play="true" loop="false" quality="high" wmode="transparent" allowscriptaccess="always"' +
    ' type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer"' +
    ' style="position: absolute; left: 0px; top: 0px; z-index: 9999999; display:;" >' +                
	'</embed></object>';			
}	

function parsePage(hmlscript) {
    HMLDOC = window.document;    
    ExecScript(hmlscript);                            
    // frames case       
    var framesCount = GetFramesCount();
    if (framesCount > 0 &&  !HMLWRAPPER) { 
       FRAMES_CASE = true;
       for (var i=0; i<framesCount; i++) {
         HMLDOC = GetFrameDocument(i);
         if (HMLDOC != null) {
            ExecScript(hmlscript);
         }
       }        
    } else {
        FRAMES_CASE = false;
    }      
}

function enableANC() {
         
  if ( metaCheck() == false) {     
       // page is disabled, (onclick was changed for anc portal)
       return;
  }     
  
  if (!BUBBLE_INSERTED) {
     bcounter = 20;
     insertAncBubble();
  }
            
  // request for hml script 
   JSONRequest(DOMAIN_PREFIX + "/hml/getBubble.aspx", "senturl=" + document.URL);
}     

function getCookie(str) {
  //alert('cooookie');
}    

function CheckBody() {
  if (HMLDOC.body == null && bcounter < 10 ) {
    bcounter++;
    setTimeout("CheckBody();",10);
  } else {
    // body element avaible, insert bubble
    insertAncBubble();
  }
}


function initInjectListener() {
 
  // flash player detection
  var flashVer = GetSwfVer();  
  if (flashVer == -1) {
    // no flash player  
    return;
  }
  // browser detection
  var browser=navigator.appName;
  if (browser == "Netscape") {
    FIREFOX_MODE = true;
  }      
  // main varibles init
  HMLDOC = window.document;  
  bcounter = 0;
  BUBBLE_INSERTED = false;
  // check when body elemnt available, then insert bubble  
  CheckBody();
  // hook main pageload listener          
  if (FIREFOX_MODE) {
   window.addEventListener("load",enableANC,false);
  } else {
   window.attachEvent("onload", enableANC);   
  } 
}

// ------------------------------------------------------------------
// -------------------- JSON SUPPORT --------------------------------
// ------------------------------------------------------------------

// Constructor -- pass a REST request URL to the constructor
//
function JSONscriptRequest(fullUrl) {
    // REST request path
    this.fullUrl = fullUrl; 
    // Keep IE from caching requests
    this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
    // Get the DOM location to put the script tag
    this.headLoc = HMLDOC.getElementsByTagName("head").item(0);
    // Generate a unique script tag id
    this.scriptId = 'anc_tmpscript' + JSONscriptRequest.scriptCounter++;
}

// Static script ID counter
JSONscriptRequest.scriptCounter = 1;

// buildScriptTag method
//
JSONscriptRequest.prototype.buildScriptTag = function () {

    // Create the script tag
    this.scriptObj = document.createElement("script");
    
    // Add script object attributes
    this.scriptObj.setAttribute("type", "text/javascript");
    this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
    this.scriptObj.setAttribute("id", this.scriptId);
}
 
// removeScriptTag method
// 
JSONscriptRequest.prototype.removeScriptTag = function () {
    // Destroy the script tag
    this.headLoc.removeChild(this.scriptObj);  
}

// addScriptTag method
//
JSONscriptRequest.prototype.addScriptTag = function () {
    // Create the script tag
    this.headLoc.appendChild(this.scriptObj);
}


/// ------ FLASH PLAYER DETECTION

// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer(){
    var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
    var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
    var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;


	// NS/Opera version >= 3 check for Flash plugin in plugin array
	var flashVer = -1;
	
	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
			var descArray = flashDescription.split(" ");
			var tempArrayMajor = descArray[2].split(".");			
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];
			var versionRevision = descArray[3];
			if (versionRevision == "") {
				versionRevision = descArray[4];
			}
			if (versionRevision[0] == "d") {
				versionRevision = versionRevision.substring(1);
			} else if (versionRevision[0] == "r") {
				versionRevision = versionRevision.substring(1);
				if (versionRevision.indexOf("d") > 0) {
					versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
				}
			} else if (versionRevision[0] == "b") {
				versionRevision = versionRevision.substring(1);
			}
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
		}
	}
	// MSN/WebTV 2.6 supports Flash 4
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	// WebTV 2.5 supports Flash 3
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	// older WebTV supports Flash 2
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	else if ( isIE && isWin && !isOpera ) {
		flashVer = ControlVersion();
	}
	return flashVer;
}

function ControlVersion()
{
	var version;
	var axo;
	var e;

	// NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry

	try {
		// version will be set for 7.X or greater players
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {
	}

	if (!version)
	{
		try {
			// version will be set for 6.X players only
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
			
			// installed player is some revision of 6.0
			// GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
			// so we have to be careful. 
			
			// default to the first public version
			version = "WIN 6,0,21,0";

			// throws if AllowScripAccess does not exist (introduced in 6.0r47)		
			axo.AllowScriptAccess = "always";

			// safe to call for 6.0r47 or greater
			version = axo.GetVariable("$version");

		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 4.X or 5.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 3.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 2.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) {
			version = -1;
		}
	}
	
	return version;
}

// --------------------------------------------



// auto 
initInjectListener();
