// IE console path & easy way to turn on and off
var debugging = true;
if (typeof console == "undefined") { var console = { log: function() {} }; } else if (!debugging || typeof console.log == "undefined") { console.log = function() {}; }

function tacform(id) {
  if (function_exists('tacform_submit_action')) {
	  var submit = tacform_submit_action(id);
	  if (submit == false){
		  return false;
	  }	  
  }
  
  $.post('/ajax/validate',$("#"+id).serialize(),
    function(responseXML) {
      $("#"+id+"error_text").html("");

      if ($("isvalid",responseXML).text() == "passed") {
        // remove onsubmit and submit form
        $("#"+id).removeAttr("onsubmit").submit();
        //$("#formsubmitbutton")
      } else {
        $("#"+id+"_error_text").html($("text",responseXML).text());
      }
    },'xml');

  return false;
}

jQuery.cookie=function(d,c,a){if(!d&&!c){d={};c=document.cookie.split(";");var b="",e="";b="";for(a=0;a<c.length;a++){b=c[a].split("=");e=jQuery.trim(b[0]);b=b.length>1?decodeURIComponent(jQuery.trim(b[1])):null;d[e]=b}return d}if(typeof c!="undefined"){a=a||{};if(c===null){c="";a.expires=-1}b="";if(a.expires&&(typeof a.expires=="number"||a.expires.toUTCString)){if(typeof a.expires=="number"){b=new Date;b.setTime(b.getTime()+a.expires*24*60*60*1E3)}else b=a.expires;b="; expires="+b.toUTCString()}e=
a.path?"; path="+a.path:"";var f=a.domain?"; domain="+a.domain:"";a=a.secure?"; secure":"";document.cookie=[d,"=",encodeURIComponent(c),b,e,f,a].join("")}else{e=null;if(document.cookie&&document.cookie!==""){c=document.cookie.split(";");for(a=0;a<c.length;a++){b=jQuery.trim(c[a]);if(b.substring(0,d.length+1)==d+"="){e=decodeURIComponent(b.substring(d.length+1));break}}}return e}};

function test_field_value(a,b,c){if($("#"+a).val()==""){$("#"+a+"-error").show();return false}if(c==true)if(/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/.test($("#"+a).val())!=true){$("#"+a+"-error").show();return false}return b}
function validateEmail(a){return/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/.test(a)};

$(document).ready(function(){
  $('#id_billing').hide();
  $('#id_cc_billing_chk').click(function() {
    $('#id_billing').slideToggle('fast');
  });
  
  /* new form processing */
  
  $("#newformmainform").submit(function() {
    var rtn = false;
    
    $("#newformprocessbtn").attr('disabled','disabled').addClass('disabled');
    
    $("#error_messages").html(""); /* clear any errors that might be in there now */
    
    /* if my billing matches my regular info then copy it over */
    var copyccary = ['firstname','lastname','address','city','state','zip','phone','email'];
    if ($('#new_cc_billing_chk').is(':checked')) {
      for(var i = 0;i < copyccary.length;i++) {
        $('#cc' + copyccary[i]).val($('#' + copyccary[i]).val());
      }
    }
      
    var isgood = $("#newformmainform").dmvalidate(); /* call my new validator */

    /* if ccamount contains a value then we must have a credit card run those validations */
    if ($("#ccamount").length > 0) {
      if ($("#ccamount").val() != '') {
        var rtnjson = {};
        var data = {};
        data.cctype = $("#cctype").val();
        data.ccnum = $("#ccnumber").val();
        data.ccccv = $("#ccccv").val();
        data.ccexpmth = $("#ccexpmth").val();
        data.ccexpyr = $("#ccexpyr").val();
    
        jQuery.ajax({
          cache: false,
          type: 'POST',
          async: false,
          timeout: 6000,
          url: '/main/credit-card-verification',
          dataType: 'json',
          data: data,
          success: function (ajaxjson) {
            rtnjson = ajaxjson;
          },
          error: function(jqXHR, textStatus, errorThrown) {
            console.log(jqXHR,textStatus,errorThrown);
          }
        });
        
        if (isgood) {
          isgood = rtnjson.isgood;
        }
        
        $("#error_messages").append(rtnjson.errors);
      }
    }

    /* did I create a newform_submit_action if so call it */
    if (function_exists('newform_submit_action')) {
      isgood = newform_submit_action(isgood);
    }
    
    /* finally submit it or not */
    if (isgood) {
      rtn = true;
    } else {
      $("#newformprocessbtn").removeAttr('disabled').removeClass('disabled');
    }
    
    return rtn;
  });
  
  $('#newformmainform [filter]:visible').each(function(index) {
    var filter = $(this).attr('filter');
    if (filter !== undefined) {
      $(this).keyallow(filter);
    }
  });
  
  $('#new_cc_billing_chk').click(function() {
    $('#new_billing').slideToggle('slow'); // hide it
  });
  
});

/* jquery wrapper */
(function($) {
  $.fn.dmvalidate = function(submit){
    return dmvalidate.form($(this).attr("id"),submit);
  };
})(jQuery);

/* my function */
var dmvalidate = {
  form: function(formname,submit) {
    submit = (!submit) ? false : submit;
    var errors = '';
    $('#'+formname+' [needed]:visible').each(function(index) {
      var field_value = $(this).val();
      var field_name = ($(this).attr("human") === undefined) ? $(this).attr("name") : $(this).attr("human");
      var validation = $(this).attr("validation");

      if (field_value === "") {
        errors += '<div>' + field_name + ' required</div>';
      } else if (validation !== undefined && field_value !== "") {
        var err = '';
        switch(validation) {
          case 'email':
            var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
            err = (field_value.match(re)) ? '' : 'Formatted Incorrectly';
          break;
          case 'city':
            var re= /^[a-zA-Z\s,]{2,64}$/
            err = (field_value.match(re)) ? '' : 'Formatted Incorrectly';
          break;
          case 'phone':
            var re = /^[0-9x -\.\(\)]{7,20}$/
            err = (field_value.match(re)) ? '' : 'Formatted Incorrectly';
          break;
          case 'zip':
            var re= /(^\d{5}$)|(^\d{5}[\- ]\d{4}$)/g
            err = (field_value.match(re)) ? '' : 'Formatted Incorrectly';
          break;
          case 'float':
            var re= /^([1-9]\d*(\.|\,)\d*|0?(\.|\,)\d*[1-9]\d*|[1-9]\d*)$/gm
            err = (field_value.match(re)) ? '' : 'Formatted Incorrectly';
          break;
          case 'integer':
            var re= /^\d*$/gm
            err = (field_value.match(re)) ? '' : 'Formatted Incorrectly';
          break;
          case 'number':
            var re= /^([1-9]\d*(\.|\,)\d*|0?(\.|\,)\d*[1-9]\d*|[1-9]\d*)$/gm
            err = (field_value.match(re)) ? '' : 'Formatted Incorrectly';
          break;
          case 'money':
            var re=  /((^\$?(([0-9]{0,1})?\.[0-9]{1,2}))|(^\$?([1-9]{1}[0-9]{0,2}([,][0-9]{3})*)(\.[0-9]{1,2})?))/g
            err = (field_value.match(re)) ? '' : 'Formatted Incorrectly';
          break;
          case 'captcha':
            err = dmvalidate.captcha(field_value);
          break;
        }
        if (err !== '') {
          errors += '<div>' + field_name + ' ' + err + '</div>';
        }
      }
    });

    $("#error_messages").append(errors);

    if (submit && errors === '') {
      $("#"+formname).submit();
    }

    return (errors === '');
  },
  
  captcha: function(field) {
    var rtnjson = {};
    var err = '';

    json = {};
    json.captcha_input_field = $("#captcha_input_field").val();
    json.captcha_input_hidden = $("#captcha_input_hidden").val();
    json.check = true;

    jQuery.ajax({
      cache: false,
      type: 'POST',
      async: false,
      timeout: 6000,
      url: '/captchanew/captcha.php',
      dataType: 'json',
      data: json,
      success: function (ajaxjson) { rtnjson = ajaxjson; },
      error: function(jqXHR, textStatus, errorThrown) { console.log(jqXHR,textStatus,errorThrown); }
    });

    if (!rtnjson.isgood) {
      err = 'Incorrect';
    }

    return err;
  }
};

function function_exists(function_name) {
  if (typeof function_name == 'string') {
    return (typeof this.window[function_name] == 'function');
  } else {
    return (function_name instanceof Function);
  }
}

(function($){
  $.fn.keyallow = function(a) {
    var allow = a + String.fromCharCode(0) + String.fromCharCode(8); /* tab & delete */
    return this.each (
      function() {
        $(this).keypress(
          function (e) {
            if (!e.charCode) k = String.fromCharCode(e.which);
            else k = String.fromCharCode(e.charCode);
            
            if (allow.indexOf(k) == -1) e.preventDefault();
            if (e.ctrlKey && k=='v') e.preventDefault();
          }
        );
        $(this).bind('contextmenu',function () {return false});
      }
    );
  };
})(jQuery);

