var sel_criteria= new Object();

$(document).ready(function() {
	$('#region_select, #country_select').sSelect({ddMaxHeight: '300px', defaultText: ''});
    $("#arrival").datepicker({
    		onSelect: function(dateText, inst) { check_dates('arrival') },
            duration: '',
            minDate: 0, maxDate: '+16M',dateFormat: "yy-mm-dd",changeMonth: true,changeYear: true,prevText: 'Earlier',nextText: 'Later'
});
    $("#departure").datepicker({
    	onSelect: function(dateText, inst) { check_dates('departure') },
        duration: '',
        minDate: 0, maxDate: '+16M',dateFormat: "yy-mm-dd",changeMonth: true,changeYear: true,prevText: 'Earlier',nextText: 'Later'
});
    
    var flag=0;
    var val = location.hash;
    if(val.length>4) {
    	var val1 = val.split("/");
        for(c in val1){
        	if(val1[c] != '#' && val1[c] != '' && val1[c]!='function(c,d){for(var b=(d||0);b<this.length;b++){if(this[b]==c){return b}}}') {    
        		if(sel_criteria[val1[c]]===undefined) {
        			flag=1;
        			sel_criteria[val1[c]]=val1[c];
        		}
        	}
        }
    }
    if(flag==1) {
        ajax_search('1');
    }
});
function check_dates(selectID) {
	var dep_date = $.datepicker.parseDate("yy-mm-dd", $("#departure").val());
	var arr_date = $.datepicker.parseDate("yy-mm-dd", $("#arrival").val());
	if (selectID=='departure') {
		if(arr_date == null) arr_date = $.datepicker.parseDate("yy-mm-dd", $("#departure").val());
		if (dep_date<=arr_date) {
			arr_date.setTime(dep_date.getTime()-(86400000*7));
			$("#arrival").val($.datepicker.formatDate( "yy-mm-dd", arr_date) );
		}
	} else {
		if(dep_date == null) dep_date = $.datepicker.parseDate("yy-mm-dd", $("#arrival").val());
		if (arr_date>=dep_date) {
			dep_date.setTime(arr_date.getTime()+(86400000*7));
			$("#departure").val($.datepicker.formatDate( "yy-mm-dd", dep_date) );
		}
	}
	
	sel_criteria['arrival']=$.datepicker.formatDate( "yy-mm-dd", arr_date);
	sel_criteria['duration']=Math.floor(((dep_date.getTime()-arr_date.getTime())/86400000),0) + '-dagen';
//alert((dep_date + '-' + arr_date));
    ajax_search();
	
}


function checkselected(date)
{
    //alert(date);
    $("#departure").datepicker('setDate', date);
    return false;
	var arr_date=$("#datepicker").val();
    var sel = arr_date.substr(0,7);
    $("#month option[value='"+sel+"']").attr('selected', 'selected');
}

function fillDate() {
$("#datepicker").val('');
var month = $("#month").val();
if(month=='-1')
    {
    }
else
    {
        var date = new Date(month.substr(0,4),(parseInt(month.substr(5,2)))-1,'01');
        $("#datepicker").datepicker( 'option', 'defaultDate', date );
    }
}
$("#datepicker").css('display','block');
    $("#period").css('display','none');
function change_region(country,lang)
{
$.ajax({
					type: "GET",
					url: "ajax/ajax.php",
                    data:'t=regions&lang='+lang+'&c='+country,
					success: function(response){
						document.getElementById('region_dd').innerHTML=response;
					}
				});

}



function ajax_search(change_left_again) {

	if(change_left_again===undefined) {
		change_left_again=0;
 	}

var hash =''
var sel_html='';
	
	for (c in sel_criteria) {
			hash = hash + '/' + sel_criteria[c];
			sel_html += '<li class="selected"><a class="search_selected"   id="sel_' + c + '" href="#' + c + '" title="remove">' + sel_criteria[c] + '</a></li>';
	}
	$("#search_criteria_left").html(sel_html);
location.hash=hash;
url = '/'+search_link+'/' + hash;
url=url.replace('//','/');
        
        sel_criteria['page']='';
	    delete sel_criteria['page'];
	ajax(change_left_again,url,'');

}

var json_search=false;
     	var slider_value='';
     	
     	$(function(){
     	  $(".search_opts, .search_props, .region_link, .country_link").click(function() {
     	  var id_name=$(this).attr('id').substring(4);
     	  if ($(this).hasClass('disabled')) return false;  
          
     	  //alert($(this).hasClass('disabled'));
     	  
     	  $(this).parent().toggleClass('selected');
          if ($(this).parent().is('.selected')) {
        	  
        	  //updateHash(id_name, true);
        	  sel_criteria[id_name]=id_name;
              if ($("#num_" + $(this).attr('id').substring(4)).html == '(1)') {
              	//do nothing since there is only one?
            	//  alert('do nothing');
              } else {
              	ajax_search(location.hash);
              }
              
              //toggleSelected(id_name,$(this).text(), 'add');
              
              //$("#search_criteria_left").append('<li class="selected"><a class="search_selected"   id="sel_' + id_name + '" href="#' + id_name + '" title="remove">' + $(this).text() + '</a></li>');
              
          } else {
        	 // toggleSelected(id_name, '', 'remove');
        	  sel_criteria[id_name]='';
        	  delete sel_criteria[id_name];
        	  //$("#sel_" + id_name).remove();
        	  //updateHash(id_name, false);
//              ajax_search(location.hash);
              ajax_search();
              
          }
          
          return false;
          
          
        });
     	  
     	
     	 
     	$(".blockheadtext").live('click', function () {
     		 for (a in sel_criteria) {
     		//	 alert(a + ' => ' + sel_criteria[a]);
     		 }
     		});
     	 
     	$(".pagelink").live('click', function () {
     		var p1 = $(this).attr('id');
     		var p = p1.split('_');
     		sel_criteria['page']='page-' + p[1];
     		
     		ajax_search();
    		return false;
     	});
     	
     	$(".search_selected").live('click', function () {
     		 var id_name=$(this).attr('id').substring(4);
     	//	 updateHash(id_name, false);
     		 if (id_name=='country') {
     			$("#country_select").val('');
     			$("#region_select").val('');
     			$("#region_select").html('');
     			$('#region_select').resetSS();
     			$("#country_select").resetSS();
     			sel_criteria['region']='';
          	    delete sel_criteria['region'];
          	    sel_criteria['city']='';
        	    delete sel_criteria['city'];
     			$("#sel_region").parent().remove();
     		 }
     		 if (id_name=='region') {
     			sel_criteria['city']='';
        	    delete sel_criteria['city'];
     			$("#region_select").val('');
     			$('#region_select').resetSS();
     		 }
     		 if (id_name=='arrival') {
     			sel_criteria['duration']='';
          	    delete sel_criteria['duration'];
     			$("#arrival").val('');
     			$("#departure").val('');
     		 }
     		 if (id_name=='duration') {
     			$("#departure").val('');
     		 }
     		sel_criteria[id_name]='';
      	    delete sel_criteria[id_name];

     		$("#opt_" + id_name).parent().removeClass('selected');
     		
     		$(this).remove();
     		
            ajax_search();
            return false;
     		});
     	
        $("#country_select").change(function() {
        	if(country_search_flag==1) {
        		country_search_flag=0;
        		return false;
        	}
        	sel_criteria['region']='';
      	    delete sel_criteria['region'];
      	    sel_criteria['city']='';
    	    delete sel_criteria['city'];
    	    
    	    get_regions($(this).val());
  			sel_criteria['country']=$(this).val();
      	    
			ajax_search();
		});
		$("#region_select").change(function() {
			if(region_search_flag==1) {
				region_search_flag=0;
        		return false;
        	}
			location.hash =location.hash.replace('/' + current_region, '') + '/' + $(this).val();
 				current_region=$(this).val();
 				sel_criteria['region']=$(this).val();
 				sel_criteria['city']='';
 	    	    delete sel_criteria['city'];
 				ajax_search();
 				
			
		});
			
        
});

     	/*
     	function toggleSelected(id_name, title, action) {
     		
     		switch(action) {
     		case 'add':
     			$("#search_criteria_left").append('<li class="selected"><a class="search_selected"   id="sel_' + id_name + '" href="#' + id_name + '" title="remove">' + title + '</a></li>');
     			break;
     		case 'remove':
     			$("#sel_" + id_name).remove();
     			break;
     		case 'change':
     			toggleSelected(id_name, '', 'remove');
     			toggleSelected(id_name, title, 'add');
     			//$("#sel_" + id_name).html(title);
     			break;
     		}
     	}
     	
     	function updateHash(id, ad) {
     		var hash = location.hash 
     		hash = hash.replace('/' + id, ''); //remove first
     		hash = hash.replace('//','/');
     		if (ad) {
     			hash += '/' + id;
     		}
     		location.hash = hash;
     	}
     	*/
     	
     	
function initSlider(id,values) {
	$("#" + id).slider({
			range: "min",
			min: values[0],
			max: values[1],
			value: values[2],
			slide: function(event, ui) {
          		var link = $(this).attr('id').substring(7) ;
          		//var re = new RegExp('\/[0-9]*\-' + link , "g");
          		//location.hash= location.hash.replace(re, '') + '/' + ui.value + '-' + link;
				$("#min_" + link).html(ui.value);
			},
			stop: function(event, ui) {if (slider_value!=ui.value) {
			 var link = $(this).attr('id').substring(7) ;
			//  var url = '/' + location.hash.substring(2);
			//  $("#houselist").html('');
			  json_search=false;
			//  toggleSelected(link, ui.value + ' ' + link, 'change');
			  sel_criteria[link]=ui.value + '-' + link;
			  ajax_search();
 }			  
			  },
			start: function(event, ui) {slider_value=ui.value;}
			
			
		});
	}
	
function ajax(change_left_again,url,q1) {
	$(".main").fadeTo("fast", 0.33);
	$.get(url, {ajax_search:1,q:q1}, function(data) {
		 
        $("#houselist").html(data);
        
        $(".main").fadeTo("fast", 1);
            if (json_search) {

            var json_object = $.parseJSON(json_search);
            //alert(json_object.navigation.itemcount);
             $(".search_opts_num").html('');
             
            //$(".search_opts_num").parent().removeClass('disabled').addClass('disabled');
            if(json_object.pro_or_not==1) {
	             for (k in json_object.props.item1) {
	            	 if (!('item' in json_object.props.item1[k])) continue;
	            	if(json_object.props.item1[k]['item'][0].num == 0) {  
	            		$("#num_" + (json_object.props.item1[k]['item'][0].link)).html('(' + json_object.props.item1[k]['item'][0].num + ')').parent().addClass('disabled') ;
	            	}
	            	else {
	            		$("#num_" + (json_object.props.item1[k]['item'][0].link)).html('(' + json_object.props.item1[k]['item'][0].num + ')').parent().removeClass('disabled') ;
	            	}
	              //$("#num_" + (json_object.props.item1[k]['item'][0].link)).removeClass('disabled');
	            }
	             
	             for (j in json_object.props_num.item1) {
	            	 if(j<=3) continue;
	            	 for(l in json_object.props_num.item1[j].item) {
	            		 if(json_object.props_num.item1[j].item[l].link !== undefined) {
	            			if(json_object.props_num.item1[j].item[l].link != 0) {
		            			if(json_object.props_num.item1[j].item[l].num == 0) {  
		            				if(!($("#num_" + (json_object.props_num.item1[j].item[l].link)).parent().parent().hasClass( 'selected' )))
		                     		$("#num_" + (json_object.props_num.item1[j].item[l].link)).html('(' + json_object.props_num.item1[j].item[l].num + ')').parent().addClass('disabled') ;
		                     	}
		                     	else {
		                     		if(!($("#num_" + (json_object.props_num.item1[j].item[l].link)).parent().parent().hasClass( 'selected' )))
		                     		$("#num_" + (json_object.props_num.item1[j].item[l].link)).html('(' + json_object.props_num.item1[j].item[l].num + ')').parent().removeClass('disabled') ;
		                     	}
	            			}
	            		 }
	            	 }
	            	 
	             }
            }
            else {
            	$(".search_opts_num").parent().addClass('disabled');
            }
             	if(change_left_again=='1') {
		            hash = '';
		            for (c in sel_criteria) {
		            	sel_criteria[c] = '';
		     			delete sel_criteria[c];
		            }
		            for (j in json_object.item) {
		            	if(json_object.item[j].name1 !== undefined) {
		            		sel_criteria[json_object.item[j].name1]=json_object.item[j].name2;
		            	}
		            }
		            
	             	sel_html='';
	         		for (c in sel_criteria) {
	         			hash = hash + '/' + sel_criteria[c];
	         			if(c=='country') {
	         				country_search_flag = 1;
	         				$("#country_select").getSetSSValue(sel_criteria[c]);
	         				get_regions(sel_criteria[c]);
	         				if(sel_criteria['region']!==undefined) {
	         					region_search_flag = 1;
		         				$("#region_select").getSetSSValue(sel_criteria['region']);
	         				}
	         			}
	         			if(c=='arrival') {
	         				$("#arrival").val(sel_criteria[c]);
	         			}
	         			if(c=='duration') {
	         				var de = sel_criteria[c];
	         				de = de.split('-dagen');
	         				var myDate=new Date(sel_criteria['arrival']);
	         				//var da = de[0]*1;
	         				myDate.setDate(myDate.getDate()+parseInt(de[0]));
	         				$("#departure").val($.datepicker.formatDate( "yy-mm-dd", myDate));
	         			}
	         			sel_html += '<li class="selected"><a class="search_selected"   id="sel_' + c + '" href="#' + c + '" title="remove">' + sel_criteria[c] + '</a></li>';
	         		}
	         		$("#search_criteria_left").html(sel_html);
	         		location.hash=hash;
             	}
            }
            document.getElementById('q').focus();
         	document.getElementById('q').blur();  
      });
}


function common(){
	$("#q").val('');
	$("#country_select").val('');
	$("#region_select").val('');
	$("#region_select").html('');
	$('#region_select').resetSS();
	$("#country_select").resetSS();
	$("#arrival").val('');
 	$("#departure").val(''); 	
}

function get_regions(country) {
	async: false
	   $.ajax({
	  type: 'GET',
	  url: "/ajax/ajax.php",
	  data: 't=regions&lang='+site_language+'&c='+country,
	  success: function(data) {
			$("#region_select").html(data);
			$('#region_select').resetSS();
	},async:false
	  });
	/*$.get('/ajax/ajax.php' ,  {t: 'regions', lang: site_language, c: country}, function(data) {
			$("#region_select").html(data);
			$('#region_select').resetSS();
	},{async: false});*/
}
