// ********************************* //
// **** Global Variables in JS ***** //

// **** COMMON VARIABLES ***** //
var xmlHttp;
var visitorNo;      // No of Visitor
var custtoken;      // Unique Customer Token
var sourceIP;       // Source Ip of Visitor
var intervalId=0;   // Unique Interval Id to kill continue Processiong
var uniqueid;       // Unique Id for Visitor
var callResponse;   // Status of Call Request
var responseStatus; // Status of Continue Call


//******** CONSTANT CALL STATUS ********* //
var	IDLE = 0;
var	CONNECTED = 1;
var BUSY = 2;
var NO_REPLY = 3;
var OTHER = 4;
var SUCCESS = 5;
var USER_HANGUP = 6;
var TO_BE_CONNECTED = 7;
var NOT_CONNECTED = 8;
var INVALID_NUMBER_FORMAT = 9;
var UNOBTAINABLE_NUMBER = 10;

var CONNECTION_ALIVE = '-6';

//******** CONSTANT MSGS ********* //
var ADV_CAN_NOT_CONTACTED   = "The advertiser can not be contacted at this moment.";
var VIS_CAN_NOT_CONTACTED   = "We are unable to contact your number.";
var VIS_ADV_CONNECTED       = "Connected to the advertiser; talk time two minutes.";
var CALLING_VIS             = "calling you...<br/>you'll get a call from +912656698800.";
var CALLING_ADV             = "calling advertiser...<br/>please stay on the line.";
var INVALID_NO              = "You have entered an invalid number";
var INVALID_NO_MSG          = "<br/>Please enter a valid 10 digit India number without 0 but with city code / full mobile number and no spaces.";
var THANK_YOU               = "Thank you for using Click-to-Call.";
var SORRY                   = "Sorry, We are unable to contact you. Please call us later.";

// **** Global Variables in JS Ends *****


DHTML_modalMessage = function()
{
    var url;								// url of modal message
    var htmlOfModalMessage;					// html of modal message

    var divs_transparentDiv;				// Transparent div covering page content
    var divs_content;						// Modal message div.
    var iframe;								// Iframe used in ie
    var layoutCss;							// Name of css file;
    var width;								// Width of message box
    var height;								// Height of message box

    var existingBodyOverFlowStyle;			// Existing body overflow css
    var dynContentObj;						// Reference to dynamic content object
    var cssClassOfMessageBox;				// Alternative css class of message box - in case you want a different appearance on one of them
    var shadowDivVisible;					// Shadow div visible ?
    var shadowOffset; 						// X and Y offset of shadow(pixels from content box)
    var MSIE;

    this.url = '';							// Default url is blank
    this.htmlOfModalMessage = '';			// Default message is blank
    this.layoutCss = 'modal-message.css';	// Default CSS file
    this.height = 200;						// Default height of modal message
    this.width = 400;						// Default width of modal message
    this.cssClassOfMessageBox = false;		// Default alternative css class for the message box
    this.shadowDivVisible = true;			// Shadow div is visible by default
    this.shadowOffset = 5;					// Default shadow offset.
    this.MSIE = false;
    if(navigator.userAgent.indexOf('MSIE')>=0) this.MSIE = true;
}

DHTML_modalMessage.prototype =
{
    close : function()
    {

        /* Hiding divs */
        this.divs_transparentDiv.style.display='none';
        this.divs_content.style.display='none';
        this.divs_shadow.style.display='none';
        if(this.MSIE)this.iframe.style.display='none';

    },

    setHtmlContent : function(newHtmlContent)
    {
        //alert("sheru");
        this.htmlOfModalMessage = newHtmlContent;

    },

    setSize : function(width,height)
    {
        if(width)this.width = width;
        if(height)this.height = height;
    },

    display : function()
    {
        if(!this.divs_transparentDiv){
            //alert("inside if");
            this.__createDivs();
        }

        // Redisplaying divs
        this.divs_transparentDiv.style.display='block';
        this.divs_content.style.display='block';
        this.divs_shadow.style.display='block';
        if(this.MSIE)this.iframe.style.display='block';
        this.__resizeDivs();

        /* Call the __resizeDivs method twice in case the css file has changed. The first execution of this method may not catch these changes */
        window.refToThisModalBoxObj = this;
        setTimeout('window.refToThisModalBoxObj.__resizeDivs()',150);

        this.__insertContent();	// Calling method which inserts content into the message div.
    },

    __createDivs : function()
    {
        // Creating transparent div
        this.divs_transparentDiv = document.createElement('DIV');
        this.divs_transparentDiv.className='modalDialog_transparentDivs';
        this.divs_transparentDiv.style.left = '0px';
        this.divs_transparentDiv.style.top = '0px';

        document.body.appendChild(this.divs_transparentDiv);

        // Creating content div
        this.divs_content = document.createElement('DIV');
        this.divs_content.className = 'modalDialog_contentDiv';
        this.divs_content.id = 'DHTMLSuite_modalBox_contentDiv';
        this.divs_content.style.zIndex = 100000;

        if(this.MSIE){
            this.iframe = document.createElement('<IFRAME src="about:blank" frameborder=0>');
            this.iframe.style.zIndex = 90000;
            this.iframe.style.position = 'absolute';
            document.body.appendChild(this.iframe);
        }

        document.body.appendChild(this.divs_content);

        // Creating shadow div
        this.divs_shadow = document.createElement('DIV');
        this.divs_shadow.className = 'modalDialog_contentDiv_shadow';
        this.divs_shadow.style.zIndex = 95000;
        document.body.appendChild(this.divs_shadow);

    },

    __resizeDivs : function()
    {

        var topOffset = Math.max(document.body.scrollTop,document.documentElement.scrollTop);

        if(this.cssClassOfMessageBox)
            this.divs_content.className=this.cssClassOfMessageBox;
        else
            this.divs_content.className='modalDialog_contentDiv';

        if(!this.divs_transparentDiv)return;

        // Preserve scroll position
        var st = Math.max(document.body.scrollTop,document.documentElement.scrollTop);
        var sl = Math.max(document.body.scrollLeft,document.documentElement.scrollLeft);

        window.scrollTo(sl,st);
        setTimeout('window.scrollTo(' + sl + ',' + st + ');',10);

        this.__repositionTransparentDiv();

        var brSize = this.__getBrowserSize();
        var bodyWidth = brSize[0];
        var bodyHeight = brSize[1];

        // Setting width and height of content div
        this.divs_content.style.width = this.width + 'px';
        this.divs_content.style.height= this.height + 'px';

        // Creating temporary width variables since the actual width of the content div could be larger than this.width and this.height(i.e. padding and border)
        var tmpWidth = this.divs_content.offsetWidth;
        var tmpHeight = this.divs_content.offsetHeight;

        this.divs_content.style.left = Math.ceil((bodyWidth - tmpWidth) / 2) + 'px';
        this.divs_content.style.top = (Math.ceil((bodyHeight - tmpHeight) / 2) +  topOffset) + 'px';
        //alert("bH====="+bodyHeight);
        //alert("tH====" + tmpHeight);
        //alert(bodyHeight - tmpHeight);
        if(this.MSIE){
            this.iframe.style.left = this.divs_content.style.left;
            this.iframe.style.top = this.divs_content.style.top;
            this.iframe.style.width = this.divs_content.style.width;
            this.iframe.style.height = this.divs_content.style.height;
        }

        this.divs_shadow.style.left = (this.divs_content.style.left.replace('px','')/1 + this.shadowOffset) + 'px';
        this.divs_shadow.style.top = (this.divs_content.style.top.replace('px','')/1 + this.shadowOffset) + 'px';
        this.divs_shadow.style.height = tmpHeight + 'px';
        this.divs_shadow.style.width = tmpWidth + 'px';

        if(!this.shadowDivVisible)this.divs_shadow.style.display='none';	// Hiding shadow if it has been disabled

    },

     __repositionTransparentDiv : function()
    {
        this.divs_transparentDiv.style.top = Math.max(document.body.scrollTop,document.documentElement.scrollTop) + 'px';
        this.divs_transparentDiv.style.left = Math.max(document.body.scrollLeft,document.documentElement.scrollLeft) + 'px';
        var brSize = this.__getBrowserSize();
        var bodyWidth = brSize[0];
        var bodyHeight = brSize[1];

        //this.divs_transparentDiv.style.width = bodyWidth + 'px';
        //this.divs_transparentDiv.style.height = bodyHeight + 'px';

        this.divs_transparentDiv.style.width = '100%';
        this.divs_transparentDiv.style.height = '100%';

    },

    __insertContent : function()
    {
        if(this.url){	// url specified - load content dynamically
            ajax_loadContent('DHTMLSuite_modalBox_contentDiv',this.url);
        }else{	// no url set, put static content inside the message box
            this.divs_content.innerHTML = this.htmlOfModalMessage;
        }
    },

    __getBrowserSize : function()
    {
        var bodyWidth = document.documentElement.clientWidth;
        var bodyHeight = document.documentElement.clientHeight;

        var bodyWidth, bodyHeight;
        if (self.innerHeight){ // all except Explorer
           bodyWidth = self.innerWidth;
           bodyHeight = self.innerHeight;
        }  else if (document.documentElement && document.documentElement.clientHeight) {
           // Explorer 6 Strict Mode
           bodyWidth = document.documentElement.clientWidth;
           bodyHeight = document.documentElement.clientHeight;
        } else if (document.body) {// other Explorers
           bodyWidth = document.body.clientWidth;
           bodyHeight = document.body.clientHeight;
        }
        return [bodyWidth,bodyHeight];

    }
}

var messageObj = new DHTML_modalMessage();	// We only create one object of this class
messageObj.setShadowOffset;	// Large shadow i have made changes
messageObj.setCssClassMessageBox;// i have made changes
messageObj.setShadowDivVisible;	// Enable shadow for these boxes changes i have made

function callme(url, width, height, titulo, custtoken)
{
   var messageTitle ='<table class="modalDialog_titleArea" width = "100%"><tr><td align="center" width="90%">' + titulo + '</td><td align="center" width="10%"><img src="http://c4c.phonon.in/C4CWidget/Images/close.gif" border="0" WIDTH="14" HEIGHT="14" onclick="closeMessage();return false"> </td><tr><table>'

   var messageContent = '<iframe src="'+url+'?custtoken='+custtoken+'"  class="frame" width="'+(width -20)+'" height="'+(height - 30)+'" frameborder="0"></iframe>';

   messageObj.setHtmlContent(messageTitle + messageContent);
   messageObj.setSize(width, height);
   messageObj.display();
}

function closeMessage()
{
    clearInterval(intervalId);
    //var id = getIntervalId();
    //clearInterval(id);
    //window.CONNECTION_ALIVE = '-1';
    //alert('Conn Status :: '+window.CONNECTION_ALIVE);
    
    messageObj.close();    
}

function getCurrCallStatus()
{
    intervalId = setInterval("retriveCurrCallStatus()",5000);
    //intervalId = setTimeout("retriveCurrCallStatus()",5000);
    //setIntervalId(setInterval("retriveCurrCallStatus()",5000));

}

function retriveCurrCallStatus()
{   
        if (uniqueid != null || custtoken != null || uniqueid != '' || custtoken != '')
        {
            xmlHttp=GetXmlHttpObject();

            if (xmlHttp==null)
            {
                alert("Your browser not support AJAX");
                return;
            }
            else
            {
                //alert("created xmlhhtp object");
            }

            var url="RetrieveStatus"
            url=url+"?unique_id="+uniqueid+"&cust_token="+custtoken;

            xmlHttp.onreadystatechange=iresponse

            xmlHttp.open("GET",url,true)

            xmlHttp.send(null);
        }
}


function iresponse()
{
    if (xmlHttp.readyState==4)
    {
        responseStatus = xmlHttp.responseText;
        xmlHttp = null;
        retriveCallAcknowledge();
        
        //getCurrCallStatus()
    }
}

// Generate Uniqueid
function getUniqueId()
{
    var MAX_LENGTH = 15;
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var string_length = MAX_LENGTH;
	var randomstring = '';
	for (var i=0; i<string_length; i++)
    {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	return randomstring;
}

// Perform Cross Domain Call
function performCrossDomainAction(visitor_No, cust_Token, source_IP)
{
    //alert('JS - With in performCrossDomainAction');

    visitorNo = visitor_No;
    custtoken = cust_Token;
    sourceIP  = source_IP;
    uniqueid  = getUniqueId();

    xmlHttp = GetXmlHttpObject();

    if (xmlHttp==null)
    {
        alert("Your browser not support AJAX");
        return;
    }
    else
    {
        //alert("created xmlhhtp object");
    }

    var url="CrossDomainCall";
    url=url+"?visitorNo="+visitorNo+"&uniqueid="+uniqueid+"&custtoken="+custtoken+"&sourceIP="+sourceIP;

    xmlHttp.onreadystatechange=CrossDomainStatusResponse

    xmlHttp.open("GET",url,true)

    xmlHttp.send(null);
}


function CrossDomainStatusResponse()
{
    if (xmlHttp.readyState==4)
    {
        //alert('Response Text :: '+ xmlHttp.responseText);

        callResponse = xmlHttp.responseText;

        xmlHttp = null;
        
        getCurrCallStatus();
        //retriveCurrCallStatus();
    }
}



function GetXmlHttpObject()
{
    var xmlHttp=null;
    try
    {
        // Firefox, Opera 8.0+, Safari
        xmlHttp = new XMLHttpRequest();
    }
    catch (e)
    {
        //Internet Explorer
        try
        {
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
        {
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    return xmlHttp;
}


function updateCurrCallStatus()
{

    var arrValue=responseStatus.split(';');

    for (var i=0 ; i<arrValue.length ; i++)
    {

        if(i == arrValue.length-1 && arrValue[i].substr(arrValue[i].length-2, 1)!=':')
        {
            //alert('with in Max length');
            arrValue[i] = arrValue[i].substr(arrValue[i].length-2, 2);
        }
        else
        {
            //alert('with in Default length');
            arrValue[i] = arrValue[i].substr(arrValue[i].length-1, 1);
        }
        //alert('Value ::  '+arrValue[i]);
    }

    var vis_status =  arrValue[1];
    var adv_status =  arrValue[0];
    var con =  arrValue[2];
    var msg = '';
    


/*
    var	IDLE = 0;
    var	CONNECTED = 1;
    var BUSY = 2;
    var NO_REPLY = 3;
    var OTHER = 4;
    var SUCCESS = 5;
    var USER_HANGUP = 6;
    var TO_BE_CONNECTED = 7;
    var NOT_CONNECTED = 8;
    var INVALID_NUMBER_FORMAT = 9;
    var UNOBTAINABLE_NUMBER = 10;
*/

/*
//******** CONSTANT MSGS ********* //
var ADV_CAN_NOT_CONTACTED   = "The advertiser can not be contacted at this moment.";
var VIS_CAN_NOT_CONTACTED   = "We are unable to contact your number.";
var VIS_ADV_CONNECTED       = "Connected to the advertiser; talk time two minutes.";
var CALLING_VIS             = "calling you...<br/>you'll get a call from +912656698800.";
var CALLING_ADV             = "calling advertiser...<br/>please stay on the line.";
var INVALID_NO              = "You have entered an invalid number";
var INVALID_NO_MSG          = "<br/>Please enter a valid 10 digit India number without 0 but with city code / full mobile number and no spaces.";
var THANK_YOU               = "Thank you for using Click-to-Call.";
*/



    if ((vis_status == IDLE  || vis_status == TO_BE_CONNECTED || vis_status == NOT_CONNECTED) && (adv_status == TO_BE_CONNECTED))
    {
        msg = CALLING_VIS;
    }
    else if ((vis_status == CONNECTED  || vis_status == SUCCESS) && (adv_status == TO_BE_CONNECTED))
    {
        msg = CALLING_ADV;
    }
    else if ((vis_status == CONNECTED  || vis_status == SUCCESS) && (adv_status == CONNECTED || adv_status == SUCCESS))
    {
        msg = VIS_ADV_CONNECTED;
    }
    else if ((vis_status == CONNECTED  || vis_status == SUCCESS) && (adv_status == BUSY))
    {
        msg = ADV_CAN_NOT_CONTACTED;
    }
    else if ((vis_status == CONNECTED  || vis_status == SUCCESS) && (adv_status == NO_REPLY))
    {
        msg = ADV_CAN_NOT_CONTACTED;
    }
    else if ((vis_status == CONNECTED  || vis_status == SUCCESS) && (adv_status == OTHER || adv_status == NOT_CONNECTED || adv_status == UNOBTAINABLE_NUMBER))
    {
        msg = ADV_CAN_NOT_CONTACTED;
    }
    else if ((vis_status == CONNECTED  || vis_status == SUCCESS) && (adv_status == USER_HANGUP))
    {
        msg = THANK_YOU;
    }
    else if ((vis_status == CONNECTED  || vis_status == SUCCESS) && (adv_status == INVALID_NUMBER_FORMAT))
    {
        msg = INVALID_NO;
    }
    else if ((vis_status == BUSY) && (adv_status == TO_BE_CONNECTED))
    {
        msg = VIS_CAN_NOT_CONTACTED;
    }
    else if ((vis_status == NO_REPLY) && (adv_status == TO_BE_CONNECTED))
    {
        msg = VIS_CAN_NOT_CONTACTED;
    }
    else if ((vis_status == OTHER || vis_status == NOT_CONNECTED || vis_status == UNOBTAINABLE_NUMBER) && (adv_status == TO_BE_CONNECTED))
    {
        msg = VIS_CAN_NOT_CONTACTED;
    }
    else if ((vis_status == USER_HANGUP))
    {
        msg = THANK_YOU;
    }
    else if ((vis_status == INVALID_NUMBER_FORMAT) && (adv_status == TO_BE_CONNECTED))
    {
        msg =  INVALID_NO + INVALID_NO_MSG;
    }

    document.getElementById('div_response').innerHTML = msg;

    //alert('Conn  :: '+window.CONNECTION_ALIVE);

    // Status Update Terminate Only if not '-6'
    if(con != CONNECTION_ALIVE)
    {
        clearInterval(intervalId);
        //clearTimeout(intervalId);
        //clearInterval(getIntervalId());
        document.getElementById("imgLoading").style.visibility = "hidden";
    }
}


// Get Acknowledgement
function retriveCallAcknowledge()
{
    var ACK     = "ACK";    
    var resp    = callResponse.substring(0,3);        

    // IF Success Response then Update Status of Curr. Call...
    if( resp == ACK )
    {
        updateCurrCallStatus();
    }    
    else
    {
        document.getElementById('imgLoading').style.visibility = "hidden";        
        document.getElementById('div_response').innerHTML = SORRY;
    }
}