function $(elid) {
    return document.getElementById(elid);
}

/* cookies */
function getCookie(cookie_name) {
    var search = cookie_name + "=";
    if (document.cookie.length > 0) {
	var offset = document.cookie.indexOf(search);
	if (offset != -1) { 
	    offset += search.length;
	    var end = document.cookie.indexOf(";", offset) 
	    if (end == -1) end = document.cookie.length;
	    return unescape(document.cookie.substring(offset, end));			}
    }
    return "";
}
function setCookie(cookie_name,cookie_value,expire_days) {
    var exp_str = "";
    if (expire_days) {
	var today = new Date();
	var cexp = new Date();
	cexp.setTime(today.getTime() + 3600000*24*expire_days);
	exp_str = ";expires=" + cexp.toGMTString();
    }
    document.cookie = cookie_name + "=" + escape(cookie_value) + ';path=/' + exp_str
}

/* recently visited page list */
/* expects global 'this_page' to be set to name of current page */
function recent_pages() {
    var recent_pages_max_length = 4;
    var el = $('recent_pages');
    if (el) return;
    var recent = getCookie('recentpages');
    var rec_lst = new Array();
    if (recent) {
	rec_lst = _recent.split(',');
	var rec_out = 'Recent pages: <ul>';
	for(var r in rec_lst) {
	    var pid = unescape(rec_lst[r]); 
	    if (pid == this_page) continue;
	    var vis_pid = _pid.replace(/(_|^)([a-z])/g, 
	        function (c_all,c_l,c_r) {return c_l+c_r.toUpperCase()});
	    vis_pid = vis_pid.replace('_',' ','g');
            rec_out += '<li><a href'+'="' + base_href + pid + '/index.html">' +
                vis_pid + "<\/li>";
	}
	rec_out += "<\/ul>";
	el.innerHTML = rec_out;
    } 
    var new_rec = new Array();
    new_rec.push(this_page);
    for (var _r in rec_lst) {
	if (rec_lst[r] != this_page) new_rec.push(rec_lst[r]);
	if (new_rec.length >= recent_pages_max_length) break;
    }
    setCookie('recentpages', new_rec.join(','));
}

/* menu */
function menu_init(target) {
    var t = $(target);
    if (!t) return;
    var m = t.childNodes;
    for (var i=0; i < m.length; i++) {
	var li = m[i];
	if (li.nodeName != 'LI') continue;
	li.onmouseover = function () { this.className += " menu_hover"; };
	li.onmouseout = function() {
	    this.className = this.className.replace(/\bmenu_hover\b/, "");
	}
    }
}


/* pager */
function pager_init(div_to_page, navigation_div, two_columns, items_per_page, divtype) {
    var dtp = $(div_to_page);
    if (!dtp) return false;
    if (!divtype) divtype='DIV';
    var pager_first_item = 0;
    var paged_el = new Array();
    for (var cn=0; cn < dtp.childNodes.length ; cn++) {
	if (dtp.childNodes[cn].nodeName == divtype && 
	    dtp.childNodes[cn].style.display != 'none') 
	    paged_el.push(dtp.childNodes[cn]);
    }
    var num_paged_el = paged_el.length;
    var num_pages = Math.ceil(num_paged_el / items_per_page);
    
    var pager_display = function () {
	var pager_last_item = pager_first_item + items_per_page - 1;
	var altcol = false;
	for (var child=0; child<num_paged_el; child++) {
	    var sty = paged_el[child].style;
	    if (child < pager_first_item || child > pager_last_item) {
		sty.display='None';
	    } else {
		sty.display='block'; // XXX assumption
		if (two_columns) {
		    sty.styleFloat = sty.cssFloat = altcol ? "right" : "left";
		    sty.width = "49%";
		    // height has to match ...
		    if (altcol) {
			// NB tile div must not have padding
			var htl = paged_el[child-1].clientHeight;
			var htr = paged_el[child].clientHeight;
			var heq = (htl > htr) ? htl : htr;
			paged_el[child-1].style.height = sty.height = heq + 'px';
		    }
		    altcol = !altcol;
		}
	    }
	}
	
	var nav_el = $(navigation_div);
	if (num_pages<2) {
	    if (nav_el) nav_el.innerHTML = "";	    
	    return; // dont add nav if not needed
	}
	
	function hr (pgid,pglbl,accesskey) {
	   var ac = (accesskey) ? ' accesskey="'+accesskey+'"' : "";
	   return '<li><a href="" onclick="return '+div_to_page+'_goto('+pgid+')"'+ac+'>'+pglbl+"<\/a><\/li>"; 
	}
	
	var nav_html = '<div class="pager_nav"><ul>';
	if (pager_first_item >= items_per_page) 
	    nav_html += hr("'previous'",'Prev');
	var cur_pg = parseInt((pager_first_item / items_per_page) + 1);
	var links2 = 5; // max num nav links shown = 2*links2+1 
	var numlinks = 2*links2 + 1;
	var first = 1;
	var last = num_pages;
	if (num_pages > numlinks) {
	    if (cur_pg <= links2) {
		last = numlinks;
	    } else if (cur_pg > num_pages - links2) {
		first = num_pages - numlinks
	    } else {
		first = cur_pg - links2;
		last = cur_pg + links2;
	    }
	}
	for (var pg = first; pg <= last; pg+=1) {
	    if (pg == cur_pg) {
		nav_html += '<li class="this">' + pg + "<\/li>";
	    } else { 
		nav_html += hr(pg, pg);
	    }
	}
	if (pager_first_item + items_per_page < num_paged_el) 
	    nav_html += hr("'next'", 'Next');
	if (!(pager_first_item==0 && items_per_page == num_paged_el)) 
	    nav_html += hr("'all'","All");
	nav_html += "<\/ul><\/div>";
	if (nav_el) nav_el.innerHTML = nav_html;
    }
    
    var pager_goto = function (page) { 
	if (page=='next') {
	    if (pager_first_item + items_per_page < num_paged_el) 
		pager_first_item += items_per_page;
	} else if (page=="previous") {
	    if (pager_first_item > items_per_page) {
		pager_first_item -= items_per_page;
	    } else {
		pager_first_item = 0;
	    }
	} else if (page=="all") {
	    pager_first_item = 0;
	    items_per_page = num_paged_el;
	    num_pages = 1;
	    // when paged, often nice to set div height to keep page steady
	    // but then 'all' items overlay whatever is underneath
	    dtp.style.height = 'auto';
	    $(navigation_div).innerHTML = "";
	} else if (page > 0) {
	    if (page <= num_pages)
		pager_first_item = ((page-1) * items_per_page);
	}
	pager_display();
	return false;
    }
    
    var anch = parseInt(self.document.location.hash.substring(1));
    if (anch && anch < num_pages) {
	pager_goto(anch);
    } else {
	pager_goto(1);
    }
    return pager_goto;
}

/* More details hide/display */
function _set_more_details (div_id, div_display, nav_display) {
    var md_el = $(div_id);
    var mdn_el = $(div_id + '_nav');
    if (md_el)md_el.style.display = div_display;
    if (mdn_el) mdn_el.style.display = nav_display;
    return true;
}
function init_more_details(div_id) {
    var anch = self.document.location.hash.substring(1);
    if (anch != (div_id + "_a")) hide_more_details(div_id);
}
function hide_more_details (div_id) { 
    return _set_more_details (div_id, 'None', 'Inline'); 
}
function show_more_details(div_id) { 
    return _set_more_details (div_id, 'Block', 'Inline');
}
function toggle_more_details(div_id) { 
    if ($(div_id).style.display == "none") 
	return show_more_details(div_id); 
    else 
	return hide_more_details (div_id); 
} 

/* shortlist/wishlist */
function shortlist(huid) {
    if(!huid) return false;
    var sl = getCookie('shortlist').split(',');
    for (var id=0; id<sl.length; id++) {
	if (sl[id]=="") sl.splice(id,1);  //split on "" gives 1 empty item
	if(sl[id]==huid) {
	    sl.splice(id,1);
	    huid="";
	    break;
	}
    }
    if (huid) sl.push(huid);
    setCookie("shortlist", sl.join(","));
    // XXX change button '{add to,remove from} shortlist >' ?
    if(typeof(show_wish_list_info)=="function") show_wish_list_info();
    return false;
}
function show_wish_list_info() {
     var wlc = $('wish_list_count');
     if (!wlc) return;
     var shortlist = getCookie('shortlist').split(',');
     wlc.innerHTML = shortlist[0] ? 
	(shortlist.length==1?"1 item selected":shortlist.length+" items selected") : "empty";
     var wl = $('wishlist');
     if(wl) wl.style.display = '';
}  
function show_shortlist(target) {
    var msdiv = $(target);
    if (!msdiv) return;
    var shortlist = getCookie('shortlist').split(',');
    var sl_out = "<h2>In your shortlist<\/h2>";
    if (shortlist && shortlist[0]) {
	sl_out += '<ul>'
	for(var sli=0; sli<shortlist.length; sli++) {
	    if (sli == 4) break;
	    var hid = unescape(shortlist[sli]); 
	    var hin = hid.replace(/(_?[A-Z])/g," \$1");
	    sl_out += '<li><a href'+'="'+relurl+hid+'/index.html">'+hin+"<\/li>";
	}
	sl_out += "<\/ul>";
	sl_out += '<a href="'+oqurl+'" title="Create a holiday from the hotels in your shortlist">Create my multi-center holiday'+"<\/a>";
    } else {
	sl_out += '<p>Add the hotels you like by clicking the add to shortlist button on that hotels page. Then you can combine them into a multi-center holiday.'+"<\/p>";
    }
    msdiv.innerHTML = sl_out;
}

function show_holiday(target) {
    var mhdiv = $(target);
    if (mhdiv) {
	var _br = "<br>";
	var hotels = getCookie('hotels');
	var depart = getCookie('departure');
	var costpp = getCookie('costpp');
	var header = '<h2>Your Holiday<h2>';
	var html = "";
	if (hotels && depart && costpp) {
	    var hh = hotels.split(',');
	    var ddm = depart.match(/([0-9]{4})-([0-9]{2})-([0-9]{2})/);
	    if (ddm) depart = ddm[3] + " / " + ddm[2] + " / " + ddm[1];
	    html += "Departing " + depart + _br; 
	    html += "<table>";
	    var totalnights = 0;
	    for (var hi=0; hi < hh.length; hi++) {
		var hv = hh[hi].split('=');
		if (hv.length==2) {
		    totalnights += parseInt(hv[1]) || 0;
		    var hname = hv[0].replace(/(_?[A-Z])/g," $1");
		    html += "<tr><td>" + hname + "<\/td><td class='nights'>" 
                            + hv[1] + "<\/td><\/tr>";
		}
	    }
	    html += "<\/table>";
	    html += "Guideline &pound;" + costpp + 
		" <span class='smaller'>per person<\/span>" + _br;
	    //html += "<a href='<!--CGI:mkhol-->?action=display'>Edit<\/a>";
	    //html += " | <a href='<!--CGI:mkhol-->?action=checkout'>Get Quote<\/a>";
	    if (totalnights==1) header += " - 1 night";
	    else  header +=  " - " + totalnights + " nights";
	} else {
	    html += "Click an <q>Add to my holiday<\/q> button on a hotel page to start creating your holiday.";
	}
	html = "<p>" + header + _br + html + "<\/p>";
	mhdiv.innerHTML = html;
    }    
}

/* hotels by feature filter */
function array_contains(arr, v) {
    for (var i =0 ; i< arr.length ; i++) {
	if (arr[i] ==v) return true;
    }
    return false;
}
function hotel_filter_init(divid) {
    var div = $(divid);
    if(!div) return;
    var lhs = '<ul class="lhs">'; var rhs = '<ul class="rhs">';
    for (f=0, alt=false; f<facility_names.length; f++) {
	var k = facility_names[f];
	var nh = hotel_filter_hotels_with_facility(k).length;
	var item = '<li><input type="checkbox" name="'+k+
	    '" onclick="hotel_filter_apply(this.form, \''+divid+'\')"> '+k+
	    ' ('+nh+ (nh==1 ? ' hotel' : ' hotels') + ')</li>';
	if (alt) { rhs += item } else { lhs += item };
	if (!alt && f+1>=facility_names.length/2) alt=true; 
    }
    lhs += '</ul>'; rhs += '</ul>';
    div.innerHTML = '<form name="hotel_filter">'+lhs+rhs+'</form>';
}
function hotel_filter_hotels_with_facility(facility) {
    var hotels = new Array();
    for (var f=0; f<facilities.length; f++) {
	var hotel = facilities[f][0];
	var hf = facilities[f][1];
	if(array_contains(hf, facility)) 
	    hotels.push(hotel);
    }
    return hotels;
}
function hotel_filter_get_matches(form) {
    var matches = new Array();
    for (var f=0; f<facilities.length; f++) {
	var hotel = facilities[f][0];
	var hf = facilities[f][1];
	for (var fni=0; fni<facility_names.length ; fni++) {
	    var fn = facility_names[fni];
	    if (form[fn].checked && !array_contains(hf, fn)) {
		hotel = '';
		break;
	    }
	}
	if (hotel) matches.push(hotel);
    }
    return matches;
}
function hotel_filter_show_wanted(wanted) {
    // assumes tiles are given id of form <hotelname>_tile
    for (var f=0; f<facilities.length; f++) {
	var hn = facilities[f][0];
	var d = $('tile_'+hn);
	if (d) {
	    d.style.display = array_contains(wanted,hn) ? 'block' : 'none';
	}
    }
}
function hotel_filter_apply(form, divid) {
    var wanted = hotel_filter_get_matches(form);
    hotel_filter_show_wanted(wanted); 
    //var pager = eval(divid.replace('_filter','_goto'));
    //if(typeof(pager)=="function") pager(1);
    var pd = divid.replace('_filter','');
    if (typeof(pager_init)=="function") { 
	eval(pd + "_goto = pager_init(pd, pd+'_nav', 1, 6, 'DIV')");
    }
    return true;
}

/* horizontal auto-scrolling gallery (with globals! => one per page) */
var gallery_target = "";
var gallery_scroll_interval = 50;
var gallery_do_autoscroll = true;
var gallery_autoscroll_dir = 1;
function init_imageflow(target_el, images) {
    var p = $(target_el);
    gallery_target = p;
    if (p.currentStyle && p.currentStyle['overflow']!='hidden') return 0; //ie6
    //var images = new Array(images);
    if (images.length<2) return 0;
    var d = document.createElement('DIV');
    d.className = 'imageflow';
    d.id = 'myImageFlow';
    var dl = document.createElement('DIV');
    dl.id = "gallery_left";
    dl.onclick = function() {gallery_scroll(-1)};
    p.parentNode.insertBefore(dl,p.parentNode.firstChild);
    var dr = document.createElement('DIV');
    dr.id = "gallery_right";
    dr.onclick = function() {gallery_scroll(1)};
    p.parentNode.insertBefore(dr,p.parentNode.firstChild);

    for(var i=0 ; i<images.length ; i++) {
	var ii = images[i];
	var img = document.createElement('img');
	img.src = ii[0];
	img.width = ii[1];
	img.height = ii[2];
	img.setAttribute('longdesc', ii[3]);
	img.alt = img.title = ii[4];
	d.appendChild(img);
    }
    p.replaceChild(d, p.firstChild);
    // hackish override of  layout.css:.primary_page_image
    p.parentNode.style.float = 'none';
    p.parentNode.style.width = '100%';
    return 1;
}
function gallery_scroll_by(amt, snap) {
    var el = gallery_target;
    var child = el.getElementsByTagName('img');
    var cur = el.scrollLeft + amt;
    var width = 0;
    var snap_left, snap_right=0;
    for (var c=0;c<child.length;c++) {
	width += child[c].scrollWidth; // includes padding
	if (width<cur) snap_left = width;
	if (width>cur && !snap_right) snap_right = width;
    }
    if (snap) cur = (amt>0) ? snap_right : snap_left;
    var last_width = child[child.length-1].width; 
    atend = (cur < 0 || cur > width-el.parentNode.scrollWidth+last_width);
    if (!atend) el.scrollLeft = cur;
    return atend;
}
function gallery_autoscroll() {
    if (!gallery_do_autoscroll) return;
    var atend = gallery_scroll_by(gallery_autoscroll_dir * 1, false);
    if (atend) gallery_autoscroll_dir = 0 - gallery_autoscroll_dir;
}
function gallery_scroll(dir) {
    gallery_do_autoscroll = false;
    gallery_scroll_by(dir, true);
}


/* client feedback pager */
function reviews_set(show, hide) {
    $(hide).style.display = 'none';
    $(show).style.display = 'block';
    $(hide+'_button').setAttribute('class','');
    $(show+'_button').setAttribute('class','this');
}

/* tripadvisor feed */
function feed_load(feed, callback, root, dest, qty) {
    var xd;
    if (window.XMLHttpRequest) {
	// safari.
	xd = new XMLHttpRequest();
	xd.onreadystatechange = function () {
	    if (xd.readyState == 4)  callback(xd, root, dest, qty);
	};
	xd.open("GET", feed, true);
	xd.send("");
    } else if (document.implementation && document.implementation.createDocument) {
	xd = document.implementation.createDocument("", "", null);
	// .onload is not reliably fired (even when external doc is loaded)
	// xd.onload = function () { callback(xd, root, dest, qty); };
	xd.async = false
        var loaded = xd.load(feed);
	if (loaded) callback(xd, root, dest, qty);
    } else if (window.ActiveXObject) {
	xd = new ActiveXObject("Microsoft.XMLDOM");
	xd.onreadystatechange = function () {
	    if (xd.readyState == 4) callback(xd, root, dest, qty);
	};
	xd.load(feed);
    } else {
	//alert('Failed to show feed '+feed);
	return;
    }
}
function feed_tripadvisor_complete(xmldoc,root, dest, qty) {
    if(xmldoc.responseXML) xmldoc = xmldoc.responseXML; // safari
    var xdtop = xmldoc.getElementsByTagName(root);
    if (!xdtop||!xdtop.length) return; // XXX prob should empty dest ?
    xdtop = xdtop[0];
    var t = xdtop.getElementsByTagName('title')[0];
    var rss_title = document.createTextNode(t.firstChild.nodeValue);
    var rss_link = xdtop.getElementsByTagName('link')[0].firstChild.nodeValue;
    var html = document.createElement('DIV');
    html.setAttribute('class','tripadvisor');
    var lnk = document.createElement('A');
    lnk.setAttribute('href',rss_link);
    lnk.setAttribute('target','_new');
    lnk.appendChild(rss_title);
    html.appendChild(lnk);
    var dl = document.createElement('DL');
    var items = xdtop.getElementsByTagName('item');    
    for (j=0; j < (items.length < qty ? items.length : qty); j++) {
	var cn = items[j];
	var title = cn.getElementsByTagName('title')[0].firstChild.nodeValue;
	var desc = cn.getElementsByTagName('description')[0].firstChild.nodeValue;
	// pubDate, link,guid,dc:creator, dc:date
	var dt = document.createElement('DT');
	dt.appendChild(document.createTextNode(title));
	var dd = document.createElement('DD');
	dd.innerHTML = desc;
	dl.appendChild(dt);
	dl.appendChild(dd);
    }
    html.appendChild(dl);
    $(dest).appendChild(html);
}
function feed_tripadvisor(hid) {
    var src = "/cuba/cgi-private/wget_feed.pl?feedid=tripadvisor;hid=";
    src += escape(hid);
    feed_load(src, feed_tripadvisor_complete, 'channel', 'tripadvisor', 2);
}

/* gallery with bar chooser and lightbox */
function set_opacity(img_style, opacity) {
    img_style.opacity = opacity;
    img_style.filter = 'filter: alpha(opacity='+(opacity*100)+')';
}

function gallerybox_show(pid,idx) {
    var el = $(pid);
    var imgs = el.getElementsByTagName('img');
    if (idx < 0) idx = imgs.length-1;
    if (idx >= imgs.length) idx = 0;
    var cur = 0;
    for (var i=0; i < imgs.length ; i++) {
        if (imgs[i].style.display != 'none') {
            cur = i;
            break;
        }
    }
    set_opacity(imgs[cur].style, 1);
    imgs[idx].style.display = 'none';
    gallerybox_fader(imgs[cur], -1);
    imgs[cur].style.display = 'none';
    set_opacity(imgs[idx].style, 0); 
    imgs[idx].style.display = 'block';
    gallerybox_fader(imgs[idx], 1);
    var gid = pid.replace('_top', '');
    var tel = $(gid+"_title");
    tel.innerHTML = imgs[idx].title;
    var cel = $(gid+"_count");
    cel.innerHTML = (idx+1) + " of " + imgs.length;
}
function gallerybox_fader(img, dir) {
    var opac = parseFloat(img.style.opacity);
    opac += 0.05 * dir;
    if (opac > 0 && opac < 1) {
        set_opacity(img.style, opac);
        setTimeout(function() {gallerybox_fader(img, dir)}, 10);
    }
}

function gallerybox_scroll(sid,dir) {
    var el = $(sid);
    var ssl = el.scrollLeft;
    var width = 134;
    ssl += dir*width;
    if (ssl < 0 ) ssl=0;
    var numimg = el.getElementsByTagName('img').length;
    numimg -= 3;
    if (ssl > numimg*width) ssl = numimg*width;
    el.scrollLeft = ssl;
}
function screen_size() {
    var w = 0, h = 0;
    if(typeof(window.innerWidth)=='number') {
	w = window.innerWidth;
	h = window.innerHeight;
    } else if(document.documentElement && 
	(document.documentElement.clientWidth||document.documentElement.clientHeight)) {
	w = document.documentElement.clientWidth;
	h = document.documentElement.clientHeight;
    } else if(document.body && (document.body.clientWidth || document.body.clientHeight)) {
	w = document.body.clientWidth;
	h = document.body.clientHeight;
    }
    return [w, h];
}
function screen_offset() {
  var x = 0, y = 0;
  if(typeof(window.pageYOffset) == 'number' ) {
    y = window.pageYOffset;
    x = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    y = document.body.scrollTop;
    x = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    y = document.documentElement.scrollTop;
    x = document.documentElement.scrollLeft;
  }
  return [ x, y ];
}
function gallery_lightbox_locate(el, idx) {
    var ssz = screen_size();
    var off = screen_offset();
    var img = el.getElementsByTagName('img')[idx];
    var w = Math.max(700, img.width);
    var h = el.clientHeight;
    var midw = (w < ssz[0]) ? (ssz[0]-w)/2 : ssz[0]-w;
    var midh = (h < ssz[1]) ? (ssz[1]-h)/2 : ssz[1]-h; 
    el.style.left = (off[0] + midw) + "px";
    el.style.top  = (off[1] + midh) + "px" ;
    el.style.zoom = '1'; // force IE to reapply CSS
}

function gallerybox_lightbox_scroll(pid, dir) {
    var el = $(pid);
    var imgs = el.getElementsByTagName('img');
    for (var i=0; i < imgs.length ; i++) {
	if (imgs[i].style.display != 'none') {
	    gallerybox_show(pid, i+dir);
            var gal = $(pid.replace("_top",''));
            gallery_lightbox_locate(gal, i+dir);
	    break;
	}
    }
}
function gallerybox_lightbox_toggle(gid,idx) {
    var el = $(gid);
    var cl = $(gid+"_container");
    var ol = $(gid+"_overlay");
    if (idx!=null) gallerybox_show(gid+"_top", idx);
    if (el.className.match(/(^|\s+)gallerybox_lightbox/)) {
	ol.style.display = 'none';
	el.className = el.className.replace(/(^|\s+)gallerybox_lightbox/,'');
    } else {
	ol.style.width = Math.max(document.body.clientWidth,screen_size()[0])+"px"; 
	ol.style.height = document.body.clientHeight+"px";
	ol.style.display = "block";
        el.className += ' gallerybox_lightbox'; // now so IE has img.height
        gallery_lightbox_locate(el, idx);
    }
}

/* itinerary cost calculator (eg in IdeasForItins) */
/* It expects at least departy,departm,departd inputs to exist */
function itinerary_setup(cgi, target_el, basecost, itin) {
    /* returns a function to be called from <form> action */
    var args = arguments;
    var cost_fn = function () { itinerary_cost.apply(null, args); };
    var _current_onload = window.onload;
    window.onload = function () { 
        itinerary_update_depart_inputs();
        cost_fn();
        if (_current_onload) _current_onload();
    }
    return cost_fn;
}

function itinerary_cost(cgi, target_el, basecost, itin) {
    /* itin is e.g. LeMirage:{1},CasaHassan:{2}
    {1} is replaced by the value of the input whose id is in extra arguments 
    to this call.
    target_el is updated with cost of hotel/flt/xfr for the itin, plus 
    specified base cost.
    */
    for(var h = 4; h < arguments.length; h++)
	itin = itin.replace('{' + (h - 4) + '}', input_value(arguments[h]));
    var fbasecost = set_str_param("&basecost={0}", basecost); 
    var depart = set_str_param("&departd={0}&departm={1}&departy={2}", 
			    input_value('departd'), 
                            input_value('departm'), 
                            input_value('departy')); 
    var gocgi = cgi + "?action=itinerary&itinerary=" + 
            escape(itin) + depart + fbasecost;
    itinerary_request(gocgi, itinerary_req_handler, target_el);
}
function input_value(elid) {
    var input = $(elid);
    return (input) ? escape(input.value) : null;
}

function set_str_param(s){
    var sout = s;
    for(var a = 1; a < arguments.length; a++)
	sout = sout.replace('{' + (a - 1) + '}', arguments[a]);
    return sout;
}

function itinerary_request(url, finalise, el) {
    if (!url) return "";
    try { $(el).innerHTML = "... calculating ..."; } catch(e) { }
    var req = false;
    if(window.XMLHttpRequest) {
        try {
            req = new XMLHttpRequest();
        } catch(e) {
            req = false;
        }
    } else if(window.ActiveXObject) {
        try {
            req = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e) {
            try {
                req = new ActiveXObject("Microsoft.XMLHTTP");
            } catch(e) {
                req = false;
            }
        }
    }
    if(req) {
        req.onreadystatechange = function () { finalise(req, el); };
        req.open("GET", url, true);
        req.send("");
    } else {
        alert("Sorry, your browser does not allow access to our online quotation. Please telephone or email us for prices");
    }

    return req;
}

function itinerary_req_handler(req, el) {
    if (req.readyState == 4 && req.status == 200) {
	// text/xml -> req.responseXML, text/{html,plain} -> req.responseText
        var content = req.responseText;
	try {
	    $(el).innerHTML = content;
	} catch(e) {
	    //alert(e);
	}
    }
}

/* update any date inputs to match last set date */
function itinerary_update_depart_inputs() {
    // XXX should use value in departure cookie if it exists?
    var now = new Date();
    $('departd').value = now.getDate();
    $('departm').value = now.getMonth() + 1;
    var year = now.getFullYear();
    var departy = $('departy');
    var departycn = departy.childNodes;
    var ydelta = 0;
    for (var v=0; v < departycn.length ; v++) {
	if(departycn[v].nodeName != 'OPTION') continue; 
	departycn[v].value = year + ydelta;
	departycn[v].innerHTML = year + ydelta;
	ydelta ++;
    }
    departy.value = year; 
}

function getElementsByClassName(node, classname) {
    if (node.getElementsByClassName)
            return node.getElementsByClassName(classname);
    else {
        // simplified - doesnt support multiple classes
        var el = document.getElementsByTagName('*');
        var out = new Array();
        for (var i=0; i<el.length; i++) {
          if (el[i].className ==  classname)
            out.push(el[i]);
        }
        return out;
    }
}

//20100229
function clickthrough_phone () {
    var _current_onload = window.onload;
    window.onload = function () { 
        var tel = "";
        var search = document.location.search || "";
        var m = search.match(/phonenumber=([0-9]{11})/);
        if (m) {
            tel = m[1];
            setCookie('phonenumber', tel);
        } else 
            tel = getCookie('phonenumber');
        if (tel) {
            var el = getElementsByClassName(document, 'addr_nr_sales');
            for (var i=0; i<el.length; i++) {
                el[i].innerHTML = tel;
            }
        }
        if (_current_onload) _current_onload();
    }
}
clickthrough_phone();

function volcano () {
    var _current_onload = window.onload;
    window.onload = function () { 
        var c = document.getElementById('primary_image');
        if (c) {
            var html = '<div class="superlight" id="volcano"><a href="/cuba/volcano/">Note about flight disruption caused by Volcano ash</a></div>';
            var div = document.createElement('DIV');
            div.innerHTML = html;
            c.insertBefore(div, c.childNodes[0]);
        }
        if (_current_onload) _current_onload();
    }
}
//volcano();

function hot_offer(where, link, title) {
    var _current_onload = window.onload;
    window.onload = function () { 
    var html = '<div class="lhs"><div class="hot_offer_head">HOT OFFER: <a href="'+link+'">'+title+'</a></div><div class="hot_offer_duration"><span id="hot_offer_days">?</span> days <span id="hot_offer_hours">?</span> hours remaining</div><div class="hot_offer_link"><a href="'+link+'">VIEW OFFER</a></div></div><div class="rhs">Get the latest offers from Travelzest\'s portfolio of boutique travel companies:<div><img src="/cuba/common/tz-signup.png"> <a href="http://www.zest4travel.co.uk/newsletter/">Email Sign-up</a></div></div>'
    var body = getElementsByClassName(document.body, where)[0];
    var div = document.createElement('DIV');
    div.className = "hot_offer";
    div.innerHTML = html;
    body.insertBefore(div, body.childNodes[0]);
    var dh = document.getElementById('hot_offer_hours');
    var dd = document.getElementById('hot_offer_days');
    var updater = function () {
        var d = new Date(); // time until midnight on Monday
        var days = (8 - d.getDay()) % 7; 
        var hours = 24 - d.getHours();
        if (d.getMinutes() > 30) hours -= 1;
        dh.innerHTML = hours;
        dd.innerHTML = days;
    };
    updater();
    setInterval(updater, 1000*60*60);
    }
    if (_current_onload) _current_onload();
}

//hot_offer('outer', "/cuba/suggested_itineraries/weekly_offer.html","&pound;175 off 13nt Havana and Beach")
//hot_offer('outer',"/cuba/iberostar_varadero/", "SAVE upto &pound;300 per family Luxury beach break");
//hot_offer('outer',"/cuba/hostal_valencia/", "6nt Havana Escape from &pound;1025pp");
//hot_offer('outer',"/cuba/sol_rio_de_luna_y_mares/", "Beach &amp; Havana 13nt &pound;1095pp");
//hot_offer('outer',"/cuba/playa_pesquero_hotel/", "Beach Break - Save &pound;95 per person");
//hot_offer('outer',"/cuba/melia_las_americas/", "Varadero Deluxe Break - Save &pound;95 per person");
//hot_offer('outer',"/cuba/hostal_valencia/", "Havana Escape - Save &pound;75 per person");
//hot_offer('outer',"/cuba/princesa_del_mar_resort_and_spa/", "Luxury Break to Valdero - Save &pound;105pp");
//hot_offer('outer',"/cuba/iberostar_tainos/", "Two-centre Summer treat, save &pound;150pp");
//hot_offer('outer',"/cuba/melia_las_americas/", "6 Night Varadero break, save &pound;95pp");
//hot_offer('outer',"/cuba/sol_cayo_largo/", "7 Night city &amp; island, save &pound;85pp");
//hot_offer('outer',"/cuba/melia_las_americas/", "6 night break in Varadero, save &pound;95pp");
//hot_offer('outer',"/cuba/royal_hideaway_cayo_ensenachos/", "Luxury in Cuba, save &pound;1755pp");
//hot_offer('outer',"/cuba/sol_rio_de_luna_y_mares/", "East Cuba beach &amp; Havana, save &pound;120pp");
hot_offer('outer',"/cuba/cayo_levisa/", "Cuba Twin Centre, save &pound;75pp");
