var map = undefined;

function init(page, type, lang, day, month, year, obj_id) {
	// init calendar
	cal_init(type, lang, day, month, year);

	switch (page) {
		case 'search':
			if (type == 'destination') {
				splash(400, 230);
				$('#part').val("1");
				avcity_req(obj_id, $('#d_from').val(), $('#d_to').val(), $('#adults').val(), $('#results'));

				$('#landmarks select').bind('change', function() {
					$('#part').val("1");
					avcity_result();
				});

				$('.currency').bind('change', function() {
					$('#part').val("1");
					avcity_result();
				});

				$('#star_rating input').bind('change', function() {
					$('#part').val("1");
					var f = '';
					$('#star_rating input').each(function() {
						if($(this).attr('checked')) {
							if(f != '') f += '|';
							f += $(this).val();
						}
					});
					$('#hstars').val(f);
					avcity_result();
					return false;
				});

				$('#price_rating input').bind('change', function() {
					$('#part').val("1");
					var f = '';
					$('#price_rating input').each(function() {
						if($(this).attr('checked')) {
							if(f != '') f += '|';
							f += $(this).val();
						}
					});
					$('#hprices').val(f);
					avcity_result();
					return false;
				});

				$('#form_preferences #btn_go').bind('click', function() {
					$('#part').val("1");
					avcity_result();
					return false;
				});

				// Modify your search
				$('a.change_search').click(function() {
					$('#travel_plan').hide();
					$('#hotel_filter').show();
					return false;
				});

				$('.language a').click(function() {
					$('#form_availability').attr('action', $(this).attr('href'));
					$('#form_availability').submit();
					return false;
				});
			} else if (type == 'hotel') {
				splash(400, 'auto');
				avhotel_req(obj_id, $('#d_from').val(), $('#d_to').val(), $('#adults').val(), $('#results'));
			}
		break;
	}

	if ((type == 'destination') || ((type == 'hotel') && (page == 'map'))) {
		// maps handler
		$('a.showmap').bind('click', function() {
			var map_cont = $(gmap_opts.mapcont);
			if( !map_cont.size() ) return false;
			
			var oid = $(this).attr('id');
			var id = oid.replace('sm_', '');
			
			if( !map_cont.hasClass('ready') || typeof map == 'undefined' ) {
				map_cont.html('<div id="map_ajax_loader"></div>');
				map_cont.show();
				center_window(map_cont);
				map_id = id;
				load_map();
			} else {
				map.show(id);
			}

			return false;
		});
		
		$(window).bind('unload', function() {
			if(typeof GUnload == 'function') GUnload();	
		});
		// /maps
	}
}

function load_map() {
	var loadscript = typeof $.loadScript != 'undefined' ? $.loadScript : $.getScript;
	var url = 'http://maps.google.com/maps?file=api&v=2&key=' + gmap_opts.gmapkey + '&async=2&callback=load_map_page&hl=' + gmap_opts.lang_code;
	loadscript(url, function() { });
}

function load_map_page() {
	var map_cont = $(gmap_opts.mapcont);
	
	var mh = $(map_cont).height();
	var mw = $(map_cont).width();
	
	var id = map_id;
	
	// init map
	var url = '';
	if(typeof(gmap_opts.page_url) != 'undefined') {
		url = gmap_opts.page_url;
		
		url = url.replace('[LANG]', gmap_opts.lang_id);
		url = url.replace('[DEST]', gmap_opts.dest_id);
		url = url.replace('[ID]', id);
		
		if(url.indexOf('?') > -1) {
			url += '&';
		} else {
			url += '?';
		}
		
		url += '&w=' + mw + '&h=' + mh;
		url += '&r=' + Math.random();
	} else {
		url = '/maps/data/page?langID=' + gmap_opts.lang_id + '&w=' + mw + '&h=' + mh + '&id=' + id + '&did=' + gmap_opts.dest_id + '&r=' + Math.random();	
	}
	 
	$(map_cont).load(url, function() {
		var loadscript = typeof $.loadScript != 'undefined' ? $.loadScript : $.getScript;
		
		loadscript('/maps/js/maps.pack.js?v=1.0.3', function() 
		{
			if(typeof gmap_opts == 'object' ) {
				map = new HotelsMap(gmap_opts);
				
				if(typeof geo_opts != 'undefined') {
					map.options(geo_opts);
				}
				
				map.init(id);
			}

			map_cont.addClass('ready');
		});
	});	
}

function center_window(map_cont) {
	var mh = $(map_cont).height();
	var mw = $(map_cont).width();
	
	var wh = $(window).height();
	var ww = $(window).width();
	
	var top = (wh - mh) / 2;
	if( $(map_cont).css('position') == 'absolute' ) { 
		top += $(window).scrollTop();
	}
	
	var left = (ww - mw) / 2 + $(window).scrollLeft();
	
	map_cont.css( { 'top' : top + 'px', 'left' : left + 'px', 'z-index' : 9999 } );
}
// /map

/* ==================================================================== */
/* Search Hotels */
/* ==================================================================== */
function avcity_req(dest_id, from, to, adults, result) {
	$.ajax({
		type:  "GET"
		,url:  "/functions/check_avail.php?page=search"
		,data: {
			dest_id: dest_id
			,from:   from
			,to:     to
			,adults: adults
			,t:      1
			,r:      Math.random()
		} 
		,dataType: "xml"
		,success: function(xml) {
			var jid = $('ca', xml).find('jid').text();
			if(jid != '') {
				avcity_get(jid, result);
			} else {
				$(result).html('');
			}
		}
	});
}

function avcity_get(jid, result) {
	$.ajax({ 
		type: "GET", 
		url: "/functions/check_avail.php?page=search", 
		data: { 
			'jid'   : jid,
			'r'     : Math.random()
		}, 
		dataType: "xml", 
		success: function(xml) {
			if($('ca', xml).find('progress').size()) {
				if($('ca', xml).find('h'))
					$("#count").text( $('ca', xml).find('h').text() );
				$("#progress").progressbar('option', 'value', $('ca', xml).find('progress').text() );
				setTimeout(function() {
					avcity_get(jid, result)
				}, 3000);
			} else if($('ca', xml).find('bad_jid').size()) {
				alert("Can't process request");
			} else if($('ca', xml).find('done').size()) {
				$("#jid").val(jid);
				$("#progress").progressbar('option', 'value', 100);
				setTimeout(function() {
					$("#splashdiv").dialog('close');
					$("#progress").progressbar('option', 'value', 0);
					$("#count").val(0);
					avcity_result(jid, result);
				}, 1000);
			}
		}
	});
}

function avcity_result(jid, from_hash) {
	var data = '/functions/check_avail.php?' + $("#form_preferences").formSerialize() + '&r=' + Math.random();
	$("#results").load(
		data,
		function() {
			$('#results .data.stars p').each(function() {
				var id  = $(this).attr('id');
				var cnt = $(this).text();
				filterdiv(id, cnt, 'star');
			});

			$('#results .data.prices p').each(function() {
				var id  = $(this).attr('id');
				var cnt = $(this).text();
				filterdiv(id, cnt, 'price');
			});

			init_hotelslist();
			$("#splashdiv").dialog('close');
			window.scrollTo(0, 0);
		}
	);
}

function filterdiv(id, cnt, filter) {
	if (filter == 'star') {
		rep = 's_';
	} else if (filter == 'price') {
		rep = 'p_';
	}

	add_id = id.replace(rep, '');

	inp_id  = 'f_'+rep+add_id;
	span_id = 's_'+rep+add_id;
	txt_id  = 'a_'+rep+add_id;
	txt     = $('#' + txt_id).text();

	if (cnt == 0) {
		$('#' + inp_id).removeAttr('checked');
		$('#' + inp_id).attr('disabled', 'disabled');
		$('#' + span_id).html('<span id="'+txt_id+'" class="inact">'+txt+'</span> <span class="inact">(0)</span>');
	} else {
		$('#' + inp_id).removeAttr('disabled');
		$('#' + span_id).html('<label for="'+inp_id+'"><a id="'+txt_id+'" class="filter_link" href="#'+filter+'_'+add_id+'">'+txt+'</a></label> ('+cnt+')');
	}
}

function init_hotelslist() {
	$('#results .hotels_sort a').bind('click', function() {
		var param = $(this).attr('id').split('_');
		$('#sort').val(param[1]);
		$('#sortd').val(param[2]);
		avcity_result();
		return false;
	});

	$('#results .nav a').bind('click', function() {
		var part = $(this).attr('class');
		part = part.replace('p_', '');
		$('#part').val(part);
		avcity_result();
		return false;
	});
}

/* ==================================================================== */
/* Search Rooms */
/* ==================================================================== */
function avhotel_req(hotel_id, from, to, adults, result) {
	$.ajax({
		type:  "GET"
		,url:  "/functions/check_avail.php?page=search"
		,data: {
			hotel_id: hotel_id
			,from:   from
			,to:     to
			,adults: adults
			,t:      2
			,r:      Math.random()
		} 
		,dataType: "xml"
		,success: function(xml) {
			var jid = $('ca', xml).find('jid').text();
			if(jid != '') {
				avhotel_get(jid, result);
			} else {
				$(result).html('');
			}
		}
	});
}

function avhotel_get(jid, result) {
	$.ajax({ 
		type: "GET", 
		url: "/functions/check_avail.php?page=search", 
		data: { 
			'jid'   : jid,
			'r'     : Math.random()
		}, 
		dataType: "xml", 
		success: function(xml) {
			if($('ca', xml).find('progress').size()) {
				$("#progress").progressbar('option', 'value', $('ca', xml).find('progress').text());
				setTimeout(function() {
					avhotel_get(jid, result)
				}, 3000);
			} else if($('ca', xml).find('bad_jid').size()) {
				alert("Can't process request");
			} else if($('ca', xml).find('done').size()) {
				$("#jid").val(jid);
				$("#progress").progressbar('option', 'value', 100);
				setTimeout(function() {
					$("#splashdiv").dialog('close');
					$("#progress").progressbar('option', 'value', 0);
					avhotel_result(jid, result);
				}, 1000);
			}
		}
	});
}

function avhotel_result(jid, from_hash) {
	var data = '/functions/check_avail.php?' + $("#form_result").formSerialize() + '&r=' + Math.random();
	$("#results").load(
		data,
		function() {
			$("#splashdiv").dialog('close');
			window.scrollTo(0, 0);
		}
	);
}

/* ==================================================================== */
/* Calendar */
/* ==================================================================== */
function cal_init(type, lang) {
	switch (lang) {
		case 'en': lang = ''; break;
		case 'pt': lang = 'pt-BR'; break;
		case 'zh': lang = 'zh-CN'; break;
	}

	$.datepicker.setDefaults($.datepicker.regional[lang]);
	$.datepicker.setDefaults({
		showOn:             'button'
		,buttonImageOnly:    true
		,buttonImage:        '/images/calendar.gif'
		,buttonText:         ''
		,showMonthAfterYear: false
		,numberOfMonths:     2
		,dateFormat:         'yy-mm-dd'
	});

	$('.calendar_field').datepicker({
		beforeShow: cal_read_linked,
		onSelect:   cal_update_linked
	});

	$('.calendar_field').each(function() {
		var d = cal_get_date($(this).val());
		var year = undefined;
		var month = undefined;
		var day = undefined;
		
		if(d) {
			year  = d.getYear();
			month = d.getMonth() + 1;
			day   = d.getDate();
			
			if(year < 2000) year += 1900; // f@#cking browsers
		}
		cal_init_monyear_field($(this).attr('id'), year, month, 12);
		cal_init_days_field($(this).attr('id'), day);
	});
	
	
	$('#d_from_my, #d_from2_my, #d_from3_my, #d_to_my, #d_to2_my, #d_to3_my').change( 
		function() {
			var id = $(this).attr('id');
			id = id.replace('_my', '');
			return cal_init_days_field(id); 
		} 
	);
	
	$('#d_from_my, #d_from_d, #d_to_my, #d_to_d, #d_from2_my, #d_from2_d, #d_to2_my, #d_to2_d, #d_from3_my, #d_from3_d, #d_to3_my, #d_to3_d').change(
		function() {
			var id = $(this).attr('id');
			id = id.replace('_my', '');
			id = id.replace('_d', '');
			
			var ret = cal_read_linked(id); 
			
			return ret;
		} 
	);
	
	$('#d_to, #d_from, #d_from2, #d_to2, #d_from3, #d_to3').change( function() {
		cal_recheck($(this).attr('id'));
	});
}

function cal_read_linked(cal_id) { 
	if(typeof(cal_id) == 'object') cal_id = cal_id.id;
	if(!cal_id) cal_id = $(this).attr('id');
	
	var from_id = cal_id;
	from_id = from_id.replace('_to', '_from');
		
	var to_id = from_id;
	to_id = to_id.replace('_from', '_to');
	
	$('#' + cal_id).val( 
		$('#' + cal_id + '_my').val() + '-' + 
		$('#' + cal_id + '_d').val() 
	);
	$('#' + cal_id).trigger('change');
	
	var today = new Date();

	var tomorrow = cal_get_date($('#' + from_id).val());
	tomorrow.setTime( tomorrow.getTime() + 86400000 );

	var md = (cal_id == to_id ? tomorrow : today);

	return {
		minDate: md,
		maxDate: null
	};
} 

function cal_update_linked(date, cal_id) { 
	if(typeof(cal_id) == 'object') cal_id = $(this).attr('id');
	
	if(!date || date == '') return false;

	var fields = date.split('-');
	
	var old_my = $('#' + cal_id + '_my').val();
	var new_my = fields[0] + '-' + fields[1];
	
	if(old_my != new_my) {
		$('#' + cal_id + '_my').val(new_my);
		cal_init_days_field(cal_id);
		/*		cal_read_linked(cal_id);*/
	}
	
	$('#' + cal_id + '_d').val(fields[2]);
	$('#' + cal_id).trigger('change');
	
	return true;
}

function cal_init_monyear_field(cal_id, year, month, offset) {
	var new_ym = new Array();
	var key = '', val = '';
	
	var month_names = $.datepicker._defaults.monthNamesShort;
	
	var today = new Date();
	
	var m = today.getMonth() + 1;
	var y = today.getYear();
	if(y < 1900) y += 1900;
	
	var select_ctrl = $('#' + cal_id + '_my');
	
	select_ctrl.empty();
	select_ctrl_m = select_ctrl.get(0);
	
	var key = '', val = '';
	for(i = 0; i < offset; ++i) {
		key = y + '-' + (m < 10 ? '0' + m : m);
		val = month_names[m - 1] + " '" + (y % 100 < 100 ? '0' + y % 100 : y % 100);

		select_ctrl_m.options[i] = new Option(val, key);
		
		++m;
		if(m > 12) {
			++y; 
			m = 1;
		}
	}
	
	select_ctrl.val(year + '-' + (month < 10 ? '0' + month : month));
}

function cal_init_days_field(cal_id, day) {
	var ym = $('#' + cal_id + '_my').val();
	var fields = ym.split('-');
	var y = fields[0];
	var m = fields[1];
	
	if(day == undefined) {
		day = $('#' + cal_id + '_d').val();
	}
	
	var select_ctrl = $('#' + cal_id + '_d');
	
	var day_names = $.datepicker._defaults.dayNamesShort;
	
	var wd = new Date(y, m - 1, 1).getDay();
	var daysInMonth = 32 - new Date(y, m - 1, 32).getDate(); 
	
	var today = new Date();
	var today_year = today.getYear();
	if(today_year < 1900) today_year += 1900;
	
	var start = 1;
	if(y == today_year && m == (today.getMonth() + 1)) {
		start = today.getDate();
	}
	
	select_ctrl.empty();
	var select_ctrl_m = select_ctrl.get(0);
	
	var cnt = 0;
	var key = '', val = '';
	for(d = start; d <= daysInMonth; ++d) {
		val = day_names[(wd + d - 1) % 7] + ' ' + d;
		key = d < 10 ? '0' + d : d;

		select_ctrl_m.options[d - start] = new Option(val, key);
		if(d == day) select_ctrl_m.options[d - start].selected = true;
		
		++cnt;
	}

	return true;
} 

function cal_recheck(cal_id) {
	var from_id = cal_id;
	from_id = from_id.replace('_to', '_from');
	
	var to_id = from_id;
	to_id = to_id.replace('_from', '_to');
	
	var d_from = cal_get_date($('#' + from_id).val());
	var d_to   = cal_get_date($('#' + to_id).val());
	var today  = new Date;
	
	if(!d_from) d_from = today;
	if(!d_to)   d_to   = today;
	
	if(d_to <= d_from) {
		d_to.setTime( d_from.getTime() + 90000000 ); // 25 hours
		
		$('#' + to_id).val($.datepicker.formatDate('yy-mm-dd', d_to));
		cal_update_linked($('#' + to_id).val(), to_id);
	}
}

function cal_get_date(value) {
	if(!value) return;
	fields = value.split('-');
	return (fields.length < 3 ? null : new Date(parseInt(fields[0], 10), parseInt(fields[1], 10) - 1, parseInt(fields[2], 10)));
}


/* ==================================================================== */
/* Splash */
/* ==================================================================== */
function splash(width, height) {
	$("#splashdiv").dialog({
		bgiframe:       true
		,modal:         true
		,title:         false
		,closeOnEscape: false
		,draggable:     false
		,resizable:     false
		,dialogClass:   'splash'
		,width:         width
		,height:        height
	}).parent().find(".ui-dialog-titlebar").remove();
	$("#progress").progressbar();
}

//--------------------------------------
function setLink(num) {
	document.forms['search_hotels'].elements['s'].value=num;
	document.forms['search_hotels'].submit();
	return false;
}
