// JavaScript Document

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}
var previousSearches = Array();

/**
 * Initialize test page.
 *
 * Author: peterl
 */

function attacheAdvancedFilterevents() {
	
	$('#advancedOptions').toggle( function() {
//		if( $("#advancedSearchFilter").length < 1 ) {
//			$('div.advancedActions ul').prepend('<li class="reveal"><a alt="Show Advanced Search Requirements" id="advancedSearchFilter">Show Yacht Toys &amp; Amenities</a></li>');
//			$("#advancedSearchFilter").click( attacheAdvancedFilterevents );
//		}
		if($('#advancedOptions:visible').length > 0 ){
			$("#advancedSearchFilter").addClass('collapse').text('Hide Advanced Search - Toys & Amenities');
		} else {
			$("#advancedSearchFilter").removeClass('collapse').text('Advanced Search - Toys & Amenities');
		}
	});
}
var prevHowToSearchValue; 
$(document).ready(function() {
	
	prevHowToSearchValue = 	getSelectedTypeSearch();
	
	/**
	  * Reformat UI slider if IE 6.0
	  *
	  * Author: waldemarm
	  **/
//	if($.browser.msie==true){
//		if($.browser.version=="6.0"){
//			$('.ui-slider').css('position','absolute');
//			$('.ui-slider').css('left','-230px');
//			$('#price_id_min_value').css('clear','both');
//			$('#length_id_min_value').css('clear','both');
//		}
//	}
			
	
	$("#advancedSearchFilter").click( attacheAdvancedFilterevents );

	$(".searchFieldOption").change(function() {
		setTimeout("refreshSearchResults(this);",250);
	});
	
	var pageForm = $("#pageForm");
	
	IDBSYachtSearch.OrganisationAreaSelect.initialise(pageForm);
	IDBSYachtSearch.Booking.initialise(pageForm);
	IDBSYachtSearch.Builder.initialise(pageForm);
	
	$('.search_by_fields_radio').click(function(event, type){
		$('.what_type_yacht').show();
		$('.current.search_by_fields').removeClass('current').fadeOut();
		var value = getSelectedTypeSearch();
		switch( value ) {
			case 'price':
				$('.search_by_price.search_by_fields').addClass('current').fadeIn();
				break;
			case 'length':
				$('.search_by_length.search_by_fields').addClass('current').fadeIn();
				$('input[name="order_by_length"]').val('desc');
				break;
			case 'builder':
				$('.search_by_builder.search_by_fields').addClass('current').fadeIn();
				break;
			case 'name':
				$('.search_by_yacht.search_by_fields').addClass('current').fadeIn();
				break;
		}
		if( value ) {
			$('.charterYachtSearch fieldset').css('background-image', 'url("")');
		}
		resetSearchValues();
		if( prevHowToSearchValue == "" || !prevHowToSearchValue ) return;
		prevHowToSearchValue = value;
		if( type ) setTimeout("refreshSearchResults( this, '"+type+"');",250);
	})
	
	/** initilise the first search **/
	if( getSelectedTypeSearch() != "" ) { 
		$('.search_by_fields_radio:checked').trigger('click', [ 'initial' ]);
	} else {
		setTimeout("refreshSearchResults(this, 'initial');", 250);
	}
	
	$('#submit_charter_search').click(function(){
		if( getSelectedTypeSearch() == 'price' && ( $('.price_search_type_radio:checked').val() == "" || !$('.price_search_type_radio:checked').val() ) ) {
			$('#price_search_type').addClass('error');
			return false;
		}
		$("#total_count").html("<img src=\"/resources/images/loading.gif\" style=\"margin-top: -10px; margin-left: 45px;\">"); 
		$(this).parents('form:first').submit();
		return true;
	})
	
	
});

function getSelectedTypeSearch() {
	var value = '';
	$('.search_by_fields_radio:checked').each(function(i){
		if( $(this).get(0).checked ) value = $(this).val();
	})
	return value;
}

function resetSearchValues() {
//	return;
	if( getSelectedTypeSearch() != 'builder' ) {
		$('#property_yacht_builder_id').val('');
		$('#search_builders_ids').multiselect('uncheckAll');
	}
	if( getSelectedTypeSearch() != 'name' ) {
		$('#yacht_id_list').val('');
	}
	if( getSelectedTypeSearch() != 'length' ) {
		$('#length_id_min_m').val('');
		$('#length_id_max_m').val('');
		$('input[name="order_by_length"]').val('');
	}
	if( getSelectedTypeSearch() != 'price' ) {
		$('#min_price_search').val('');
		$('#max_price_search').val('');
		$('#min_price_search_pph').val('');
		$('#max_price_search_pph').val('');
		$('.budget_quest_pph').hide();
		$('.price_search_type_radio').each(function(i){
			$(this).get(0).checked = false;
		})
	} else {
		$('.budget_quest_pph').hide();
		$('.budget_quest_pw').hide();
		if( $('.price_search_type_radio:checked').val() == '2' ) {
			$('.budget_quest_pph').show();
		} else if( $('.price_search_type_radio:checked').val() == '2' ) {
				$('.budget_quest_pw').show();
		}
	}
	$('#total_count span:first').html('');
	setUpYachtsResultNumber(-1);
//	$('#total_count').text( $('#total_count').text().toString().replace('/','') );
}

var ajaxFormRequest;
var yachtPricesList = null, yachtPricesPHList = null;
var currencyRates = new Object();
function setUpYachtsResultNumber ( yachtCount ) {
	try {
		if( parseInt( totalCountAbsolute ) < parseInt( yachtCount ) ) totalCountAbsolute = yachtCount; 
		if( totalCountAbsolute ) {
			if( /*yachtCount != totalCountAbsolute &&*/ yachtCount > -1 ) { 
				$("#total_count").html("<span style=\"color: orange;font-size: 1.7em;font-weight: bold;\">"+yachtCount + "</span>/" + totalCountAbsolute + " " + " <span class=\"label\">Yachts</span>");
			} else {
//				console.log( initialCharterSearchPage );
				if( initialCharterSearchPage ) {
					$("#total_count").html("<span style=\"color: orange;font-size: 1.7em;font-weight: bold;\"></span><span style=\"font-size: 1.7em;font-weight: bold;\">" + totalCountAbsolute + "</span> " + " <span class=\"label\">Yachts Available</span>");
				} else { 
					$("#total_count").html("<span style=\"color: orange;font-size: 1.7em;font-weight: bold;\"></span>" + totalCountAbsolute + " " + " <span class=\"label\">Yachts</span>");
				}
			}
		}
	} catch ( e ) { console.log( e ); }
	
}
var totalCountAbsolute = null;
function refreshSearchResults(this_object, type){
	if( $("#pageForm").length < 1 ) return;
	
	if( type != 'initial' ) {
		$('.search_form_stats a.button.complete').hide();
		$('.search_form_stats a.button.search').show();
	}
	if( type == 'initial' && $('input[name="tmp_total_absolute_count"]').val() > 0 && parseInt( $('#total_number_of_showed_results').text() ) && 1 == 2) {
		totalCountAbsolute = $('input[name="tmp_total_absolute_count"]').val();
		setUpYachtsResultNumber( parseInt( $('#total_number_of_showed_results').text() ) );
	} else {
		$("#total_count").html("<img src=\"/resources/images/loading.gif\" style=\"margin-top: -10px; margin-left: 45px;\">");
	}
	
	/**
	 * Submit the form to find out how many matches we have got!
	 */
	try {
		ajaxFormRequest.formRequestAjaxObject.abort();
	} catch (e ) {}
	ajaxFormRequest = $("#pageForm").ajaxSubmit({
		
		url: '/property/search',
		type: 'GET',
		success: function(responseData) {
			yachtTotalCount = $("property_yacht_id_count_absolute", responseData).text();
			yachtCount = $("property_yacht_id_count", responseData).text();
			
			totalCountAbsolute = yachtTotalCount;
			$('input[name="tmp_total_absolute_count"]').val( totalCountAbsolute );
	
			if(type == 'initial' && $("#total_count span").length > 1 );
			else {
				if( type == 'initial' && yachtCount == yachtTotalCount && parseInt( $('#total_number_of_showed_results').text() ) > 0 ) { 
					setUpYachtsResultNumber( parseInt( $('#total_number_of_showed_results').text() ) );
				} else if( type == 'initial' && yachtCount == yachtTotalCount ) setUpYachtsResultNumber( -1 );
				else setUpYachtsResultNumber(yachtCount);
			}
			
			$('currency_element', responseData).each(function( i ) {
				currencyRates[ $(this).attr('id') ] = parseFloat( $(this).attr('rate') );
			})
			
			yachtPricesList = new Array();
			$('yachts_prices_list price_level', responseData).each(function(i){
				yachtPricesList[i] = { 'price' : $(this).attr('price') * currencyRates[ $('#rblCurrencyCode').val() ], 'count' : $(this).attr('count') };
			})
			
			yachtPricesPHList = new Array();
			$('yachts_prices_list_pph price_level', responseData).each(function(i){
				yachtPricesPHList[i] = { 'price' : $(this).attr('price') * currencyRates[ $('#rblCurrencyCode').val() ], 'count' : $(this).attr('count') };
			})
//			console.log( new Object( yachtPricesList ) );
			if( type != 'builders' ) {
				var buildersSelect = $('#search_builders_ids');
				buildersSelect.html('<option value="">Select</option><option value="-1">All builders</option>');
				$('search_builders_list builder', responseData).each(function(i) {
					buildersSelect.append('<option value="'+$(this).attr('id')+'" count="'+$(this).attr('charter_count')+'">'+$(this).attr('name')+/*' ( '+$(this).attr('charter_count')' )'++*/'</option>');
				})
				buildersSelect.multiselect('destroy');
				buildersSelect.multiselect({
				   selectedText: "No. Of Builders Selected: #",
				   noneSelectedText: 'Select Builder'
				});
				$('.inputRow.search_by_builder ul.ui-multiselect-checkboxes li label:first').css('padding-left', '0px');
				
				if( $('#property_yacht_builder_id').val() != "" && $('#property_yacht_builder_id').val() && type == 'initial' ) {
					var ids = $('#property_yacht_builder_id').val().split(',');
					if( ids.length < 1 ) ids[0] = -1;
//					console.log( ids );
					for(var t = 0; t < ids.length; t++) {
						if( ids[t] == "" ) continue;
						$('#search_builders_ids option[value="'+ids[t]+'"]').get(0).selected = true;
						$('input[value="'+ids[t]+'"]', $('div.search_by_builder .ui-multiselect-checkboxes.ui-helper-reset')).get(0).checked = true;
					}
					
				} else {
					$('#property_yacht_builder_id').val('');
				}
				IDBSYachtSearch.prevValuesCondition = $('#property_yacht_builder_id').val();
			}
			if( $('#property_yacht_builder_id').val() == "" ) {
				$( '#ui-multiselect-search_builders_ids-option-1' ).get(0).checked = true;
			}
			//if( type != 'price_per_head' && type != 'price_per_week' && type != 'length') return;
			
			if( type == 'regions' || ( type == 'initial' /*&& $('#organisation_area_id_live').val() != ''*/ ) );
			else if( type == 'currency' ) initializePriceSlider();
			else return;
			
			initialPricesMinPricePPH = initialPricesMaxPricePPH = false;
			if( type != 'initial' ) $('#max_price_search_pph').val('');
			
			switch( parseInt( $('#rblCurrencyCode').val() ) ) {
				case 1:
					var maxPrice = parseInt( $('property_yacht_top_price_usd', responseData).text() );
					var maxSelect = $('#price_id_max_usd');
					var minPrice = parseInt( $('property_yacht_bot_price_usd', responseData).text() );
					var minSelect = $('#price_id_min_usd');
					if( parseInt( $('property_yacht_top_price_guest_eur', responseData).text() ) < 0 ) var maxPphPrice = 850000 - 100;
					else var maxPphPrice = 100 + parseInt( $('property_yacht_top_price_guest_eur', responseData).text() );
					var minPphPrice = 100 + parseInt( $('property_yacht_bot_price_guest_usd', responseData).text() );
					break;
				case 2:
					var maxPrice = parseInt( $('property_yacht_top_price_gbp', responseData).text() );
					var maxSelect = $('#price_id_max_gbp');
					var minPrice = parseInt( $('property_yacht_bot_price_gbp', responseData).text() );
					var minSelect = $('#price_id_min_gbp');
					if( parseInt( $('property_yacht_top_price_guest_eur', responseData).text() ) < 0 ) var maxPphPrice = 850000;
					else var maxPphPrice = 100 + parseInt( $('property_yacht_top_price_guest_eur', responseData).text() );
					var minPphPrice = 100 + parseInt( $('property_yacht_bot_price_guest_gbp', responseData).text() );
					break;
				case 3:
					var maxPrice = parseInt( $('property_yacht_top_price_eur', responseData).text() );
					var minPrice = parseInt( $('property_yacht_bot_price_eur', responseData).text() );
					if( parseInt( $('property_yacht_top_price_guest_eur', responseData).text() ) < 0 ) var maxPphPrice = 850000;
					else var maxPphPrice = 100 + parseInt( $('property_yacht_top_price_guest_eur', responseData).text() );
					var minPphPrice = 100 + parseInt( $('property_yacht_bot_price_guest_eur', responseData).text() );
					break;
			}
			if( ( maxPphPrice - minPphPrice ) < 1000 ) maxPphPrice = minPphPrice + 1000;
			
			if( !initialPricesMinPricePPH || ( initialPricesMinPricePPH > minPphPrice ) ) {
				initialPricesMinPricePPH = minPphPrice + 100;
				try {
					$("#price_range_slider_pph").slider('value', minPphPrice + 200 );
				} catch(e) {}
			}
			var toRebuild = !initialPricesMaxPricePPH;
			if( !initialPricesMaxPricePPH || ( initialPricesMaxPricePPH < maxPphPrice ) ) {
				initialPricesMaxPricePPH = maxPphPrice + 100;
			}
			
			if( !initialPricesMinPrice || initialPricesMinPrice > minPrice ) {
				initialPricesMinPrice = minPrice + 1000;
			}
			if( !initialPricesMaxPrice || initialPricesMaxPrice < maxPrice ) {
				initialPricesMaxPrice = maxPrice+1000;
			}
			initializePriceSlider();
//			$('#price_search_type').trigger('change');

			
			/*
			//Connecting the sliders @author: Stanislav
			if( type != 'length' ) {
				var maxLengthM = parseInt( $("property_yacht_top_length_m", responseData).text() );
				if( maxLengthM > -1 ) {
					var maxSelectVal = -1;
					$('#length_id_max_m option').each(function( i ){
						if( parseInt( $(this).text() ) > maxLengthM && maxSelectVal == -1 ) {
							maxSelectVal = parseInt( $(this).attr('value') ); 
						}
					})
					if( maxSelectVal == -1 ) maxSelectVal = $('#length_id_max_m option:last').attr('value');  
					$('#length_id_max_m').val( maxSelectVal );
				}
				
				var minLengthM = parseInt( $("property_yacht_bot_length_m", responseData).text() );
				if( minLengthM > -1 ) {
					$('#length_id_min_m option').each(function( i ){
						if( parseInt( $(this).text() ) < minLengthM ) {
							minSelectVal = parseInt( $(this).attr('value') ); 
						}
					})
					if( minLengthM == -1 ) minSelectVal = $('#length_id_min_m option:first').attr('value'); 
					$('#length_id_min_m').val( minSelectVal );
				}
				
				var maxLengthF = parseInt( $("property_yacht_top_length_f", responseData).text() );
				if( maxLengthF > -1 ) {
					var maxSelectVal = -1;
					$('#length_id_max_ft option').each(function( i ){
						if( parseInt( $(this).text() ) > maxLengthM && maxSelectVal == -1 ) {
							maxSelectVal = parseInt( $(this).attr('value') ); 
						}
					})
					if( maxSelectVal == -1 ) maxSelectVal = $('#length_id_max_ft option:last').attr('value');  
					$('#length_id_max_ft').val( maxSelectVal );
				}
				
				var minLengthF = parseInt( $("property_yacht_bot_length_f", responseData).text() );
				if( minLengthF > -1 ) {
					var minSelectVal = -1;
					$('#length_id_min_ft option').each(function( i ){
						if( parseInt( $(this).text() ) < minLengthF ) {
							minSelectVal = parseInt( $(this).attr('value') ); 
						}
					})
					if( minSelectVal == -1 ) minSelectVal = $('#length_id_min_ft option:first').attr('value');   
					$('#length_id_min_ft').val( minSelectVal );
				}
				
				var length_code_id = $('#rblproperty_yacht_length').val();
//				initializeLengthSlider($("#length_select_" + length_code_id));
				
			}
			switch( parseInt( $('#rblCurrencyCode').val() ) ) {
				case 1:
					var maxPrice = parseInt( $('property_yacht_top_price_usd', responseData).text() );
					var maxSelect = $('#price_id_max_usd');
					var minPrice = parseInt( $('property_yacht_bot_price_usd', responseData).text() );
					var minSelect = $('#price_id_min_usd');
					var maxPphPrice =  parseInt( $('property_yacht_top_price_guest_usd', responseData).text() );
					var minPphPrice =  parseInt( $('property_yacht_bot_price_guest_usd', responseData).text() );
					break;
				case 2:
					var maxPrice = parseInt( $('property_yacht_top_price_gbp', responseData).text() );
					var maxSelect = $('#price_id_max_gbp');
					var minPrice = parseInt( $('property_yacht_bot_price_gbp', responseData).text() );
					var minSelect = $('#price_id_min_gbp');
					var maxPphPrice =  parseInt( $('property_yacht_top_price_guest_gbp', responseData).text() );
					var minPphPrice =  parseInt( $('property_yacht_bot_price_guest_gbp', responseData).text() );
					break;
				case 3:
					var maxPrice = parseInt( $('property_yacht_top_price_eur', responseData).text() );
					var maxSelect = $('#price_id_max_eur');
					var minPrice = parseInt( $('property_yacht_bot_price_eur', responseData).text() );
					var minSelect = $('#price_id_min_eur');
					var maxPphPrice =  parseInt( $('property_yacht_top_price_guest_eur', responseData).text() );
					var minPphPrice =  parseInt( $('property_yacht_bot_price_guest_eur', responseData).text() );
					break;
			}
			if( maxPphPrice < minPphPrice ) {
				maxPphPrice = minPphPrice = -1;
			}
			
			var maxSelectPph = $('#price_range_max_pph');
			var minSelectPph = $('#price_range_min_pph');
			
			if( type != 'price_per_week' ) {
				if( maxPrice > -1 ) {
					var maxSelectPrice = -1;
					$('option', maxSelect).each(function(i){
						if( parseInt( $(this).text().replace(',', '') ) > maxPrice && maxSelectPrice == -1) {
							maxSelectPrice = $(this).attr('value');
						}
					})
					if( maxSelectPrice == -1 ) maxSelectPrice = $('option:last', maxSelect).attr('value');  
					maxSelect.val( maxSelectPrice );
				}
				if( minPrice > -1 ) {
					var minSelectPrice = -1;
					$('option', minSelect).each(function(i){
						if( parseInt( $(this).text().replace(',', '') ) < minPrice ) {
							minSelectPrice = $(this).attr('value');
						}
					})
					if( minSelectPrice == -1 ) minSelectPrice = $('option:first', minSelect ).attr('value');  
					minSelect.val( minSelectPrice );
				}
				
				var currency_code_id = $('#rblCurrencyCode').val();
				var currency_code = $('#rblCurrencyCode :selected').attr('title').toLowerCase();
//				initializePriceSlider($("#currency_select_" + currency_code_id), currency_code);
			}
			
			if( type != 'price_per_head' ) {
				if( maxPphPrice > -1 ) {
					var maxSelectPrice = -1;
					$('option', maxSelectPph).each(function(i){
						if( parseInt( $(this).text().replace(',', '') ) > maxPphPrice && maxSelectPrice == -1) {
							maxSelectPrice = $(this).attr('value');
						}
					})
					if( maxSelectPrice == -1 ) maxSelectPrice = $('option:last', maxSelectPph).attr('value'); 
					maxSelectPph.val( maxSelectPrice );
				}
				if( minPphPrice > -1 ) {
					var minSelectPrice = -1;
					$('option', minSelectPph).each(function(i){
						if( parseInt( $(this).text().replace(',', '') ) < minPphPrice ) {
							minSelectPrice = $(this).attr('value');
						}
					})
					if( minSelectPrice == -1 ) minSelectPrice = $('option:first', minSelectPph).attr('value'); 
					minSelectPph.val( minSelectPrice );
				}
				var currency_code_id = $('#rblCurrencyCode').val();
				var currency_code = $('#rblCurrencyCode :selected').attr('title').toLowerCase();
			}
			//END connecting sliders
			*/
			
		}
	});
	
};


/**
 * Show price min/max if duration is over 7 days / otherwise - hide
 */
function showHidePriceFields(cruiseDuration){
	var min_duration = 7; //minimum number of days to show proces 
	if(cruiseDuration==''){
		cruiseDuration = 0;
	}
	//alert(cruiseDuration);
	if(cruiseDuration<min_duration){
		//hide
		$('.price_id_max').css('display','none');
		$('.price_id_min').css('display','none');	
		$('#read_prices').val('f');		
	} 
	else{
		//show
		$('.price_id_min').css('display','');
		$('.price_id_max').css('display','');					
		$('#read_prices').val('t');			
	}
}
 
	 
/**
 * Date functions 
 */
function two_digit(num) {
	if (num < 10) {
		return "0" + num;
	}
	return num;
}

function displayDate(d) {
	var new_month = two_digit(d.getMonth() + 1);
	var new_day = two_digit(d.getDate());
	var new_year = d.getFullYear();	
	return new_day + "/" + new_month + "/" + new_year;
} 

/**
 * @todo fix spelling mistake of function name
 *
 * Author: peterl
 *
 * Function which check if selected language item has been choosen before
 *
 * Author: waldemarm
 */
function checkIfYachExists(languageID){
	var itemExist = false
	$("#yachtList > li").each(function(){
		if($(this).attr("id").split("_")[1]==languageID){
			itemExist = true;
		}
	});
	return itemExist;
};


function y2k(number) { return (number < 1000) ? number + 1900 : number; }

function daysBetweenDates(date_from,date_to) {
	
			var year_from = date_from.split('/')[2];
			var mont_from = date_from.split('/')[1];
			var day_from  = date_from.split('/')[0];
			var year_to	  = date_to.split('/')[2];
			var month_to  = date_to.split('/')[1];
			var day_to	  = date_to.split('/')[0];
			
			var startDate 	= new Date(year_from,mont_from,day_from);
			var endDate 	= new Date(year_to,month_to,day_to);
    var difference =  
      Date.UTC(y2k(endDate.getYear()),endDate.getMonth(),endDate.getDate(),0,0,0) - Date.UTC(y2k(startDate.getYear()),startDate.getMonth(),startDate.getDate(),0,0,0);
    return difference/1000/60/60/24;
}

/** show number of days betwee two dates (daysBetweenDates(startDate, endDate)) **/

function two_digit(num) {
	if (num < 10) {
		return "0" + num;
	}
	return num;
}
		
function displayDate(d) {
	var new_month = two_digit(d.getMonth() + 1);
	var new_day = two_digit(d.getDate());
	var new_year = d.getFullYear();	
	return new_day + "/" + new_month + "/" + new_year;
}

