﻿var d = new Date();
$("[data-date-format='DD/MM/YYYY']").attr("class", "custom_text_box");
//$("[data-date-format='DD/MM/YYYY']").attr("class", "custom_text_box");
$('[aria-describedby="sony_dateofpurchase_description"]').next().remove();
$('[aria-describedby="sony_dateofpurchase_description"]').attr("style", "width:690px")
$('[aria-describedby="sony_dateofpurchase_description"]').datepicker({
    maxDate: new Date(d.setDate(d.getDate() - 1)),
    dateFormat: "dd/mm/yy"
});

$.blockUI({
    fadeIn: 1000,
    css: {
        border: 'none',
        padding: '15px',
        backgroundColor: '#000',
        '-webkit-border-radius': '10px',
        '-moz-border-radius': '10px',
        opacity: .5,
        color: '#fff'
    },
    message: 'Please wait...',
    //onBlock: function () {

    //    window.onload();
    //    $.unblockUI();
    //}
});

var bShowJobNo = true;
//$(document).ready(function () {

    $(".actions").attr("style", "border-top : 0px solid #e5e5e5");

    //Set Locale for the Page
    var contactUsLocale = $("#countrylocale").val();
    $("#sony_locale").val(contactUsLocale);   
    // Data label localization country wise
    {
        var ClearButton = "Clear";
        var SubmitButton = "Submit";
        var ModelText = '<div class="helper_text"><a href="https://www.google.com.sg/maps" target="_blank" style="padding-right: 15px;">How to find your model?&nbsp;<img src="/question_mark.png" alt="How to find model name?"></a></div>';
        var completeAllFields = "Please complete all these fields";
        var GeneralInfo = "General Information";
        var attachWarning = "File size should not exceed 2 MB. Only these file types are accepted: PDF, GIF, JPG, JPEG, DOC, DOCX";
        var MainEnquiryHead = "Your Enquiry";
        var TermsConditions = "Before you click submit, please kindly read the <a href='https://www.sony.com.sg/section/privacypolicy' target='_blank'>Privacy Policy</a>.";
        var SubscribeText = "Keep me updated on service related details and events for my product";
        var SuggestAnAnswerHelper = '<div id="idsupportcontent" class="col-sm-12 helper_text" style="padding-right: 18px; padding-bottom: 5px;"><a href="https://translate.google.com/" target="_blank">Quick search on our<br>support content?&nbsp;<img src="/question_mark.png" alt="search on support"></a></div>';
        var ContinueToSubmit = "Continue to Submit";
        var SuggestAnAnswer = "Suggest me An Answer";
        var SearchPageHeader = "Suggested Answers";
        var PleaseSelect = "Please Select";
        var CharacterCountHelper = "characters remaining";
        //var ContactIsRequired = "Contact is a required field.";
        var NoSuggestionFound = "No Suggestions Found";
        var SuggestAnAnswerMandatoryFields = "Model and Description cannot be empty";
        var SuggestionCloseButton = "Close";

        var objState = [];
        $("[data-date-format='DD/MM/YYYY']").attr("class", "custom_text_box");
        // Fetch the locale based on URL
        var localeFromURL = (window.location.href).split('/')[3];

        //var d = new Date();
        var fetchState = false;
        switch (contactUsLocale.toLowerCase()) {
            case "en_sg":
                contactUsLocale = "en_SG";
                //$('[aria-describedby="sony_dateofpurchase_description"]').datepicker({
                //    maxDate: new Date(d.setDate(d.getDate() - 1)),
                //    dateFormat: "dd/mm/yy"
                //});
                ModelText = "";
                SuggestAnAnswerHelper = "";
                TermsConditions = "Before you click submit, please kindly read the <a href='https://www.sony.com.sg/section/privacypolicy' target='_blank'>Privacy Policy</a>.";
                $("#description").attr("placeholder","Please DO NOT include confidential information such as NRIC no.");
                break;
            case "en_ph":
                contactUsLocale = "en_PH";
                ClearButton = "Clear";
                SubmitButton = "Submit";
                ModelText = "";
                SuggestAnAnswerHelper = "";
                ContinueToSubmit = "Continue to Submit";
                SuggestAnAnswer = "Suggest me An Answer";
                SearchPageHeader = "Suggested Answers";
                PleaseSelect = "Please Select";
                NoSuggestionFound = "No Suggestions Found";
                CharacterCountHelper = "characters remaining";
                //ContactIsRequired = "Contact is a required field.";
                completeAllFields = "Please complete all these fields";
                SuggestAnAnswerMandatoryFields = "Model and Description cannot be empty";
                SuggestionCloseButton = "Close";
                GeneralInfo = "General Information";
                attachWarning = "File size should not exceed 2 MB. Only these file types are accepted: PDF, GIF, JPG, JPEG, DOC, DOCX";
                MainEnquiryHead = "Your Enquiry";
                TermsConditions = "Before you click submit, please kindly read the <a href='https://www.sony.com.ph/section/privacypolicy' target='_blank'>Privacy Policy</a>.";
                //$('[aria-describedby="sony_dateofpurchase_description"]').datepicker({
                //    maxDate: new Date(d.setDate(d.getDate() - 1)),
                //    dateFormat: "dd/mm/yy"
                //});
                break;
            case "en_my":
                ClearButton = "Clear";
                SubmitButton = "Submit";
                ModelText = "";
                SuggestAnAnswerHelper = "";
                ContinueToSubmit = "Continue to Submit";
                SuggestAnAnswer = "Suggest me An Answer";
                SearchPageHeader = "Suggested Answers";
                PleaseSelect = "Please Select";
                NoSuggestionFound = "No Suggestions Found";
                CharacterCountHelper = "characters remaining";
                //ContactIsRequired = "Contact is a required field.";
                completeAllFields = "Please complete all these fields";
                SuggestAnAnswerMandatoryFields = "Model and Description cannot be empty";
                SuggestionCloseButton = "Close";
                GeneralInfo = "General Information";
                attachWarning = "File size should not exceed 2 MB. Only these file types are accepted: PDF, GIF, JPG, JPEG, DOC, DOCX";
                MainEnquiryHead = "Your Enquiry";
                TermsConditions = "By ticking the box, you hereby indicate and acknowledge that you have read and understood our Personal Data Protection Notice at <a href='https://www.sony.com.my/section/privacypolicy'>Privacy Policy</a> and hereby consent to us processing your personal data in the manner and for the purposes described in our Personal Data Protection Notice. Do not tick the box if you do not agree to or otherwise have any objections.";
                //$('[aria-describedby="sony_dateofpurchase_description"]').datepicker({
                //    maxDate: new Date(d.setDate(d.getDate() - 1)),
                //    dateFormat: "dd/mm/yy"
                //});
                fetchState = true;
                break;
            case "en_in":
                ClearButton = "Clear";
                SubmitButton = "Submit";
                ModelText = "";
                SuggestAnAnswerHelper = "";
                ContinueToSubmit = "Continue to Submit";
                SuggestAnAnswer = "Suggest me An Answer";
                SearchPageHeader = "Suggested Answers";
                PleaseSelect = "Please Select";
                NoSuggestionFound = "No Suggestions Found";
                CharacterCountHelper = "characters remaining";
                //ContactIsRequired = "Contact is a required field.";
                completeAllFields = "Please complete all these fields";
                SuggestAnAnswerMandatoryFields = "Model and Description cannot be empty";
                SuggestionCloseButton = "Close";
                GeneralInfo = "General Information";
                attachWarning = "File size should not exceed 2 MB. Only these file types are accepted: PDF, GIF, JPG, JPEG, DOC, DOCX";
                MainEnquiryHead = "Your Enquiry";
                TermsConditions = "Before you click submit, please kindly read the <a href='https://www.sony.co.in/section/privacypolicy' target='_blank'>Privacy Policy</a>.";
                //$('[aria-describedby="sony_dateofpurchase_description"]').datepicker({
                //    maxDate: new Date(d.setDate(d.getDate() - 1)),
                //    dateFormat: "dd/mm/yy"
                //});
                fetchState = true;
                break;
            case "en_id":
                ClearButton = "Clear";
                SubmitButton = "Submit";
                ModelText = "";
                SuggestAnAnswerHelper = "";
                ContinueToSubmit = "Continue to Submit";
                SuggestAnAnswer = "Suggest me An Answer";
                SearchPageHeader = "Suggested Answers";
                PleaseSelect = "Please Select";
                NoSuggestionFound = "No Suggestions Found";
                CharacterCountHelper = "characters remaining";
                //ContactIsRequired = "Contact is a required field.";
                completeAllFields = "Please complete all these fields";
                SuggestAnAnswerMandatoryFields = "Model and Description cannot be empty";
                SuggestionCloseButton = "Close";
                GeneralInfo = "General Information";
                attachWarning = "File size should not exceed 2 MB. Only these file types are accepted: PDF, GIF, JPG, JPEG, DOC, DOCX";
                MainEnquiryHead = "Your Enquiry";
                TermsConditions = "Before you click submit, please kindly read the <a href='https://www.sony.co.id/section/privacypolicy' target='_blank'>Privacy Policy</a>.";
                //$('[aria-describedby="sony_dateofpurchase_description"]').datepicker({
                //    maxDate: new Date(d.setDate(d.getDate() - 1)),
                //    dateFormat: "dd/mm/yy"
                //});
                break;
            case "en_au":
                ClearButton = "Clear";
                SubmitButton = "Submit";
                ModelText = "";
                SuggestAnAnswerHelper = "";
                ContinueToSubmit = "Continue to Submit";
                SuggestAnAnswer = "Suggest me An Answer";
                SearchPageHeader = "Suggested Answers";
                PleaseSelect = "Please Select";
                NoSuggestionFound = "No Suggestions Found";
                CharacterCountHelper = "characters remaining";
                //ContactIsRequired = "Contact is a required field.";
                completeAllFields = "Please complete all these fields";
                SuggestAnAnswerMandatoryFields = "Model and Description cannot be empty";
                SuggestionCloseButton = "Close";
                GeneralInfo = "General Information";
                attachWarning = "File size should not exceed 2 MB. Only these file types are accepted: PDF, GIF, JPG, JPEG, DOC, DOCX";
                MainEnquiryHead = "Your Enquiry";
                TermsConditions = "I have read and understood the Sony <a href='http://store.sony.com.au/privacy-collection-notice.html' target='_blank'>Privacy Collection Notice</a> and <a href='http://store.sony.com.au/privacy-policy.html' target='_blank'>Privacy Policy</a>.";
                bShowJobNo = false;
                //$('[aria-describedby="sony_dateofpurchase_description"]').datepicker({
                //    maxDate: new Date(d.setDate(d.getDate() - 1)),
                //    dateFormat: "dd/mm/yy"
                //});
                break;
            case "en_nz":
                ClearButton = "Clear";
                SubmitButton = "Submit";
                ModelText = "";
                SuggestAnAnswerHelper = "";
                ContinueToSubmit = "Continue to Submit";
                SuggestAnAnswer = "Suggest me An Answer";
                SearchPageHeader = "Suggested Answers";
                PleaseSelect = "Please Select";
                NoSuggestionFound = "No Suggestions Found";
                CharacterCountHelper = "characters remaining";
                //ContactIsRequired = "Contact is a required field.";
                completeAllFields = "Please complete all these fields";
                SuggestAnAnswerMandatoryFields = "Model and Description cannot be empty";
                SuggestionCloseButton = "Close";
                GeneralInfo = "General Information";
                attachWarning = "File size should not exceed 2 MB. Only these file types are accepted: PDF, GIF, JPG, JPEG, DOC, DOCX";
                MainEnquiryHead = "Your Enquiry";
                TermsConditions = "I have read and understood the Sony <a href='http://store.sony.co.nz/privacy-collection-notice.html' target='_blank'>Privacy Collection Notice</a> and <a href='http://store.sony.co.nz/privacy-policy.html' target='_blank'>Privacy Policy</a>.";
                bShowJobNo = false;
                //$('[aria-describedby="sony_dateofpurchase_description"]').datepicker({
                //    maxDate: new Date(d.setDate(d.getDate() - 1)),
                //    dateFormat: "dd/mm/yy"
                //});
                break;
            case "th_th":
                ClearButton = "ลบเนื้อหาออก";
                SubmitButton = "ส่งข้อมูล";
                ModelText = "";
                SuggestAnAnswerHelper = "";
                ContinueToSubmit = "ดำเนินการต่อเพื่อกรอกแบบฟอร์ม";
                SuggestAnAnswer = "แนะนำคำตอบให้ฉัน";
                SearchPageHeader = "คำตอบที่แนะนำ";
                PleaseSelect = "โปรดเลือก";
                NoSuggestionFound = "ไม่พบคำแนะนำ";
                CharacterCountHelper = "จำนวนตัวอักษรที่เหลืออยู่";
                //ContactIsRequired = "Contact is a required field.";
                SuggestAnAnswerMandatoryFields = "กรุณาใส่ชื่อรุ่นและคำอธิบาย";
                SuggestionCloseButton = "ปิด";
                completeAllFields = "กรุณาเติมข้อความในช่องเหล่านี้ให้ครบ";
                GeneralInfo = "ข้อมูลทั่";
                attachWarning = "ขนาดไฟล์ต้องไม่เกิน 2 MB. เฉพาะไฟล์เหล่านี้เท่านั้น: PDF, GIF, JPG, JPEG, DOC, DOCX";
                MainEnquiryHead = "ชนิดของการสอบถาม";
                TermsConditions = "ก่อนที่ท่านจะคลิกส่งข้อมูล กรุณาอ่าน <a href='https://www.sony.co.th/section/privacypolicy' target='_blank'>นโยบายความเป็นส่วนตัว</a>.";
                //$('[aria-describedby="sony_dateofpurchase_description"]').datepicker({
                //    maxDate: new Date(d.setDate(d.getDate() - 1)),
                //    dateFormat: "dd/mm/yy"
                //});
                break;
            case "vi_vn":
                ClearButton = "Xóa";
                SubmitButton = "Gởi";
                ModelText = "";
                SuggestAnAnswerHelper = "";
                ContinueToSubmit = "Tiếp tục Gửi";
                SuggestAnAnswer = "Đề xuất cho tôi một giải pháp";
                SearchPageHeader = "Các giải pháp được đề xuất";
                PleaseSelect = "Vui lòng chọn";
                NoSuggestionFound = "Không tìm thấy giải pháp";
                CharacterCountHelper = "kí tự còn lại";
                //ContactIsRequired = "Contact is a required field.";
                SuggestAnAnswerMandatoryFields = "Loại máy và mô tả không được để trống";
                SuggestionCloseButton = "Đóng";
                completeAllFields = "Vui lòng điền vào tất cả các trường này";
                GeneralInfo = "Thông tin chung";
                attachWarning = "Kích thước tập tin không vượt quá 2 MB. Chỉ chấp nhận với các loại tập tin: PDF, GIF, JPG, JPEG, DOC, DOCX";
                MainEnquiryHead = "Loại yêu cầu";
                TermsConditions = "Trước khi bạn nhấp gởi, xin vui lòng đọc <a href='https://www.sony.com.vn/section/privacypolicy' target='_blank'>Chính sách bảo mật</a>.";
                bShowJobNo = false;
                //$('[aria-describedby="sony_dateofpurchase_description"]').datepicker({
                //    maxDate: new Date(d.setDate(d.getDate() - 1)),
                //    dateFormat: "dd/mm/yy"
                //});
                break;
                //case "fr":
            case "fr_fr":
            case "fr_xa":
                contactUsLocale = "fr_XA";
                ClearButton = "Effacer";
                SubmitButton = "Envoi";
                ModelText = "";
                SuggestAnAnswerHelper = "";
                ContinueToSubmit = "Continuer à soumettre";
                SuggestAnAnswer = "Suggère moi une réponse";
                SearchPageHeader = "Réponses suggérées";
                PleaseSelect = "Veuillez faire un choix";
                NoSuggestionFound = "Aucune suggestion trouvée";
                CharacterCountHelper = "caractères restants";
                //ContactIsRequired = "Contact is a required field.";
                SuggestAnAnswerMandatoryFields = "Le modèle et la description ne peuvent pas être vides";
                SuggestionCloseButton = "Fermer";
                completeAllFields = "Veuillez remplir tous les champs";
                GeneralInfo = "Information d'ordre général";
                attachWarning = "La taille du fichier ne doit pas excéder 2 Mo. Seuls ces fichiers-ci sont acceptés : PDF, GIF, JPG, JPEG, DOC, DOCX";
                MainEnquiryHead = "Type de requête";
                TermsConditions = "Avant de cliquer sur \"Soumettre\", veuillez lire la <a href='https://www.sony-africa.com/section/privacypolicy' target='_blank'>Politique de confidentialité</a>.";
                bShowJobNo = false;
                //$('[aria-describedby="sony_dateofpurchase_description"]').datepicker({
                //    maxDate: new Date(d.setDate(d.getDate() - 1)),
                //    dateFormat: "dd/mm/yy"
                //});
                break;
            case "en_th":
                ClearButton = "Clear";
                SubmitButton = "Submit";
                ModelText = "";
                SuggestAnAnswerHelper = "";
                ContinueToSubmit = "Continue to Submit";
                SuggestAnAnswer = "Suggest me An Answer";
                SearchPageHeader = "Suggested Answers";
                PleaseSelect = "Please Select";
                NoSuggestionFound = "No Suggestions Found";
                CharacterCountHelper = "characters remaining";
                //ContactIsRequired = "Contact is a required field.";
                SuggestAnAnswerMandatoryFields = "Model and Description cannot be empty";
                SuggestionCloseButton = "Close";
                completeAllFields = "Please complete all these fields";
                GeneralInfo = "General Information";
                attachWarning = "File size should not exceed 2 MB. Only these file types are accepted: PDF, GIF, JPG, JPEG, DOC, DOCX";
                MainEnquiryHead = "Your Enquiry";
                TermsConditions = "Before you click submit, please kindly read the <a href='https://www.sony.co.th/section/privacypolicy?site=hp_en_TH_i' target='_blank'>Privacy Policy</a>.";
                //$('[aria-describedby="sony_dateofpurchase_description"]').datepicker({
                //    maxDate: new Date(d.setDate(d.getDate() - 1)),
                //    dateFormat: "dd/mm/yy"
                //});
                break;
            case "en_ap":
                ClearButton = "Clear";
                SubmitButton = "Submit";
                ModelText = "";
                SuggestAnAnswerHelper = "";
                ContinueToSubmit = "Continue to Submit";
                SuggestAnAnswer = "Suggest me An Answer";
                SearchPageHeader = "Suggested Answers";
                PleaseSelect = "Please Select";
                NoSuggestionFound = "No Suggestions Found";
                CharacterCountHelper = "characters remaining";
                //ContactIsRequired = "Contact is a required field.";
                SuggestAnAnswerMandatoryFields = "Model and Description cannot be empty";
                SuggestionCloseButton = "Close";
                completeAllFields = "Please complete all these fields";
                GeneralInfo = "General Information";
                attachWarning = "File size should not exceed 2 MB. Only these file types are accepted: PDF, GIF, JPG, JPEG, DOC, DOCX";
                MainEnquiryHead = "Your Enquiry";
                TermsConditions = "Before you click submit, please kindly read the <a href='https://www.sony-asia.com/section/privacypolicy' target='_blank'>Privacy Policy</a>.";
                bShowJobNo = false;
                //$('[aria-describedby="sony_dateofpurchase_description"]').datepicker({
                //    maxDate: new Date(d.setDate(d.getDate() - 1)),
                //    dateFormat: "dd/mm/yy"
                //});
				$("#description").attr("placeholder","Please DO NOT include personal or confidential information in your enquiry.");
                break;
            case "zh_tw":
                ClearButton = "清除";
                SubmitButton = "送出";
                ModelText = "";
                SuggestAnAnswerHelper = "";
                ContinueToSubmit = "繼續填寫表單";
                SuggestAnAnswer = "相關疑難排除";
                SearchPageHeader = "建議之解決方案";
                PleaseSelect = "請選擇";
                NoSuggestionFound = "無相關建議";
                CharacterCountHelper = "剩餘字數";
                //ContactIsRequired = "Contact is a required field.";
                SuggestAnAnswerMandatoryFields = "請填寫產品型號及描述";
                SuggestionCloseButton = "關閉";
                completeAllFields = "請完整填寫所有欄位";
                GeneralInfo = "一般資訊";
                attachWarning = "檔案大小不得大於 2 MB。僅支援 PDF、GIF、JPG、JPEG、DOC、DOCX 檔案類型";
                MainEnquiryHead = "詢問類別";
                bShowJobNo = false;
                //$('[aria-describedby="sony_dateofpurchase_description"]').datepicker({
                //    maxDate: new Date(d.setDate(d.getDate() - 1)),
                //    dateFormat: "dd/mm/yy"
                //});
                TermsConditions = "送出前，請先詳閱<a href='https://www.sony.com.tw/corporate/privacy/privacy.asp' target='_blank'>隱私權聲明</a>.";
                break;
            case "ar_xm":
                ClearButton = "مسح";
                SubmitButton = "إرسال";
                ModelText = "";
                SuggestAnAnswerHelper = "";
                ContinueToSubmit = "اكمل عمليه الادخال";
                SuggestAnAnswer = "اقبرح الاجابه";
                SearchPageHeader = "الاجابات المقترحه";
                PleaseSelect = "برجاء التحديد";
                NoSuggestionFound = "لا توجد مقتراحات";
                CharacterCountHelper = "الحروف المتبقية";
                //ContactIsRequired = "Contact is a required field.";
                SuggestAnAnswerMandatoryFields = "يجب ادخال اسم الموديل و المواصفات";
                SuggestionCloseButton = "إغلاق";
                completeAllFields = "برجاء إكمال كافة هذه الحقول";
                GeneralInfo = "معلومات عامة";
                attachWarning = "يتعين أن لا يزيد حجم الملف عن 2 ميجا بايت وأن يكون بتنسيق PDF وGIF وJPG وJPEG وDOC وDOCX فقط.";
                MainEnquiryHead = "نوع الاستفسار";
                bShowJobNo = false;
                //$('[aria-describedby="sony_dateofpurchase_description"]').datepicker({
                //    maxDate: new Date(d.setDate(d.getDate() - 1)),
                //    dateFormat: "dd/mm/yy"
                //});
                TermsConditions = 'قبل النقر على زر "إرسال"، برجاء قراءة <a href="https://www.sony-mea.com/section/privacypolicy?site=hp_ar_ME_i" target="_blank">سياسة الخصوصية</a>.';
                break;
            case "en_xm":
                contactUsLocale = "en_XM";
                ClearButton = "Clear";
                SubmitButton = "Submit";
                ModelText = "";
                SuggestAnAnswerHelper = "";
                ContinueToSubmit = "Continue to Submit";
                SuggestAnAnswer = "Suggest me An Answer";
                SearchPageHeader = "Suggested Answers";
                PleaseSelect = "Please Select";
                NoSuggestionFound = "No Suggestions Found";
                CharacterCountHelper = "characters remaining";
                //ContactIsRequired = "Contact is a required field.";
                completeAllFields = "Please complete all these fields";
                SuggestAnAnswerMandatoryFields = "Model and Description cannot be empty";
                SuggestionCloseButton = "Close";
                GeneralInfo = "General Information";
                attachWarning = "File size should not exceed 2 MB. Only these file types are accepted: PDF, GIF, JPG, JPEG, DOC, DOCX";
                MainEnquiryHead = "Your Enquiry";
                bShowJobNo = false;
                //$('[aria-describedby="sony_dateofpurchase_description"]').datepicker({
                //    maxDate: new Date(d.setDate(d.getDate() - 1)),
                //    dateFormat: "dd/mm/yy"
                //});
                TermsConditions = "Before you click submit, please kindly read the <a href='https://www.sony-mea.com/section/privacypolicy' target='_blank'>Privacy Policy</a>.";
                break;
            default:
                contactUsLocale = "en_SG";
                break;
        }
    }

    var buttonsHTML = '<div class="custom_form_group row">' +
                        '<div class="col-xs-12 col-sm-12 required_field_info">' +
                        '		(<font style="color: #f00;">*</font>) ' + completeAllFields + '' +
                        '	</div>	' + SuggestAnAnswerHelper +
                       '<div id="btn_suggestion_Group" class="col-xs-12 col-sm-12 multi_button_group">' +
                    '<input id="btn_continue_to_submit" type="button" value=" ' + ContinueToSubmit + '" style="background-color:#5887f5;font-size: 14px;padding: 7px 10px; border:0;margin:0;width:auto;color: #fff;font-family: SST W01 Roman,Helvetica Neue,Helvetica,Arial,sans-serif;"' +
                    ' onclick="ShowGeneralSection()">' +
                        '&nbsp;<input id="btn_suggest_me_answer" type="button" value=" ' + SuggestAnAnswer + ' " style="background-color:#5887f5;font-size: 14px;padding: 7px 10px; border:0;margin:0;width:auto;color: #fff;font-family: SST W01 Roman,Helvetica Neue,Helvetica,Arial,sans-serif;"' +
                        ' onclick="modalOnClick( \'' + SuggestAnAnswerMandatoryFields + '\', \'' + NoSuggestionFound + '\', \'' + SearchPageHeader + '\' )">' +
                        '<!-- Modal -->' +
                        '<div class="modal fade" id="suggest_me_answer" role="dialog">' +
                           ' <div class="modal-dialog">' +
                            '    <!-- Modal content-->' +
                             '   <div class="modal-content">' +
                              '      <button type="button" class="close" data-dismiss="modal">&times;</button>' +
                               '     <div class="modal-body custom_modal-body" style="text-align:left">' +
                                '        <div class="custom_modal_title"> ' + SearchPageHeader + ' </div>' +
                                 '       <div id="dynamic_modal_content"></div>' +
                                  '  </div>' +
                                    '<div class="modal-footer">' +
                                    ' <div class="row">' +
                                     ' <div class="col-md-6 col-sm-6 media-left">' +
                                        ' <div id="page-selection" style="margin: 0 auto; text-align: left;"></div>' +
                                     '</div>' +
                                     ' <div class="col-md-6 col-sm-6 media-left">' +
                                     '   <button type="button" class="btn btn-default" style="background-color:#5887f5;font-size: 14px;padding: 7px 10px; border:0;margin:0;width:auto;color: #fff;' +
    'font-family: SST W01 Roman,Helvetica Neue,Helvetica,Arial,sans-serif;" data-dismiss="modal"> ' + SuggestionCloseButton + ' </button>' +
                                        '</div>' +
                                        '</div>' +
       '                             </div>' +
        '                        </div>' +
         '                   </div>' +
          '              </div>' +
           '         </div></div>';

    var hrHTML = '<hr/>' +
				    '<div class="custom_support_header" style="text-align:left;">' + GeneralInfo + '</div>' +
				'<br/>';

    // Change Page Field Style
    var tCol = $('.section td:first-child');
    if (tCol != null && tCol != undefined) {
        tCol.removeAttr("class");
        tCol.toggleClass("custom_form_group row");
    }

    var divinforequired = $(".info.required");
    if (divinforequired != null && divinforequired != undefined) {
        divinforequired.removeAttr("class");
        divinforequired.addClass("custom_label_panel col-xs-12 col-sm-4");
        var label = divinforequired.find('label');
        if (label != null && label != undefined) {
            label.removeAttr("class");
            label.toggleClass("custom_form_label custom_form_label_required");
        }
    }

    var divinfo = $(".info");
    if (divinfo != null && divinfo != undefined) {
        divinfo.removeAttr("class");
        divinfo.addClass("custom_label_panel col-xs-12 col-sm-4");
        var label = divinfo.find('label');
        if (label != null && label != undefined) {
            label.removeAttr("class");
            label.toggleClass("custom_form_label");
        }
    }

    var control = $(".control");
    if (control != null && control != undefined) {
        //control.removeAttr("class");
        control.addClass("custom_form_panel col-xs-12 col-sm-8");

        var inputs = control.find('input');
        $.each(inputs, function (index, value) {
            var id = value.id;
            var attrtype = $("#" + id).attr("type");
            if (attrtype == "text") {
                $("#" + id).attr("class", "custom_text_box");
            }
            else if (attrtype == "radio") {
                $("#" + id).attr("class", "custom_form_radio_button");
                $("[for=" + id + "]").attr("class", "custom_form_radio_label");
            }
        });

        var select = control.find('select');
        $.each(select, function (index, value) {
            var id = value.id;
            $("#" + id).removeAttr("class");
            $("#" + id).attr("class", "custom_select_box");
        });

    }
    $("fieldset").attr("style", "margin-bottom:0px;");

    //$("[for=customerid]").closest("tr").hide();

    $("[for=sony_locale]").closest("tr").hide();
    $("#sony_locale")[0].style.display = 'none'
    $("#sony_locale_label")[0].style.display = 'none'
    $("#customerid")[0].style.display = 'none'
    $("#customerid_label")[0].style.display = 'none'

    var presents = $(".validation-header span[role='presentation']");
    if (presents != null && presents != undefined) {
        $(".validation-header span[role='presentation']").removeAttr("class");
        $(".validation-header span[role='presentation']").attr("fa fa-info-circle");
    }
    var objTitle = $(".tab-title");
    if (objTitle != null && objTitle != undefined) {
        objTitle.removeAttr("class");
        objTitle.toggleClass("custom_support_header");
        objTitle.html(MainEnquiryHead);
    }

    // $("[for=sony_subscribe]").closest("tr").hide();

    $(hrHTML).insertBefore($("[data-name=tab_section_generalinformation]"));
    //$(buttonsHTML).insertAfter($("[data-name=tab_section_yourenquiry]"));

    $(ModelText).insertAfter($("#sony_modelname_label").parent());
    $(".content_form_section").attr("style", "display: none;");

    var clearbutton = "<input type='reset' value='" + ClearButton + "' id='ClearTrackFormButton' class='btn'></input>";
    var submit = $("#InsertButton").parent().html();
    submit = clearbutton + submit;
    $("#InsertButton").parent().html(submit);
    $("#InsertButton").parent().addClass("multi_button_group");
    $("#InsertButton").parent().attr("style", "border:none;padding:0;");
    $("#InsertButton").attr("class", "");
    $("#InsertButton").attr("style", "background-color:#5887f5;font-size: 14px;padding: 7px 10px; border:0;margin:0;width:112.61px;color: #fff;font-family: SST W01 Roman,Helvetica Neue,Helvetica,Arial,sans-serif;");
    $("#InsertButton").attr("value", SubmitButton);
    $("#ClearTrackFormButton").attr("style", "background-color:#5887f5;font-size: 14px;padding: 7px 10px; border:0;width:112.61px;color: #fff;font-family: SST W01 Roman,Helvetica Neue,Helvetica,Arial,sans-serif;");

    var termcond = $("[for=sony_conditions]").closest("tr");
    $("#sony_conditions").attr("class", "custom_form_checkbox");
    var termcondHTML = termcond.find("span.checkbox").html();
    termcond.html("");
    var checkboxHtml = '<tr><td class="custom_form_group required_field_info">(<font style="color: #f00;">*</font>) ' + completeAllFields + '</td></tr><tr><td class="custom_form_group">' + termcondHTML + '<label for="chk_agree" class="custom_form_checkbox_label">' + TermsConditions + '</label></td></tr>';
    if (contactUsLocale == "en_IN") {
        var subscribe = $("[for=sony_subscribe]").closest("tr");
        $("#sony_subscribe").attr("class", "custom_form_checkbox");
        var subscribeHTML = subscribe.find("span.checkbox").html();
        subscribe.html("");
        checkboxHtml = '<tr><td class="custom_form_group required_field_info">(<font style="color: #f00;">*</font>) ' + completeAllFields + '</td></tr><tr><td class="custom_form_group">' + subscribeHTML + '<label for="chk_agree" class="custom_form_checkbox_label">' + SubscribeText + '</label></td></tr><tr><td class="custom_form_group">' + termcondHTML + '<label for="chk_agree" class="custom_form_checkbox_label">' + TermsConditions + '</label></td></tr>';
    }

    var CaptchaElement = $(".captcha-cell").parent();
    if (CaptchaElement.length > 0 && CaptchaElement != undefined && CaptchaElement != null) {
        var CaptchaHTML = CaptchaElement.html();
        CaptchaHTML = "<tr><td colspan='1' rowspan='1' class='custom_form_group row'><div class='custom_label_panel col-xs-12 col-sm-4'>&nbsp;</div><div class='control custom_form_panel col-xs-12 col-sm-8'>" + CaptchaHTML + "</div></td><td class='cell zero-cell'></td></tr>";
        $(CaptchaHTML).insertBefore(termcond);
        CaptchaElement.html('');
    }

    $(checkboxHtml).insertAfter(termcond);

    //Move and Restyle Attach Button
    var attach = '<span style="clear:both;font-size:10px;color:#808080;">' + attachWarning + '</span>';
    $("#AttachFile").parent().attr("class", "custom_form_panel col-xs-12 col-sm-8");
    var attachButtonHTML = $(".cell.file-cell").parent().html();
    $(".cell.file-cell").parent().html("");
    $(attachButtonHTML).insertBefore(termcond);
    $('input[type="checkbox"][id="sony_conditions"]').change(function () {
        if ($("#title") != null && $("#title") != undefined) {
            if (this.checked) {
                var date1 = new Date();
                $("#title").val('ContactUs_' + contactUsLocale + '_' + $("#sony_givenname").val() + '_' + date1.toDateString());
            }
            else {
                $("#title").val('');
            }
        }
    });

    $(attach).insertAfter($("#AttachFile"));
    $(".cell.file-cell").removeAttr("class");
    $("#AttachFile").attr("style", "border: none; display: inline-block;margin-top: 10px;height: 26px;cursor: pointer;width: 100%;font-size: 14px;line-height:16px;");

    // Fetch and fill values for Picklist
    {
        var objcustomer = [];
        var objcountry = [];
        var objplaceofpurchase = [];
        var objtypeofenqarray = [];
        var objproductgrouparray = [];
        var objproductgroup = {
        };
        var objcategoryarray = [];
        var objcategoryseries = {
        };
       
        // fetch Anonymous Customer
        $.ajax({ //3
            cache: false,
            type: "GET",
            url: "/contactsearch/",
            async: false,
            contentType: "text/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                if (msg.value.length > 0) {
                    objcustomer.push(msg);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log(XMLHttpRequest.responseText);
                objcustomer = XMLHttpRequest.responseText;
            }
        });
        // fetch country based on locale
        $.ajax({ //3
            cache: false,
            type: "GET",
            async: false,
            url: "/countrylocale/?locale=" + $("#countrylocale").val(),
            contentType: "text/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                objcountry.push(msg);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                objcountry = XMLHttpRequest.responseText;
            }
        });

        // fetch type of Enquiry based on locale
        $.ajax({ //3
            cache: false,
            type: "GET",
            async: false,
            url: "/typeofenquiry/?locale=" + $("#countrylocale").val(),
            contentType: "text/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                objtypeofenqarray.push(msg);
                objtypeofenqarray.sort();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log(XMLHttpRequest.responseText);
                //objtypeofenqarray = XMLHttpRequest.responseText;
            }
        });
        // fetch Product Group based on locale
        $.ajax({ //3
            cache: false,
            type: "GET",
            async: false,
            url: "/productgroup/?locale=" + $("#countrylocale").val(),
            contentType: "text/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                objproductgrouparray.push(msg);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log(XMLHttpRequest.responseText);
            }
        });

        // fetch Place of Purchase based on locale
        if (!(contactUsLocale.toLowerCase() == "en_au" || "en_nz")) {
            $.ajax({ //3
                cache: false,
                type: "GET",
                async: false,
                url: "/fetchplaceofpurchase/?countrylocale=" + $("#countrylocale").val(),
                contentType: "text/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    objplaceofpurchase.push(msg);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    console.log(XMLHttpRequest.responseText);
                }
            });
        }

        // Set Customer default
        $("#customerid").closest("tr").hide();
        $("#customerid")[0].style.display = 'none'
        $("#customerid_label")[0].style.display = 'none'
        if (objcustomer != null && objcustomer != undefined && objcustomer.length > 0) {
            $("#customerid_name").attr("value", objcustomer[0].value[0]["ContactName"]);
            $("#customerid").attr("value", objcustomer[0].value[0]["CustomerId"]);
        } else {
            $("#customerid_name").attr("value", "Portal Customer");
            $("#customerid").attr("value", "99db51a2-c34e-e111-bb8d-00155d03a715");
        }
        $("#customerid_entityname").attr("value", "contact");

        var selectCountryVal = $("#sony_placeofresidence option:selected").val();
        //fill country into the selection Box
        $("#sony_placeofresidence option").each(function () {
            $(this).remove();
        });

        if (objcountry != null && objcountry != undefined && objcountry.length > 0) {

            $('#sony_placeofresidence').append($('<option>', {
                value: (""),
                text: (PleaseSelect)
            }));
            var iLength = 0; var selectCountryGUID = "";
            $.each(objcountry, function (index, value) {
                $.each(value.value, function (index, values) {
                    iLength++;
                    $('#sony_placeofresidence').append($('<option>', {
                        value: (values["CountryGuid"]),
                        text: (values["CountryName"])
                    }));
                    selectCountryGUID = values["CountryGuid"];
                });
            });

            if (selectCountryVal != null && selectCountryVal != undefined && selectCountryVal != "") {
                $("#sony_placeofresidence").val(selectCountryVal).prop('selected', true);
            } else if (iLength == 1) {
                $("#sony_placeofresidence").val(selectCountryGUID).prop('selected', true);
            }
        }

        //fill type of enquiry into the selection Box
        var selecttoeVal = $("#sony_typeofenquiry option:selected").val();
        $("#sony_typeofenquiry option").each(function () {
            $(this).remove();
        });
        // Added by Raji -29/04/2019 for separate mobile contact us page.
        var partialUrl = (window.location.href).split('/')[4];

        if (partialUrl.indexOf('mobile') != -1) {
            //$('#sony_typeofenquiry').append($('<option>', {
            //    value: (""),
            //    text: ("Mobiles")
            //}));
            for (var i = 0; i < objtypeofenqarray[0].value.length; i++) {
                if (objtypeofenqarray[0].value[i].EnquiryName.toLowerCase() === "mobiles") {
                    $('#sony_typeofenquiry').append($('<option>', {
                        //value: (values["EnquiryId"]),
                        //text: (values["EnquiryVal"])
                        value: objtypeofenqarray[0].value[i].EnquiryId,
                        text: objtypeofenqarray[0].value[i].EnquiryVal
                    }));
                }
            }

            //$("#sony_typeofenquiry").prop('disabled', true);
            $('#sony_typeofenquiry').attr('readonly', true);
            $('#sony_typeofenquiry').attr("style", "pointer-events: none;background-color: #F6F6F6  !important");
            if (selecttoeVal != null && selecttoeVal != undefined && selecttoeVal != "") {
                $("#sony_typeofenquiry").val(selecttoeVal).prop('selected', true);
            }
            //ShowTOEBehaviour($("#sony_typeofenquiry"));

            $("[data-name=tab_section_yourenquiry]").show();
            $("[data-name=tab_yourenquiry_productgroup]").show();
            //$("[data-name=tab_yourenquiry_repairdetails]").show();
            $("#sony_jobno").closest("tr").hide();
            $("[data-name=tab_section_generalinformation]").parent().show();
            $("#InsertButton").parent().show();
            $("#btn_suggestion_Group").hide();
            $("#idsupportcontent").hide();
        }
        else {
            //$('#sony_typeofenquiry').append($('<option>', {
            //    value: (""),
            //    text: (PleaseSelect)
            //}));

            if (objtypeofenqarray != null && objtypeofenqarray != undefined && objtypeofenqarray.length > 0) {
                $.each(objtypeofenqarray, function (index, value) {
                    $.each(value.value, function (index, values) {
                        $('#sony_typeofenquiry').append($('<option>', {
                            value: (values["EnquiryId"]),
                            text: (values["EnquiryVal"])
                        }));
                    });
                });
                if (selecttoeVal != null && selecttoeVal != undefined && selecttoeVal != "") {
                    $("#sony_typeofenquiry").val(selecttoeVal).prop('selected', true);
                }
            }
        }

       
        

        // fill product group into pick list
        var selectedProdGroup = $("#sony_productgroup option:selected").val();
        $("#sony_productgroup option").each(function () {
            $(this).remove();
        });
        $('#sony_productgroup').append($('<option>', {
            value: (""),
            text: (PleaseSelect)
        }));
        if (objproductgrouparray != null && objproductgrouparray != undefined && objproductgrouparray.length > 0) {
            $.each(objproductgrouparray, function (index, value) {
                $.each(value.value, function (index, values) {
                    $('#sony_productgroup').append($('<option>', {
                        value: (values["Productgroupid"]),
                        text: (values["ProductGroupName"])

                    }));
                    objproductgroup[(values["ProductGroupName"])] = (values["Productgroupid"]);
                });
            });
            if (selectedProdGroup != null && selectedProdGroup != undefined && selectedProdGroup != "") {
                $("#sony_productgroup").val(selectedProdGroup).prop('selected', true);
            }
        }

        //fill Place of purchase into the selection Box
        var selectedpurchaseplace = $("#sony_placepurchased option:selected").val();
        $("#sony_placepurchased option").each(function () {
            $(this).remove();
        });
        $('#sony_placepurchased').append($('<option>', {
            value: (""),
            text: (PleaseSelect)
        }));

        if (objplaceofpurchase != null && objplaceofpurchase != undefined && objplaceofpurchase.length > 0) {
            $.each(objplaceofpurchase, function (index, value) {
                $.each(value.value, function (index, values) {
                    $('#sony_placepurchased').append($('<option>', {
                        value: (values["sony_placeid"]),
                        text: (values["sony_name"])
                    }));
                });
            });
            if (selectedpurchaseplace != null && selectedpurchaseplace != undefined && selectedpurchaseplace != "") {
                $("#sony_placepurchased").val(selectedpurchaseplace).prop('selected', true);
            }
        }

        // fill product category into picklinst
        var selectcategoryVal = $("#sony_productcategory option:selected").val();
        $("#sony_productcategory option").each(function () {
            $(this).remove();
        });
        $('#sony_productcategory').append($('<option>', {
            value: (""),
            text: (PleaseSelect)
        }));

        $("#objproductgroup option").each(function () {
            var key = $(this).text();
            var value = $(this).val();
            objproductgroup[key] = value;
        });

        for (var property in objproductgroup) {
            if (objproductgroup.hasOwnProperty(property)) {
                var partialurl = objproductgroup[property];
                $.ajax({ //3
                    cache: false,
                    type: "GET",
                    async: false,
                    url: "/searchproductseries/?productgroup=" + partialurl,
                    contentType: "text/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        objcategoryarray.push(msg);
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        console.log(XMLHttpRequest.responseText);
                        //objcategoryarray = XMLHttpRequest.responseText;
                    }
                });
            }
        }

        $("#sony_productgroup").change(function () {
            $("#sony_productcategory option").each(function () {
                $(this).remove();
            });

            $('#sony_productcategory').append($('<option>', {
                value: (""),
                text: (PleaseSelect)
            }));
            var bHasValue = false;
            $.each(objcategoryarray, function (index, value) {
                $.each(value.value, function (index, values) {
                    if ($("#sony_productgroup").val() == values["ProductCategory"]) {
                        bHasValue = true;
                        $('#sony_productcategory').append($('<option>', {
                            value: (values["CategoryGuid"]),
                            text: (values["CategoryName"])
                        }));
                    }
                });
            });
            if (bHasValue == false)
                $("#sony_productcategory").closest("tr").hide();
            else
                $("#sony_productcategory").closest("tr").show();
        });

        //fetch state based on locale
        if (fetchState == true) {
            $.ajax({ //3
                cache: false,
                type: "GET",
                async: false,
                url: "/FetchStatebyLocale/?locale=" + $("#countrylocale").val(),
                contentType: "text/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    if (msg.value.length > 0) {
                        objState.push(msg);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    console.log(XMLHttpRequest.responseText);
                    //objState = XMLHttpRequest.responseText;
                }
            });
            var selectedState = $("#sony_state option:selected").val();
            $("#sony_state option").each(function () {
                $(this).remove();
            });
            $('#sony_state').append($('<option>', {
                value: (""),
                text: (PleaseSelect)
            }));

            if (objState != null && objState != undefined && objState.length > 0) {
                $.each(objState, function (index, value) {
                    $.each(value.value, function (index, values) {
                        $('#sony_state').append($('<option>', {
                            value: (values["StateGUID"]),
                            text: (values["StateName"])
                        }));

                    });
                });
                if (selectedState != null && selectedState != undefined && selectedState != "") {
                    $("#sony_state").val(selectedState).prop('selected', true);
                }
            }
        }

        var nCharcRemaining = 2000;
        if ($('#description').val() != undefined && $('#description').val() != "" && $('#description').val().length > 0) {
            nCharcRemaining = nCharcRemaining - $('#description').val().length;
        }
        $("<p class='TinyText'><i><span id='remainingC'>" + nCharcRemaining + "</span> " + CharacterCountHelper + "</i></p>").insertAfter("#description");
        $('#description').keydown(function () {
            var key = event.keyCode || event.charCode;
            if (this.value.length > 2000) {
                return false;
            }
            $("#remainingC").html((2000 - this.value.length));
        });
        //if (partialUrl.indexOf('mobile') == -1) {
        //    $("[data-name=tab_section_yourenquiry]").hide();
        //    $("[data-name=tab_yourenquiry_productgroup]").hide();
        //    //$("[data-name=tab_yourenquiry_repairdetails]").hide();
        //    $("#sony_jobno").closest("tr").hide();
        //    $("[data-name=tab_section_generalinformation]").parent().hide();
        //    $("#InsertButton").parent().hide();
        //    $("#btn_suggestion_Group").hide();
        //    $("#idsupportcontent").hide();
        //}

        if (selecttoeVal != null && selecttoeVal != undefined && selecttoeVal != "") {
            $("#" + $(".contact-form-btn").attr("rel")).fadeIn(custom_fadeIn_speed);
            $(".contact-form-btn").addClass("contact_form_active");
            ShowTOEBehaviour($("#sony_typeofenquiry"));           
        }
        //$("[data-date-format='DD/MM/YYYY']").attr("class", "custom_text_box");
        //$('[aria-describedby="sony_dateofpurchase_description"]').next().remove();
        //$('[aria-describedby="sony_dateofpurchase_description"]').attr("style", "width:690px")
        //$('[aria-describedby="sony_dateofpurchase_description"]').hide();
        //$("#sony_dateofpurchase").attr("style", "display:block");
        //$('[aria-describedby="sony_dateofpurchase_description"]').datepicker({
        //    maxDate: new Date(d.setDate(d.getDate() - 1)),
        //    dateFormat: "dd/mm/yy"
        //});
        var objautoselecttoe = [];
        var params = {
        };
        params = getAllQueryVariable();

        $.each(params, function (index, value) {
            var DecodedValue = decodeURI(value);
            if (index == "jid") {
                $("#sony_jobno").val(DecodedValue);
            }
            if (index == "email") {
                $("#sony_emailaddress").val(DecodedValue);
            }
            if (index == "contactno") {
                $("#sony_contactno").val(DecodedValue);
            }
            if (index == "pdp") {
                $("#sony_modelname").val(DecodedValue);
            }
            if (index == "toe") {
                $("#" + $(".contact-form-btn").attr("rel")).fadeIn(custom_fadeIn_speed);
                $(".contact-form-btn").addClass("contact_form_active");
                $.ajax({ //3
                    cache: false,
                    type: "GET",
                    async: false,
                    url: "/autoselecttoe/?locale=" + contactUsLocale + "&toe=" + DecodedValue,
                    contentType: "text/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        if (msg.value.length > 0) {
                            objautoselecttoe.push(msg);
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        console.log(XMLHttpRequest.responseText);
                        //objautoselecttoe = XMLHttpRequest.responseText;
                    }
                });
                if (objautoselecttoe.length > 0) {
                    $("#sony_typeofenquiry").val(objautoselecttoe[0].value[0]["EnquiryId"]).prop('selected', true);
                    SetSelectionBehaviour(objautoselecttoe);
                }
            }

            if (index == "cat") {
                var selectedProductGroupID = "";
                var selectedProductCategoryID = "";
                $.each(objcategoryarray, function (index, selCatvalue) {
                    $.each(selCatvalue.value, function (index, values) {
                        if (DecodedValue == values["CategoryCode"]) {
                            selectedProductCategoryID = values["CategoryGuid"];
                            selectedProductGroupID = values["ProductCategory"];
                        }
                    });
                });
                var bPdtGroupSelected = false;
                if (selectedProductGroupID == "") {
                    if (objproductgrouparray != null && objproductgrouparray != undefined && objproductgrouparray.length > 0) {
                        $.each(objproductgrouparray, function (index, selGrpvalue) {
                            $.each(selGrpvalue.value, function (index, values) {
                                if (DecodedValue == values["ProductgroupCode"]) {
                                    $("#sony_productgroup").val(values["Productgroupid"]).prop('selected', true);
                                    bPdtGroupSelected = true;
                                }
                            });
                        });
                    }
                }
                else {
                    $("#sony_productgroup").val(selectedProductGroupID).prop('selected', true);
                }

                if (selectedProductCategoryID != "") {
                    $("#sony_productcategory option").each(function () {
                        $(this).remove();
                    });
                    $('#sony_productcategory').append($('<option>', {
                        value: (""),
                        text: (PleaseSelect)
                    }));

                    $.each(objcategoryarray, function (index, selcat1value) {
                        $.each(selcat1value.value, function (index, values) {
                            if (selectedProductGroupID == values["ProductCategory"]) {
                                $('#sony_productcategory').append($('<option>', {
                                    value: (values["CategoryGuid"]),
                                    text: (values["CategoryName"])
                                }));
                            }
                        });
                    });
                    $("#sony_productcategory").val(selectedProductCategoryID).prop('selected', true);
                }
            }
        });

        if (contactUsLocale == "en_IN") {
            $("#sony_subscribe").prop("checked", "true");
        }
    }
    var objselecttedtoe = [];
    $("#sony_typeofenquiry").change(function () {
        ShowTOEBehaviour($(this));
        $("[data-date-format='DD/MM/YYYY']").attr("class", "custom_text_box");
        $('[aria-describedby="sony_dateofpurchase_description"]').next()[0].remove();
        $('[aria-describedby="sony_dateofpurchase_description"]').attr("style", "width:690px")
        //$('[aria-describedby="sony_dateofpurchase_description"]').hide();
        //$("#sony_dateofpurchase").attr("style", "display:block");
        $('[aria-describedby="sony_dateofpurchase_description"]').datepicker({
            maxDate: new Date(d.setDate(d.getDate() - 1)),
            dateFormat: "dd/mm/yy"
        });
    });
    //$("#sony_dateofpurchase").change(function () {
    //    $("[data-date-format='DD/MM/YYYY']").attr("class", "custom_text_box");
    //    $('[aria-describedby="sony_dateofpurchase_description"]').next().hide();
    //    $('[aria-describedby="sony_dateofpurchase_description"]').hide();
    //    //$("#sony_dateofpurchase").attr("style", "display:block");
    //    $("#sony_dateofpurchase").datepicker({
    //        maxDate: new Date(d.setDate(d.getDate() - 1)),
    //        dateFormat: "dd/mm/yy"
    //    });
    //});
    //$("#sony_dateofpurchase").load(function () {

    //    console.log("1");
    //});
    //$("#sony_dateofpurchase").change(function () {
    //    console.log("1");
    //    $('[aria-describedby="sony_dateofpurchase_description"]').next().hide();
    //    var d = new Date();
    //    $('[aria-describedby="sony_dateofpurchase_description"]').datepicker({
    //        maxDate: new Date(d.setDate(d.getDate() - 1)),
    //        dateFormat: "dd/mm/yy"
    //    });

    //    $('[aria-describedby="sony_dateofpurchase_description"]').attr("style", "width:690px");
//});

   // $('[aria-describedby="sony_dateofpurchase_description"]').hide();
    //$("#sony_dateofpurchase").datepicker({
    //    maxDate: new Date(d.setDate(d.getDate() - 1)),
    //    dateFormat: "dd/mm/yy"
    //});
   
    $.getScript('/HideFormFieldsJS.js', function () {
        HideFromFields(contactUsLocale, "contact-us");
    });
//});

function ShowTOEBehaviour(toeObject) {
    if (toeObject.val() == "") {
        $("[data-name=tab_section_yourenquiry]").hide();
        $("[data-name=tab_yourenquiry_productgroup]").hide();
        //$("[data-name=tab_yourenquiry_repairdetails]").hide();
        $("#sony_jobno").closest("tr").hide();
        $("[data-name=tab_section_generalinformation]").parent().hide();
        $("#InsertButton").parent().hide();
        $("#btn_suggestion_Group").hide();
        $("#idsupportcontent").hide();
    }

    if (toeObject.val() != "") {
        //$("[data-date-format='DD/MM/YYYY']").attr("class", "custom_text_box");
        //$('[aria-describedby="sony_dateofpurchase_description"]').next().remove();
        //$('[aria-describedby="sony_dateofpurchase_description"]').attr("style", "width:690px")
        ////$('[aria-describedby="sony_dateofpurchase_description"]').hide();
        ////$("#sony_dateofpurchase").attr("style", "display:block");
        //$('[aria-describedby="sony_dateofpurchase_description"]').datepicker({
        //    maxDate: new Date(d.setDate(d.getDate() - 1)),
        //    dateFormat: "dd/mm/yy"
        //});
        var selecttedtoe = $("#sony_typeofenquiry option:selected").val();
        objselecttedtoe = [];
        $.ajax({ //3
            cache: false,
            type: "GET",
            url: "/selectedtoebehaviour/?locale=" + $("#countrylocale").val() + "&eqtypeval=" + selecttedtoe,
            async: false,
            contentType: "text/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                if (msg.value.length > 0) {
                    objselecttedtoe.push(msg);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                objselecttedtoe = XMLHttpRequest.responseText;
            }
        });
        SetSelectionBehaviour(objselecttedtoe);
    }
}

function SetSelectionBehaviour(objselecttoe) {

    if (objselecttoe.length > 0 && objselecttoe[0].value[0]["Behaviour"].length > 0) {
        if ($("#countrylocale").val() == "en_IN") {
            if (objselecttoe[0].value[0]["EnquiryName"] != null && objselecttoe[0].value[0]["EnquiryName"] != undefined &&
                objselecttoe[0].value[0]["EnquiryName"] == "escalate_an_existing_case") {
                addValidator("sony_jobno", "Repair Job No./ Talisma ID");
            }
            else {
                removeValidator("sony_jobno");
            }
        }

        if (objselecttoe[0].value[0]["Behaviour"] == 0) {
            $("[data-name=tab_section_yourenquiry]").show();
            $("[data-name=tab_yourenquiry_productgroup]").hide();
            //$("[data-name=tab_yourenquiry_repairdetails]").hide();
            $("#sony_jobno").closest("tr").hide();
            $("[data-name=tab_section_generalinformation]").parent().show();
            $("#InsertButton").parent().show();
            $("#btn_suggestion_Group").hide();
            $("#idsupportcontent").hide();

        }
        else if (objselecttoe[0].value[0]["Behaviour"] == 1) {
            $("[data-name=tab_section_yourenquiry]").show();
            $("[data-name=tab_yourenquiry_productgroup]").show();
            //$("[data-name=tab_yourenquiry_repairdetails]").show();
            $("#sony_jobno").closest("tr").hide();
            $("[data-name=tab_section_generalinformation]").parent().show();
            $("#InsertButton").parent().show();
            $("#btn_suggestion_Group").hide();
            $("#idsupportcontent").hide();
        }
        else if (objselecttoe[0].value[0]["Behaviour"] == 2) {
            $("[data-name=tab_section_yourenquiry]").show();
            $("[data-name=tab_yourenquiry_productgroup]").show();
            //$("[data-name=tab_yourenquiry_repairdetails]").show();
            if (bShowJobNo)
                $("#sony_jobno").closest("tr").show();
            $("[data-name=tab_section_generalinformation]").parent().hide();
            $("#btn_continue_to_submit").show();
            $("#InsertButton").parent().show();
            $("#btn_suggestion_Group").show();
            $("#idsupportcontent").show();
        }
        else {
            $("[data-name=tab_section_yourenquiry]").show();
            $("[data-name=tab_yourenquiry_productgroup]").hide();
            //$("[data-name=tab_yourenquiry_repairdetails]").hide();
            $("#sony_jobno").closest("tr").hide();
            $("[data-name=tab_section_generalinformation]").parent().show();
            $("#InsertButton").parent().show();
            $("#btn_suggestion_Group").hide();
            $("#idsupportcontent").hide();

        }
    }
    else {
        $("[data-name=tab_section_yourenquiry]").show();
        $("[data-name=tab_yourenquiry_productgroup]").hide();
        //$("[data-name=tab_yourenquiry_repairdetails]").hide();
        $("#sony_jobno").closest("tr").hide();
        $("[data-name=tab_section_generalinformation]").parent().show();
        $("#InsertButton").parent().show();
        $("#btn_suggestion_Group").hide();
        $("#idsupportcontent").hide();

    }
}


var model = '';
var description = '';
var html = '';
var totalCount = 0;
var count = "5";
var CurrentPage = 1;

function PopulateSuggestions(itemArray, noResultsMsg, searchHeaderText) {
    if (itemArray.length > 0) {
        $(".custom_modal_title").html(searchHeaderText);
        $('#dynamic_modal_content').html('');
        $.each(itemArray, function (index, item) {
            var answer = item.description;
            if (answer == '' || answer == undefined) {
                answer = '&nbsp;';
            }
            html = html.concat('<div class="custom_modal_faq_section"><div class="custom_modal_faq_question"><a href="' + item.url + '" target="_blank">' + item.title + '</a></div><ul class="custom_modal_faq_answer_section"><li class="custom_modal_answer">' + answer + '</li></ul></div>');
        });
        $("#dynamic_modal_content").append(html);
        html = '';
    } else {
        $(".custom_modal_title").html('');
        $("#dynamic_modal_content").html("<h5>" + noResultsMsg + "</h5>");
    }

}

var availableTags = [];

function getSonyGWTAPIUrl() {
    var sony_gwt_api = "";

    $.ajax({ //3
        cache: false,
        type: "GET",
        async: false,
        url: "/sony_gwt_api/?locale=" + $("#countrylocale").val(),
        contentType: "text/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            sony_gwt_api = msg.value[0].sony_configurationvalue;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log(XMLHttpRequest.responseText);
            //objtypeofenqarray = XMLHttpRequest.responseText;
        }
    });
    return sony_gwt_api;
}

function getHslSupportSvcUrl() {
    var hsl_service_url = "";

    $.ajax({ //3
        cache: false,
        type: "GET",
        async: false,
        url: "/hsl_support_svc/",
        contentType: "text/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            hsl_service_url = msg.value[0].sony_configurationvalue;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log(XMLHttpRequest.responseText);
        }
    });
    return hsl_service_url;
}

$("#sony_modelname").keyup(function () {
    if ($("#sony_modelname").val().length >= 2) {
        model = $("#sony_modelname").val();
        if (!(contactUsLocale.toLowerCase() == "en_au" || "en_nz")) {
            callApiForSearchModel(model);
        }  
    };
});

function modalOnClick(mandatoryErrorMsg, noResultsMsg, searchHeaderText) {
    $('#page-selection').html('');
    model = $("#sony_modelname").val();
    description = $("#description").val();
    if (model == "" || description == "") {
        alert(mandatoryErrorMsg);
        return false;
    } else {
        callApiForRecords(count, 1, noResultsMsg, searchHeaderText);
        $('#page-selection').bootpag({
            total: totalCount,
            page: parseInt(1),
            maxVisible: 5,
            leaps: true,
            firstLastUse: false,
            first: '←',
            last: '→',
            wrapClass: 'pagination',
            activeClass: 'active',
            disabledClass: 'disabled',
            nextClass: 'next',
            prevClass: 'prev',
            lastClass: 'last',
            firstClass: 'first'
        }).on("page", function (event, /* page number here */ num) {
            if (CurrentPage != num) {
                callApiForRecords(count, num, noResultsMsg, searchHeaderText);
                CurrentPage = num;
            }
        });
        $('#suggest_me_answer').modal('show');
    }
}

function callApiForRecords(count, page, noResultsMsg, searchHeaderText) {
    var query = encodeURI(description);
    var modelName = model.toLowerCase();
    modelName = modelName.replace(/^\s+|\s+$/g, '');
    var localeVal = $("#countrylocale").val();
    var start = (parseInt(count) * parseInt(page)) - (parseInt(count));
    var dynApiUrl = getSonyGWTAPIUrl() + "search/" + encodeURI(modelName) + "?query=" + query + "&locale=" + localeVal + "&num=" + count + "&start=" + start + "&searchInSubDocuments=true"; //added &searchInSubDocuments=true to align with SWT search result count.
    $.ajax({ //3  
        cache: false,
        type: "GET",
        async: false,
        url: dynApiUrl,
        contentType: "text/json; charset=utf-8",
        //data: JSON.stringify({
        //    apiUrl: dynApiUrl
        //}),
        dataType: "json",
        success: function (JSONresponse) {
            //var JSONresponse = JSON.parse(msg.d);
            var arrayOfResults = JSONresponse.searchResponse.results;
            var responseCount = JSONresponse.searchResponse.count;
            if (responseCount < count) {
                totalCount = responseCount;
            }
            else {
                totalCount = JSONresponse.searchResponse.count / count;
            }

            PopulateSuggestions(arrayOfResults, noResultsMsg, searchHeaderText);

        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            var arrayVal = [];
            totalCount = 0;
            PopulateSuggestions(arrayVal, noResultsMsg, searchHeaderText);
        }
    }); //3

}

function callApiForSearchModel(model) {
    var query = encodeURI(model);
    var localeVal = $("#countrylocale").val();

    var dynApiUrl = getSonyGWTAPIUrl() + localeVal + "/suggest?query=" + query;
    $.ajax({ //3  
        cache: false,
        type: "GET",
        async: false,
        url: dynApiUrl,
        contentType: "text/json; charset=utf-8",
        //data: JSON.stringify({
        //    apiUrl: dynApiUrl
        //}),
        dataType: "json",
        success: function (msg) {
            //var JSONresponse = JSON.parse(msg.d);
            var arrayOfResults = msg.suggestions;
            var resultList = "<datalist>";

            $.each(arrayOfResults, function (index, item) {
                var tags = (item.name);
                //tags = tags.replace("</em>", "");
                var idx = jQuery.inArray(tags, availableTags);
                if (idx == -1) {
                    availableTags.push(tags);
                }
            });
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //alert(XMLHttpRequest.status);
            console.log(XMLHttpRequest.responseText);
        }
    }); //3

}

$(function () {

    $("#sony_modelname").autocomplete({
        source: availableTags
    });
});

function getAllQueryVariable() {
    var objParams = {
    };
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        objParams[pair[0]] = pair[1];
    }
    return objParams;
}

function onCustomerChange() {
    var val = $("#customerid").val();
    var entitlement = $("#entitlementid").parent();
    var product = $("#productid").parent();
    if (val) {
        disableEnable(entitlement, false);
        disableEnable(product, false);
    } else {
        disableEnable(entitlement, true);
        disableEnable(product, true);
    }
    updateContactRequired();
}

function disableEnable($param, disabled) {
    $param.find('input').each(function () {
        $(this).attr("disabled", disabled);
    });

    $param.find('button').each(function () {
        $(this).attr("disabled", disabled);
    });
}

function updateContactRequired() {
    var customerTypeVal = $("#customerid_entityname").val();
    if (customerTypeVal && customerTypeVal == "account") {
        $("#primarycontactid_label").parent().addClass("required");
    } else {
        $("#primarycontactid_label").parent().removeClass("required");
    }
}

function ShowGeneralSection() {
    $("[data-name=tab_section_generalinformation]").parent().show();
    $("#btn_continue_to_submit").hide();
    $("#InsertButton").parent().show();
}

//eg. addValidator("customerid", "Customer")
function addValidator(fieldName, fieldLabel) {

    if (typeof (Page_Validators) == 'undefined') return;
    // Create new validator
    $("#" + fieldName + "_label").parent().addClass("required");
    $("#" + fieldName + "_label").addClass("custom_form_label_required");
    var label = $("#" + fieldName + "_label").html();
    var newValidator = document.createElement('span');
    newValidator.style.display = "none";
    newValidator.id = "RequiredFieldValidator" + fieldName;
    newValidator.controltovalidate = fieldName;
    newValidator.errormessage = "<a href='#" + fieldName + "_label'>" + label + " is a mandatory field.</a>";
    newValidator.validationGroup = "";
    newValidator.initialvalue = "";
    newValidator.evaluationfunction = function () {
        var value = $("#" + fieldName).val();
        if (value == null || value == "") {
            return false;
        } else {
            return true;
        }
    };

    // Add the new validator to the page validators array:
    Page_Validators.push(newValidator);

    // Wire-up the click event handler of the validation summary link
    $("a[href='#" + fieldName + "_label']").on("click", function () {
        scrollToAndFocus(fieldName + '_label', fieldName);
    });
}

function removeValidator(fieldName) {
    $.each(Page_Validators, function (index, validator) {
        if (validator.id == "RequiredFieldValidator" + fieldName) {
            Page_Validators.splice(index, 1);
        }
    });
    $("#" + fieldName + "_label").parent().removeClass("required");
    $("#" + fieldName + "_label").removeClass("custom_form_label_required");
}

$("[data-date-format='DD/MM/YYYY']").attr("class", "custom_text_box");
//$("[data-date-format='DD/MM/YYYY']").attr("class", "custom_text_box");
$('[aria-describedby="sony_dateofpurchase_description"]').next().remove();
$('[aria-describedby="sony_dateofpurchase_description"]').attr("style", "width:690px")
$('[aria-describedby="sony_dateofpurchase_description"]').datepicker({
    maxDate: new Date(d.setDate(d.getDate() - 1)),
    dateFormat: "dd/mm/yy"
});

$.unblockUI();

