var quoteRequestController;

var QuoteRequestController = Class.create({
	baseHref: false,
	//Departure -> Return Time selects copy for updateReturnTime()
	departureTimeSelects: ['dep_day','dep_month','dep_year','dep_time'],
	returnTimeSelects:   ['ret_day','ret_month','ret_year','ret_time'],
	
  initialize:function()
  {
	  this.baseHref=$('baseTag').href;
    this.setupEvents();
    this.updateReturnFlightDetailsAreVisible();
  },

  setupEvents:function() {
    $('return_yes').observe('click', function(evnt) { this.updateReturnFlightDetailsAreVisible(); }.bind(this) );
    $('return_no').observe('click', function(evnt) { this.updateReturnFlightDetailsAreVisible(); }.bind(this) );
    $('return_yes').observe('change', function(evnt) { this.updateReturnFlightDetailsAreVisible(); }.bind(this) );
    $('return_no').observe('change', function(evnt) { this.updateReturnFlightDetailsAreVisible(); }.bind(this) );
    
    $('have_freight_yes').observe('change', function(evnt) { if ($('have_freight_yes').checked) this.openDangerousGoodsPopup(); }.bind(this) );
    if ($('charter_share_yes'))
	    $('charter_share_yes').observe('change', function(evnt) { if ($('charter_share_yes').checked) this.openCharterShareTermsPopup(); }.bind(this) );

  },

	updateReturnFlightDetailsAreVisible:function()
	{
	  if ($('return_no').checked) {
	    $('return_date_row').hide();
	    $('return_time_row').hide();
	    this.updateReturnTime(false);
	  } else {
	    $('return_date_row').show();
	    $('return_time_row').show();
	    this.updateReturnTime(true);
	  }
	},

	//Update the return time from the depatrure time or the last stopover departure time. Unset the return time if no return flight is required.
	updateReturnTime:function(returnRequired) {
		var lastStopoverIdx=this.getLastStopoverIdx();
    // We might want to copy from field like dep_day, stopover0_dep_day or stopover1_dep_day
		var srcPrefix=(lastStopoverIdx===false) ? '' : 'stopover'+(lastStopoverIdx)+'_';
		for(var i=0; i<this.departureTimeSelects.length; i++) {
			$(this.returnTimeSelects[i]).selectedIndex= returnRequired ? $(srcPrefix+this.departureTimeSelects[i]).selectedIndex : 0;
		}
	},
	
	updateStopoverDepartureTime:function(idx) {
	  var srcPrefix='stopover'+(idx-1)+'_';
    var destPrefix='stopover'+idx+'_';
	  if(!$(srcPrefix+'dep_day')) {
		  srcPrefix='';
	  }
		for(var i=0; i<this.departureTimeSelects.length; i++) {
			$(destPrefix+this.departureTimeSelects[i]).selectedIndex= $(srcPrefix+this.departureTimeSelects[i]).selectedIndex;
		}
	},

	getLastStopoverIdx:function() {
		var lastRow=$('addStopoverRow').previous('.stopoverRow');
		if(lastRow) {
			var classNameIdx=lastRow.classNames().detect(function(name) { return /stopover[0-9]+/.test(name); });
			if(classNameIdx) {
			  return parseInt(classNameIdx.replace(/stopover([0-9]+)/, "$1")); //Extract idx
		  }
		}
		return false;
	},	
	
	getNextStopoverIdx:function() {
		var lastIdx=this.getLastStopoverIdx();
		if(lastIdx===false) {
			return 0;
		}
		return lastIdx+1;
	},
	
	addStopover:function() {
		var idx=this.getNextStopoverIdx();
	  new Ajax.Request(this.baseHref+'quote.stopoverFragment', {
		  method: 'post',
		  parameters: {'idx':idx},
		  onCreate: function() {
			  $('addStopoverAjaxLoader').show();
		  },		
		  onFailure: function(transport) { this.ajaxFailure(transport); },
		  onSuccess: function(transport) {
			  $('addStopoverAjaxLoader').hide();
			  try{ responseData=transport.responseText.evalJSON(); }
			  catch(e) { this.ajaxFailure(transport); return; }
			  if(responseData['result']!='OK') {
				  this.ajaxFailure(transport);
			    return;
		    }
		    //Process expected data
		    this.addStopoverCallBack(idx,responseData['html']);
		  }.bind(this)
    });
	},
	
	addStopoverCallBack:function(idx,html) {
		$('addStopoverRow').insert({before: html});
		this.updateStopoverDepartureTime(idx);
	},

	removeStopover:function(idx) {
		$$('tr.stopover'+idx).each(Element.remove)
	},
	
  ajaxFailure: function(transport) {
	  alert('There was a problem contacting the server. Please check that your internet connection is working.');
	  if(console && console.log)
	    console.log(transport);
  },
  
  openDangerousGoodsPopup:function()
  {
    Shadowbox.open({
        content:    $('baseTag').href + 'quote.dangerous-goods-popup',
        player:     "iframe",
        title:      "",
        height:     500,
        width:      550
    });
    /*
    window.open(
      $('baseTag').href + 'quote.dangerous-goods-popup',
      'dangerous-goods-popup',
      "height=500,width=550,scrollbars=1"
    );
    */
  },
  
  openCharterShareTermsPopup:function()
  {
    Shadowbox.open({
      content:    $('baseTag').href + 'quote.charter-share-terms-popup',
      player:     "iframe",
      title:      "",
      height:     180,
      width:      550
    });
/*
    window.open(
      $('baseTag').href + 'quote.charter-share-terms-popup',
      'charter-share-terms-popup',
      "height=500,width=550,scrollbars=1"
    );
*/
  }
  
});

document.observe('dom:loaded', function() {
  quoteRequestController = new QuoteRequestController();
});
