var originalLeft=null;
var originalTop=null;
var speed = 10;
 var interval; 
var landingTime = new Date(); 
 var statusFlag=true; 
 var popupCheckEnable='0'; 
 var  isOnline = "0";
 var popupDetails = new Array(5);
 var newwindowForChat = null;
 var varglobal='0';
var popUpImagePath='';
var regEx = /<[^>]*>/g;
var ref = document.referrer.toString(); 
    ref = ref.toString().replace(regEx, "");
var loc = document.location.toString();
    loc=loc.toString().replace(regEx, "");
var tit = document.title.toString(); 
    tit=tit.toString().replace(regEx, "");
var urlforstr = "&wr=" + ref + "&wl=" + loc + "&wt=" + tit; 

function Get_Cookie(name) {   
   var start = document.cookie.indexOf(name+"=");
   var len = start+name.length+1;
   if ((!start) && (name != document.cookie.substring(0,name.length))) return null;
   if (start == -1) return null;
   var end = document.cookie.indexOf(";",len);
   if (end == -1) end = document.cookie.length;   
   return unescape(document.cookie.substring(len,end));
}

function Set_Cookie(name,value,expires,path,domain,secure) {
    var cookieString = name + "=" +escape(value) +
       //( (expires) ? ";expires=" + expires.toGMTString() : "") +
       ( (path) ? ";path=" + path : "") +
       ( (domain) ? ";domain=" + domain : "") +
       ( (secure) ? ";secure" : "");
    document.cookie = cookieString;
}

function Delete_Cookie(name,path,domain) {
   if (Get_Cookie(name)) document.cookie = name + "=" +
      ( (path) ? ";path=" + path : "") +
      ( (domain) ? ";domain=" + domain : "") +
      ";expires=Thu, 01-Jan-70 00:00:01 GMT";
}

var today = new Date();
var zero_date = new Date(0,0,0);
today.setTime(today.getTime() - zero_date.getTime());
var cookie_expire_date = new Date(today.getTime() + (8 * 7 * 86400000));

function setVisitorID() {
   if (Get_Cookie('VisitorID')) {
       var VisitorID = Get_Cookie('VisitorID');
   }else{
       Set_Cookie('VisitorID',Math.random(),cookie_expire_date);       
   }
}

function setSessionID() {
   if (!Get_Cookie('SessionID'))
       Set_Cookie('SessionID',Math.random());
}

function setOperatorStatus() {
   if (!Get_Cookie('Ostatus'))
       Set_Cookie('Ostatus',true);
}

function setVisitorInfo(value) {
   if (!Get_Cookie('ViRequest'))
       Set_Cookie('ViRequest',value);
}

var loaded_script = true; 

function readCookie(name) {
	var nameEQ = name + "=";	
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

 function GeoLocation()
 {
    var etime_url = 'http://gd.geobytes.com/Gd?after=-1&variables=GeobytesCountry,GeobytesCity,GeobytesRegion';		
    AjaxCallFullUrl( etime_url, 'geolocation');   
    setTimeout("generateLocation()",2000);
 }
 //===Region Mainak Start=========
/*
function GetImageWidth(src)
{
    return 230;
}

function GetImageHeight(src)
{
    var objImage = new Image();
    objImage.src = src;
    var height = 0;
    do {
        var height = parseInt(objImage.height);
    } while (height <= 0)    
    return height; // add close image height
}

*/

count=0;           
orgPosition=0;
NoOfShakes=20;
shiftIndex=0;
//direction = true/false
function Shake(id,blnDirection) 
{  
   	if(count == 0){
   	    orgPosition = parseInt(document.getElementById(id).style.left); 
   	}
   	if(count<(NoOfShakes/2))
   	{   	    
   	        shiftIndex += 3;
   	}
   	else{
   	        shiftIndex -= 3;
   	}
   	var temp;
   	if(blnDirection){
   	    temp = orgPosition + shiftIndex
   	    document.getElementById(id).style.left = temp + "px";
   	}
   	else{
   	    temp = orgPosition - shiftIndex
   	    document.getElementById(id).style.left = temp + "px";
   	} 	  
   	if(count<NoOfShakes){
   	  	setTimeout("Shake('" + id + "'," + (!blnDirection) + ");", 100);
   	  	count++;
   	}   	
   	else{
   	    document.getElementById(id).style.left = orgPosition + "px";  
   	    count=0;           
        shiftIndex=0;
        ImageMovementStopped(); 
   	    return;
   	}
}

//====================================================================================
//onclick="javascript:moveRight(divPic,400);"
function moveRight(id,finalPos) 
{       	
   	var orgPos = parseInt(document.getElementById(id).style.left);   	
    moveObjRight(id,orgPos,finalPos);  
}

function moveObjRight(id,pos,finalPos)
{  
    document.getElementById(id).style.left = pos + "px";
    var newPos = 2 + pos;
    if(pos<finalPos){
        setTimeout("moveObjRight('" + id + "'," + newPos + "," + finalPos + ");", speed);
    }  
    else{
        ImageMovementStopped(); 
    }
}
//====================================================================================
//=========onclick="javascript:moveLeft(divPic,400);
function moveLeft(id,finalPos)  
{       	
   	var orgPos=parseInt(document.getElementById(id).style.left);   	
    moveObjLeft(id,orgPos,finalPos);  
}

function moveObjLeft(id,pos,finalPos)
{  
    document.getElementById(id).style.left = pos + "px";
    var newPos = pos - 2;
    if(pos>finalPos){
        setTimeout("moveObjLeft('" + id + "'," + newPos + "," + finalPos + ");", speed);
    }  
    else{
        ImageMovementStopped(); 
    }
}
//======================================================================================
//=======onclick="javascript:moveDown(divPic,350)
function moveDown(id,finalPos)  
{       	
    var orgPos=parseInt(document.getElementById(id).style.top);   	
    moveObjDown(id,orgPos,finalPos);  
}

function moveObjDown(id,pos,finalPos)
{  
    document.getElementById(id).style.top = pos + "px";
    var newPos = pos + 2;
    if(pos<finalPos){
        setTimeout("moveObjDown('" + id + "'," + newPos + "," + finalPos + ");", speed);
    }  
    else{
        ImageMovementStopped(); 
    }
}


//======================================================================================

function moveUp(id,finalPos)  
{       	
   	var orgPos=parseInt(document.getElementById(id).style.top);   	
    moveObjUp(id,orgPos,finalPos);
}

function moveObjUp(id,pos,finalPos)
{  
    document.getElementById(id).style.top = pos + "px";
    var newPos = pos - 2;
    if(pos>finalPos){
        setTimeout("moveObjUp('" + id + "'," + newPos + "," + finalPos + ");", speed);
    }  
    else{
        ImageMovementStopped(); 
    }
}
/*
function GetWindowWidth()
{
  var myWidth = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
      myWidth = window.innerWidth;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
  }
  return parseInt(myWidth)-15;
}


function GetWindowHeight()
{
  var myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myHeight = document.body.clientHeight;
  }
  return parseInt(myHeight)-10;
}
*/
function checkVScroll() {
    var displayed_height = $(window).height();
    var offsetHeight = document.body.offsetHeight;
    if (offsetHeight > displayed_height) {
        return true;
    }
    else {
        return false;
    }
}

function checkHScroll() {
    var displayed_width = $(window).width();
    var offsetWidth = document.body.offsetWidth;
    if (offsetWidth > displayed_width) {
        return true;
    }
    else {
        return false;
    }
}

function findVScrollWidth() {
    var window_width = $(window).width();
    var offsetWidth = document.body.offsetWidth;
    var result = parseInt(window_width) - parseInt(offsetWidth);
    return result;
}

function findHScrollHeight() {
    return ($(window).height() - document.body.offsetHeight);
}

function GetWindowWidth() {
    var myWidth = $(window).width();
    if (checkVScroll()) {
        myWidth -= 16;
    }
    return parseInt(myWidth);
}

function GetWindowHeight() {
    var myHeight=$(window).height();
    if (checkHScroll()) {
        myHeight -=16;
    }
    return parseInt(myHeight);
}
//==========================================================================
function AjaxCall(url,id)
{
        var head = document.getElementsByTagName('head').item(0); 	
	    var old = document.getElementById(id); 
	    if (old)
	    { 
		    head.removeChild(old); 
	    }        
        var s = document.createElement('script'); 
        s.src  = prefix_url + url + '&random=' + Math.random(); 
	    s.type = 'text/javascript'; 
	    s.defer = true; 
	    s.id = id;
	    void(head.appendChild(s));
}

function AjaxCallFullUrl(url,id)
{
        var head = document.getElementsByTagName('head').item(0); 	
	    var old = document.getElementById(id); 
	    if (old)
	    { 
		    head.removeChild(old); 
	    }        
        var s = document.createElement('script'); 
        s.src  = url + '&random=' + Math.random(); 
	    s.type = 'text/javascript'; 
	    s.defer = true; 
	    s.id = id;
	    void(head.appendChild(s));
}

function createXmlHttpRequest() {
    var oHttp;
    if (window.XMLHttpRequest){
        oHttp = new XMLHttpRequest();
        return oHttp;
    }
    else if (window.ActiveXObject){
        var versions = new Array("MSXML2.XmlHttp.6.0", "MSXML2.XmlHttp.3.0","Microsoft.XMLHTTP");
        for (var i = 0; i < versions.length; i++){
            try{
                oHttp = new ActiveXObject(versions[i]);
                return oHttp;
            }
            catch (error){}
        }
    }
    return null;
}



function OnLoadCheckingCallback()
{
    var check = true;
    if(parseInt(sessionTimeout)==0){
        check = true;
    }
    else{
        var tDiff = (new Date() - landingTime) / 1000; 
        if ( tDiff < (parseInt(sessionTimeout)*60) ){
            check = true;
        }
       else{
            check = false;
       } 
    }    
    if(trackingEnabled == '0'){check = false;}
	if ( check )
	{
        checkProcess();        
        setTimeout("OnLoadCheckingCallback();",5000);     
    }
}

function OnLoadTrackingCallback() {
    var check = true;
    if (parseInt(sessionTimeout) == 0) {
        check = true;
    }
    else {
        var tDiff = (new Date() - landingTime) / 1000;
        if (tDiff < (parseInt(sessionTimeout) * 60)) {
            check = true;
        }
        else {
            check = false;
        }
    }
    if (trackingEnabled == '0') { check = false; }
    if (check) {
        checkTrackingProcess();
        setTimeout("OnLoadTrackingCallback();", 5000);
    }
}

function autoPopupCallback()
{
    if( proactivepopUpvaluere != null && proactivepopUpvaluere != "" ){
        setTimeout("showAutoPopup();", (  (parseInt(proactivepopUpvaluere)) *1000) );
    }
}

function GetActualLeft(left)
{
    var offset;
    if(window.pageXOffset){
        offset = window.pageXOffset;
    }else if(document.body != null && document.body.scrollLeft){
        offset = document.body.scrollLeft;
    }else if(document.documentElement != null && document.documentElement.scrollLeft){ 
        offset = document.documentElement.scrollLeft;
    }else{
        offset = 0;
    } 
    var total = parseInt(left) + parseInt(offset);
    return total;
}

function GetActualTop(top)
{
    var offset;
    if(window.pageYOffset){
        offset = window.pageYOffset;
    }else if(document.body != null && document.body.scrollTop){
        offset = document.body.scrollTop;
    }else if(document.documentElement != null && document.documentElement.scrollTop){ 
        offset = document.documentElement.scrollTop;
    }else{
        offset = 0;
    } 
    var total = parseInt(top) + parseInt(offset);
    return total;
}

function GetVerticalCentrePosition(imgHeight) 
{
    return ( parseInt(GetWindowHeight()) - parseInt(imgHeight) ) / 2;
}

function GetHorizontalCentrePosition(imgWidth)
{
    return (parseInt(GetWindowWidth()) - parseInt(imgWidth)) / 2;
}

function displayPopup(popupArray, isAuto, objImage, objCloseImg, width, height)     
{
    var final_left = 0;
    var final_top = 0;   
    if (popupArray[2] == 'Top left') {
        final_left = parseInt(popupArray[1]);
        final_top = parseInt(popupArray[0]);
    } else if (popupArray[2] == 'Bottom left') {
        final_top = parseInt(GetWindowHeight()) - (parseInt(popupArray[6]) + parseInt(popupArray[0]));
        final_left = parseInt(popupArray[1]);
    } else if (popupArray[2] == 'Top Right') {
        final_left = parseInt(GetWindowWidth()) - (parseInt(popupArray[5]) + parseInt(popupArray[1]));
        final_top = parseInt(popupArray[0]);
    } else if (popupArray[2] == 'Bottom Right') {
        final_left = parseInt(GetWindowWidth()) - (parseInt(popupArray[5]) + parseInt(popupArray[1]));
        final_top = parseInt(GetWindowHeight()) - (parseInt(popupArray[6]) + parseInt(popupArray[0]));
    }

    if (popupArray[0] == '-1') {
        final_top=GetVerticalCentrePosition(popupArray[6]);
    }
    if (popupArray[1] == '-1') {
        final_left = GetHorizontalCentrePosition(popupArray[5]);
    }    
    if (final_left < 0) { final_left = 0; }
    if (final_top < 0) { final_top = 0; }

    originalLeft = final_left;
    originalTop = final_top;

    final_left = GetActualLeft(final_left);
    final_top = GetActualTop(final_top);

    var initial_left;
    var initial_top;
    if (popupArray[3] == 'Left to Right') {
        initial_left = GetActualLeft(0);
        initial_top = final_top;
        //alert('left to right : initial_left=' + initial_left +' initial_top=' + initial_top + ' final_left=' + final_left + ' final_top=' + final_top);
        SetPopupBody('rtpopup_jagenerated', initial_left, initial_top, objImage, objCloseImg, isAuto, width, height);
        moveRight('formsettings', final_left);
    } else if (popupArray[3] == 'Top to Bottom') {
        initial_left = final_left;
        initial_top = GetActualTop(0);
        SetPopupBody('rtpopup_jagenerated', initial_left, initial_top, objImage, objCloseImg, isAuto, width, height);
        moveDown('formsettings', final_top);
    } else if (popupArray[3] == 'Bottom to Top') {
        initial_left = final_left;
        initial_top = GetActualTop(parseInt(GetWindowHeight()) - parseInt(popupArray[6]));
        SetPopupBody('rtpopup_jagenerated', initial_left, initial_top, objImage, objCloseImg, isAuto, width, height);
        moveUp('formsettings', final_top);
    } else if (popupArray[3] == 'Right to Left') {
        initial_left = GetActualLeft(parseInt(GetWindowWidth()) - parseInt(popupArray[5]));
        initial_top = final_top;
        SetPopupBody('rtpopup_jagenerated', initial_left, initial_top, objImage, objCloseImg, isAuto, width, height);
        moveLeft('formsettings', final_left);
    } else if (popupArray[3] == 'Shake') {
        initial_left = final_left;
        initial_top = final_top;
        SetPopupBody('rtpopup_jagenerated', initial_left, initial_top, objImage, objCloseImg, isAuto, width, height);
        Shake('formsettings', true);
    } else if (popupArray[3] == 'Still') {
        SetPopupBody('rtpopup_jagenerated', final_left, final_top, objImage, objCloseImg, isAuto, width, height);
        ImageMovementStopped();
    }       
             
}


function generateOperatorProactivePopUp(popupArray, isAuto)    //popUpImagePath
{
    if (popupArray[4] != '' && popupArray[4] != null) {
        varglobal = 0;
        popupCheckEnable = '0';
        if (!document.getElementById("rtpopup_jagenerated")) {
            var ee_container = document.createElement("DIV");
            ee_container.id = 'rtpopup_jagenerated';
            ee_body = document.getElementsByTagName("BODY")[0];
            void (ee_body.appendChild(ee_container));
            var parentPath = prefix_url;
            var imageSrc = parentPath + popupArray[4];
            var css_path = parentPath + "css/popupChatbox.css";
            var top = popupArray[0] + "px";
            var left = popupArray[1] + "px";

            var headID = document.getElementsByTagName("head")[0];
            var fileref = document.createElement("link");
            fileref.setAttribute("rel", "stylesheet");
            fileref.setAttribute("type", "text/css");
            fileref.setAttribute("href", css_path);
            headID.appendChild(fileref);

            var objCloseImg = new Image();
            var objImage = new Image();
            if (isAuto == "1") {
                objImage = autoPopupImage;
                objCloseImg = autoPopupCloseImage;
                displayPopup(autoPopupDetails, isAuto, objImage, objCloseImg, autoPopupDetails[5], autoPopupDetails[6]);
            }
            else {
                if (navigator.userAgent.indexOf("MSIE") != -1) {
                    //alert("IE");
                    objImage.src = imageSrc;
                    objCloseImg.src = prefix_url + "Images/close_popup_btn1.png";
                    displayPopup(popupArray, isAuto, objImage, objCloseImg, popupArray[5], popupArray[6]);
                }
                else {
                    //alert("Non-IE");
                    objImage.src = imageSrc;
                    objImage.onload = function() {
                        objCloseImg.src = prefix_url + "Images/close_popup_btn1.png";
                        objCloseImg.onload = function() {
                            objImage.onload = displayPopup(popupArray, isAuto, objImage, objCloseImg, popupArray[5], popupArray[6]);
                        }
                    }    
                }                        
            } 
        }
    }
}

function ImageMovementStopped()
{
    window.onscroll=setNewPosition;
    speed = 1;
}

function setNewPosition()
{        
    if(document.getElementById('formsettings')){  
        if(originalLeft!=null && originalTop!=null){
            currentTop = parseInt(document.getElementById('formsettings').style.top);
            currentLeft = parseInt(document.getElementById('formsettings').style.left);
            newTop = GetActualTop(originalTop); 
            newLeft = GetActualLeft(originalLeft);
           if(newTop>currentTop){
                moveDown('formsettings',newTop);
           }else if(newTop<currentTop){
                moveUp('formsettings',newTop);
           }           
           if(newLeft>currentLeft){
                moveRight('formsettings',newLeft);
           }else if(newLeft<currentLeft){
                moveLeft('formsettings',newLeft);
           }           
            document.getElementById('formsettings').style.top = newTop+'px';
            document.getElementById('formsettings').style.left = newLeft+'px';
        }
    }
}

function opInvite()
{    
    if(varglobal == '1' && readCookie('Ostatus'))
    {
        proactivepopUpvaluere=0;            
        if( !newwindowForChat && popupCheckEnable=='1' ){
            generateOperatorProactivePopUp(popupDetails, '0');
        }        
    }
}

function showAutoPopup()
{    
          if( popupCheckEnable == '1' && readCookie('Ostatus') && varglobal != "1" && !newwindowForChat ){   
                generateOperatorProactivePopUp(autoPopupDetails,'1');  
                AutoPopupShown();
          }     
}

function Initiate(wid,did,cid)
{
    setVisitorID();
    var x = readCookie('VisitorID');
    if(x == null){
        alert("Please enable browser cookie for proper working of chat");
    } 
   else{
       var url = 'https://livechat.reliabletechnologies.in/ServerCallPage.aspx?id=' + x + '&wid=' + wid + '&did=' + did + '&cid=' + cid + urlforstr; 
        AjaxCallFullUrl(url, 'Initiate');
        url = 'https://livechat.reliabletechnologies.in/JS/jquery-1.4.2.min.js';
        //url ='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js';
        var head = document.getElementsByTagName('head').item(0);
        var old = document.getElementById('JQuery');
        if (old) {
            head.removeChild(old);
        }
        var s = document.createElement('script');
        s.src = url;
        s.type = 'text/javascript';
        s.defer = true;
        s.id = 'JQuery';
        void (head.appendChild(s));
   } 
}
//===Region Mainak End=========
function tracking(wid, did, cid, startChat) {
    var x = readCookie('VisitorID');
    if (x == null) {
        alert("Please enable browser cookie for proper working of chat");
    }
    else {
        var url = 'https://livechat.reliabletechnologies.in/trackingcallpage.aspx?id=' + x + '&wid=' + wid + '&did=' + did + '&cid=' + cid + '&startChat=' + startChat;
        AjaxCallFullUrl(url, 'tracking');
    }
}

function retStatus(wid, did, cid) {
    setVisitorID();
    var x = readCookie('VisitorID');
    if (x == null) {
        alert("Please enable browser cookie for proper working of chat");
    }
    else {
        var url = 'https://livechat.reliabletechnologies.in/StatusCallPage.aspx?action=fetch&sessionid=' + x + '&wid=' + wid + '&did=' + did + '&cid=' + cid + urlforstr;
        AjaxCallFullUrl(url, 'retStatus');
    }
}

