/*
 * Script: /Scripts/jquery-wowdk.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 knowntime    = $('#frmHIOrderKnowntime');
var birthcountry = $('#frmHIOrderBirthcountry');
var birthplace   = $('#frmHIOrderBirthplace');
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 cCurrencyDKK    = 4;

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

/* order context */

function OrderContext() {
  /* header */
  this.apiid = apiid.val();
  this.language = language.val();
  this.product = product.val();
  /* cover name */
  this.name = '';
  this.gender = cGenderFemale;
  /* delivery */
  this.deliveryoption = cDeliveryEmail;
  this.emailaddress = '';
  this.emailconfirmation = '';
  /* date */
  this.day = 0;
  this.month = 0;
  this.year = 0;
  /* time */
  this.hour = -1;
  this.minute = -1;
  this.knowntime = 1;
  /* place */
  this.place = '';
  this.placeid = 0;
  this.regionname = '';
  this.country = 'CF';
  this.statename = '';
  this.longitude = 0;
  this.latitude = 0;
  /* pricing */
  this.currency = cCurrencyDKK;
  this.symbol = 'kr. ';
  this.tracker = ' DKK';
  this.price = 0;
  this.handling = 0;
  /* T&C */
  this.tcagreed = false;
}

/* product */

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

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

OrderContext.prototype.checkProduct = function() {
  return true;
};

/* name */

OrderContext.prototype.setName = function( name ) {
  this.name = name;
};

OrderContext.prototype.getName = function() {
  return this.name;
};

OrderContext.prototype.checkName = function() {
  if( this.checkUnsetName() == false ) return false;
  return true;
};

OrderContext.prototype.checkUnsetName = function() {
  if( this.name == '' ) {
    this.error_message = 'Please set report name';
    return false;
  }
  return true;
};

/* gender */

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

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

/* email address */

OrderContext.prototype.setEmailAddress = function( address ) {
  this.emailaddress = address;
};

OrderContext.prototype.getEmailAddress = function() {
  return this.emailaddress;
};

OrderContext.prototype.setEmailConfirmation = function( address ) {
  this.emailconfirmation = address;
};

OrderContext.prototype.getEmailConfirmation = function() {
  return this.emailconfirmation;
};

OrderContext.prototype.checkEmail = function() {
  if( this.checkUnsetEmail() == false ) return false;
  if( this.checkUnsetEmailConfirmation() == false ) return false;
  if( this.checkValidEmail() == false ) return false;
  if( this.checkEqualEmail() == false ) return false;
  return true;
};

OrderContext.prototype.checkUnsetEmail = function() {
  if( this.emailaddress == '' ) {
    this.error_message = 'Please set email address';
    return false;
  }
  return true;
};

OrderContext.prototype.checkUnsetEmailConfirmation = function() {
  if( this.emailconfirmation == '' ) {
    this.error_message = 'Please confirm email address';
    return false;
  }
  return true;
};

OrderContext.prototype.checkValidEmail = function() {
  if( this.emailaddress.indexOf('@') == -1 || this.emailaddress.indexOf('.') == -1 ) {
    this.error_message = 'Please enter a valid email address (name@domain)';
    return false;
  }
  return true;
};

OrderContext.prototype.checkEqualEmail = function() {
  if( this.emailaddress != this.emailconfirmation ) {
    this.error_message = 'Please confirm delivery email address';
  }
  return true;
};

/* currency */

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

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

/* symbol */

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

/* tracker */

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

/* delivery option */

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

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

/* price */

OrderContext.prototype.updatePriceDeprecated = function() {
  order_price.empty();
  switch( this.deliveryoption ) {
  case cDeliveryEmail:
    order_price.html( fmtPrice( 195, 0, 'kr. ', '' ) );
    break;
  case cDeliveryPost:
    order_price.html( fmtPrice( 270, 25, 'kr. ', '' ) );
    break;
    }
};

OrderContext.prototype.updatePrice = function() {
  $.getJSON(
    'http://www.world-of-wisdom.com/06_affiliates/sme/ajax/validate_price_remote.php?callback=?',
    {
      i: 34,
      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 {
	this.error_message = 'price update failed';
      }
    }
  );
};

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

/* handling */

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

/* date */

OrderContext.prototype.setBirthDay = function( day ) {
  this.day = parseInt(day);
};

OrderContext.prototype.setBirthMonth = function( month ) {
  this.month = parseInt(month);
};

OrderContext.prototype.setBirthYear = function( year ) {
  if( year != "Year" ) {
    this.year = parseInt(year);
  }
};

OrderContext.prototype.checkDate = function() {
  if( this.checkUnsetDate() == false ) return false;
  if( this.checkValidDate() == false ) return false;
  return true;
};

OrderContext.prototype.checkUnsetDate = function() {
  if( this.day == 0 || this.month == 0 || this.year == 0 || this.year == 'Year' ) {
    this.error_message = 'Please select a date of birth';
    return false;
  }
  return true;
};

OrderContext.prototype.checkValidDate = function() {
  var daysInMonth = DaysArray(12);
  if ( (this.month == 2 && this.day > daysInFebruary(this.year)) || this.day > daysInMonth[this.month]){
    this.error_message = 'Please select a valid date of birth';
    return false;
  }
  return true;
};

/* time */

OrderContext.prototype.setBirthHour = function( hour ) {
  this.hour = parseInt(hour);
};

OrderContext.prototype.setBirthMinute = function( minute ) {
  this.minute = parseInt(minute);
};

OrderContext.prototype.checkTime = function() {
  if( this.checkUnsetTime() == false ) return false;
  if( this.checkValidTime() == false ) return false;
  this.checkUnknownTime();
  return true;
};

OrderContext.prototype.checkUnsetTime = function() {
  if( this.hour == -1 && this.minute == -1 ) {
    this.error_message = 'Please select a time of birth or set as unknown';
    return false;
  }
  return true;
};

OrderContext.prototype.checkValidTime = function() {
  if( this.checkUnknownTime == false ) {
    if( this.hour >= 0 && this.hour < 24 && this.minute >= 0 && this.minute < 60) {
      return true;
    }
    this.error_message = 'Please select a valid time of birth';
    return false;
  }
  return true;
};

OrderContext.prototype.checkUnknownTime = function() {
  if( this.hour == -2 ) {
    this.minute = 0;
    this.knowntime = 0;
    return true;
  }
  return false;
};

/* birth place */

OrderContext.prototype.getBirthCountry = function() {
  return this.country;
};

OrderContext.prototype.setBirthCountry = function( country ) {
  this.country = country;
};

/* error handling */

OrderContext.prototype.isValidForm = function() {
  if( this.checkName() == false ) return false;
  if( this.checkEmail() == false ) return false;
  if( this.checkDate() == false ) return false;
  if( this.checkTime() == false ) return false;
  this.error_message = 'Is valid form';
  return true;
};

OrderContext.prototype.getErrorMessage = function() {
  return this.error_message;
};

/* initialise form context */

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( cCurrencyDKK );
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 getBirthCountry() {
  return context.getBirthCountry();
}

function fmtPrice( price, handling, symbol, tracker ) {
  markup = '<strong>'
    + 'kr. ' + price
    + ( (handling != 0) ? ( ' + porto ' + 'kr. ' + handling ) : '' )
    + '</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 setCurrencyDKK() {
  context.setCurrency( cCurrencyDKK );
  context.updatePrice();
}

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

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(
      'http://www.world-of-wisdom.com/06_affiliates/sme/ajax/validate_place_remote.php?callback=?',
      {
	state: $('#frmHIOrderBirthcountry').val(),
	place: $('#frmHIOrderBirthplacename').val(),
	placeid: $('#frmHIOrderBirthplaceid').val()
      },
      function( response ) {
	if( response.valid == true ) {
	  $('#frmHIOrder tr.wow-error-place')
	    .hide();
	  /* check that the customer has agreed the T&C */
	  if( document.frmHIOrder.vilkar.checked == true ) {
	    $('#frmHIOrder')
	      .submit();
	  } else {
	    alert('Accepter venligst handelsbetingelserne');
	  }
	} else {
	  /* manage unknown location */
	  $('#frmHIOrder tr.wow-error-place')
	    .show();
	  $('#frmHIOrderBirthplace')
	    .empty();
	  $('#frmHIOrderBirthplace_text')
	    .empty()
	    .focus();
	}
      }
    ); /* end getJSON */
  } else {
    $('#frmHIOrder tr.wow-error-place')
      .show();
    $('#frmHIOrderBirthplace')
      .empty();
    $('#frmHIOrderBirthplace_text')
      .empty()
      .focus();
  }
  return false;
}

function agreeTC() {
  if( context.tcagreed == false ) {
    context.tcagreed = true;
    $("#frmHIOrder tr.wow-commit-purchase").show();
  } else {
    context.tcagreed = false;
    $("#frmHIOrder tr.wow-commit-purchase").hide();
  }
}

function submitOrder() {
  if( checkName() == false ) return;
  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();
}

function popup(theURL) { //v2.0
  leftPos = 0;
  topPos = 0;
  if (screen) {
    leftPos = (screen.width / 2) - 200;
    topPos = (screen.height / 2) - 150;
  }
  window.open(theURL,'','toolbar=no,status=no,menubar=no,scrollbars=no,resizable=no,width=400,height=350,left=' + leftPos + ',top =' + topPos);
}

function popupwithscroll(theURL) { //v2.0
  leftPos = 0;
  topPos = 0;
  if (screen) {
    leftPos = (screen.width / 2) - 200;
    topPos = (screen.height / 2) - 150;
  }
  window.open(theURL,'','toolbar=no,status=no,menubar=no,scrollbars=yes,resizable=no,width=400,height=350,left=' + leftPos + ',top =' + topPos);
}

function tunnel() {
  leftPos = 0;
  topPos = 0;
  if (screen) {
    leftPos = (screen.width / 2) - 200;
    topPos = (screen.height / 2) - 150;
  }
  window.open('about:blank','securetunnel','width=400,height=350,toolbar=no,menubar=no,status=no,resizable=no,scrollbars=no,left=' + leftPos + ',top =' + topPos);
}

function prepareReceipt( orderid ) {
  var product = 'Horoskop Analyser';
  var price = 0;
  var net = 0;
  var tax = 0;
  $.getJSON(
    'http://www.world-of-wisdom.com/06_affiliates/sme/ajax/prepare_receipt_remote.php?callback=?',
    {
      portalid : 34,
      orderid : parseInt( orderid )
    },
    function( response ) {
      if( response.valid == true ) {
	formatReceipt(
	  orderid,
	  response.product,
	  response.price,
	  response.net,
	  response.tax
	  );
      }
    }
  );
}

function formatReceipt( orderid, product, price, net, tax ) {
  var fmtReceipt = '<table width="100%">'
    + '<tr>'
    + '<th width="10%">Ordrenr.</th>'
    + '<th width="60%">Vare</th>'
    + '<th width="15%">Stk. Pris</th>'
    + '<th width="15%">Total Pris</th>'
    + '</tr>'
    + '<tr>'
    + '<td>' + orderid + '</td>'
    + '<td>' + product + '</td>'
    + '<td>' + price + ',00</td>'
    + '<td>' + price + ',00</td>'
    + '</tr>'
    + '<table>'
    + '<table width="100%"'
    + '<tr>'
    + '<th width="33%">Total excl. moms</th>'
    + '<th width="34%">Moms udg&oslash;r</th>'
    + '<th width="33%">Total incl. moms</th>'
    + '</tr>'
    + '<tr>'
    + '<th>' + net + ',00</th>'
    + '<th>' + tax + ',00</th>'
    + '<th>' + price + ',00</th>'
    + '</tr>'
    + '<table>';
  $('p#receipt').html( fmtReceipt );
}

$(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(
      'http://www.world-of-wisdom.com/wsapi/acs/suggest_remote2.php?callback=?'
    );

    $.getJSON(
      'http://www.world-of-wisdom.com/wsapi/acs/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('');
	context.setBirthCountry( $('#frmHIOrderBirthcountry').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();
	}
      });

    $('#frmHIOrderName').focus();

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

