
var JBobj = {
	searchExtra: false,
	searchLastType: '', 
	getYmd: function(date) {
		var dt = new Date(date);
		var m = dt.getMonth() + 1;
		var d = dt.getDate();
		m = m < 10 ? '0'+m : m;
		d = d < 10 ? '0'+d : d;
		return dt.getFullYear()+'-'+m+'-'+d;
	},
	
	subscribe: function() {
		var form = $('form[name="subscribe"]');
		var email = $('input[name="email"]', form);
		
		if (JBobj.checkEmail($.trim(email.val()))) {
			InnstantTracker.addEvent({act: 'email clicked', syn: true});
			form.submit();
		} else email.focus();
	},
	
    loadHotelsAjax : function(no_reload, params) {

        if ($('#area_id').val() != '0') {
            var url = '/search/?ajax_reload=1&area_id=' + $('#area_id').val() + '&check_in_date=' + encodeURIComponent($('#check_in_date').val()) + '&check_out_date=' + encodeURIComponent($('#check_out_date').val()) + '&room_type=' + $('#search_rooms').val() + '&price_min=' + $('#price_slider').slider('values', 0) + '&price_max=' + $('#price_slider').slider('values', 1) + '&hotel_name=' + encodeURIComponent($('#hotel_name').val()) + '&order=' + $('#order').val() + '&direction=' + $('#direction').val() + (params ? params : '');
            $('#error_box_search').hide();
            var stars = '';
            if ($('#stars_all').attr('checked') == true) {
                stars = '0,1,2,3,4,5';            
            } else {
                if ($('#stars_5').attr('checked') == true) {
                    stars = '5';
                }
                if ($('#stars_4').attr('checked') == true) {
                    stars += (stars != '' ? ',' : '') + '4';
                }
                if ($('#stars_3').attr('checked') == true) {
                    stars += (stars != '' ? ',' : '') + '3';
                }
                if ($('#stars_2').attr('checked') == true) {
                    stars += (stars != '' ? ',' : '') + '2';
                }
                if ($('#stars_1').attr('checked') == true) {
                    stars += (stars != '' ? ',' : '') + '1';
                }
            }
            url += '&stars=' + stars;
            
            if ($('#WithPictures').attr('checked') == true) {
            	url += '&WithPictures=1';
            }
            
            var facilities = '';
            $("input[name='search_facility\\[\\]']").each(function() { if (this.checked) { facilities += (facilities ? ',' : '') + this.value; } } );

            url += '&facilities=' + facilities;
            if (no_reload) {
                url += '&no_reload=1';
            }
            
            if ($('#landmarkId').val()) {
            	url += '&landmarkId='+$('#landmarkId').val();
            }
            
            if ($('#hotelId').val()) {
            	url += '&hotelId='+$('#hotelId').val();
            }
            
            if (no_reload) {
                $('#loading').dialog('open');
            }
            
            $('#right').load(url ,{}, function() { $('#view_totalHotels').html($('#totalHotels').val()); $('#view_cntHotelsWithPictures').html($('#cntHotelsWithPictures').val()); $('#loading').dialog('close'); JBobj.anchor('#left');  } );
            
        } else {
            $('#error_box_search').show();
        }
        
                
    }
    
,	Sorting : function(type, order, direction)
	{
		$('#order').val(type); $('#direction').val(order == type ? (direction + 1) % 2 : 0);
		JBobj.loadHotelsAjax(1);
	}
	
,	teBookNow : function(hotel){
	}
	
,	expandHotel: function(hotelId, noEvent, hotelName)
	{
        if(!noEvent) {
            InnstantTracker.addEvent({act: $.trim($("#button_"+hotelId).text()) + ' clicked', val: hotelName});
        }
		if (!SearchPage.stop) {
			SearchPage.stop = true;
			$('#progressBar').html('').animate({'height': 'hide'}, 300);
		}
		
		var button = $('#button_' + hotelId).get(0);
		var blockExpand = $('#rooms_block_'+hotelId).get(0);
		
		if ('[+] show rates' == $(button).html()) {
			$(button).html('[-] close');
			
			if (!$(blockExpand).html()) {
				$(blockExpand).html('<img src=\'/images/loading2.gif\' onload="JBobj.expandHotelLoad(' + hotelId + ');" />');
			} else {
				$(blockExpand).animate({'height': 'show'}, 500);
			}
		} else {
			$(blockExpand).animate({'height': 'hide'}, 500);
			$('#button_'+hotelId).html('[+] show rates');
		}
	}
	
,	expandHotelLoad: function(hotelId)
	{
		var blockExpand = $('#rooms_block_'+hotelId).get(0);
		$(blockExpand).animate(
			{'height': 'show'}
		,	300
		,	function() {
				var page = $('#pag').val();
				
				$.post(
					getLink('search/details/')
				,	{'hotelId' : hotelId, 'page' : page}
				,	function(data) {
						$(blockExpand)
						.animate({'height': 'hide'}, 300, function(){$(this).html(data).animate({'height': 'show'}, 500)});
					}
				);
			}
		);
	}
	
,	getRoomsRq:function()
	{
		var rooms = "";
		$("#search-form-small select[name^='rooms[']").each(function(){
		    rooms += '&' + $(this).attr('name') + '=' + $(this).val();
		});
		return rooms;
	}
	
,	getFirstRoomData:function()
	{
		var res = {
			numAdults: parseInt($("#search-form-small select[name='rooms[0][adults]']").val())
		,	numChildren: parseInt($("#search-form-small select[name='rooms[0][children][]']").length)
		};
		return res;
	}
    
,   loadHotels: function(params, attach, trackEvent) 
	{
		var word = $.trim($('#search_location').val());
		if ('city, hotel, landmark or country' == word) {
			word = '';
		}
		if (word || attach) {
			if (attach) {
				var dates = Dates.get('searchFormAttach');
				if (dates['alt']['checkInDate'] && dates['alt']['checkOutDate']) {
		        	var cityId = parseInt($('#city_id_attach').val());
		        	var checkInDate = dates['alt']['checkInDate'];
		        	var checkOutDate = dates['alt']['checkOutDate'];
	        	} else {
	        		$('#checkAvailabilityDialog').dialog('open');
	        		return false;
	        	}
			} else {
				var dates = Dates.get();
				var cityId = parseInt($('#cityId').val());
				var checkInDate = dates['alt']['checkInDate'];
		    	var checkOutDate = dates['alt']['checkOutDate'];
		    	var onRequest = $('#onRequestInit').get(0);
		    	var countryCode = $('#countryCodeInit').get(0);
			}
			
			var nodates = $('#nodates').attr('checked');
			
			if ((!nodates && (!checkInDate || !checkOutDate)) && (!JBobj.searchExtra || JBobj.searchExtra[0] != 'country')) {
				$('#error_box_search').show();
				return;
			}
			
        	
        	checkInDate = encodeURIComponent(checkInDate);
		    checkOutDate = encodeURIComponent(checkOutDate);
		    
		    if (!nodates) {
			    InnstantTracker.addEvent({act: 'search', val: word+'/'+checkInDate+'/'+checkOutDate, syn: true});
			    if (!JBobj.searchExtra || JBobj.searchExtra[0] == 'city') {
			    	var url =
			    	'search/' +
			    	'?checkInDate=' + checkInDate +
			    	'&checkOutDate=' + checkOutDate;
			    	if (cityId) {
			    		url += '&cityId=' + cityId;
			    	} else {
			    		url += '&word=' + word;
			    	}
			    	if (onRequest) {
			    		url += '&onRequest=' + $(onRequest).val();
			    	}
			    	if (countryCode) {
		    			url += '&countryCode=' + $(countryCode).val();
			    	}
			    	url += this.getRoomsRq();
			    } else {
			    	var dates = Dates.selectors();
			    	var url = 'search-bridge/'+JBobj.searchExtra[0]+'/'+JBobj.searchExtra[1]+'/'+JBobj.getYmd($(dates['checkInDate']).datepicker('getDate'))+'/'+JBobj.getYmd($(dates['checkOutDate']).datepicker('getDate'))+'/?opt=1' + this.getRoomsRq();
			    }
	            
		    } else {
		    	InnstantTracker.addEvent({act: 'citysearch', val: word, syn: true});
		    	if (!JBobj.searchExtra || JBobj.searchExtra[0] == 'city') {
			    	var url =
			    	'citysearch/';
			    	if (cityId) {
			    		url += '?cityId=' + cityId;
			    	} else {
			    		url += '?word=' + word;
			    	}
			    	url += this.getRoomsRq();
		    	} else {
		    		var url = 'search-bridge/'+JBobj.searchExtra[0]+'/'+JBobj.searchExtra[1]+'/?opt=1' + this.getRoomsRq();
		    	}
		    }
		    
		    InnstantTracker.addEvent({act: 'City search started', syn: true});
		    var hash = '';
		    if (!JBobj.searchExtra || JBobj.searchExtra[0] == 'city') {
			    hash = window.location.hash;
		    	if (isset('SearchPage')) {
		    		hash = hash.replace(/p:\[\d]/,'p:[1]');
		    	}
		    	
		    	if (hash) {
		    		 url += '&time='+new Date().getTime();	
		    	}
		    }
	    	
	    	window.location = getLink(url+hash);
		} else {
			$('#error_box_search').show();
		}
    }

,	DestinationOnkeypress : function() {
		$('#cityId').val(0); 
		$('#error_box_search').hide();
		$('#areas_results').hide();
	}
	
,	dialogSearch: function()
	{
		var word = $.trim($('#dialog_search_location').val());
		if (word) {
			var dates = Dates.get('promotion');
			var checkin = dates['alt']['checkInDate'];
			var checkout = dates['alt']['checkOutDate'];
			
			if (checkin && checkout) {
	        	var cityId = parseInt($('#cityId').val());
	        	var checkInDate = encodeURIComponent(checkin);
	        	var checkOutDate = encodeURIComponent(checkout);
        	} else {
        		return false;
        	}
        	
	    	var url =
	    	'search/' +
	    	'?checkInDate=' + checkInDate +
	    	'&checkOutDate=' + checkOutDate;
	    	if (cityId) {
	    		url += '&cityId=' + cityId;
	    	} else {
	    		url += '&word=' + word;
	    	}
	    	window.location = getLink(url);
		}
	}
    
,   saveCache : function(type) {

        var url = '/search/?ajax_reload=1&cache=1&no_reload=1&area_id=' + $('#area_id').val() + '&check_in_date=' + encodeURIComponent($('#check_in_date').val()) + '&check_out_date=' + encodeURIComponent($('#check_out_date').val()) + '&room_type=' + $('#search_rooms').val() + '&type=' + type;
        
        if ($('#landmarkId').val()) {
        	url += '&landmarkId='+$('#landmarkId').val()+'&order=6';
        }
        
        $('#right').load(url ,{}, function() { $('#view_totalHotels').html($('#totalHotels').val()); $('#view_cntHotelsWithPictures').html($('#cntHotelsWithPictures').val()); } );
                
    }
    
,   loadCities : function (word) {
        if (word) {
          	$("#search_variants").load('/index/getcities/?word=' + encodeURIComponent(word), {}, function (data) { if (data != '') { $('#search_variants').show(); } else { $('#search_variants').hide(); } } );
        } else {
            $('#search_variants').hide();
        }
    }
,openLoyaltydata: function(t)
	{
		var open = $(t).replaceClass('close','open');
		$('#LoyaltyDetails').animate({height: open?'show':'hide'}, 300);
	}
	,openReferenceDetails: function(t)
	{
		var open = $(t).replaceClass('close','open');
		$('#ReferenceDetails').animate({height: open?'show':'hide'}, 300, function(){
		});
	}
,	anchor : function(obj){
		if (!$(obj).get(0)) return false;
		destination = $(obj).offset().top;
		$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination-5}, 500 );
		return false;
	}
    
,	lock : false    
    
,   checkBookingRoomPage: function(hotel_id, check_in_date, check_out_date, trackEvent, nosubmit)
	{
        if (trackEvent) {
			InnstantTracker.addEvent({act: trackEvent+' clicked', syn: true});
        }
		$('#error_box_' + hotel_id).hide();
		
		var rooms = 0;
		var isRooms = false;
		var dates = check_in_date && check_out_date;
	    $("#rooms_table_hotel_" + hotel_id + " select.sel-room.cnt").each(function(){
	    	isRooms = true;
	    	rooms += parseInt($(this).val());
	    });
	    
	    if (!rooms && isRooms) {
			$('#error_box_' + hotel_id + '_error1').show();
			$('#error_box_' + hotel_id).fadeIn(500);
			$('#loading_box_' + hotel_id).hide();
			JBobj.anchor('#rooms_table_hotel_' + hotel_id);
			return false;
	    } else if (!rooms && !isRooms && dates) {
	    	JBobj.loadHotelRooms();
	    	return false;
	    } else if (!dates) {
	    	$('#checkAvailabilityDialog').dialog('open');
	    } else if (!nosubmit) {
	    	var frm = $('#booking_room_' + hotel_id);
	    	if ($('#pag').val() != 'search') {
		    	var dates = Dates.selectors('checkAvailability');
	    		var act = $('#act').val()+'/'+this.getYmd($(dates['checkInDate']).datepicker('getDate'))+'/'+this.getYmd($(dates['checkOutDate']).datepicker('getDate'))+'/';
	    		if (REMOTE_BOOKING) {
		    		act += '?rb=1';
		    	}
		    	frm.attr('action', act);
	    	}
	    	frm.submit();
	    }
		
		return;
    }
,   checkBookingPackagePage: function(hotel_id, package_id, check_in_date, check_out_date, trackEvent, nosubmit)
	{
		var p_roomsids=$('input[id=p_roomsids'+hotel_id+'_'+package_id+']');
		var p_roomsids_count=$('input[id=p_roomsids_count'+hotel_id+'_'+package_id+']');
		
		jQuery('.sel-room option').attr('selected', false);
		
		$.each( p_roomsids , function(k, v){
			$('select[id=selected_rooms_'+v.value+'] option[value='+p_roomsids_count[k].value+']').attr('selected', 'selected');
		});
		
		JBobj.totalBookingPrice(hotel_id);
		JBobj.checkBookingRoomPage(hotel_id,check_in_date,check_out_date,'Booking from packages list');
		return;
    }
,	CheckCardNumber : function()
	{
		if (!parseInt($('#card_number').val()))
		{
			return false;
		}
		var card_number = $('#card_number').val().split("");
		var card_type_id = parseInt($('#card_type').val());
		var must_credit_card_length = 16;
		switch (card_type_id)
		{
			case 1: // American Express
				var first_number = new Array('3');
				must_credit_card_length = 15;
				break;
			case 2: // Visa
				var first_number = new Array('4');
				break;
			case 3: // Master Card
				var first_number = new Array('5');
				break;
			case 4: // Discover
				var first_number = new Array('6','0','1','1');
				break;
			default:
				return false;
				break;
		}
		if (card_number.length != must_credit_card_length)
		{
			return false;
		}
		else
		{
            for (var j = 0; j < first_number.length; j++)
			{
				if (card_number[j] != first_number[j])
				{
					return false;
				}
			}
			var sum = 0;
			return true;

            /*for (var j = 0; j < (must_credit_card_length - 1); j++)
			{
				var digit = card_number[j];
				if ((j & 1) == (must_credit_card_length & 1))
				{
					digit *= 2;
				}
				if (digit > 9)
				{
					digit -= 9;
				}
				sum += digit;
			}
			var check_digit = new Array(0, 9, 8, 7, 6, 5, 4, 3, 2, 1);
			var last_number = check_digit[sum % 10];
			if (card_number[must_credit_card_length-1] != last_number)
			{
				return false;
			}
			else
			{
				return true;
			}*/
		}
	}
	
,	checkCaptcha: function()
	{
		var element = $('#recaptcha_response_field').get(0);
		$(element).val( $.trim( $(element).val() ) );
		if ($(element).val()) {
			$(element).removeClass("not-true");
			return true;
		} else {
			$(element).addClass("not-true").focus();
			return false;
		}
	}
	
,	checkBookingPaymentPage: function()
	{
		$('#error_box').hide();
		$('#error_box_paypal').hide();
		var cvcErr = $('#cardCvc').val().length < 3;
		if (!$('#frm').checkForm() || cvcErr) {
			if (cvcErr) {
				$('#cardCvc').addClass("not-true");
			}
			$('#error_box').show();
			return false;
		}
		
		var submitButton = $('#submit_button').get(0);
    	submitButton.onclick = '';
    	$(submitButton).addClass('disabled');
    	
    	$.facebox({ div: '#processingTransaction' });
    	var ref = parseInt($('#reservationId').val());
    	$.post('/booking-payment/payment/?ref='+ref,	$('#frm').formToArray(),
    	function(rs) {
    		var httpHost = rs.httpHost ? 'http://www.'+rs.httpHost+'/' : $('#HTTP_HOST').val();
    		
    		if (rs.status == 'success') {
    			$.facebox({ div: '#processingFinished' });
    		} else {
    			$('#error_box_paypal_contact').attr('href', httpHost+'contact');
				$('#error_box_paypal .text').html(rs.msg);
    			$('#dinamic_button').html(rs.button);
    			$('#error_box_paypal .error_box_paypal-close').show();
    			$('#error_box_paypal').show();
    			
    			if (rs.enable) {
    				submitButton.onclick = function() {JBobj.checkBookingPaymentPage();};
					$(submitButton).removeClass('disabled');
    			}
    			
    			setTimeout("$.facebox.close();",300);
    		}
    	}, 'json');
    	
    	return true;
	}
    
,	berrOpen: function(data)
	{
		InnstantTracker.addEvent({act: 'Booking failed'});
		var httpHost = $('#HTTP_HOST').val();
		$('#error_box_paypal').show();
		$('#error_box_paypal .error_box_paypal-close').show();
		$('#error_box_paypal_contact').attr('href', httpHost+'contact');
		$('#error_box_paypal .text').html(data.text);
		$('#dinamic_button').html(data.button);
		setTimeout("$.facebox.close();",300);
	}
    
,	testZipCode: function(zipCode) {
		zipCode = $.trim(zipCode.toLowerCase());
		if (zipCode == 'na') {
			return false;
		}
        var reg = new RegExp("^[a-z0-9 ]+$");
		return reg.test(zipCode);
	}
    
,   checkNumbers : function(evt) {
        
        var charCd = (evt.which != null) ? evt.which : event.keyCode;
        var evt = window.event || evt;
        var special = evt.ctrlKey || evt.altKey;
        if (charCd > 31 && (charCd < 48 || charCd > 57) && !special) {
            return false;
        }
        return true;
    }
    
,   disableQuantity : function(facility_obj) {
        var arr = facility_obj.id.split('_');
        facilityId = arr[2];
        $('#quantity_' + facilityId).each(function() { this.disabled = !facility_obj.checked } );
    }

,   checkEmail : function(email) {
	   var reg = /^[_\.0-9a-z-]+@([0-9a-z][0-9a-z-]{1,}\.)+[a-z]{2,6}$/;
	   
	   return reg.test(email);
    }
    
,   checkLogin : function(noRedirect) {
        $('#error_login').html('');
        $.post('/index/login/', {'email' : $('#auth_email').val(), 'pass' : $('#auth_pass').val() }, function(data) {
                if (data == 'ok') {
                    if (!noRedirect) {
                    	window.location = getLink('booking/');
                    } else {
                    	window.location.reload();
                    }
                    authDialogs.close();
                } else {
                    $('#error_login').html('Authorization failed!');
                }
            }
        );
        
    }
    
,   checkLoginAether : function() {
        $('#error_login').html('');
        $.post('/index/login-aether/', {'account' : $('#account').val(), 'auth_login' : $('#auth_login').val(), 'auth_password' : $('#auth_password').val()}, function(data) {
                if (data == 'ok') {
                    authDialogsAether.close();
                    window.location.reload();
                } else {
                    $('#error_login').html('Authorization failed!');
                }
            }
        );
        
    }
    
,	openLoginNClose: function()
	{
		authDialogs.authorization(1);
	}
    
,   passwordRecovery : function(messageSend, messageNot) {
		$('#passwordRecoveryMessage').html('');
        $.post(getLink('index/passwordrecovery/'), {'email' : $('#emailRecovery').val() }, function(data) {
                if (data != '') {
                	document.getElementById('passwordRecoverySend').style.visibility = "hidden";
                    $('#passwordRecoveryMessage').html(messageSend);
                } else {
                    $('#passwordRecoveryMessage').html('<span style="color: #e51a1a;">'+messageNot+'</span>');
                }
            }
        );  
    }
    
,	resetHotelRooms : function(local, hotelId, check_in_date, check_out_date, PLUS_DAYS, skin)
	{
		if (!local && check_in_date && check_out_date)
		{
			if (!skin) skin = 1;
			$('#roomsblock'+hotelId).html('');
			$('#roomsblock'+hotelId).addClass('loading');
	        $('#error_box_' + hotelId).hide();
	        $('#roomsblock'+hotelId).load
	        (
	        	'/hotel-rooms/'
	        ,	{ 'hotel_id' : hotelId, 'check_in_date' : check_in_date, 'check_out_date' : check_out_date, 'view_all' : JBobj.flagViewAllRooms, 'reset' : 1, 'skin' : skin }
	        ,	function(data)
	        	{
	        		$('#roomsblock'+hotelId).removeClass('loading');
	        		if (!local) {
		        		var in_date = new Date(check_in_date);
		        		var date = new Date();
		        		var check_date = new Date(date.getUTCFullYear(), date.getMonth(), (date.getDate()+PLUS_DAYS));
		        		if (in_date.getTime() >= check_date.getTime()) {
		        			$('#buttonProceed').attr('class', 'button4');
		        		} else {
		        			$('#buttonProceed').addClass('hidden');
		        		}
	        		}
	        	}
	        );
		}
	}
	
,	getLocation : function(check_in_date, check_out_date)
	{
		if (!JBobj.startDate || !JBobj.endDate) return false;
		var new_check_in_date = new Date(check_in_date);
		var new_check_out_date = new Date(check_out_date);
		
		if (!new_check_in_date.getTime()) {
			new_check_in_date = check_in_date.split('-');
		    new_check_in_date = new Date(new_check_in_date[0], parseInt(new_check_in_date[1])-1, new_check_in_date[2]);
		}
		if (!new_check_out_date.getTime()) {
			new_check_out_date = check_out_date.split('-');
		    new_check_out_date = new Date(new_check_out_date[0], parseInt(new_check_out_date[1])-1, new_check_out_date[2]);
		}
		
		var old_check_in_date = JBobj.startDate;
		    old_check_in_date = old_check_in_date.split('-');
		    old_check_in_date = new Date(old_check_in_date[0], parseInt(old_check_in_date[1])-1, old_check_in_date[2]);
		var old_check_out_date = JBobj.endDate;
		    old_check_out_date = old_check_out_date.split('-');
		    old_check_out_date = new Date(old_check_out_date[0], parseInt(old_check_out_date[1])-1, old_check_out_date[2]);
		    
		if (new_check_in_date.getTime() != old_check_in_date.getTime() || new_check_out_date.getTime() != old_check_out_date.getTime()) {
			var loc = '/hotel/' + JBobj.CitySeoName + '/' + JBobj.SeoName + '/';
				loc += new_check_in_date.getFullYear() + '-' + (new_check_in_date.getMonth() < 9 ? '0'+(new_check_in_date.getMonth()+1) : new_check_in_date.getMonth()+1) + '-' + (new_check_in_date.getDate() < 10 ? '0'+new_check_in_date.getDate() : new_check_in_date.getDate()) + '/';
				loc += new_check_out_date.getFullYear() + '-' + (new_check_out_date.getMonth() < 9 ? '0'+(new_check_out_date.getMonth()+1) : new_check_out_date.getMonth()+1) + '-' + (new_check_out_date.getDate() < 10 ? '0'+new_check_out_date.getDate() : new_check_out_date.getDate()) + '/';
				
			return loc;
		} else {
			return false;
		}
	}
    
,	roomTypeRequired : 0
	
,	pollCnt: 0

,	getSparam: function() {
		var dates = Dates.get('checkAvailability');
		var res = {
			'checkInDate':dates['alt']['checkInDate'],
			'checkOutDate':dates['alt']['checkOutDate'],
			'onRequest':$('#onRequestInit').val(),
			'countryCode':$('#countryCodeInit').val()
		};
    	return res;
	}
	
,   loadHotelRooms: function(poll, check)
	{
		var Sparam = JBobj.getSparam();
		var check = check ? 0 : 1;
		var hotelId = $('#hotel_id').val();
		var checkInDate = Sparam['checkInDate'];
		var checkOutDate = Sparam['checkOutDate'];
		var onRequest = Sparam['onRequest'];
		var countryCode = Sparam['countryCode'];
		
		if (!poll && check) {
			$('#reset_loading').html('<img src="/images/'+(RTL?'loading-hotels-big_rtl.gif':'loading-hotels-small.gif')+'" alt="" onload="$(this).css(\'visibility\', \'visible\')" />');
			$('#cha_loading').animate({height: 'show'}, 200);
		} else if (!check) {
			$('#nocheck_loading').animate({height: 'show'}, 200);
		}
		
		var data =
		'hotelId=' + hotelId +
		'&checkInDate=' + checkInDate +
		'&checkOutDate=' + checkOutDate + 
		'&onRequest='    + onRequest   +
		'&countryCode='  + countryCode +
		this.getRoomsRq();
		
		if (richemont) {
			data += '&skin=2';
		}
		
		if (!check) {
			data += '&check=0';
		}
		
		if (check) {
			PriceComparison.others.afterChecking = 0;
			PriceComparison.load();
			if (isset('inban2')) {
				inban2.setView('2');
			}
		}
		
		$.ajax({
			type: 'POST',
			url: getLink('hotel-rooms/'),
			data: data,
			dataType: 'json',
			success: function(data) {
				var status = data['status'];
				var rooms = data['rooms'];
				var firstRoomData = JBobj.getFirstRoomData();
				
				if (check) {
					
					if (JBobj.pollCnt < 20) {
						++JBobj.pollCnt;
					} else {
						status = 'done';
					}
					
					if ('working' == status) {
						$('#roomsblock'+hotelId).html(data['rooms']);
						setTimeout("JBobj.loadHotelRooms(1,false)", 2000);
					} else {
						JBobj.pollCnt = 0;
                        if (!data['gotprice']) {
                        	data['gotprice'] = 0;
                        }
                        InnstantTracker.addEvent({act: 'gotprice', val: hotelId+'|'+checkInDate+'|'+checkOutDate+'|'+data['gotprice'], syn: true});
                        if (!data['gotprice']) {
                        	InnstantTracker.addEvent({act: 'no avaialbe rooms', val: data['searchId'], syn: true});
                        }
                        
                    	$('#reset_loading').html('Done');
                    	$('#roomsblock'+hotelId).html(data['rooms']);
                		if (data['gotprice']) JBobj.anchor('#caForm');
                		var prices = {};
                		prices[hotelId] = data['price'];
  
                		PriceComparison.run({
								"json": data['pricecompare'],
                			"view":   {"prices": prices},
                			"others": {"afterChecking":1,"numAdults":firstRoomData.numAdults,"numChildren":firstRoomData.numChildren}
                		});
                		
                    	if (!richemont) {
                    		JBobj.similarHotelsPoll('hotelId='+hotelId);
                    	}
					}
				} else {
					$('#nocheck_loading').animate({height: 'hide'}, 200, function(){  
						$('#roomsblock'+hotelId).html(data['rooms']);
						if (data['rooms']) {
							var prices = {};
                    		prices[hotelId] = data['price'];
                    		 		
							PriceComparison.run({
								"json": data['pricecompare'],
								"view": {"prices": prices},
								"others": {"numAdults":firstRoomData.numAdults,"numChildren":firstRoomData.numChildren}
							});
						}
					});
					
					
					if (!richemont) {
						if (data['rooms']) {
							JBobj.similarHotelsPoll('hotelId='+hotelId);
						} else {
							$('#similar-hotels').html('');
						}
					}
				}
			}
		});
    }
    
,	altDialogCheckAvailability: function()
	{
		var dates1 = Dates.selectors('checkAvailability');
		var dates2 = Dates.selectors('altDialog');
		var checkInDate = $(dates2['checkInDate']).val();
		var checkOutDate = $(dates2['checkOutDate']).val();
		
		if (checkInDate && checkOutDate) {
			$(dates1['checkInDate']).val(checkInDate);
			$(dates1['checkOutDate']).val(checkOutDate);
			$(dates1['alt']['checkInDate']).val($(dates2['alt']['checkInDate']).val());
			$(dates1['alt']['checkOutDate']).val($(dates2['alt']['checkOutDate']).val());
			
			$('#alternativeDialog').dialog('close');
			JBobj.loadHotelRooms();
		}
	}
    
,   totalBookingPrice : function(hotelId) {
        var sum = 0;
        var roomsCnt = $('#rooms_table_hotel_' + hotelId + ' select[class="sel-room cnt"]');
        var priceAllRooms = $('#rooms_table_hotel_' + hotelId + ' input[name="priceAllRooms[]"]');
        var onlythese = $('#rooms_table_hotel_' + hotelId + ' input[name="onlythese[]"]');
					
			$('#rooms_table_hotel_' + hotelId + ' input[name="room_price[]"]').each(function(i){
					$("#rooms_table_hotel_" + hotelId +" .room_select_box_"+i+" select").attr("disabled","disabled");
					$("#rooms_table_hotel_" + hotelId +" .room_select_box_"+i+" .combination-message").css("display","block");
			 });
			 
        $('#rooms_table_hotel_' + hotelId + ' input[name="room_price[]"]').each(function(i){
	
        	var priceAllRoom = parseInt($(priceAllRooms[i]).val());
        	var roomCnt = parseInt($(roomsCnt[i]).val());
        	var price = parseInt($(this).val());
        	var share = 0;
        	var thisone = $(onlythese[i]).val().split(',');
        	
        	if (roomCnt) {
				
            $.each(thisone, function(key, value) { 
					$("#rooms_table_hotel_" + hotelId +" .room_select_box_"+value+" select").removeAttr("disabled");
					$("#rooms_table_hotel_" + hotelId +" .room_select_box_"+value+" .combination-message").css("display","none");
				});
				
	    		if (priceAllRoom) {
	    			share = price;
	    		} else {
	        		share = price * roomCnt;
	    		}
	    		sum += share;
	    		
	    		$('#hotel'+hotelId+'share'+i).html(share);
	    		$(this).parent('td').parent('tr').addClass('selected');
        	} else {
        		$(this).parent('td').parent('tr').removeClass('selected');
        		$('#hotel'+hotelId+'share'+i).html('');
        	}
        });
        
        if (sum == 0)
        {
			  $('#rooms_table_hotel_' + hotelId + ' input[name="room_price[]"]').each(function(i){
					$("#rooms_table_hotel_" + hotelId +" .room_select_box_"+i+" select").removeAttr("disabled");
					$("#rooms_table_hotel_" + hotelId +" .room_select_box_"+i+" .combination-message").css("display","none");
				});
		  }
        
        $("#total_room_price_" + hotelId).html(sum);
    }
    
,	Trim : function(x) {
		var ch = x.toString();
		var c  = ch.charAt(0);
		
		while (c == " ") { 
			ch = ch.slice(1);
			c  = ch.charAt(0);
		}
		c = ch.charAt(ch.length - 1);
		while(c == " " || c == "\n") { 
			ch = ch.slice(0, -1);
			c = ch.charAt(ch.length - 1);
		}
		return (ch) ? ch : false;
	}
	
,	CheckField : function(Field, Email) {
		var Check = true;
		
		if (Email) { Check = (this.checkEmail(Field.value)) ? true : false; }
		else       { Check = (this.Trim(Field.value))       ? true : false; }
		
		if (!Check) {
			Field.focus();
		}
		
		return Check;
	}
    
,	CheckSendContactForm : function() {
		var FormContact = document.FormContact;
		var FirstName   = FormContact.FirstName;
		var LastName    = FormContact.LastName;
		var Email       = FormContact.Email;
		var Capcha      = FormContact.recaptcha_response_field;
		var Check       = true;
		
		if (!this.CheckField(Capcha))      { Check = false; }
		if (!this.CheckField(Email, true)) { Check = false; }
		if (!this.CheckField(LastName))    { Check = false; }
		if (!this.CheckField(FirstName))   { Check = false; }
		
		if (Check) {
			FormContact.submit();	
		}
	}
	
,	CheckSendFormContactBestPrice : function() {
		var FormContactBestPrice = document.FormContactBestPrice;
		var FirstName            = FormContactBestPrice.FirstName;
		var LastName             = FormContactBestPrice.LastName;
		var Phone                = FormContactBestPrice.Phone;
		var Email                = FormContactBestPrice.Email;
		var ReservationID        = FormContactBestPrice.ReservationID;
		var LowestPrice          = FormContactBestPrice.LowestPrice;
		var Source               = FormContactBestPrice.Source;
		var Capcha               = FormContactBestPrice.recaptcha_response_field;
		var Check                = true;
		
		if (!this.CheckField(Capcha))        { Check = false; }
		if (!this.CheckField(Source))        { Check = false; }
		if (!this.CheckField(LowestPrice))   { Check = false; }
		if (!this.CheckField(ReservationID)) { Check = false; }
		if (!this.CheckField(Email, true))   { Check = false; }
		if (!this.CheckField(Phone))         { Check = false; }
		if (!this.CheckField(LastName))      { Check = false; }
		if (!this.CheckField(FirstName))     { Check = false; }
		
		if (Check) {
			FormContactBestPrice.submit();
		}
	}
	
,	CheckSendFormAddHotel : function() {
		var FormAddHotel = document.FormAddHotel;
		var HotelName   = FormAddHotel.HotelName;
		var NumberRooms = FormAddHotel.NumberRooms;
		var Address     = FormAddHotel.Address;
		var Zipcode     = FormAddHotel.Zipcode;
		var City        = FormAddHotel.City;
		var Province    = FormAddHotel.Province;
		var Country     = FormAddHotel.Country;
		var Phone       = FormAddHotel.Phone;
		var Fax         = FormAddHotel.Fax;
		var Name        = FormAddHotel.Name;
		var Gender      = FormAddHotel.Gender;
		var Email       = FormAddHotel.Email;
		var RetypeEmail = FormAddHotel.RetypeEmail;
		var Capcha      = FormAddHotel.recaptcha_response_field;
		var Check       = true;
		
		if (!this.CheckField(Capcha))            { Check = false; }
		if (RetypeEmail.value != Email.value) {
			Check = false;
			RetypeEmail.focus();
		}
		if (!this.CheckField(Email, true))       { Check = false; }
		if (!this.CheckField(Gender))            { Check = false; }
		if (!this.CheckField(Name))              { Check = false; }
		if (!this.CheckField(Fax))               { Check = false; }
		if (!this.CheckField(Phone))             { Check = false; }
		if (!this.CheckField(Country))           { Check = false; }
		if (!this.CheckField(Province))          { Check = false; }
		if (!this.CheckField(City))              { Check = false; }
		if (!this.CheckField(Zipcode))           { Check = false; }
		if (!this.CheckField(Address))           { Check = false; }
		if (!this.CheckField(NumberRooms))       { Check = false; }
		if (!this.CheckField(HotelName))         { Check = false; }
		
		if (Check) {
			FormAddHotel.submit();
		}
	}
	
,	CheckSendFormRequestFormForGroups : function() {
		var FormRequestFormForGroups   = document.FormRequestFormForGroups;
		var City                       = FormRequestFormForGroups.City;
		var CheckInDate                = FormRequestFormForGroups.CheckInDate;
		var TargetStarRating           = FormRequestFormForGroups.TargetStarRating;
		var NumberOfNights             = FormRequestFormForGroups.NumberOfNights;
		var NumberOfGuests             = FormRequestFormForGroups.NumberOfGuests;		
		var RoomType                   = FormRequestFormForGroups.RoomType;		
		var GroupType                  = FormRequestFormForGroups.GroupType;
		var AverageAgeOfGuests         = FormRequestFormForGroups.AverageAgeOfGuests;
		var MaximumCostPerRoomPerNight = FormRequestFormForGroups.MaximumCostPerRoomPerNight;		
		var PlaceRequired              = FormRequestFormForGroups.PlaceRequired;		
		var Name                       = FormRequestFormForGroups.Name;
		var Phone                      = FormRequestFormForGroups.Phone;
		var Email                      = FormRequestFormForGroups.Email;
		var UserType                   = FormRequestFormForGroups.UserType;
		var Capcha                     = FormRequestFormForGroups.recaptcha_response_field;	
		var Check                      = true;
		
		if (!this.CheckField(Capcha))                     { Check = false; }
		if (!this.CheckField(UserType))                   { Check = false; }
		if (!this.CheckField(Email, true))                { Check = false; }
		if (!this.CheckField(Phone))                      { Check = false; }
		if (!this.CheckField(Name))                       { Check = false; }		
		if (!this.CheckField(PlaceRequired))              { Check = false; }		
		if (!this.CheckField(MaximumCostPerRoomPerNight)) { Check = false; }
		if (!this.CheckField(AverageAgeOfGuests))         { Check = false; }
		if (!this.CheckField(GroupType))                  { Check = false; }		
		if (!this.CheckField(RoomType))                   { Check = false; }		
		if (!this.CheckField(NumberOfGuests))             { Check = false; }
		if (!this.CheckField(NumberOfNights))             { Check = false; }
		if (!this.CheckField(TargetStarRating))           { Check = false; }
		if (!this.CheckField(CheckInDate))                { Check = false; }
		if (!this.CheckField(City))                       { Check = false; }
		
		if (Check) {
			FormRequestFormForGroups.submit();
		}
	}
	
,	CheckSendBookingPersonalDetailsForm : function() {
		var Form = document.booking_personal_details;
		var Check = true;
		
		if (Form.password.value != '') {
			if (Form.password.value.length < 6) {
				Form.password.focus();
				Check = false;
			} else if (Form.confirm_password.value != Form.password.value) {
				Form.confirm_password.focus();
				Check = false;
			}
		}
		if (!this.CheckField(Form.last_name))  { Check = false; }
		if (!this.CheckField(Form.first_name)) { Check = false; }
		
		if (Check) {
			Form.submit();
		}
	}
	
,	openPopup : function(URL, WinName, height, width, external){
        if(height=='' || !height) {
        	height=screen.height/2;
        }
        height_factor = ((screen.height/100)*90);
        if(height >= height_factor) {
        	height=height_factor;
        }

        if(width=='' || !width) {
        	width=screen.width/2;
        }
        width_factor = ((screen.width/100)*98);
        if(width >= width_factor) {
       		width=width_factor;
        }

        var top=((screen.height-height)/2)-(screen.height/20);
        if(top<1) {top=1;}

        var left=(screen.width - width) / 2;
        if(left<1) {left=1;}

        win=window.open(URL, WinName, 'toolbar=no,location=no,directories=no,status=0,menubar=no,scrollbars=1,resizable=1,copyhistory=no,width='+width+',height='+height+',top='+top+',left='+left+'');
        if(!external)
        {
            win.resizeTo(width, height);
            win.moveTo(left, top);
        }
    }
	
,	Booking_More_Details : function(ReservationID, Value) {
		$('#booking_details_'+ReservationID).show(); 
		if ($('#booking_details_'+ReservationID).html().length < 100) {
			$('#booking_details_'+ReservationID).html('<div style=\'text-align:center; padding:20px;\'><img src=\'/images/loading2.gif\' /></div>'); 
			$('#booking_details_'+ReservationID).load(getLink('booking/details/'), {'booking_id' : ReservationID }); 
		}
		var Button = $('#more_details_'+ReservationID).get(0);
		Button.onclick = function() {
			JBobj.Booking_Close_More_Details(ReservationID, Value);
		};
		$('#more_details_text_'+ReservationID).html(Value.Close);
	}
	
,	Booking_Close_More_Details : function(ReservationID, Value) {
		$('#booking_details_'+ReservationID).hide();
		var Button = $('#more_details_'+ReservationID).get(0);
		Button.onclick = function() {
			JBobj.Booking_More_Details(ReservationID, Value);
		};
		$('#more_details_text_'+ReservationID).html(Value.More_Details);
	}
	
,	Mouse : function(This, Over)
	{
		if (Over)
		{
			if (This.className !== 'mouse' && This.className.indexOf(' mouse') === -1)
			{
				This.className += (This.className ? ' ' : '') + 'mouse';
			}
		}
		else
		{
			This.className = This.className == 'mouse' ? '' : This.className.replace(' mouse', '');
		}
	}

,	Average_Rating : function()
	{
		var data = new Array(
			$('#staff_hidden').val()
		,	$('#services_hidden').val()
		,	$('#cleanliness_hidden').val()
		,	$('#comfort_hidden').val()
		,	$('#location_hidden').val()
		,	$('#money_hidden').val()
		);
		var average = Average(data, 1);
		$('#average').html(average);
		$("#average_hidden").val(average);
		return true;
	}
	
,	getPersonsIcon: function(input)
	{
		var numAdults = input['numAdults'];
		var numChildren = input['numChildren'];
		var icon = '';
		var width = 0;
		
    	while (numChildren) {
			icon += '<span class="sprite childicon"></span>';
			numChildren--;
			width += 12;
		}
		while (numAdults) {
			icon += '<span class="sprite ch"></span>';
			numAdults--;
			width += 18;
		}
		icon = '<div style="width:'+width+'px;" class="person-cont">'+icon+'</div>';
		return icon;
	}
	
,	flagViewAllRooms : 0
	
,	ViewAllRooms : function(_this, hotelId, Text)
	{
		var view = _this.innerHTML == Text.View;
		JBobj.flagViewAllRooms = view ? 1 : 0;
		var i = view ? -1 : 2;
		$('#rooms_table_hotel_'+hotelId+' .row-room').each(
			function()
			{
				if (view)
				{
					try     {this.style.display = 'table-row';}
					catch(e){this.style.display = 'block';}
				}
				else
				{
					var id = this.id.split('_');
					id = id[1];
					if (id > 2) this.style.display = 'none';
				}
			}
		);
		_this.innerHTML = (view) ? Text.Close : Text.View;
		
	}

,	clearFilters : function(noEvent)
	{
		if (noEvent) {
			var hash = SearchPage.Hash.get();
			if (hash) {
				SearchPage.update = false;
				var selectors = SearchPage.Hash.selectors;
				for (var i in selectors) {
					if (hash[i]) {
						if (i=='s') {
							$('#stars_all').attr('checked', false);
						} else if (i=='b') {
							$('#boards_all').attr('checked', false);
						}
						$(selectors[i]).each(function(inx){
							var v = in_array(i,['b']) ? inx : parseInt(this.value);
							if (in_array(v, hash[i])) {
								this.checked = true;
							}
						});
					}
				}
				if (hash['pr'] && hash['pr'].length == 2) {
					var currencySign = $('#currencySign').val();
					var usdrate = parseFloat($('#usdrate').val());
					var minPrice = Math.round(hash['pr'][0] * usdrate);
					var maxPrice = Math.round(hash['pr'][1] * usdrate);
					try {
					$('#price_slider').slider('values', 0, minPrice);
					$('#price_slider').slider('values', 1, maxPrice);
					}catch(e){}
					SearchPage.priceSliderView({'currencySign':currencySign,'minPrice':minPrice,'maxPrice':maxPrice});
				}
				
				if (hash['o'] && hash['o'].length == 2) {
					SearchPage.sortingType = hash['o'][0];
					SearchPage.direction = hash['o'][1] ? true : false;
				}
				
				if (hash['p']) {
					SearchPage.changePage = hash['p'][0];
				}
			}
			SearchPage.filterClick(true, 1);
		} else {
			InnstantTracker.addEvent({act: 'clear filters'});
			var currencySign = $('#currencySign').val();
			var minPrice = $('#price_slider').slider('option', 'min');
			var maxPrice = $('#price_slider').slider('option', 'max');
			try {
			$('#price_slider').slider('values', 0, minPrice);
			$('#price_slider').slider('values', 1, maxPrice);
			}catch(e){}
			$("#search_form_advance select :first").attr("selected", "selected");
			SearchPage.priceSliderView({'currencySign':currencySign,'minPrice':Math.round(parseFloat(minPrice)),'maxPrice':Math.round(parseFloat(maxPrice))});
			var hotel_name = $('#hotel_name').get(0);
			var landmarkAddress = $('#landmarkAddress').get(0);
			var Streetaddress = $('#Streetaddress').get(0);
			$('#hotel_name').val(hotel_name.defaultValues[0]).addClass('default');
			$('#landmarkAddress').val(landmarkAddress.defaultValue).addClass('default');
			$('#Streetaddress').val(Streetaddress.defaultValue).addClass('default');
			$("#search_form_advance input[type='checkbox']").each(function(){this.checked = false;});
			$('#stars_all').attr('checked', 'checked');
			$('#boards_all').attr('checked', 'checked');
			$('#providers_all').attr('checked', 'checked');
			SearchPage.sortingType = 0;
			$('#contLandmarkName').css('visibility', 'hidden');
			SearchPage.filterClick(true, 1);
			JBobj.anchor('#head');
		}
	}
	
,	DiscountBannerClick : function() {
		if (!$('#check_in').val() || !$('#check_out').val()) {
			flashing();
		}
	}
	
,	getMarkerHtml : function(hotel){
		var html = [
	        '<div class="baloon-text">'
	    ,   '<b>' + hotel.name + '</b><br />'
	    ,   hotel.address + '<br />'
	    ,   hotel.price || hotel.stars ? '<center><div class="price-stars">' : ''
	    ,   hotel.price ? '<b class="baloon-price">' + hotel.price + '</b>' : ''
	    ,   hotel.stars ? '<div class="graphic stars baloon-stars number' + hotel.stars + '"></div>' : ''
	    ,   hotel.price || hotel.stars ? '</div></center>' : ''
	    ,   hotel.link ? '<div class="hotel-info">' + hotel.link + '</div>' : ''   
	    ,   '</div>'
	    ].join('');
	    
	    return html;
	}

,	getBreakfastIcon: function(data)
	{
		if (typeof data != 'object') {
			var type = data;
			var size = 'large';
		} else {
			var type = data.type;
			var size = data.size;
		}
		
		switch (type) {
			case 'FB':
				return '<span class="sprite '+size+' full board"></span>';
			case 'HB':
				return '<span class="sprite '+size+' half board"></span>';
			case 'All Inclusive':
			case 'AI':
				return '<span class="sprite '+size+' all board"></span>';
		}
		
		if (type && type != 'RO' && type != '-' && type != 'EP') {
			return '<span class="sprite '+size+' bb board"></span>';
		} else {
			return '';
		}
	}
	
,	isBoard: function(type)
	{
		return type && type != 'RO' && type != '-' && type != 'EP';
	}
	
,	similarHotelsPoll: function(req)
	{
		var html = 
		'<p class="load">' +
			'<span>Loading other available hotels</span>' +
			'<img src="/images/'+(RTL?'loading-hotels-big_rtl.gif':'loading-hotels-small.gif')+'" alt="" />' +
		'</p>';
		$('#similar-hotels').html(html);
		
		$.ajax({
			type: 'POST',
			url: getLink('similar-hotels/poll/'),
			data: req,
			dataType: 'json',
			success: function(data) {
				if (!data['status'] || data['status'] == 'working') {
					var time = 7000;
					setTimeout("JBobj.similarHotelsPoll('" + req +  "')", time);
				} else {
					$('#similar-hotels').html(data['similar-hotels']);
					$('#nearbyhotels').html(data['nearbyhotels']);
				}
			}
		});
	}
	
,	similarHotelsPoll2: function(req)
	{
		$.ajax({
			type: 'POST',
			url: getLink('similar-hotels/poll2/'),
			data: req,
			dataType: 'json',
			success: function(data) {
				if (!data['altsimilarhotels']) {
					var time = 3000;
					setTimeout("JBobj.similarHotelsPoll2('" + req +  "')", time);
				} else {
					$('#altsimilarhotels').html(data['altsimilarhotels']);
					JBobj.similarHotelsPoll(req);
				}
			}
		});
	}
	
,	getDistanceView: function(distance)
	{
		distance = parseFloat(distance);
		if (distance < 1) {
			return Math.round(distance * 100) + '0 m';
		} else {
			return distance.toFixed(1) + ' km';
		}
	}
	
,	additionalRooms: function(data)
	{
		var trs = $('#rooms_table_hotel_' + data.hotelId + ' tbody tr');
		var trsCnt = trs.length;
		var i = 0;
		for (; i < trsCnt; i++) {
			if (i <= data.displayedCnt || i == trsCnt - 1)
				continue;
				
			if (data.flag) {
				$(trs[i]).hide();
			} else {
				$(trs[i]).show();
			}
		}
		$('#finalPrice' + data.hotelId).attr('rowspan', data.flag ? data.displayedCnt : trsCnt);
		if (data.flag) {
			$(data.self).html('<span class="sign">[+]</span> Show all other room types');
			$('#additionalmsg' + data.hotelId).show();
			data.flag = false;
		} else {
			$(data.self).html('<span class="sign">[-]</span> See less room types');
			$('#additionalmsg' + data.hotelId).hide();
			data.flag = true;
		}
		data.self.onclick = function(){JBobj.additionalRooms(data);};
	}
,	additionalPackages: function(data)
	{
		var trs = $('#Hotel_package_item_'+data.hotelId+' .hotel_packages');
		var trsCnt = trs.length;

		var i = 0;
		for (; i < trsCnt; i++) {
			if (i <= 0 || i == trsCnt)
				continue;
				
			if (data.flag) {
				$(trs[i]).hide();
			} else {
				$(trs[i]).show();
			}
		}

		if (data.flag) {
			$(data.self).html('<span class="sign">[+]</span> Show more combinations');
			$('#additionalmsg2' + data.hotelId).show();
			data.flag = false;
		} else {
			$(data.self).html('<span class="sign">[-]</span> Show less combinations');
			$('#additionalmsg2' + data.hotelId).hide();
			data.flag = true;
		}
		data.self.onclick = function(){JBobj.additionalPackages(data);};
	}
,	hotelClickEvent: function(hotel)
	{
		InnstantTracker.addEvent({act: 'hotel name clicked', val: hotel['name']+'|'+hotel['price'], syn: true});
	}
	
,	changingImg: {
		parent: $('#changingImage').get(0),
		images: [],
		call: false,
		
		leafOver: function(inx) {
			var images = $('img', this.parent);
			var cnt = images.length;
			
			if (cnt > 1) {
				var lastInx = cnt - 1;
				var isLastInx = inx >= lastInx;
				var newInx = isLastInx ? 0 : inx + 1;
				var image = images[isLastInx ? lastInx : inx];
				
				if (isLastInx) {
					var oldzIndex = image.style.zIndex;
					image.style.zIndex = this.images.length + 1;
					$(images).show();
				}
				
				var _this = this;
				
				$(image).fadeOut(1500, function(){
					if (JBobj.changingImg.call) {
						var tmp = images[newInx].src.split('/');
						tmp = tmp[tmp.length-1].split('.')[0];
						eval(JBobj.changingImg.call+'('+tmp+');');
					}
					if (isLastInx) {
						$(image).css('zIndex', oldzIndex).show();
					}
					setTimeout("JBobj.changingImg.leafOver("+newInx+");", 3000);
				});
			}
		},
		
		loader: function() {
			var parent = this.parent;
			var uploads = $('img', parent);
			var uploadsCnt = uploads.length;
			var images = this.images;
			
			if (uploadsCnt < images.length) {
				var image = new Image();
				image.src = images[uploadsCnt]['Src'];
				image.style.zIndex = images.length - uploadsCnt;
				this.image = image;
				setTimeout("JBobj.changingImg.append(); JBobj.changingImg.loader();", 1000);
			}
		},
		
		append: function() {
			this.parent.appendChild(this.image);
		},
		
		run: function() {
			setTimeout("JBobj.changingImg.leafOver(0);", 3000);
			this.loader();
		}
	}
};

function liFormat(row, i, num, li) {
	var res = '';
    var block = '';
	var sep = false;
	if (JBobj.searchLastType != row[1]) {
		JBobj.searchLastType = row[1];
		var text = '';
        block += '&nbsp;';
		switch (row[1]) {
			case "city": text = 'Cities/Areas'; break;
			case "hotel": text = 'Hotels'; break;
			case "lm": text = 'Landmarks'; break;
			case "country": text = 'Country'; break;
		}
		block += '<span class="category '+row[1]+'"><strong>'+text+'</strong></span>';
		if (i != 1) {
			//$(li).addClass('separator');
			sep = true;
		}
	}
	if (i == num) {
		JBobj.searchLastType = '';
	}
	res += row[0];
	return {res:res,sep:sep,block:block};
}

function selectItem(extra) {
	JBobj.searchExtra = extra;
	var field = $('#search_location');
	if (field.get(0)) {
		field.get(0).notClear = true;
	}
	switch (extra[0]) {
		case 'city':
			$('#cityId').val(extra[1]);
			if (JBobj.searchDialog) {
				$('#dialog_search_location').focus();
			} else {
				field.focus();
			}
			break;
		default:
			//JBobj.searchExtra = extra;
			break;
	}
}

function stripTags(self) {
	var string=self.toString();
	return string.replace(new RegExp('<\/?()[^>]*>','gi'),'');
}

function setCookie(name, value, expires, path, domain, secure) {
	document.cookie = name + "=" + escape(value) +
	((expires) ? "; expires=" + expires : "")    +
	((path)    ? "; path=" + path : "")          +
	((domain)  ? "; domain=" + domain : "")      +
	((secure)  ? "; secure" : "");
}

/**
 * Вычисление среднего значения ряда чисел
 * 
 * @param data - массив чисел
 * @param c - количество цифр после запятой
 * @return average - среднее число
 */
function Average(data, c)
{
	var sum = 0;
	var number = data.length;
	
	for (var i = 0; i < number; i++)
	{
		sum += parseFloat(data[i]);
	}
	
	var average = (sum / number).toFixed(c);
	
	return average;
}

function inputFocus() {
	var defVal = this.defaultValue ? [this.defaultValue] : (this.defaultValues ? this.defaultValues : []);
	if (!empty(defVal)) {
		var val = $.trim($(this).val());
		if (in_array(val, defVal)) {
			$(this).removeClass('default').val('');
		}
	}
}

function inputBlur() {
	var defVal = this.defaultValue ? this.defaultValue : (this.defaultValues ? this.defaultValues[this.defaultValuesInx] : '');
	if (!$.trim(this.value)) {
		$(this).addClass('default').val(defVal);
	}
}

function in_array(needle, haystack)
{
	for (var key in haystack) {
		if (needle === haystack[key]) {
			return true;
		}
	}
	
	return false;
}

function getDistance(point1, point2)
{
	return Math.acos(
		Math.sin(Math.PI * point1.lat / 180) * Math.sin(Math.PI * point2.lat / 180) + 
		Math.cos(Math.PI * point1.lat / 180) * Math.cos(Math.PI * point2.lat / 180) * 
		Math.cos(Math.PI *(point2.lng - point1.lng) / 180)
	) * 6378.137;
}

(function($){$.fn.expectation = function(remove){
	if (!remove) {
		$(this).each(function(){
				$('<div class="expectation" style="position: absolute; z-index: 999; width: '+this.clientWidth+'px; height: '+this.clientHeight+'px; left: 0px; top: 0px;"></div>').appendTo(this);
		});
	} else {
		var obj = this;
		$('.expectation', this).each(function(){
			$(obj).get(0).removeChild(this);
		});
	}
	return this;
};}(jQuery));

function addslashes(str) {
	return str.replace(/([\"\'])/g, "\\$1");
}

function print_r(vare, ret) {
	var getr = function(vare, level) {
		var br = "\n";
		var tab = "\t";
		var i = 0;
		var level = level || 0;
		var ptab = '';
		var ctab = '';
		
		for (; i < level; i++) {
			ptab = ctab += tab;
		}
		
		ctab += tab;
		
		var res = typeof vare + br + ptab + '(' + br;
		
		for (i in vare) {
			res +=
			ctab + '[' + i + '] => ' +
			(typeof vare[i] === 'object' ? getr(vare[i], level + 1) : vare[i] + br);
		}
		
		res += ptab + ')' + br;
		return res;
	}
	
	var res = getr(vare);
	
	if (ret) {
		return res;
	} else {
		document.write(res);
	}
}

function setCheckOutMaxDate(checkIn, checkOut, RANGE_DAYS) {
	//var checkIn = checkIn.charAt(0) == '#' ? checkIn : '#' + checkIn;
	//var checkOut = checkOut.charAt(0) == '#' ? checkOut : '#' + checkOut;
	var d = $(checkIn).datepicker('getDate');
	if (d) {
		var maxDate = new Date(d.getFullYear(), d.getMonth(), d.getDate()+RANGE_DAYS);
		if (maxDate < $(checkOut).datepicker('getDate')) {
			$(checkOut).datepicker('setDate', maxDate); 
		}
		$(checkOut).datepicker('option', 'maxDate', maxDate);
	}
}

function isset(variable)
{
	return eval('typeof ' + variable + ' !== "undefined"');
}

function getFlashMovie(movieName) {   var isIE = navigator.appName.indexOf("Microsoft") != -1;   return (isIE) ? window[movieName] : document[movieName];  }

var absInb2 = {
	init: function(input) {
		this.input = input;
		this.views =  {
			'1': ['for the best deal', 'fill in the dates', 'of your stay']
		,	'2': ['getting', 'the best deal', 'for you!']
		,	'3': ['comparing prices', 'on other websites:', ['booking.com', 'hotels.com', 'easytobook.com']]
		,	'4': ['book now pay later', 'secure payments', 'free cancellations']
		,	'6': ['select a room', 'from the list below', 'and click book now']
		,	'7': [input.brand, 'vs other sites', 'click to compare']
		};
	},
	
	collection:[],
	addCollection: function(obj) {
		this.collection.push(obj);
		return this.collection.length - 1;
	}
};
var Inb2 = function(id) {
	this.inx = this.addCollection(this);
	this.id = 'in_board2'+(id || '');
	this.setView = function(viewId) {
		try {
			var id = this.id;
			$('#'+id).css('z-index', 3);
			var banner = getFlashMovie(id);
			if (banner) {
				if (this.viewId != viewId) {
					if (banner.updateline) {
						this.viewId = viewId;
						var view = this.views[viewId];
						var line = 1;
						
						for (var i in view) {
							var data = view[i];
							
							if (typeof data == 'string') {
								banner.updateline(line + '|' + data);
							} else {
								this.multiupdateline(line, viewId, 0);
							}
							
							++line;
						}
					} else {
						setTimeout("absInb2.collection["+this.inx+"].setView(\'"+viewId+"\');", 500);
					}
				}
			}
		} catch(e) {
			if("undefined" != typeof console) {
	            console.log(e.message);
	         }	
		}
	};
	
	this.multiupdateline = function(line, viewId, i) {
		try {
			if (this.viewId == viewId) {
				var id = this.id;
				var data = this.views[viewId][line-1];
				i = i >= data.length ? 0 : i;
				getFlashMovie(id).updateline(line + '|' + data[i]);
				setTimeout("absInb2.collection["+this.inx+"].multiupdateline("+line+", "+viewId+", "+(++i)+");", 6000);
			}
		} catch(e) {
			if("undefined" != typeof console) {
	            console.log(e.message);
	         }	
		}
	}
};
Inb2.prototype = absInb2;


var flbooknow = {
	imyfun: function(p, c) {
		var top = getTop(p, c);
		if (top !== false) {
			if (top < 65) {
				top = 65;
			}
			$(c).css('top', top + 'px');
		}
	},
	init: function(p, c) {
		flbooknow.imyfun(p, c);
		$(window).scroll(function(){
			flbooknow.imyfun(p, c);
		});
	}
}
function getTop(p, c) {
	var top = false;
	
	if ($(p).get(0) && $(c).get(0)) {
		var p = {
			't': $(p).offset().top
		,	'b': $(p).offset().top + $(p).get(0).clientHeight
		,	'h': $(p).get(0).clientHeight};
		var w = {
			't': $(document).scrollTop()
		,	'b': $(document).scrollTop() + document.documentElement.clientHeight};
		var c = {
			'h': $(c).get(0).clientHeight};
		var o = {};
		
		//alert($(document).scrollTop());
		//alert(print_r(w,1));
			
		if (p.t > w.t) {// сверху
			if (p.t < w.b) {// видно
				if (p.b > w.b) {
					//console.log("сверху видно");
					o.t = p.t;
					o.b = w.b;
				} else {
					//console.log("видно");
					o = p;
				}
			} else {
				//console.log("сверху не видно");
				o = false;
			}
		} else if (w.b < p.b) {//середина
			//console.log("середина");
			o = w;
		} else {// низ
			if (p.b > w.t) {
				//console.log("снизу видно");
				o.t = w.t;
				o.b = p.b;
			} else {
				//console.log("снизу не видно");
				o = false;
			}
		}
		
		if (o) {
			o.h = o.b - o.t;
			var z = o.t - p.t;
			var top = (o.h - c.h) / 2;
			top = top > 0 ? top + z : z;
			if (top + c.h > p.h) {
				top = p.h - c.h;
			}
		}
	}
	
	return top;
}

function clone(o) {
 if(!o || 'object' !== typeof o)  {
   return o;
 }
 var c = 'function' === typeof o.pop ? [] : {};
 var p, v;
 for(p in o) {
 if(o.hasOwnProperty(p)) {
  v = o[p];
  if(v && 'object' === typeof v) {
    c[p] = clone(v);
  }
  else {
    c[p] = v;
  }
 }
}
 return c;
}

function getLink(link) {
	link = link || '';
	return HTTP_HOST + link;
}

(function($){$.fn.ccselect=function(inp){
	var selector = this.selector;
	var sum = $('#sum').html();
	var sum2 = $('#sum_eur').html();
	$(this).change(function(){
		var change = false;
		if (inp[this.value]) {
			var data = inp[this.value];
			if (parseInt(data['diff']) > 0) {
				change = true;
				var part = 'Using # will entail an increase in price of'.replace('#',$.trim(this.options[this.selectedIndex].innerHTML));
								var text = 
				part+' <b>'+data['percent']+'%</b> (<b>'+data['diff']+' '+data['currencyTitle']+'</b>).<br /><br />' +
				'In order to be able to offer you the lowest prices available, we keep our margins to a minimum. Therefore, to help maintain our low price margin, some credit card types require higher transaction fees.<br /><br />' +
				'Click the &quot;accept&quot; button to update the price, or click the &quot;cancel&quot; button to choose another credit card type.<br /><br />' +
				'MasterCard and Visa entail no increase in price.' +
				'<div class="btn">\
					<div onclick="$(\'#sum\').html(\''+sum+'\'); $(\'#sum_eur\').html(\''+sum2+'\');$(\''+selector+'\').get(0).options[0].selected = true; $.facebox.close();" class="button n4" style="margin: 0px 2px;">\
						<div class="sprite b5 lt"></div>\
						<div class="elastic-x b5 cr">Cancel</div>\
						<div class="sprite b5 rt"></div>\
					</div>\
					<div onclick="$(\'#sum\').html(\''+data['amount']+' '+data['currencyTitle']+'\'); $(\'#sum_eur\').html(\'('+data['amountSel']+' '+inp['currencyTitleSel']+')\'); $.facebox.close();" class="button n4" style="margin: 0px 2px;">\
						<div class="sprite b5 lt"></div>\
						<div class="elastic-x b5 cr">Accept</div>\
						<div class="sprite b5 rt"></div>\
					</div>\
				</div>';
				$.facebox(text, 'ccinfo');
			}
		}
		if (!change) {
			$('#sum').html(sum);
			$('#sum_eur').html(sum2);
		}
	});
};}(jQuery));

var Dates = {
	get: function(location) {
		var name = "dates" + (location ? "[" + location + "]" : "");
		return {
			'checkInDate': $("input[name='" + name + "[checkInDate]']").val()
		,	'checkOutDate': $("input[name='" + name + "[checkOutDate]']").val()
		,	'alt': {
				'checkInDate': $("input[name='" + name + "[alt][checkInDate]']").val()
			,	'checkOutDate': $("input[name='" + name + "[alt][checkOutDate]']").val()
			}
		};
	},
	selectors: function(location) {
		var name = "dates" + (location ? "[" + location + "]" : "");
		return {
			'checkInDate': "input[name='" + name + "[checkInDate]']"
		,	'checkOutDate': "input[name='" + name + "[checkOutDate]']"
		,	'alt': {
				'checkInDate': "input[name='" + name + "[alt][checkInDate]']"
			,	'checkOutDate': "input[name='" + name + "[alt][checkOutDate]']"
			}
		};
	},
	onSelect: function(location, type) {
		var selectors = this.selectors(location);
		if (type == 1) {
			setCheckOutMaxDate(selectors['checkInDate'],selectors['checkOutDate'],21);
			if ($(selectors['checkInDate']).datepicker('getDate') >= $(selectors['checkOutDate']).datepicker('getDate')) {
				var newDate = $(selectors['checkInDate']).datepicker('getDate');
				$(selectors['checkOutDate']).datepicker('setDate',new Date(newDate.getFullYear(), newDate.getMonth(), newDate.getDate() + 1)); 
			}
		} else if (type == 2) {
			if ($(selectors['checkInDate']).datepicker('getDate') >= $(selectors['checkOutDate']).datepicker('getDate')) {
				var newDate = $(selectors['checkOutDate']).datepicker('getDate');
				$(selectors['checkInDate']).datepicker('setDate',new Date(newDate.getFullYear(), newDate.getMonth(), newDate.getDate() - 1)); 
			}
			setCheckOutMaxDate(selectors['checkInDate'],selectors['checkOutDate'],21);
		}
	}
};

function empty(mixed_var) {
    var key;    
    if (mixed_var === "" ||
        mixed_var === 0 ||
        mixed_var === "0" ||
        mixed_var === null ||        mixed_var === false ||
        typeof mixed_var === 'undefined'
    ){
        return true;
    } 
    if (typeof mixed_var == 'object') {
        for (key in mixed_var) {
            return false;
        }
        return true;
    }
 
    return false;
}


var Tooltip = {
	add: function(inp) {
		var cont = this.get(inp);
		$(inp['selector']).hover(
			function(){
				cont.stop().animate({deception:1}, 500, function(){cont.appendTo(inp['selector']);});
			}
		,	function(){
				
				cont.stop().animate({deception:1}, 700, function(){cont.remove();});
			}
		);
	},
	get: function(inp) {
		var style = "";
		for (var i in inp.coords) {
			style += i+':'+inp.coords[i]+'px;';
		}
		var cont = typeof inp.content == 'object' ? $(inp.content[0]).html() : inp.content;
		var html = 
		'<div class="tooltip" style="'+style+'">'+
			'<table class="border">'+
				'<tr>'+
					'<td class="graph1 top-left"><div class="size1"></div></td>'+
					'<td class="graph1 top-center"></td>'+
					'<td class="graph1 top-right"><div class="size1"></div></td>'+
				'</tr>'+
				'<tr>'+
					'<td class="graph2 center-left"></td>'+
					'<td class="center-center">'+
					
						cont+
					
					'</td>'+
					'<td class="graph2 center-right"></td>'+
				'</tr>'+
				'<tr>'+
					'<td class="graph1 bottom-left"></td>'+
					'<td class="graph1 bottom-center"></td>'+
					'<td class="graph1 bottom-right"></td>'+
				'</tr>'+
			'</table>'+
		'</div>';
		return $(html);
	}
};

(function($){$.fn.isClass=function(cls){
	return in_array(cls, $(this).get(0).className.split(' '));
};}(jQuery));

(function($){$.fn.changeClass=function(cls1, cls2){
	$(this).get(0).className = $(this).get(0).className.replace(cls1, cls2);
};}(jQuery));

(function($){$.fn.replaceClass=function(cls1, cls2){
	if ($(this).isClass(cls1)) {
		$(this).changeClass(cls1, cls2);
		return true;
	} else {
		$(this).changeClass(cls2, cls1);
		return false;
	}
};}(jQuery));

var NestedItems = {
	init: function(data) {
		$(data.item).click(function(){
			if ($(this).isClass('open')) {
				$(this).removeClass('open');
				$(data.nestedItems, $(this).parent()).animate({'height':'hide'}, 300);
			} else {
				$(this).addClass('open');
				$(data.nestedItems, $(this).parent()).animate({'height':'show'}, 300);
			}
		});
	}
};

//$('input').keypresstest(new RegExp('a')); все кроме а
//$('input').keypresstest(new RegExp('a'), true); только а
(function($){$.fn.keypresstest=function(reg, flag){
	$(this).keypress(function(e){
		try {
			if (in_array(e.keyCode, [
				8//стереть
			,	37//лево
			,	38//верх
			,	39//право
			,	40//низ
			,	9//tab
			,	46//del
			])) {
				return true;
			}
			var ch = String.fromCharCode($.browser.msie || $.browser.opera ? e.keyCode : e.charCode);
			var res = reg.test(ch);
			return flag ? res : !res;
		} catch (err) {
			if ("undefined" != typeof console) {
				console.log(err.message);
			}
			return true;
		}
	});
};}(jQuery));

function flybox(page,center_on,title)
{
	center_on = typeof(center_on) != 'undefined' ? center_on : true;
	title = typeof(title) != 'undefined' ? title : '';
	
	$.fancybox(
		{
		'speedIn'		:	600, 
		'speedOut'		:	200,
		'width'			: 500,
		'titlePosition': 'inside',
		'centerOnScroll': center_on,
		'title': title,
		'href': page
		}
	);
}
var authDialogs = {
	authorization: function(noRedirect) {
		var noRedirect = noRedirect ? 1 : 0;
		var html =
		'<div id="authorization" class="auth-dialog">'+
			'<fieldset>'+
				'<label for="auth_email">E-mail</label>'+
				'<input class="ui-corner-all" type="text" name="email" id="auth_email" value="" onkeypress="if (event.keyCode == 13) JBobj.checkLogin('+noRedirect+');" />'+
			'</fieldset>'+
			'<fieldset>'+
				'<label for="auth_pass">Password</label>'+
				'<input class="ui-corner-all" type="password" name="pass" id="auth_pass" value="" onkeypress="if (event.keyCode == 13) JBobj.checkLogin('+noRedirect+');" />'+
				'<div id="error_login"></div>'+
				'<a class="forgotPassword" href="javascript:void(0);" onclick="authDialogs.passwordrecovery('+noRedirect+');">'+
					'I forgot my password'+
				'</a>'+
			'</fieldset>'+
			'<div class="container-button-dialog strok">';
			
				if (!noRedirect) {
					html +=
					'<div class="button n4" onclick="authDialogs.close();">'+
						'<div class="sprite b5 lt"></div>'+
						'<div class="elastic-x b5 cr">Close</div>'+
						'<div class="sprite b5 rt"></div>'+
					'</div>';
				}
				
			html +=
				'<div class="button n4" onclick="JBobj.checkLogin('+noRedirect+');">'+
					'<div class="sprite b5 lt"></div>'+
					'<div class="elastic-x b5 cr">Sign In</div>'+
					'<div class="sprite b5 rt"></div>'+
				'</div>'+
			'</div>'+
		'</div>';
		$.facebox(html);
	},
	
	passwordrecovery: function(noRedirect) {
		var noRedirect = noRedirect ? 1 : 0;
		var html =
		'<div id="passwordrecovery" class="auth-dialog">'+
			'<p class="passwordRecoveryInfo">Please provide your email address associated with your account</p>'+
			'<fieldset>'+
				'<label for="emailRecovery">E-mail</label>'+
				'<input class="ui-corner-all" type="text" name="emailRecovery" id="emailRecovery" value="" onkeypress="if (event.keyCode == 13) JBobj.passwordRecovery(\'An email has been sent to your email account\',\'Email incorrect\');" />'+
			'</fieldset>'+
			'<p id="passwordRecoveryMessage" class="passwordRecoveryMessage"></p>'+
			'<div class="container-button-dialog strok">';
							
				if (!noRedirect) {
					html +=
					'<div class="button n4" onclick="authDialogs.close();">'+
						'<div class="sprite b5 lt"></div>'+
						'<div class="elastic-x b5 cr">Close</div>'+
						'<div class="sprite b5 rt"></div>'+
					'</div>';
				}
				
			html +=
				'<div class="button n4" id="passwordRecoverySend" onclick="JBobj.passwordRecovery(\'An email has been sent to your email account\',\'Email incorrect\');">'+
					'<div class="sprite b5 lt"></div>'+
					'<div class="elastic-x b5 cr">Send</div>'+
					'<div class="sprite b5 rt"></div>'+
				'</div>'+
			'</div>'+
		'</div>';
		$.facebox(html);
	},
	
	close: function() {
		$.facebox.close();
	}
};

var cancelDialog = {
	skeleton: function(html) {
		
		//$.facebox.position();
		$(document).bind('beforeReveal.facebox', function() {
			var height = $(window).height() - 100;
			$('#facebox .cancel-dialog').css('overflow', 'auto').css('height', height + 'px');
			$('#facebox').css('top', ($(window).scrollTop() + 10) + 'px');
		});
		$.facebox('<h3 class="mytitle">Booking Cancellation</h3>'+html, 'cancel-dialog');
	},
	
	loading: function() {
		this.skeleton('<div class="loading5"></div>');
	},
	
	open: function(bookingId) {
		this.loading();
		$.post(getLink("booking/cancelmessage/"+bookingId+"/"),{},function (data){
			cancelDialog.skeleton('<div class="mycont">'+data+'</div>');
		});
	},
	
	cancel: function(bookingId) {
		if ($('#i-agree').attr('checked')) {
			this.loading();
	    	$.ajax({
	    		type: 'POST'
	    	,	url: getLink("booking/cancel/"+bookingId)
	    	,	data: ''
			,	dataType: 'json'
	    	,	success:function(data) {
	    			if (data.status == 1) {
	    				window.location = getLink("booking/");
	    			} else {
	    				cancelDialog.skeleton('<p class=\'errmsg\'>'+data.message+'</p>'+cancelDialog.getClose());
	    			}
	    		}
	    	,	error:function() {
	    			cancelDialog.skeleton('<p class=\'errmsg\'>error</p>'+cancelDialog.getClose());
	    		}
	    	});
		}
	},
	
	getClose: function() {
		var close = '<div class="button n4" onclick="cancelDialog.close();">'+
			'<div class="sprite b5 lt"></div>'+
			'<div class="elastic-x b5 cr">Close</div>'+
			'<div class="sprite b5 rt"></div>'+
		'</div>';
		return close;
	},
	
	close: function() {
		$.facebox.close();
	},
	
	yes: function() {
		$('#cancel-info').hide();
		$('#i-agree-cont').show();
	},
	
	init: function() {
		$("#i-agree").click(function(){
			if ($(this).attr("checked")) {
				$("#cancel-button").removeClass("disabled");
			} else {
				$("#cancel-button").addClass("disabled");
			}
		});
	}
};

var authDialogsAether = {
	authorization: function() {
		var html =
		'<div id="authorization" class="auth-dialog">'+
			'<fieldset>'+
				'<label for="auth_email">Agency ID</label>'+
				'<input class="ui-corner-all" type="text" name="account" id="account" value="" onkeypress="if (event.keyCode == 13) JBobj.checkLoginAether();" />'+
			'</fieldset>'+
			'<fieldset>'+
				'<label for="auth_pass">User name</label>'+
				'<input class="ui-corner-all" type="text" name="auth_login" id="auth_login" value="" onkeypress="if (event.keyCode == 13) JBobj.checkLoginAether();" />'+
			'</fieldset>'+
			'<fieldset>'+
				'<label for="auth_pass">Password</label>'+
				'<input class="ui-corner-all" type="password" name="auth_password" id="auth_password" value="" onkeypress="if (event.keyCode == 13) JBobj.checkLoginAether();" />'+
				'<div id="error_login"></div>'+
			'</fieldset>'+
			'<div class="container-button-dialog strok">'+
				'<div class="button n4" onclick="JBobj.checkLoginAether();">'+
					'<div class="sprite b5 lt"></div>'+
					'<div class="elastic-x b5 cr">Sign In</div>'+
					'<div class="sprite b5 rt"></div>'+
				'</div>'+
			'</div>'+
		'</div>';
		$.facebox(html);
	},
	
	close: function() {
		$.facebox.close();
	}
};var PriceComparison =
{
	isLoad: false,
	modul: 1,
	
	view: {
		prices: {},
		site:'',
		roomName:''
	},
	
	others: {},
	
	request: {
		url: 'http://www.innstant.com/compare/api.php',
		params: {
			mid:'',
			currency:'',
			userid:'',
			useragent:'',
			userip:'',
			
			action:'HotelSearch',
			callback:'?',
			format:'jsonp'
		},
		
		get: function() {
			var request = this.url;
			var i = 0;
			
			for (var key in this.params) {
				request += (i ? '&' : '?') + key + '=' + this.params[key];
				i = 1;
			}
			
			return request;
		},
		
		set: function(params, page) {
			if (!params) {params = {};}
			if (!page) {page = 'hotel';}
			var id = {};
			switch (page) {
				case 'hotel':
					var dates = Dates.selectors('checkAvailability'); 
					id = {
						'checkIn':dates['alt']['checkInDate'],
						'checkOut':dates['alt']['checkOutDate']
					};
					break;
					
				case 'search':
					var dates = Dates.selectors(); 
					id = {
						'checkIn':dates['alt']['checkInDate'],
						'checkOut':dates['alt']['checkOutDate']
					};
					break;
			}
			
			var firstRoomData = JBobj.getFirstRoomData();
			
			params['guests'] = firstRoomData.numAdults + firstRoomData.numChildren;
			params['rooms'] = 1;
			params['checkin'] = this.getDate(id['checkIn']);
			params['checkout'] = this.getDate(id['checkOut']);
			this.params = $.extend(this.params, params);
			return this;
		},
		
		getDate: function(fieldId) {
			var date = $(fieldId).val();
			if (date) {
				return date;
			}
		}
	},
	
	pcBlock: {
		rows: '',
		rowsCnt:0,
		
		get: function(ids) {
			if (ids) return new Array('#pcBlock','#pcBlock2');
			return $("#pcBlock").get(0);
		},
		
		addRow: function(site) {
			if (this.rowsCnt < 4) {
				var cur = PriceComparison.view['currencySign'];
				var click = PriceComparison.getClickEvent(site);
				this.rows +=
				'<tr class="'+(this.rowsCnt % 2 ? '' : 'not-')+'even">' +
					'<td class="image">'+
						'<a href="'+site['clickurl']+'" target="_blank"'+click+'><span class="site"><img src="/images/providers/'+site['providercode']+'-big.gif" alt="'+site['provider']+'" /></span></a>'+
					'</td>'+
					'<td class="price">'+
						'<a href="'+site['clickurl']+'" target="_blank"'+click+'><span class="price">'+cur+''+site['totalprice']+'</span></a>'+
					'</td>'+
					'<td class="but">'+
						'<a class="button5" href="'+site['clickurl']+'" target="_blank"'+click+'><span class="r"><span class="c">go to site</span></span></a>'+
					'</td>'+
				'</tr>';
				
				++this.rowsCnt;
			}
		},
		
		getHtml: function() {
			var cur = PriceComparison.view['currencySign'];
			var mid = PriceComparison.request.params['mid'];
			var params = PriceComparison.view;
			var click = 'onclick="JBobj.anchor(\'#rooms_table_hotel_'+mid+'\');"';
			var html = '';
			html +=
			'<table class="other-sites">';
				if (params.prices[mid]) {
					html +=
					'<tr class="even">' +
						'<td class="image" style="border-bottom: 1px solid #296C84;">'+
							'<a class="ourprice" '+click+'><span class="site"><img src="/images/providers/'+params["site"]+'.png" alt="Our price" /></span></a>'+
						'</td>'+
						'<td class="price" style="border-bottom: 1px solid #296C84;">'+
							'<a class="ourprice" '+click+'><span class="price">'+cur+'<span class="our-price">'+params.prices[mid]+'</span></span></a>'+
						'</td>'+
						'<td class="but" style="border-bottom: 1px solid #296C84;">'+
							'<a class="button9 black" onclick="JBobj.checkBookingRoomPage('+mid+', Dates.get(\'checkAvailability\')[\'alt\'][\'checkInDate\'], Dates.get(\'checkAvailability\')[\'alt\'][\'checkOutDate\'], \'Book Now\')"><span class="r"><span class="c">book now</span></span></a>'+
						'</td>'+
					'</tr>';
				}
				html +=
				this.rows +
			'</table>';
			return html;
		}
	},
	
	pcTab: {
		rows: '',
		
		get: function() {
			return $("#pcTab").get(0);
		},
		
		addRow: function(site, num) {
			var cur = PriceComparison.view['currencySign'];
			var click = PriceComparison.getClickEvent(site);
			var icon = JBobj.getPersonsIcon(PriceComparison.others);
			this.rows +=
			'<tr class="'+(num % 2 ? '' : 'not-')+'even">'+
				'<td class="image">'+
					'<a href="'+site['clickurl']+'" target="_blank"'+click+'><img src="/images/providers/'+site['providercode']+'-big.gif" alt="'+site['provider']+'" /></a>'+
				'</td>'+
				'<td class="name">'+
					'<a href="'+site['clickurl']+'" target="_blank"'+click+'>'+site['provider']+'</a>'+
				'</td>'+
				'<td class="room name">'+
					'<a href="'+site['clickurl']+'" target="_blank"'+click+'>'+site['name']+'</a>'+
				'</td>'+
				'<td class="icon">'+
					icon+
				'</td>'+
				'<td class="price">'+
					'<a href="'+site['clickurl']+'" target="_blank"'+click+'>'+cur+' '+site['totalprice']+'</a>'+
				'</td>'+
				'<td class="but">'+
					'<a class="button5" href="'+site['clickurl']+'" target="_blank"'+click+'><span class="r"><span class="c">go to site</span></span></a>'+
				'</td>'+
			'</tr>';
		},
		
		getHtml: function() {
			var params = PriceComparison.view;
			var mid = PriceComparison.request.params['mid'];
			var click = 'onclick="JBobj.anchor(\'#rooms_table_hotel_'+mid+'\');"';
			var icon = JBobj.getPersonsIcon(PriceComparison.others);
			var html = '';
			html +=
			'<table class="compare-price">';
				html +=
				'<tr>'+
					'<td colspan="6" style="padding-bottom: 0px;">'+
						'<h3 class="bltitle">Price Comparison</h3>'+
					'</td>'+
				'</tr>';
				if (params.prices[mid]) {
					var cur = PriceComparison.view['currencySign'];
					var roomName = PriceComparison.view['roomName'];
					html +=
					'<tr class="our">'+
						'<td class="image">'+
							'<a '+click+'><img src="/images/providers/'+params["site"]+'.png" alt="" /></a>'+
						'</td>'+
						'<td class="name">'+
							'<a class="ourprice" '+click+'>Our price</a>'+
						'</td>'+
						'<td class="room name">';
						if (roomName) {
							html +=
							'<a class="ourprice" '+click+'>'+roomName+'</a>';
						}
						html +=
						'</td>'+
						'<td class="icon">'+
							icon+
						'</td>'+
						'<td class="price">'+
							'<a class="ourprice" '+click+'>'+cur+' <span class="our-price">'+params.prices[mid]+'</span></a>'+
						'</td>'+
						'<td class="but">'+
							'<a class="button5" onclick="JBobj.checkBookingRoomPage('+mid+', Dates.get(\'checkAvailability\')[\'alt\'][\'checkInDate\'], Dates.get(\'checkAvailability\')[\'alt\'][\'checkOutDate\'], \'Book Now\')"><span class="r"><span class="c">book now</span></span></a>'+
						'</td>'+
					'</tr>';
				}
				html +=
				this.rows +
			'</table>';
			return html;
		}
	},
	
	hide: function() {
		if (isset('inban2')) {
			inban2.setView('1');
		}
		var pcBlockConts = this.pcBlock.get(true);
		var pcTabCont = this.pcTab.get();
		for (var i in pcBlockConts) {
			var pcBlockCont = pcBlockConts[i];
			$(pcBlockCont).parent("div").parent("div").show();
			$(pcBlockCont).parent("div").hide();
			$(".pcBanner .load").hide();
			$(".pcBanner").removeClass("loa").show();
			$(".pcBanner .loz").show();
		}
		if (pcTabCont) {
			$(pcTabCont).html('');
		}
		
		if ($('#pcFloat').get(0)) {
			$('#pcFloat').fadeOut(500, function(){$(this).css('top', -180).show();});
		}
		$('#in_board2en').css('visibility', 'visible');
		$('#pcTab2').html('');
	},
	
	load: function() {
		var pcBlockConts = this.pcBlock.get(true);
		for (var i in pcBlockConts) {
			var pcBlockCont = pcBlockConts[i];
			$(pcBlockCont).parent("div").parent("div").show();
			$(pcBlockCont).parent("div").hide();
			$(".pcBanner .loz").hide();
			$(".pcBanner").addClass("loa").show();
			$(".pcBanner .load").show();
		}
		$('#pcTab2').html('');
		$('#load2 .text').html(PriceComparison.others.afterChecking ? '2. Still searching other sites for price comparison' : '2. Also searching other sites for price comparison');
	},
	
	noRooms: function() {
		var pcBlockCont = this.pcBlock.get();
		var pcTabCont = this.pcTab.get();
		
		if (pcBlockCont) {
			$(pcBlockCont).parent("div").parent("div").hide();
		}
		if (pcTabCont) {
			$(pcTabCont).html("<p class='nosite'>click to get price comparison: <a href='http://click.innstant.com/' target='_blank'>http://click.innstant.com/</a></p>");
		}
	},
	
	getClickEvent: function(site,mid) {
		if (!mid) {
			mid = this.request.params['mid'];
		}
		var cur = this.request.params['currency'];
		var price = this.view.prices[mid];
		return ' onclick="InnstantTracker.addEvent({act: \'hotelscombined link clicked\', val: \''+site['provider']+' ('+cur+' '+site['totalprice']+'), our price ('+cur+' '+price+')\', syn: true});"';
	},
	
	isMinOurPrice: function(input, fl) {
		var
			input = $.extend({'hotelId':0, 'sites': []}, input)
		,	min = true
		,	ourPrice = this.view.prices[input['hotelId']]
		,	key = ''
		,	site = {};
		
		for (key in input['sites']) {
			if (min && input['sites'][key]['totalprice'] < ourPrice) {
				min = false;
				break;
			}
		}
		
		if (!fl) {
			$('#FoundLP'+input['hotelId']).css('display', min ? 'block' : 'none');
		}
		
		return min;
	},
	
	run: function(input) {
		if (!this.modul) {
			$("#cha_loading").animate({height: 'hide'}, 200);
			return;
		}
		var pcBlock = this.pcBlock;
		var pcTab = this.pcTab;
		var pcBlockCont = pcBlock.get();
		var pcTabCont = pcTab.get();
	
		//if (!pcBlockCont) {return false;}
		
		input = $.extend({"json":{}, "view":{}, "others":{}}, input);
		this.request.set(input["url"]);
		this.view = $.extend(this.view, input["view"]);
		this.others = $.extend(this.others, input["others"]);

		if (!this.request.params['checkin'] || !this.request.params['checkout']) {
			this.hide();
			if (pcTabCont) {
								$(pcTabCont).html("<p class='nosite'>In order to get rates please fill your reservation&#039;s information details in the “Check availability” box above.</p>");
			}
			return false;
		}
			
		pcTab.rows = '';
		pcBlock.rows = '';
		pcBlock.rowsCnt = 0;
		
		var mid = this.request.params["mid"];

		var isRoomBlock = $("#roomsCont"+mid).get(0) ? true : false;
		
		if (!isRoomBlock && input.others["afterChecking"]) {
			this.noRooms();
		}
			
		if (isRoomBlock) {
			this.load();
			if (isset('inban2')) {
				inban2.setView('3');
			}
		}

		data = input["json"];

	//	$.getJSON(this.request.get(), function(data) {
			$("#cha_loading").animate({height: 'hide'}, 200);
			if (data && data.length) {
		
				InnstantTracker.addEvent({act: "holescombined banner loaded"});
				
				if (isRoomBlock) {
					$(pcBlockCont).parent("div").parent("div").show();
				}
				
				for (var key in data) {
	    			var site = data[key];
	    			site['totalprice'] = Math.round(site['totalprice']);
	    			
	    			if (isRoomBlock) {
	    				pcBlock.addRow(site);
	    			}
	    			
	    			if (pcTabCont || PriceComparison.others["viewId"] == 6 || PriceComparison.others["viewId"] == 7 || PriceComparison.others["viewId"] == 8) {
	    				pcTab.addRow(site, key);
	    			}
				}

				if (isRoomBlock) {
						
					var s = 0;
					var html = '';
					var cityData = {};
					cityData[mid] = data;
					PriceComparison.cityData = cityData;
					var crow = PriceComparison.getCityRow({'id': mid});
					if (PriceComparison.others["viewId"] == 4 || PriceComparison.others["viewId"] == 5) {
						html = crow;
						s = 1;
					} else if (PriceComparison.others["viewId"] == 6 || PriceComparison.others["viewId"] == 7 || PriceComparison.others["viewId"] == 8) { 
						html = pcTab.getHtml();
						s = 2;
					}
					var isMinOurPrice = PriceComparison.isMinOurPrice({'hotelId': mid, 'sites': data});
					$('#in_board2en').css('visibility', isMinOurPrice?'hidden':'visible');
					$("#pcBlockHead").html(isMinOurPrice ? 'Our Price Wins - Check For Yourself:' : 'Available On Other Sites:');
					$(".pcBanner").each(function(i){
						$(this).removeClass("loa").fadeOut(300, function(){
							if (i==0) {
								$(pcBlockCont).html(pcBlock.getHtml()).parent("div").fadeOut(400).fadeIn(400);
							} else {
								if (s==2) {
									$('#pcBlock'+(i+1)).html('').parent("div").fadeOut(400).fadeOut(400);
									$('#pcTab2').html(html);
								} else {
									$('#pcBlock'+(i+1)).html(s==1?html:crow).parent("div").fadeOut(400).fadeIn(400);
								}
							}
						});
					});
				
					var pcFloat = $('#pcFloat');

					if (pcFloat.get(0)) {
						$('#pcFloat div').html(pcBlock.getHtml());
						var top = $('#caForm').offset().top;
						setTimeout("$('#pcFloat').animate({top: "+top+"}, 1500);", 1500);
					}
					
					if (isset('inban2')) {
						var nview = '4';
						if (isMinOurPrice) {
							nview = 'wins';
							absInb2.views[nview] = [
								isMinOurPrice ? PriceComparison['view']['site']+' wins:' : 'price comparison:'
							,	'Our price: '+PriceComparison['view']['prices'][mid]+' '+ PriceComparison['request']['params']['currency']
							,	'Competitor: '+Math.round(data[0]['totalprice'])+' '+ PriceComparison['request']['params']['currency']
							];
						}
						inban2.setView(nview);
					}
				} else {

					var cityData = {};
					cityData[mid] = data;
					PriceComparison.cityData = cityData;
					var hotel = {'id': mid};
					var cityRow = PriceComparison.getCityRow(hotel);
					if (cityRow) {
						$("#altOtherSites").html(cityRow);
					}
					PriceComparison.none(isRoomBlock);
				}
				
				if (pcTabCont) {
					$(pcTabCont).html(pcTab.getHtml());
				}
			} else {
				PriceComparison.none(isRoomBlock);
				PriceComparison.noRooms();
			}
		//});
	},
	
	none: function(isRoomBlock) {
		if (PriceComparison['others']['afterChecking'] || isRoomBlock) {
			if (isset('inban2')) {
				inban2.setView('4');
			}
			
			var pcBlockConts = PriceComparison.pcBlock.get(true);
			for (var i in pcBlockConts) {
				$(pcBlockConts[i]).parent().parent().hide();
			}
		} else {
			if (isset('inban2')) {
				inban2.setView('1');
			}
		}
	},
	
	cityData: {},
	
	getCityRow: function(hotel, isRow) {
		var hotelId = hotel['id'];
		var row = "";
		data = this.cityData[hotelId] ? this.cityData[hotelId] : false;
		
		if (data) {
			var cur = this.view['currencySign'];
			var price = this.view.prices[hotelId];
			
			hotel['CountrySeoName'] = hotel['CountrySeoName'] ? hotel['CountrySeoName'] : this['others']['CountrySeoName'];
			hotel['CitySeoName'] = hotel['CitySeoName'] ? hotel['CitySeoName'] : this['others']['CitySeoName'];
			hotel['SeoName'] = hotel['SeoName'] ? hotel['SeoName'] : this['others']['SeoName'];
			
			var rows = '';
			if (price) {
				var click = this['others']['page'] == "hotel" ? 'onclick="JBobj.anchor(\'#rooms_table_hotel_'+hotelId+'\');"' : 'href="'+getLink('hotel/' + hotel['CountrySeoName'] + '/' + hotel['CitySeoName'] + '/' + hotel['SeoName'] + '/')+'"';
				rows += '<li><a class="ourprice" '+click+'>Our price '+cur+''+price+'</a></li>';
			}
			
			var i = 0;
			var datalen = data.length;
			for (var key in data) {
				if (i < 4) {
					var site = data[key];
					site['totalprice'] = Math.round(site['totalprice']);
					var click = this.getClickEvent(site,hotelId);
					rows +=
					'<li'+( (i == 3 || i == (datalen-1)) ? ' class="last"' : '')+'><a href="'+site['clickurl']+'" target="_blank"'+click+'>'+site['provider']+' '+cur+''+site['totalprice']+'</a></li>';
				} else {
					break;
				}
				
				++i;
			}
			
			var head = this.isMinOurPrice({'hotelId': hotelId, 'sites': data}) ? 'We have the lowest price on the web - click to check for yourself' : 'Also available on other booking sites';
			
			row +=
			'<div class="sothersites strok">'+
				'<div class="cont">'+
					'<h3>'+head+':</h3>'+
					'<p class="clicktoopen">'+
						'<span>* click to open in a new window - make sure you compare the same deal</span>'+
						'<a href="javascript:void(JBobj.openPopup(\''+getLink('price-comparison/popup/')+'\',\'PriceComparison\',500,770))">learn more</a>'+
					'</p>'+
					'<ul>'+
						rows+
					'</ul>'+
					'<div class="seefull"><a href="'+getLink('compare/' + hotel['CountrySeoName'] + '/' + hotel['CitySeoName'] + '/' + hotel['SeoName'] + '/#tab')+'" onclick="$(\'#alternativeDialog\').dialog(\'close\');">See full comparison</a></div>'+
				'</div>'+
			'</div>';
			
			if (isRow) {
				row =
				'<tr>'+
					'<td colspan="4" class="sothersitescont">' +
						row+
					'</td>'+
				'</tr>';
			}
		}
		return row;
	},
	
	newView: {
		get: function(hotel, noAllHtml) {
			var res = '';
			
			if (PriceComparison.isLoad) {
				var data = PriceComparison.getCityRow(hotel);
				
				if (data) {
					res = this.getWithData(data);
				} else {
					res = this.getWithoutData();
				}
			} else {
				res = this.getLoading(hotel);
			}
			
			if (!noAllHtml) {
				res = this.getHtml({'html': res, 'hotel': hotel});
			}
			
			return res;
		},
		
		getWithData: function(data) {
			res = data;
			return res;
		},
		
		getWithoutData: function() {
			var res =
			'<div class="no-data">No vacancies have been found for this hotel at our competitors sites.</div>';
			return res;
		},
		
		getLoading: function(hotel) {
			var res = '';
			//%2Fimages%2Fproviders%2F
			//http%3A%2F%2Fwww.innstant.com%2Fimages%2Fproviders%2F
			if (hotel) {
				var id = "loading2"+hotel['id'];
				res =
				'<div class="load strok">'+
					'Searching other sites for price comparison:'+
					'<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0"  width="700" height="50" id="'+id+'" align="middle">'+
						'<param name="allowScriptAccess" value="sameDomain" />'+
						'<param name="allowFullScreen" value="false" />'+
						'<param name="wmode" value="transparent"/>'+
						'<param name="movie" value="/flash/loading2.swf?rootpath=%2Fimages%2Fproviders%2F" />'+
						'<param name="quality" value="high" />'+
						'<param name="bgcolor" value="#ffffff" />'+
						'<embed src="/flash/loading2.swf?rootpath=%2Fimages%2Fproviders%2F" wmode="transparent" quality="high" bgcolor="#ffffff" width="700" height="50" name="'+id+'" align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />'+
					'</object>'+
				'</div>';
			}
			
			return res;
		},
		
		getHtml: function(data) {
			var html = data['html'];
			var hotel = data['hotel'];
			var hotelId = hotel['id'];
			
			var res =
			'<tr class="pcnw">'+
				'<td id="pcHotel-'+hotelId+'" colspan="7" style="width: auto;">'+html+'</td>'+
			'</tr>';
			return res;
		}
	},
	
	runCity: function(input) {
		input = $.extend({"url":{}, "view":{}, "others":{}}, input);
		this.others = input.others;
		this.view = $.extend(this.view, input["view"]);
		this.request.params["action"] = "CitySearch";
		/*var url = this.request.set(input["url"], 'search').get();
		$.getJSON(url,function(data){
			PriceComparison.isLoad = true;
			InnstantTracker.addEvent({act: "holescombined banner loaded"});
			if (data) {
				PriceComparison.cityData = data;
				PriceComparison.addCompAll();
				if (SearchPage.stop) {
					if (SearchPage.status == 'done') {
						SearchPage.updateDialog();
					}
				} else if (SearchPage.status != 'none' && SearchPage.hotels.length) {
					SearchPage.updatePage();
				}
			}
		});*/
	},
	
	compCnt: 0,
	
	addComp: function(hotel) {
		var comp = 0;
		var sites = this.cityData[hotel['id']];
		if (sites) {
			comp = this.isMinOurPrice({'hotelId': hotel['id'], 'sites': sites}) ? 2 : 1;
			if (comp == 2) {
				++this.compCnt;
			}
		}
		hotel['comp'] = comp;
		return hotel;
	},
	
	addCompAll: function() {
		var hotels = SearchPage.data.hotels;
		for (var key in hotels) {
			hotels[key] = this.addComp(hotels[key]);
		}

		SearchPage.data.hotels = hotels;
	},
	
	floatClose: function() {
		if ($('#in_board2').get(0) && $('#pcFloat').get(0)) {
			var x=$('#pcFloat').offset().left; 
			var y=$('#pcFloat').offset().top; 
			if (y>0) {
				$('#pcFloat').css('position','absolute').css('left',x+'px').css('top',y+'px')
				.animate({top: $('#in_board2').offset().top, left: $('#in_board2').offset().left}, 700, function(){
					$('#in_board2').css('z-index', 0); 
					$(this).css('position', 'fixed').css('top', '-180px').css('left', x+'px').show();
				});
			}
		} else {
			$('#pcFloat').css('top', '-180px');
		}
	}
};
var SearchForm = {
	d: {},
	init: function(inp) {
		var d = this.d = $.extend(this.d, inp);
		if (d.skin != 2) {
	       $("#search_location").autocomplete(d.morbaURL, {
	        	dataType: 'jsonp',
	       		delay: 300,
	        	minChars: 2,
	        	matchSubset: 1,
	        	autoFill: true,
	        	matchContains: 1,
	        	cacheLength: 10,
	        	selectFirst: true,
	        	formatItem: liFormat,
	        	maxItemsToShow: 20,
	        	onItemSelect: selectItem,
	        	width: RTL ? 0 : 450,
	        	extraParams: {l: d.domain, s: d.section}	
	        });
			
			$("#search_location").focus(function(){
				//if(this.value == d.signature.replace(/&#039;/,"'")) {
					if (!this.notClear) {
						$(this).removeClass('default').val('');
					}
				//}
			}).blur(function() {
				this.notClear = false;
				if(!$.trim(this.value)) {
					$(this).addClass('default');
					this.value = d.signature;
				}
			});
		}
		
		if (d.page === 'hotel') {
        	$('#search_location').focus(function(){SearchForm.sfShow()});
        	$('#sf_change-dest').click(function(){
        		InnstantTracker.addEvent({act: 'change location clicked'});
        		SearchForm.sfShow();
        	});
        }
        
        $('#nodates').click(function(){
        	var color = this.checked ? '#fff' : '#000';
        	var dates = Dates.selectors();
        	$(dates['checkInDate']).css('color', color);
        	$(dates['checkOutDate']).css('color', color);
        });
	},
	sfShow: function() {
		PriceComparison.floatClose();
		$('#sf_change-dest').hide();
		$('#sf_hidden-part').show();
	}
};
var SearchPage =
{
	data: [],
	hotels: [],
	filtered:[],
	status: 'none',
	displayedCnt: 20,
	pageActive: 1,
	direction: true,
	sortingType: 0,
	checkInDate: '',
	checkOutDate: '',
	stop: false,
	buf: false,
	time: false,
	point: false,
	update: false,
	citysearch: false,
	
	init: function() {
		this.sortingType = parseInt($('#order').val());
		this.citysearch = parseInt($('#citysearch').val());
		$('#price_search').html('from <span class="min-price" dir="ltr"></span> to <span class="max-price" dir="ltr"></span>');
		return this;
	},
	
	poll: function(firstQuery)
	{
		if (!this.time) {
			var date = new Date();
			this.time = date.getTime();	
		}
		
		var data =
		'&landmarkId=' + $('#landmarkId').val() +
		'&citysearch=' + this.citysearch;
		
		if (this.stop) {
			data += '&stop=1';
		}
		
		if (firstQuery) {
			data += '&firstQuery=1';
		}
		
		$.ajax({
			type: 'POST',
			url: getLink('search/poll/'),
			data: data,
			dataType: 'json',
			success: function(data) {
				comparedata = [];
				
				if (SearchPage.isPC() && data['hotels']) {
					for (var key in data['hotels']) {
						var hotel = data['hotels'][key];
		
						PriceComparison.view.prices[hotel['id']] = hotel['room']['priceConvert'];
						var hotelid = hotel['id'];
								
						if (hotel['sites'].length > 0) {
							PriceComparison.isLoad = true;
							
						//	comparedata[hotelid] = hotel['sites'];
	
							PriceComparison.cityData[hotelid] = hotel['sites'];
							PriceComparison.addCompAll();

							if (SearchPage.stop) {
								if (SearchPage.status == 'done') {
									//SearchPage.updateDialog();
								}
							} else if (SearchPage.status != 'none' && SearchPage.hotels.length) {
								//SearchPage.updatePage();
							
							}
						}
						else
						{
							if (data['status'] == 'done' || SearchPage.stop) {
								PriceComparison.isLoad = true;
							}
						}
					
						if (PriceComparison.isLoad) {
							data['hotels'][key] = PriceComparison.addComp(hotel);
						}
					}
				}
				SearchPage.success(data);
			}
		});
	},
	
	setStop: function() {
		this.stop = true;
		$('#progressBar').animate({'height': 'hide'}, 500);
	},
	
	success: function(data)
	{
		data = this.merge(data);
		if (!data['currencySign']) data['currencySign'] = $('#currencySign').val();
		
		this.checkInDate = $('#checkInDate').val();
		this.checkOutDate = $('#checkOutDate').val();
		
		var hotels = data['hotels'];
		var hotelsCnt = hotels.length;
		var status = data['status'];
		var stop = this.stop;
		this.status = status;
		this.point = data.point;
		
		if ('working' == status) {
			if (!stop && hotelsCnt) {
				var date = new Date();
				var time = date.getTime();
				
				if (time - this.time >= 45000) {
					this.setStop();
				}
				
				this.data = data;
				this.hotels = hotels;
				this.updatePage();
			}
			
			setTimeout("SearchPage.poll()", 3000);
		} else {
            InnstantTracker.addEvent({act: 'City search finished'});
			$('#progressBar').animate({'height': 'hide'}, 500);
			if (stop) {
				this.buf = data;
				if (!this.isPC() || PriceComparison.isLoad) {
					this.updateDialog(1);
				}
			} else {
				this.data = data;
				this.hotels = hotels;
				this.updatePage();
				
				if (PriceComparison.isLoad) {
					this.updatePage();
				}
			}
		}
	},
	
	updateDialog: function(buf) {
		
		var strings = [];
		
		strings['More results are available'] = 'More results are available';
		strings['Show updated results'] = 'Show updated results';
		strings['Yes'] = 'Yes';
		strings['No'] = 'No';
		strings['buf'] = (buf?1:0);
		
		var html = SearchPage_Template.updateDialog.dialog(strings);
		$.facebox(html, 'showup');
	},
	
	ispc: null,
	isPC: function() {
		var ispc = this.ispc;
		if (ispc === null) {
			ispc = $('#priceComparison').val();
			ispc = ispc == 'undefined' ? null : parseInt(ispc);
			this.ispc = ispc;
		}
		return ispc;
	},
	
	merge: function(data)
	{
		if (!data) {
			return this.data;
		}
		
		var cache = this.data;
		
		if (!cache) {
			return data;
		}
		
		var elements = {'old': [], 'new': []};
		for (var i = 0; i < 2; i++) {
			var tmp = i ? data : cache;
			if (tmp['hotels'] && tmp['hotels'].length) {
				elements[i ? 'new' : 'old'] = tmp['hotels'];
			} else {
				tmp = i ? cache : data;
				var results = tmp['hotels'] && tmp['hotels'].length ? tmp['hotels'] : [];
				data['hotels'] = results;
				return data;
			}
		}
		
		for (var newKey in elements['new']) {
			var newe = elements['new'][newKey];
			var flag = false;		
			
			for (var keyOld in elements['old']) {
				var old = elements['old'][keyOld];
				if (old['id'] == newe['id']) {
					elements['old'][keyOld] = newe;
					flag = true;
				}
			}
			if (!flag) {
				elements['old'].push(newe);
			}
		}
		data['hotels'] = elements['old'];
		return data;
	},
	
	buildTable1: function()
	{
		var data = this.data;

		var hotels = this.hotels;
		var hotelsCnt = hotels.length;
		var checkInDate = this.checkInDate;
		var checkOutDate = this.checkOutDate;
		var displayedCnt = this.displayedCnt;
		var pageActive = this.pageActive;
		var zi = hotelsCnt;
		var viewId = data['viewId'];
		
		var html = SearchPage_Template.buildTable1.top();
			
			if (!hotelsCnt) {
				dataArr['strings'] = [];
				dataArr['strings']['We are sorry, but there are no hotels available that match your search criteria'] = 'We are sorry, but there are no hotels available that match your search criteria';
				dataArr['strings']['Please expand your search criteria to include more options and click the "search" button again'] = 'Please expand your search criteria to include more options and click the &quot;search&quot; button again';
				
				html += SearchPage_Template.buildTable1.item_hotel_no_results(dataArr);
			    
			    $('#searchResult').html(html);
			    return true;
			}
			
			for (var key = (pageActive - 1) * displayedCnt; key < pageActive * displayedCnt; key++) {
				if (key >= hotelsCnt) {
					break;
				}
				
				var hotel = hotels[key];
				var room = hotel['room'];
				
				// opening <tr>
				html += SearchPage_Template.buildTable1.item_top();
				
					// image
					var dataArr = [];
					dataArr['image_url'] = getLink('hotel/' + hotel['CountrySeoName'] + '/' + hotel['CitySeoName'] + '/' + hotel['SeoName'] + '/');
					dataArr['image'] = hotel["image"];
					dataArr['Name'] = hotel["Name"];
				
					html += SearchPage_Template.buildTable1.item_image(dataArr);
					
					// hotel name
					var dataArr = [];
					dataArr['hotel_name'] = hotel['Name'];
					dataArr['formated_price'] = data['currencySign'] + ' ' + (room['priceConvert']/data["cntDays"]);
					dataArr['hotelUrl'] = getLink('hotel/' + hotel['CountrySeoName'] + '/' + hotel['CitySeoName'] + '/' + hotel['SeoName'] + '/');
					dataArr["starsTitle"] = data["starsTitle"];
					dataArr["starts"] = hotel['Stars'];
					dataArr["Address"] = hotel['Address'];
					dataArr["hotelid"] = hotel['id'];
					dataArr["hotel_distance"] = hotel['distance'];
					dataArr["sortingType"] = this.sortingType;
					dataArr["hotel_distanceView"] = hotel['distanceView'];
					dataArr["point_name"] = this.point['name'];
					dataArr["hotel_zone"] = hotel['zone'];
					dataArr["hotel_LandmarkDistance"] = hotel['LandmarkDistance'];
					dataArr["hotel_LandmarkName"] = hotel['LandmarkName'];
					
					html += SearchPage_Template.buildTable1.item_hotel_name(dataArr);
					
					// review
					var dataArr = [];
					dataArr["hotel_review_link"] = getLink('reviews/' + hotel['CountrySeoName'] + '/' + hotel['CitySeoName'] + '/' + hotel['SeoName'] + '/#tab');
					dataArr['hotel_review'] = hotel["review"];
					dataArr["hotel_reviews_page"] = getLink('booking-review/'+hotel['id']+'/?anonymous=1');
					dataArr['reviewsTitle'] = data["reviewsTitle"];
					dataArr['tripadivsorReview'] = getLink('tripadivsor/' + hotel['CountrySeoName'] + '/' + hotel['CitySeoName'] + '/' + hotel['SeoName'] + '/#tab');
					dataArr['GuestRating'] = hotel['GuestRating'];
					dataArr['strings'] = [];
					dataArr['strings']['Guest rating'] = 'Guest rating';
					dataArr['RoundGuestRating'] = Math.round(hotel['GuestRating']*2);
					dataArr['hotel_ReviewsCnt'] =hotel["ReviewsCnt"];
					dataArr['reviews_url'] = getLink('reviews/' + hotel['CountrySeoName'] + '/' + hotel['CitySeoName'] + '/' + hotel['SeoName'] + '/#tab');
					dataArr['popularity'] = parseInt(hotel['Popularity']);
					dataArr['hotel_key'] = key;
					zi = (--zi);
					dataArr['z_index'] = zi;
					dataArr['popularityText'] = data["popularityText"];
					
					dataArr['use_room_board'] = 0;
					dataArr['use_hotel_board'] = 0;
					dataArr['use_no_board'] = 0;
					
					if (JBobj.isBoard(room['board'])) {
						dataArr['room_boardLink'] = room['boardLink'];
						dataArr['room_boardTitle'] = room['boardTitle'];
						dataArr['room_board'] = JBobj.getBreakfastIcon(room['board']);
						dataArr['room_boardText'] = room['boardText'];
						dataArr['use_room_board'] = 1;
					} else if (JBobj.isBoard(hotel['board'])) {
						dataArr['strings']['This hotel offers various board options'] = 'This hotel offers various board options';
						dataArr['use_hotel_board'] = 1;
						dataArr['hotel_boardText'] = hotel['boardText'];
					} else {
						dataArr['strings']['None'] = 'None';
						dataArr['room_boardLink'] = room['boardLink'];
						dataArr['use_no_board'] = 1;
					}
					
					dataArr['strings']['Be the first'] = 'Be the first';
					dataArr['strings']['to review this hotel'] = 'to review this hotel';
					
					html += SearchPage_Template.buildTable1.item_hotel_review(dataArr);
					
					// price
					var dataArr = [];
					dataArr['room_haspackage'] = room['haspackage'];
					dataArr['currencySign'] = data['currencySign'];
					dataArr['room_minpackage'] = room["minpackage"];
					dataArr['room_price'] = room["price"];
					dataArr['viewId'] = viewId;
					dataArr['cntDays'] = data["cntDays"];
					dataArr['parsed_cntDays'] = parseInt(data["cntDays"]);
					dataArr['hotel_Special'] = hotel["Special"];
					dataArr['hotel_id'] =hotel["id"];
					dataArr['hotel_name'] =hotel["Name"];

					dataArr['hotel_link'] = 'hotel/' + hotel["CountrySeoName"] + '/' + hotel["CitySeoName"] + '/' + hotel["SeoName"] + '/';
					if (!this.citysearch) {
						dataArr['hotel_link'] += checkInDate + '/' + checkOutDate + '/';
					}
					dataArr['hotel_link'] = getLink(dataArr['hotel_link']);
					dataArr['is_city_search'] = this.citysearch;

					dataArr['strings'] = [];
					dataArr['strings']['Minimum combination price'] = 'Minimum combination price';
					dataArr['strings']['Incl. taxes & fees'] = 'Incl. taxes & fees';
					dataArr['strings']['Nights'] = 'Nights';
					dataArr['strings']['Night'] = 'Night';
					dataArr['strings']['Special Deal'] = 'Special Deal';
					dataArr['strings']['Book now'] = 'Book now';
					dataArr['strings']['show rates'] = 'show rates';

					html += SearchPage_Template.buildTable1.item_hotel_price(dataArr);
				
				// closing </tr>
				html += SearchPage_Template.buildTable1.item_bottom();
				
				// details
				var dataArr = [];
				dataArr['hotel_id'] = hotel['id'];
				
				html +=  SearchPage_Template.buildTable1.item_hotel_details(dataArr);;
				
				var otherSites = PriceComparison.getCityRow(hotel, true);
				if (otherSites) {html += otherSites;}
			}
		
		html += SearchPage_Template.buildTable1.bottom();
		
		$('#searchResult').html(html);
		return true;
	},
	
	buildTable: function()
	{
		var data = this.data;
		var hotels = this.hotels;
		var hotelsCnt = hotels.length;
		var checkInDate = this.checkInDate;
		var checkOutDate = this.checkOutDate;
		var viewId = data['viewId'];
		var isPC = this.isPC();
		
		var addClass = viewId == 8 && isPC ? ' pcmerge' : '';
		
		// <table> opening
		var dataArr = [];
		dataArr['viewId'] = viewId;
		dataArr['has_price_comparison'] = isPC;
		dataArr['is_city_search'] = this.citysearch;
		dataArr['sort_by_name_click'] = 'SearchPage.sortClick(2);';
		dataArr['sort_by_stars_click'] = 'SearchPage.sortClick(4);';
		dataArr['sort_by_board_click'] = 'SearchPage.sortClick(3);';
		dataArr['sort_by_guest_rating_click'] = 'SearchPage.sortClick(5);';
		dataArr['sort_by_price_click'] = 'SearchPage.sortClick(1);';
		dataArr['sortingType'] = this.sortingType;
		dataArr['direction'] = this.direction;
		
		dataArr['strings'] = [];
		dataArr['strings']['Name'] = 'Name';
		dataArr['strings']['Stars'] = 'Stars';
		dataArr['strings']['Board'] = 'Board';
		dataArr['strings']['Guest Rating'] = 'Guest Rating';
		dataArr['strings']['Price'] = 'Price';
		dataArr['strings']['Total Price'] = 'Total Price';
		dataArr['strings']['Sort results by'] = 'Sort results by';
		
		var SortTable = SearchPage_Template.buildTable.sortView(dataArr);
		dataArr['SortTable'] = SortTable;
		dataArr['got_hotels'] = hotelsCnt;
				
		var html = SearchPage_Template.buildTable.top(dataArr);
			
			if (hotelsCnt) {
				var displayedCnt = this.displayedCnt;
				var pageActive = this.pageActive;
				for (var i = (pageActive - 1) * displayedCnt; i < pageActive * displayedCnt; i++) {
					if (i >= hotelsCnt) {
						break;
					}
					var hotel = hotels[i];
					var room = hotel['room'];
					var elements = [];
					
					// <tr> start
					html += SearchPage_Template.buildTable.item_top();
					
						// images
						var dataArr = [];
						dataArr['image_url'] = getLink('hotel/' + hotel['CountrySeoName'] + '/' + hotel['CitySeoName'] + '/' + hotel['SeoName'] + '/');
						dataArr['image'] = hotel["image"];
						dataArr['Name'] = hotel["Name"];
						
						elements[0] = SearchPage_Template.buildTable.item_image(dataArr); // Images
						
						// name
						var dataArr = [];
						dataArr['hotel_click_event'] = 'JBobj.hotelClickEvent({name:\''+hotel['Name']+'\',price:\''+data['currencySign'] + ' ' + (room['priceConvert']/data["cntDays"])+'\'});';
						dataArr['hotel_link'] = getLink('hotel/' + hotel['CountrySeoName'] + '/' + hotel['CitySeoName'] + '/' + hotel['SeoName'] + '/');
						dataArr['hotel_Name'] = hotel['Name'];	
						dataArr["hotel_distance"] = hotel["distance"];
						dataArr["sortingType"] = this.sortingType;
						dataArr["hotel_distanceView"] = hotel["distanceView"];
						
						if (typeof this.point['name'] != 'undefined') 
						{
							dataArr["point_name"] = this.point['name'];
						}
						else
						{
							dataArr["point_name"] = '';
						}
						
						dataArr["hotel_zone"] = hotel['zone'];
						dataArr["hotel_LandmarkDistance"] = hotel['LandmarkDistance'];
						dataArr["hotel_LandmarkName"] = hotel['LandmarkName'];
						dataArr["is_city_search"] = this.citysearch;
						dataArr["hotel_id"] = hotel["id"];
						dataArr["hotel_rates_click"] = 'JBobj.expandHotel(' + hotel["id"] + ', false,\'' + addslashes(hotel['Name']) + '\');';
						dataArr["enlargeMap_click"] = 'SearchPage.enlargeMap('+hotel['id']+');';
						dataArr['has_price_comparison'] = isPC;
						dataArr["photos_link"] = getLink('photos/' + hotel['CountrySeoName'] + '/' + hotel['CitySeoName'] + '/' + hotel['SeoName'] + '/#tab');
						dataArr["reviews_link"] = getLink('reviews/' + hotel['CountrySeoName'] + '/' + hotel['CitySeoName'] + '/' + hotel['SeoName'] + '/#tab');
						dataArr["compare_link"] = getLink('compare/' + hotel['CountrySeoName'] + '/' + hotel['CitySeoName'] + '/' + hotel['SeoName'] + '/#tab');
						dataArr["map_link"] = getLink('map/' + hotel["CountrySeoName"] + '/' + hotel["CitySeoName"] + '/' + hotel["SeoName"] + '/#tab');
						dataArr["is_special"] = hotel["Special"];
						dataArr["hotel_Address"] = hotel['Address'];

						dataArr['strings'] = [];
						dataArr['strings']['from'] = 'from';
						dataArr['strings']['in'] = 'in';
						dataArr['strings']['Rates'] = 'Rates';
						dataArr['strings']['Map'] = 'Map';
						dataArr['strings']['Photos'] = 'Photos';
						dataArr['strings']['Reviews'] = 'Reviews';
						dataArr['strings']['Price Comparison'] = 'Price Comparison';
						dataArr['strings']['Best Price Guaranteed'] = 'Best Price Guaranteed';
						dataArr['strings']['Special Deal'] = 'Special Deal';
											
						elements[1] = SearchPage_Template.buildTable.item_hotel_name(dataArr); // hotel name
						elements[7] = SearchPage_Template.buildTable.item_inner_links(dataArr); // inner links
						
						// stars
						var dataArr = [];
						dataArr['hotel_Popularity'] = parseInt(hotel["Popularity"]);
						dataArr['starsTitle'] = data["starsTitle"];
						dataArr['hotel_Stars'] = hotel["Stars"];
						
						elements[2] = SearchPage_Template.buildTable.item_hotel_stars(dataArr); // stars
						
						// breakfast
						var dataArr = [];
						dataArr['use_room_board'] = 0;
						dataArr['use_hotel_board'] = 0;
						dataArr['use_no_board'] = 0;
						dataArr['strings'] = [];
						
						if (JBobj.isBoard(room['board'])) {
							dataArr['room_boardLink'] = room['boardLink'];
							dataArr['room_boardTitle'] = room['boardTitle'];
							dataArr['room_board'] = JBobj.getBreakfastIcon(room['board']);
							dataArr['room_board_small'] = JBobj.getBreakfastIcon({'type':room['board'],'size':'small'});
							dataArr['room_boardText'] = room['boardText'];
							dataArr['use_room_board'] = 1;
						} else if (JBobj.isBoard(hotel['board'])) {
							dataArr['strings']['This hotel offers various board options'] = 'This hotel offers various board options';
							dataArr['use_hotel_board'] = 1;
							dataArr['hotel_boardText'] = hotel['boardText'];
						} else {
							dataArr['strings']['None'] = 'None';
							dataArr['room_boardLink'] = room['boardLink'];
							dataArr['use_no_board'] = 1;
						}
						
						elements[3] = SearchPage_Template.buildTable.item_hotel_breakfast(dataArr); // breakfast
						
						// rating
						var dataArr = [];
						dataArr['hotel_Popularity'] = parseInt(hotel["Popularity"]);
						dataArr['record_num'] = i;
						dataArr['popularityText'] = data["popularityText"];
						dataArr['hotel_GuestRating'] = hotel["GuestRating"];
						dataArr['hotel_reviewsTitle'] = data["reviewsTitle"];
						dataArr['tripadvisor_link'] = getLink('tripadvisor/' + hotel["CountrySeoName"] + '/' + hotel["CitySeoName"] + '/' + hotel["SeoName"] + '/#tab');
						dataArr['reviews_link'] = getLink('reviews/' + hotel['CountrySeoName'] + '/' + hotel['CitySeoName'] + '/' + hotel['SeoName'] + '/#tab');
						dataArr['hotel_GuestRating'] = hotel["GuestRating"];
						dataArr['hotel_Reviews_Count'] = hotel["ReviewsCnt"];
						dataArr['GuestRatingCnt'] = hotel['GuestRatingCnt'];

						dataArr['strings'] = [];
						dataArr['strings']['Based on'] = 'Based on';
						dataArr['strings']['based on'] = 'based on';
						dataArr['strings']['Reviews'] = 'Reviews';
						dataArr['strings']['reviews'] = 'reviews';
						dataArr['strings']['User reviews'] = 'User reviews';
						dataArr['strings']['be the first to review'] = 'be the first to review';
						
						elements[4] = SearchPage_Template.buildTable.item_hotel_rating(dataArr); // rating
						
						// price
						var dataArr = [];
						dataArr['room_price'] = room['price'];
						dataArr['room_old_price'] = room['priceOld'];
						dataArr['haspackage'] = room['haspackage'];
						dataArr['currencySign'] = data['currencySign'];
						dataArr['room_minpackage'] = room['minpackage'];
						dataArr['viewId'] = viewId;
						dataArr['days_count'] = data["cntDays"];
						dataArr["is_city_search"] = this.citysearch;
						
						dataArr['strings'] = [];
						dataArr['strings']['Minimum combination price'] = 'Minimum combination price';
						dataArr['strings']['Incl. taxes & fees'] = 'Incl. taxes & fees';
						dataArr['strings']['Nights'] = 'Nights';
						dataArr['strings']['Night'] = 'Night';
						dataArr['strings']['Exclusive prices!'] = 'Exclusive prices!';
						elements[5] = SearchPage_Template.buildTable.item_hotel_price(dataArr); // price
						
						// book now
						var dataArr = [];
						dataArr['book_now_link'] =  'hotel/' + hotel["CountrySeoName"] + '/' + hotel["CitySeoName"] + '/' + hotel["SeoName"] + '/';
						if (!this.citysearch) {
							dataArr['book_now_link'] += checkInDate + '/' + checkOutDate + '/';
						}
						dataArr['book_now_link'] = getLink(dataArr['book_now_link']); 
						dataArr['hotel_Special'] = hotel["Special"];
						dataArr["is_city_search"] = this.citysearch;
						dataArr["expand_hotel_click"] = 'JBobj.expandHotel(' + hotel["id"] + ', false,\'' + addslashes(hotel['Name']) + '\');';
						dataArr["hotel_id"] = hotel["id"];

						dataArr["hotel_data"] = hotel;
						dataArr["viewId"] = viewId;
						dataArr['has_price_comparison'] = isPC;

						dataArr['strings'] = [];
						dataArr['strings']['Special Deal'] = 'Special Deal';
						dataArr['strings']['Book now'] = 'Book now';	
						dataArr['strings']['show rates'] = 'show rates';	
						
						elements[6] = SearchPage_Template.buildTable.item_hotel_book_now(dataArr); // book now
						
						var element_order = SearchPage_Template.buildTable.element_order();
						
						$.each(element_order, function(index, value) { 
							html += elements[value];
						});
					
					// room list
					var dataArr = [];
					dataArr["hotel_id"] = hotel["id"];
					dataArr["hotel"] = hotel;
					dataArr['hotel_link'] = getLink('hotel/' + hotel['CountrySeoName'] + '/' + hotel['CitySeoName'] + '/' + hotel['SeoName'] + '/');
					dataArr['has_price_comparison'] = isPC;
					dataArr['is_city_search'] = this.citysearch;
					dataArr["hotel_rates_click"] = 'SearchPage.expandHotel({t:this,id:' + hotel["id"] + ',name:\'' + addslashes(hotel['Name']) + '\',noEvent:false});';
						
					dataArr['strings'] = [];
					dataArr['strings']['For room types click here'] = 'For room types click here';
					
					html += SearchPage_Template.buildTable.item_hotel_room_list(dataArr);
				}
			} else if ('working' != this.status || this.stop) {
				dataArr['strings'] = [];
				dataArr['strings']['We are sorry, but there are no hotels available that match your search criteria'] = 'We are sorry, but there are no hotels available that match your search criteria';
				dataArr['strings']['Please expand your search criteria to include more options and click the "search" button again'] = 'Please expand your search criteria to include more options and click the &quot;search&quot; button again';
				
				html += SearchPage_Template.buildTable.item_hotel_no_results(dataArr);
			}

		html += SearchPage_Template.buildTable.bottom(dataArr);
		
		$("#searchResult").html(html);
	},
	
	buildNavigation: function()
	{
		var pageCnt = this.getPageCnt();
			
		if (pageCnt) {
			var html = '';
			var pageActive = this.pageActive;
			
			html += SearchPage_Template.buildNavigation.top();
			
				if (pageCnt > 1) {
					
					if (pageActive != 1) {
						var dataArr = [];
						dataArr["back_link"] = (pageActive - 1);

						dataArr['strings'] = [];
						dataArr['strings']['Previous'] = 'Previous';			
						
						html += SearchPage_Template.buildNavigation.previous_page(dataArr);
					}
					
					for (var page = pageActive - 3 >= 1 ? pageActive - 3 : 1; page <= (pageActive + 3 < pageCnt ? pageActive + 3 : pageCnt); page++) {
						if (page != pageActive - 3 && page != 1) {
	        	    		html += ' - ';
	        	    	}
	        	    	if (page != pageActive) {
							var dataArr = [];
							dataArr["page"] = page;
	        	    		html += SearchPage_Template.buildNavigation.clickable_page(dataArr);
	        	    	} else {
							var dataArr = [];
							dataArr["page"] = page;
	        	    		html += SearchPage_Template.buildNavigation.active_page(dataArr);
	        	   	}
					}
					
					if (pageActive != pageCnt) {
						var dataArr = [];
						dataArr["next_link"] = (pageActive + 1);

						dataArr['strings'] = [];
						dataArr['strings']['Next'] = 'Next';			
						
						html += SearchPage_Template.buildNavigation.next_page(dataArr);
	        		}
				}
				
			html += SearchPage_Template.buildNavigation.bottom();
			
			$('#searchNavigation').html(html);
			return true;
		} else {
			$('#searchNavigation').html('');
			return false;
		}
	},
	
	buildAll: function()
	{
		var viewId = this.data['viewId'];
		
		switch (viewId) {
			case 1:
			case 3:
				this.buildTable1();
				break;
			default:
				this.buildTable();
		}
		
		this.buildNavigation();
		this.setHtmlInfo();
		$('#topexpandall').html('[+] expand all');
		$('#botexpandall').html('[+] expand all');
		if (this.hotels.length) {
			$('#topexpandall').show();
			$('#botexpandall').show();
		} else {
			$('#topexpandall').hide();
			$('#botexpandall').hide();
		}
		var sortingType = this.sortingType;
		
		var sortingTypes = new Array(1,2,3,4,5);
		for (i in sortingTypes) {
			var type = sortingTypes[i];
			var cssClass = 'essort';
			if (sortingType == type) {
				cssClass += " active " + (this.direction ? 'rsort' : 'sort');
			}
			$('#hotels-header_sort' + type).attr('class', cssClass);
		}
		
		if (sortingType == 6) {
			var sortSelect = $('#sorting').get(0);
			var cntOprions = sortSelect.options.length;
			var isOptionDist = false;
			for (i = 0; i < cntOprions; i++) {
				if (sortSelect.options[i].value == sortingType) {
					isOptionDist = true;
					break;
				}
			}
			if (!isOptionDist) {
				sortSelect.options[cntOprions] = new Option('By Distance', sortingType);
			}
		}
		
		$('#sorting option').each(function(){
			var selected = sortingType == $(this).val();
			$(this).attr('selected', selected);
			
			if (selected) {
				$('#sortingSkin').html($(this).html());
			}
		});
		
		this.map.set();
		$('#bigMap').html("");
		$('#infoDialog').html('').dialog('close');
		this.Hash.set();
	},
	
	updatePage: function(isbuf)
	{		
		if (isbuf && this.buf) {
			this.data = this.buf;
			this.hotels = this.data['hotels'];
			this.buf = false;
		}
		
		this.direction = true;
		this.setPriceSlider();
		this.update = true;
		JBobj.clearFilters(1);
		this.update = false;
	
		// ?  hotels out of ?  have pictures
		var hotels = SearchPage.data.hotels;
		var withPictures = 0;
		
		for (var i in hotels) {
			var hotel = hotels[i];
			
			if (0 === hotel["image"].indexOf("http")) {
				withPictures++;
			}
		}
		
		$('#view_cntHotelsWithPictures').html(withPictures);
		$('#cont_cntHotelsWithPictures').show();	
	},
	
	getPageCnt: function()
	{
		return Math.ceil(SearchPage.hotels.length / SearchPage.displayedCnt);
	},
	
	navigationClick: function(page)
	{
		JBobj.anchor('#head');
		if (!parseInt(page)) {
			var page = 1;
		}
		
		var action = this.pageActive > page ? 'previous clicked' : 'next clicked';
		InnstantTracker.addEvent({act: action, val: page});
		
		this.pageActive = page;
		this.buildAll();
	},
	
	setHtmlInfo : function()
	{
		// (Showing ? - ? results of ?)
		var showingInfo = '';
		var hotelsCnt = this.hotels.length;
		if (hotelsCnt) {
			var pageActive = this.pageActive;
			var displayedCnt = this.displayedCnt;
			
			if (pageActive * displayedCnt < hotelsCnt) {
				var see = displayedCnt;
			} else {
				var see = displayedCnt - (pageActive * displayedCnt - hotelsCnt);
			}
			
			showingInfo = 'Showing ' + ((pageActive - 1) * displayedCnt + 1) + ' - ' + ((pageActive - 1) * displayedCnt + see) + ' results of ' + hotelsCnt;
		}
		$("#showingInfo-bottom").html(showingInfo);
		$("#showingInfo-top").html(showingInfo);
		
		// Facilities cnt
		$('#facilities fieldset').each(function(){
			$('span', this).html('0');
			$('div', this).show();
			$(this).hide();
		});
		
		var hotels = this.hotels;
		var ffId = new Array(); 
		for (var i in hotels) {
			var hotel = hotels[i];
			for (var j in hotel['Facilities']) {
				if (ffId[hotel['Facilities'][j]]) {
					ffId[hotel['Facilities'][j]] += 1;
				} else {
					ffId[hotel['Facilities'][j]] = 1;
				}
			}
		}
		
		for (i in ffId) {
			$('#facilityCnt' + i).html(ffId[i]);
			$('#facilitiesRow' + i).show();
		}
		
		if (this.citysearch) {
			var res = 'Star rating: ';
			var stars = new Array();
			var tmp = $(this.Hash.selectors.s);
			var i = tmp.length-1;
			for (; i >= 0; i--) {
				if (tmp[i].checked) {
					stars.push(tmp[i].value);
				}
			}
			res += '<b class="distinguish">'+(stars.length?stars:'1-5')+'</b>, Price: <b class="distinguish">'+$('#currencySign').val()+' '+$('#price_slider').slider('values', 0)+'-'+$('#price_slider').slider('values', 1)+'</b>';
			$('#searchInfo').html(res);
		}
	},
	
	getSortVal: function(hotel) {
		/*
		1. comp + cheap +image
		2. comp +cheap +noimage
		3. nocomp+image
		4. nocomp+noimage
		5. comp+expensive+image
		6. comp+expensive+noimage
		*/
		var val = null;
		var img = hotel['image'].indexOf('http') === 0;
		var comp = hotel['comp'];
		if (comp) {
			if (comp == 2) {
				val = img ? 1 : 4;
			} else {
				val = img ? 3 : 6;
			}
		} else {
			val = img ? 2 : 5;
		}
		return val;
	},
	
	sorting: function(type)
	{				
		if (type == 6 && this.point) {
			$('#contLandmarkName').css('visibility', 'visible');
			$('#landmarkName').html(this.point['name']);
			$(this.point['type']=='lm'?'#landmarkAddress':'#Streetaddress').val(this.point['name']).removeClass('default');
		} else {
			$('#contLandmarkName').css('visibility', 'hidden');
		}
		
		var hotels = clone(this.filtered);
		var hotelsCnt = hotels.length;
		gType = parseInt(type);
		if (5 == gType || 3 == gType || 4 == gType) {
			this.direction = gType == this.sortingType ? !this.direction : true;
		} else {
			this.direction = gType == this.sortingType ? !this.direction : false;
		}
		
		var mix = this.update && gType === 0 && hotelsCnt > 3;
		
		if (mix && SearchPage.isPC() && PriceComparison.isLoad) {
			mix = PriceComparison.compCnt > 3;
		}
		
		/*
		* 2,4,6 pozicii dolzhny byt' samymi deshevymi 
		*/	   
		if (mix) {						
			hotels = hotels.sort(function(a, b){
	
				if (SearchPage.isPC() && PriceComparison.isLoad) {
					a["Popularity"] = parseFloat(a["Popularity"]) ? parseFloat(a["Popularity"]) : 0;
					b["Popularity"] = parseFloat(b["Popularity"]) ? parseFloat(b["Popularity"]) : 0;
					return a['Popularity'] < b['Popularity'] ? 1 : -1;
					var av = SearchPage.getSortVal(a);
					var bv = SearchPage.getSortVal(b);
					if (av != bv) {
						return av > bv ? 1 : -1;
					}
				}

				var a_pic = a["image"].indexOf("http") === 0;
		    	var b_pic = b["image"].indexOf("http") === 0;
		    	if (a_pic != b_pic) {
		    		return b_pic > a_pic ? 1 : -1;
		    	}
				
				if (a.room.price != 0 && b.room.price == 0)
					return -1;
				
				if (a.room.price == 0 && b.room.price != 0)
					return 1;
				
				if (a.room.price && b.room.price) 
					return a['room']['price'] > b['room']['price'] ? 1 : -1;
				
				return 0;
			});
			var cheaps = new Array(hotels[0], hotels[1], hotels[2]);
			hotels.splice(0,3);
		}
		
		hotels = hotels.sort(function(a, b){
			var direction = SearchPage.direction;
			var update = SearchPage.update;
			var aRoom = a['room'];
			var bRoom = b['room'];

			switch (gType) {
				case 0: // popularity
					a["Popularity"] = parseFloat(a["Popularity"]) ? parseFloat(a["Popularity"]) : 0;
					b["Popularity"] = parseFloat(b["Popularity"]) ? parseFloat(b["Popularity"]) : 0;
					return a['Popularity'] < b['Popularity'] ? 1 : -1;
					if (update && SearchPage.isPC() && PriceComparison.isLoad == false) {
						var av = SearchPage.getSortVal(a);
						var bv = SearchPage.getSortVal(b);
						if (av != bv) {
							return av > bv ? 1 : -1;
							
						}
					}
					
					a["Popularity"] = parseInt(a["Popularity"]) ? parseInt(a["Popularity"]) : 0;
					b["Popularity"] = parseInt(b["Popularity"]) ? parseInt(b["Popularity"]) : 0;
					
					var a_pic = a["image"].indexOf("http") === 0;
			    	var b_pic = b["image"].indexOf("http") === 0;
			    	
			    	if (a_pic || b_pic) {
						if (! (a_pic && b_pic)) {
							return b_pic ? 1 : -1;
						}
			    	}

				if (a['Popularity'] != b['Popularity']) {
						return a['Popularity'] < b['Popularity'] ? 1 : -1;
					}
				
					if (aRoom['price'] == 0 && bRoom['price'] != 0)
						return 1;
					
					if (aRoom['price'] != 0 && bRoom['price'] == 0)
						return -1;
					
					if (aRoom['price'] && bRoom['price'])	
						return aRoom['price'] > bRoom['price'] ? 1 : (aRoom['price'] == bRoom['price'] ? (a["Name"] > b["Name"] ? 1 : -1) : -1);
					
					return 0;
					
					break;
				
				case 1: // price
					var aminpackage = aRoom['minpackage'];
					var bminpackage = bRoom['minpackage'];
					
					if (aRoom['minpackage'] == 0)
					{
					   aRoom['minpackage'] = aRoom['price']*100;
					}
					
					if (bRoom['minpackage'] == 0)
					{
					 	bRoom['minpackage'] = bRoom['price']*100;
					}
					  
						if (aRoom['minpackage'] == bRoom['minpackage']) {
							return a['Name'] > b['Name'] ? 1 : -1;
						}
					
						if (direction) {
							return aRoom['minpackage'] < bRoom['minpackage'] ? 1 : -1;
						} else {
							return aRoom['minpackage'] > bRoom['minpackage'] ? 1 : -1;
						}
					break;
				
				case 2: // name
    	            if (direction) {
	                    return a['Name'] < b['Name'] ? 1 : -1;
    	            } else {
	                    return a['Name'] > b['Name'] ? 1 : -1;
    	            }
    	        	break;
    	        	
    	        case 3: // board
    	        	if (aRoom['boardValue'] == bRoom['boardValue']) {
    	        		return parseInt(a['id']) > parseInt(b['id']) ? 1 : -1;
					}
    	            if (direction) {
	                    return aRoom['boardValue'] < bRoom['boardValue'] ? 1 : -1;
    	            } else {
	                  	return aRoom['boardValue'] > bRoom['boardValue'] ? 1 : -1;
    	            }
    	        	break;
    	        	
    	         case 4: // stars
    	            if (direction) {
	                    return a['Stars'] < b['Stars'] ? 1 : (a['Stars'] == b['Stars'] ? (a['Name'] > b['Name'] ? 1 : -1) : -1);
    	            } else {
	                    return a['Stars'] > b['Stars'] ? 1 : (a['Stars'] == b['Stars'] ? (a['Name'] > b['Name'] ? 1 : -1) : -1);
    	            }
    	       		break;
    	       		
				case 5: // guest rating
					if (direction) {
						return a['GuestRating'] < b['GuestRating'] ? 1 : (a['GuestRating'] == b['GuestRating'] ? (a['Name'] > b['Name'] ? 1 : -1) : -1);
					} else {
						return a['GuestRating'] > b['GuestRating'] ? 1 : (a['GuestRating'] == b['GuestRating'] ? (a['Name'] > b['Name'] ? 1 : -1) : -1);
					}
					break;
					
				case 6: // distance
		        	if (a['distance'] === "" && b['distance'] !== "") {
		        		return 1;
		        	} else if (a['distance'] !== "" && b['distance'] === "") {
		        		return -1;
		        	} else {
						return parseFloat(a['distance']) > parseFloat(b['distance']) ? 1 : -1;
		        	}
		        	break;
			}
		});
		
		/*
		* 2,4,6 pozicii dolzhny byt' samymi deshevymi 
		* next
		*/
		if (mix) {
			hotels.splice(1,0,cheaps[0]);
			hotels.splice(3,0,cheaps[1]);
			hotels.splice(5,0,cheaps[2]);
		}
		
		this.hotels = hotels;
		this.sortingType = gType;
		this.pageActive = this.changePage ? this.changePage : 1;
		this.changePage = false;
		this.buildAll();
	},
	
	setPriceSlider: function()
	{
		
		var hotels = this.data['hotels'];
		var cnt = hotels ? hotels.length : 0;
		var minPrice = cnt ? hotels[0]['room']['price'] : 0;
		var maxPrice = cnt ? hotels[0]['room']['price'] : 0;
		var currencySign = $('#currencySign').val();
		
		for (var i in hotels) {
			var price = hotels[i]['room']['price'];
			
			if (minPrice > price) {
				minPrice = price;
			}
			
			if (maxPrice < price) {
				maxPrice = price;
			}
		}
		
		$('#price_slider').slider('option', 'min', minPrice)
                          .slider('option', 'max', maxPrice);
                          
        try {
        $('#price_slider').slider('values', 0, minPrice);
		$('#price_slider').slider('values', 1, maxPrice);
		}catch(e){}
		
		SearchPage.priceSliderView({'currencySign':currencySign,'minPrice':minPrice,'maxPrice':maxPrice});
	},
	
	priceSliderView: function(data) {
		$('#price_search .min-price').html(data.currencySign + ' ' + data.minPrice);
		$('#price_search .max-price').html(data.currencySign + ' ' + data.maxPrice);
		$('#price_search').show();
	},
	
	filter: function()
	{
		var hotelsAll = this.data['hotels'];
		var hotels = [];
		var minPrice = parseInt($('#price_slider').slider('values', 0));
		var maxPrice = parseInt($('#price_slider').slider('values', 1));
		
		var rminPrice = parseInt($('#price_slider').slider('option', 'min'));
		var rmaxPrice = parseInt($('#price_slider').slider('option', 'max'));
		var changePrice = minPrice != rminPrice || maxPrice != rmaxPrice;
		
		var hotelName = $('#hotel_name').get(0);
		hotelName = in_array($.trim(hotelName.value), hotelName.defaultValues) ? false : $.trim(hotelName.value);
		var hotel_name_opt = parseInt($('#hotel_name_opt').val());
		var stars = new Array();
		var boards = new Array();
		var withPictures = $("#WithPictures").attr("checked");
		var advancedView = this.data['advancedView'];
		
		if (hotelName) {
			InnstantTracker.addEvent({act: 'hotel name search', val: hotelName});
		}
		
		$('input[name="stars[]"]').each(function(){
			if (this.checked) {
				stars.push(this.value);
			}
		});
		
		var starsCnt = stars.length;
		
		if (!$('#boards_all').attr('checked')) {
			$("#search_form_advance input[name='boards[]']").each(function(){
				if (this.checked) {
					boards.push(this.value);
				}
			});
		}
		
		var boardsCnt = boards.length;
		
		if (advancedView) {
			var providers = new Array();
			if (!$('#providers_all').attr('checked')) {
				$("#search_form_advance input[name='providers[]']").each(function(){
					if (this.checked) {
						providers.push(this.value);
					}
				});
			}
			
			var providersCnt = providers.length;
		}
		
		var facilities = new Array();
		$("input[name='facilityFamilies[]']").each(function(){
			if (this.checked) {
				facilities.push(this.value);
			}
		});
		var facilitiesCnt = facilities.length;
		var isFilter = facilitiesCnt || boardsCnt || (advancedView && providersCnt) || withPictures || hotelName || starsCnt || changePrice;
		if (isFilter) {
			$('#showAllhotels span:last').html(hotelsAll.length);
			$('#showAllhotels').css('display', 'block');
		} else {
			$('#showAllhotels').css('display', 'none');
		}
		
		var polyzone = $('#polyzone').val();
        
		try {
        opt = document.getElementById('polyzone').options;
        for(i=0;i<opt.length;i++) {
            if(opt[i].selected) {
                 opt[i].style.fontWeight = 'bold';
            } else {
                 opt[i].style.fontWeight = "normal";
            }
        }
		} catch(e) {
		}
        
        
		
		for (var i in hotelsAll) {
			var hotel = hotelsAll[i];
			var price = parseInt(hotel['room']['price']);
			
			if (polyzone && !in_array(polyzone, hotel['polyzoneid'])) {
				continue;
			}
			
			if (facilitiesCnt) {
				var filter = false;
				
				for (var j in facilities) {
					if (!in_array(facilities[j], hotel['Facilities'])) {
						filter = true;
						break;
					}
				}
				
				if (filter) {
					continue;
				}
			}
			
			if (boardsCnt) {
				var filter = true;
				
				for (var j in boards) {
					if (in_array(boards[j], hotel['boards'])) {
						filter = false;
						break;
					}
				}
				
				if (filter) {
					continue;
				}
			}
			
			if (advancedView && providersCnt) {
				var filter = false;
				
				for (var j in providers) {
					if (!in_array(providers[j], hotel['providers'])) {
						filter = true;
						break;
					}
				}
				
				if (filter) {
					continue;
				}
			}
 			
			if (withPictures) {
				if (0 !== hotel["image"].indexOf("http")) {
					continue;
				}
			}
			
			if (hotelName) {
				var reg = hotel_name_opt == 0 ? hotelName : (hotel_name_opt == 1 ? '^'+hotelName : '');
				if (reg) {
					reg = new RegExp(reg, "i");
					if (!reg.test(hotel['Name'])) {
						continue;
					}
				}
			}
			
			if (price < minPrice || price > maxPrice) {
				continue;
			} else if (starsCnt && !in_array(hotel['Stars'], stars)) {
				continue;
			}
			
			
			hotels.push(hotel);
		}
		
		this.pageActive = 1;
		this.filtered = hotels;
		this.direction = !this.direction;
		this.sorting(this.sortingType);
	}
	
,	map:
	{
		hotels: []		

	,	set: function()
		{
			var hotels = SearchPage.hotels;
			var hotelsCnt = hotels.length;
			SearchPage.map.hotels = [];
			
			if (hotelsCnt) {
				
				var displayedCnt = SearchPage.displayedCnt;
				var pageActive = SearchPage.pageActive;
				
				for (var i = (pageActive - 1) * displayedCnt; i < pageActive * displayedCnt; i++) {
					if (i >= hotelsCnt) {
						break;
					}
					
					var hotel = hotels[i];
					
					hotel['Latitude'] = parseFloat(hotel['Latitude']) ? parseFloat(hotel['Latitude']) : false;
					hotel['Longitude'] = parseFloat(hotel['Longitude']) ? parseFloat(hotel['Longitude']) : false;
					
					if (hotel['Latitude'] && hotel['Longitude']) {
						SearchPage.map.hotels.push({
							id: hotel['id']
						,	lat: hotel['Latitude']
		                ,   lng: hotel['Longitude']
		                ,	view: true
		                ,	html: JBobj.getMarkerHtml({name: hotel['Name'], address: hotel['Address'], price: hotel['room']['price'], stars: hotel['Stars'], link: '<a href="'+getLink('hotel/' + hotel['CountrySeoName'] + '/' + hotel['CitySeoName'] + '/' + hotel['SeoName'] + '/')+'">hotel info</a>'})
		                ,	Name: hotel['Name']
		                ,	Address: hotel['Address']
						});
					}
				}
			}
			
			if (SearchPage.map.hotels.length) {
				$("#map").gmap({
					markers : SearchPage.map.hotels
				,	control : 1
				});
			} else {
				$("#map").html("");
			}
		}
	},
	
	enlargeMap: function(hotelId)
	{
		$('#bigMapDialog').dialog('option','title','Map');
		var hotels = this.map.hotels;
		if (hotelId) {
			for (var i in hotels) {
				if (hotelId == hotels[i]['id']) {
					hotels = [hotels[i]];
					$('#bigMapDialog').dialog('option','title','Map - ' + hotels[0]['Name'] + ', address: ' + hotels[0]['Address']);
					break;
				}
			}
		}
		$('#bigMapDialog').dialog('open');
		if (hotels) {
			$('#bigMap').gmap({markers : hotels, control : 2});
		}
	},
	
	expandAll: function()
	{
        InnstantTracker.addEvent({act: 'expand all clicked'});
		var self = $('#topexpandall').get(0);
		var flag = $(self).html() == '[+] expand all';
		var html = flag?'[-] close all':'[+] expand all';
		$(self).html(html);
		$('#botexpandall').html(html);
		var hotels = this.hotels;
		var hotelsCnt = hotels.length;
		var displayedCnt = this.displayedCnt;
		var pageActive = this.pageActive;
		
		for (var key = (pageActive - 1) * displayedCnt; key < pageActive * displayedCnt; key++) {
			if (key >= hotelsCnt) {
				break;
			}
			
			var hotelId = hotels[key]['id'];
			$('#button_' + hotelId).html(flag?'[+] show rates':'[-] close');
			JBobj.expandHotel(hotelId, true);
		}
	},
	
	sortClick: function(sortType, nostop)
	{
		if (!nostop) {
			this.setStop();
		}
		sortType = parseInt(sortType);
		var type = '';
		switch (sortType) {
			case 0: type += 'Popularity'; break;
			case 1: type += 'Price'; break;
			case 2: type += 'Name'; break;
			case 3: type += 'Board'; break;
			case 4: type += 'Stars'; break;
			case 5: type += 'Guest Rating'; break;
			case 6: type += 'Distance'; break;
		}
		InnstantTracker.addEvent({act: 'sort by', val: type});
		$('#infoDialog').html('Sorting by ' + type + ' ...').dialog('open');
		setTimeout('SearchPage.sorting(' + sortType + ')', 100);
	},
	
	filterClick: function(noDialog, nostop)
	{
		if (!nostop) {
			this.setStop();
		}
		if (noDialog) {
			this.filter();
		} else {
			var message = 'Filtering results';
			$('#infoDialog').html(message + ' ...').dialog('open');
			setTimeout("SearchPage.filter(); JBobj.anchor('#head');", 100);
		}
	},
	
	setDistance: function()
	{
		var key;
		var hotel;
		var distance;
		var point2;
		var point1 = this.point;
		var hotels = this.filtered;
		for (key in hotels) {
			hotel = hotels[key];
			point2 = {'lat': hotel['Latitude'], 'lng': hotel['Longitude']};
			distance = getDistance(point1, point2);
			hotel['distance'] = distance;
			hotel['distanceView'] = JBobj.getDistanceView(distance);
			hotels[key] = hotel;
		}
		this.filtered = hotels;
	},
	
	addressNotDialog: function()
	{
		$.facebox('The requested address was not found.<br />Please modify your search and try again. <ul class="btn" style="width: 75px;"><li class="button4" onclick="$.facebox.close();"><span class="r"><span class="c">close</span></span></li></ul>', 'showup');
	},
	
	buildDistance: function()
	{
		if (this.point && this.point['id']) {
			$('#infoDialog').html('Get coordinates').dialog('open');
			$.post(
				'/index/getlandmarkdata/',
				{id:this.point['id']},
				function(data) {
					if (data.latitude || data.longitude) {
						SearchPage.point['lat'] = data.latitude;
						SearchPage.point['lng'] = data.longitude;
						SearchPage.point['type'] = 'lm';
						SearchPage.point['name'] = data.name;
						SearchPage.runBuildDistance();
					} else {
						$('#infoDialog').html('').dialog('close');
						SearchPage.addressNotDialog();
					}
				},
				'json'
			);
		} else {
			$('#landmarkAddress').focus();
		}
	},
	
	buildDistanceStreetaddress: function()
	{
		var Streetaddress = $.trim($('#Streetaddress').val());
		if (Streetaddress && Streetaddress != $('#Streetaddress').get(0).defaultValue) {
			$('#infoDialog').html('Get coordinates').dialog('open');
			var geocoder = new google.maps.Geocoder();
			var address = this.data['CountryName'] + ', ' + this.data['CityName'] + ', ' + Streetaddress;
			geocoder.geocode({'address': address}, function(results, status){
	            var point = false;
				if (status == google.maps.GeocoderStatus.OK) {
	                var coords = results[0].geometry.location;
	                var pointid = SearchPage.point && SearchPage.point['id'] ? SearchPage.point['id'] : '';
	                SearchPage.point = {};
	                SearchPage.point['id'] = pointid;
	                SearchPage.point['type'] = 'addr';
	                SearchPage.point['name'] = Streetaddress;
	                SearchPage.point['lat'] = coords.lat();
	                SearchPage.point['lng'] = coords.lng();
	                SearchPage.runBuildDistance();
	            } else {
	            	$('#infoDialog').html('').dialog('close');
	            	SearchPage.addressNotDialog();
	            }
	        });
		} else {
			$('#Streetaddress').focus();
		}
	},
	
	runBuildDistance: function()
	{
		this.setDistance();
		this.sortClick(6, 1);
	},
	
	getHotel: function(hotelId)
	{
		var
			hotels = this.hotels
		,	hotel = {}
		,	i = 0;
		for (i in hotels) {
			hotel = hotels[i];
			if (hotel['id'] == hotelId) {
				return hotel;
			}
		}
		return hotel;
	},
	
	getHotelsPerPage: function() {
		var res = [];
		var hotels = this.hotels;
		var hotelsCnt = hotels.length;
		var pageActive = this.pageActive;
		var displayedCnt = this.displayedCnt;

		for (var key = (pageActive - 1) * displayedCnt; key < pageActive * displayedCnt; key++) {
			if (key >= hotelsCnt) {
				break;
			}
			
			res.push(hotels[key]);
		}
		
		return res;
	},
	
	Hash:{
		selectors:{s:"input[name='stars[]']",b:"#search_form_advance input[name='boards[]']",f:"input[name='facilityFamilies[]']"},
		getParam:function() {
			var param = [];
			if (SearchPage.pageActive > 1) {
				param['p'] = [SearchPage.pageActive];
			}
			for (var i in this.selectors) {
				param[i] = [];
				$(this.selectors[i]).each(function(inx){
					if (this.checked) {
						var v = in_array(i,['b']) ? inx : parseInt(this.value);
						param[i].push(v);
					}
				});
			}
			
			var minp = $('#price_slider').slider('option', 'min');
			var maxp = $('#price_slider').slider('option', 'max');
			var tminp = $('#price_slider').slider('values', 0);
			var tmaxp = $('#price_slider').slider('values', 1);
			if (minp != tminp || maxp != tmaxp) {
				var usdrate2 = parseFloat($('#usdrate2').val());
				param['pr'] = new Array(Math.round(tminp*usdrate2),Math.round(tmaxp*usdrate2));
			}
			
			if (SearchPage.sortingType != 0) {
				param['o'] = [SearchPage.sortingType,SearchPage.direction ? 1 : 0];
			}
			
			return param;
		},
		set:function() {
			if (SearchPage.status == 'done' || SearchPage.stop) {
				var hash = '';
				var param = this.getParam();
				var com = false;
				for (var i in param) {
					if (param[i].length) {
						hash += (com?',':'')+i+':['+param[i]+']';
						com = true;
					}
				}
				window.location.hash = hash ? '{'+hash+'}' : '';
			}
		},
		get:function() {
			var hash = window.location.hash.replace('#','');
			if (hash && eval("typeof "+hash+" == 'object'")) {
				eval("hash = "+hash+";");
				return hash;
			}
			return false;
		}
	}
}











function timlog(p){
	var d=new Date();
	var s=':';
	var log='<p><b style="color:'+(p.f?'green;">start ':'red;">finish ')+p.a+'</b> '+d.getHours()+s+d.getMinutes()+s+d.getSeconds()+' ('+d.getMilliseconds()+'ms)</p>';
	$(log).appendTo('#timlog');
}
var SearchPage_Template =
{
	updateDialog:
	{
		dialog: function(Strings)
		{
			var html = Strings['More results are available']+'.<br />\
			'+Strings['Show updated results']+'?\
			<ul class="btn">\
				<li class="button n4" onclick="InnstantTracker.addEvent({act: \'update results final\'}); SearchPage.updatePage('+Strings['buf']+'); JBobj.anchor(\'#head\'); $.facebox.close();">\
					<div class="sprite b5 lt"></div>\
					<div class="elastic-x b5 cr">'+Strings['Yes']+'</div>\
					<div class="sprite b5 rt"></div>\
				</li>\
				<li class="button n4" onclick="$.facebox.close();">\
					<div class="sprite b5 lt"></div>\
					<div class="elastic-x b5 cr">'+Strings['No']+'</div>\
					<div class="sprite b5 rt"></div>\
				</li>\
			</ul>';
	
			return html;
		}
	},
	
	buildTable1:
	{
		top: function()
		{
			var html = '<table class="new-search_result searchtab">' +
			'<tbody>';
			
			return html;
		},
		
		item_top: function()
		{
			var html = '<tr>';
			return html;
		},
		
		// image
		item_image: function(data)
		{
			var html = '<td class="def image">' +
								'<a href="'+data['image_url']+'">' +
									'<img src="' + data["image"] + '" alt="' + data["Name"] + '" title="' + data["Name"] + '" />' +
								'</a>' +
							'</td>';
			return html;
		},
		
		// hotel name
		item_hotel_name: function(data)
		{
			var html = '<td class="def hotel-name">' +
						'<div class="inner">' +
							'<a onclick="JBobj.hotelClickEvent({name:\''+data['hotel_name']+'\',price:\''+data['formated_price']+'\'});" class="name" href="'+data['hotelUrl']+'">' +
								data['hotel_name'] +
							'</a>' +
							
							'<div class="hotelStarSmall" title="' + data['starsTitle'] + '"><span class="N' + data['starts']  + '"></span></div>' +
							
							'<div class="map">' +
								'<span class="kmfrom">' + data['Address'] + '</span>' +
								' ( <a onclick="SearchPage.enlargeMap('+data['hotelid']+');">map</a> )';
								if (data['hotel_distance'] && data['sortingType'] == 6) {
									html +=
									' <span class="distance">' + data['hotel_distanceView'] + ' from ' + data['point_name']  +'</span>';
								} else if (data["hotel_zone"]) {
									html +=
									'<p class="kmfrom">' +
										 ' in ' + data["hotel_zone"] +
									'</p>';
								} else if (data["hotel_LandmarkDistance"] && data["hotel_LandmarkName"]) {
									html +=
									'<p class="kmfrom">' +
										data["hotel_LandmarkDistance"] + ' from ' + data["hotel_LandmarkName"] +
									'</p>';
								}
								
								html +=
							'</div>';
							
							html +=
						'</div>';
					'</td>';
					
			return html;
		},
		
		// review
		item_hotel_review: function(data)
		{
			var html = 
					'<td class="def hotel-review">';
						
						if (data["hotel_review"]) {
							html += '<div class="review">' +
								'<div class="quote"></div>' +
								'<p>' + data["hotel_review"]["PlusText"] + '</p>' +
								'<a class="all" href="'+data["hotel_review_link"]+'">All Reviews</a>' +
								'<i>' + data["hotel_review"]["Name"] + '</i> ' + data["hotel_review"]["Date"] +
							'</div>';
							
						}
						
						if (data['GuestRating']) {
							html += '<a class="hotelRating" title="' + data["reviewsTitle"] + '" href="'+data['tripadivsorReview']+'">' +
								data['strings']['Guest rating'] +
								'<span class="hotelReviews"><span class="N' + data['RoundGuestRating'] + '"></span></span>' +
								'<span class="mtext">based on ' + data["hotel_ReviewsCnt"] + ' reviews</span>' +
							'</a>';
						} else {
							html += '<a class="hotelRating" title="be the first to review" href="'+data['reviews_url']+'">' +
								'<span><img src="/images/noreviews.png"></span>' + 
								'<span class="mtext">be the first to review</span>' +
							'</a>';
						}
						
						if (data['popularity'] >= 9) {
							html +=
							'<div class="thumb-up" onmouseover="$(\'#hotel_info_' + data['hotel_key'] + '\').show();" onmouseout="$(\'#hotel_info_' + data['hotel_key'] + '\').hide();" style="z-index: ' + data['z_index'] + '">' +
								'<div id="hotel_info_' + data['hotel_key'] + '" class="cvc-info">' +
									'<div class="cvc-info-top"></div>' +
		                            '<div class="cvc-text v2">' +
		                            	data["popularityText"] +
		                            '</div>' +
		                        '</div>' +
		                    '</div>';
						}
						
						if (data['use_room_board'] == 1) {
							html +=
							'<a class="breakfast" href="' + data['room_boardLink'] + '" title="' + data['room_boardTitle'] + '">' +
								data['room_board'] +
								' ' + data['room_boardText'] +
							'</a>';
						} else if (data['use_hotel_board'] == 1) {
							html +=
							'<a class="breakfast" title="'+data['strings']['This hotel offers various board options']+'">' +
								'<span class="sprite available board"></span> ' +
								data['hotel_boardText'] +
							'</a>';
						} else if (data['use_no_board'] == 1){
							html +=
							'<a class="breakfast" href="' + data['room_boardLink'] + '">' +
								data['strings']['None'] +
							'</a>';
						}
						
						if (!data["hotel_review"]) {
							html +=
							'<p class="strok bethefirst"><a href="'+data["hotel_reviews_page"]+'">'+data['strings']['Be the first']+'</a> '+data['strings']['to review this hotel']+'.</p>';
						}
						
					html +=
					'</td>';
					
			return html;
		},
		
		// price
		item_hotel_price: function(data)
		{
			var html = 
					'<td class="def price">';
					
						if (data['room_haspackage'] == 1)
						{
							html +=
							'<div class="both">' +
								'<span class="sum">' + data['currencySign'] + ' ' + data['room_minpackage'] + '</span><br />';
	
								html +=
							'<span class="incl-taxes">'+data['strings']['Minimum combination price']+'<br/>'+data['strings']['Incl. taxes & fees']+'</span></div>';
						}
						else
						{
							html +=
							'<div class="both">' +
								'<span class="sum">' + data['currencySign'] + ' ' + data['room_price'] + '</span><br />';
								if (data['viewId'] == 1) {
									html +=
									'<span class="num-nights"><b class="x">&times;</b> <b>' + data["cntDays"] + '</b> ' + (data['parsed_cntDays'] > 1 ? data['strings']['Nights'] : data['strings']['Night']) + '</span>';
								}
								html +=
							'</div>';
						}
						
						if (data['hotel_Special']) {
							html +=
							'<strong class="special-deal">'+data['strings']['Special Deal']+'!</strong>';
						}
						
						html +=
						'<a class="button4" href="'+data['hotel_link']+'">' +
							'<span class="r">' +
								'<span class="c">' +
									data['strings']['Book now']+'!' +
								'</span>' +
							'</span>' +
						'</a>';
						if (!data['is_city_search']) {
							html +=
							'<a class="search-more_details" onclick="JBobj.expandHotel(' + data['hotel_id'] + ', false,\'' + addslashes(data['hotel_name']) + '\')" id="button_' + data['hotel_id'] + '">[+] '+data['strings']['show rates']+'</a>';
						}
						html +=
					'</td>';
					
			return html;
		},
		
		// details
		item_hotel_details: function(data)
		{
			var html =
				'<tr>' +
					'<td class="expand" colspan="4">' +
						'<div class="search-hidden" id="rooms_block_' + data['hotel_id'] + '"></div>' +
					'</td>' +
				'</tr>';
				
			return html;
		},
		
		// No results
		item_hotel_no_results: function(data)
		{
			var html =
				'<tr>' +
			        '<th class="no-hotels">'+data['strings']['We are sorry, but there are no hotels available that match your search criteria']+'.<br />'+data['strings']['Please expand your search criteria to include more options and click the "search" button again']+'.</th>' +
			    '</tr>';
				
			return html;
		},
		
		item_bottom: function()
		{
			var html = '</tr>';
			return html;
		},
		
		bottom: function()
		{
			var html =
				'</tbody>' +
			'</table>';
			
			return html;
		}
	},
	
	buildTable:
	{
		// Search page items order
		element_order: function()
		{
			var order = [];
			order[0] = 0; // Images
			order[1] = 1; // hotel name
			order[2] = 7; // inner links
			order[3] = 2; // stars
			order[4] = 3; // breakfast
			order[5] = 4; // rating
			order[6] = 5; // price
			order[7] = 6; // inner links
			
			return order;
		},
		
		// Table top
		top: function(data)
		{
			var addClass = data['viewId'] == 8 && data['has_price_comparison'] ? ' pcmerge' : '';
			
			var html = '<table class="hotels searchtab'+addClass+'">';
			
			// Show sort table
			if (data['got_hotels']){
				html += data['SortTable'];
			}
			
			html += '<tbody>';
			
			return html;
		},
		
		// Sort view
		sortView: function (data)
		{
			var html =
				'<thead>' +
			 		'<tr class="title">' +
				 		'<th colspan="2" onclick="'+data['sort_by_name_click']+'">' +
				 			'<span class="essort" id="hotels-header_sort2">'+data['strings']['Name']+'<span class="sorts"></span></span>' +
				 		'</th>' +
						'<th onclick="'+data['sort_by_stars_click']+'">' +
				 			'<span class="essort" id="hotels-header_sort4">'+data['strings']['Stars']+'<span class="sorts"></span></span>' +
				 		'</th>' +
						'<th onclick="'+data['sort_by_board_click']+'">' +
				 			'<span class="essort" id="hotels-header_sort3">'+data['strings']['Board']+'<span class="sorts"></span></span>' +
				 		'</th>' +
						'<th onclick="'+data['sort_by_guest_rating_click']+'">' +
							'<span class="essort" id="hotels-header_sort5">'+data['strings']['Guest Rating']+'<span class="sorts"></span></span>' +
						'</th>' +
				 		'<th onclick="'+data['sort_by_price_click']+'">' +
				 			'<span class="essort" id="hotels-header_sort1">' + (data['is_city_search'] || data['viewId'] == 2 || data['viewId'] == 4 || data['viewId'] == 6 || data['viewId'] == 8 ? data['strings']['Price'] : data['strings']['Total Price']) + '<span class="sorts"></span></span>' +
				 		'</th>' +
				 		'<th></th>' +
					'</tr>' +
				'</thead>';
				
			return html;
		},
		
		// <tr> top
		item_top: function()
		{
			var html = '<tr class="res">';
			return html;
		},
		
		// image
		item_image: function(data)
		{
			var html = '<td class="images">' +
							'<a href="'+data['image_url']+'">' +
								'<img style="width: 67px; height: 55px;" src="' + data["image"] + '" alt="" title="' + data["Name"] + '" />' +
							'</a>' +
						'</td>';
						
			return html;
		},
		
		// hotel name
		item_hotel_name: function(data)
		{
			var html = 
						'<td class="westin">' +
							'<a onclick="'+data['hotel_click_event']+'" href="'+data['hotel_link']+'">' +
								data['hotel_Name'] +
							'</a>';
					
			return html;
		},
		
		// hotel inner links
		item_inner_links: function(data)
		{
				var html = '';
						if (data["hotel_distance"] && data["sortingType"] == 6) {
								html += '<span class="distance">' + data["hotel_distanceView"] + ' '+data['strings']['from']+' ' + data["point_name"]  +'</span>';
							} else if (data["hotel_zone"]) {
								html +=
								'<p class="kmfrom">' +
									' '+data['strings']['in']+' ' + data["hotel_zone"] +
								'</p>';
							} else if (data['hotel_LandmarkDistance'] && data['hotel_LandmarkName']) {
								html +=
								'<p class="kmfrom">' +
									data["hotel_LandmarkDistance"] + ' '+data['strings']['from']+' ' + data["hotel_LandmarkName"] +
								'</p>';
							}
							
							html +=
							'<ul class="hotel-pages strok">';
								if (data["is_city_search"] == false) {
									html +=
									'<li><a onclick="'+data["hotel_rates_click"]+'">'+data['strings']['Rates']+'</a></li>';
								}
								html +=
									'<li><a onclick="'+data["enlargeMap_click"]+'">'+data['strings']['Map']+'</a></li>' +
									'<li><a href="'+data["photos_link"] +'">'+data['strings']['Photos']+'</a></li>' +
									'<li'+(data['has_price_comparison']?'':' class="no-bg"')+'><a href="'+data["reviews_link"]+'">'+data['strings']['Reviews']+'</a></li>';
									if (data['has_price_comparison']) {
										html +=
										'<li class="no-bg"><a href="'+data["compare_link"] +'">'+data['strings']['Price Comparison']+'</a></li>';
									}
							'</ul>' +
						'</td>';
			
			return html;
		},
		
		// stars
		item_hotel_stars: function(data)
		{
			var html =
						'<td class="container-stars">' +
							'<div style="width: 70px; margin: 0px auto; '+(data['hotel_Popularity'] >= 9 ? 'margin-top:5px;' : 'height:37px;')+'">' +
								'<div class="hotelStarSmall" title="' + data["starsTitle"] + '"><span class="N' + data['hotel_Stars'] + '"></span></div>' +
							'</div>' +
						'</td>';
						
			return html;
		},
		
		// breakfast
		item_hotel_breakfast: function(data)
		{
			var html =
						'<td class="breakfast">';
							if (data['use_room_board']) {
								html +=
								'<a class="mtext" href="' + data['room_boardLink'] + '" title="' + data['room_boardTitle'] + '">' +
									data['room_board'] +
									' ' + data['room_boardText'] +
								'</a>';
							} else if (data['use_hotel_board']) {
								html +=
								'<a class="mtext" title="'+data['strings']['This hotel offers various board options']+'">' +
									'<span class="sprite available board"></span> ' +
									data['hotel_boardText'] +
								'</a>';
							} else {
								html +=
								'<a class="mtext" href="' + data['room_boardLink']  + '">' +
									data['strings']['None'] +
								'</a>';
							}
						html +=
						'</td>';
						
			return html;
		},
		
		// rating
		item_hotel_rating: function(data)
		{
			var html =
						'<td class="container-guest_rating">';
							if (data['hotel_Popularity'] >= 9) {
								html +=
								'<div style="width:30px;margin:0px auto;"><div class="thumb-up tiny" onmouseover="$(\'#hotel_info_' + data['record_num'] + '\').show();" onmouseout="$(\'#hotel_info_' + data['record_num'] + '\').hide();">' +
									'<img src="/images/thumb-up.png" width="25" alt="" />' +
									'<div id="hotel_info_' + data['record_num'] + '" class="cvc-info">' +
	                            		'<div class="cvc-text">' +
		                            		data["popularityText"] +
		                            	'</div>' +
		                        	'</div>' +
		                    	'</div></div>';
							}
							if (data['hotel_GuestRating']) {
								html +=
								'<a class="hotelRating" title="' + data['hotel_reviewsTitle'] + '" href="'+data['tripadvisor_link']+'">' +
									'<span class="hotelReviews"><span class="N' + Math.round(data['hotel_GuestRating']*2) + '"></span></span>' +
									'<span class="mtext">'+data['strings']['based on']+' ' + data['hotel_Reviews_Count'] + ' '+data['strings']['reviews']+'</span>' +
								'</a>';
							} else {
								html += '<a class="hotelRating" title="'+data['strings']['be the first to review']+'" href="'+data['reviews_link']+'">' +
									'<span><img src="/images/noreviews.png"></span>' + 
									'<span class="mtext">'+data['strings']['be the first to review']+'</span>' +
								'</a>';
							}
						html +=
						'</td>';
			
			return html;
		},
		
		// price
		item_hotel_price: function(data)
		{
			var html =
						'<td class="price">';
							if (data['room_price']) {
								
								if (data['haspackage'] == 1)
								{
									html += data['currencySign'] + ' ' + data['room_minpackage'];
									if (data['viewId'] == 2 || data['viewId'] == 4 || data['viewId'] == 6 || data['viewId'] == 8) {
										html +=
									'<br /><span class="num-nights"><b class="x">&times;</b> <b>' + data['days_count'] + '</b> '  + (parseInt(data['days_count']) > 1 ? data['strings']['Nights'] : data['strings']['Night']) + '</span>';
									}
									html +='<span class="incl-taxes">'+data['strings']['Minimum combination price']+'<br/>'+data['strings']['Incl. taxes & fees']+'</span>';
			
								}
								else
								{
									html += data['currencySign'] + ' ' + data['room_price'] ;
									if (data['viewId'] == 2 || data['viewId'] == 4 || data['viewId'] == 6 || data['viewId'] == 8) {
										html +=
									'<br /><span class="num-nights"><b class="x">&times;</b> <b>' + data['days_count'] + '</b> '  + (parseInt(data['days_count']) > 1 ? data['strings']['Nights'] : data['strings']['Night']) + '</span>';
									}
									html +=
									'<span class="incl-taxes">'+data['strings']['Incl. taxes & fees']+'</span>';
								}
							}
							else {
								html += '<span class="exclusive_prices">'+data['strings']['Exclusive prices!']+'</span>';
							}
						html += '</td>';
			
			return html;
		},
		
		// book now
		item_hotel_book_now: function(data)
		{
			var html =
						'<td class="container-button">';
							if (data['hotel_Special']) {
								html +=
								'<strong class="special-deal">'+data['strings']['Special Deal']+'!</strong>';
							}
							html +=
							'<a class="button4" href="'+data['book_now_link'] +'">' +
								'<span class="r">' +
									'<span class="c">' +
										data['strings']['Book now'] +
									'</span>' +
								'</span>' +
							'</a>';
							if (!data["is_city_search"]) {
								html +=
								'<div class="strok"><a class="search-more_details" onclick="'+data["expand_hotel_click"]+'" id="button_' + data["hotel_id"] + '">[+] '+data['strings']['show rates']+'</a></div>';
							}
							html +=
						'</td>';
						
					html +=
			'</tr>';
			
			if (data["viewId"] == 8 && data['has_price_comparison']) {
				var otherSites = PriceComparison.newView.get(data["hotel_data"]);
				if (otherSites) {html += otherSites;}
			}
		
			return html;
		},
		
		// room list
		item_hotel_room_list: function(data)
		{
			var html =
					'<tr>' +
						'<td class="container-search-hidden" colspan="7">' +
							'<div class="search-hidden" id="rooms_block_' + data["hotel_id"] + '"></div>' +
						'</td>' +
					'</tr>' +
					'<tr class="bord">' +
						'<td colspan="7"></td>' +
					'</tr>';
					
			return html;
		},
		
		// No results
		item_hotel_no_results: function(data)
		{
			var html =
				'<tr>' +
			        '<th class="no-hotels">'+data['strings']['We are sorry, but there are no hotels available that match your search criteria']+'.<br />'+data['strings']['Please expand your search criteria to include more options and click the "search" button again']+'.</th>' +
			    '</tr>';
			    
			return html;
		},
		
		// Close table
		bottom: function()
		{
			var html =
				'</tbody>' +
			'</table>';
			
			return html;
		}
	},
	
	buildNavigation:
	{
		// Start table
		top: function()
		{
			var html =
			'<div class="result-pages">' +
				'<span class="showing-results" id="showingInfo-bottom"></span>' +
				'<div class="fright" style="padding-right: 5px;">';
			
			return html;
		},
		
		// Start table
		bottom: function()
		{
			var html =
				'</div>' +
			'</div>';
			
			return html;
		},
		
		// Previous
		previous_page: function(data)
		{
			var html =
						'<span class="bkn" onclick="SearchPage.navigationClick(' + data["back_link"] + ');">&lt;'+data['strings']['Previous']+'</span> ';
			
			return html;
		},
		
		// Click-able page
		clickable_page: function(data)
		{
			var html =
						'<span onclick="SearchPage.navigationClick(' + data['page'] + ');">' + data['page'] + '</span>';

			return html;
		},
		
		// Active page
		active_page: function(data)
		{
			var html =
						'<span class="active">' + data['page'] + '</span>';

			return html;
		},
		
		// Active page
		next_page: function(data)
		{
			var html =
						' <span class="bkn" onclick="SearchPage.navigationClick(' + data["next_link"] + ');">'+data['strings']['Next']+'&gt;</span>';

			return html;
		}
	}
}

