/*
 * Script: /Scripts/jquery-wow.js
 * Author: Andy Gray
 *
 * Description
 * Manages the orderform context
 */

String.prototype.trim = function() {
  return this.replace(/^\s+|\s+$/g,"");
};

/* elements */

var apiid        = $('#frmHIOrderAPIId');
var product      = $('#frmHIOrderProduct');
var language     = $('#frmHIOrderLanguage');
var name         = $('#frmHIOrderName');
var email        = $('#frmHIOrderEmail');
var emailconfirm = $('#frmHIOrderEmailConfirm');
var birthday     = $('#frmHIOrderBirthday');
var birthmonth   = $('#frmHIOrderBirthmonth');
var birthyear    = $('#frmHIOrderBirthyear');
var birthhour    = $('#frmHIOrderBirthhour');
var birthminute  = $('#frmHIOrderBirthminute');
var birthcountry = $('#frmHIOrderBirthcountry');
var birthplace   = $('#frmHIOrderBirthplace');
var knowntime    = $('#frmHIOrderKnowntime');
var order_price  = $('#form-order-price');

/* constant definitions */

var cGenderFemale = 1;
var cGenderMale   = 2;

var cDeliveryEmail = 1;
var cDeliveryPost  = 2;

var cCurrencyDollar = 1;
var cCurrencyPound  = 2;
var cCurrencyEuro   = 3;

var url = '/wsapi/acs/';
var default_country = 'JX';

/* order context */

function OrderContext() {
  this.product = 'undefined';
  this.gender = cGenderFemale;
  this.deliveryoption = cDeliveryEmail;
  this.currency = cCurrencyDollar;
  this.symbol = '$';
  this.tracker = ' USD';
  this.price = 0;
  this.handling = 0;
}

OrderContext.prototype.setProduct = function( product ) {
  this.product = product;
};

OrderContext.prototype.getProduct = function() {
  return this.product;
};

OrderContext.prototype.setGender = function( gender ) {
  this.gender = gender;
};

OrderContext.prototype.getGender = function() {
  return this.gender;
};

OrderContext.prototype.setCurrency = function( currency ) {
  this.currency = currency;
};

OrderContext.prototype.getCurrency = function() {
  return this.currency;
};

OrderContext.prototype.getSymbol = function() {
  return this.symbol;
};

OrderContext.prototype.getTracker = function() {
  return this.tracker;
};

OrderContext.prototype.setDeliveryOption = function( option ) {
  this.deliveryoption = option;
};

OrderContext.prototype.getDeliveryOption = function() {
  return this.deliveryoption;
};

OrderContext.prototype.updatePrice = function() {
  $.getJSON(
    '/06_affiliates/sme/ajax/validate_price.php',
    {
      p: this.product,
      c: this.currency,
      d: this.deliveryoption
    },
    function( response ) {
      if( response.valid == true ) {
	this.price = response.price;
	this.handling = response.handling;
	this.symbol = response.symbol;
	this.tracker = response.tracker;
	order_price.empty();
	order_price.html( fmtPrice( response.price, response.handling, response.symbol, response.tracker ) );
      } else {
      }
    }
  );
};

OrderContext.prototype.getPrice = function() {
  return this.price;
};

OrderContext.prototype.getHandling = function() {
  return this.handling;
};

// instantiate the order context using form default values
var context = new OrderContext();

// initialise context from form field values
context.setProduct( product.val() );
switch( context.getProduct() ) {
case 'personal':
case 'season':
  context.setDeliveryOption( cDeliveryEmail );
  $('#frmHIOrder tr.wow-addressline').hide();
  break;
default:
  context.setDeliveryOption( cDeliveryPost );
  $('#frmHIOrder tr.wow-addressline').show();
  break;
}
context.setCurrency( cCurrencyDollar );
context.updatePrice();

function setGenderFemale() {
  context.setGender( cGenderFemale );
}

function setGenderMale() {
  context.setGender( cGenderMale );
}


function setDeliveryEmail() {
  context.setDeliveryOption( cDeliveryEmail );
  context.updatePrice();
  $('#frmHIOrder tr.wow-addressline').hide();
}

function setDeliveryPrintedCopy() {
  context.setDeliveryOption( cDeliveryPost );
  context.updatePrice();
  $('#frmHIOrder tr.wow-addressline').show();
}

function fmtPrice( price, handling, symbol, tracker ) {
  markup = '<strong>'
    + 'Price: ' + symbol + price + tracker
    + ( (handling != 0) ? ( ' + ' + symbol + handling + tracker + ' P&amp;P' ) : '' )
    + '</strong>';
  return markup;
}

function setCurrencyUSD() {
  context.setCurrency( cCurrencyDollar );
  context.updatePrice();
}

function setCurrencyGBP() {
  context.setCurrency( cCurrencyPound );
  context.updatePrice();
}

function setCurrencyEUR() {
  context.setCurrency( cCurrencyEuro );
  context.updatePrice();
}

function checkEmailFormat() {
  if( $('#frmHIOrderEmail').val().indexOf('@') == -1 || $('#frmHIOrderEmail').val().indexOf('.') == -1 ) {
    $('#frmHIOrder tr.wow-error-emailformat').show();
    return false;
  }
  $('#frmHIOrder tr.wow-error-emailformat').hide();
  return true;
}

function checkEmailConfirmation() {
  if( $('#frmHIOrderEmail').val() != $('#frmHIOrderEmailConfirm').val() ) {
    $('#frmHIOrder tr.wow-error-emailconfirm').show();
    return false;
  } else {
    $('#frmHIOrder tr.wow-error-emailconfirm').hide();
  }
  return true;
}

function checkDeliveryLine1() {
  if( $('#frmHIOrderPostalAddressLine1').val().length == 0 ) {
    $('#frmHIOrder tr.wow-error-delivery-line1').show();
    return false;
  } else {
    $('#frmHIOrder tr.wow-error-delivery-line1').hide();
  }
  return true;
}

function checkDeliveryTown() {
  if( $('#frmHIOrderPostalAddressLine3').val().length == 0 ) {
    $('#frmHIOrder tr.wow-error-delivery-town').show();
    return false;
  } else {
    $('#frmHIOrder tr.wow-error-delivery-town').hide();
  }
  return true;
}

function checkDeliveryPostcode() {
  if( $('#frmHIOrderPostalAddressLine4').val().length == 0 ) {
    $('#frmHIOrder tr.wow-error-delivery-postcode').show();
    return false;
  } else {
    $('#frmHIOrder tr.wow-error-delivery-postcode').hide();
  }
  return true;
}

function checkDeliveryCountry() {
  if( $('#frmHIOrderPostalAddressLine5').val().length == 0 ) {
    $('#frmHIOrder tr.wow-error-delivery-country').show();
    return false;
  } else {
    $('#frmHIOrder tr.wow-error-delivery-country').hide();
  }
  return true;
}

function DaysArray(n) {
  for (var i = 1; i <= n; i++) {
    this[i] = 31;
    if ( i == 4 || i == 6 || i == 9 || i == 11) { this[i] = 30; }
    if ( i == 2 ) { this[i] = 29; }
  }
  return this;
}

function daysInFebruary (year){
  return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

function checkDate() {
  var daysInMonth = DaysArray(12);
  var day = $('#frmHIOrderBirthday').val();
  var month = $('#frmHIOrderBirthmonth').val();
  var year = $('#frmHIOrderBirthyear').val();
  if( day == 0 || month == 0 || year == 0 ) {
    $('#frmHIOrder tr.wow-error-date').show();
    return false;
  }
  if ( (month == 2 && day > daysInFebruary(year)) || day > daysInMonth[month]){
    $('#frmHIOrder tr.wow-error-date').show();
    return false;
  }
  $('#frmHIOrder tr.wow-error-date').hide();
  return true;
}

function checkTime() {
  // check that a time or unknown has been selected
  if( $('#frmHIOrderBirthhour').val() == -2 || $('#frmHIOrderBirthminute').val() == -2 ) {
    $('#frmHIOrder tr.wow-error-time').show();
    return false; // no time set
  }
  // if an hour has been selected or is unknown, set the minute to 0
  if( $('#frmHIOrderBirthhour').val() >= -1 && $('#frmHIOrderBirthminute').val() == -2 ) {
    $('#frmHIOrderBirthminute').val(0);
  }
  $('#frmHIOrder tr.wow-error-time').hide();
  return true;
}

function checkLocation() {
  if( $('#frmHIOrderBirthplace').val().length > 0 ) {
    $.getJSON(
      '/06_affiliates/sme/ajax/validate_place.php',
      {
	state: $('#frmHIOrderBirthcountry').val(),
	place: $('#frmHIOrderBirthplace').val()
      },
      function( response ) {
	if( response.valid == true ) {
	  $('#frmHIOrderBirthplaceid').val( response.placeid );
	  $('#frmHIOrderBirthregion').val( response.regionname );
	  $('#frmHIOrderBirthcountryname').val( response.statename );
	  $('#frmHIOrderBirthlongitude').val( response.longitude );
	  $('#frmHIOrderBirthlatitude').val( response.latitude );
	  $('#frmHIOrder tr.wow-error-place').hide();
	  $('#frmHIOrder').submit();
	} else {
	  // todo - list the multiple response frame
	  if( response.rows > 1 ) {
	    /* manage duplicates as the 1st option for now */
	    $('#frmHIOrderBirthplaceid').val( response.placeid );
	    $('#frmHIOrderBirthregion').val( response.regionname );
	    $('#frmHIOrderBirthcountryname').val( response.statename );
	    $('#frmHIOrderBirthlongitude').val( response.longitude );
	    $('#frmHIOrderBirthlatitude').val( response.latitude );
	    $('#frmHIOrder tr.wow-error-place').hide();
	    $('#frmHIOrder').submit();
	  } else {
	    /* manage unknown location */
	    $('#frmHIOrder tr.wow-error-place').show();
	    $('#frmHIOrderBirthplace').empty().focus();
	  }
	}
      }
    ); /* end getJSON */
  } else {
    $('#frmHIOrder tr.wow-error-place').show();
    $('#frmHIOrderBirthplace').focus();
  }
  return false;
}

function submitOrder() {
  if( checkEmailFormat() == false ) return;
  if( checkEmailConfirmation() == false ) return;
  if( context.deliveryoption == cDeliveryPost ) {
    if( checkDeliveryLine1() == false ) return;
    if( checkDeliveryTown() == false ) return;
    if( checkDeliveryPostcode() == false ) return;
    if( checkDeliveryCountry() == false ) return;
  }
  if( checkDate() == false ) return;
  if( checkTime() == false ) return;
  /* note submit managed through callback */
  checkLocation();
}

$(document).ready(

  function() {

    $('#frmHIOrderName').blur(
      function() {
	if( name.val().trim().length == 0 ) {
	  $('#frmHIOrder tr.wow-error-name').show();
	} else {
	  $('#frmHIOrder tr.wow-error-name').hide();
	}
      });

    $('#frmHIOrderEmail').blur(
      function() {
	if( email.val().trim().length == 0 ) {
	  $('#frmHIOrder tr.wow-error-email').show();
	} else {
	  $('#frmHIOrder tr.wow-error-email').hide();
	}
      });

    $('#frmHIOrderEmailConfirm').blur(
      function() {
	if( ( emailconfirm.val().trim().length == 0 ) ) {
	  $('#frmHIOrder tr.wow-error-emailconfirm').show();
	} else {
	  $('#frmHIOrder tr.wow-error-emailconfirm').hide();
	}
	checkEmailConfirmation();
      });

    $('#frmHIOrderPostalAddressLine1').blur(
      function() {
	checkDeliveryLine1();
      });

    $('#frmHIOrderPostalAddressLine3').blur(
      function() {
	checkDeliveryTown();
      });

    $('#frmHIOrderPostalAddressLine4').blur(
      function() {
	checkDeliveryPostcode();
      });

    $('#frmHIOrderPostalAddressLine5').blur(
      function() {
	checkDeliveryCountry();
      });

    $('#frmHIOrderBirthday').blur(
      function() {
	checkDate();
      });

    $('#frmHIOrderBirthmonth').blur(
      function() {
	checkDate();
      });

    $('#frmHIOrderBirthyear').blur(
      function() {
	checkDate();
      });

    $('#frmHIOrderBirthhour').change(
      function() {
	if( $('#frmHIOrderBirthhour').val() == -1 ) {
	  $('#frmHIOrderBirthminute').val(0);
	  $('#frmHIOrderKnowntime').val(0);
	} else {
	  $('#frmHIOrderKnowntime').val(1);
	}
      });

    $('#frmHIOrderBirthplace').autocomplete(
      url+'suggest.php',
      {
	delay: 10,
	minChars: 2,
	matchSubset: 1,
	matchContains: 1,
	cacheLength: 10,
	autoFill: true,
	extraParams: {
	  state: function() { return $('#frmHIOrderBirthcountry').val(); }
	}
      });

    $.getJSON(
      url+'atlas.json.php?method=getStatesXML&callback=?',
      function( data ) {
	$.each( data, function( key, value ) {
	  if( value.abbrev == default_country ) {
	    $('#frmHIOrderBirthcountry').append('<option value=' + value.abbrev + ' SELECTED' + '>' + value.name + '</option>');
	  } else {
	    $('#frmHIOrderBirthcountry').append('<option value=' + value.abbrev + '>' + value.name + '</option>');
	  }
	});
	$('#frmHIOrderBirthcountry').val( default_country );
      }
    );

    $('#frmHIOrderBirthcountry').change(
      function(){
	$('#frmHIOrderBirthplace').val('');
      }
    );

    $('#frmHIOrderBirthplace').change(
      function(){
	if( $('#frmHIOrderBirthplace').val().trim().length >= 0 ) {
	  $('#frmHIOrder tr.wow-error-birthplace').hide();
	} else {
	  $('#frmHIOrder tr.wow-error-birthplace').show();
	}
      }
    );

    $('#frmHIOrderBirthplace').blur(
      function() {
	if( $('#frmHIOrderBirthplace').val().trim().length < 3 ) {
	  $('#frmHIOrder tr.wow-error-birthplace').show();
	} else {
	  $('#frmHIOrder tr.wow-error-birthplace').hide();
	}
      });

    //context.setDeliveryOption( cDeliveryEmail );
    //context.setCurrency( cCurrencyDollar );
    $('#frmHIOrderName').focus();

  } /* outer function */
); /* document(ready) */
