﻿ (function($) {

     $.fn.ccmanager = function(customSettings) {

         var settings = {
             ccmodifylink: "a.ccmodify",
             ccnewlink: "a#addnewcc",
             ccguestid: null,
             ccexpcontroldate: null,  //YYYYMMDD
             showremovecc: false,
             loadccrec: function(ccrow) { return new CCRecord(); },
             oncomplete: function() { }
         };

         //         var CCRecord = function() {
         //             this.ccguestid = null;
         //             this.ccid = null;
         //             this.cctype = null;
         //             this.cctypedesc = null;
         //             this.ccnumber = null;
         //             this.ccexpmonth = null;
         //             this.ccexpyear = null;
         //             this.ccbillingname = null;
         //             this.ccbillingaddress = null;
         //             this.removeccinfo = null;
         //         };

         var opts = $.extend(settings, customSettings);
         for (var i in opts) { $.ccmanager[i] = opts[i]; }

         var ccrec;

         //CC MODIFY FORM
         $.ccmanager.ccmodifylink = $($.ccmanager.ccmodifylink);
         $.ccmanager.ccmodifylink.click(function(event) {

             event.preventDefault();
             $('.profile_ccinfo_update').remove();
             $('#guestccinfo, .addcccontrols').hide();

             var ccRow = $(this).parent('td').parent('tr');
             ccrec = $.ccmanager.loadccrec(ccRow);

             $($('#guestccinfo_updateccfrm_temp').parsetemplate(ccrec)).insertAfter(ccRow);
             $('#modify_ccexpirationmonth option[value=' + ccrec.ccexpmonth + ']').attr("selected", "selected");
             $('#modify_ccexpirationyear option[value=' + ccrec.ccexpyear + ']').attr("selected", "selected");

             //CC Exp Month/Year Selection Changed Handler
             var ccExpControlDate = new Date(new Date().getFullYear(), new Date().getMonth(), 1);
             if ($.ccmanager.ccexpcontroldate != null) {
                 ccExpControlDate = new Date($.ccmanager.ccexpcontroldate.substr(0, 4), $.ccmanager.ccexpcontroldate.substr(4, 2) - 1, 1);
             };

             handleCCExpired('#modify_ccexpirationmonth', '#modify_ccexpirationyear', ccExpControlDate);
             $("#modify_ccexpirationmonth option, #modify_ccexpirationyear option").click(function() {
                 handleCCExpired('#modify_ccexpirationmonth', '#modify_ccexpirationyear', ccExpControlDate);
             });

             $.ccmanager.showremovecc ? $('.removecc').show() : $('.removecc').hide();

             $('#modify_ccbillingname').focus();

             //Close CC Modify Form
             $('.cancelsaveccrecord').click(function(event) {
                 event.preventDefault();
                 $('tr.profile_ccinfo_update').remove();
                 $.ccmanager.oncomplete(null);
                 return false;
             });

             //UPDATE CC INFO
             $('.saveccrecord').click(function(event) {

                 event.preventDefault();
                 var ccRecToUpdate = new CCRecord();
                 if ($.ccmanager.ccguestid != null) { ccRecToUpdate.ccguestid = $.ccmanager.ccguestid; };
                 ccRecToUpdate.ccid = ccrec.ccid;
                 ccRecToUpdate.ccexpmonth = $('#modify_ccexpirationmonth').val();
                 ccRecToUpdate.ccexpyear = $('#modify_ccexpirationyear').val();
                 ccRecToUpdate.ccbillingname = $('#modify_ccbillingname').val();
                 ccRecToUpdate.ccbillingaddress = $('#modify_ccbillingaddress').val();
                 ccRecToUpdate.removeccinfo = $('#removeccinfo').is(':checked')

                 ProcessCCInfoUpdate(ccRecToUpdate, ccExpControlDate);
                 return false;

             });

             return false;
         });


         //ADD NEW CC INFO
         $.ccmanager.ccnewlink = $($.ccmanager.ccnewlink);
         $.ccmanager.ccnewlink.click(function(event) {

             event.preventDefault();
             $('.profile_ccinfo_update').remove();
             clearCCForm('#guestccinfo');
             $('#guestccinfo, .addcccontrols').show();
             $('.ccexpiredmessage, .ccexpiredmessageRes').hide();

             //CC Exp Month/Year Selection Changed Handler
             var ccExpControlDate = new Date(new Date().getFullYear(), new Date().getMonth(), 1);
             if ($.ccmanager.ccexpcontroldate != null) {
                 ccExpControlDate = new Date($.ccmanager.ccexpcontroldate.substr(0, 4), $.ccmanager.ccexpcontroldate.substr(4, 2) - 1, 1);
             };

             //handleCCExpired('#creditcardexpirationmonth', '#creditcardexpirationyear', ccExpControlDate);
			$("#creditcardexpirationmonth option").click(function() {
				if ($("#creditcardexpirationyear").val() !== null && $("#creditcardexpirationyear").val() !== "") {
					handleCCExpired('#creditcardexpirationmonth', '#creditcardexpirationyear', ccExpControlDate);
				}
			});

             $("#creditcardexpirationyear option").click(function() {
                 handleCCExpired('#creditcardexpirationmonth', '#creditcardexpirationyear', ccExpControlDate);
             });
             
             $('.addccrecord').unbind('click');

             $('.addccrecord').click(function(event) {
                 event.preventDefault();
                 var ccRecToAdd = new CCRecord();
                 if ($.ccmanager.ccguestid != null) { ccRecToAdd.ccguestid = $.ccmanager.ccguestid; };
                 ccRecToAdd.ccid = 0;
                 ccRecToAdd.cctype = $('#creditcardtype').val();
                 ccRecToAdd.cctypedesc = $('#creditcardtype option:selected').text(),
                 ccRecToAdd.ccnumber = $('#creditcardnumber').val();
                 ccRecToAdd.ccexpmonth = $('#creditcardexpirationmonth').val();
                 ccRecToAdd.ccexpyear = $('#creditcardexpirationyear').val();
                 ccRecToAdd.ccbillingname = $('#ccbillingname').val();
                 ccRecToAdd.ccbillingaddress = $('#ccbillingaddress').val();
                 ccRecToAdd.removeccinfo = false;

                 ProcessNewCCInfo(ccRecToAdd, ccExpControlDate);
                 return false;
             });

             $('.canceladdccrecord').click(function(event) {
                 event.preventDefault();
                 $('#guestccinfo').hide();
                 $.ccmanager.oncomplete(null);
                 return false;
             });

             return false;

         });

         return this;

     };


     var ProcessCCInfoUpdate = function(ccRecToUpdate, ccExpControlDate) {

         // required fields validation
         var _formvalidated = true;
         var _errormessage = "";

         if (handleCCExpired('#modify_ccexpirationmonth', '#modify_ccexpirationyear', ccExpControlDate)) {
             _formvalidated = false;
             _errormessage = BE.hotelstringresources.$$MESSAGE_FILL_REQUIRED_FIELDS;
         };

         $('#ccform .errorfield').blur(function() {
             if (this.className.indexOf('regrequired') >= 0) {
                 if ($(this).val() != '') { $(this).removeClass('errorfield'); }
             }
             else { $(this).removeClass('errorfield'); }
         });

         if (_formvalidated == false) {
             $('#formError').show();
             $('#formError span').html(_errormessage);
             $($('#ccform .errorfield')[0]).focus();
             $('html, body').animate({ scrollTop: 0 }, 'fast');
             return false;
         }
         else { $('#formError').hide(); }

         $.ajax({
             type: "post",
             timeout: 30000,
             url: "be.ashx",
             contentType: "application/x-www-form-urlencoded",
             data: {
                 'cmd': 'post',
                 'psk588': 'psk588',
                 'task': 'modifyccrecord',
                 'guestccrecord': $('#guestccinfo_updateccxml_temp').parsetemplate(ccRecToUpdate),
                 'pg': 'updateguestprofile'
             },
             success: function(ajaxresult) {

                 //Check for error
                 var errorCode = JSON.parse(ajaxresult).errorcode;
                 if (typeof errorCode === "undefined") {
                     $.ccmanager.oncomplete(ccRecToUpdate);
                 }
                 else {
                     $('body').popupwarning({
                         warningheader: 'Sorry',
                         warningmessage: JSON.parse(ajaxresult).errormsg,
                         buttondisplaytext: 'Close',
                         onload: function() { showopaquelayer(); },
                         onclose: function() { hideopaquelayer(); },
                         onbuttonclick: function() { hideopaquelayer(); }
                     });
                 }

                 $('.profile_ccinfo_update').remove();
             },

             error: function(request, errorType, errorThrown) { ajaxerrorhandler(request, errorType, errorThrown); }

         });

     }; //ProcessCCInfoUpdate

     var ProcessNewCCInfo = function(ccRecToAdd, ccExpControlDate) {

         // required fields validation
         var _formvalidated = true;
         var _errormessage = "";
         $($("#guestccinfo").children()).removeClass('errorfield');

         if (!checkcreditcard($('#creditcardnumber').val(), $('#creditcardtype').val())) {
             $('#creditcardtype, #creditcardnumber').addClass('errorfield');
             _formvalidated = false;
             _errormessage = BE.hotelstringresources.$$MESSAGE_INVALID_CC;
         };

         if (handleCCExpired('#creditcardexpirationmonth', '#creditcardexpirationyear', ccExpControlDate)) {
             _formvalidated = false;
             _errormessage = BE.hotelstringresources.$$MESSAGE_FILL_REQUIRED_FIELDS;
         };

         $('#guestccinfo .regrequired').each(function() {
             if ($(this).val() == '') {
                 $(this).addClass('errorfield');
                 _formvalidated = false;
                 _errormessage = BE.hotelstringresources.$$MESSAGE_FILL_REQUIRED_FIELDS;
             }
         });

         $('#registration .errorfield').blur(function() {
             if (this.className.indexOf('regrequired') >= 0) {
                 if ($(this).val() != '') { $(this).removeClass('errorfield'); }
             }
             else { $(this).removeClass('errorfield'); }
         });


         if (_formvalidated == false) {
             $('#formError').show();
             $('#formError span').html(_errormessage);
             $($('#ccform .errorfield')[0]).focus();
             $('html, body').animate({ scrollTop: 0 }, 'fast');
             return false;
         }
         else { $('#formError').hide(); }

         $.ajax({
             type: "post",
             timeout: 30000,
             url: "be.ashx",
             contentType: "application/x-www-form-urlencoded",
             data: {
                 'cmd': 'post',
                 'psk588': 'psk588',
                 'task': 'addccrecord',
                 'guestccrecord': $('#guestccinfo_newccxml_temp').parsetemplate(ccRecToAdd),
                 'pg': 'repeatguestnewccinfo'
             },
             success: function(ajaxresult) {

                 var errorCode = JSON.parse(ajaxresult).error;

                 //Check for error
                 if (typeof errorCode !== "undefined") {

                     $('body').ajaxStop(function() { showprogress(false); });
                     $('body').popupwarning({
                         warningheader: 'Sorry',
                         warningmessage: 'Your transaction could not be processed. Please correct the required fields and try again.',
                         buttondisplaytext: 'Try Again',
                         onload: function() { showopaquelayer(); },
                         onclose: function() { },
                         onbuttonclick: function() { }
                     });

                 }
                 else {
                     ccRecToAdd.ccid = ajaxresult;
                     ccRecToAdd.ccnumber = 'xxxx-' + ccRecToAdd.ccnumber.substr(ccRecToAdd.ccnumber.length - 4);
                     $.ccmanager.oncomplete(ccRecToAdd);
                     $('#guestccinfo').hide();
                 }

             },

             error: function(request, errorType, errorThrown) { ajaxerrorhandler(request, errorType, errorThrown); }

         });

     } //ProcessNewCCInfo



     function emptyProfileTableMessage(locationID, msgContent) {

         if ($('#' + locationID + ' table tbody tr').length === 0) {
             $('#' + locationID + ' table').remove();
             $('<h3>' + msgContent + '</h3>').insertAfter('#' + locationID + ' hr');
         }

     };


     function clearCCForm(form) {

         $(':input', form).each(function() {
             var type = this.type;
             var tag = this.tagName.toLowerCase(); // normalize case

             // password inputs, and textareas
             if (type == 'text' || type == 'password' || tag == 'textarea')
                 this.value = "";

             // checkboxes and radios need to have their checked state cleared
             else if (type == 'checkbox' || type == 'radio')
                 this.checked = false;

             // select elements need to have their 'selectedIndex' property set to -1
             else if (tag == 'select')
                 this.selectedIndex = -1;
         });

     };

     $.extend({ ccmanager: {} });
 })(jQuery);

