// JavaScript Document
var initialPricesMaxPricePPH;
var initialPricesMinPricePPH;
var initialPricesMaxPrice;
var initialPricesMinPrice;
var initialPriceSliderYachtResults = null;


$(document).ready(function(){
	
	/**
	 * Check whether the price slider exists because the "By Yacht" tab doesn't have one
	 * and this code will fail if it is not able to locate the list.
	 *
	 * Author: peterl
	 */
	if ($('#rblCurrencyCode').length > 0) {
		// Check to see if a default currency is used in the cookie
		var currency_code_id = 3;
		if(_getCookie('currency_code_id_preferred')!=null){
			currency_code_id = _getCookie('currency_code_id_preferred');
		}
		
		/** @todod - because this code does not work correctly with my accoutn section we have to refactore this a little bit **/
		//$('#rblCurrencyCode').val(currency_code_id);
		  
		var currency_code_id = $('#rblCurrencyCode').val();
		var currency_code  = $('#rblCurrencyCode :selected').attr('title').toLowerCase();
//		initializePriceSlider($("#currency_select_" + currency_code_id), currency_code);
		
		$('#rblCurrencyCode').multiselect({
			multiple: false,
			noneSelectedText: 'Curr',
			header: false,
			height: 'auto',
			//minWidth: 'auto'
			minWidth: 90
		});
		var currentCurrency = $('#rblCurrencyCode').val();
		$('#rblCurrencyCode').bind("multiselectclick", function(event, ui){
			var value;
			for(var i = 0; i < $('#rblCurrencyCode').multiselect("getChecked").length; i++) {
				value = $('#rblCurrencyCode').multiselect("getChecked")[i].value;	
				$( '#rblCurrencyCode option[value="'+value+'"]' ).get(0).selected = true;
				$('#rblCurrencyCode').multiselect({ selectedText: $( '#rblCurrencyCode option[value="'+value+'"]' ).text() });
				break;
			}
			$('#rblCurrencyCode').multiselect("close");
			if( currentCurrency !=  $('#rblCurrencyCode').val() ) { 
				$('#rblCurrencyCode').trigger('change'); 
				currentCurrency = null;
			}
		});
		
		$('#rblCurrencyCode').change(function(e, type){
			$('.search_form_stats a.button.complete').hide();
			$('.search_form_stats a.button.search').show();
			initialPriceSliderYachtResults = parseInt( $('#total_count span:first').text() ); 
			
			if( type != 'initial' ) setTimeout("refreshSearchResults(this, 'currency');", 250);
			$.cookie('currency_code_id_preferred', currency_code_id, { path: '/', expires: 365 });
		})
		$('#rblCurrencyCode').trigger('multiselectclick');
		
		
		/** switch between values in different currencies **/
		$('.price_search_type_radio, .price_search_type_labels').click(function(){
			$('.budget_quest').show();
			$('.search_form_stats a.button.complete').hide();
			$('.search_form_stats a.button.search').show();
			$('.price_search_type_radio').removeClass('error');
			currency_code_id = $('#rblCurrencyCode').val();
			currency_code = $('#rblCurrencyCode :selected').attr('title').toLowerCase();
			initializePriceSlider($("#currency_select_" + currency_code_id), currency_code);
			/**
			 * Save currency in a cookie to set this currency as a default one.
			 * 
			 * Author: waldemar.matlosz
			 */
			 $.cookie('currency_code_id_preferred', currency_code_id, { path: '/', expires: 365 });
		});
		initializePriceSlider();
	}
	
});


function formatNumber(v){
	var val = parseInt( v ).toString();
	var result = "";
	var len = val.length;
	while (len > 3){
		result = ","+val.substr(len-3,3)+result;
		len -=3;
	}
	return val.substr(0,len)+result;
}

function searchPriceArrays( pricesList, price ) {
	//TODO: optimize the array search
	try {
		var arrLength = pricesList.length;
		var prevPoint = 0;
		if( price > parseInt( pricesList[ arrLength - 1 ].price ) ) return pricesList[ arrLength - 1 ].count; 
		if( price < parseInt( pricesList[ 0 ].price ) ) return 0;
//		console.log('looking for: ' + price);
		for(var i = 0; i < arrLength; i++) {
//			console.log( pricesList[ i ] );
			if( pricesList[ i ].price < price ) continue;
			else if( parseInt( pricesList[ i ].price ) == price ) {
				if( pricesList[ i ].price == pricesList[ i + 1 ].price ) continue;
				return pricesList[ i ].count
			} else return pricesList[ i - 1 ].count;
		}
		return 0;
		var initPoint = parseInt( arrLength / 2 );
		var intoSmaller = false, intoBigger = false;
		do {
			if( pricesList[ initPoint ].price < price ) {
				intoSmaller = true;
				var tmp = initPoint;
				initPoint += parseInt( ( arrLength - initPoint ) / 2 );
				prevPoint = tmp;
			} else if( pricesList[ initPoint ].price > price ) {
				intoBigger = true;
				initPoint = parseInt( initPoint - ( initPoint - prevPoint ) / 2  );
			} else {
				return pricesList[ initPoint ].count;
				break;
			}
			if( prevPoint == initPoint ){ 
				if( pricesList[ initPoint ].price >= price ) return pricesList[ initPoint ].count;
				return 0;
			}
		} while(1);
	} catch ( e ) { return 0; }
	
}
function searchPriceArraysReverse( pricesList, results ) {
	//TODO: optimize the array search
	try {
		var arrLength = pricesList.length;
		var prevPoint = 0;
		if( results >= pricesList[ arrLength - 1 ].count ) return pricesList[ arrLength - 1 ].price; 
		if( results <= pricesList[ 0 ].count ) return pricesList[ 0 ].price;
//		console.log('looking for: ' + price);
		for(var i = 0; i < arrLength; i++) {
//			console.log( pricesList[ i ] );
			if( pricesList[ i ].count < results );
			else if( pricesList[ i ].count == results ) return pricesList[ i ].price;
			else return pricesList[ i - 1 ].price;
		}
		return 0;
	} catch ( e ) { return null; }
}

function initializePriceSlider(context, selected_currency_code){
	
	if( $('.price_search_type_radio:checked').val() == 1 ) {
		$('.budget_quest_pph').hide();
		$('.budget_quest_pw').show();
		$('.price_range_selected').show();
		$('.inputField.pph_description').hide();
		$("#price_range_slider_pph").slider( "destroy" );
		$("#price_range_slider_pph").html('');
		$("#price_range_slider_pph").hide();
		$("#price_range_slider").show();
		
		var min = initialPricesMinPrice ? initialPricesMinPrice : 1000;
		var max = initialPricesMaxPrice && initialPricesMaxPrice <= 850000 ? initialPricesMaxPrice : 850000;
		if( min % 10000 > 0 ) min += 10000 - ( min % 10000 );
		$('#price_scale_bottom span.replace_text').text(  $('#rblCurrencyCode option:selected').attr('symbol') + ' ' + formatNumber( min ) );
		$('#price_scale_top span.replace_text').text(  $('#rblCurrencyCode option:selected').attr('symbol') + ' ' + formatNumber( max ) );
		if( initialPriceSliderYachtResults != null && initialPriceSliderYachtResults > 0 ) {
			var initialValue = searchPriceArraysReverse(yachtPricesList, initialPriceSliderYachtResults);
			initialValue += 50 - initialValue % 50;
		} else if( $('#max_price_search').val() ) {
			var initialValue = $('#max_price_search').val(); 
		} else {
			var initialValue = min;
		}
		
		$("#price_range_slider").slider({
			disabled: !( yachtPricesList && yachtPricesList.length > 0 ),
			min: min,
			max: max,
			step: 10000,
			values: [ initialValue ],
			slide: function( event, ui ) {
				$('.search_form_stats a.button.complete').hide();
				$('.search_form_stats a.button.search').show();
				if( ui.values[ 0 ] < 850000 ) {
					$('#max_price_search').val( ui.values[ 0 ] );
					$('#price_id_min_value').text( $('#rblCurrencyCode option:selected').attr('symbol') + ' ' + formatNumber( ui.values[ 0 ] ) );
				} else { 
					$('#max_price_search').val( 9999999999 );
					$('#price_id_min_value').text( 'all' + ' *' );
				}
				
				var count =  searchPriceArrays( yachtPricesList, parseInt( $('#max_price_search').val() ) );
				setUpYachtsResultNumber( count );
			},
			stop: function( event, ui ) {
				if( ui.values[ 0 ] < 850000 ) {
					$('#max_price_search').val( ui.values[ 0 ] );
					$('#price_id_min_value').text( $('#rblCurrencyCode option:selected').attr('symbol') + ' ' + formatNumber( ui.values[ 0 ] ) );
				} else { 
					$('#max_price_search').val( 9999999999 );
					$('#price_id_min_value').text( 'all' );
				}
				
				var count =  searchPriceArrays( yachtPricesList, parseInt( $('#max_price_search').val() )  );
				setUpYachtsResultNumber( count );
				//setTimeout("refreshSearchResults(this);", 250);
			}
		});
		if( $( "#price_range_slider" ).slider( "values", 0 ) < 850000 ) $('#price_id_min_value').text( $('#rblCurrencyCode option:selected').attr('symbol') + ' ' + formatNumber( $( "#price_range_slider" ).slider( "values", 0 ) )  );
		else $('#price_id_min_value').text( 'all' + ' *' );
		
		var count =  searchPriceArrays( yachtPricesList, parseInt( $('#max_price_search').val() ) );
		setUpYachtsResultNumber( count );
		$('#max_price_search').val( $( "#price_range_slider" ).slider( "values", 0 ) );
//		setTimeout("refreshSearchResults(this);", 250);
	} else if( $('.price_search_type_radio:checked').val() == 2 ) {
		$('.budget_quest_pph').show();
		$('.budget_quest_pw').hide();
		$('.price_range_selected').show();
		$('.inputField.pph_description').show();
		$("#price_range_slider").slider( "destroy" );
		$("#price_range_slider").hide();
		$("#price_range_slider_pph").show();
		var min = initialPricesMinPricePPH ? initialPricesMinPricePPH : 100;
		var max = 9000;//initialPricesMaxPricePPH && initialPricesMaxPricePPH <= 9000 ? initialPricesMaxPricePPH : 9000;
		if( min % 50 >= 0 ) min += 50 - ( min % 50 );
		min = min >= 7500 ? 7400 : min;
		
		if( !initialPricesMaxPricePPH ) initialPricesMaxPricePPH = 850000;
		if( initialPricesMaxPricePPH % 50 > 0 ) initialPricesMaxPricePPH += 50 - ( initialPricesMaxPricePPH % 50 );
		var bigPerc = parseInt( ( initialPricesMaxPricePPH - 7500 ) );
		
		if( initialPriceSliderYachtResults != null && initialPriceSliderYachtResults > 0 ) {
			var initialValue = searchPriceArraysReverse(yachtPricesPHList, initialPriceSliderYachtResults);
			initialValue += 50 - initialValue % 50;
			$('#max_price_search_pph').val( initialValue );
		} else if( $('#max_price_search_pph').val() && $('#max_price_search_pph').val() > 7500 ) {
			var searchedValPerc = ( $('#max_price_search_pph').val() - 7500 ) / ( initialPricesMaxPricePPH - 7500 );
			var initialValue = searchedValPerc * 1500 + 7500;
		} else if( $('#max_price_search_pph').val() && $('#max_price_search_pph').val() <= 7500 ) {
			var initialValue = $('#max_price_search_pph').val();
		} else var initialValue = min + 50;

		$('#price_scale_bottom span.replace_text').text(  $('#rblCurrencyCode option:selected').attr('symbol') + ' ' + formatNumber( min ) );
		$('#price_scale_top span.replace_text').text(  $('#rblCurrencyCode option:selected').attr('symbol') + ' ' + formatNumber( initialPricesMaxPricePPH && initialPricesMaxPricePPH >= 9000 ? initialPricesMaxPricePPH : 9000 ) );
		//console.log( !( yachtPricesPHList != null && yachtPricesPHList.length > 0 ) );
		$("#price_range_slider_pph").slider({
			disabled: !( yachtPricesPHList != null && yachtPricesPHList.length > 0 ),
			min: min,
			max: max,
			step: 50,
//			values: [ ( max - min ) / 2 ],
//			values: [ $('#max_price_search_pph').val() ? $('#max_price_search_pph').val() : ( min + 50 ) ],
			values: [ initialValue > 7500 ? parseInt( ( ( ( initialValue - 7500 ) / bigPerc ) * 1500  ) + 7500 ) : initialValue ],
			slide: function( event, ui ) {
				$('.search_form_stats a.button.complete').hide();
				$('.search_form_stats a.button.search').show();
				if( ui.values[ 0 ] < 7500 ) {
					$('#max_price_search_pph').val( ui.values[ 0 ] );
					$('#price_id_min_value').text( $('#rblCurrencyCode option:selected').attr('symbol') + ' ' + formatNumber( ui.values[ 0 ] ) + ' *' );
				} else {
					var smallPart = ui.values[ 0 ] - 7500;
					var perc = smallPart / 1500;
					var finalValue = parseInt( perc * bigPerc + 7500 );
					$('#max_price_search_pph').val( finalValue >= initialPricesMaxPricePPH  ? 999999999 : finalValue  );
					$('#price_id_min_value').text( finalValue >= initialPricesMaxPricePPH ? 'All' : $('#rblCurrencyCode option:selected').attr('symbol') + ' ' + formatNumber( finalValue ) + ' *' );
				}
				if( ui.values[ 0 ] >= max && totalCountAbsolute > 0) var count = totalCountAbsolute; 
				else var count =  searchPriceArrays( yachtPricesPHList, parseInt( $('#max_price_search_pph').val() ) );
				setUpYachtsResultNumber( count );
			},
			stop: function( event, ui ) {
				if( ui.values[ 0 ] < 7500 ) {
					$('#max_price_search_pph').val( ui.values[ 0 ] );
					$('#price_id_min_value').text( $('#rblCurrencyCode option:selected').attr('symbol') + ' ' + formatNumber( ui.values[ 0 ] ) + ' *' );
				} else {
					var smallPart = ui.values[ 0 ] - 7500;
					var perc = smallPart / 1500;
					var finalValue = parseInt( perc * bigPerc + 7500 );
					$('#max_price_search_pph').val( finalValue >= initialPricesMaxPricePPH  ? 999999999 : finalValue  );
					$('#price_id_min_value').text( finalValue >= initialPricesMaxPricePPH ? 'All' : $('#rblCurrencyCode option:selected').attr('symbol') + ' ' + formatNumber( finalValue ) + ' *' );
				}
				if( ui.values[ 0 ] >= max && totalCountAbsolute > 0) var count = totalCountAbsolute; 
				else var count =  searchPriceArrays( yachtPricesPHList, parseInt( $('#max_price_search_pph').val() ) );
				setUpYachtsResultNumber( count );
//				setTimeout("refreshSearchResults(this);", 250);
			}
		});
		
		if( $('#max_price_search_pph').val() == '' ) $('#max_price_search_pph').val( $( "#price_range_slider_pph" ).slider( "values", 0 ) >= initialPricesMaxPricePPH ? 999999999 : $( "#price_range_slider_pph" ).slider( "values", 0 ) );
		
		var count =  parseInt( $('#max_price_search_pph').val() ) >= initialPricesMaxPricePPH ? totalCountAbsolute : searchPriceArrays( yachtPricesPHList, parseInt( $('#max_price_search_pph').val() ) );
		setUpYachtsResultNumber( count );
		$('#price_id_min_value').text( $('#max_price_search_pph').val() >= initialPricesMaxPricePPH ? 'All' : ( $('#rblCurrencyCode option:selected').attr('symbol') + ' ' + formatNumber( $('#max_price_search_pph').val() ) ) + ' *' );
//		setTimeout("refreshSearchResults(this);", 250);
	} else {
		$('.price_range_selected').hide();
		$("#price_range_slider").slider( "destroy" );
		$("#price_range_slider").hide();
		$("#price_range_slider_pph").slider( "destroy" );
		$("#price_range_slider_pph").html('');
		$("#price_range_slider_pph").hide();
		$('.budget_quest').hide();
	}
//	setTimeout("refreshSearchResults(this);", 250);
	return;
	
		
}

function updatePriceList(currency_code_id){
	if(currency_code_id==1){			
		$("#price_id_min").removeOption(/./);
		$('#price_id_min_usd').copyOptions("#price_id_min",'all');
		/** select first item on the min list **/
		$('#price_id_min').val($("#price_id_min option:first").attr("value"));

		//$('#price_id_min').find('option[value=1]').attr('selected');
		$("#price_id_max").removeOption(/./);
		$('#price_id_max_usd').copyOptions("#price_id_max",'all');
		/** select last item on the max list **/
		$('#price_id_max').val($("#price_id_max option:last").attr("value"));		

	}
	else{
		$("#price_id_min").removeOption(/./);
		$('#price_id_min_eur').copyOptions("#price_id_min",'all');
		/** rubbish selection :| **/
		$('#price_id_min').val($("#price_id_min option:first").attr("value"));
		//$('#price_id_min').val('0');
		//$('#price_id_max').val('0');		
		//$('#price_id_min').find('option[value=5]').attr('selected');
		$("#price_id_max").removeOption(/./);
		$('#price_id_max_eur').copyOptions("#price_id_max",'all');
	}	
};

