﻿if (!this.IPS) {
    IPS = {};
}
if (!this.IPS.L1) {
    IPS.L1 = {
        previousSubmissions:[],
        currentVehicleID:null,
        viewVideoClick: function(videoURL) {
            if (IPS.L1.Serv.VideoPlayerURL) {
                var newWin = window.open('', 'L1_Media', 'height=480,width=640,resizeable');
                newWin.document.write('<html><head><script type="text/javascript">function getBorderSizes(){var wh=[null,null];if(getViewportWH()[0] && window.resizeTo){window.resizeTo(300,300);wh[0]=300-getViewportWH()[0];wh[1]=300-getViewportWH()[1];}return wh;}function getViewportWH(){var wh=[null,null];if(window.innerWidth){wh[0]=window.innerWidth;wh[1]=window.innerHeight;}else if(document.documentElement && document.documentElement.clientWidth){wh[0]=document.documentElement.clientWidth;wh[1]=document.documentElement.clientHeight;}else if(document.body && document.body.clientWidth){wh[0]=document.body.clientWidth;wh[1]=document.body.clientHeight;}return wh;} function resizeViewport(){var wh=getBorderSizes();if(wh[0] && window.resizeTo && document.images){window.resizeTo(640+wh[0], 480+wh[1]);}};<\/script></head><body style="margin:0; padding:0;" onload="resizeViewport();"><form id="form1" runat="server"><div align="center"><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="640" height="480" align="middle"><param name="allowScriptAccess" value="sameDomain" /><param name="movie" value="' + IPS.L1.Serv.VideoPlayerURL + '" /><param name="FlashVars" value="flvURL=' + videoURL + '&ControlPanelColor=0xa6caf0&buttonColor=0x000000&ControlPanelPosition=0&showControlPanel=1&ShowtimeColor=0xffffff&bAutoPlay=1&bAutoRepeat=0&BufferTime=5000&tmeColor=0xffffff&loaColor=0x666666&GroundColor=0x000000&conNum=0&bShowtime=1&startvolume=100" /><param name="quality" value="high" /><param name="bgcolor" value="#000000" /><param name="scale" value="noscale" /><param name="salign" value="lt" />  <embed src="' + IPS.L1.Serv.VideoPlayerURL + '" width="640" height="480" align="middle" quality="high" bgcolor="#000000" scale="noscale" salign="lt" flashvars="flvURL=' + videoURL + '&ControlPanelColor=0xa6caf0&buttonColor=0x000000&ControlPanelPosition=0&showControlPanel=1&ShowtimeColor=0xffffff&bAutoPlay=1&bAutoRepeat=0&BufferTime=5000&tmeColor=0xffffff&loaColor=0x666666&GroundColor=0x000000&conNum=0&bShowtime=1&startvolume=100" allowscriptsccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /></object></div></form></body></html>');
                newWin.document.close();
                newWin.focus();
            }
        },
        
        viewSisterVideoClick:function(mediaID){
        	var newWin = window.open('', 'L1_Media', 'height=340,width=500,resizable,location=no');
			newWin.document.write('<html> <head> <title>Media Player</title></head><body><iframe frameborder="0" height="100%" width="100%" scrolling="no" src="http://3df.pod0.sister.tv/3df/3df-dist-2.0/player.php?mediaid=' + mediaID + '" /></body> </html> <html>');
			newWin.document.close();
            newWin.focus();
        },
        
        alreadySubmittedData:function(dataString){
            var alreadySubmitted = false;
            for(var i = 0; i < IPS.L1.previousSubmissions.length; i++){
                if(dataString == IPS.L1.previousSubmissions[i]){
                    alreadySubmitted = true;
                    break;
                }
            }
            return alreadySubmitted;
        },
        
        getUserInfo:function(){
            var user = {};
            var fName = $('L1_FirstName');
            var lName = $('L1_LastName');
            var phone = $('L1_Phone');
            var postal = $('L1_Postal');
            var street1 = $('L1_Street1');
            var street2 = $('L1_Street2');
            var city = $('L1_City');
            var state = $('L1_State');
            var email = $('L1_Email');
            if(fName){
                user.FirstName = fName.value.trim();
            }            
            if(lName){
                user.LastName = lName.value.trim();
            }
            if(phone){
                user.PhoneNumber = IPS.Shared.StripFormat.phoneNumber(phone.value.trim());
            }
            if(postal){
                user.PostalCode = IPS.Shared.StripFormat.postalCode(postal.value.trim());
            }
            if(street1){
                user.Address1 = street1.value.trim();
            }
            if(street2){
                user.Address2 = street2.value.trim();
            }
            if(city){
                user.City = city.value.trim();
            }
            if(state){
                user.State = state.options[state.selectedIndex].value.trim();
            }
            if(email){
                user.Email = email.value.trim();
            }
            return user;
        },
        
        clearResults:function(){
            var resultP = $('L1_Result');
            if(resultP){
                while(resultP.firstChild){
                    resultP.removeChild(resultP.firstChild);
                }
                resultP.style.display = 'none';
            }
        },

        clearValidators: function() {
            var popup = $('L1_PopUp');
            var allLis = popup.getElementsByTagName('LI');
            for(var i = 0; i < allLis.length; i++){
                IPS.Shared.Validate.markValid(allLis[i]);
            }
            var valMsg = $('L1_ValMsg');
            if(valMsg){
                valMsg.style.display = 'none';
            }
        },
        
        validateForm:function(subFormName){
            var isValid = true;
            IPS.L1.clearValidators();
            var fName = $('L1_FirstName');
            var lName = $('L1_LastName');
            var email = $('L1_Email');
            var postal = $('L1_Postal');
            var phone = $('L1_Phone');
            var fNameLi = $('L1_FirstNameLi');
            var lNameLi = $('L1_LastNameLi');
            var emailLi = $('L1_EmailLi');
            var postalLi = $('L1_PostalLi');
            var phoneLi = $('L1_PhoneLi');
            var valMsg = $('L1_ValMsg');
            if(fName && fNameLi){
                if(fName.value.trim() == ''){
                    isValid = false;
                    IPS.Shared.Validate.markInvalid(fNameLi);                
                }
            }
            if(lName && lNameLi){
                if(lName.value.trim() == ''){
                    isValid = false;
                    IPS.Shared.Validate.markInvalid(lNameLi);
                }
            }
            if (email && emailLi) {
                if (!IPS.Shared.Validate.email(email.value.trim())) {
                    isValid = false;
                    IPS.Shared.Validate.markInvalid(emailLi);
                }
            }
            if (postal && postalLi) {
                if (postal.value.trim().length > 0 && !IPS.Shared.Validate.postalCode(IPS.Shared.StripFormat.postalCode(postal.value.trim()))) {
                    isValid = false;
                    IPS.Shared.Validate.markInvalid(postalLi);
                }
            }
            if (phone && phoneLi) {
                if (phone.value.trim().length > 0 && !IPS.Shared.Validate.phoneNumber(IPS.Shared.StripFormat.phoneNumber(phone.value.trim()))) {
                    isValid = false;
                    IPS.Shared.Validate.markInvalid(phoneLi);
                }
            }
            switch(subFormName){
                case 'Email':
                    var emailName = $('L1_EmailName');
                    var emailEmail = $('L1_EmailEmail');
                    var emailNameLi = $('L1_EmailNameLi');
                    var emailEmailLi = $('L1_EmailEmailLi');
                    if(emailName && emailNameLi){
                        if(emailName.value.trim() == ''){
                            isValid = false;
                            IPS.Shared.Validate.markInvalid(emailNameLi);
                        }
                    }
                    if(emailEmail && emailEmailLi){
                        if(!IPS.Shared.Validate.email(emailEmail.value.trim())){
                            isValid = false;
                            IPS.Shared.Validate.markInvalid(emailEmailLi);
                        }
                    }
                    break;
                case 'Offer':
                    //this is a little different. it is valid if at least one of the two fields are filled out.
                    //also, for text an offer, both email and phone are required.
                    var offerPrice = $('L1_OfferPrice');
                    var offerPayment = $('L1_OfferPayment');
                    var offerPriceLi = $('L1_OfferPriceLi');
                    var offerPaymentLi = $('L1_OfferPaymentLi');
                    if(offerPrice && offerPriceLi && offerPayment && offerPaymentLi){
                        //if they are both empty, invalid
                        if(offerPrice.value.trim() == '' && offerPayment.value.trim() == ''){
                            isValid = false;
                            IPS.Shared.Validate.markInvalid(offerPriceLi);
                            IPS.Shared.Validate.markInvalid(offerPaymentLi);
                        }else{ //if at least one has a value, validate that they are numbers
                            if(offerPrice.value.trim() != '' && !IPS.Shared.Validate.money(offerPrice.value.trim())){
                                isValid = false;
                                IPS.Shared.Validate.markInvalid(offerPriceLi);
                            }
                            if(offerPayment.value.trim() != '' && !IPS.Shared.Validate.money(offerPayment.value.trim())){
                                isValid = false;
                                IPS.Shared.Validate.markInvalid(offerPaymentLi);
                            }
                        }
                    }
                    if(IPS.L1.Serv.IsTextAnOffer == true){
                        if(postal && postalLi){
                            if(postal.value.trim() == ''){
                                isValid = false;
                                IPS.Shared.Validate.markInvalid(postalLi);
                            }
                        }                        
                        if (phone && phoneLi) {
                            if (phone.value.trim() == '') {
                                isValid = false;
                                IPS.Shared.Validate.markInvalid(phoneLi);
                            }
                        }
                    }
                    break;
                case 'TestDrive':
                    var testDriveDate = $('L1_TestDriveDate');
                    var testDriveTime = $('L1_TestDriveTime');
                    var testDriveDateLi = $('L1_TestDriveDateLi');
                    var testDriveTimeLi = $('L1_TestDriveTimeLi');
                    var testDriveDateAlt = $('L1_TestDriveDateAlt');
                    var testDriveTimeAlt = $('L1_TestDriveTimeAlt');
                    var testDriveDateAltLi = $('L1_TestDriveDateAltLi');
                    var testDriveTimeAltLi = $('L1_TestDriveTimeAltLi');
                    if(testDriveDate && testDriveDateLi){
                        if(!IPS.Shared.Validate.date(testDriveDate.value.trim())){
                            isValid = false;
                            IPS.Shared.Validate.markInvalid(testDriveDateLi);
                        }
                    }
                    if(testDriveTime && testDriveTimeLi){
                        if(!IPS.Shared.Validate.time(testDriveTime.value.trim())){
                            isValid = false;
                            IPS.Shared.Validate.markInvalid(testDriveTimeLi);
                        }
                    }
                    if(testDriveDateAlt && testDriveDateAltLi && testDriveDateAlt.value.trim() != ''){
                        if(!IPS.Shared.Validate.date(testDriveDateAlt.value.trim())){
                            isValid = false;
                            IPS.Shared.Validate.markInvalid(testDriveDateAltLi);
                        }
                    }                             
                    if(testDriveTimeAlt && testDriveTimeAltLi && testDriveTimeAlt.value.trim() != ''){
                        if(!IPS.Shared.Validate.time(testDriveTimeAlt.value.trim())){
                            isValid = false;
                            IPS.Shared.Validate.markInvalid(testDriveTimeAltLi);
                        }
                    }
                    break;
                case 'TradeIn':
                    var tradeInYear = $('L1_TradeInYear');
                    var tradeInMake = $('L1_TradeInMake');
                    var tradeInModel = $('L1_TradeInModel');
                    var tradeInMileage = $('L1_TradeInMileage');
                    var tradeInYearLi = $('L1_TradeInYearLi');
                    var tradeInMakeLi = $('L1_TradeInMakeLi');
                    var tradeInModelLi = $('L1_TradeInModelLi');
                    var tradeInMileageLi = $('L1_TradeInMileageLi');
                    if(tradeInYear && tradeInYearLi){
                        if(!IPS.Shared.Validate.year(tradeInYear.value.trim())){
                            isValid = false;
                            IPS.Shared.Validate.markInvalid(tradeInYearLi);
                        }
                    }
                    if(tradeInMake && tradeInMakeLi){
                        if(tradeInMake.value.trim() == ''){
                            isValid = false;
                            IPS.Shared.Validate.markInvalid(tradeInMakeLi);                
                        }
                    }
                    if(tradeInModel && tradeInModelLi){
                        if(tradeInModel.value.trim() == ''){
                            isValid = false;
                            IPS.Shared.Validate.markInvalid(tradeInModelLi);                
                        }
                    }
                    if(tradeInMileage && tradeInMileageLi){
                        if(!IPS.Shared.Validate.wholeNum(tradeInMileage.value.trim())){
                            isValid = false;
                            IPS.Shared.Validate.markInvalid(tradeInMileageLi);
                        }
                    }
                    break;
            }
            if(valMsg){
                if(isValid != true){
                    valMsg.style.display = '';
                }
            }
            return isValid;
        },
            
        closeBtnClick: function(e) {
            if(!e){
                e = window.event;
            }
            var popup = $('L1_PopUp');
            if (popup) {
                popup.style.display = 'none';
                IPS.Shared.removeCover();
            }
            if(e){
                if ('preventDefault' in e) {
                    e.preventDefault();
                } else if ('returnValue' in e) {
                    e.returnValue = false;
                }
            }
        },
        
        changePopupClass:function(className){
            var popup = $('L1_PopUp');
            if (popup) {
                IPS.Shared.removeClass(popup, 'L1_EmailFriend');
                IPS.Shared.removeClass(popup, 'L1_MakeOffer');
                IPS.Shared.removeClass(popup, 'L1_TradeIn');
                IPS.Shared.removeClass(popup, 'L1_TestDrive');
                IPS.Shared.addClass(popup, className);
            }
        },
        
        hideAllSubForms:function(){
            var emailSub = $('L1_EmailFriendForm');
            var offerSub = $('L1_MakeOfferForm');
            var testDriveSub = $('L1_TestDriveForm');
            var tradeInSub = $('L1_TradeInForm');
            if(emailSub && offerSub && testDriveSub && tradeInSub){
                emailSub.style.display = 'none';
                offerSub.style.display = 'none';
                testDriveSub.style.display = 'none';
                tradeInSub.style.display = 'none';
            }
            var L1_PhoneRequiredIndicator = $('L1_PhoneRequiredIndicator');
            var L1_ZipRequiredIndicator = $('L1_ZipRequiredIndicator');
            if(L1_PhoneRequiredIndicator){
                L1_PhoneRequiredIndicator.style.display = 'none';
            }
            if(L1_ZipRequiredIndicator){
                L1_ZipRequiredIndicator.style.display = 'none';
            }
        },
        
        showPopUp:function(){
            var popup = $('L1_PopUp');
            if (popup) {
                popup.parentNode.removeChild(popup);
                IPS.Shared.addCover();
                document.body.appendChild(popup);
                popup.style.display = '';
                IPS.Shared.centerElement(popup);
            }
        }, 

        showOfferForm: function(vehicleName, vehicleID) {
            IPS.L1.currentVehicleID = vehicleID;
            //show the correct header text
            var header = $('L1_MainHeader');
            if (header) {
                while (header.firstChild) {
                    header.removeChild(header.firstChild);
                }
                var tn = document.createTextNode(IPS.L1.Serv.OfferHeaderText);
                header.appendChild(tn);
            }
            var subheader = $('L1_SubHeader');
            if (subheader) {
                while (subheader.firstChild) {
                    subheader.removeChild(subheader.firstChild);
                }
                var tn = document.createTextNode(vehicleName);
                subheader.appendChild(tn);
            }
            IPS.L1.changePopupClass('L1_MakeOffer');
            IPS.L1.hideAllSubForms();
            IPS.L1.clearValidators();
            IPS.L1.clearResults();
            var sub = $('L1_MakeOfferForm');
            if (sub) {
                sub.style.display = '';
            }
            //show the add'l req indicators if this is the text offer
            if(IPS.L1.Serv.IsTextAnOffer == true){
                var L1_PhoneRequiredIndicator = $('L1_PhoneRequiredIndicator');
                var L1_ZipRequiredIndicator = $('L1_ZipRequiredIndicator');
                if(L1_PhoneRequiredIndicator){
                    L1_PhoneRequiredIndicator.style.display = '';
                }
                if(L1_ZipRequiredIndicator){
                    L1_ZipRequiredIndicator.style.display = '';
                }
            }
            var submitBtn = $('L1_SubmitBtn');
            submitBtn.onclick = IPS.L1.submitOffer;
            IPS.L1.showPopUp();
        },

        submitOffer: function(e) {
            if (!e && window.event) {
                e = window.event;
            }
            IPS.L1.clearResults();
            if (IPS.L1.validateForm('Offer')) {
                var formData = {};
                formData.User = IPS.L1.getUserInfo();
                formData.Offer = {};
                formData.VehicleID = IPS.L1.currentVehicleID;
                var offerPrice = $('L1_OfferPrice');
                var offerPayment = $('L1_OfferPayment');
                var offerMessage = $('L1_OfferMessage');
                if (offerPrice) {
                    formData.Offer.PurchasePriceOffer = IPS.Shared.StripFormat.money(offerPrice.value).trim();
                }
                if (offerPayment) {
                    formData.Offer.MonthlyPaymentOffer = IPS.Shared.StripFormat.money(offerPayment.value).trim();
                }
                if (offerMessage) {
                    formData.Offer.Message = offerMessage.value.trim();
                }
                var formDataString = 'submitOfferRequest~^~' + JSON.stringify(formData);
                if (!IPS.L1.alreadySubmittedData(formDataString)) {
                    L1CallServer(formDataString, 'submitOfferRequest');
                    IPS.L1.previousSubmissions.push(formDataString);
                    //disable the submit button until the response comes back
                    var submitBtn = $('L1_SubmitBtn');
                    if (submitBtn) {
                        submitBtn.onclick = null;
                        IPS.Shared.disableElement(submitBtn);
                    }
                }
            }
            if (e) {
                if ('preventDefault' in e) {
                    e.preventDefault();
                } else if ('returnValue' in e) {
                    e.returnValue = false;
                }
            }
        },

        submitOfferRequestHandler: function(args) {
            var response = JSON.parse(args);
            var resultP = $('L1_Result');
            if (resultP) {
                while (resultP.firstChild) {
                    resultP.removeChild(resultP.firstChild);
                }
                resultP.appendChild(document.createTextNode(response));
                resultP.style.display = '';
            }
            //re-enable the submit button
            var submitBtn = $('L1_SubmitBtn');
            if (submitBtn) {
                submitBtn.onclick = IPS.L1.submitOffer;
                IPS.Shared.enableElement(submitBtn);
            }
        },

        submitOfferRequestError: function(error) {
            var resultP = $('L1_Result');
            if (resultP && IPS.L1.Serv.FailureMsg) {
                while (resultP.firstChild) {
                    resultP.removeChild(resultP.firstChild);
                }
                resultP.appendChild(document.createTextNode(IPS.L1.Serv.FailureMsg));
                resultP.style.display = '';
            }
            //re-enable the submit button
            var submitBtn = $('L1_SubmitBtn');
            if (submitBtn) {
                submitBtn.onclick = IPS.L1.submitOffer;
                IPS.Shared.enableElement(submitBtn);
            }
        },
        
        receiveServerData:function(response, context){
            if(IPS.L1[context + 'Handler']){
                IPS.L1[context + 'Handler'].call(this, response);
            }
        },
        
        serverError:function(error, context){
            if(IPS.L1[context + 'Error']){
                IPS.L1[context + 'Error'].call(this, error);
            }else{
                alert('There was an error on the server.');
            }
        }
    };
} else {
    throw 'IPS.L1 already exists.';
}

//addEvent(window, 'load', IPS.L1.init);