//jQuery.noConflict( )

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        var path = options.path ? '; path=' + options.path : '';
        var domain = options.domain ? '; domain=' + options.domain : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

function exitPop()
{
        window.open('http://www.providentaffiliates.co.uk/38492/paydayuk-E/left-site.html','','width=476,height=498,toolbar=no,titlebar=no,menubar=no');
}

function getLastXofMonth(x) {
  c = new Date()
  c.setMonth(c.getMonth()+1)
  c.setDate(0)
  num = 7
  while(c.toString().substring(0,2) != x.substring(0,2)) {
    c.setDate(c.getDate()-1)
    num -=1
    if(num==0)
      break
  }
  return c
}

// stick params -> cookie
if(location.search != "")
  jQuery.cookie('__MEM_search', location.search, {domain:"www.paydaynow.co.uk", path:"/" })


jQuery(document).ready(function(){

  jQuery('.input_text').blur( function() {
      jQuery("#" + this.id).css({ backgroundColor: "white" })
  })

  jQuery('select').blur( function() {
      jQuery("#" + this.id).css({ backgroundColor: "white"})
  })

  jQuery('.input_text').focus( function() {
      jQuery("#" + this.id).css({ backgroundColor: "white" })
  })

  jQuery("#dataprotection_link").click(
             function() {
              window.open(this.href, 'dataprotection',
'toolbar=0,scrollbars=yes,location=0,statusbar=0,menubar=0,resizable=0,width=500,height=640')
                 return false
             }
        )

  /****  PARAMS FORM THE URL *****/





  if(jQuery('#form1').length > 0) {
    params = jQuery.cookie('__MEM_search') || ""
    keyvals = params.split(/[?&]/)
    jQuery.each(keyvals, function(i, keyval) {
      key = keyval.split("=")[0]
      val = keyval.split("=")[1]
      if(key && val) {
        elem = jQuery('#form1 input#' + key)[0]
        if(jQuery('#form1 input#' + key).length > 0)
          elem.value = val
        else
          jQuery('#form1').append("<input id='" + key + "' name='" + key + "' type=hidden value='" + val + "' />")
      }
    })

	if($('#p').val()=="PDUK" || $('#p').val()=="STORE" || $('#p').val()=="MYPAY" || $('#p').val()=="MEM" || $('#p').val()=="PDNO"  || $('#p').val()=="PUOV2" || $('#p').val()=="MSN")
	{

		window.onunload= exitPop;
	}

  }

  jQuery('#pay_freq').bind("change", function() {
    np = jQuery('#next_pay_date')[0]
    c = new Date()
    switch(this.selectedIndex) {
      case 0:
        np.disabled = 0
        np.value = ""

        break
      case 1:
        np.disabled = 1
        c.setMonth(c.getMonth()+1)
        c.setDate(0)
        if(c.getDay() == 6) //SATURDAY
          c.setDate(c.getDate() - 1)
        else if(c.getDay() == 0) // SUNDAY
          c.setDate(c.getDate() - 2 )
        np.value = formatDate(c, "dd/MM/yyyy")
        break
      case 2:
        np.disabled = 0
        np.value = ""
        break
      case 3:
        np.disabled = 0
        np.value = ""
        break
      case 4:
        np.disabled = 1
        c = getLastXofMonth("Monday")
        np.value = formatDate(c, "dd/MM/yyyy")
        break
      case 5:
        np.disabled = 1
        c = getLastXofMonth("Tuesday")
        np.value = formatDate(c, "dd/MM/yyyy")
        break
      case 6:
        np.disabled = 1
        c = getLastXofMonth("Wednesday")
        np.value = formatDate(c, "dd/MM/yyyy")
        break
      case 7:
        np.disabled = 1
        c = getLastXofMonth("Thursday")
        np.value = formatDate(c, "dd/MM/yyyy")
        break
      case 8:
        np.disabled = 1
        c = getLastXofMonth("Friday")
        np.value = formatDate(c, "dd/MM/yyyy")
        break
    }
    np.style.backgroundColor = "white"

  })

  jQuery("#submit_f").click(function(){

    var invalid_fields = 0
    jQuery('select:visible').each(function(i) {
      col = "white"
      if(!this.disabled && !is_valid(this.value, this.id)) {
        col = "pink"
        invalid_fields += 1
      }
      jQuery("#" + this.id).css({ backgroundColor: col })
    })

    jQuery('.input_text').each(function(i) {
      col = "white"

      if(PreProcess[this.id])
        this.value = PreProcess[this.id](this.value)

      if(!this.disabled && !is_valid(this.value, this.id)) {
        col = "pink"
        invalid_fields += 1
      }


      jQuery("#" + this.id).css({ backgroundColor: col })
    })

    /*********/
    //CUSTOM
    hp = jQuery('#home_phone').get(0)
    wp = jQuery('#work_phone').get(0)
    if(!(hp.style.backgroundColor == "white" && wp.style.backgroundColor == "white") && invalid_fields==1) {
      invalid_fields=0
    }

    if(invalid_fields > 0) {
      scroll(0,0)
      jQuery('#form_invalid').fadeIn("slow")
      return false;
    } else {
      if(jQuery('#agree_to_dpa').get(0).checked) {

        alrt="Sorry, our application process requires you : \n"
        if(jQuery('#primary_income')[0].value != "FT")
          alrt += "* to be in Fulltime Employment\n"
        if(jQuery('#direct_deposit')[0].value != "0")
          alrt += "* to have Direct Deposit capability\n"
        if(jQuery('#debit_card')[0].value == "NA" || jQuery('#debit_card')[0].value == "")
          alrt += "* to have a Debit Card\n"

          jQuery('#next_pay_date2').get(0).value = jQuery('#next_pay_date').get(0).value
          jQuery('#submitting_button').css({display:'none'})
          jQuery('#submitting').css({display:'block', fontWeight:'bold', fontSize:'12px'})
          urchinTracker("/funnel/send-application.htm")// track with google,the completed application form sent to the server!
          window.onunload = "";
	  jQuery('#form1').get(0).submit()
        } else {
        alert("You must check and agree to our terms and conditions to submit this form")

      }
      return false;
    }

   })
})

var PreProcess = {
  mobile_phone: function(i) {return i.replace(/ /g, "")},
  home_phone: function(i) {return i.replace(/ /g, "")},
  work_phone: function(i) {return i.replace(/ /g, "")},
  postcode: function(i) { return i.toUpperCase() },
  monthly_pay: function(i) { return i.replace(/\.[0-9]{2}$/,"")},
  loan_amount: function(i) { return i.replace(/\.[0-9]{2}$/,"")}
	
}

var Regx = {
  email : /^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{ 1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name))$/,
  first_name : /[A-Za-z]+/,
  second_name : /[A-Za-z]+/,
  house_name : /[A-Za-z0-9 ]{1,50}/,
  work_phone : /^0[12345689][0-9]{9}$/,
  home_phone : /^0[12345689][0-9]{9}$/,
  mobile_phone : /^07[0-9]{9}$/,
  address : /[A-Za-z0-9 ]+/,
  town : /[A-Za-z ]+/,
  postcode: /(^(((GIR)\s{0,1}((0AA))))|(((X9)\s{0,1}((9AL))))|(((X9)\s{0,1}((9LF))))|(((X9)\s{0,1}((9BN))))|(([A-PR-UWYZ][0-9][0-9]?)|([A-PR-UWYZ][A-HK-Y][0-9][0-9]?)|([A-PR-UWYZ][0-9][A-HJKSTUW])|([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRVWXY]))\s{0,1}([0-9][ABD-HJLNP-UW-Z]{2})$)/,
  monthly_pay: /^[0-9]{2,10}$/,
  loan_amount: /^[0-9]{2,10}$/,
	next_pay_date: /^[0-9][0-9]\/[0-9][0-9]\/[0-9][0-9][0-9][0-9]$/


}

var Validations = {
  date_of_birth : function(x) {
    date = parseDate(x, true)
    if(date==null)
      return false
    return (date<new Date())
  },
  next_pay_date: function(x) {
    date = parseDate(x, true)
    if(date==null)
      return false
    return (date>new Date())
  },
  confirm_email: function(x) {
    return jQuery('#confirm_email').get(0).value == jQuery('#email').get(0).value
  }
}

function is_valid(value, id) {
  if(value=="") {
    Form_valid = false
    return false
  }

  if(Regx[id] && !value.match(Regx[id])) {
    Form_valid = false
    return false
  }

  if(Validations[id] && !Validations[id](value)) {
    Form_valid = false
    return false
  }

  return true
}
