// dependencies:
//  script/jQuery

//
// jquery extensions: 
//
(function($) {
  var __control_id_prefix = 'Register_';

  // find server-side control by id
  // leading '#' is optional
  $.asp = function(id) {
    if(id.charAt(0)=='#') id = id.substring(1);
    return $('#'+__control_id_prefix+id); 
  };

})(jQuery);



//
// startup
//
$(function() {
  $('#Country').change(populateProviders);
  $('#WirelessServiceProvider').change(cacheProviderValue);
  $.asp('#chk_SendSMS').click(toggleSMSfieldsVisibility);
  $('#header').hover(toggleHoverHelp,toggleHoverHelp);
  $.asp('#Location').attr('readonly','true');
  $.asp('#LocationText').bind('keypress', function(e) {
    if((e.keyCode || e.which) == 13) {
      setTimeout(SearchLocation, 1);
    };
  });

  var c = $.asp('#Country').val();
  var p = $.asp('#WirelessServiceProvider').val();
  populateCountry(c);
  populateProviders(p);
  
  if(isSMSchecked()) toggleSMSfieldsVisibility();
  
  var ip2loc = $.asp('#Location').val();
  if(ip2loc) CreateVirtualEarthMap(null, true);
});

function popupHelp(id) {  
  $.openDOMWindow({ 
      width:485,
      height:500,
      borderColor:'#0033ff',
      borderSize:2,
      overlay:0,
      windowSourceID:id
    });
}

function toggleHoverHelp() {
  $('#signupHoverHelp').toggleClass('hidden');
}

$.text2xml = function(sXML) { 
  var out; 
  try { 
    var dXML = ($.browser.msie)? new ActiveXObject("Microsoft.XMLDOM"): new DOMParser();
    dXML.async = false; 
  } catch(e) { throw new Error("XML Parser could not be instantiated"); }; 
  try { 
    if($.browser.msie) out = (dXML.loadXML(sXML))?dXML:false; 
    else out = dXML.parseFromString(sXML, "text/xml"); 
  } 
  catch(e){ throw new Error("Error parsing XML string"); }; 
  return out;
}

var countries;

function parseCountries(xml) {
  var arr = [];
  var i = 0;
  
  // Firefox, Opera, ...    
  var c = $(xml).find('countries').find('country');
  if(c.size()>0) {
    c.each(function() {   
      var name = this.childNodes[0].textContent;
      // * assumes fixed child order: (name, countryCode, provider)
      if(!i || arr[i-1].name != name) {  // a new country?
        arr[i] = new Object();
        arr[i].name = name;
        arr[i].code = this.childNodes[1].textContent;
        arr[i].providers = [];
        arr[i].providers.push(this.childNodes[2].textContent);
        ++i;
      }
      else {
        arr[i-1].providers.push(this.childNodes[2].textContent);
      }});
    return arr;
  }
  
  // IE
  c = $(xml).find('COUNTRIES').find('COUNTRY');
  c.each(function() {
    var name = this.selectSingleNode('NAME').text;
    if(!i || arr[i-1].name != name) {  // a new country?
      arr[i] = new Object();
      arr[i].name = name;
      arr[i].code = this.selectSingleNode('COUNTRYCODE').text;
      arr[i].providers = [];
      arr[i].providers.push(this.selectSingleNode('PROVIDER').text);
      ++i;
    }
    else {
      arr[i-1].providers.push(this.selectSingleNode('PROVIDER').text);
    }});
    
  return arr;
}

function populateCountry(selectedCountry) {
  var xmlRaw = $('#ProviderData').html();  
  $('#ProviderData').remove();
  countries = parseCountries($.text2xml(xmlRaw));

  var el = $('#Country')[0];
  el.options.length = 0;
  for(var i = 0; i < countries.length; i++) {
    var blurb = countries[i].name+' +'+countries[i].code;
    el.options[i] = new Option(blurb, i);
    el.options[i].selected = (blurb == selectedCountry);
  }
}

function populateProviders(selectedProvider) {
  var providersDl = $('#WirelessServiceProvider')[0];
  providersDl.options.length = 0;  
  var selectedIdx = $('#Country')[0].value;  
  selectedIdx = selectedIdx ? parseInt(selectedIdx) : 0;
  var p = countries[selectedIdx].providers;
  var i;
  for(i = 0; i < p.length; i++) {
    providersDl.options[i] = new Option(p[i], i);
    providersDl.options[i].selected = (p[i] == selectedProvider);
  }
  providersDl.options[i] = new Option("Other...", i);
  providersDl.options[i].selected = ("Other..." == selectedProvider);
  //
  cacheCountryValue();
  cacheProviderValue();
}

function cacheCountryValue() {
  var i = parseInt($('#Country').val());
  var c = $('#Country')[0][i];
  if(c.innerText) c=c.innerText; else c=c.text; //ie vs. ff
  $.asp('#Country').val(c);
}

function cacheProviderValue() {
  var i = parseInt($('#WirelessServiceProvider').val());
  var c = $('#WirelessServiceProvider')[0][i];
  if(c.innerText) c=c.innerText; else c=c.text; //ie vs. ff
  $.asp('#WirelessServiceProvider').val(c);
}

function ChangeLocation() { 
  $.openModalWindow("SetLocationDiv", "SetLocationOnSignUpShade");
  CreateVirtualEarthMap(UpdateLocation);
}

function UpdateLocation(loc) {
  $.asp('#Location').val(loc);
}

function toggleSMSfieldsVisibility() {
  $(".SMSinfo").toggleClass("hidden");
}

function isUsernameOk() {
  var illchars = /[\(\)\<\>\,\;\:\\\/\"\'\%\s\[\]]/;
  var username = $.asp('#Username');
  if(username.val() == "") {
   username.addClass('hilite');
   document.location = '#top';
   alert("Please enter a user name.");
   return false;
  }
  if (illchars.test(username.val())) {
   username.addClass('hilite');
   alert("The user name field contains invalid characters.\nPlease create a user name which does not contain\n( ) < > , ; : \\ / \" ' % [ ] or space");
   return false;
  }
  if(/^\d/.test(username.val())) {
   username.addClass('hilite');
   alert("Please create a user name which does not begin with a digit.");
   return false;  
  }
  var sync = true;
  if(!CheckIfUsernameAvailable(sync)) {
    username.addClass('hilite');
    return false;
  }
  return true;
}

function CheckIfUsernameAvailable(sync) {
  if(sync || isUsernameOk()) {
    clearHighlights();
    var u = $.asp('#Username').val();
    var resp = $.ajax({
      url: '../ajax/CheckUsername.ashx?username='+u,
      success: usernameCB,
      async: !sync,
      timeout: 1000, //ms
      error: function(e) {
        alert('The server did not respond.\nPlease try again later.');
      }
    });
    return resp.responseText.match('available');
  }
  return false;
}

function usernameCB(resp) {
  if(resp && resp.childNodes && resp.childNodes.length == 1 
    && (resp.childNodes[0].nodeTypedValue == 'available' ||  // IE
        resp.childNodes[0].text == 'available')) {           // FF
    $('.usernameAvailable').show();
    $('.usernameUnavailable').hide();    
  }
  else {
    $.asp('#Username').addClass('hilite');
    $('.usernameAvailable').hide();
    $('.usernameUnavailable').show();
  }
}

function ValidateForm() {
  clearHighlights();  
  return isUsernameOk() && isPasswordOk() && isEmailOk() && isSMSok() && isTermsCheckboxOk();
}

function isTermsCheckboxOk() {
  if($.asp('#TermsCheckBox:checked').val()) return true;
  alert("You must agree with the terms and conditions of service");
  return false;
}

function clearHighlights() {
  $.asp('#EmailAddy').removeClass('hilite');
  $.asp('#Username').removeClass('hilite');
  $.asp('#Password').removeClass('hilite');
  $.asp('#Password2').removeClass('hilite');
  $('#Country').removeClass('hilite');
  $('#WirelessServiceProvider').removeClass('hilite');
  $.asp('#PhoneNumber').removeClass('hilite');  
  $.asp('#CaptchaSolution').removeClass('hilite');
}

function isEmailOk() {
  var emailFilter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/;
  var email = $.asp('#EmailAddy');
  if(email.val() == "") {
    email.addClass('hilite');
    alert("Please enter an e-mail address");
    return false;
  }
  if (!(emailFilter.test(email.val())))  {
    email.addClass('hilite');
    alert("Please enter a valid email address.");
    return false;
  }
  return true;
}

function isPasswordOk() {
  var illchars = /[\x80-\xff]/;
  var pwd = $.asp('#Password');
  var pwd2 = $.asp('#Password2');
  
  if (pwd.val() == "") {
    pwd.addClass('hilite');
    document.location = '#top';
    alert("Please enter a password.");
    return false;
  }
  if (pwd2.val() == "") {
    pwd2.addClass('hilite');
    document.location = '#top';
    alert("Please confirm the password.");
    return false;
  }
  if (pwd.val() != pwd2.val()) {
    pwd.addClass('hilite');
    pwd2.addClass('hilite');
    document.location = '#top';
    alert("Passwords do not match.");
    return false;
  }
  if(illchars.test(pwd.val())) {
    pwd.addClass('hilite');
    pwd2.addClass('hilite');
    document.location = '#top';
    alert("Password contains invalid characters.\nPlease try again using ASCII<128");
    return false;
  }
  return true;
}

function isSMSchecked() {
  return $.asp('#chk_SendSMS:checked').val();
}

function isSMSok() {
  if(!isSMSchecked()) return true;
  var serviceProvider = $('#WirelessServiceProvider');
  if(!serviceProvider.val()) {
    $('#Country').addClass('hilite');
    serviceProvider.addClass('hilite');
    alert("Please select your country and wireless service provider.");
    return false;
  }  

  var phoneNum = $.asp('#PhoneNumber');
  var n = phoneNum.val().replace(/[^\d]/g,''); // strip non-#s
  var sms = /^[\d]{7,16}$/;
  if(!sms.test(n) || !phoneNum.val()) {
    phoneNum.addClass('hilite');
    alert("Please enter a valid mobile phone number.");
    return false;
  }
  return true;
}

////////////////////////////////////////////////////////////////////////
///////////////////// VE MAP & MapTP support ///////////////////////////
////////////////////////////////////////////////////////////////////////
//dependencies:
// + <script type="text/javascript" src="http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.1" />
// + <script type="text/javascript" src="http://api.maptp.map24.com/ajax?appkey=FJX43acd003821e27d8d8deb62d069fdX17"></script>
// + jQuery

var pushpin = null;
var map = null;   
var isNavteqReady = false;

$(function() {
  // init Navteq
  Map24.loadApi(["core_api", "wrapper_api"], navteqReady);
});

function navteqReady() {
  Map24.MapApplication.init( { NodeName: "navteqMap", MapType: "Static" } );
  isNavteqReady = true;
}

var UpdateLocationCallback;

function CreateVirtualEarthMap(updateLocationCallback, fromIP2Loc) {
  UpdateLocationCallback = updateLocationCallback; 
  __fromIP2LocHack = fromIP2Loc;
  
  var lat = $.asp('#Latitude').val();
  var lon = $.asp('#Longitude').val();
  var zoom = $.asp('#Zoom').val();
  var targetDiv = 'mapDiv';

 if(map) {
    map.Dispose();
    map = null;
  }
  map = new VEMap( targetDiv );
  map.SetDashboardSize(VEDashboardSize.Small);  
  
  if(lat && lon && zoom) {
    var fixed = false;
    var showSwitch = true;
    var tileBuffer = 0; // 0 to 3
    map.LoadMap(new VELatLong(lat, lon), zoom, VEMapStyle.Road, fixed, VEMapMode.Mode2D, showSwitch, tileBuffer);  
  }
  else {
    map.LoadMap(null, null, VEMapStyle.Road);
    var loc = $.asp("#Location").val();
    if(loc) { 
      $.asp("#LocationText").val(loc);
      SearchLocation();
    }
  }
  
  var icon = "<div><img src='images/marker.gif'></div>";
  pushpin = new VEShape(VEShapeType.Pushpin, map.GetCenter());
  pushpin.SetCustomIcon(icon);
  map.AddShape(pushpin);
    
  map.AttachEvent("onmousemove", mapMoveHandler);
  map.AttachEvent("onchangeview", mapChangeViewHandler);
  map.AttachEvent("onendzoom", mapZoomHandler);
  
  mapReverseGeocode(null);
}

var __fromIP2LocHack = false;
var __skipChangeView = false;

function mapChangeViewHandler(e) {
  if(__skipChangeView) { __skipChangeView = false; return; }
  if(__fromIP2LocHack) { __fromIP2LocHack = false; __skipChangeView = true; map.SetZoomLevel(10); }
  mapMoveHandler(e);
  mapReverseGeocode(e);
}

function mapMoveHandler(e) {
	var latlon = map.GetCenter();
  if(pushpin && pushpin.GetPoints()[0] != latlon)
	  pushpin.SetPoints([latlon]);
  
  var zoom = map.GetZoomLevel();
  $.asp('#Latitude').val(latlon.Latitude);
  $.asp('#Longitude').val(latlon.Longitude);
  $.asp('#Zoom').val(zoom);
  $('#DisplayLatitude').html(latlon.Latitude);
  $('#DisplayLongitude').html(latlon.Longitude);
  $('#DisplayZoom').html(zoom);
}

function mapReverseGeocode(e) {
  if(isNavteqReady) {
    $('#ReverseGeoSpinner').show();
    var geocoder = new Map24.GeocoderServiceStub();
    var lat = $.asp('#Latitude').val() * 60.0;
    var lon = $.asp('#Longitude').val() * 60.0;
    geocoder.reverseGeocode({ Longitude: lon, Latitude: lat, CallbackFunction: rvsGeocodeCallback });  
  }
  else {
    setTimeout(mapReverseGeocode, 500);
  }
}

function mapZoomHandler(e) {
  var z = map.GetZoomLevel();
  $.asp('#Zoom').val(z);
  $('#DisplayZoom').html(z);
  showLocation(rvsGeocodeLoc);
}

var rvsGeocodeLoc;

function rvsGeocodeCallback(location){
  rvsGeocodeLoc = location;
  showLocation(rvsGeocodeLoc);  
}

function showLocation(loc) {
  if(!loc) return;
  var zoom = $.asp('#Zoom').val();
  var text = loc.getCountry() ? loc.getCountry() : "";
  if(zoom >= 4 && loc.getState()) text = loc.getState() + ", " + text;
//  if(zoom >= 5 && zoom <= 7 && loc.getCounty()) text = loc.getCounty()+", "+text;
//  if(zoom >= 8 && loc.getCity()) 
  if(loc.getCity()) text = loc.getCity()+", "+text; // no more street address per Jennifer 2-mar-09
//  if(zoom >= 11 && loc.getStreet()) text = loc.getStreet()+", "+text;
//  if(zoom >= 12 && loc.getHouseNo()) text = loc.getHouseNo()+" "+text;
  $('#ReverseGeoSpinner').hide();
  $('#ReverseGeoResult').html(text);
}

function SearchLocation() {
  var loc = $.asp('#LocationText').val();
  FindLocation(loc);
}

function FindLocation(loc) {
  map.Find(null, loc);
}

function SaveLocationF() {
  mapCleanUp();
  if(UpdateLocationCallback) UpdateLocationCallback($('#ReverseGeoResult').html());
}

function CancelSetLocation() {
  $.asp('#Latitude').val(null);
  $.asp('#Longitude').val(null);
  $.asp('#Zoom').val(null);  
  mapCleanUp();
}

function mapCleanUp() {
  $.closeModalWindow('SetLocationDiv', 'SetLocationOnSignUpShade');
  map.Dispose();
  map = null;
}