var LP_PHONE_NUMBER_COOKIE = "LPPhoneNumber";
var LP_PHONE_NUMBER_COOKIE_SPERATOR = "^";
var LP_PRE_CALL_URL_COOKIE = "LPPreCallUrl";
var LP_CALLBACK_URL_COOKIE = "LPCallbackUrl";
var LP_RESIZE_COOKIE = "LPResize";
var LP_PHONE_NUMBER_FIELD = "onlyphoneNumber";
var LP_EXTENSION_FIELD = "Extension";
var LP_COUNTRY_FIELD = "country";

var INVALID_PHONE = "Invalid phone number";
var ONLY_PREFIX = "Country prefix should contain only digits";
var INVALID_TICKET_ID = "Please enter a valid ticket id (LTK000000000X) or leave the field blank.";

var lpResize = false;
var shouldFixSize = true;

if (typeof(lpMinPhoneNumberLength) == "undefined")
	lpMinPhoneNumberLength = 5;

if (typeof(lpMaxPhoneNumberLength) == "undefined")
	lpMaxPhoneNumberLength = 10;

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}

function MM_addRemoveLayers() {
    var i,p,d,v,obj,args=MM_addRemoveLayers.arguments;
    for (i=0; i<(args.length-2); i+=3)
    {
        if ((obj=MM_findObj(args[i]))!=null)
        {
            v=args[i+2];
            if (obj.style)
            {
                obj=obj.style;
                d=(v=='show')?'block':(v=='hide')?'none':v;
                v=(v=='show')?'visible':(v=='hide')?'hidden':v;
            }
            obj.visibility=v;
            obj.display=d;
        }
    }
}

// get and validate phone number using the following rules:
// Do not send a request when phone number has less than lpMinPhoneNumberLength digits
// (default=5); show an error message.
// Remove all spaces, ) (, dashes and dots.
// Remove dial prefixes: 0, 00, 011.
function getPhoneNumber(theForm)
{
    var phoneNumber = "";
    var alertString = null;

    var phoneNumberField = theForm[LP_PHONE_NUMBER_FIELD];
    if (phoneNumberField != null)
        phoneNumber += phoneNumberField.value;
    else
    {
        for (i = 1; i <= lpMaxPhoneNumberLength; i++)
        {
            var phoneNumberField = theForm[LP_PHONE_NUMBER_FIELD+i];
            if (phoneNumberField != null)
            {
                if (phoneNumberField.value == "")
                    alertString = INVALID_PHONE;
                phoneNumber += phoneNumberField.value;
            }
            else
                break;
        }
    }

    // remove "().-" chars from the string
	phoneNumber = phoneNumber.replace(/[ \(\)\.\-]/g, "");

	if (phoneNumber.substring(0,3) == "011")
	{
		phoneNumber = phoneNumber.substring(3, phoneNumber.length);
	}
	else if (phoneNumber.substring(0,2) == "00")
	{
		phoneNumber = phoneNumber.substring(2, phoneNumber.length);
	}
	else if (phoneNumber.substring(0,1) == "0")
	{
		phoneNumber = phoneNumber.substring(1, phoneNumber.length);
	}

    if (phoneNumber.length < lpMinPhoneNumberLength || phoneNumber.length > lpMaxPhoneNumberLength ||
        phoneNumber.match(/^\d+$/) == null)
	{
	 	 alertString = INVALID_PHONE;
	}

	if (alertString != null) {
		alert(alertString);
		return null;
	}

	return phoneNumber;
}

function verify(formobj)
{
    var q4=formobj[LP_EXTENSION_FIELD].value;
    var q1=formobj[LP_COUNTRY_FIELD].value;
    var q3=getPhoneNumber(formobj);
    var q5=formobj.Ticket.value;
    var q2=formobj.identifier.value;

    if (q3 == null)
        return false;
    
    formobj["SESSIONVAR!Country"].value=q1;
    formobj.phoneNumber.value = q1+q3;
    formobj["SESSIONVAR!Callers_Number"].value=q1+q3;
    formobj["SESSIONVAR!Extension"].value=q4;
    formobj["SESSIONVAR!Ticket"].value=q5;
    formobj["SESSIONVAR!identifier"].value=q2;

	var val = formobj.phoneNumber.value;
	var ok = ((val != null) && (val.match(/^\d+$/) != null));
	var alertString = null;

	if (! ok)
		alertString = ONLY_PREFIX;

	var val = formobj.Ticket.value;
	var ok2 = (val == null) || (val == "") || (val.match(/LTK\d+X/) != null);
	if (! ok2) {
		if (alertString == null)
			alertString = "";
		else
			alertString += "\n";
		alertString += INVALID_TICKET_ID;
	}
	if (! (ok && ok2))
		alert(alertString);
    if (ok && ok2) {
        setPhoneNumberCookies(formobj);
        setPreCallUrlCookie();
        setCallbackUrlCookie(formobj);
    }
	return ok && ok2;
}

function onCallMe(formObj)
{
    if (verify(formObj))
    {
        shouldFixSize = false;
        formObj.submit();
    }
}

// Display the queue status in lpcttApproximatedTimeInQueue and lpcttApproximatedPlaceInQueue
// fields, if lpcttDisplayQueueStatus variable is not true nothing will be done.
// this methos is used by /hcp/html/lpCheckVisitorQueueStats.js script
// and must being loaded before it.
function visitorQueueStatsNotifyFunction(avgWait, estimatedPlaceInQueue, status)
{
    if (status != LP_SERVICE_UP)
        return;

    var	waitMsg	= "";
    var	placeInQueueMsg	= "";
    var	hrs	= Math.floor(avgWait / 3600);
    var	mnts = Math.floor(avgWait /	60);
    if (hrs	> 0) {
        waitMsg	= hrs +	(hrs > 1 ? " Hours"	: "	Hour");
        avgWait	= avgWait -	(hrs * 3600);
    }
    if (mnts > 0) {
        waitMsg	= waitMsg +	(hrs > 0 ? " and " : "") + mnts	+ (mnts	> 1	? "	Minutes" : " Minute");
        avgWait	= avgWait -	(mnts *	60);
    }
    if (hrs	== 0 &&	avgWait	> 0) {
        waitMsg	= waitMsg +	(mnts >	0 ?	" and "	: "") +	avgWait	+ (avgWait > 1 ? " Seconds"	: "	Second");
    }

    var queueLengthMsg = estimatedPlaceInQueue - 1;
    if (queueLengthMsg == 0)
        queueLengthMsg = 'no';

    var approximatedTimeInQueue = document.getElementById("approximatedTimeInQueue");
    if (approximatedTimeInQueue != undefined)
        approximatedTimeInQueue.innerHTML = waitMsg;
    var approximatedPlaceInQueue = document.getElementById("approximatedPlaceInQueue");
    if (approximatedPlaceInQueue != undefined)
        approximatedPlaceInQueue.innerHTML = queueLengthMsg;
}

function getCookie(c_name)
{
	if (document.cookie.length > 0)
	{
		c_start=document.cookie.indexOf(c_name + "=")
		if (c_start!=-1)
		{
			c_start=c_start + c_name.length+1
			c_end=document.cookie.indexOf(";",c_start)
			if (c_end==-1) c_end=document.cookie.length
				return unescape(document.cookie.substring(c_start,c_end))
		}
	}
	return null
}

function setCookie(c_name, value, expiredays)
{
	var exdate=new Date()
	exdate.setDate(exdate.getDate()+expiredays)
	var cookieValue = c_name + "=" +escape(value);
	if (expiredays != null)
		cookieValue += ';expires=' + exdate.toGMTString();
	document.cookie = cookieValue;
}

function loadPhoneNumberFromCookie(theForm)
{
        var cookieValue = getCookie(LP_PHONE_NUMBER_COOKIE);
        if (cookieValue != null)
        {
            var cookieValues = cookieValue.split(LP_PHONE_NUMBER_COOKIE_SPERATOR);
            var fieldsCount = 2; // country and extension
            if (theForm[LP_PHONE_NUMBER_FIELD] != null)
                fieldsCount++;
            else
            {
                for (i = 1; i <= lpMaxPhoneNumberLength && theForm[LP_PHONE_NUMBER_FIELD + i] != null ; i++)
                    fieldsCount++;
            }

            if (fieldsCount != cookieValues.length)
                return; // the number of phone fields has changed

            var countryOptions = theForm[LP_COUNTRY_FIELD].options;
            var found = false;
            for (var i = 0; i < countryOptions.length; i++)
            {
                if (countryOptions[i].text == cookieValues[0])
                {
                    theForm[LP_COUNTRY_FIELD].selectedIndex = i;
                    found = true;
                    break;
                }
            }

            if (!found)
                theForm[LP_COUNTRY_FIELD].value = cookieValues[0];

            var phoneNumberField = theForm[LP_PHONE_NUMBER_FIELD];
            if (phoneNumberField != null)
                phoneNumberField.value = cookieValues[1];
            else
            {
                for(i = 1; i <= fieldsCount; i++)
                {
                    var phoneNumberField = theForm[LP_PHONE_NUMBER_FIELD + i];
                    if (phoneNumberField != null)
                        phoneNumberField.value = cookieValues[i];
                }
            }

            theForm[LP_EXTENSION_FIELD].value = cookieValues[cookieValues.length - 1];
        }
}

function setPhoneNumberCookies(theForm)
{
    if (typeof(lpcttPrePopulatePhone) != "undefined" && lpcttPrePopulatePhone)
    {
        var cookieValue = "";

        var countryControl = theForm[LP_COUNTRY_FIELD];
        cookieValue += countryControl.options[countryControl.selectedIndex].text;

        var phoneNumberField = theForm[LP_PHONE_NUMBER_FIELD];
        if (phoneNumberField != null)
            cookieValue += LP_PHONE_NUMBER_COOKIE_SPERATOR + phoneNumberField.value;
        else
        {
            for (i = 1; i <= lpMaxPhoneNumberLength; i++)
            {
                var phoneNumberField = theForm[LP_PHONE_NUMBER_FIELD+i];
                if (phoneNumberField != null)
                    cookieValue += LP_PHONE_NUMBER_COOKIE_SPERATOR + phoneNumberField.value;
                else
                    break;
            }
        }

        var extensionField = theForm[LP_EXTENSION_FIELD];
        if (extensionField != null)
            cookieValue += LP_PHONE_NUMBER_COOKIE_SPERATOR + extensionField.value;

        setCookie(LP_PHONE_NUMBER_COOKIE, cookieValue, 365)
    }
}

function isResizeCookie()
{
    return getCookie(LP_RESIZE_COOKIE) == "true";
}

function setResizeCookie()
{
    setCookie(LP_RESIZE_COOKIE, "true", null)
}

function clearResizeCookie()
{
    setCookie(LP_RESIZE_COOKIE, "false", null)
}

function fixSize() {
  if (! lpResize) return;
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  try {
  xdelta = (document.all) ? 8 : 10;
  ydelta = (document.all) ? 17 : 0;
  window.resizeTo(xdelta + window.document.body.scrollWidth + window.document.body.scrollWidth - myWidth,window.document.body.scrollHeight + window.document.body.scrollHeight - myHeight - ydelta);
  } catch(e) {
  }
}

function fixSizeBack() {
    if (! isResizeCookie()) return;
    if (! shouldFixSize) return;
    clearResizeCookie();
    if (document.all)
        window.resizeTo(window.screen.availWidth, window.screen.availHeight);
}

function setPreCallUrlCookie()
{
    setCookie(LP_PRE_CALL_URL_COOKIE, document.URL, null);
}

function loadPreCallUrlFromCookie()
{
    shouldFixSize = false;
    var preCallUrl = getCookie(LP_PRE_CALL_URL_COOKIE);
    if (preCallUrl != null)
        document.location = preCallUrl;
}

function setCallbackUrlCookie(formObj)
{
    var formAction = formObj.action;
    var formElements = formObj.elements;
    var formParams = "";

    for (i = 0; i < formElements.length; i++)
    {
         formParams += "&" + formElements[i].name + "=" + escape(formElements[i].value);
    }
    setCookie(LP_CALLBACK_URL_COOKIE, formAction + formParams, null);
}

function loadCallbackUrlFromCookie()
{
    shouldFixSize = false;
    var callbackUrl = getCookie(LP_CALLBACK_URL_COOKIE);
    if (callbackUrl != null)
        document.location = callbackUrl;
}

function setNextFocus(phoneNumberFieldObj)
{
    if (phoneNumberFieldObj.value.length == phoneNumberFieldObj.maxLength)
    {
        var fieldName = phoneNumberFieldObj.name;
        var fieldNameSuffix = fieldName.substr(fieldName.length-1);
        var nextFieldNameSuffix = parseInt(fieldNameSuffix) + 1;
        var nextFieldName = fieldName.substr(0, fieldName.length-1) + nextFieldNameSuffix
        var nextField = phoneNumberFieldObj.form.elements[nextFieldName];

        if (nextField != null)
        {
            nextField.focus();
            nextField.select();
        }
    }
}

function handleButtonsVisibility(buttonId, cookieName)
{
    if (getCookie(cookieName) == null)
    {
        var buttonControl = document.getElementById(buttonId);
        if (buttonControl != null)
            buttonControl.style.visibility = "hidden";
    }
}

function handleRetryVisibility(id) {
    handleButtonsVisibility(id, LP_CALLBACK_URL_COOKIE)
}

function handleBackVisibility(id) {
    handleButtonsVisibility(id, LP_PRE_CALL_URL_COOKIE)
}

function onCancelCall()
{
    shouldFixSize = false;
    document.cancelForm.submit();
}
