function DL_QualWidget() {
    this.url = "http://" + document.location.host;
    this.PageName = "default.aspx";
    this.PhoneSwapText = LANDING_PHONE_SWAP;
    this.AddressSwapText = LANDING_ADDRESS_SWAP;
    this.InvalidPhoneNumberError = GENERAL_INVALID_PHONE_NUMBER;
    this.InvalidAddressError = GENERAL_INVALID_ADDRESS;
    this.InvalidZipError = GENERAL_INVALID_ZIPCODE;
    this.InvalidApartmentError = GENERAL_INVALID_APARTMENT;
    this.InvalidCityError = GENERAL_INVALID_CITY;
    this.InvalidStateError = GENERAL_INVALID_STATE;
    this.InvalidEmailError = SEARCH_PANEL_INVALID_EMAIL;

    this.Option1Label = LANDING_OPTION1_LABEL;
    this.Option1Required = false;
    this.Option1ValidationMessage = LANDING_OPTION1_VALIDATION_MSG;
    this.Option1Show = null;
    this.Option2Label = LANDING_OPTION2_LABEL;
    this.Option2Required = false;
    this.Option2ValidationMessage = LANDING_OPTION2_VALIDATION_MSG;
    this.Option2Show = null;
    this.Option3Label = LANDING_OPTION3_LABEL;
    this.Option3Required = false;
    this.Option3ValidationMessage = LANDING_OPTION3_VALIDATION_MSG;
    this.Option3Show = null;
    this.Option4Label = LANDING_OPTION4_LABEL;
    this.Option4Required = false;
    this.Option4ValidationMessage = LANDING_OPTION4_VALIDATION_MSG;
    this.Option4Show = null;
    this.Option5Label = LANDING_OPTION5_LABEL;
    this.Option5Required = false;
    this.Option5ValidationMessage = LANDING_OPTION5_VALIDATION_MSG;
    this.Option5Show = null;

    this.ApartmentLabel = LANDING_APARTMENT_LABEL;
    this.ZipLabel = LANDING_ZIP_LABEL;
    this.PhoneLabel = LANDING_PHONE_LABEL;
    this.AddressLabel = LANDING_ADDRESS_LABEL;
    this.EmailLabel = LANDING_EMAIL_LABEL;

    this.standInText = new Hash();
    //this.standInText.set("dl_addressInput", "Type address here");
    //this.standInText.set("dl_emailInput", "Email@email.com");

    this.mode = this.DisplayMode.PHONE;

    this.PhoneRequired = true;
    this.AddressRequired = true;
    this.EmailRequired = false;
    this.AllowModeSwitch = true;
    this.CityRequired = false;
    this.StateRequired = false;
    this.PhoneSuffixTab = true;

    this.option1 = null;
    this.option2 = null;
    this.option3 = null;
    this.option4 = null;
    this.option5 = null;

    this.couponCodeContainerID = null;

    //init promo id
    if (typeof (CampaignInfo) != 'undefined') {
        var campaign = $H(CampaignInfo);
        if (campaign) this.PromoID = campaign.get("promoid");
    }

    this.handleKey = this.handleKey.bind(this);
    this.standinFocus = this.inputStandinFocus.bind(this);
    this.standinBlur = this.inputStandinBlur.bind(this);
    this.blurHandler = this.BlurHandler.bindAsEventListener(this);

    var endIdx = Math.min(location.href.lastIndexOf(location.search), location.href.lastIndexOf(location.hash));
    var pagename = location.href.substring(location.href.indexOf(location.pathname, 8) + 1, endIdx).toLowerCase();
    Event.observe(window, "load", this.init.bind(this));
}

DL_QualWidget.prototype.init =
function() {
	if (this.MobileRedirectURL) {
		window.DigitalCommerce_MobileRedirectURL = this.MobileRedirectURL;
		if(detectMobile())
			return;
	}

	this.setupStandInText();
	this.setupHandleKey();
	this.prePop();

	for (var i = 1; i < 6; i++) {
		var show = this["Option" + i + "Show"];
		if (show != null) {
			var pnl = $('dl_option' + i + 'Panel');
			if (show == true) {
				if (pnl) pnl.style.display = "block";
			}
			else {
				if (pnl) pnl.style.display = "none";
			}
		}
	}

	//ensure that proper panel is showing
	var addressPanel = $("dl_addressPanel");
	var phonePanel = $("dl_phonePanel");
	if (this.mode == this.DisplayMode.PHONE && phonePanel.getStyle("display") == "none") {
		addressPanel.style.display = "none";
		phonePanel.style.display = "block";
	}
	else if (this.mode == this.DisplayMode.ADDRESS && addressPanel.getStyle("display") == "none") {
		addressPanel.style.display = "block";
		phonePanel.style.display = "none";
	}


	var areaInput = $("dl_areaInput");
	if (areaInput)
		Event.observe(areaInput, "paste", this.handlePaste.bindAsEventListener(this));

	var allInputs = $("digitallanding_searchPanel").select("input");
	for (var i = 0; i < allInputs.length; i++) {
		Event.observe(allInputs[i], "blur", this.blurHandler);
	}

	if (this.couponCodeContainerID && typeof (DigitalCommerce_CouponCode) != 'undefined' && DigitalCommerce_CouponCode) {
		var container = $(this.couponCodeContainerID);
		if (container)
			container.innerHTML = DigitalCommerce_CouponCode;
	}

};

DL_QualWidget.prototype.prePop =
function() {
    var queryPairs = document.location.search.substr(1).split("&");
    var inputQueryVars = new Hash();
    queryPairs.each(function(item) {
        var kvp = item.split("=");
        inputQueryVars.set(kvp[0].toLowerCase(), kvp[1]);
    });
    this.inputQueryVars = inputQueryVars;

    for (var i = 1; i < 6; i++) {
        this.popField("option" + i);
    }

    this.popField("email");
    this.popField("zip", "zipCode");
    this.popField("address");
    this.popField("city");
    this.popField("apt", "apartment");

    var phone = this.inputQueryVars.get("phone");
    if (phone) {
        this.processPaste(null, phone);
    }

    var state = this.inputQueryVars.get("st") || this.inputQueryVars.get("state");
    if (state) {
        var stateDDL = $("dl_stateInput");
        for (var i = 0; i < stateDDL.options.length; i++) {
            if (stateDDL.options[i].value.toLowerCase() == state.toLowerCase())
                stateDDL.selectedIndex = i;
        }
    }
};

DL_QualWidget.prototype.popField =
function(queryKey, fieldID) {
    fieldID = fieldID || queryKey;
    var val = this.inputQueryVars.get(queryKey);
    if (val) {
        var input = $("dl_" + fieldID + "Input");
        if (input)
            input.value = unescape(val);
    }
};

DL_QualWidget.prototype.handlePaste =
function(e) {
    var input = $("dl_areaInput");
    input.value = "";
    input.maxLength = 100;
    this.processPaste.defer();
};

DL_QualWidget.prototype.processPaste =
function(e, phone) {
    var area = $("dl_areaInput");

    phone = phone || area.value;
    var num = phone.replace(/\D/g, "");

    if (num.length >= 3)
        area.value = num.substr(0, 3);
    if (num.length > 3) {
        var prefix = $("dl_prefixInput");
        prefix.value = num.substr(3, 3);
    }
    if (num.length > 6) {
        var suffix = $("dl_suffixInput");
        suffix.value = num.substr(6, 4);
    }

    area.maxLength = 3;
};

DL_QualWidget.prototype.setupHandleKey =
function() {
    var div = $("digitallanding_searchPanel");
    if (div)
        Event.observe(div, "keypress", this.handleKey);
};

DL_QualWidget.prototype.handleKey =
function(e) {
    var keyCode = e.keyCode || e.which;
    if (keyCode == 13) {
        this.SubmitAddress();
    }
};

DL_QualWidget.prototype.setupStandInText =
function() {
    var obj = this;
    this.standInText.each(function(pair) {
        var input = $(pair.key);
        if (input.type != "text") return;
        input.value = pair.value;
        input.className = "landing-qualpanel-input-standin";
        Event.observe(input, "focus", obj.standinFocus);
    });
};

DL_QualWidget.prototype.inputStandinFocus =
function(evt) {
    var input = Event.element(evt);
    Event.stopObserving(input, "focus", this.standinFocus);

    var standinText = this.standInText.get(input.id);
    var text = input.value;
    if (text == standinText) {
        input.className = "";
        input.value = "";
    }
    Event.observe(input, "blur", this.standinBlur);
};

DL_QualWidget.prototype.inputStandinBlur =
function(evt) {
    var input = Event.element(evt);
    Event.stopObserving(input, "blur", this.standinBlur);

    var standinText = this.standInText.get(input.id);
    var text = input.value;
    if (text == "") {
        input.value = standinText;
        input.className = "landing-qualpanel-input-standin";
    }

    Event.observe(input, "focus", this.standinFocus);
};

DL_QualWidget.prototype.BlurHandler =
function(evt) {
    var target = Event.element(evt);
    if (target.type == "text")
        target.value = target.value.strip();
};


DL_QualWidget.prototype.SwapLink = function() {
    var txt = "";
    if (this.AllowModeSwitch) {
        if (this.mode == this.DisplayMode.PHONE)
            txt = this.AddressSwapText;
        else if (this.mode == this.DisplayMode.ADDRESS)
            txt = this.PhoneSwapText;
    }

    if (txt)
        document.write(txt);
};

DL_QualWidget.prototype.OptionLabel =
function(i) {
    if (this["Option" + i + "Required"])
        document.write("<span id=\"dl_Option" + i + "Marker\" class=\"landing-qualpanel-Marker\">*</span>");

    var str = this["Option" + i + "Label"];
    document.write(str + ":");
};

DL_QualWidget.prototype.Label =
function(lbl) {
    document.write(this[lbl + "Label"] + ":");
};

DL_QualWidget.prototype.PhoneOver = function(e) {
    var element = e.srcElement || e.target;
    var chr = e.charCode || e.keyCode;
    if (chr == 9 || chr == 16) return; //ignore tab and shift key
    var len = element.value.length;
    switch (element.id) {
        case "dl_areaInput":
            if (len == 3) {
                this.selectInput("dl_prefixInput");
            }
            break;
        case "dl_prefixInput":
            if (len == 3) { this.selectInput("dl_suffixInput"); }
            break;
        case "dl_suffixInput":
            if (len == 4 && this.PhoneSuffixTab) {
                if (this.mode == this.DisplayMode.ADDRESSANDPHONE) {
                    var addrPanel = $("dl_addressPanel");
                    if (addrPanel && addrPanel.getStyle("display") != "none")
                        this.selectInput("dl_addressInput");
                }
                else {
                    var emailPanel = $("dl_emailPanel");
                    if (emailPanel && emailPanel.getStyle("display") != "none")
                        this.selectInput("dl_emailInput");
                }
            }
            break;
    }
};

DL_QualWidget.prototype.selectInput = function(inputID) {
    var input = $(inputID);
    input.focus();
    if (input.select && input.type != "button")
        input.select();
};

DL_QualWidget.prototype.SwapPanels = function() {
    if ((this.mode & this.DisplayMode.PHONE) == this.DisplayMode.PHONE) {
        this.mode = this.DisplayMode.ADDRESS;
        $("dl_addressPanel").style.display = "block";
        $("dl_phonePanel").style.display = "none";
        $("dl_swapLink").innerHTML = this.PhoneSwapText;
    }
    else if ((this.mode & this.DisplayMode.ADDRESS) == this.DisplayMode.ADDRESS) {
        this.mode = this.DisplayMode.PHONE;
        $("dl_addressPanel").style.display = "none";
        $("dl_phonePanel").style.display = "block";
        $("dl_swapLink").innerHTML = this.AddressSwapText;
    }

    var dynamicDivs = $$('div.qualPanel');
    if (dynamicDivs) {
        var qualPanel = $('landing-content-qual');
        var h = qualPanel.getHeight() + "px";
        dynamicDivs.each(function(d) { d.style.height = h; });
    }
};

DL_QualWidget.prototype.DisplayMode =
{
    ADDRESS: 1,
    PHONE: 2,
    ADDRESSANDPHONE: 3
};

DL_QualWidget.prototype.SubmitAddress = function() {
	if (this.IsValid()) {
		var queryVars = new Hash();
		var phonePanel = $("dl_phonePanel");
		if (phonePanel.getStyle("display") != "none") {
			var areacode = $F("dl_areaInput");
			var prefix = $F("dl_prefixInput");
			var suffix = $F("dl_suffixInput");
			if (areacode != this.standInText.get("dl_areaInput") && prefix != this.standInText.get("dl_prefixInput") && suffix != this.standInText.get("dl_suffixInput")) {
				var phone = areacode + prefix + suffix;
				if (phone)
					queryVars.set("phone", phone);
			}
		}

		var addrPanel = $("dl_addressPanel");
		if (addrPanel.getStyle("display") != "none") {
			var addr = $F("dl_addressInput");
			if (addr && addr != this.standInText.get("dl_addressInput"))
				queryVars.set("address", addr);

			var aptFld = $("dl_apartmentInput");
			var apt = aptFld ? aptFld.value : null;
			if (apt && apt != this.standInText.get("dl_apartmentInput")) queryVars.set("apt", apt);
			var cityFld = $("dl_cityInput");
			var city = cityFld ? cityFld.value : null;
			if (city && cityFld != this.standInText.get("dl_cityInput")) queryVars.set("city", city);
			var stateDDL = $("dl_stateInput");
			if (stateDDL) {
				var state = stateDDL ? stateDDL.options[stateDDL.selectedIndex].value : null;
				if (state) queryVars.set("state", state);
			}

			var zipFld = $("dl_zipCodeInput");
			var zip = zipFld ? zipFld.value : null;
			if (zip && zip != this.standInText.get("dl_zipCodeInput")) queryVars.set("zip", zip);
		}

		var emailFld = $("dl_emailInput");
		var email = emailFld ? emailFld.value : null;
		if (email && email != this.standInText.get("dl_emailInput")) {
			if (email) queryVars.set("email", email);
		}

		if (typeof (DigitalCommerce_SID) != 'undefined')
			queryVars.set("SID", DigitalCommerce_SID);

		this.GetExtraQueryVars(queryVars);

		for (var i = 1; i < 6; i++) {
			var pnl = $("dl_option" + i + "Panel");
			if (pnl && (pnl.getStyle("display") != "none")) {
				var fld = $("dl_option" + i + "Input");
				if (fld.value != "" && fld.value != this.standInText.get("dl_option" + i + "Input"))
					queryVars.set("option" + i, fld.value);
			}
		}

		GetCampaignCustomizations(queryVars);

		var querystring = queryVars.toQueryString();

		var u = this.url + "/dispatch.aspx?" + querystring;

		if (typeof (AnalyticsManager) != 'undefined')
			u = AnalyticsManager.Instance().GetLinkerUrl(u);

		//determine if is Internet Explorer
		var isIE = false;

		try {
			isIE = (navigator.userAgent.toLowerCase().indexOf('msie') > -1);
		} catch (err) { }

		//re-define for IE
		if (isIE) {
			var referLink = document.createElement('a');
			referLink.href = u;
			document.body.appendChild(referLink);
			referLink.click();
		}
		else
			window.location.href = u;

		if (window.event)
			window.event.returnValue = false;
	}
};

DL_QualWidget.prototype.GetExtraQueryVars = function(vars) {
    var extras = ["option1", "option2", "option3", "option4", "option5", "PromoID", "featuredcategory"];
    for (var i = 0; i < extras.length; i++) {
        if (this[extras[i]])
            vars.set(extras[i].toLowerCase(), this[extras[i]]);
    }
};

function GetCampaignCustomizations(vars) {
    var keys = [
	    "promoid", "originatorid", "source", "campaign", "affiliateid",
	    "option1", "option2", "option3", "option4", "option5", "option6",
	    "featuredcategory", "exsvc", "sourceplatformid", "newcustomer", "language"];
    var ccs = [];
    var campaign = $H(CampaignInfo);
    for (var i = 0; i < keys.length; i++) {
        var val = campaign.get(keys[i]);
        if (val) vars.set(keys[i], val);
    }

    var queryString = location.search;
    var queryVars = queryString.toQueryParams();
    if (queryVars.newcustomer) {
        vars.set("newcustomer", queryVars.newcustomer);
    }
}

DL_QualWidget.prototype.IsValid = function() {
    var valid = true;
    var phoneShowing = ((this.mode & this.DisplayMode.PHONE) == this.DisplayMode.PHONE);
    var phoneValid = true;
    var addressShowing = ((this.mode & this.DisplayMode.ADDRESS) == this.DisplayMode.ADDRESS);
    var addressValid = true;
    var phone = $("dl_areaInput").value + $("dl_prefixInput").value + $("dl_suffixInput").value;

    if (phoneShowing) {
        if (!IsPhoneValid(phone, this.PhoneRequired)) {
            $("dl_phoneMarker").style.display = "";
            phoneValid = false;
            alert(this.InvalidPhoneNumberError);
            $("dl_areaInput").focus();
            return false;
        }
    }

    if (addressShowing) {
        addressValid &= this.ValidateAddressField("dl_address", IsAddressValid, this.AddressRequired, this.InvalidAddressError);
        if (!addressValid) {
            $("dl_addressInput").focus();
            return false;
        }
        addressValid &= this.ValidateAddressField("dl_zipCode", IsZipValid, this.AddressRequired, this.InvalidZipError);
        if (!addressValid) {
            $("dl_zipCodeInput").focus();
            return false;
        }


        addressValid &= this.ValidateAddressField("dl_apartment", this.IsApartmentValid.bind(this), false, this.InvalidApartmentError, "dl_apt");
        addressValid &= this.ValidateAddressField("dl_city", IsCityValid, false, this.InvalidCityError);

        var stateDDL = $("dl_stateInput");
        if (stateDDL) {
            if (!IsStateValid($F(stateDDL), false)) {
                $("dl_stateMarker").style.display = "";
                addressValid = false;
                alert(this.InvalidStateError);
            }
            else {
                $("dl_stateMarker").style.display = "none";
            }
        }
    }

    valid = phoneValid && addressValid;

    $("dl_emailInput").value = $("dl_emailInput").value.strip();
    var email = $("dl_emailInput").value;
    if (!this.IsEmailValid(email, this.EmailRequired)) {
        alert(this.InvalidEmailError);
        valid = false;
    }

    //validate optional fields
    for (var i = 1; i < 6; i++) {
        var pnl = $("dl_option" + i + "Panel");
        if (pnl && (pnl.getStyle("display") != "none")) {
            if (this["Option" + i + "Required"]) {
                var fld = $("dl_option" + i + "Input");
                if (fld.value == "") {
                    alert(this["Option" + i + "ValidationMessage"]);
                    fld.focus();
                    valid = false;
                }
            }
        }
    }

    return valid;
};

DL_QualWidget.prototype.ValidateAddressField = function(fldID, validationFunction, required, errMsg, markerID) {
    var valid = true;
    markerID = markerID || fldID;
    var fld = $(fldID + "Input");
    if (!fld) {
        valid = !required;
    }
    else {
        fld.value = fld.value.strip();

        if (!validationFunction(fld.value, required)) {
            $(markerID + "Marker").style.display = "inline";
            valid = false;
            alert(errMsg);
        }
        else if (required && fld.value == this.standInText.get(fld.id)) {
            $(markerID + "Marker").style.display = "inline";
            valid = false;
            alert(errMsg);
        }
        else {
            $(markerID + "Marker").style.display = "none";
        }
    }

    return valid;
};

function IsPhoneValid(phone, required) {
    if (phone.length == 0)
        return !required;

    var phoneRegex = /^[2-9][0-8][0-9][2-9][0-9]{6}$/;
    return phoneRegex.test(phone);
}

DL_QualWidget.prototype.IsApartmentValid = function(apt, required) {
    var aptStandInText = this.standInText.get("dl_apartmentInput");
    var exp = /^[A-Za-z0-9][\s\-A-Za-z0-9]*$/;

    if (required) {
        if (!apt || apt == aptStandInText || !exp.test(apt))
            return false;
    }
    else {
        if (apt && apt.length > 0 && apt != aptStandInText && !exp.test(apt))
            return false;
    }

    return true;
};

function IsZipValid(zip, required) {
    if (zip.length == 0)
        return !required;

    var zipRegex = /^\d{5}$/;
    return zipRegex.test(zip);
}

function IsAddressValid(addr, required) {
    if (addr.length == 0)
        return !required;

    return true;
}

function IsCityValid(city, required) {
    if (city.length == 0)
        return !required;

    var cityRegex = /^[A-Za-z ]*$/;
    return cityRegex.test(city);
}

function IsStateValid(state, required) {
    if (state.length == 0)
        return !required;

    return true;
}

DL_QualWidget.prototype.IsEmailValid =
function(email, required) {
    //if(email.length == 0 && !required)
    //	return true;

    var emailStandInText = this.standInText.get("dl_emailInput");

    if (required) {
        if (email.length > 0 && email == emailStandInText)
            return false;
    }
    else {
        if (email && email.length > 0 && email != emailStandInText && !emailRegex.test(email))
            return false;
    }


    return true;
};

var emailRegex = /^[a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/;

var DigitalLanding = new DL_QualWidget();

function VerisignSeal() {
    var host = document.location.host;
    document.write("<script src=\"https://seal.verisign.com/getseal?host_name=" + host + "&#x26;size=M&#x26;use_flash=NO&#x26;use_transparent=NO&#x26;lang=en\"></sc" + "ript>");
   }
   
//////////////////////////////////////
/// isMobile
/// returns whether the current request is coming from a (selected) mobile device
//////////////////////////////////////
function isMobile() {
	var mobileStrings = ["android", ["mobile", "safari"], "blackberry", "windows phone", "iemobile"];
	var ua = navigator.userAgent.toLowerCase();
	for (var i = 0; i < mobileStrings.length; i++) {
		var str = mobileStrings[i];
		if (typeof (str) == "string" && ua.indexOf(str) > -1)
			return true;
		else if(typeof(str) == "array") {
			var match = true;
			for(var j=0; j<str.length; j++){
				if(ua.indexOf(str[j]) == -1) {
					match = false;
					break;
				}
			}
			if(match) return true;
		}
	}
	
	return false;
}

/////////////////////////
/// detects whether the current request is coming from one of our selected mobile devices,
/// if so, replace the current location with the global DigitalCommerce_MobileRedirectURL
/////////////////////////
function detectMobile() {
	var url, redirecting = false;
	url = (typeof (DigitalCommerce_MobileRedirectURL) != 'undefined') ? DigitalCommerce_MobileRedirectURL : null;
	if (url && isMobile()) {
		redirecting = true;
		location.replace(url);
	}

	return redirecting;
}

//if using the widget, the widget will do this for you
//Event.observe(window, "load", detectMobile);

//use when we get rid of prototype here
/*
if (window.attachEvent)
	window.attachEvent("onload", detectMobile);
else if (window.addEventListener)
	window.addEventListener("load", detectMobile, false);
*/
