/**
 * Initialization script for taxi ordering feature
 *
 * Daniel Nordstrom
 * Nintera(ctive)
 */

  if(typeof String.prototype.trim !== 'function') {
	  String.prototype.trim = function() {
	    return this.replace(/^\s+|\s+$/g, ''); 
	  }
	}  

/**
 * Add validation method for street names
 */
jQuery.validator.addMethod("street", function(value, element) {
	var cityID = 0;
	if($('#departure_city').length > 0) {
		cityID = $('#departure_city').val();
	}
	else if($('#place').length > 0) {
		cityID = $('#place').val();
	}
	
	var streetCheck = OrderSystem.prototype.path + 'php/getAutocomplete.php?city=' + cityID + '&q=' + value.trim();
	var streetFound = false;
	/* Check departure address */
	$.ajax({
		method: 	"GET", 
    url:      streetCheck,
		async: 		false,
    success:  function(data) {
								streets = data.split('\n');

								for(var x = 0; x < streets.length; x++) {
									if(streets[x] != '' && streets[x] == value.trim().toUpperCase()) {
										streetFound = true;
									}
								}
              }
  });
	return streetFound;
}, "Please enter a valid street address.");

/**
 * Starting class definition
 */ 
var OrderSystem = function() {};

  /* Relative URL to the ordering system, with trailing slash */
  OrderSystem.prototype.path = window.location.pathname.replace(/frontpage(\/)?$/, '').replace(/\/(en|nl)(\/?)?$/, '/');
  OrderSystem.prototype.path += 'sites/all/modules/ordersystem/';
  if (typeof ordersystem_path !== 'undefined') OrderSystem.prototype.path = ordersystem_path;
  
  /* URL to website, no trailing slash */
  OrderSystem.prototype.url = 'http://' + window.location.host;
  if (typeof ordersystem_url !== 'undefined') OrderSystem.prototype.url = ordersystem_url;
  
  /* Keeps track of window fragment identifier (hash) */
  OrderSystem.prototype.hash = '';
  
  /* Default example remarks text for text field will be fetched here. */
  OrderSystem.prototype.remarks = '';
  
  /* Default language */
  OrderSystem.prototype.lang = 'nl';
  
  /**
   * Resizes the parent dialog box of iframe by using fragment identifier
   *
   * @param New size of dialog box
   */
  OrderSystem.prototype.resizeParent = function(size) {
   /* Resize dialog window */
   window.top.location.hash = '#resize-' + size;
  }
  
  /**
   * Close the parent dialog box of the iframe
   */
  OrderSystem.prototype.closeParent = function(size) {
   /* Resize dialog window */
   window.top.location.hash = '#close';
  }
  
  /**
   * Initialize textarea example text
   */
  OrderSystem.prototype.initTextarea = function() {
    $('#remarks').addClass('example');
    OrderSystem.prototype.remarks = $('#remarks').val();
    $('#remarks').focus(function() {
      if($(this).val() == OrderSystem.prototype.remarks) {
        $(this).removeClass('example');
        $(this).val('');
      }
    });
    $('#remarks').blur(function() {
      if($(this).val() == '') {
        $(this).addClass('example');
        $(this).val(OrderSystem.prototype.remarks);
      }
    });
  }

  
  /**
   * Calculates taxi ride price
   *
   * @param Distance of route
   */
  OrderSystem.prototype.calculatePrice = function(distance) {
  	/**
  	 * Each of the pricing arrays consist of three elements:
  	 * 1: kilometers from which the price should be valid
  	 * 2: price per kilometer
  	 * 3: one time price
  	 * The array should be sorted top-down, the longest distance as first element
  	 */
  	var prices = [
  	    [50, 1.45, 0],
  	    [25, 1.75, 0],
  	    [2, 2.2, 0],
  	    [0, 0, 7.5]
  	  ];
  	var totalPrice = 0;
  	
  	for(var x = 0; x < prices.length; x++) {
  		if(distance >= prices[x][0]) {
  			totalPrice += ((distance - prices[x][0]) * prices[x][1]) + prices[x][2];
  			distance = prices[x][0];
  		}
  	}
  	totalPrice = Math.round(totalPrice * 20) / 20;
  	return totalPrice.toFixed(2);
  }
  
  /**
   * Initialize step one of TCA website ordering process
   */
  OrderSystem.prototype.initTCAStepOne = function(dep_address, dep_nr, dep_suffix, dep_city, dest_address, dest_nr, dest_suffix, dest_city, time) {
    /* Template file to load next */
    /* Get previous form values if provided */
    var template = OrderSystem.prototype.path + 'templates/order.step-2.php';

    if(dep_address !== undefined) {
      $('#departure_address').val(dep_address);
      $('#departure_nr').val(dep_nr);
      $('#departure_suffix').val(dep_suffix);
      $('#destination_address').val(dest_address);
      $('#destination_nr').val(dest_nr);
      $('#destination_suffix').val(dest_suffix);
      // $("select#time option").each(function() { this.selected = (this.text == time); });
    }
    
    /* Prepare autocomplete fields */
    OrderSystem.prototype.initAutocomplete();
    
    /* Addresses needs to be filled in before number */
    $('#departure_nr').click(function() {
      if($('#departure_address').val().length < 3) {
        $(this).blur();
      }
    });
    
    $('#destination_nr').click(function() {
      if($('#destination_address').val().length < 3) {
        $(this).blur();
      }
    });
    
    /* Bind button click */
    $('#submit').click(function() {
      var dep_address   = $('#departure_address').val().trim();
      var dep_nr        = $('#departure_nr').val();
      var dep_suffix    = $('#departure_suffix').val();
      var dep_city      = $('#departure_city').val();
      var dest_address  = $('#destination_address').val().trim();
      var dest_nr       = $('#destination_nr').val();
      var dest_suffix   = $('#destination_suffix').val();
      var dest_city     = $('#destination_city').val();
      var time          = (parseInt($('#date').val())+parseInt($('#time').val()));

      /* Validate form */
      var validator = $("form").validate({
         rules: {
           departure_address:   "street",
           departure_nr:        "required",
           departure_city:      "required",
           destination_address: "required",
           destination_nr:      "required",
           destination_city:    "required"
         },
         messages: {
            departure_address:   "",
            departure_nr:        "",
            departure_city:      "",
            destination_address: "",
            destination_nr:      "",
            destination_city:    ""
          },
          onkeyup:    false,
          onfocusout: false,
          onclick:    false
      });
      
      if(validator.form() === false) {
        return false;
      }
      
      $.ajax({
        url:      template,
        data:     {
                    "dep_city":   dep_city,
                    "dest_city":  dest_city,
                    "time":       time
                  },
        success:  function(data) {
                    $.fn.colorbox.resize({ height: 770 });
                    $('#order-system').parent().html(data);
                    
                    OrderSystem.prototype.initTCAStepTwo(dep_address.trim().toUpperCase(), dep_nr, dep_suffix, dep_city, dest_address.trim().toUpperCase(), dest_nr, dest_suffix, dest_city, time);
                  }
      });
      /* Return false to disable link */
      return false;
    });
  }
  
  /**
   * Initialize step two
   */
  OrderSystem.prototype.initTCAStepTwo = function(dep_address, dep_nr, dep_suffix, dep_city, dest_address, dest_nr, dest_suffix, dest_city, time) {
    /* Get form values */
    $('#departure_address').html(dep_address);
    $('#departure_nr').html(dep_nr);
    $('#departure_suffix').html(dep_suffix);
    //$('#departure_city').html(dep_city);
    //$('#departure_time').html(time);
    $('#destination_address').html(dest_address);
    $('#destination_nr').html(dest_nr);
    $('#destination_suffix').html(dest_suffix);
    //$('#destination_city').html(dest_city);
    
    /* Create Google Maps API map, service and renderer objects */
    var mapOptions = {
      mapTypeId:  google.maps.MapTypeId.ROADMAP
    }
    var directionsService   = new google.maps.DirectionsService();
    var directionsDisplay   = new google.maps.DirectionsRenderer();
    var map                 = new google.maps.Map(document.getElementById("map"), mapOptions);
    directionsDisplay.setMap(map);
    
    /* Request directions using Google Directions API */
    var request = {
      origin:         dep_address + ' ' + dep_nr + dep_suffix + ', ' + $('#departure_city').html(),
      destination:    dest_address + ' ' + dest_nr + dest_suffix + ', ' + $('#destination_city').html(),
      travelMode:     google.maps.DirectionsTravelMode.DRIVING,
      unitSystem:     google.maps.DirectionsUnitSystem.IMPERIAL
    };
    directionsService.route(request, function(response, status) {
      /* Display results using DirectionsRenderer object */
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
      }
      
      /* Get distance in kilometres */
      var distance  = response.routes[0].legs[0].distance.value / 1000;
      var price     = OrderSystem.prototype.calculatePrice(distance);
      
      /* Display price */
      $('#ride-price').html(price);
      
    });
    
    /* Template file to load next */
    var template = OrderSystem.prototype.path + 'templates/order.step-3.php';
    
    /* Bind button click */
    $('#submit').click(function() {
      $.ajax({
        url:      template,
        data:     {
                    "dep_city":   dep_city,
                    "dest_city":  dest_city,
                    "time":       time
                  },
        success:  function(data) {
                    $.fn.colorbox.resize({ height: 520 });
                    $('#order-system').parent().html(data);
                    OrderSystem.prototype.initTCAStepThree(dep_address, dep_nr, dep_suffix, dep_city, time, dest_address, dest_nr, dest_suffix, dest_city);
                  }
      });
      /* Return false to disable link */
      return false;
    });
    
    /* Set up back links */
    $('.back').click(function() {
      var template = OrderSystem.prototype.path + 'templates/order.step-1.php';
      $.ajax({
        url:      template,
        data:     {
                    "dep_city":   dep_city,
                    "dest_city":  dest_city,
                    "time":       time
                  },
        success:  function(data) {
                    $.fn.colorbox.resize({ height: 520 });
                    $('#order-system').parent().html(data);
                    OrderSystem.prototype.initTCAStepOne(dep_address, dep_nr, dep_suffix, dep_city, dest_address, dest_nr, dest_suffix, dest_city, time);
                  }
      });
      /* Return false to disable link */
      return false;
    });
  }
  
  /**
   * Initialize step three
   */
  OrderSystem.prototype.initTCAStepThree = function(dep_address, dep_nr, dep_suffix, dep_city, dep_time, dest_address, dest_nr, dest_suffix, dest_city) {
    /* Get form values */
    $('#departure_address').html(dep_address);
    $('#departure_nr').html(dep_nr);
    $('#departure_suffix').html(dep_suffix);
    //$('#departure_city').html(dep_city);
    $('#destination_address').html(dest_address);
    $('#destination_nr').html(dest_nr);
    $('#destination_suffix').html(dest_suffix);
    //$('#destination_city').html(dest_city);
    
    /* Initialize textarea example text */
    OrderSystem.prototype.initTextarea();
    
    /* Template file to load next */
    var template = OrderSystem.prototype.path + 'templates/order.step-4.php';
    
    /* Bind button click */
    $('#submit').click(function() {
      /* Validate form */
      var validator = $("form").validate({
         rules: {
           name:    "required",
           phone:   "required",
           remarks: "required",
           email:   {
             required:  true,
             email:     true
           }
         },
         messages: {
            remarks:  "",
            name:     "",
            phone:    "",
            email:    ""
          }
      });
      $("#phone").rules("add", {
        minlength: 9,
        maxlength: 14
      });
      
      if(validator.form() === false) {
        return false;
      }
      
      var remarks = $('#remarks').val();
      
      $.ajax({
        url:      template,
        type:     "GET",
        data:     {
                    "name":         $('#name').val(),
                    "phone":        $('#phone').val(),
                    "email":        $('#email').val(), 
                    "remarks":      remarks,   
                    "dep_address":  dep_address,
                    "dep_nr":       dep_nr,
                    "dep_suffix":   dep_suffix,
                    "dep_city":     dep_city,
                    "dep_time":     dep_time,
                    "dest_address": dest_address,
                    "dest_nr":      dest_nr,
                    "dest_suffix":  dest_suffix,
                    "dest_city":    dest_city
                  },
        success:  function(data) {
                    $.fn.colorbox.resize({ height: 480 });
                    $('#order-system').parent().html(data);
                    OrderSystem.prototype.initTCAStepFour(dep_address, dep_nr, dep_suffix, dep_time, dep_city, dest_address, dest_nr, dest_suffix, dest_city, remarks);
                  }
      });
      /* Return false to disable link */
      return false;
    });
  }
  
  /**
   * Initialize step four
   */
  OrderSystem.prototype.initTCAStepFour = function(dep_address, dep_nr, dep_suffix, dep_city, dep_time, dest_address, dest_nr, dest_suffix, dest_city, remarks) {
    /* Get form values */
    $('#departure_address').html(dep_address);
    $('#departure_nr').html(dep_nr);
    $('#departure_suffix').html(dep_suffix);
    //$('#departure_city').html(dep_city);
    $('#destination_address').html(dest_address);
    $('#destination_nr').html(dest_nr);
    $('#destination_suffix').html(dest_suffix);
    //$('#destination_city').html(dest_city);
    $('#remarks').html(remarks);
    
    /* Bind button click */
    $('#submit').click(function() {
      $.fn.colorbox.close();
      /* Return false to disable link */
      return false;
    });
  }
  
  /**
   * Initialize step one of TCA website ordering process
   */
  OrderSystem.prototype.initExternalStepOne = function(dep_address, dep_nr, dep_suffix, dep_city, dest_name, dest_address, dest_nr, dest_suffix, dest_city, time) {
    
    /* Template file to load next */
    var template = OrderSystem.prototype.path + 'templates/iframe.step-2.php';
    
    /* Get previous form values if provided */
    if(dep_address !== undefined) {
      $('#departure_address').val(dep_address);
      $('#departure_nr').val(dep_nr);
      $('#departure_suffix').val(dep_suffix);
      $('#departure_city').val(dep_city);
      $('#destination_name').val(dest_name);
      $('#destination_address').val(dest_address);
      $('#destination_nr').val(dest_nr);
      $('#destination_suffix').val(dest_suffix);
      $('#destination_city').val(dest_city);
      //$("select#time option").each(function() { this.selected = (this.text == time); });
    }
    
    /* Prepare autocomplete fields */
    OrderSystem.prototype.initAutocomplete();
    
    /* Addresses needs to be filled in before number */
    $('#departure_nr').click(function() {
      if($('#departure_address').val().length < 3) {
        $(this).blur();
      }
    });
    
    /* Bind button click */
    $('#submit').click(function() {
      var dep_address   = $('#departure_address').val().trim();
      var dep_nr        = $('#departure_nr').val();
      var dep_suffix    = $('#departure_suffix').val();
      var dep_city      = $('#departure_city').val();
      var dest_name     = $('#destination_name').val();
      var dest_address  = $('#destination_address').val().trim();
      var dest_nr       = $('#destination_nr').val();
      var dest_suffix   = $('#destination_suffix').val();
      var dest_city     = $('#destination_city').val();
      var time          = $('#time').val();
      
      /* Validate form */
      var validator = $("form").validate({
         rules: {
           departure_address:   "required",
           departure_nr:        "required",
           departure_city:      "required",
           destination_address: "required",
           destination_nr:      "required",
           destination_city:    "required"
         },
         messages: {
            departure_address:   "",
            departure_nr:        "",
            departure_city:      "",
            destination_address: "",
            destination_nr:      "",
            destination_city:    ""
          },
          onkeyup:    false,
          onfocusout: false,
          onclick:    false
      });
      
      if(validator.form() === false) {
        return false;
      }
      
      $.ajax({
        url:      template,
        data:     {
                    "dep_city":   dep_city,
                    "dest_city":  dest_city,
                    "dep_time":   time
                  },
        success:  function(data) {
                    /* Resize dialog box */
                    OrderSystem.prototype.resizeParent(770);
                    $('#order-system').parent().html(data);
                    OrderSystem.prototype.initExternalStepTwo(dep_address, dep_nr, dep_suffix, dep_city, dest_name, dest_address, dest_nr, dest_suffix, dest_city, time);
                  }
      });
      /* Return false to disable link */
      return false;
    });
  }
  
  /**
   * Initialize step two
   */
  OrderSystem.prototype.initExternalStepTwo = function(dep_address, dep_nr, dep_suffix, dep_city, dest_name, dest_address, dest_nr, dest_suffix, dest_city, time) {
    /* Get form values */
    $('#departure_address').html(dep_address);
    $('#departure_nr').html(dep_nr);
    $('#departure_suffix').html(dep_suffix);
    //$('#departure_city').html(dep_city);
    //$('#departure_time').html(time);
    $('#destination_name').html(dest_name);
    $('#destination_address').html(dest_address);
    $('#destination_nr').html(dest_nr);
    $('#destination_suffix').html(dest_suffix);
    //$('#destination_city').html(dest_city);
    
    /* Create Google Maps API map, service and renderer objects */
    var mapOptions = {
      mapTypeId:  google.maps.MapTypeId.ROADMAP
    }
    var directionsService   = new google.maps.DirectionsService();
    var directionsDisplay   = new google.maps.DirectionsRenderer();
    var map                 = new google.maps.Map(document.getElementById("map"), mapOptions);
    directionsDisplay.setMap(map);
    
    /* Request directions using Google Directions API */
    var request = {
      origin:         dep_address + ' ' + dep_nr + dep_suffix + ', ' + $('#departure_city').html(),
      destination:    dest_address + ' ' + dest_nr + dest_suffix + ', ' + $('#destination_city').html(),
      travelMode:     google.maps.DirectionsTravelMode.DRIVING,
      unitSystem:     google.maps.DirectionsUnitSystem.IMPERIAL
    };
    directionsService.route(request, function(response, status) {
      /* Display results using DirectionsRenderer object */
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
      }
      
      /* Get distance in kilometres */
      var distance  = response.routes[0].legs[0].distance.value / 1000;
      var price     = OrderSystem.prototype.calculatePrice(distance);
      
      /* Display price */
      $('#ride-price').html(price);
      
    });
    
    /* Template file to load next */
    var template = OrderSystem.prototype.path + 'templates/iframe.step-3.php';
    
    /* Bind button click */
    $('#submit').click(function() {
      $.ajax({
        url:      template,
        data:     {
                    "dep_city":   dep_city,
                    "dest_city":  dest_city,
                    "dep_time":   time
                  },
        success:  function(data) {
                    /* Resize dialog box */
                    OrderSystem.prototype.resizeParent(520);
                    $('#order-system').parent().html(data);
                    OrderSystem.prototype.initExternalStepThree(dep_address, dep_nr, dep_suffix, dep_city, time, dest_name, dest_address, dest_nr, dest_suffix, dest_city);
                  }
      });
      /* Return false to disable link */
      return false;
    });
    
    /* Set up back links */
    $('.back').click(function() {
      var template = OrderSystem.prototype.path + 'templates/iframe.step-1.php';
      $.ajax({
        url:      template,
        type:     "GET",
        data:     {
                    name:         dest_name,
                    addr:         dest_address,
                    nr:           dest_nr,
                    suff:         dest_suffix,
                    city:         dest_city,
                    "dep_city":   dep_city,
                    "dest_city":  dest_city,
                    "dep_time":   time
                  }, 
        success:  function(data) {
                    /* Resize dialog box */
                    OrderSystem.prototype.resizeParent(550);
                    $('#order-system').parent().html(data);
                    OrderSystem.prototype.initExternalStepOne(dep_address, dep_nr, dep_suffix, dep_city, dest_name, dest_address, dest_nr, dest_suffix, dest_city, time);
                  }
      });
      /* Return false to disable link */
      return false;
    });
  }
  
  /**
   * Initialize step three
   */
  OrderSystem.prototype.initExternalStepThree = function(dep_address, dep_nr, dep_suffix, dep_city, dep_time, dest_name, dest_address, dest_nr, dest_suffix, dest_city) {
    /* Get form values */
    $('#departure_address').html(dep_address);
    $('#departure_nr').html(dep_nr);
    $('#departure_suffix').html(dep_suffix);
    //$('#departure_city').html(dep_city);
    $('#destination_name').html(dest_name);
    $('#destination_address').html(dest_address);
    $('#destination_nr').html(dest_nr);
    $('#destination_suffix').html(dest_suffix);
    //$('#destination_city').html(dest_city);
    
    /* Initialize textarea example text */
    OrderSystem.prototype.initTextarea();
    
    /* Template file to load next */
    var template = OrderSystem.prototype.path + 'templates/iframe.step-4.php';
    
    /* Bind button click */
    $('#submit').click(function() {
      /* Validate form */
      var validator = $("form").validate({
         rules: {
           name:    "required",
           phone:   "required",
           remarks: "required",
           email:   {
             required:  true,
             email:     true
           }
         },
         messages: {
            remarks: "",
            name:    "",
            phone:   "",
            email:   ""
          }
      });
      
      if(validator.form() === false) {
        return false;
      }
      
      var remarks = $('#remarks').html();
      
      $.ajax({
        url:      template,
        type:     "GET",
        data:     {
                    "name":         $('#name').val(),
                    "phone":        $('#phone').val(),
                    "email":        $('#email').val(),
                    "remarks":      remarks,
                    "dep_address":  dep_address,
                    "dep_nr":       dep_nr,
                    "dep_suffix":   dep_suffix,
                    "dep_city":     dep_city,
                    "dep_time":     dep_time,
                    "dest_name":    dest_name,
                    "dest_address": dest_address,
                    "dest_nr":      dest_nr,
                    "dest_suffix":  dest_suffix,
                    "dest_city":    dest_city
                  },
        success:  function(data) {
                    /* Resize dialog box */
                    OrderSystem.prototype.resizeParent(490);
                    $('#order-system').parent().html(data);
                    OrderSystem.prototype.initExternalStepFour(dep_address, dep_nr, dep_suffix, dep_time, dep_city, dest_name, dest_address, dest_nr, dest_suffix, dest_city, remarks);
                  }
      });
      /* Return false to disable link */
      return false;
    });
  }
  
  /**
   * Initialize step four
   */
  OrderSystem.prototype.initExternalStepFour = function(dep_address, dep_nr, dep_suffix, dep_city, dep_time, dest_name, dest_address, dest_nr, dest_suffix, dest_city, remarks) {
    /* Get form values */
    $('#departure_address').html(dep_address);
    $('#departure_nr').html(dep_nr);
    $('#departure_suffix').html(dep_suffix);
    //$('#departure_city').html(dep_city);
    $('#destination_name').html(dest_name);
    $('#destination_address').html(dest_address);
    $('#destination_nr').html(dest_nr);
    $('#destination_suffix').html(dest_suffix);
    //$('#destination_city').html(dest_city);
    $('#remarks').html(remarks);
    
    /* Bind button click */
    $('#submit').click(function() {
      OrderSystem.prototype.closeParent();
      /* Return false to disable link */
      return false;
    });
  }

  /**
   * Initialize button generator first step
   */
  OrderSystem.prototype.initGeneratorStepOne = function() {
		/* Prepare autocomplete fields */
    OrderSystem.prototype.initAutocomplete();

    /* Next step template */
    var template = OrderSystem.prototype.path + 'templates/generator.step-2.php';

    /* Bind button click */
    $('#submit').click(function() {
			/* Validate form */
      var validator = $("form").validate({
         rules: {
					 name: 		  "required",
					 email: 	  {
												email: 		true,
												required: true
											},
					 phone: 	  "required",
           address:   "street",
           nr:        "required",
           place:     "required"
         },
         messages: {
           name: 		  "",
					 email: 	  "",
					 phone: 	  "",
	         address:   "",
	         nr:        "",
	         place:     ""
          }
      });
      
      if(validator.form() === false) {
        return false;
      }

      /* Get form values */
      var name     = $('#name').val();
      var place    = $('#place').val();
      var address  = $('#address').val();
      var nr       = $('#nr').val();
      var suffix   = $('#suffix').val();
      var email    = $('#email').val();
      var phone    = $('#phone').val();

      $.ajax({
        url:      template,
        success:  function(data) {
                    $.fn.colorbox.resize({ height: 480 });
                    $('#order-system').parent().html(data);
                    OrderSystem.prototype.initGeneratorStepTwo(name, place, address, nr, suffix, email, phone);
                  }
      });
      /* Return false to disable link */
      return false;
    });
  }
   
  /**
   * Initialize button generator second step
   */
  OrderSystem.prototype.initGeneratorStepTwo = function(name, place, address, nr, suffix, email, phone) {
    /* Bind buttons to their respective radio buttons */
    $('.button').each(function() {
      $(this).click(function() {
        $(this).next().attr('checked', 'checked');
      });
    });
    
    /* Next step template */
    var template = OrderSystem.prototype.path + 'templates/generator.step-3.php';

    /* Bind button click */
    $('#submit').click(function() {
      /* Get selected button */
      var button = $('input:radio:checked').val();

      $.ajax({
        url:      template,
				data: 		{
										"name": 		name,
										"place": 		place,
										"address": 	address,
										"nr": 			nr,
										"suffix": 	suffix,
										"email": 		email,
										"phone": 		phone,
										"button": 	button
									},
        success:  function(data) {
                    $.fn.colorbox.resize({ height: 480 });
                    $('#order-system').parent().html(data);
                    OrderSystem.prototype.initGeneratorStepThree(name, place, address, nr, suffix, email, phone, button);
                  }
      });
      /* Return false to disable link */
      return false;
    });
  }
  
  /**
   * Initialize button generator second step
   */
  OrderSystem.prototype.initGeneratorStepThree = function(name, place, address, nr, suffix, email, phone, button) {
    /* Bind buttons to their respective radio buttons */
    $('.button').each(function() {
      $(this).click(function() {
        $(this).next().attr('checked', 'checked');
      });
    });
    
    $('#code').click(function() {
      $(this).focus().select();
    });
    
    /* Bind button click */
    $('#submit').click(function() {
      $.fn.colorbox.close({ height: 480 });
      return false;
    });
  }
  
  /**
   * Initializes ordering button
   *
   * @param tca TRUE if the TCA website itself is loading the object
   */
  OrderSystem.prototype.initButton = function(tca) {
    /* Determine init function - different for TCA website and client websites */
    if(tca === true) {
      /* Get current language from URL */
      if (window.location.pathname.lastIndexOf('/en') != -1) {
	  	OrderSystem.prototype.lang = 'en';
      }
      var callback = this.initTCAStepOne;
      /* Bind button to AJAX dialog */
      $('a[rel="order-system"]').attr("href", OrderSystem.prototype.url + OrderSystem.prototype.path + 'templates/order.step-1.php?lang=' + OrderSystem.prototype.lang).colorbox({
        width:      680,          // Width of dialog box
        height:     590,          // Height of dialog box
        opacity:    0.6,          // Opacity of dialog box
        scroll:     false,        // Hide scroll bar
        onComplete: callback     // First step init callback
      });
    }
    else {
      var callback = this.initExternalStepOne;
      /* Bind button to AJAX dialog */
      $('a[rel="order-system"]').colorbox({
        width:      680,          // Width of dialog box
        height:     550,          // Height of dialog box
        opacity:    0.6,          // Opacity of dialog box
        scroll:     false,        // Hide scroll bar
        onComplete: callback,     // First step init callback
        iframe:     true         // Put content in iframe since it's cross-domain
      });
    }
    
    
    /* Initialize button generator button */
    callback = this.initGeneratorStepOne;
    
    /* Bind button to AJAX dialog */
    $('a[rel="button-generator"]').attr("href", OrderSystem.prototype.url + OrderSystem.prototype.path + 'templates/generator.step-1.php?lang=' + OrderSystem.prototype.lang).colorbox({
      width:      680,          // Width of dialog box
      height:     510,          // Height of dialog box
      opacity:    0.6,          // Opacity of dialog box
      scroll:     false,        // Hide scroll bar
      onComplete: callback     // First step init callback
    });
  }
  
  /**
   * Initialize autocomplete addresses field
   */
  OrderSystem.prototype.initAutocomplete = function() {
    var url     = OrderSystem.prototype.path + 'php/getAutocomplete.php';
    var options = {
      minChars: 3,
      width: 180,
      extraParams: {
        city: $('#departure_city').val()
      }
    }
    $('#departure_address').autocomplete(url, options);
    //$('#destination_address').autocomplete(url, options);
		$('#address').autocomplete(url, options);
		
		$('#departure_city').change(function() {
	    options = {
	      minChars: 3,
	      width: 180,
	      extraParams: {
	        city: $('#departure_city').val()
	      }
	    }
	    $('#departure_address').setOptions(options);
		});
		
		options = {
      minChars: 3,
      width: 180,
      extraParams: {
        city: $('#place').val()
      }
    }
		$('#address').autocomplete(url, options);
		$('#place').change(function() {
	    options = {
	      minChars: 3,
	      width: 180,
	      extraParams: {
	        city: $('#place').val()
	      }
	    }
	    $('#address').setOptions(options);
		});
  }
  
  /**
   * Add the order system button to the page
   */
  OrderSystem.prototype.printButton = function() {
    // var url     = OrderSystem.prototype.url + OrderSystem.prototype.path + 'css/images/' + ordersystem_button;
    //     $('#tca_ordersystem_button').attr('src', url);
  }
  
  /**
   * Check if the fragment identifier of the window has changed
   */
  OrderSystem.prototype.hashChanged = function() {
    var hash = parent.window.location.hash.slice(1);
    if(hash != OrderSystem.prototype.hash) {
      OrderSystem.prototype.hash = hash;
      return true;
    }
    return false;
  }
  
  /**
   * Return the current fragement identifier of the browser window
   */
  OrderSystem.prototype.getHash = function() {
    return OrderSystem.prototype.hash;
  }
  
