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

(function($){

    $.fn.validateHelper = function(el, options) {

        var main_options = $.extend({}, $.fn.inputUpdater.defaults, options);
        var options = $.meta ? $.extend({}, main_options,
$this.data()) : main_options;
        return $.fn.validateHelper.validate(el, options);

    }

    $.fn.validateHelper.validate = function(el,options) { 
            var t = options.rules.split(' ');
            var val = $(el).val();
            var canSubmit = true;
            for(i=0;i<t.length;i++)
            {
                    if(t[i] == 'required') canSubmit =
$.fn.validateHelper.isRequired(val);
                    if(t[i] == 'alpha') canSubmit =
$.fn.validateHelper.isAlpha(val);
                    if(t[i] == 'numeric') canSubmit =
$.fn.validateHelper.isNumeric(val);
                    if(t[i].match(/date/gi)!=null) canSubmit =
$.fn.validateHelper.isDate(val);
                    if(t[i].match(/length/gi)!=null) canSubmit =
$.fn.validateHelper.isLength(val, t[i]);
                    if(t[i].match(/creditcarddate/gi)!=null) canSubmit
= $.fn.validateHelper.isCreditcarddate(val);
            }
        //    console.log(val+':'+canSubmit)
            return canSubmit;

        };

        $.fn.validateHelper.isRequired = function(val) {          //   console.log(val.length)
            if(val.length > 0) return true;
            else return false;
        };

        $.fn.validateHelper.isNumeric = function(val) {          //  console.log(val.match(/^\d*$/))
            if(val.match(/^\d*$/)!=null && val.match(/^\d*$/)!="") return true;
            else return false;
        };

        $.fn.validateHelper.isAlpha = function(val) { 
            if(val.match(/\w/)!=null) return true;
            else return false;
        };

        $.fn.validateHelper.isAlphaNumeric = function(val) {
             if(val.match(/\d\w/)!=null) return true;
             else return false;
        };

        $.fn.validateHelper.isDate = function(val) { 
            val = ''+val;
            if(Date.parse(val) == null) return false;
            else return true;

        };


        $.fn.validateHelper.isCreditcarddate = function(val) { 
            var today = Date.today().set({day:1});
            var future = Date.parse(''+val);
            if(Date.today().set({day:1}).compareTo(future) < 1) return true;
            else return false;

        };

        $.fn.validateHelper.isLength = function(val,len) { 
            var s = len.split('_');
            if(val.length == s[1]) return true;
            else return false;
        };

})(jQuery);


(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);
               
        }



       $.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)
       {
         //  console.log(post)
           $.ajax({
                type:'post',
                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
            {
                parent.find('div.status').children('img').attr('src',options.successImagePath);
                parent.effect("highlight",{},1000,function(){
                     $.fn.eip.convertToOriginal(parent, options, obj);
                });
               
                if($.isFunction(options.submitCallback)) options.submitCallback(parent,options,obj,data);
            }
       }

       $.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" /><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>');
       }


       $.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');
            obj.inputType = $(field).attr('type');
            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.inputType=='textarea')
                {
                    html = '<textarea rel="'+obj.validate+'" name="'+obj.name+'" id="'+obj.id+'"  msg="'+obj.errormsg+'">'+obj.originalValue+'</textarea>';
                }
            else if(obj.inputType=='checklist')
                {
                    if(!obj.originalValue.match(/<br>/)) var picks = obj.originalValue.split('\n');
                    else
                    {
                    	obj.originalValue = obj.originalValue.replace(/\n/,'');
                    	picks = obj.originalValue.split('<br>');
                   	}
                    console.log(picks);
                    html='<div class="picks" rel="'+obj.validate+'" name="'+obj.name+'" id="'+obj.id+'"  msg="'+obj.errormsg+'">';
                    
                    
                    var sobj = $.parseJSON(obj.selectField);
                  
                    var checked = '';
                    for(i in sobj)
                        {
                            checked = '';
                            for(j in picks)
                             {
                                if(sobj[i] == picks[j].replace(/'/,'')) checked = 'checked';
                             }
                           html+= '<input type="checkbox" name="'+obj.name+'SPLIT'+i+'" '+checked+' value="'+i+'" text="'+sobj[i]+'">'+sobj[i]+'<br />';
                        }
                    html+='</div>';
                   
                }
            else 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;
                 }

                 if(obj[i].inputType=='checklist')
                     {
                         value = '';
                         parent.find(':checkbox').each(function(){
                             if($(this).is(':checked')) {
                               value+= $(this).attr('text')+'<br>';
                             }
                         });
                     }

                 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 type="'+obj[i].inputType+'" 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>');
        }

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


        $.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);


