"use strict";
/*globals jQuery $ window document Log ATGImageInputs */

/*
    dialogs.js
    Copyright 2010 AutoZone, Inc.
    Content is confidential to and proprietary information of
    AutoZone, Inc., its subsidiaries and affiliates.
*/

/*
  AZPro Dialogs Javascript file.

  author jbrowne
  version %PCMS_HEADER_SUBSTITUTION_START%$Id: %PM% %PR% %PRT% %PO% %PS% $%PCMS_HEADER_SUBSTITUTION_END%
*/

var Dialog = {
    commonOptions: {
        autoOpen: false,
        width: 600,
        modal: true,
        draggable: false,
        resizable: false
    }
};

$(window).load(function () {


    $('#dialog-searching-autozone-network').each(function() {
        var dialog = $(this),
            options = {};

        options = $.extend(options, Dialog.commonOptions);
        dialog.dialog(options);
    });

    $('#dialog-logout-intercept-unsaved-items').each(function() {
        var dialog = $(this);
        dialog.dialog({
            autoOpen: false,
            width: 600,
            modal: true,
            draggable: false,
            resizable: false,
            buttons: {
                "Save and Update Cart": function() {
                    dialog.dialog("close");
                    window.location.href = "/order/quote/current.jsp";
                },
                "Exit without Saving": function() {
                    // Clear the quote and then log out.
                    $.ajax({
                        type: "POST",
                        url: "/rest/bean/atg/commerce/order/purchase/CartModifierFormHandler/clearQuote/",
                        data: {},
                        success: function(response) {
                            $('#logoutForm').each(function() {
                                $(this).submit();
                            });
                        },
                        error: function(xhr) {
                            // Log out anyway.
                            $('#logoutForm').each(function() {
                                $(this).submit();
                            });
                        }
                    });
                }
            }
        });
    });


  $('#dialog-remove-category').each(function() {
        var dialog = $(this);
    dialog.dialog({
      autoOpen: false,
      width: 600,
      modal: true,
      draggable: false,
      resizable: false,
      buttons: {
        "Do Not Remove": function() {
          $(this).dialog("close");
        },
        "Remove": function() {
          var jobCategoryId = $('input#create-jobs-remove-category-id').val(),
                        selector = ['#selected-category\\:', jobCategoryId].join(''),

                        // Keep a reference to the parent so that the number of categories can be tracked. If there are zero
                        // then a redirect should probably be issued.
                        parent = $(selector).closest('div.content-section');

                    // Remove the nearest previous div.content-box-head* as well as the current selector
                    // These should both be wrapped in their own div or something for easier removal but they aren't.

                    // Also: If the previous div.content-box-head* is div.content-box-head-outer.with-buttons, then
                    // the buttons need to be preserved to the next div.content-box-head.
                    $(selector).prev('div[class^=content-box-head]:first').each(function() {
                        var div = $(this);
                        if (div.hasClass('with-buttons')) {
                            // This is a wrapper around .content-box-head-buttons and .content-box-head.
                            // A new <div> will need to be created that matches the shape of .content-box-head-outer .with-buttons.

                            // Grab the buttons and move them to the new wrapping div.content-box-head-outer
                            var buttons = div.find('.content-box-head-buttons:first');
                            div.nextAll('div[class^=content-box-head]:first').each(function() {
                                var next = $(this);
                                var wrapper = $('<div class="content-box-head-outer with-buttons">');
                                next.wrap(wrapper).before(buttons);
                            });
                        }
                    }).andSelf().remove();

                    // update the session vales for category and part types selections
                    var removeHandled = true,
                       removeCategoryUri = '/rest/bean/autozone/pro/formhandler/GenericManageJobsFormHandler/removeCategory',
                      jobCategoryId = ['removeCatId', '=', $('input#create-jobs-remove-category-id').val()].join('');

                    $.ajax({
                        url: removeCategoryUri,
                        type: 'POST',
                        data: jobCategoryId,
                        async: false, // Don't allow simultaneous requests
                        success: function(response) {

                      try {
                        var json = JSON.parse(response);
                            if (!json.atgResponse) {
                                removeHandled = false;
                            }

                      } catch (exception) { // Error in Json
                        dialog.dialog('close');
                      }

                        },
                        error: function(xhr) {
                            throw xhr.statusText;
                        }
                    });
                    if (parent.find('div[class^=content-box-head]').length === 0) {
                        // No more categories left on this page; go back to category selection
                      window.location.href = 'step1BrowseCategories.jsp';
                    }

          dialog.dialog('close');
        }
      },
          open: function(event, ui) {
              // Copy the form values from the base to the dialog.
        var jobCategoryName = $('input#create-jobs-remove-category-name').val();
        $('#category-alert').html("Are you sure you wish to remove category " + jobCategoryName + "?");
              return false;
          }
    });
  });


  $('#dialog-delete-shop').each(function() {
        var dialog = $(this);
        dialog.dialog({
      autoOpen: false,
      width: 600,
      modal: true,
      draggable: false,
      resizable: false,
      buttons: {
        "Do Not Delete": function() {
          dialog.dialog("close");
        },
        "Delete": function() {
                    // Get a reference to the form and the delete submit button. Disable the other submit buttons.
                    // Submit the form.
                    var form = $('#changeShopForm'),
                        deleteButton = $(".account-manage-shop-delete-shop-link:first");

                    ATGImageInputs.addXYPair(deleteButton);
                    $('.account-manage-make-current-shop-link').disable();
                    form.submit();
          dialog.dialog("close");
        }
      }
    });
    });

    $('#dialog-change-quantity-to-zero').each(function() {
        var dialog = $(this);
        dialog.dialog({
            autoOpen: false,
            width: 600,
            modal: true,
            draggable: false,
            resizeable: false,
            buttons: {
                'Continue': function() {
					if(!omniture.removeProduct()){
						Log.error('Unable to track customer Add To Cart via Omniture.');
					}
					dialog.dialog('close');
					$('#update-quantity').focus().click();
                },
                'Cancel': function() {
                    dialog.dialog('close');
                }
            }
        });
    });


    $('#dialog-quote-unsaved-warning').each(function() {
        var dialog = $(this);
    dialog.dialog({
      autoOpen: false,
      width: 600,
      modal: true,
      draggable: false,
      resizable: false,
      buttons: {
        "Save and Update Cart": function() {
          $(this).dialog("close");
        },
        "Continue Without Saving": function() {
          $(this).dialog("close");
        }
      }
    })
    });



  $('#dialog-exit-create-manage-jobs').each(function() {
        var dialog = $(this);
    dialog.dialog({
      autoOpen: false,
      width: 600,
      modal: true,
      draggable: false,
      resizable: false,

      buttons: {
        "OK": function() {
          var isLink = $("#isLink").val(),
              linkTarget = $("#linkTarget").val();

          if ($(this).data("form")) {
            $(this).data("form").submit();
            return false;
          }

          /* Clicked value is a link, continue to the destination */
          if (isLink == "true") {
            document.location.href = linkTarget;
          } else {
            switch (linkTarget) {
            case "search-btn-go":
              var searchButton = $("#search-btn-go");
                        ATGImageInputs.addXYPair(searchButton);
              $("#searchForm").submit();
              break;

            case "btnLogout":
              $("#logoutForm").submit();
              break;

            } //end switch
          }
          $(this).dialog("close");
        }
      }

    });
    });

    $('#dialog-admin-to-basic').each(function() {
        var dialog = $(this);
    dialog.dialog({
      autoOpen: false,
      width: 600,
      modal: true,
      draggable: false,
      resizable: false,
      buttons: {
        "Cancel": function() {
          dialog.dialog("close");
        },
        "Continue": function() {
              var form = $('#addressForm'),
                        editButton = $(".edit-user-admin-to-basic-link:first");

                    ATGImageInputs.addXYPair(editButton);
                    //form.find(':submit').disable();
                    //form.find('#demote-admin-user').enable();
                    //form.submit();

                    $('#submit-form').click();
            //$(this).dialog("close");
        }
      }

    })
    });


    $('#dialog-last-admin').each(function() {
        var dialog = $(this);
        dialog.dialog({
      autoOpen: false,
      width: 600,
      modal: true,
      draggable: false,
      resizable: false,
      buttons: {
        "OK": function() {
          dialog.dialog("close");
        }
      }

    });
    });

    $('#dialog-update-cart-no-items').each(function() {
        var dialog = $(this);
    dialog.dialog({
      autoOpen: false,
      width: 600,
      modal: true,
      draggable: false,
      resizable: false,
      buttons: {
        "Cancel": function() {
          dialog.dialog("close");
        },
        "Continue": function() {
          dialog.dialog("close");
        }
      }
    });
    });

    $('#dialog-current-quote-not-saved').each(function() {
        var dialog = $(this);
        dialog.dialog({
      autoOpen: false,
      width: 600,
      modal: true,
      draggable: false,
      resizable: false,
      buttons: {
        "Cancel": function() {
                    var dialog = $('#dialog-save-current-quote');
                    if (dialog.length == 0) {
                        dialog = $('#dialog-update-current-quote');
                    }
                    dialog.dialog('open');
                    $(this).dialog('close');
        },
        "Continue": function() {
          $(this).dialog("close");
        }
      }

    });
    });


    $('#dialog-delete-user').each(function() {
        var dialog = $(this);
        dialog.dialog({
            autoOpen: false,
            width: 600,
            modal: true,
            draggable: false,
            resizable: false,
            buttons: {
                "Cancel": function() {
                    $(this).dialog("close");
                },
                "Continue": function() {
                    // Disable all submit buttons so ATG doesn't get confused
                    var form = $('#userForm');
                    form.find(':submit').disable();
                    form.find('#delete-user').enable();
                    form.submit();
                }
            }
        });

    });


    $('#dialog-manage-vehicles-remove').each(function() {
        var dialog = $(this);
        dialog.dialog({
            autoOpen: false,
            width: 600,
            modal: true,
            draggable: false,
            resizable: false,
            buttons: {
                "Cancel": function() {
                    dialog.dialog("close");
                },
                "Continue": function() {
                    // Disable all submit buttons so ATG doesn't get confused
                    var form = $('#vehicleForm');
                    form.find(':submit').disable();
                    form.find('#delete-vehicle').enable();

                    var deleteButton = $(".manage-vehicles-remove-link:first");
                    ATGImageInputs.addXYPair(deleteButton);
                    form.submit();
                    dialog.dialog("close");
                }
            }
        });
    });

    $('#dialog-ymme-year').each(function() {
        var dialog = $(this);
        dialog.dialog({
      autoOpen: false,
      dialogClass: 'modal-wrapper',
      width: 660,
      modal: true,
      position: ['center', 100],
      draggable: false,
      resizable: false
    });
    $('#ui-dialog-title-dialog-ymme-year').html("Vehicle Selection - Year");
    });

    $('#dialog-ymme-make').each(function() {
        var dialog = $(this);
        dialog.dialog({
      autoOpen: false,
      dialogClass: 'modal-wrapper',
      width: 660,
      position: ['center', 100],
      modal: true,
      draggable: false,
      resizable: false

    });
    $('#ui-dialog-title-dialog-ymme-make').html("Vehicle Selection - Make");
    });

    $('#dialog-ymme-model').each(function() {
        var dialog = $(this);
      dialog.dialog({
      autoOpen: false,
      dialogClass: 'modal-wrapper',
      width: 660,
      position: ['center', 100],
      modal: true,
      draggable: false,
      resizable: false

    });
    $('#ui-dialog-title-dialog-ymme-model').html("Vehicle Selection - Model");
    });

    $('#dialog-ymme-engine').each(function() {
        var dialog = $(this);
        dialog.dialog({
      autoOpen: false,
      dialogClass: 'modal-wrapper',
      width: 660,
      position: ['center', 100],
      modal: true,
      draggable: false,
      resizable: false

    });
    $('#ui-dialog-title-dialog-ymme-engine').html("Vehicle Selection - Engine");
    });

    $('#dialog-ymme-vin').each(function() {
        var dialog = $(this);
        dialog.dialog({
      autoOpen: false,
      dialogClass: 'modal-wrapper',
      width: 660,
      position: ['center', 100],
      modal: true,
      draggable: false,
      resizable: false

    });
    });

    $('#dialog-save-current-quote').each(function() {
        var dialog = $(this);
        dialog.dialog({
      autoOpen: false,
      dialogClass: 'modal-wrapper',
      width: 660,
      height: 350,
      modal: true,
      draggable: false,
      resizable: false,
      buttons: {
      },
            open: function(event, ui) {
                // Copy the form values from the base to the dialog.
                var names = ['quote-name', 'quote-notes'];
                $.each(names, function() {
                    //Log.debug("Searching for ", this);
                    var selectors = {};
                    selectors.source = ['#', this].join('');

                    // There are two dialogs: one for saving a quote initially, and another for saving an already
                    // persistent quote. Since there are two the selectors need to be a class instead of an id.
                    selectors.destination = ['.dialog', this].join('-');
                    var source = $(selectors.source);
                    var destination = $(selectors.destination);

                    if (source && destination) {
                        destination.each(function() {
                            $(this).val(source.val());
                        });

                    } else {
                        Log.error("Cant find source ", source, " or destination ", destination);
                    }

                });
                dialog.find('#cancel-save-quote').click(function() {
                    dialog.dialog('close');
                });
            }
        });
    });

    $('#dialog-delete-quote').each(function() {
        var dialog = $(this);
        dialog.dialog({
            autoOpen: false,
      dialogClass: 'modal-wrapper',
      width: 660,
      height: 520,
      modal: true,
      draggable: false,
      resizable: false,
      buttons: {
                "Yes, continue delete": function() {
                    var source = dialog.data('source'); // This is the button that was clicked
                    ATGImageInputs.addXYPair(source); // Make sure it's "clicked"
                    var form = source.closest('form'); // The enclosing form
                    form.find(':image:not(.delete-quote)').remove(); // Get rid of other submit buttons
                    form.submit();
                },
                "No, return to quote": function() {
                    dialog.dialog("close");
                }
      },
            open: function(event, ui) {
                return false;
            }
        });
    });

    $('#dialog-items-are-being-added').each(function() {
        $(this).dialog({
            autoOpen: false,
            dialogClass: 'modal-wrapper',
            width: 660,
            modal: true,
            draggable: false,
            resizable: false,
            buttons: {}
        });
    });

    $('#dialog-update-current-quote').each(function() {
        $(this).dialog({
      autoOpen: false,
      dialogClass: 'modal-wrapper',
      width: 660,
      height: 520,
      modal: true,
      draggable: false,
      resizable: false,
      buttons: {
      },
            open: function(event, ui) {
                // Copy the form values from the base to the dialog.
                var names = ['quote-name', 'quote-notes', 'quote-id'];
                $.each(names, function() {
                    Log.debug("Searching for ", this);
                    var source = $(['#', this].join(''));
                    var destination = $(['#dialog', this].join('-'));
                    if (source && destination) {
                        destination.val(source.val());
                    } else {
                        Log.error("Cant find source ", source, " or destination ", destination);
                    }

                });
                return false;
            }
        });
    });

    $('#dialog-dont-delete-yourself').each(function() {
        var dialog = $(this);
        dialog.dialog({
            autoOpen: false,
            dialogClass: 'modal-wrapper',
            width: 660,
            modal: true,
            draggable: false,
            resizable: false,
            buttons: {
                'OK': function() {
                    dialog.dialog("close");
                }
            }
        });
    });

  /* Set up the links on the gateway page. */
  $('#create-jobs-remove-category-link').click(function() {
    $('#dialog-remove-category').dialog('open');
    return false;
  });

  $('.account-manage-shop-delete-shop-link').click(function() {
        $('#dialog-delete-shop').dialog('open');
    return false;
  });

  $('.edit-user-admin-to-basic-link').click(function() {
    $('#dialog-admin-to-basic').dialog('open');
    return false;
  });

  $('.edit-user-last-admin-link').click(function() {
    $('#dialog-last-admin').dialog('open');
    return false;
  });

  $('.update-cart-no-items-link').click(function() {
    $('#dialog-update-cart-no-items').dialog('open');
    return false;
  });

  $('#delete-user-link').click(function() {
        // Check to see if the user removable; i.e.: you can't delete yourself
        var form = $('#userForm'),
            radio = form.find('input:radio[name=user-administration-radio]:checked'),
            pin = radio.val(),
            username = $.trim(radio.closest('td').next('td.username').text()),
            url = '/rest/bean/autozone/pro/service/rest/UserService/isUserRemovable/',
            data = {
                arg1: username
            };

        $.ajax({
            type: 'POST',
            url: url,
            data: data,
            success: function(response) {
          var json = JSON.parse(response.atgResponse);
                if (json.removable) {
                    // The user is removable. Show the confirmation dialog.
                    $('#dialog-delete-user').dialog('open');
                } else {
                    // The user is not removable. Show an error dialog.
                    $('#dialog-dont-delete-yourself').dialog('open');
                }

            },
            error: function(xhr) {
              console.log("delete user error " + xhr);
            }
        });

    return false;
  });

  $('#current-quote-not-saved-link').click(function() {
    $('#dialog-current-quote-not-saved').dialog('open');
    return false;
  });

  $('.manage-vehicles-remove-link').click(function() {
    if ($('.check-vehicle:checked').is(':checked')) {
      $('#dialog-manage-vehicles-remove').dialog('open');
      return false;
    } else {
            var form = $('#vehicleForm');
            form.find(':submit').disable();
            form.find('#delete-vehicle').enable();
            form.submit();
    }
  });

  $('#exit-create-manage-jobs-link').click(function() {
    $('#dialog-exit-create-manage-jobs').dialog('open');
    return false;
  });

  $('#ymme-year-link').click(function() {
    $('#dialog-ymme-year').dialog('open');
    return false;
  }); // dialog found in /vehicle/ymme/overlays.jsp

  $('#ymme-make-link').click(function() {
    $('#dialog-ymme-make').dialog('open');
    return false;
  }); // dialog found in /vehicle/ymme/overlays.jsp

  $('#ymme-model-link').click(function() {
    $('#dialog-ymme-model').dialog('open');
    return false;
  }); // dialog found in /vehicle/ymme/overlays.jsp

  $('#ymme-engine-link').click(function() {
    $('#dialog-ymme-engine').dialog('open');
    return false;
  }); // dialog found in /vehicle/ymme/overlays.jsp

    $('input.update-quote:image').click(function() {
        var dialog = $('#dialog-update-current-quote');
        var link = $(this);
        dialog.dialog('open');
        // Hide this dialog and show the warning dialog when the cancel button is pressed.
        dialog.find('#cancel-save-quote').click(function() {
            dialog.dialog('close');
            var otherDialog = $('#dialog-current-quote-not-saved');
            otherDialog.dialog('open');
            return false;
        });
        return false;
    });

    $('input.delete-quote:image').click(function() {

        var source = $(this);
        $('#dialog-delete-quote').each(function() {
            $(this).data('source', source);
            $(this).dialog('open');
        });
        return false;
    });

    if ($('#emailprefs').length) {
    if($.cookie('emailPrefs') < '5') {

    $( "#emailprefs" ).dialog({
    width: 460,
    modal: true,
    title: 'Update Your Email Preferences',
    beforeClose: function(event, ui){
         $('input[name="/autozone/pro/formhandler/UpdateEmailPreferencesFormHandler.userPrefs"]').attr('checked', false);
         $('#emailPrefsForm').submit();
         }
    });

   if( $.cookie('emailPrefs') == null){
     var emailPrefsAttempts = 0;
   } else {
    var emailPrefsAttempts = parseInt($.cookie('emailPrefs'));
   };
    emailPrefsAttempts =  emailPrefsAttempts + 1;
    $.cookie('emailPrefs', emailPrefsAttempts , { expires: 365 });

    };
    }

/*	$('#vin-decoder-link').click(function() {
    $('#dialog-ymme-vin').dialog('open');
    return false;
  }); // dialog found in /vehicle/ymme/overlays.jsp
*/
});

