// Window Open ( target="_blank" )
function wo(url)
{
	window.open(url, '', '');
}

function init(page, type, lang_id, lang, day, month, year, obj_id, booked_id, theme)
{
	if ((type == 'destination') || (type == 'hotel')) {
		initLanguages();
	}
	
	initCalendar(lang, theme);
	
	switch (page) {
		case 'search':
			if (type == 'destination') {
				splash(400, 'auto');
				$('#part').val("1");
				avcity_req(obj_id, $('#d_from').val(), $('#d_to').val(), $('#adults').val(), lang_id);
				
				initFilter();
				
				// Modify your search
				$('#modify_search').click(function() {
					$('#search_params').hide();
					$('#form_availability').show();
					return false;
				});
				
				$('.language a').click(function() {
					$('#form_availability').attr('action', $(this).attr('href'));
					$('#form_availability').submit();
					return false;
				});
			}
			break;
		case 'rooms':
			splash(400, 'auto');
			if (($('#a').val() == 15) && ($('#u').val() == 0)) {
				avdata = [booked_id, "", "", $('#adults').val(), $('#currency').val(), lang_id, "", 0]
				get_booked_availability(avdata);
			} else {
				avhotel_req(obj_id, $('#d_from').val(), $('#d_to').val(), $('#adults').val(), lang_id, $('#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
	}
}

//*** Languages
function initLanguages()
{
	$(document).ready(function() {
		$("#languages").mouseover(function () {
			$("#languages").addClass("languages-show");
		});
		$("#languages").mouseout(function () {
			$("#languages").removeClass("languages-show");
		});
	});
}

//*** Map
var map = undefined;
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 } );
}

//*** Search Hotels
function avcity_req(dest_id, from, to, adults, lang)
{
	$.ajax({
		type: "GET",
		url: "/functions/check_avail.php",
		data: {
			page:    'search',
			dest_id: dest_id,
			from:    from,
			to:      to,
			adults:  adults,
			lang:    lang,
			t:       1,
			r:       Math.random()
		},
		dataType: "xml",
		success: function(xml) {
			var jid = $('ca', xml).find('jid').text();
			var bot = $('ca', xml).find('bot').text();
			if (jid != '') {
				avcity_get(jid);
			} else if (bot != '') {
				$("#bot").val(1);
				avcity_result();
			} else {
				$("#splash").dialog('close');
				window.scrollTo(0, 0);
				alert("Can't process request");
			}
		}
	});
}
function avcity_get(jid)
{
	$.ajax({ 
		type: "GET", 
		url: "/functions/check_avail.php", 
		data: { 
			page: 'search',
			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', parseInt($('ca', xml).find('progress').text()) );
				setTimeout(function() {
					avcity_get(jid)
				}, 3000);
			} else if($('ca', xml).find('bad_jid').size()) {
				$("#splash").dialog('close');
				window.scrollTo(0, 0);
				alert("Can't process request");
			} else if($('ca', xml).find('done').size()) {
				$("#count").text( $('ca', xml).find('done').text() );
				$("#jid").val(jid);
				$("#progress").progressbar('option', 'value', 100);
				setTimeout(function() {
					$("#splash").dialog('close');
					$("#progress").progressbar('option', 'value', 0);
					$("#count").val(0);
					avcity_result();
				}, 1000);
			}
		}
	});
}
function avcity_result()
{
	$("#results").load('/functions/check_avail.php?' + $("#form_preferences").formSerialize() + '&r=' + Math.random(), function() {
		$('#data_stars p').each(function() {
			var id  = $(this).attr('id');
			var cnt = $(this).text();
			var act = $(this).attr('class') == 'active';
			filterdiv(id, cnt, act, 'star');
		});
		$('#data_prices p').each(function() {
			var id  = $(this).attr('id');
			var cnt = $(this).text();
			var act = $(this).attr('class') == 'active';
			filterdiv(id, cnt, act, 'price');
		});
		init_hotelslist();
		$("#splash").dialog('close');
		window.scrollTo(0, 0);
	});
}
function filterdiv(id, cnt, act, filter)
{
	if (filter == 'star') {
		rep = 's_';
	} else if (filter == 'price') {
		rep = 'p_';
	}
	
	add_id  = id.replace(rep, '');
	li_id   = 'l_' + rep + add_id;
	inp_id  = 'f_' + rep + add_id;
	span_id = 's_' + rep + add_id;
	
	$('#' + span_id).html('(' + cnt + ')');
	if (parseInt(cnt)) {
		$('#' + li_id).removeClass('inactive');
		$('#' + inp_id).removeAttr('disabled');
		if (act) {
			$('#' + inp_id).attr('checked', 'checked');
		}
	} else {
		$('#' + li_id).addClass('inactive');
		$('#' + inp_id).removeAttr('checked');
		$('#' + inp_id).attr('disabled', 'disabled');
	}
}
function init_hotelslist()
{
	$('#sort-by a').click(function() {
		var param = $(this).attr('id').split('_');
		$('#sort').val(param[1]);
		$('#sortd').val(param[2]);
		avcity_result();
		return false;
	});
	$('#navigation a').click(function() {
		var part = $(this).attr('class');
		part = part.replace('p_', '');
		$('#part').val(part);
		avcity_result();
		return false;
	});
}
function initFilter()
{
	$('#s-distance').change(function() {
		$('#part').val("1");
		avcity_result();
	});
	$('#s-location').change(function() {
		$('#part').val("1");
		avcity_result();
	});
	$('#s-currency').change(function() {
		$('#part').val("1");
		avcity_result();
	});
	$('#s-stars input').change(function() {
		$('#part').val("1");
		var f = '';
		$('#s-stars input').each(function() {
			if ( $(this).attr('checked') ) {
				if (f != '') f += '|';
				f += $(this).val();
			}
		});
		$('#hstars').val(f);
		avcity_result();
		return false;
	});
	$('#s-prices input').change(function() {
		$('#part').val("1");
		var f = '';
		$('#s-prices input').each(function() {
			if ( $(this).attr('checked') ) {
				if (f != '') f += '|';
				f += $(this).val();
			}
		});
		$('#hprices').val(f);
		avcity_result();
		return false;
	});
	$('#s-find').click(function() {
		$('#part').val("1");
		avcity_result();
		return false;
	});
}

//*** Search Rooms
function avhotel_req(hotel_id, from, to, adults, lang, result)
{
	$.ajax({
		type:  "GET",
		url:  "/functions/check_avail.php",
		data: {
			page:     'search',
			hotel_id: hotel_id,
			from:     from,
			to:       to,
			adults:   adults,
			lang:     lang,
			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", 
		data: {
			page: 'search',
			jid:  jid,
			r:    Math.random()
		}, 
		dataType: "xml", 
		success: function(xml) {
			if($('ca', xml).find('progress').size()) {
				$("#progress").progressbar('option', 'value', parseInt($('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() {
					avhotel_result(jid, result);
				}, 1000);
			}
		}
	});
}
function avhotel_result(jid, from_hash)
{
	$("#results").load('/functions/check_avail.php?' + $("#form_result").formSerialize() + '&r=' + Math.random(), function(response) {
		if (response.substr(0, 6) == 'booked') {
			$("#results").text('');
			data = response.substr(6).split('|');
			get_booked_availability(data);
		} else {
			$("#splash").dialog('close');
		}
	});
}

//*** Calendar
function initCalendar(lang,theme)
{
	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:        theme>100?'/templates/hotel1/images/calendar.gif':'/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 = getDate( $(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_to_my, #d_to2_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').change( function() {
		var id = $(this).attr('id');
		id = id.replace('_my', '');
		id = id.replace('_d', '');
		return cal_read_linked(id); 
		} 
	);
	
	$('#d_to, #d_from, #d_from2, #d_to2').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 = getDate( $('#' + 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_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);
		val = month_names[m - 1] + " '" + 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 = getDate( $('#' + from_id).val() );
	var d_to   = getDate( $('#' + 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 getDate(value)
{
	if (!value) return;
	fields = value.split('-');
	return fields.length < 3 ? null : new Date(fields[0], fields[1] - 1, fields[2]);
}

//*** Splash
function splash(width, height)
{
	$("#splash").dialog({
		width:         width,
		height:        height,
		bgiframe:      true,
		modal:         true,
		title:         false,
		closeOnEscape: false,
		draggable:     false,
		resizable:     false,
		position:      { collision: 'none' } /* Dialog positioned on left side in Safari */
	}).parent().find(".ui-dialog-titlebar").remove();
	$("#progress").progressbar();
}

//*** Booked Availability
function get_booked_availability(data)
{
	//booked_id, from, to, adults, currency, lang_id, use_dates
	$.ajax({ 
		type: "GET", 
		url: "/functions/check_avail.php", 
		data: {
			page:      'booked_avail',
			hotel_id:  data[0],
			from:      data[1],
			to:        data[2],
			adults:    data[3],
			currency:  data[4],
			lang_id:   data[5],
			use_dates: data[7],
			r:         Math.random()
		}, 
		success: function(text) {
			if (text.length > 1) {
				$('#results').html(text);
				init_load_rooms_block();
				init_show_prices(); // overload click for button 'Show Prices'
				init_book_now(data[6]); // overload click (form method, form action)) for button 'Book Now'
				if (!$.browser.msie || $.browser.version.substr(0,1)>7) { $(window).bind('scroll', function () {scroll_book_now()}); }
				$("#splash").dialog('close');
			} else {
				$("#a").val('1');
				avhotel_result();
				$("#a").val('15');
			}
		}
	});
}
function init_show_prices()
{
	$('.bl-btn').click(function() {
		$("#popup-dates-div").dialog({
			width:         258,
			dialogClass:   'popup-dates',
			bgiframe:      true,
			modal:         true,
			title:         $("#popup-dates-title").text(),
			closeOnEscape: true,
			draggable:     false,
			resizable:     false
		});
		return false;
	});
	
	if ( $(".bl-btn").length <= 0 ) {
		$("#currency_div").show();
	}
}
function init_book_now(lang)
{
	url = lang == 'en' ? '/book/' : '/' + lang + '/book/';
	$('#results form').attr('action', url);//.attr('method', 'post');
}
function scroll_book_now()
{
	if (!$('.book-scroll').size()) return;

	$('.book-scroll').addClass('fix').css('top','auto');
	var se = $('.book-scroll');
	var sep = $('.book-scroll').offset();
	var st = sep.top;
	var sb = st + $('.book-scroll').height();
	var rp = $('#rooms_avail_0').offset();
	var rh = $('#rooms_avail_0').height() +  rp.top;
	//alert('Top - ' + rp.top + ' Bottom - ' + rh + ' Current - '+ st + ' sb - ' + sb + ' otst - ' + (rh-$('.book-scroll').height() - 20));
	//alert(sep.top - rp.top);
	if (st < rp.top)
	{
		se.removeClass('fix');	
	}
	else 
	if (sb>rh-20)
	{
		var new_top = ($('#rooms_avail_0').height()-$('.book-scroll').height()-20);
		//alert(new_top);
		if (new_top<40) new_top=40;
		se.removeClass('fix').css('top', new_top + 'px');
	}
	else
	{
		se.addClass('fix').css('top','auto');
	}						    																    								    				    															    					    					
}


