var lastRadioBox = '';
var checking =0;

function getAjaxQueue() {
	var checkin = $('#checkin').val();
	var checkout = $('#checkout').val();

	var district_id = document.getElementById('district_id').value;	  
    var currencyBox = $('#currency option:selected').val();
  	// var currencyBox = $('#currency').val();
	var currency = currencyBox.split(',');
	var currencyRate = currency[0];
	var currencyCode = currency[1];
	var district_id = $('#district_id').val();

	if (!district_id) district_id = 0;	 
	else if (district_id == -1) district_id = 0;	

	  RatesProgress.qTimes = parseInt(RatesProgress.qTimes + 1);
      var requestURL = '/ajax/bestrate/' + checkin + '/' + checkout + '/'+ RatesProgress.qTimes;
        requestURL+= '/' + currencyCode +'/' + district_id;

	RatesProgress.ajaxCall = true;
	$.ajax({
		url: requestURL,
		type: 'GET',
		dataType : 'json',
		async: true,  
		success : function(json) {
			RatesProgress.setAjax(json);
		}
	});

	var uHotels =  RatesProgress.qTimes * 15;	

//	alert(RatesProgress.total);	
//	var text = "Updating ( " + uHotels + " / " + total + " Hotels)";	
//	alert(RatesProgress.fnRecordsTotal() + " " + RatesProgress.fnRecordsDisplay() );
//	$('#uHotel').html(uHotels);
//	$('#totalHotel').html(RatesProgress.total);

}

var RatesProgress = {
	processed : [],
	total : 0,
	qTimes : 0,
	isDone : false,
	ajaxCall : false,	
	run : function() {
 		
		if(navigator.appName=="Microsoft Internet Explorer"){
			setTimeout('getAjaxQueue()', 700);
		}else{
			getAjaxQueue();
		}

		return;

	},
	recheck : function() {
		var oTable = $('#hotels').dataTable();
		var oSettings = oTable.fnSettings();

		var pageLength = $('select.page_length option:selected').val();
		if (this.processed.length <= (pageLength+1)) {
			oTable.fnStandingRedraw();
		}

		var iMax = oSettings.fnRecordsTotal();
		var iTotal = 15 * this.qTimes;
		
		if (iTotal > iMax) iTotal = iMax; 
		
		document.getElementById('uHotel').innerHTML = iTotal+" / "+ iMax + "&nbsp;";

		this.run();
		return;

	},
	setAjax : function(ratesData) {

		var oTable = $('#hotels').dataTable();
		var oSettings = oTable.fnSettings();

		if (ratesData == null) {
			checking=0;
			//RatesProgress.callBack= 0;
			oTable.fnStandingRedraw();
			
			document.getElementById('currency').disabled = false;
			document.getElementById('pageloading').style.display = "none";	
			document.getElementById('searchresults').style.display = "";				

			return;
		}

		var dataLen = ratesData.length;

		for ( var i = 0; i < dataLen; i++) {
			var hotelData = ratesData[i];
			var hotelID = hotelData.hotel_id;

			this.processed.push(hotelID);

			var rowIndex = parseInt(oTable.fnFindCellRowIndexes(hotelID, 1));
			
			oTable.fnDataUpdate(hotelData, rowIndex, 6);
			this.tableSettings = oSettings;
		}
		this.recheck();

		return;
	}
};

/*
 * Filter functions
 */

$.fn.dataTableExt.afnFiltering.push(function(oSettings, aData, iDataIndex) {
	var isChecked = $('input:radio[name="radio"]:checked').val();
	if (isChecked != 'bestbuy') {
		return true;
	}
	
	var type = aData[2];
	if (type == 'e') {
		return false;
	} 
	
	return true;
});

$.fn.dataTableExt.afnFiltering.push(function(oSettings, aData, iDataIndex) {
	var priceIndex = 6;
	var roomPrice = aData[priceIndex];

	if (roomPrice < 0) {
		return false;
	}

	return true;
});

/*
 * API functions
 */

$.fn.dataTableExt.oApi.fnDataUpdate = function(oSettingsInstance, aData,
		iRowIndex, iColumnIndex) {
	
	if (iRowIndex == undefined) {
		return;
	}
	
	var currRow = oSettingsInstance.aoData[iRowIndex];
	if (currRow == undefined) {
		return;
	}

	var dataRow = currRow._aData;
	
	switch (iColumnIndex) {
	case 6:
		if (aData != undefined) {
			hotelBox = $('<div/>').html(dataRow[7]);
			
			var roomPrice = Math.floor(aData.price);
			if (roomPrice < 1) {
				roomPrice = -1;
			}
			dataRow[iColumnIndex] = roomPrice;

			if (roomPrice < 1) {
				hotelBox.find('.p_name').hide();
				hotelBox.find('.h_price_curr').hide();
				hotelBox.find('.h_price').text('N/A');
				hotelBox.find('.h_price2').text('N/A');
			} else {
				var currencyBox = $('#currency option:selected').val();
				//var currencyBox = $('#currency').val();
				var currency = currencyBox.split(',');
				var currencyRate = currency[0];
				var currencyCode = currency[1];
				var promo_name = aData.promo_name;

				hotelBox.find('.p_name').text(promo_name);
				hotelBox.find('.h_price_curr').text(currencyCode);
				hotelBox.find('.h_price').text(roomPrice);
				hotelBox.find('.h_price2').text(roomPrice);
				
				var roomSelling = aData.selling_price;
				if (roomSelling > 0) {
					if (roomSelling == roomPrice) {
						hotelBox.find('.p_selling_box').hide();
					} else {
						hotelBox.find('.h_selling_curr').text(currencyCode);
						hotelBox.find('.h_selling').text(roomSelling);
						hotelBox.find('.h_selling2').text(roomSelling);
						dataRow[9] = (roomSelling-roomPrice);
					}
				} else {
					hotelBox.find('.p_selling_box').hide();
				}				
				
			}



			dataRow[7] = hotelBox.html();
			
			//var hotelID = aData.hotel_id;
			//var dispBox = $('#hotel_' + hotelID);
			//if (dispBox.html() != null) {
			//	dispBox.html(hotelBox.html());
			//}
			
		}
		break;
	}
}

$.fn.dataTableExt.oApi.fnPageLengthUpdate = function(oSettings, sLength) {
	/* Redraw the table */
	oSettings._iDisplayLength = parseInt(sLength, 10);
	oSettings.oApi._fnCalculateEnd(oSettings);

	if (oSettings.fnDisplayEnd() == oSettings.fnRecordsDisplay()) {
		oSettings._iDisplayStart = oSettings.fnDisplayEnd()
				- oSettings._iDisplayLength;
		if (oSettings._iDisplayStart < 0) {
			oSettings._iDisplayStart = 0;
		}
	}

	if (oSettings._iDisplayLength == -1) {
		oSettings._iDisplayStart = 0;
	}

	oSettings.oApi._fnDraw(oSettings);
};

$.fn.dataTableExt.oApi.fnFindCellRowIndexes = function(oSettings, sSearch,
		iColumn) {
	var i, iLen, j, jLen, aOut = [], aData;

	for (i = 0, iLen = oSettings.aoData.length; i < iLen; i++) {
		aData = oSettings.aoData[i]._aData;

		if (typeof iColumn == 'undefined') {
			for (j = 0, jLen = aData.length; j < jLen; j++) {
				if (aData[j] == sSearch) {
					aOut.push(i);
				}
			}
		} else if (aData[iColumn] == sSearch) {
			aOut.push(i);
		}
	}

	return aOut;
}

$.fn.dataTableExt.oApi.fnStandingRedraw = function(oSettings) {
	//alert(checking);
   if(checking==0)
   {
	if (oSettings.oFeatures.bServerSide === false) {
		var before = oSettings._iDisplayStart;
			
		oSettings.oApi._fnReDraw(oSettings);
		oSettings._iDisplayStart = before;
		oSettings.oApi._fnCalculateEnd(oSettings);
	}
	// draw the 'current' page
	oSettings.oApi._fnDraw(oSettings);
	checking++;
   }
};

$.fn.dataTableExt.oPagination.extStyle = {
	"fnInit" : function(oSettings, nPaging, fnCallbackDraw) {
		nPaging.innerHTML = '';

		$('.paginate_button .first').click(function() {
			if (oSettings.oApi._fnPageChange(oSettings, "first")) {
				fnCallbackDraw(oSettings);
				$(document).scrollTop($("#pageNationButton").position().top);	
				
			}
		}).bind('selectstart', function() {
			return false;
		});

		$('.paginate_button .previous').click(function() {
			if (oSettings.oApi._fnPageChange(oSettings, "previous")) {
				fnCallbackDraw(oSettings);
				$(document).scrollTop($("#pageNationButton").position().top);	
			}
		}).bind('selectstart', function() {
			return false;
		});

		$('.paginate_button .next').click(function() {
			if (oSettings.oApi._fnPageChange(oSettings, "next")) {
				fnCallbackDraw(oSettings);
				$(document).scrollTop($("#pageNationButton").position().top);	
			}
		}).bind('selectstart', function() {
			return false;
		});

		$('.paginate_button .last').click(function() {
			oSettings.oApi._fnPageChange(oSettings, "last");
			fnCallbackDraw(oSettings);
			$(document).scrollTop($("#pageNationButton").position().top);	
		}).bind('selectstart', function() {
			return false;
		});
	},

	"fnUpdate" : function(oSettings, fnCallbackDraw) {
		if (!oSettings.aanFeatures.p) {
			return;
		}

		var iStart = oSettings._iDisplayStart + 1, 
		iEnd = oSettings.fnDisplayEnd(), 
		iMax = oSettings.fnRecordsTotal(), 
		iTotal = oSettings.fnRecordsDisplay(), 
		sStart = oSettings.fnFormatNumber(iStart), 
		sEnd = oSettings.fnFormatNumber(iEnd), 
		sMax = oSettings.fnFormatNumber(iMax), 
		sTotal = oSettings.fnFormatNumber(iTotal);
		
		RatesProgress.total = oSettings.fnRecordsTotal();

		$(".paginate_button .pageStartNum").html(sStart);
		$(".paginate_button .pageEndNum").html(sEnd);
		$(".paginate_button .pageTotalNum").html(sTotal);
		$(".paginate_button .pageMaxNum").html(sMax);

		var iPageCount = $.fn.dataTableExt.oPagination.iFullNumbersShowPages;
		var iPageCountHalf = Math.floor(iPageCount / 2);
		var iPages = Math.ceil(oSettings.fnRecordsDisplay() / oSettings._iDisplayLength);
		var iCurrentPage = Math.ceil(oSettings._iDisplayStart / oSettings._iDisplayLength) + 1;
		var sList = "";
		var iStartButton, iEndButton, i, iLen;
		var oClasses = oSettings.oClasses;

		/* Pages calculation */
		if (iPages < iPageCount) {
			iStartButton = 1;
			iEndButton = iPages;
		} else {
			if (iCurrentPage <= iPageCountHalf) {
				iStartButton = 1;
				iEndButton = iPageCount;
			} else {
				if (iCurrentPage >= (iPages - iPageCountHalf)) {
					iStartButton = iPages - iPageCount + 1;
					iEndButton = iPages;
				} else {
					iStartButton = iCurrentPage - Math.ceil(iPageCount / 2) + 1;
					iEndButton = iStartButton + iPageCount - 1;
				}
			}
		}

		for (i = iStartButton; i <= iEndButton; i++) {
			if (iCurrentPage != i) {
				sList += '<span class="af ' + oClasses.sPageButton + '">' + i + '</span>';
			} else {
				sList += '<span class="af ' + oClasses.sPageButtonActive + '">' + i + '</span>';
			}

			sList += '&nbsp;';
		}
		$('.paginate_button .numbers').html(sList);

		$('.paginate_button .numbers span').click(function() {
			var iTarget = (this.innerHTML * 1) - 1;
			oSettings._iDisplayStart = iTarget * oSettings._iDisplayLength;
			$(document).scrollTop($("#pageNationButton").position().top);	
			fnCallbackDraw(oSettings);
		});
	}
};

function updateSortingFilter(savedSort) {
	// Update sorting select box
	savedSort.reverse();
	$.each(savedSort, function(index, item) {
		var field = '';
		var radio = '';
		var value = item[1];
		
		switch(item[0]) {
		case 3 : 
			radio = 'stars';
			field = '#stars_sorting';
			break;
		case 6 : 
			radio = 'price';
			field = '#price_sorting';
			break;
		case 8 : 
			radio = 'guest';
			field = '#guest_rating';
			break;
		case 9 : 
			radio = 'price';
			field = '#price_sorting';
			value = 'promo';
			break;
		}
	
		if (field != '') {
			$('input:radio[name="radio"][value="'+radio+'"]').attr('checked', 'checked');
			$(field+' option[value="'+value+'"]').attr('selected', 'selected');
			$(field).parent().show();
			
			lastRadioBox = radio;
		}
	}); 
}

function updateSorting() {
	var checkedChild = $("input[name='radio']:radio:checked");
	var checkedValue = checkedChild.val();
	var selectedChild = checkedChild.parent().parent().find('select');
	var selectedValue = $('option:selected', selectedChild).val();
	var sortOrder = [];
	
	switch(checkedValue) {
		case 'bestbuy'	:
			checking=0;
			$('#hotels').dataTable().fnStandingRedraw();
			break;
		case 'price'    : 
			if (selectedValue == 'promo') {
				sortOrder = [[9, 'desc'], [ 6, 'asc']];
			} else {
				sortOrder.push([6, selectedValue]);
			}
			break;
		case 'stars'    : 
			sortOrder.push([3, selectedValue]);
			break;
		case 'guest'	 : 
			sortOrder.push([8, selectedValue]);
			break;
	}
	
	if (selectedChild != null) {
		if (lastRadioBox == '') {
			lastRadioBox = checkedValue;
		}
		
		var lastRadio = $("input:radio[name='radio'][value='"+lastRadioBox+"']").parent().parent();
		var lastRadioOrder = $('.order_box', lastRadio);
		if (lastRadioOrder != null) {
			lastRadioOrder.parent().hide();
		}
		
		lastRadioBox = checkedValue
		selectedChild.parent().show();
	}
	
	if (sortOrder.length > 0) {
		$('#hotels').dataTable().fnSort(sortOrder); 
	}
}

function delayIdle() {
	
}

function startLoading() {						   
	$('#checkin').datepicker({
		buttonImage : '/images/btn_cal.jpg',
		buttonImageOnly : true,
		firstDay : 1,
		dateFormat : 'yy-mm-dd',
		gotoCurrent : true,
		minDate : 0,
		maxDate : '+2y',
		changeMonth : true,
		changeYear : true,
		closeText : 'X',
		showOn : 'both',
		showButtonPanel : false,
		yearRange : 'c-2:c+2',
		beforeShow : function(input, inst) {
			inst.dpDiv.css({
				marginTop : -input.offsetHeight + 'px',
				marginLeft : (input.offsetWidth + 27) + 'px'
			});
		},
		onClose : function(dateText, inst) {
			var startDate = $('#checkin').val();
			var mdy = startDate.split('-');

			var endDate = new Date(mdy[0], mdy[1] - 1, Math.round(mdy[2]) + 2);
			$('#checkout').datepicker("setDate", endDate);

			var minDate = new Date(mdy[0], mdy[1] - 1, Math.round(mdy[2]) + 1);
			$('#checkout').datepicker("option", "minDate", minDate);
		}
	});
	
	$('#checkout').datepicker({
		buttonImage : '/images/btn_cal.jpg',
		buttonImageOnly : true,
		firstDay : 1,
		dateFormat : 'yy-mm-dd',
		gotoCurrent : true,
		minDate : 0,
		maxDate : '+2y',
		changeMonth : true,
		changeYear : true,
		closeText : 'X',
		showOn : 'both',
		showButtonPanel : false,
		yearRange : 'c-2:c+2',
		beforeShow : function(input, inst) {
			inst.dpDiv.css({
				marginTop : -input.offsetHeight + 'px',
				marginLeft : (input.offsetWidth + 27) + 'px'
			});
		}
	});

	$('#hotels').dataTable({
		"aaSorting" : [[ 0, "asc" ]],
		"bPaginate" : true,
		"bInfo" : true,
		"bStateSave" : true,
		"sCookiePrefix": "",
		"fnStateLoadCallback": function ( oSettings, oData ) {
			oData.sFilter = "";
			updateSortingFilter(oData.aaSorting.slice());
			return true;
		},
		"sDom" : '<tp><r>',
		"sPaginationType" : "extStyle",
		// "sPaginationType" : "full_numbers",
		// "bServerSide" : true,
		// "sAjaxSource" : "/ajax/list",
		// "fnServerData" :
		// fnHotelRatesPipeline,
		/*
		 * "fnDrawCallback" :
		 * function(oSettings) { } ,
		 */

		// "sDom" : 'pr',
		"aoColumns" : [
			{"sType" : "numeric", "sSortDataType": "dom-text" }, 
			{"sType" : "numeric", "sSortDataType": "dom-text" },
			{"sType" : "string", "sSortDataType": "dom-text" },
			{"sType" : "numeric", "sSortDataType": "dom-text" },
			{"sType" : "string", "sSortDataType": "dom-text" },
			{"sType" : "string", "sSortDataType": "dom-text" },
			{"sType" : "numeric", "sSortDataType": "dom-text" },
			{"sType" : "string", "bSearchable" : true},
			{"sType" : "numeric", "sSortDataType": "dom-text" },
			{"sType" : "numeric", "sSortDataType": "dom-text" }],
		"fnRowCallback" : function(nRow, aData,iDisplayIndex,iDisplayIndexFull) {
			
			if (!RatesProgress.ajaxCall) return nRow;
			
			var dispIndex = 7;

			var newDisp = $('<div/>').html(aData[dispIndex]);
			
			var roomPrice = aData[6];
			if (roomPrice > 0) {
				// Save net price value
				
				var currency = document.getElementById('currency').value;
				var currency_new = currency.split(',');
				var select_currency = document.getElementById('select_currency').value;
			
				aData[6]	= roomPrice;
				
				// Calculate selected currency value
				roomPrice = Number(currency_new[0])*roomPrice/Number(select_currency);
		
				newDisp.find('.h_price_curr').text(currency_new[1]);
				newDisp.find('.h_price').text(Math.floor(roomPrice));
				
				if (newDisp.find('.thumbnail img').attr('src') == '') {
					var hotel_thumb = newDisp.find('.thumbnail img').attr('o_src');
					newDisp.find('.thumbnail img').attr('src', hotel_thumb);
					newDisp.find('.thumbnail').parent().show();
				}
				
				var roomSelling = Number(newDisp.find('.h_selling2').text());
				if (roomSelling > 0) {
				// Calculate selected currency value
					roomSelingCurr = Number(currency_new[0])*roomSelling/Number(select_currency);
				
					newDisp.find('.h_selling_curr').text(currency_new[1]);
					newDisp.find('.h_selling').text(Math.floor(roomSelingCurr));
				//	aData[dispIndex] = newDisp.html();
				}
				
				aData[dispIndex] = newDisp.html();
				
				var display = nRow.getElementsByTagName('td')[dispIndex].innerHTML;
				if (display != aData[dispIndex]) {
					nRow.getElementsByTagName('td')[dispIndex].innerHTML = aData[dispIndex];
				}
				
			}

			
			
			return nRow;
		},
		"fnInitComplete" : function() {
			//alert("fnInitComplete")
			//this.fnStandingRedraw();
			//RatesProgress.init(hotels);
			RatesProgress.run();

//			$('#hotels').dataTable().fnFilter($('#searchFilter').val());
			//$('#hotels').dataTable().fnSort([[0, 'asc']]);
			//updateSorting();
		}
	});

	var oTable = $('#hotels').dataTable();
	var oSettings = oTable.fnSettings();

	$('#searchFilter')
		.keyup(function() {
			var keywords = $(this).val();
			if (keywords == '') {
				return;
			}
			$('#hotels').dataTable().fnFilter(keywords);
		}).blur(function() {
			if ($(this).val() == '') {
				$('#hotels').dataTable().fnFilter('');
			}
		});

	$('select.page_length').change(function() {
		$('select.page_length').val($(this).val());
		$('#hotels').dataTable().fnPageLengthUpdate($(this).val());
	});

	$("input[name='radio']:radio").change(function() {
		return updateSorting();
	});

	$(".order_box").change(function() {
		var selectedChild = this;
		var selectedName = this.name;
		var selectedValue = $('option:selected', selectedChild).val();
		var sortOrder = [];
		var radioField = '';
		
		switch(selectedName) {
			case 'price_sorting'    :
				if (selectedValue == 'promo') {
					sortOrder = [[9, 'desc'], [ 6, 'asc']];
				} else {
					sortOrder.push([6, selectedValue]);
				}
				radioField = 'price';
				break;
			case 'stars_sorting'    : 
				sortOrder.push([3, selectedValue]);
				radioField = 'stars';
				break;
			case 'guest_rating'	: 
				sortOrder.push([8, selectedValue]);
				radioField = 'guest';
				break;
			break;
		}
		
		if (sortOrder.length>0) {
			$('#hotels').dataTable().fnSort(sortOrder);
			$("input:radio[name='radio'][value='"+radioField+"']").attr('checked', 'checked');
		}
	});
}

function updateRate() {
	
	checking=0;
	updateSession();
	 $('#hotels').dataTable().fnStandingRedraw(); 
          chgdeal();
}

$(window).load(function() {
	$.ajax({
		url: '/ajax/updateRatio2',
		cache: false,
		async: true,  
		success: function(response) {
			$('#currency_list2').html(response);
			document.getElementById('initloading').style.display = "none";				
			document.getElementById('pageloading').style.display = "";	
			document.getElementById('searchresults').style.display = "none";
			startLoading();
                              chgdeal();
		}
   });
});

 

