$(document).ready(
	function() {
	    if (window.location.toString().indexOf("?tab=1") != -1) {
	        $('#mdcContactInfoTab').removeClass('mdcConTabSelected');
	        $('#mdcGOLTab').addClass('mdcConTabSelected');
	        $('#mdcContactInfo').addClass('mdcHide');
	        $('#mdcGOL').removeClass('mdcHide');
	    }

	    $('#mdcContactTab .mdcConTab').hover(
			function() { if ($(this).hasClass('mdcConTabSelected')) return; $(this).toggleClass('mdcConHover'); },
			function() { if ($(this).hasClass('mdcConTabSelected')) return; $(this).toggleClass('mdcConHover'); }
		);
	    $('#mdcContactTab .mdcConTab').click(function() {
	        $(this).siblings().removeClass('mdcConTabSelected'); $(this).removeClass('mdcConHover'); $(this).addClass('mdcConTabSelected');
	        var sId = $(this).attr('id');
	        var sDesId = sId.substring(0, sId.length - 3);
	        $('#' + sDesId).siblings().css('display', 'none');
	        $('#' + sDesId).css('display', 'block');

	        var tabName = document.getElementById(sId).innerHTML;
	        var virUrl = "ContactUs/" + tabName.replace(/\s/g, "");
	        TrackTab(virUrl);
	    });
	    $('.mdcWebTrendsDcs').click(function() {
	        var titleValue = $(this).attr('title');
	        if (titleValue != null) {
	            TrackTab(titleValue);
	        }
	    });

	    var hasProductInstall = DetectFlashVer(6, 0, 65);
	    if (!hasProductInstall) {
	        $("#mdcFlashInstallTipDiv").css("display", "block");
	        $("#golswfIframe").css("display", "none");

	    }
	    setContactPopupPositions();
	    var sendmessagebutton = document.getElementById("sendmessage");
	    if (sendmessagebutton != null) {
	        sendmessagebutton.onclick = function() { Web2CasePopUp(); }
	        if (getQuerystring('op') == 'alert') {
	            OpenWeb2CasePopupForAlert();
	        }
	        InitializeInputboxes();
	    }

	    RestoreInputValues();

	}
);

function TrackTab(virtualUrl) {
    dcsMultiTrack('DCS.dcsuri', virtualUrl, 'WT.ti', '');
}

jQuery.fn.center = function() {
    this.css("position", "absolute");
    this.css("top", ($(window).height() - this.outerHeight()) / 2 + $(window).scrollTop() + "px");
    this.css("left", ($(window).width() - this.outerWidth()) / 2 + $(window).scrollLeft() + "px");
    return this;
}

function setContactPopupPositions() {
    $('#mdcBorderOutside').center();
    $('#mdcBorderInside').center();
    $('#mdcBorderOutsideThankYou').center();
    $('#mdcBorderInsideThankYou').center();

    var opCode = getQuerystring('op');
    if (opCode == 'done') {
        $('#mdcBorderOutsideThankYou').removeClass('mdcHide');
        $('#mdcBorderInsideThankYou').removeClass('mdcHide');
        $('#mdcContactUsThankYouControl').removeClass('mdcHide');
    }
}

function Web2CasePopUp() {
    $('#mdcContactFormPopupControl').toggleClass('mdcHide');
    $('#mdcBorderInside').toggleClass('mdcHide');
    $('#mdcBorderOutside').toggleClass('mdcHide');
    var captchaImage = $(".captchaImage");
    if (!$('#mdcContactFormPopupControl').hasClass('mdcHide') && captchaImage.length > 0 && captchaImage.width() < 50) {
        $("#btnTryNewWords").click();
    }    
}

function CloseWeb2CaseDonePopup() {
    //$('#mdcBorderOutsideThankYou').addClass("mdcHide");
    //$('#mdcBorderInsideThankYou').addClass("mdcHide");
    //$('#mdcContactUsThankYouControl').addClass("mdcHide");
    window.location.href = window.location.href.replace("?op=done", "").replace("&op=done", "");
}

function OpenWeb2CasePopupForAlert() {
    setInquiryTypeAsSales();
    $('#sendmessage').click();
}

function validateInput() {
    var firstName = document.getElementById('firstName');
    var lastName = document.getElementById('lastName');
    var company = document.getElementById('company');
    var phone = document.getElementById('phone');
    var email = document.getElementById('email');
    var country = document.getElementById('country');
    var inquiryType1 = $("#mdcRightPanelBottom .selectEnvInquiryType")[0];

    //Hide error message
    var formError = document.getElementById('formError');
    if (formError != null) {
        formError.innerHTML = '';
        $('#mdcErrorBlurb').addClass('mdcHide');
    }

    //compute name
    var nameCtl = document.getElementById('name');
    if (nameCtl != null)
    { nameCtl.value = getFullName(document.getElementById('firstName').value, document.getElementById('lastName').value); }

    //compute region
    var regionVal = getRegion(document.getElementById('country').value);
    $("#mdcContactFormPopupControl .txtEnvRegion").val(regionVal);

    //compute subject
    var subjectCtl = document.getElementById('subject');
    if (subjectCtl != null)
    { subjectCtl.value = $(inquiryType1).val(); }

    var nameError = document.getElementById('nameError');
    var companyError = document.getElementById('companyError');
    var phoneError = document.getElementById('phoneError');
    var emailError = document.getElementById('emailError');
    var countryError = document.getElementById('countryError');
    var InquiryTypeError = document.getElementById('InquiryTypeError');

    nameError.innerHTML = '';
    companyError.innerHTML = '';
    phoneError.innerHTML = '';
    emailError.innerHTML = '';
    countryError.innerHTML = '';
    InquiryTypeError.innerHTML = '';


    if (firstName != null && lastName != null && nameError != null) {
        if ((trim(firstName.value) + trim(lastName.value) == '') ||
			(trim(firstName.value) + trim(lastName.value) == 'First NameLast Name')) {
            nameError.innerHTML = 'Name is required';
        }
    }

    if (!checkBlank(company, companyError)) {
        companyError.innerHTML = 'Company is required';
    }

    if (!checkBlank(phone, phoneError)) {
        phoneError.innerHTML = 'Phone is required';
    }
    else {
        var phoneNo = phone.value;

        //Reject if non-number characters occur consecutively 
        var charRegex = /\D{2,}/;
        if (charRegex.test(phoneNo)) {
            phoneError.innerHTML = 'Please provide a valid phone number';
        }
        else {
            //Strip allowable non-number characters
            phoneNo = phoneNo.replace(/\+/g, '');
            phoneNo = phoneNo.replace(/\(/g, '');
            phoneNo = phoneNo.replace(/\)/g, '');
            phoneNo = phoneNo.replace(/ /g, '');
            phoneNo = phoneNo.replace(/\./g, '');
            phoneNo = phoneNo.replace(/-/g, '');
            phoneNo = phoneNo.replace(/x/gi, ''); //ext

            var numberRegex = /^-{0,1}\d*\.{0,1}\d+$/;

            if (!numberRegex.test(phoneNo)) {
                phoneError.innerHTML = 'Please provide a valid phone number';
            }
        }

    }

    if (!checkBlank(email, emailError)) {
        emailError.innerHTML = 'Email is required';
    }
    else {
        var atChar = email.value.indexOf("@");
        var dotChar = email.value.lastIndexOf(".");
        if ((atChar < 1) || (dotChar - atChar < 2) || (dotChar == (email.value.length - 1))) {
            emailError.innerHTML = 'Please provide a valid email address';
        }
    }

    if (!checkBlank(country, countryError)) {
        countryError.innerHTML = 'Country is required';
    }

    if (!checkBlank(inquiryType1, InquiryTypeError)) {
        InquiryTypeError.innerHTML = 'Inquiry type is required';
    }

    var checkValue = nameError.innerHTML + companyError.innerHTML + phoneError.innerHTML;
    checkValue += emailError.innerHTML + countryError.innerHTML + InquiryTypeError.innerHTML;


    if (checkValue.length != 0) {
        if (formError != null) {
            formError.innerHTML = 'Several errors occurred. Please review the form and try again';
            $('#mdcErrorBlurb').removeClass('mdcHide');
        }
        return false;
    }
    return true;
}

function trim(str) {
    return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

function checkBlank(textField, errorField) {
    if (textField != null && errorField != null) {
        if (trim(textField.value) == '' || textField.value == 0) {
            return false;
        }
    }

    return true;
}

function getQuerystring(key, default_) {
    if (default_ == null) default_ = "";
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
    var qs = regex.exec(window.location.href);
    if (qs == null)
        return default_;
    else
        return qs[1];
}

function setInquiryTypeAsSales() {
    var aSelector = $('#mdcRightPanelBottom .selectEnvInquiryType').get(0);
    if (null != aSelector) {
        for (var i = 0; i < aSelector.options.length; i++) {
            if (aSelector.options[i].text == "Sales") {
                aSelector.options[i].selected = true;
                break;
            }
        }
    }
}

function getFullName(firstName, lastName) {
    if (firstName == null) firstName = '';
    if (lastName == null) lastName = '';

    return firstName + ' ' + lastName;
}

function getRegion(country) {
    country = country.toLowerCase();
    var region = '';
    switch (country) {
        case "american samoa":
        case "anguilla":
        case "antigua and barbuda":
        case "argentina":
        case "aruba":
        case "bahamas":
        case "barbados":
        case "belize":
        case "bermuda":
        case "bolivia":
        case "brazil":
        case "canada":
        case "cayman islands":
        case "chile":
        case "colombia":
        case "costa rica":
        case "cuba":
        case "dominica":
        case "dominican republic":
        case "ecuador":
        case "el salvador":
        case "grenada":
        case "guatemala":
        case "guyana":
        case "haiti":
        case "honduras":
        case "jamaica":
        case "mexico":
        case "netherlands antilles":
        case "nicaragua":
        case "panama":
        case "paraguay":
        case "peru":
        case "puerto rico":
        case "saint kitts and nevis":
        case "saint lucia":
        case "suriname":
        case "trinidad and tobago":
        case "turks and caicos islands":
        case "united states":
        case "uruguay":
        case "venezuela":
        case "northern marianas":
        case "saint vincent and the grenadines":
        case "united states minor outlying islands":
            region = "AMERICAS";
            break;
        case "australia":
        case "bangladesh":
        case "bhutan":
        case "cambodia":
        case "china":
        case "christmas island":
        case "cocos (keeling) islands":
        case "cook islands":
        case "east timor":
        case "fiji":
        case "guam":
        case "hong kong":
        case "india":
        case "indonesia":
        case "kiribati":
        case "macau":
        case "malaysia":
        case "maldives":
        case "marshall islands":
        case "mongolia":
        case "nauru":
        case "nepal":
        case "new zealand":
        case "niue":
        case "norfolk island":
        case "palau":
        case "philippines":
        case "papua new guinea":
        case "samoa":
        case "singapore":
        case "solomon islands":
        case "sri lanka":
        case "taiwan":
        case "thailand":
        case "tokelau":
        case "tonga":
        case "tuvalu":
        case "vanuatu":
            region = "ASIA";
            break;
        case "faeroe islands":
        case "falkland islands":
        case "libya":
        case "macedonia":
        case "moldova":
        case "reunion ('e' inflected)":
        case "russia":
        case "sao tome and principe (multiple inflections)":
        case "south georgia and south sandwich islands":
        case "tanzania":
        case "vatican city":
        case "wallis and futuna ":
        case "afghanistan":
        case "albania":
        case "algeria":
        case "andorra":
        case "angola":
        case "antarctica":
        case "armenia":
        case "austria":
        case "azerbaijan":
        case "bahrain":
        case "belarus":
        case "belgium":
        case "benin":
        case "bosnia and herzegovina":
        case "botswana":
        case "bouvet island":
        case "british indian ocean territory":
        case "bulgaria":
        case "burkina faso":
        case "burundi":
        case "cameroon":
        case "cape verde":
        case "central african republic":
        case "chad":
        case "channel islands":
        case "comoros":
        case "congo":
        case "cote d'ivoire":
        case "croatia":
        case "cyprus":
        case "czech republic":
        case "denmark":
        case "djibouti":
        case "egypt":
        case "equatorial guinea":
        case "eritrea":
        case "estonia":
        case "ethiopia":
        case "finland":
        case "france":
        case "french guiana":
        case "french polynesia":
        case "french southern territories":
        case "gabon":
        case "gambia":
        case "georgia":
        case "germany":
        case "ghana":
        case "gibraltar":
        case "greece":
        case "greenland":
        case "guadeloupe":
        case "guernsey":
        case "guinea":
        case "guinea-bissau":
        case "hungary":
        case "iceland":
        case "iraq":
        case "ireland":
        case "israel":
        case "italy":
        case "jersey":
        case "jordan":
        case "kazakhstan":
        case "kenya":
        case "kuwait":
        case "kyrgyzstan":
        case "latvia":
        case "lebanon":
        case "lesotho":
        case "liberia":
        case "liechtenstein":
        case "lithuania":
        case "luxembourg":
        case "madagascar":
        case "malawi":
        case "mali":
        case "malta":
        case "martinique":
        case "mauritania":
        case "mauritius":
        case "mayotte":
        case "monaco":
        case "montenegro":
        case "montserrat":
        case "morocco":
        case "mozambique":
        case "namibia":
        case "netherlands":
        case "new caledonia":
        case "niger":
        case "nigeria":
        case "norway":
        case "oman":
        case "pakistan":
        case "poland":
        case "portugal":
        case "qatar":
        case "romania":
        case "rwanda":
        case "saint helena":
        case "saint pierre and miquelon":
        case "san marino":
        case "saudi arabia":
        case "senegal":
        case "serbia":
        case "seychelles":
        case "sierra leone":
        case "slovakia":
        case "slovenia":
        case "somalia":
        case "south africa":
        case "spain":
        case "svalbard and jan mayen":
        case "swaziland":
        case "sweden":
        case "switzerland":
        case "tajikistan":
        case "togo":
        case "tunisia":
        case "turkey":
        case "turkmenistan":
        case "uganda":
        case "ukraine":
        case "united arab emirates":
        case "united kingdom":
        case "uzbekistan":
        case "western sahara":
        case "yemen":
        case "yugoslavia":
        case "zambia":
        case "zimbabwe":
            region = "EMEA";
            break;
        case "japan":
            region = "JAPAN";
            break;
        default:
            region = "AMERICAS";
    }
    return region;
}

function InitializeInputboxes() {
    var firstName = document.getElementById('firstName');
    var lastName = document.getElementById('lastName');
    var country = document.getElementById('country');
    var inquiryType1 = $("#mdcRightPanelBottom .selectEnvInquiryType")[0];

    if (firstName.value == 'First Name') {
        firstName.style.color = '#999999';
    }
    else {
        firstName.style.color = 'black';
    }

    if (lastName.value == 'Last Name') {
        lastName.style.color = '#999999';
        //lastName.select();
    }
    else {
        lastName.style.color = 'black';
    }
    InitializeSelectBox(country);
    InitializeSelectBox(inquiryType1);
}

function InitializeSelectBox(inputField) {
    var aColor = 'black';
    if (inputField == null) {
        return;
    }
    if (inputField.selectedIndex == 0) {
        aColor = '#999999';
    }
    else {
        aColor = 'black';
    }
    inputField.style.color = aColor;
    inputField.options[0].style.color = aColor;
}

function ChangeDefaultStyles(textFieldId) {
    var textField = document.getElementById(textFieldId);

    if ((textFieldId == "firstName" && textField.value == 'First Name') ||
        (textFieldId == "lastName" && textField.value == 'Last Name')) {
        textField.value = '';
    }
    textField.style.color = 'black';
}

function TryNewLink(captchURL) {
    $.ajax({ url: captchURL, cache: false, success: function(data) {
        var responseData = data;
        var captchaText = String(responseData);
        ($(".captchaImage")[0]).src = captchURL + '?CaptchaText=' + captchaText;
        $(".hiddenCaptchaDiv")[0].children[0].value = captchaText;
    }
    });
}

function FetchInputValues() {
    var aDivStr = '{|}';
    var aInputValues = $("#name").val() + aDivStr
        + $("#company").val() + aDivStr
        + $("#phone").val() + aDivStr
        + $("#email").val() + aDivStr
        + $("#country").val() + aDivStr
        + $("#mdcRightPanelBottom .mdcField select").val() + aDivStr
        + $("#description").val() + aDivStr
        + $("#mdcContactFormPopupControl .txtEnvRegion").val() + aDivStr;
    $("#mdcRightPanelBottom .txtInputValues").val(aInputValues);
}

function RestoreInputValues() {
    var aDivStr = '{|}';
    var aInputValues = $("#mdcRightPanelBottom .txtInputValues").val();
    var aInputArray = aInputValues.split(aDivStr);

    if (aInputArray.length >= 8) {
        $("#name").val(aInputArray[0]);
        $("#company").val(aInputArray[1]);
        $("#phone").val(aInputArray[2]);
        $("#email").val(aInputArray[3]);
        $("#country").val(aInputArray[4]);
        $("#mdcRightPanelBottom .mdcField select").val(aInputArray[5]);
        $("#description").val(aInputArray[6]);

        $('#mdcContactFormPopupControl').removeClass('mdcHide');
        $('#mdcBorderInside').removeClass('mdcHide');
        $('#mdcBorderOutside').removeClass('mdcHide');
    }
}

