var errors, hddnClientId, edtClientName, edtClientSurname, selIdTypeId, edtClientIdNo, selClientTypeId, cbClientAddrBill, hddnAddressId, edtClientPhone, edtClientPhoneAlt, edtClientEmail, edtClientNote, selGenderId, selRewardLevelId, edtClientBusinessName, edtClientVatNo, edtClientRegNo, cbClientContract, hddnClientDeleted, hddnLastUpdate;
var module = baseRootURL + "client/";

var addressItem = new addSelectionList('addressItem', 'address', 'addressElement');
addressItem.setColWidth(6);

var buildingAddressItem = new addSelectionList('buildingAddressItem', 'buildingAddress', 'buildingAddressElement');
addressItem.setColWidth(6);

var buildingItem = new addSelectionList('buildingItem', 'building', 'buildingElement');
addressItem.setColWidth(6);

function registerClient(action) {
  errors = false;
  validate_hddnClientId();
  validate_selClientTypeId();


  if ($("#divClientBusiness").is(":visible")) {
      
      	
			edtClientIdNo		= null;
			selClientGender	    = null;
          validate_edtClientName();
    validate_edtClientSurname();
    validate_edtClientBusinessName();
    validate_edtClientVatNo();
    validate_cbClientAddrBill();
    validate_hddnAddressId();
    validate_edtClientPhone();
    validate_edtClientPhoneAlt();
    validate_edtClientEmail();
    validate_edtClientNote();
    validate_selGenderId();
    validate_cbClientContract();
    validate_selRewardLevelId();
    validate_hddnClientDeleted();
    validate_selAreaId();
    validate_selAddressTypeId();
    validate_hddnCountryId();
    validate_hddnPostId();
    validate_txtBuildingNeeds();
    validate_edtBuildingName();
    validate_edtAddressStreet();
    validate_edtAddressSuburb();
    validate_edtAddressCounty();
    validate_edtAddressCity();
    validate_edtAddressPostalCode();
      
    validate_edtBuildingAddressStreet();
    validate_edtBuildingAddressSuburb();
    validate_edtBuildingAddressCounty();
    validate_edtBuildingAddressCity();
    validate_edtBuildingAddressPostalCode();

    var ind = parseInt(selIdTypeId);
    if (ind == 1) {
      validate_edtClientRegNo();

    } else {
      validate_edtClientRegNo();
    }
  } else {
      
    edtClientBusinessName   =null;
    edtClientVatNo          =null;
      
    validate_edtClientName();
    validate_edtClientSurname();
    validate_selIdTypeId();
    validate_edtClientIdNo();
    validate_selGenderId();

    validate_cbClientAddrBill();
    validate_hddnAddressId();
    validate_edtClientPhone();
    validate_edtClientPhoneAlt();
    validate_edtClientEmail();
    validate_edtClientNote();
    validate_selGenderId();
    validate_cbClientContract();
    validate_selRewardLevelId();
    validate_hddnClientDeleted();
    validate_selAreaId();
    validate_selAddressTypeId();
    validate_hddnCountryId();
    validate_hddnPostId();
    validate_txtBuildingNeeds();
    validate_edtBuildingName();
    validate_edtAddressStreet();
    validate_edtAddressSuburb();
    validate_edtAddressCounty();
    validate_edtAddressCity();
    validate_edtAddressPostalCode();
      
    validate_edtBuildingAddressStreet();
    validate_edtBuildingAddressSuburb();
    validate_edtBuildingAddressCounty();
    validate_edtBuildingAddressCity();
    validate_edtBuildingAddressPostalCode();

  }


  if (!errors) {
    var data = {};
    data.dummy = ""; //we seem to get errors from the first value, so always add a dummy value first.
    data.action = action;
    if (document.getElementById("hddnClientId") != null) data.hddnClientId = hddnClientId;
    data.edtClientName = edtClientName;
    data.edtClientSurname = edtClientSurname;
    data.selIdTypeId = selIdTypeId;
    data.edtClientIdNo = edtClientIdNo;
    data.selClientTypeId = selClientTypeId;
    data.cbClientAddrBill = cbClientAddrBill;
    data.hddnAddressId = hddnAddressId;
    data.edtClientPhone = edtClientPhone;
    data.edtClientPhoneAlt = edtClientPhoneAlt;
    data.edtClientEmail = edtClientEmail;
    data.edtClientNote = edtClientNote;
    data.selGenderId = selGenderId;
    data.selRewardLevelId = selRewardLevelId;
    data.edtClientBusinessName = edtClientBusinessName;
    data.edtClientVatNo = edtClientVatNo;
    data.edtClientRegNo = edtClientRegNo;
    data.cbClientContract = cbClientContract;
    data.hddnClientDeleted = hddnClientDeleted;
    data.hddnLastUpdate = hddnLastUpdate;
      
	data.addresses  = addressItem.getItemsAsString();
	data.buildingAddresses  = buildingAddressItem.getItemsAsString();
	data.buildings  = buildingItem.getItemsAsString();

	data.longitude	= window.lng === undefined ? '' : window.lng;
	data.latitude	= window.lat === undefined ? '' : window.lat;	

    callModule("client/client_val.php", data);
  }
}

function insertClient() {
  registerClient(0)
}

function modifyClient() {
  registerClient(1)
}

function validate_hddnClientId() {
  if (document.getElementById("hddnClientId") != null) hddnClientId = document.getElementById("hddnClientId").value;
}

function validate_edtClientName() {
  edtClientName = validateRequiredText("edtClientName", "Client Name is required.");
}

function validate_edtClientSurname() {
  edtClientSurname = validateRequiredText("edtClientSurname", "Client Surname is required.");
}

function validate_selIdTypeId() {
  selIdTypeId = validateSelection("selIdTypeId", "Please select Id Type Id.");
}

function validate_edtClientIdNo() {
  edtClientIdNo = validateNumericField("edtClientIdNo", "Client Id No should be a numeric.");
}

function validate_selClientTypeId() {
  selClientTypeId = validateRequiredSelection("selClientTypeId", "Please select Client Type Id.");
}

function validate_cbClientAddrBill() {
      cbClientAddrBill = document.getElementById("cbClientAddrBill").checked;

}

function validate_hddnAddressId() {
  if (document.getElementById("hddnAddressId") != null) hddnAddressId = document.getElementById("hddnAddressId").value;
}

function validate_edtClientPhone() {
  edtClientPhone = validatePhoneNumber("edtClientPhone", "Phone number is required.", false);
}

function validate_edtClientPhoneAlt() {
  edtClientPhoneAlt = validatePhoneNumber("edtClientPhoneAlt", "Phone number is required.", false);
}

function validate_edtClientEmail() {
  edtClientEmail = validateRequiredEmail("edtClientEmail", "Valid email address required.");
}

function validate_edtClientNote() {
  edtClientNote = document.getElementById("edtClientNote").value;
}

function validate_selGenderId() {
  selGenderId = validateRequiredSelection("selGenderId", "Please select Client Gender.");
}

function validate_edtClientBusinessName() {
  edtClientBusinessName = validateRequiredText("edtClientBusinessName", "Client Business Name is required.");
}

function validate_edtClientVatNo() {
  edtClientVatNo = validateNumericField("edtClientVatNo", "Client Vat No should be a numeric.");
}

function validate_edtClientRegNo() {
  edtClientRegNo = validateNumericField("edtClientRegNo", "Client Reg No should be a numeric.");
}

function validate_cbClientContract() {
  cbClientContract = document.getElementById("cbClientContract").checked;
}

function validate_hddnClientDeleted() {
  if (document.getElementById("hddnClientDeleted") != null) hddnClientDeleted = document.getElementById("hddnClientDeleted").value;
}

function validate_hddnLastUpdate() {
  if (document.getElementById("hddnLastUpdate") != null) hddnLastUpdate = document.getElementById("hddnLastUpdate").value;
}


function validate_hddnAddressId() {
  if (document.getElementById("hddnAddressId") != null) hddnAddressId = document.getElementById("hddnAddressId").value;
}

function validate_hddnClientId() {
  if (document.getElementById("hddnClientId") != null) hddnClientId = document.getElementById("hddnClientId").value;
}

function validate_hddnAddressTypeId() {
  if (document.getElementById("hddnAddressTypeId") != null) hddnAddressTypeId = document.getElementById("hddnAddressTypeId").value;
}

function validate_hddnCountryId() {
  if (document.getElementById("hddnCountryId") != null) hddnCountryId = document.getElementById("hddnCountryId").value;
}

function validate_hddnPostId() {
  if (document.getElementById("hddnPostId") != null) hddnPostId = document.getElementById("hddnPostId").value;
}


function validate_selRewardLevelId(){selRewardLevelId=validateRequiredSelection("selRewardLevelId", "Please make a valid selection.");}


function validate_edtAddressStreet() {
  edtAddressStreet = validateRequiredText("edtAddressStreet", "Address Street is required.");
}

function validate_edtAddressSuburb() {
  edtAddressSuburb = validateRequiredText("edtAddressSuburb", "Address Suburb is required.");
}

function validate_edtAddressCity() {
  edtAddressCity = validateRequiredText("edtAddressCity", "Address City is required.");
}

function validate_edtAddressCounty() {
  edtAddressCounty = validateRequiredText("edtAddressCounty", "Address County is required.");
}

function validate_edtAddressPostalCode() {
  edtAddressPostalCode = validateRequiredText("edtAddressPostalCode", "Address Postal Code is required.");
}

function validate_edtAddressLng() {
  edtAddressLng = validateRequiredText("edtAddressLng", "Address Lng is required.");
}

function validate_edtAddressLat() {
  edtAddressLat = validateRequiredText("edtAddressLat", "Address Lat is required.");
}

function validate_hddnBuildingId(){
	if (document.getElementById("hddnBuildingId") != null) hddnBuildingId=document.getElementById("hddnBuildingId").value;}

function validate_edtBuildingName() {
  edtBuildingName = validateRequiredText("edtBuildingName", "Building Name is required.");
}

function validate_edtBuildingAddressStreet() {
  edtBuildingAddressStreet = validateRequiredText("edtBuildingAddressStreet", "Building Address Street is required.");
}

function validate_edtBuildingAddressSuburb() {
  edBuildingtAddressSuburb = validateRequiredText("edtBuildingAddressSuburb", "Building Address Suburb is required.");
}

function validate_edtBuildingAddressCity() {
  edtBuildingAddressCity = validateRequiredText("edtBuildingAddressCity", "Building Address City is required.");
}

function validate_edtBuildingAddressCounty() {
  edtBuildingAddressCounty = validateRequiredText("edtBuildingAddressCounty", "Building Address County is required.");
}

function validate_edtBuildingAddressPostalCode() {
  edtBuildingAddressPostalCode = validateRequiredText("edtBuildingAddressPostalCode", "Building Address Postal Code is required.");
}

function validate_selAddress(){selAddress=validateRequiredSelection("selAddress", "Please specify the address type.");}

function validate_selClientId(){selClientId=validateRequiredSelection("selClientId", "Please make a valid selection.");}

function validate_selAreaId(){selAreaId=validateRequiredSelection("selAreaId", "Please make a valid selection.");}

function validate_selAddressTypeId(){selAddressTypeId=validateRequiredSelection("selAddressTypeId", "Please make a valid selection.");}

function validate_edtBuildingName(){edtBuildingName=validateRequiredText("edtBuildingName", "This field is required.");}
function validate_txtBuildingNeeds(){txtBuildingNeeds=document.getElementById("txtBuildingNeeds").value;}


function viewClient(id) {
  var data = {}
  data.dummy = "";
  data.hddnClientId = id;
  data.action = 2;
  callModule("client/client_val.php", data);
}

function editClient(id) {
  var data = {}
  data.dummy = "";
  data.hddnClientId = id;
  data.action = 3;
  callModule("client/client_val.php", data);
}

function deleteClient(id, desc) {
  if (confirm("Are you sure you want to delete " + desc + " and all associated records?")) {
    var data = {}
    data.dummy = "";
    data.hddnClientId = id;
    data.action = 4;
    callModule("client/client_val.php", data);
  }
}


function setClientTypeNatureName() {
  "use strict";
  var sel = document.getElementById('selGenderId');
  document.getElementById('edtGenderName').value = sel.options[sel.selectedIndex].innerHTML;
}

function doGenderRefinement(obj) {
  var data = {}
  data.dummy = "";
  data.field_id = 'selGenderId';
  data.input_id = obj.value;
  callModule("lib/getGendersByName.php", data);
}

function setAreaName() {
  "use strict";
  var sel = document.getElementById('selAreaId');
  document.getElementById('edtAreaName').value = sel.options[sel.selectedIndex].innerHTML;
}

function doAreaRefinement(obj) {
  var data = {}
  data.dummy = "";
  data.field_id = 'selAreaId';
  data.input_id = obj.value;
  callModule("lib/getAreasByName.php", data);
}

function setAddressTypeName() {
  "use strict";
  var sel = document.getElementById('selAddressTypeId');
  document.getElementById('edtAddressTypeName').value = sel.options[sel.selectedIndex].innerHTML;
}

function doAddressTypeRefinement(obj) {
  var data = {}
  data.dummy = "";
  data.field_id = 'selAddressTypeId';
  data.input_id = obj.value;
  callModule("lib/getAddressTypesByName.php", data);
}

function setCountryName() {
  "use strict";
  var sel = document.getElementById('selCountryId');
  document.getElementById('edtCountryName').value = sel.options[sel.selectedIndex].innerHTML;
}

function doCountryRefinement(obj) {
  var data = {}
  data.dummy = "";
  data.field_id = 'selCountryId';
  data.input_id = obj.value;
  callModule("lib/getCountriesByName.php", data);
}

function setSuburbName() {
  "use strict";
  var sel = document.getElementById('selPostId');
  document.getElementById('edtSuburbName').value = sel.options[sel.selectedIndex].innerHTML;
}

function doSuburbRefinement(obj) {
  var data = {}
  data.dummy = "";
  data.field_id = 'selPostId';
  data.input_id = obj.value;
  callModule("lib/getPostsByName.php", data);
}

function setRewardLevelName() {
  "use strict";
  var sel = document.getElementById('selRewardLevelId');
  document.getElementById('edtRewardLevelName').value = sel.options[sel.selectedIndex].innerHTML;
}

function doRewardLevelRefinement(obj) {
  var data = {}
  data.dummy = "";
  data.field_id = 'selRewardLevelId';
  data.input_id = obj.value;
  callModule("lib/getRewardLevelsByName.php", data);
}

function selIdType() {
  "use strict";
  var sel = document.getElementById('selIdType');
  document.getElementById('selIdType').value = sel.options[sel.selectedIndex].innerHTML;
}

function doIdTypeRefinement(obj) {
  var data = {}
  data.dummy = "";
  data.field_id = 'selIdType';
  data.input_id = obj.value;
  callModule("lib/getIdTypeByName.php", data);
}


function getAddressOptions(obj) {
  var data = {}
  data.dummy = "";
  data.field_id = 'edtAddressPostalCode';
  //data.input_id = obj.value;

  //var sel = document.getElementById('edtAddressPostalCode');

  //data.field_value = sel.value;

  //  callModule("lib/getAddressOptions.php", data);
  console.log('attempting ajax call...');

  $.ajax({
    url: "/lib/getAddressOptions.php",
    type: "POST",
    data: {
      "field_value": "MK44AP"
    },
    success: function (data, textStatus, jqXHR) {
      //var jData = jQuery.parseJSON(data);
      console.log(data);
    },
    error: function (jqXHR, textStatus, errorThrown) {}
  });

  console.log('end of call attempt...');


}

function prepEditFields(val) {
  IDTypeVal = val;
  getIdTypeByClientType(setIdField);
  document.getElementById('selIdTypeId').value = val;
}

function getIdTypeByClientType(callback) {
  var data = {};
  data.input_id = document.getElementById('selClientTypeId').value;
  data.field_id = 'selIdTypeId';
  callModule('lib/getIdTypeByClientType.php', data, setFieldsByClientType);
  if (callback) callback();
}

function setFieldsByClientType() {
  var ind = parseInt(document.getElementById('selClientTypeId').value);

  switch (ind) {
    case 1:
      {
        $('#divClientBusiness').hide();
        $('#divClientIndividual').show();
        $('#divClientProxy').hide();
        break;
      }
    case 2:
      {
        $('#divClientIndividual').hide();
        $('#divClientBusiness').show();
        $('#divClientProxy').hide();
        break;
      }
    case 3:
      {
        $('#divClientBusiness').hide();
        $('#divClientIndividual').show();
        $('#divClientProxy').show();
        break;
      }
  }

//  if (IDTypeVal) {
//    var seliti = document.getElementById('selIdTypeId');
//    for (var x = 0; x < seliti.options.length; x++) {
//      if (seliti.options[x].value == IDTypeVal) {
//        seliti.selectedIndex = x;
//        break;
//      }
//    }
//  }
}


function registerAddress(action) {
  errors = false;

  validate_edtAddressStreet();
  validate_edtAddressSuburb();
  validate_edtAddressCity();
  validate_edtAddressCounty();
  validate_edtAddressPostalCode();

  if (!errors) {
    var data = {};
    data.dummy = ""; //we seem to get errors from the first value, so always add a dummy value first.
    data.action = action;
    if (document.getElementById("hddnAddressId") != null) data.hddnAddressId = hddnAddressId;
    data.hddnClientId = hddnClientId;
    data.hddnAddressTypeId = hddnAddressTypeId;
    data.hddnCountryId = hddnCountryId;
    data.hddnPostId = hddnPostId;
    data.edtAddressStreet = edtAddressStreet;
    data.edtAddressSuburb = edtAddressSuburb;
    data.edtAddressCity = edtAddressCity;
    data.edtAddressCounty = edtAddressCounty;
    data.edtAddressPostalCode = edtAddressPostalCode;
    //	data.edtAddressLng = edtAddressLng;
    //	data.edtAddressLat = edtAddressLat;
    callModule("address/address_val.php", data);

  }
}

function addClientAddress() {
  registerAddress(0)
}

function addAddressToArray()
{
  validate_hddnAddressId();
  validate_edtAddressStreet();
  validate_edtAddressSuburb();
  validate_edtAddressCity();
  validate_edtAddressCounty();
  validate_edtAddressPostalCode();
    
    //if (!errors)
	//{
		var se = document.getElementById('selAddressTypeId');
        var addType = se.options[se.selectedIndex].text;
		
        if (se.selectedIndex)
		{
  			addressItem.setTag(''+edtAddressStreet+','+edtAddressSuburb+','+edtAddressCity+','+edtAddressCounty+','+edtAddressPostalCode+'');
			addressItem.setColWidth(24);
			addressItem.setDisplayText(addType+': '+edtAddressStreet+', '+edtAddressSuburb+', '+edtAddressCity+', '+edtAddressCounty+', '+edtAddressPostalCode);
            
            addressItem.addItem(se);
			console.log(addressItem);
        }            
            
		//}
	}
    

/*function addBuildingAddressToArray()
{
    
    //if (!errors)
	//{
		var se = document.getElementById('selAreaId');
        var addType = se.options[se.selectedIndex].text;
		
        if (se.selectedIndex)
		{
  			buildingAddressItem.setTag(''+edtBuildingAddressStreet+','+edtBuildingAddressSuburb+','+edtBuildingAddressCity+','+edtBuildingAddressCounty+','+edtBuildingAddressPostalCode+'');
			buildingAddressItem.setColWidth(24);
			buildingAddressItem.setDisplayText(addType+': '+edtBuildingAddressStreet+', '+edtBuildingAddressSuburb+', '+edtBuildingAddressCity+', '+edtBuildingAddressCounty+', '+edtBuildingAddressPostalCode);
            
            buildingAddressItem.addItem(se);
			console.log(buildingAddressItem);
        }            
            
		//}
	}*/

function addBuildingToArray()
{
  validate_hddnBuildingId();
  validate_selAreaId();
  validate_edtBuildingName();
  validate_txtBuildingNeeds();
    
    //if (!errors)
	//{
		var se		= document.getElementById('selAreaId');
		var addType = se.options[se.selectedIndex].text;
		if (se.selectedIndex)
		{
            
/*            buildingItem.setTag(edtBuildingName);
			buildingItem.setColWidth(6);
			buildingItem.setDisplayText(addType+': '+edtBuildingName);
			buildingItem.addItem(se);
            
            buildingItem.setTag(txtBuildingNeeds);
			buildingItem.setColWidth(6);
			buildingItem.setDisplayText(addType+': '+txtBuildingNeeds);
			buildingItem.addItem(se);
            			console.log(buildingItem);      */      

            
        buildingAddressItem.setTag(''+edtBuildingAddressStreet+','+edtBuildingAddressSuburb+','+edtBuildingAddressCity+','+edtBuildingAddressCounty+','+edtBuildingAddressPostalCode+'');
            
			buildingAddressItem.setColWidth(6);
			buildingAddressItem.setDisplayText(addType+': '+edtBuildingAddressStreet+', '+edtBuildingAddressSuburb+', '+edtBuildingAddressCity+', '+edtBuildingAddressCounty+', '+edtBuildingAddressPostalCode);
            
            buildingAddressItem.addItem(se);
			console.log(buildingAddressItem);
		//}
	}
    
    
}

function setRewardLevelName()
{
	"use strict"; 
	var sel = document.getElementById('selRewardLevelId');
	document.getElementById('edtRewardLevelName').value = sel.options[sel.selectedIndex].innerHTML;
}