/*---------------------------------------------------------------------
  res-rates.js
  Functions used specifically by res-rates.html
---------------------------------------------------------------------*/

function external() {
	if (!document.getElementsByTagName) return;
	var a = document.getElementsByTagName('a');
	for (var i=0;i<a.length;i++){
		var o = a[i];
		if (o.getAttribute('href') && o.getAttribute('rel') == 'external')
			o.target = '_blank';
		}
  	}
window.onload = external;

function show_enquiry(class_code, class_desc, rate_info){
	var frmRes = de('frmRes');
	frmRes.action = 'https://secure.carsplus.com.au/webres/a1car/enquiry_form.html?desired_class='+class_code+'&class_desc='+class_desc+'&rate_info='+rate_info;
	frmRes.submit();
	}

/*---------------------------------------------------------------------
  postToSelf
  Post the page contents back to itself. This allows us to refresh
  dependent items. 

  Eg: options are dependent upon the vehicle class that is selected.  
  If another class is selected we want to update the options to 
  reflect the correct class.
  I considered segmenting the options refresh and estimate refresh into
  seperate functions - but it's faster to do it this way - and variables
  can maintain scope.
---------------------------------------------------------------------*/
var dynamic_loading = false;

function postToSelf(){
  var fmR = de('frmRes');

  // Leave if we don't have active scripting
  if (! fmR.active_scripting.value ) return false;

  // return ( without a value ) if they're still loading.
  if (dynamic_loading){
	dynamic_loading.checked = 1;
	return;
	}

  var event = event || arguments[0] || window.event || window.sel_trigger;
  if (event.tagName){
	dynamic_loading = event;
	}
  else {
  	dynamic_loading = event.srcElement || event.currentTarget || event.target;
	}

  // If called from o_qty check that the box is checked before refreshing
  if ( dynamic_loading.name.match(/o_qty_(\d)/) ){
	cB = de('o_cb_'+RegExp.$1);
	if (! cB.checked ){
		dynamic_loading = false;
		return;
		}
	}

  var args = [];

  if ( fmR.vehicle_rate_id ){
	args['rate_id'] = lRB(fmR.vehicle_rate_id);
	}

  var loop = new Array( 'pickup_loc',
			'pickup_date',
			'pickup_time',
			'corp_rate_id',
			'corp_rate_pin',
			'cust_no',
			'renter_last',
			'frequent_renter_no',
			'orig_corp_rate_id',
			'renter_age_range',
			'renter_bdate',
			'voucher_class',
			'voucher_days',
			'voucher_issuer',
			'voucher_no',
			'voucher_pin');

  for (var i=0;i<loop.length;i++){
	if ( fmR[ loop[i] ] ){
		args[loop[i]] = fmR[ loop[i] ].value;
		}
	}	

// If no options table - we must continue to regenerate the quotation
  if ( de('options_table_body') ){
    var oTb = de('options_table_body');
    var oEc = 0;
    var rTH = 0;
    var rC = oTb.rows[0] ? oTb.rows[0].cells.length || 5 : 5;
  
    var iTb = 0;

    // If we failed to refresh last time - don't try to gather information - just remove cell
    if ( oTb.failed_refresh || oTb.getAttribute('failed_refresh') ){
	iTb = oTb.childNodes.length+1;
	rC = 5;
	rTH = lO(oTb,1).offsetHeight;
	oTb.removeChild(lO(oTb,1));
	}

    if ( dynamic_loading.name.match(/o_cb_(\d)/) &&
	 de('o_type_'+RegExp.$1).value == 'L' ){
	var o_cnt = de('option_count').value;
	var disabled = 1;
	if (!dynamic_loading.checked) disabled = 0;
	for (var i=1;i<=o_cnt;i++){
		if (i == RegExp.$1) continue;
		if (de('o_type_'+i).value == 'L'){
			var cb = de('o_cb_'+i);
			cb.checked = 0;
			cb.disabled = disabled;
			var lit_td = next_element(cb.parentNode);
			if (disabled == 1){
				var b = lit_td.appendChild( document.createElement('B') );
				b.appendChild( document.createTextNode(' ( Unavailable )'));
				}
			else {
				var b = child_ofTag(lit_td, 'B');
				if (b) b.parentNode.removeChild(b);
				}
			}
		}
	}

    // Can't just do a while loop any more - in some circumstances we don't remove anything
    while ( iTb < oTb.childNodes.length){
	var cO = oTb.childNodes[iTb];
 	if (cO.nodeType == 1){
		rTH += cO.offsetHeight;
		// Check box is first element of first child
		var cB = lO(lO(cO));
		var opt_id = cB.name.split(/_/)[2];
		if (cB.checked){
			oEc++;
			args['o_cb_'+oEc] = cB.value;
			var p_qty = de('o_qty_'+opt_id);
			var qty;
			// If we don't ge a qty name back - we've got a code... ignore it
			if (p_qty && p_qty.name.match(/o_qty/)){
				qty = p_qty.value;
				}
			else {
				qty = 1;
				}
			args['o_qty_'+oEc] = qty;
			// We definately need the rate - get it from a new id (ie can't handle refs)
			args['o_rate_'+oEc] = de('o_rate_'+opt_id).value;
			}
		}
	// Only remove the item if we're regenerating the options
	if (dynamic_loading.name == 'vehicle_rate_id'){
  		oTb.removeChild(oTb.childNodes[iTb]);
		}
	else {
		// Only increment if we haven't removed an item
		++iTb;
		}
	}

    // Add the options to the url no matter what - quotation might need them
    args['option_count'] = oEc;

    // If we were called from vehicles table then regenerate
    if (dynamic_loading.name == 'vehicle_rate_id'){
	genPW(oTb, rTH, rC, 'Please wait ... Updating Options for new car class!');
	genST('dyn_options_update', 'https://secure.carsplus.com.au/webres/a1car/dyn_optionsTable.js', args);
	}
    // Otherwise disable the quantity field, if it exists
    else {
	// We're trying to regenerate an estimate without a estimate table
	if (! de('estimate_table_body') ){
		dynamic_loading = false;
                return;
		}
	var cBQ;
	// Check this option is editable and we're going to estimate
	if ( cBQ = de( 'o_qty_'+dynamic_loading.name.split(/_/)[2] ) ){
		cBQ.disabled=1;
		args['reactivate_opt_qty'] = cBQ.name;
		}
	}
    }

  // No matter what the occasion - we always want to requote

  // If they don't have a quotation section - Now we can return
  if (! de('estimate_table_body')){
  	if (! de('options_table_body') ){
		// There's no genST running for options either
		dynamic_loading = false;
		}
	return true;
	}
  
  args['return_loc'] = fmR.return_loc.value;
  args['return_date'] = fmR.return_date.value;
  args['return_time'] = fmR.return_time.value;

  eTb = de('estimate_table_body');
  var rTH = 0;
  var rC = eTb.rows[0].cells.length || 5;
  while ( eTb.childNodes.length ){
	var cE = eTb.childNodes[0];
	if (cE.nodeType == 1) rTH += cE.offsetHeight;
	eTb.removeChild(eTb.childNodes[0]);
	}
  genPW(eTb, rTH, rC, 'Please wait ... Requoting reservation!');
  genST('dyn_estimate_update', 'https://secure.carsplus.com.au/webres/a1car/dyn_estimateTable.js', args);
  }


/*---------------------------------------------------------------------
  checkVehClassChange
  Check if the vehicle class has been changed. If yes, repost the
  form back to itself.

  NOTE: The onchange event is not being fired the very first time
  a change is made. This is designed to catch all checks by being
  called from the onClick event.
---------------------------------------------------------------------*/
function checkVehClassChange (origval, newval){
  if (origval != newval) {
    de('frmRes').action = 'res2.html';
  }
}

/*---------------------------------------------------------------------
  genPW
  Generate a Please wait message in the given table.
  The number of cells is taken form the second row down
---------------------------------------------------------------------*/
function genPW(obj, objH, cS, msg){
  if (!objH) objH = '25px';

  var rTr = obj.insertRow(obj.rows.length);
  rTr.height = objH;
  var rTd = rTr.insertCell(0);
  with (rTd){
	colSpan = cS;
	height = objH;
	align = 'center';
	with (style){
		color = '#BB0000';
		fontWeight = 'bold';
		fontSize = '11px';
		fontFamily = 'Arial, sans-serif';
		}
	}
  var new_msg = document.createTextNode( msg );
  rTd.appendChild(new_msg);
  }

/*---------------------------------------------------------------------
  genST
  Generate a ScriptTag from the information given to us.
  Note that we replace +s at the last moment.
  escape() won't work on this, since it considers + safe.
  We do this because of Apache::Request
---------------------------------------------------------------------*/
function genST(nm,url,args_array){
  if ( de(nm) ) document.body.removeChild( de(nm) );
  var st = document.createElement('SCRIPT');
  st.id = nm
  st.language = "Javascript";
  st.type = "text/javascript";
  
  if (! url.match(/\?/)) url += '?';
  else url += '&';
  if (!args_array) args_array = [];
  
  var now = new Date();
  args_array['tag_id'] = 'server_request_'+now.valueOf();

  	for (var k in args_array){
		var kn = k;
		var kv = args_array[k];
		if (kn.replace) kn = kn.replace(/\&/g, '%26');
		if (kv && kv.replace) kv = kv.replace(/\&/g, '%26');
		url += kn+'='+kv+'&';
		}
  try { 
	url = url.replace( /\+/g, '%2B'); 
	}
  catch (e){ 
	var str = 'Your browser is having trouble compiling regular expressions:\n';
	str += e.description+'\n';
	str += "You may discover some functionality doesn't work the way it was intended.\nWe're sorry for any inconvienience, please contact us if you have any trouble completing your booking!";
	alert( str );
	}
  st.src = url;
  document.body.appendChild(st);
  }

/*---------------------------------------------------------------------
  supressClick
  Generate a ScriptTag from the information given to us.
---------------------------------------------------------------------*/
function supressClick (event){
  	var event = event || arguments[0] || window.event;
	var srcO = event.srcElement || event.currentTarget || event.target;
	if (event.keyCode == 13){
		srcO.blur();
		return false;
		}
	}

function toggle_radio(button){
	var node = button.parentNode.parentNode;
	while (node){
		if (node.name == 'vehicle_rate_id') break;
		node = node.previousSibling;
		}
	if (!node) return;
	node.click();
}



