// Shared variables used by lead form control.
var lfLdCount = 0;
var lfLdLim = -1;
var lfContact = 1;
var lfOffer = 2;
var lfTestDrive = 3;
//used for ajax calendar
var dateString = "";

function LeadForm()
{
	this.Init = function(id)
	{
	    this._clientId = id;
	    this._vehId = -1;
	    this._dlrId = -1;
	    this._leadType = lfContact;
	    this._onSuccess = null;
	    this._convPage = "";
	    this._waTrackAction = "";
	    this._elmFocus = null;

	    // Add handlers so we can call functions associated with this object.
        $addHandlers($get(this._clientId + "_aSend"), {click:this.Send}, this);
        $addHandlers($get(this._clientId + "_aUpdtImg"), {click:this.UpdateCapture}, this);
        // Handlers for key press to map "enter" to the send button.
        $addHandlers($get(this._clientId + "_divLF"), {keypress:this.CheckKey}, this);

        this._delOnSuccessConfirm = Function.createDelegate(this, this.OnSuccessConfirm);
        this._delFocus = Function.createDelegate(this, this.Focus)

        // Setup a method to cleanup
        var delDispose = Function.createDelegate(this, this.Dispose);
        Sys.Application.add_unload(delDispose);
	}

    // Clean up after ourself
	this.Dispose = function()
	{
        $clearHandlers($get(this._clientId + "_aSend"));
        $clearHandlers($get(this._clientId + "_aUpdtImg"));
        $clearHandlers($get(this._clientId + "_divLF"));

        this._delOnSuccessConfirm = null;
        this._delFocus = null;
	}

    this.Focus = function()
    {
        // If in a lead popup, make sure we're back in the correct Z-index before setting focus.
        showShadowBox("divLeadPopup");

        if(this._elmFocus)
        {
	        setFocus(this._elmFocus);
        }
        else
        {
            setFocus($get(this._clientId + "_txtFirstName"));
        }
    }

    this.CaptureFocus = function()
    {
        setFocus($get(this._clientId + "_txtCapt"));
    }

	this.SetLeadCount = function(count)
	{
//	    alert("SetLeadCount: " + lfLdCount + " to " + count);

        lfLdCount = count;

        // find the capture div for all lead form controls on the page.
        var objList = document.getElementsByName("divCapt");

        for(i=0; i<objList.length; i++)
        {
            if(this.UseCapture())
            {
                // show the capture control
                removeCssClass(objList[i], "hide");
            }
            else
            {
                // hide the capture control
                addCssClass(objList[i], "hide");
            }
        }

        fixIEHeight();
	}

	this.UseCapture = function()
	{
	    // If lfLdCount is negative, or
	    // If there is a non-negative limit & the count is at least that,
	    // we use the input capture.
	    return ((0 > lfLdCount) || ((0 <= lfLdLim) && (lfLdLim <= lfLdCount)));
	}

    this.Send = function()
    {
        if(this.Validate())
        {
            // If in a lead popup, make sure the lead form will be behind the grey background while the progress is open.
            ProgressVar.Open();

            captVal = "";
            captInput = "";

            // Do we need to use the input capture control?
            if(this.UseCapture())
            {
                captVal = $get(this._clientId + "_ImageHipChallenge_dat").value;
                captInput = $get(this._clientId + "_txtCapt").value;
            }

            dateValue = "";
            timeValue = ""
            if(this._leadType == lfTestDrive)
            {
                dateValue = $get(this._clientId + "_txtTDDate").value;
                timeValue = $get(this._clientId + "_ddlTDTime").value
            }

            Reynolds.CL.Web.WebServices.VehicleFunctions.SubmitLead(this._leadType,
                this._vehId,
                this._dlrId,
                $get(this._clientId + "_txtFirstName").value, $get(this._clientId + "_txtLastName").value,
                $get(this._clientId + "_txtEmail").value,
                $get(this._clientId + "_txtDayPhone").value, $get(this._clientId + "_txtEveningPhone").value,
                $get(this._clientId + "_txtMessage").value,
                $get(this._clientId + "_cbFinance").checked, $get(this._clientId + "_cbTradeIn").checked,
                $get(this._clientId + "_txtOffer").value,
                dateValue, timeValue,
                captVal, captInput, WSKey,
                SubmitLeadSuccess,
                SubmitLeadFailure, this);
        }

        return false;
    }

    function SubmitLeadSuccess(result, context)
    {
        context.UpdateCapture();

        if(0 < context._waTrackAction.length)
        {
            fnWAPageView(context._waTrackAction);
        }

        // If we need to do conversion tracking, add an IFrame and load the file
        // that containst the conversion code snippet.
        if(0 < context._convPage.length)
        {
	        var conversionIframe = document.createElement("IFRAME");
	        conversionIframe.style.display = 'none';
	        document.body.appendChild(conversionIframe);
	        conversionIframe.src = context._convPage;
    	}

    	// Clear the fields that are not set by default on page load.
    	$get(context._clientId + "_txtMessage").value = "";
    	$get(context._clientId + "_txtOffer").value = "";
    	if(this._leadType == lfTestDrive)
    	{
    	    $get(context._clientId + "_txtTDDate").value = "";
    	}
    	$get(context._clientId + "_cbFinance").checked = false;
    	$get(context._clientId + "_cbTradeIn").checked = false;

	    // A negative lead count indicates no cookie. If it is currently negative, don't increment.
	    if(0 <= lfLdCount)
	    {
            context.SetLeadCount(lfLdCount + 1);
        }

        AlertVar.OpenAlert("SUCCESS", "", result, context._delOnSuccessConfirm);
        ProgressVar.Close();
    }

    function SubmitLeadFailure(err, context)
    {
//    alert(document.cookie);
        try
        {
            if(0 == document.cookie.length)
            {
                context.SetLeadCount(-1);
            }
        }
        catch(E)
        {
            context.SetLeadCount(-1);
        }

        context.UpdateCapture();

        // Open the alert
        context._elmFocus = $get(context._clientId + "_txtCapt");
        AlertVar.OpenAlert("ERROR", "", err.get_message(), context._delFocus);
		
        ProgressVar.Close();
    }

	// Validate inputs on the control.
	this.Validate = function()
	{
	    valid = true;
	    var elm;
	    var elmFocus = null;

	    // Clear the error messages.
   	    addCssClass($get(this._clientId + "_lferrReq"), "hide");
   	    addCssClass($get(this._clientId + "_lferrFormat"), "hide");

	    // Check the First Name value.
	    elm = $get(this._clientId + "_txtFirstName");
	    ClearErrBkg(elm);
	    if(0 == elm.value.length)
	    {
	        valid = false;
       	    removeCssClass($get(this._clientId + "_lferrReq"), "hide");
	        SetErrBkg(elm);
            if(!elmFocus){elmFocus = elm;}
	    }

	    // Check the Last Name value.
	    elm = $get(this._clientId + "_txtLastName");
	    ClearErrBkg(elm);
	    if(0 == elm.value.length)
	    {
	        valid = false;
	        removeCssClass($get(this._clientId + "_lferrReq"), "hide");
	        SetErrBkg(elm);
            if(!elmFocus){elmFocus = elm;}
	    }

	    // Check the Email value.
	    elm = $get(this._clientId + "_txtEmail");
	    ClearErrBkg(elm);
	    if(0 == elm.value.length)
	    {
	        valid = false;
	        removeCssClass($get(this._clientId + "_lferrReq"), "hide");
	        SetErrBkg(elm);
            if(!elmFocus){elmFocus = elm;}
	    }
	    else if (!g_regexEmail.test(elm.value))
        {
	        valid = false;
	        removeCssClass($get(this._clientId + "_lferrFormat"), "hide");
	        SetErrBkg(elm);
            if(!elmFocus){elmFocus = elm;}
        }

	    // Check the Day Phone value.
	    elm = $get(this._clientId + "_txtDayPhone");
	    ClearErrBkg(elm);
	    if(0 == elm.value.length)
	    {
	        valid = false;
	        removeCssClass($get(this._clientId + "_lferrReq"), "hide");
	        SetErrBkg(elm);
            if(!elmFocus){elmFocus = elm;}
	    }
	    else if (!g_regexPhone.test(elm.value))
        {
	        valid = false;
	        removeCssClass($get(this._clientId + "_lferrFormat"), "hide");
	        SetErrBkg(elm);
            if(!elmFocus){elmFocus = elm;}
        }

	    // Check the Evening Phone value.
	    elm = $get(this._clientId + "_txtEveningPhone");
	    ClearErrBkg(elm);
	    if((0 < elm.value.length) && !g_regexPhone.test(elm.value))
        {
	        valid = false;
	        removeCssClass($get(this._clientId + "_lferrFormat"), "hide");
	        SetErrBkg(elm);
            if(!elmFocus){elmFocus = elm;}
        }

        // Check the Offer value.
	    if(this._leadType == lfOffer)
	    {
	        elm = $get(this._clientId + "_txtOffer");
	        ClearErrBkg(elm);
	        if(0 == elm.value.length)
	        {
	            valid = false;
	            removeCssClass($get(this._clientId + "_lferrReq"), "hide");
	            SetErrBkg(elm);
	            if(!elmFocus){elmFocus = elm;}
	        }
	    }

	    // Check the Test Drive value.
	    if(this._leadType == lfTestDrive)
	    {
	        elm = $get(this._clientId + "_txtTDDate");
	        ClearErrBkg(elm);
	        if(0 == elm.value.length)
	        {
	            valid = false;
	            removeCssClass($get(this._clientId + "_lferrReq"), "hide");
	            SetErrBkg(elm);
	            if(!elmFocus){elmFocus = elm;}
	        }
	        else
	        {
	            //Check the format
	            var reg =/^\d{2}\/\d{2}\/\d{4}$/;
	            var testDate = elm.value;
	            var dateValid = true;
	            var month = testDate.substr(0, 2);
	            var day = testDate.substr(3, 2);
	            var year = testDate.substr(6, 4);

	            if (testDate.search(reg) == -1)
	            {
	                dateValid = false;
	            }
	            else
	            {

	                //Check that the date is valid
	                if (month == 2)
	                {
	                    if (day == 29)
	                    {
	                        if (year % 4 != 0 || (year % 100 == 0 && year % 400 != 0))
	                        {
	                            dateValid = false;
	                        }
	                    }
	                    else if (day  > 28)
	                    {
	                        dateValid = false;
	                    }
	                }
	                else if (month > 12)
	                {
	                    dateValid = false;
	                }
	                else if (month == 4 || month == 6 || month == 9 || month == 11)
	                {
	                    if (day > 30)
	                    {
	                        dateValid = false;
	                    }
	                }
	                else
	                {
	                    if (day > 31)
	                    {
	                        dateValid = false;
	                    }
	                }
	            }

	            if (dateValid)
	            {
	                //Finally, check that the date is today or in the future
	                var today = new Date;
	                var sentDate = new Date;
	                sentDate.setDate(day);
	                sentDate.setMonth(month - 1);
	                sentDate.setFullYear(year);

	                if (sentDate < today)
	                {
	                    valid = false;
	                    removeCssClass($get(this._clientId + "_lferrFormat"), "hide");
	                    SetErrBkg(elm);
	                }
	            }
	            else
	            {
	                valid = false;
	                removeCssClass($get(this._clientId + "_lferrFormat"), "hide");
	                SetErrBkg(elm);
	            }
	        }

            // Check the time drop down.
 	        elm = $get(this._clientId + "_ddlTDTime");
 	        ClearErrBkg(elm);
	        if(0 > elm.selectedIndex)
	        {
	            valid = false;
	            removeCssClass($get(this._clientId + "_lferrReq"), "hide");
	            if(!elmFocus){elmFocus = elm;}
	        }
	    }

	    // Check the input capture control if it is needed.
        if(this.UseCapture())
	    {
	        elm = $get(this._clientId + "_txtCapt");
	        ClearErrBkg(elm);
	        if(0 == elm.value.length)
	        {
	            valid = false;
	            removeCssClass($get(this._clientId + "_lferrReq"), "hide");
	            SetErrBkg(elm);
	            if(!elmFocus){elmFocus = elm;}
	        }
	    }

	    if(!valid)
	    {
	        // If there was a validation error, be sure the error messages are setup. We don't include them in the
	        // HTML because we don't want these words high on the Search Engine content rankings.
            $get(this._clientId + "_lferrReq").innerHTML = "Required field(s) missing.";
            $get(this._clientId + "_lferrFormat").innerHTML = "Invalid format on field(s).";

            setFocus(elmFocus);
	    }

	    // Fix IE height incase we hid or un-hid error messages.
	    fixIEHeight();

	    return valid;
	}

    this.OnSuccessConfirm = function()
    {
        // If in a lead popup, make sure we're back in the correct Z-index
        hideShadowBox("divLeadPopup");

        // Has an OnSend handler been registered?
        if(null != this._onSuccess)
        { this._onSuccess(); }
    }

    this.UpdateCapture = function()
    {
        $get(this._clientId + "_txtCapt").value = "";
        //$get(this._clientId + "_ImageHipChallenge_img").src = "";

        Reynolds.CL.Web.WebServices.VehicleFunctions.GetImageHipChallengeHTML(this._clientId, WSKey,
            UpdateCaptureSuccess,
            null, this);

        return false;
    }

    function UpdateCaptureSuccess(result, context)
    {
        $get(context._clientId + "_divCaptContent").innerHTML = result;

        setFocus($get(context._clientId + "_txtCapt"));
    }

    this.CheckKey = function(evt)
    {
        // evt is a Sys.UI.DomEvent object

        if (mapKeyToAction(evt))
        {
            this.Send();
            setFixValidation();
            return false;
        }
    }

}

function calendarShown(sender, e)
{
    if ($get('hiddenIE6'))
    {
        // The controls we need to hide have the same prefix as the calendar extender.
        _clientId = sender.get_id().substring(0, sender.get_id().lastIndexOf('_'));
        addCssClass($get(_clientId + "_ddlTDTime"), "invis");
        addCssClass($get(_clientId + "_aSend"), "invis");
    }

    //Set the date in the calendar to the date in the textbox
    //Needed due to date corrections handled by JS.
    updateDate(sender);
}

function calDateChange(sender, e)
{
    colorDate(sender.get_element().id);
}

function colorDate(txtTDDateId)
{
    var dateBox = $get(txtTDDateId);
    var dateInBox = dateBox.value;
    var today = new Date;
    var userDate = new Date;

    var month = dateInBox.substr(0, 2);
	var day = dateInBox.substr(3, 2);
	var year = dateInBox.substr(6, 4);

    userDate.setMonth(month - 1);
    userDate.setDate(day);
    userDate.setFullYear(year);

    if (userDate >= today)
    {
        dateBox.style.color = "#000";
    }
    else
    {
        dateBox.style.color = "#F00";
    }
}

function calendarHide(sender, e)
{
    if ($get('hiddenIE6'))
    {
        // The controls we need to show have the same prefix as the calendar extender.
        _clientId = sender.get_id().substring(0, sender.get_id().lastIndexOf('_'));
        removeCssClass($get(_clientId + "_ddlTDTime"), "invis");
        removeCssClass($get(_clientId + "_aSend"), "invis");
    }
}

function dateBlur(sender)
{
    //If Date matches format of mm/dd/yy change to mm/dd/yyyy
    //This is to correct the default behavior of the ajax mask editor

    var txtBox = sender.id;
    var passedDate = $get(txtBox).value;
    var reg =/^\d{2}\/\d{2}\/\d{2}\_\_$/;

    if (passedDate.search(reg) != -1)
    {
        //delay change to allow mask editor to do its change first
        window.setTimeout('dateReplace(\''+txtBox+'\',\''+passedDate+'\')', 150);
        window.setTimeout('colorDate(\''+txtBox+'\')', 200);
    }
    else
    {
        dateString = passedDate;
        colorDate(txtBox);
    }
}

function dateKeyPress(sender)
{
    $get(sender.id).style.color = "#000";
}

function dateReplace(txtBox, passedDate)
{
    var century = "20";

    var sub1 = passedDate.substring(0,6);
    var sub2 = passedDate.substring(6,8);
    var newString = sub1 + century + sub2;
    $get(txtBox).value = newString;
    dateString = newString;
}

function updateDate(sender)
{
    var reg =/^\d{2}\/\d{2}\/\d{4}$/;

    //if the last date set by javascript matches a correct format
    //set the date in the calendar to match the date in the textbox
    if (dateString.search(reg) != -1)
    {
        sender.set_selectedDate(dateString);
        dateString = "";
    }
}

