//requires jquery 1.26+, jquery.globalplugins, jqueryformplugins

(function ($) {
    var m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        s = {
            'array': function (x) {
                var a = ['['], b, f, i, l = x.length, v;
                for (i = 0; i < l; i += 1) {
                    v = x[i];
                    f = s[typeof v];
                    if (f) {
                        v = f(v);
                        if (typeof v == 'string') {
                            if (b) {
                                a[a.length] = ',';
                            }
                            a[a.length] = v;
                            b = true;
                        }
                    }
                }
                a[a.length] = ']';
                return a.join('');
            },
            'boolean': function (x) {
                return String(x);
            },
            'null': function (x) {
                return "null";
            },
            'number': function (x) {
                return isFinite(x) ? String(x) : 'null';
            },
            'object': function (x) {
                if (x) {
                    if (x instanceof Array) {
                        return s.array(x);
                    }
                    var a = ['{'], b, f, i, v;
                    for (i in x) {
                        v = x[i];
                        f = s[typeof v];
                        if (f) {
                            v = f(v);
                            if (typeof v == 'string') {
                                if (b) {
                                    a[a.length] = ',';
                                }
                                a.push(s.string(i), ':', v);
                                b = true;
                            }
                        }
                    }
                    a[a.length] = '}';
                    return a.join('');
                }
                return 'null';
            },
            'string': function (x) {
                if (/["\\\x00-\x1f]/.test(x)) {
                    x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                        var c = m[b];
                        if (c) {
                            return c;
                        }
                        c = b.charCodeAt();
                        return '\\u00' +
                            Math.floor(c / 16).toString(16) +
                            (c % 16).toString(16);
                    });
                }
                return '"' + x + '"';
            }
        };

	$.toJSON = function(v) {
		var f = isNaN(v) ? s[typeof v] : s['number'];
		if (f) return f(v);
	};

	$.parseJSON = function(v, safe) {
		if (safe === undefined) safe = $.parseJSON.safe;
		if (safe && !/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(v))
			return undefined;
		return eval('('+v+')');
	};

	$.parseJSON.safe = false;

})(jQuery);



(function($) {



        $.fn.eip = function(options) {

        var main_options = $.extend({}, $.fn.eip.defaults, options);



            return this.each(function() {
                $this = $(this);
                 // if metadata is present, extend main_opts, otherwise just use main_opts
                var options = $.meta ? $.extend({}, main_options, $this.data()) : main_options;

               $.fn.eip.setEvents(this,options);

            });
        };


        $.fn.eip.setEvents = function(el,options)
        {
            $(el).unbind().mouseover(function(){
                    $.fn.eip.mouseover(this,options);
                }).mouseout(function(){
                    $.fn.eip.mouseout(this,options);
                }).click(function(){
                    $.fn.eip.click(this,options);
                    return false;
                });
        }


        $.fn.eip.click = function(el,options)
        {
            var obj = {};
            var inputCount = 0;
            var parent = $(el).parents(options.parentElement);
            $.fn.eip.mouseout(el,options);
            parent.find('span').each(function(){
                obj[inputCount] = $.fn.eip.convertToInputs(el,options,this);
                inputCount++;
            })

            /*parent.mouseover(function(){
                       $.fn.eip.clearTimer(parent)
                  })
                  .mouseout(function(){
                       $.fn.eip.setTimer(parent,options,obj);
                  });*/



            //if only one input, add the save button after the input field

                    for(i in obj)
                    {
                        if(i==0)
                        {
                            var save = '<a href="#" class="save" id="save_'+obj[i].idNum+'">';
                            if(options.saveButton!=null) save+='<img src="'+options.saveButton+'" />';
                            else save+= options.saveText;
                            save+='</a>';
                           // console.log(save)
                        }

                    }
                   // console.log(obj[i].id);
                     if(inputCount==1) $("#"+obj[i].id).after(save);
                     else parent.append('<li class="li_save">'+save+'</li>');

                     $.fn.eip.save(parent,options,obj);
             return false;
        }



       $.fn.eip.prepareSubmit = function(parent,options,obj)
       {
           var post = {};
           for(i in obj)
           {
               post[obj[i].name] = obj[i].newValue;
               if(options.actionType!='insert')
                {
                    var sid = obj[i].id.split('_');
                    post['id'] = sid[2];
                }
           }
           post['action'] = options.actionType;
           if(options.page!=null) post['action'] = post['action'] + '_' + options.page;

           //add any extra fields that may have been created (usually checkboxes or radio buttons
           parent.find('input:checkbox,input:radio').each(function(){
               if($(this).is(':checked'))
               {
                    var name = $(this).attr('name');
                    var value = $(this).val();
                    post[name] = value;
               }
           });

           $.fn.eip.doSubmit(parent,options,obj,post);
       }


       $.fn.eip.doSubmit = function(parent,options,obj,post)
       {
           var d = getDomain();
         // alert(post)
           $.ajax({
                url: '/'+options.submitPath,
                data:post,
                dataType: options.dataType,
				success: function (data, textStatus) {
                    $.fn.eip.responseSuccess(parent,options,obj,data)
                },
				error: function(XMLHttpRequest, textStatus, errorThrown){
                    $.fn.eip.responseError(parent,options)
                },
				beforeSend: function (XMLHttpRequest) {
                    $.fn.eip.ajaxLoading(parent,options)
                },
				complete: function (XMLHttpRequest) {
                    $.fn.eip.ajaxComplete(parent,options)
                }
			});
       }


       $.fn.eip.responseSuccess = function(parent,options,obj,data)
       {
          if(data.success==false)
            {
                $.fn.eip.jsonFail(parent,options,obj,data);
            }
            else if(data.success=='moreInfo')
            {
                $.fn.eip.custom(parent,options,obj,data);
            }
            else
            {
                parent.find('div.status').children('img').attr('src',options.successImagePath);
                parent.effect("highlight",{},2000,function(){
                     $.fn.eip.convertToOriginal(parent, options, obj);
                });

                if($.isFunction(options.submitCallback)) options.submitCallback(parent,options,obj,data);
            }
       }

       $.fn.eip.custom = function(parent,options,obj,data) //this function is custom for bocajava
       {
           var y = new Array();
           var type="billing";
           if(data.ccs!=null)
           {
               var z = {};
               z.shipToId = data.shipToId;

               for(i in data.ccs){
                 y[i] = data.ccs[i];
               }
               z.ccs = y;
               type="shipping";
           }

           if(data.shiptos!=null)
           {
               var z = {};
               z.ccId = data.ccId;

               for(i in data.shiptos){
                 y[i] = data.shiptos[i];
               }
               z.shiptos = y;
           }

            var html = '<li class="new_address" style="width:100%"><ul class="fv alert"><li class="cb" style="width:95%;"><input type="checkbox" name="changeAddresses" id="f_changeAddresses" value="true" /><label>A '+type+' address was found that matches your old address. Check this box if you would like to update it.</label></li></ul></li>';
                    if(parent.find('div.alert').length == 0) {
                        parent.children('li.li_save').before(html);
                        parent.find('div.status').remove();
                    }

       }

       $.fn.eip.jsonFail = function(parent,options,obj,data)
        {

            if(data.error == "Address not found")
                {
                  //  $this.siblings('div.status').html('<img class="error_btn" title="there has been an error updating the database. please try again" src="'+options.errorImagePath+'"  />')
                    var html = '<li class="address_not_found" style="width:100%"><ul class="fv alert"><li class="cb" style="width:95%;"><input type="checkbox" name="overrideAddress" id="f_overrideAddressFailure" value="true" style="width:25px;"/><label>This address was not found in the USPS database. Please check this box and resubmit if you would like to use this address.</label></li></ul></li>';
                    if(parent.find('div.alert').length == 0) {
                        parent.children('li.li_save').before(html);
                        parent.find('div.status').remove();
                    }
                }
            else
                {
                    $.fn.eip.responseError(parent,options,data);
                }
        }

       $.fn.eip.responseError = function(parent,options,data)
       {
           //make this a modal dialogue error;
           if(data)
               {
                   var error = data.error;
               }
           else error = 'There has been a problem. Please try again.';
           parent.find('div.status').remove();
           parent.find('a.save').after('<div class="status tooltip" title="'+error+'"><img src="'+options.errorImagePath+'"  /></div>');
           //$(".tooltip").unbind().simpletooltip({cssClass:'tt_invalid'});
       }


       $.fn.eip.save = function(parent,options,obj)
       {
           for(i in obj)
           {
               if(obj[i].errormsg=='' ||obj[i].errormsg==null) obj[i].errormsg="This field is required";
           }


           parent.find('a.save').unbind().click(function(){
              //fields are ready to save - collect key/value pairs, validate data, and send to ajax function
              var e = 0;
              parent.find('div.status').remove();
              for(i in obj)
              {
                  var valid = true;
                  var $this = obj[i];
                  var value = $("#"+$this.id).val();
                  if($this.validate!=undefined) valid = $.fn.validateHelper("#"+$this.id,{rules:$this.validate})
                  if(!valid)
                      {
                          e++;
                          $.fn.eip.fieldError(parent,options,$this)
                      }
                  else  $this.newValue = value;
              }

              if(e==0) $.fn.eip.prepareSubmit(parent,options,obj);
              return false;

           });



           $(document).bind('keydown', 'return', function(){
                            $('a.save').trigger('click');
           });

       }

       $.fn.eip.fieldError = function(parent,options,obj)
       {
           var msg = obj.errorMessage;
           $("#"+obj.id).after('<div class="status tooltip" title="'+msg+'"><img src="'+options.errorImagePath+'"  /></div>');
           $(".tooltip").unbind().simpletooltip({cssClass:'tt_invalid'});
       }


        $.fn.eip.convertToInputs = function(el,options,field)
        {
            var obj = {};
            var parent = $(el).parents(options.parentElement);
            obj.originalValue = $(field).html();
            obj.id= $(field).attr('id');
            var nameS = obj.id.split('_');
            obj.name = nameS[1];
            obj.idNum = nameS[2];
            obj.selectField = $(field).attr('sel');
            obj.validate = $(field).attr('rel');
            obj.errormsg = $(field).attr('msg');
            obj.field = field;

            var html = '<input type="text" sel="'+obj.selectField+'" rel="'+obj.validate+'" name="'+obj.name+'" value="'+obj.originalValue+'" id="'+obj.id+'"  msg="'+obj.errormsg+'" />';
            if(obj.selectField!="undefined" && obj.selectField!=undefined && obj.selectField != '')
                {
                    html = '<select sel="'+obj.selectField+'" rel="'+obj.validate+'" name="'+obj.name+'" id="'+obj.id+'" msg="'+obj.errormsg+'">';

                    var sobj = $.parseJSON(obj.selectField);


                    for(i in sobj)
                        {
                            html+='<option value="'+i+'">'+sobj[i]+'</option>';
                        }
                    html+='</select>';
                }

                 $(obj.field).before(html).remove();

                 $("#"+obj.id).keyup(function(){
                      $.fn.eip.clearTimer(parent);
                 })

           return obj;
        }


        $.fn.eip.convertToOriginal = function(parent,options,obj)
        {
            $.fn.eip.clearTimer(parent);
            //clear status messages when originals return
            parent.find('div.status').remove();
            parent.children('li.li_save,li.address_not_found').remove();

            for(i in obj) //loop through each affected field
            {
                //console.log($('#'+obj[i].id).parents(options.parentElement))

                 $('#'+obj[i].id).parents(options.parentElement);
                 var value = obj[i].originalValue;
                 if(obj[i].newValue!=null){

                    if(obj[i].selectField!="undefined" && obj[i].selectField!=undefined && obj[i].selectField != '')
                    {
                        var sobj = $.parseJSON(obj[i].selectField);
                        value = sobj[obj[i].newValue];
                    }
                    else value = obj[i].newValue;
                 }
                 var id= obj[i].id;
                 var nameS = id.split('_');
                 var name = nameS[1];
                 var selectField = obj[i].selectField;
                 var rel = obj[i].validate;
                 var msg = obj[i].errormsg;
                 var html = '<span sel="'+obj[i].selectField+'" rel="'+obj[i].validate+'" id="'+obj[i].id+'" msg="'+obj[i].errormsg+'">'+value+'</span>';

                 $('#'+obj[i].id).siblings('a.save').remove();
                 $('#'+obj[i].id).siblings('div.status').remove();
                 $('#'+obj[i].id).before(html).remove();
                 $("#"+obj[i].id).unbind().mouseover(function(){
                            $.fn.eip.mouseover(this,options);
                        }).mouseout(function(){
                            $.fn.eip.mouseout(this,options);
                        }).click(function(){
                            $.fn.eip.click(this,options);
                            return false;
                        });
            }

        }

        $.fn.eip.mouseover = function(el,options)
        {
              var o = $(el).offset();
              var w = $(el).width();
              var h = $(el).height();

              var html = '<div id="editImg"></div>';
              $("body").append(html);
              $('#editImg').ifixpng().css({
                    top: (o.top-32),
                    left: (o.left-20)
              }).fadeIn(500);
        }

        $.fn.eip.mouseout = function(el,options)
        {
            $("#editImg").remove();
        }

        $.fn.eip.ajaxLoading = function(parent,options)
        {
           // $(".iu_validate_error").remove();
           // parent.find('a.save').after('<div class="status"><img src="'+options.loadingImagePath+'" /></div>');
           var el = parent.find('a.save');
           ajaxicator(el);
        }

        $.fn.eip.ajaxComplete = function(parent,options)
        {
            //var $this = $(el);
         //   if($this.siblings('div.status').html()!=null) $this.siblings('div.status').remove();
          	var el = parent.find('a.save');
           	ajaxicator(el,'off');
        }


        $.fn.eip.defaults = {
            parentElement: '.ed',
            element:'span',
            saveText:'save',
            page: null,
            dataType: 'json', //how form submit data is returned - same params as jquery ajax object http://docs.jquery.com/Ajax/jQuery.ajax#options
            errorMessage: 'this field is required',
            actionType: 'update', //action taken by SQL
            submitSuccessMessage: null, //message for users when form submission succeeds
  			submitCallback: null, //callback function for submit
            presubmitCallback: null, //callback function for use before the submit - good for specialty validation
  			loadingImagePath: 'images/ajax-loader.gif', //location of loading animated gif
            errorImagePath: 'images/indicator_error.gif', //location of loading animated gif
            successImagePath: 'images/indicator_success.gif', //location of loading animated gif
            select:''
        };


       $.fn.eip.setTimer = function(el,options,obj) {
                    $.fn.eip.clearTimer(el);
			     	$(el).oneTime(2000,"timer_",function () {

                        $.fn.eip.convertToOriginal(el,options,obj)

			      	});

				}

		$.fn.eip.clearTimer = function(el){
					$(el).stopTime('timer_');
				}


        function debug($obj) {
          if (window.console && window.console.log)
            window.console.log($obj);
        };

    })(jQuery);


function runInPlace(page)
{
   $(".actions li span").eip({
           page:page,
           submitPath:'ShipToAjaxAction.do',
           loadingImagePath:'/bocajava/images/2009/loading_small.gif',
           errorImagePath:'/bocajava/images/2009/indicator_error.gif',
           successImagePath:'/bocajava/images/2009/indicator_success.gif'
      });


   //   $("#logo").simpletooltip({cssClass:'tt_invalid'});


   var ccType = {
       'AE':'American Express',
       'DI':'Discover',
       'MC':'MasterCard',
       'VI':'Visa'
   }

   var resType = {
       'R':'Residence',
       'C':'Office',
       'B':'P.O Box'
   }

    var accountType = {
       'C':'Checking',
       'S':'Savings',
       'X':'Corporate Checking'
   }



   function startRunning(page)
   {

   //$(".actions li span").eip();
/*
   $(".editable li span").unbind().mouseover(function(){
      active(this);
   }).mouseout(function(){
       $("#editImg").remove();

   }).click(function(){

       var $this = $(this);
       var theparent = $this.parent('div');
       var id = $this.attr('id');


       var thegrandparent = $this.parents('ul');
       if(thegrandparent.attr('class').match(/group/gi) !=null)
          {
                var headoftable = thegrandparent;
                var endoftable = headoftable.children('li').children('div').children('span')
                var validation = '';
                var errormsg = '';
          }
       else
           {
               var headoftable = theparent;
               var endoftable = headoftable.children('span')
           }

       clearTimer(headoftable,id);
       clearInputs(headoftable,id);

       var size = endoftable.length;
       endoftable.each(function(){
           var $this = $(this);
           var save = '';
           var id = $this.attr('id');
           var n = id.split('_');
           var name = n[1];
           var type='text';
           validation = $this.attr('rel');
           errormsg = $this.attr('msg');
             if($this.siblings('label').attr('type')!=null) type = $this.siblings('label').attr('type');
              var hidden = '<div class="hidden">'+$this.html()+'</div>';
              if(type=='text') var input = '<input msg="'+errormsg+'" rel="'+validation+'" type="text" name="'+name+'" id="'+id+'" value="'+$this.html()+'">';
              else if(type=='select')
               {
                   var input = '<select name="'+name+'" id="'+id+'" msg="'+errormsg+'" rel="'+validation+'">';
                   if(name=='typeName') var atype = ccType;
                   else if(name=='ectype')
                       {
                           atype = accountType;
                       }
                   else atype = resType;

                           for(i in atype)
                                {
                                    if($this.html()==atype[i]) var selected='selected';
                                    else var selected = '';
                                    input+='<option value="'+i+'" '+selected+'>'+atype[i]+'</option>';
                                }

                input+='</select>';
               }
               if(size==1) var save = ' <a href="#" class="save">save</a>';

               $this.unbind();
               $("#editImg").remove();


             var thisparent = $this.parent('div');

             thisparent.append(hidden+input+save);
             $this.remove();
          });

      if(size>1)
      {

          var saveHTML = '<li class="saveBTN"><a href="#" class="insert">save</a></li>';
         headoftable.append(saveHTML)

          $(".saveBTN").unbind().mouseover(function(){
               clearTimer(headoftable,id);
          });

      }




       prepareSave(headoftable,id, validation,errormsg,page);

       headoftable.unbind().mouseover(function(){
           clearTimer(headoftable,id)
       }).mouseout(function(){
           setTimer(headoftable,id)
       });

       $("#"+id).unbind().focus(function(){
           clearTimer(headoftable,id)
       }).keyup(function(){
           clearTimer(headoftable,id)
       });
       */

      //if all fields are in a list item, then overall parent is the UL - this is where ID should be pulled from
      //var parent = $(this).parents('.editable');

  // });
   }




    function setTimer(el,id) {
			     	el.oneTime(1000,"timer_"+id,function () {
                 //       console.log('here')
                        clearInputs(el,id);

			      	});

				}

    function clearTimer(el,id){
					el.stopTime('timer_'+id);
				}

   function clearInputs(el,id, submit)
   {

         $(".iu_validate_error").remove();
         $(".address_not_found").remove();

       if(el.attr('class').match(/group/gi)!=null)
           {
               var endoftable = el.children('li').children('div').children(':input');
           }
       else
           {
               var endoftable = el.children(':input');
               if(endoftable.length==0) endoftable = el.children('div').children(':input');
           }

        el.siblings('div.saveBTN').remove();
        endoftable.each(function(){
            var id = $(this).attr('id');
            var field = 'select';
            if(submit==undefined) submit = false;
            var $this =  $("select#"+id);
            if($this.length==0) {
                $this = $("input#"+id);
                field = 'input';
            }
            var id =  $this.attr('id');
            var rel = $this.attr('rel');
            var msg = $this.attr('msg');



            var val = $this.val();
            if(field=='select')
                {
                    $this.children('option').each(function(){
                       if($(this).attr('value')== val) val = $(this).html();
                    });
                }
            var text = $this.prev().html();
            var displaytext = text;
            if(submit && val!=text) {
                 //console.log(text+";"+val+";"+displaytext)
                var tag = $this.siblings('label').html();
                tag = tag.replace(/:/gi,'');
                displaytext = val;
                addNotice('You have updated the value of <b>'+tag+'</b> to <b>'+displaytext+'</b>');
                //$(document).unbind('keydown', 'return');
            }

 //console.log(text+";"+val+";"+displaytext)
            $this.next().remove();
            $this.prev().remove();

            var replace = '<span id="'+id+'" rel="'+rel+'" msg="'+msg+'">'+displaytext+'</span>';

            $this.after(replace).remove();

        });

            startRunning(page);

   }

   function active(el)
   {
      var o = $(el).offset();
      var w = $(el).width();
      var h = $(el).height();

      var html = '<div id="editImg"></div>';
      $("body").append(html);
      $('#editImg').ifixpng().css({
            top: (o.top-32),
            left: (o.left-20)
      }).fadeIn(500);
   }

   function prepareSave(el,id, validation,msg,page)
   {
       if(msg=='' ||msg==null) msg="This field is required";
        //jquery hotkeys

      $("a.save").eip({
           valueType:validation,
           errorMessage:msg,
           submitPath:'ShipToAjaxAction.do',
           loadingImagePath:'/bocajava/images/2009/loading_small.gif',
           errorImagePath:'/bocajava/images/2009/indicator_error.gif',
           successImagePath:'/bocajava/images/2009/indicator_success.gif',
           actionType:'update_'+page,
           parent:'li',
           presubmitCallback: function(el,parent,options){
                var theparent = $("#"+id).parent('div');
                theparent.unbind();
                clearTimer(theparent,id);
                return true;
              //  return validate_selection_count(parent,'delete');

           },
           submitCallback: function(el,parent,options,data){
              //  var val = $("#"+id).val();
              //  console.log(val)
              //  $("#"+id).prev().html(val);

                clearInputs(parent,id,true);


           }
       });


       $("a.insert").eip({
           valueType:'',
           errorMessage:'',
           submitPath:'ShipToAjaxAction.do',
           loadingImagePath:'/bocajava/images/2009/loading_small.gif',
           errorImagePath:'/bocajava/images/2009/indicator_error.gif',
           successImagePath:'/bocajava/images/2009/indicator_success.gif',
           actionType:'update_'+page,
           parent:'ul',
           presubmitCallback: function(el,parent,options){

                headoftable.unbind();
                clearTimer(headoftable,id);
                return true;
              //  return validate_selection_count(parent,'delete');

           },
           submitCallback: function(el,parent,options,data){
              //  var val = $("#"+id).val();
               // console.log(parent)
              //  $("#"+id).prev().html(val);

                clearInputs(parent,id,true);


           }
       });

   }

   $(document).bind('keydown', 'return', function(){
           $("a.save").trigger('click');
   });

   startRunning(page);
}
