var Remove_Links = {

	links: jQuery("a[href='']:not([name])"),
	
	initialize: function() {
	
		var self = Remove_Links;
	
		if (!self.links.length) {
			return false;
		}
		
		self.links.remove();
	
	}

}
Remove_Links.initialize();

var Forms = {
  initialize: function() {
    this.addValidationRules();
    this.formValidate();
  },

  addValidationRules: function() {

    jQuery.validator.addMethod("title", function(value, element, params) { 
      return value != 0;
    }, "<br/>Please select your Title");

	jQuery.validator.addMethod("dob", function(value, element) { 
	  
		var name = element.name.split("[");
		
		if (name.length === 2) {
			name = name[0];
		}
		else {
			return true;
		}
			
		var day = parseFloat(jQuery("*[name='" + name + "[d]']").val());
		var month = parseFloat(jQuery("*[name='" + name + "[m]']").val())
		var year = parseFloat(jQuery("*[name='" + name + "[y]']").val())
		
		if (day === "" || month === "" || year === "") {
			return true;
		}
		
		if (isNaN(day) || isNaN(month) || isNaN(year)) {
			return true;
		}
		
		var y = parseInt(year / 4) * 4; 
		
		var error_31 = day === 31 & (month === 2 || month === 4 || month === 06 || month === 09 || month === 11);
		var error_29 = day === 29 & month === 2 & year !== y; 	
		
		if (error_31) {
			return false;
		}
		
		if (error_29) {
			return false;
		}
		
		return true;
	 
	}, "Please specify a correct date");

  },

  formValidate: function() {
    jQuery("form").each(function() { 
      jQuery(this).validate(); 
    });
  }
}

Forms.initialize();

var TheSource = {

  initialize: function() {

    var param = this.getParam("theSource");
    var override = this.getParam("Override")
    var hear = jQuery("#hear-about-us");
    var cookie = this.getCookie("theSource");
    var self = TheSource;

    if(param != "") {
      if(cookie == "" || override == "1") {
        this.setCookie("theSource", param, 90, "/", ".hl.co.uk", "");
      }
    }

	if(typeof(client_details) !== "undefined" && client_details !== "") {
      	this.setCookie("theSource", "WWWLI", 90, "/", ".hl.co.uk", "");
    }

    cookie = this.getCookie("theSource");

    if(cookie != "")
    {
      jQuery("#hear-about-us").hide();
	  jQuery(".theSource_1").append("<option value='" + cookie + "'>" + cookie + "</option>");
      jQuery(".theSource_1 option:last").attr("selected", "true");
    }

    if(hear.length !== 0)
    {
      var form = hear.parents("form:first");
      form.submit(function() {
          self.setCookie("theSource", jQuery(".theSource_1").val(), 90, "/", ".hl.co.uk", "");
      });
    }
  },

  setCookie: function Set_Cookie( name, value, expires, path, domain, secure ) {
    // set time, it's in milliseconds
    var expires_date = new Date();
    expires_date.setDate(expires);

    document.cookie = name + "=" +escape( value ) + ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + ( ( path ) ? ";path=" + path : "" ) + ( ( domain ) ? ";domain=" + domain : "" ) + ( ( secure ) ? ";secure" : "" );
  },

  getCookie: function(c_name) {
    if (document.cookie.length > 0) {
      c_start=document.cookie.indexOf(c_name + "=");
      if(c_start != -1)
      {
        c_start = c_start + c_name.length + 1; 
        c_end = document.cookie.indexOf(";",c_start);
        
        if(c_end == -1)
        {
          c_end = document.cookie.length;
        }

        return unescape(document.cookie.substring(c_start, c_end));
      }
    }
    
    return "";
  },

  getParam: function(param) {
    var value = "";
    var param_list = location.toString().split("&");
    
    for(i = 0; i < param_list.length; i++) 
    {
      if(param_list[i].search(param) != -1)
      {
        value = param_list[i].split("=")[1];
      }
    }
    
    return value;
  }
}

TheSource.initialize();

var PostcodeChecker = {
  pc_label: jQuery("#address-container-label"),
  pc_input: jQuery(".address_postcode"),
  pc_container: jQuery("#postcode-container"),
  pc_button: jQuery("#postcode-checker"),
  pc_info: jQuery("#postcode-info"),
  address_details: jQuery("#address-details"),
  address_details_manual: jQuery("#address-details-manual"),
  additional_details: jQuery("#additional-details"),
  address_container_info: jQuery("#address-container-info"),
  postcode_info: jQuery("#postcode-info"),
  form_submit: jQuery("#form-submit"),
  pc_url: location.protocol + "//www.hl.co.uk/ajax/postcode-checker",

  initialize: function() {
    var self = PostcodeChecker;

    // check to see if client details have been nested in the page
    if(typeof(client_details) !== "undefined" && client_details !== "")
    {
      self.autocomplete(client_details);
      return false;
    }

    self.address_details_manual.hide();
    self.additional_details.hide();
    // self.form_submit.hide();
    self.pc_button.css("display", "inline");
    self.pc_input.css("float", "left");
    self.pc_info.css("display", "block");
    self.pc_button.click(self.pc_click);
    self.pc_container.change(self.pc_change);
    self.address_container_info.click(self.pc_manual_click);
    self.postcode_info.children("span").click(self.pc_manual_click);
  },

  autocomplete: function(client_details) {



//function to read a value from the cookie
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0) === ' ') {
                     c = c.substring(1,c.length);
                }
		if (c.indexOf(nameEQ) === 0) {
                     return c.substring(nameEQ.length,c.length);
                }
	}
	return null;
}

// sets reg details to one
jQuery("#content form #personal-details").append('<input type="hidden" value="1" name="use_reg_details" />');

// gets the client number from the cookie
jQuery("#content form #personal-details").append('<input type="hidden" value="' + client_details.clientNumber + '" name="client_num" />');



    // handle the text fields
    var text_form_fields = ["title","forenames","surname","email","postCode","phoneDaytime","phoneEvening"];    
    for(var i = 0; i < text_form_fields.length; i++)
    {
      if(jQuery("." + text_form_fields[i]).val() === "" && client_details[text_form_fields[i]] !== "")
      {
        jQuery("." + text_form_fields[i]).val(client_details[text_form_fields[i]]);

         // if user is logged in, replace the form fields with hidden input and print the input values
         var tempStoreId = jQuery("." + text_form_fields[i]).attr('id');
         jQuery("." + text_form_fields[i]).after(   jQuery("." + text_form_fields[i]).attr('value')   );
         jQuery("." + text_form_fields[i]).before('<input type="hidden" value="' + jQuery("." + text_form_fields[i]).attr('value') + '" name="' + jQuery("." +         text_form_fields[i]).attr('name') + '" id="tempID" />');
         jQuery("." + text_form_fields[i]).remove();
         jQuery('#tempID').attr('id',tempStoreId);

      }

    }

    // handle the address lines
    var i = 1;
    for(var j = 0; j < client_details.address.length; j++)
    {
      if(jQuery(".address" + i).val() === "")
      {
		if( client_details.address[j] !== "" ){
 	         jQuery(".address" + i).val(client_details.address[j]);

	         // if user is logged in, replace the form fields with hidden input and print the input values (for address fields)
	         var tempStoreId = jQuery(".address" + i).attr('id');
	         jQuery(".address" + i).after(   jQuery(".address" + i).attr('value')   );
	         jQuery(".address" + i).before('<input type="hidden" value="' + jQuery(".address" + i).attr('value') + '" name="' + jQuery(".address" + i).attr('name') + '" id="tempID" />');
	         jQuery(".address" + i).remove();
	         jQuery('#tempID').attr('id',tempStoreId);
  		}
        i++;
      }
    }

    var l = client_details.address.length;
    for( var k = 0; k < 5 - client_details.address.length; k++) {
        l++;
        jQuery(".address" + l ).parent().remove();
    }
    


    
  },

  pc_click: function() {
    var self = PostcodeChecker;
    self.address_fill_with("#######".split("#"));			
    self.pc_input.addClass("loading");
    self.pc_label.text("Please wait, loading...");
    self.pc_container.animate({opacity: 0.5});
    self.pc_container.children("option").click(function() {
      jQuery(this).removeAttr("selected").blur();
      return false;
    });
    self.postcode_info.slideUp(500);
    self.address_details_manual.slideUp(500);
    self.call_ajax(self.pc_input.val());
  },

  pc_change: function() {
    var self = PostcodeChecker;
    self.address_fill_with(self.pc_container.val().toString().split(", "));
    self.additional_details.slideDown(500, function() {
      //self.form_submit.slideDown(500);
      //jQuery('#additional-details #hear-about-us h2').hide();
      //jQuery('#additional-details #hear-about-us').show();
    });
  },

  call_ajax: function(value) {
    var self = PostcodeChecker;
    jQuery.ajax({
      url: self.pc_url + "?postcode=" + value,
      dataType: "json",
      success: function(data) {
        var i = 0;
        self.pc_container.empty();

        if(data.SStatus == "N")
        {
          self.pc_label.text("Postcode not found");
        }
        else
        {
          while((typeof(data[i])!="undefined"))
          {
            var address = data[i].PartialAddress.split(", ");
            address.pop();
            address = address.toString().replace(/,/g, ", ");
            self.pc_container.append('<option value="'+address+'">'+address+'</option>');
            ++i;
          }		
          self.pc_label.text("Highlight your address below");	
        }

        self.pc_input.removeClass("loading");
        self.pc_container.animate({opacity: 1});
        self.address_details.slideDown(500);
      },
      error: function() {
        self.pc_input.removeClass("loading");
        self.pc_manual_click();
      }
    });
  },

  pc_manual_click: function() {
    var self = PostcodeChecker;

    //jQuery('#additional-details #hear-about-us h2').hide();
    //jQuery('#additional-details #hear-about-us').show();

    self.address_fill_with("#######".split("#"));
    self.postcode_info.slideUp(500);
    self.address_details.slideUp(500, function() {
      self.address_details_manual.slideDown(500, function() {
        self.additional_details.slideDown(500, function() {
          // self.form_submit.slideDown(500);
        });
      });
    });
  },

  address_fill_with: function(values) {
    jQuery(values).each(function(i) {
      if(i > 4)
      {
        return false;
      }
      
      jQuery("#address-details-manual input:eq(" + i + ")").val(this);
    });
  }
}

PostcodeChecker.initialize();
