var uri = location.href;
uri = uri.replace(/[^\/]+\/\/[^\/]+/,"");
var uripath = uri.split('/');
//var lang = (uri.match(/^\/ja\//))?'ja':'en';
var lang = (uripath[1].match(/^ja$/))?'ja':'en';
var category = uripath[2];

function flashentries() {
  $('#results').children().remove();
  $('#sort > a').hide().removeClass('priority');
  $('#pager > p').remove();
  entries.hide();
}
function showentry (sp,ep) {
  if (sp<ep) {
    $(listing[sp]).show('fast',function(){
      var img = $(this).find('.thumb>a>img');
      $(img).attr('src',$(img).attr('orgsrc'));
      showentry(sp+1,ep);
    });
  }
}


var title_order = 'ascend';
var price_order = 'ascend';
var sort_priority = 'price';
function sort_by_title(){
  listing.sort(function(a,b){
    var a_val = $(a).children('h2').text().substr(0,6);
    var b_val = $(b).children('h2').text().substr(0,6);
    if(title_order=='ascend') {
      return a_val.localeCompare(b_val);
    }else if(title_order=='descend') {
      return b_val.localeCompare(a_val);
    }
  });
}
function sort_by_price(){
  listing.sort(function(a,b){
    var a_val = $(a).children('.amount').text();
    var b_val = $(b).children('.amount').text();
    if(price_order=='ascend'){
      return parseInt(a_val) > parseInt(b_val) ? 1:-1;
    }else if(price_order=='descend') {
      return parseInt(a_val) < parseInt(b_val) ? 1:-1;
    }
  });
}
function sort_by(){
  if(sort_priority=='title') {
    sort_by_price();
    sort_by_title();
    $('#sort > a.title_order').addClass('priority');
  }else if(sort_priority=='price') {
    sort_by_title();
    sort_by_price();
    $('#sort > a.price_order').addClass('priority');
  }
  $('#sort>.title_order.'+title_order).show();
  $('#sort>.price_order.'+price_order).show();
}

var listing = new Array();
function nextEntries(n) {
  entries = $('#listing > .entries > .entry');
  flashentries();
  if($('#fs_recommend').is(':checked')) {
    entries = entries.filter(":has(.promotion)");
  }
  if($('#fs_title').val()!='') {
    entries = entries.filter(":has(h2:contains("+$('#fs_title').val()+"))");
  }

  if($('select').is('#fs_range') && $('#fs_range').val()!='') {
  	var fs_ranges = $('#fs_range').val();
  	if(!fs_ranges) fs_ranges = '0:999999999';
  	fs_ranges = fs_ranges.split(':');
  	fs_ranges[0] = (fs_ranges[0]!='')?parseInt(fs_ranges[0]):0;
  	fs_ranges[1] = (fs_ranges[1]!='')?parseInt(fs_ranges[1]):999999999;
  	entries = entries.filter(function(){
  	  var this_amount = $(this).children('.amount').text().replace(/,/g,'');
  	  this_amount = parseInt(this_amount);
  	  return this_amount>fs_ranges[0] && this_amount<fs_ranges[1];
  	});
  }
  listing = entries.clone();
  listing = jQuery.makeArray(listing);

  var pn = 10;
  var sp = n;
  var ep = n+pn;
  if(ep>listing.length) {
    ep = listing.length;
  }
  if(listing.length==0){
  	$('#noresult').css('display','block');
  }else{
  	$('#noresult').css('display','none');
    sort_by();
    $(listing).appendTo('#results');
    showentry(sp,ep);
  }
  location.hash='#/'+sp;

  if (0 < sp) {
    $('#page_prev')
  	  .css('display','inline')
  	  .removeAttr('href')
  	  .unbind('click')
  	  .bind('click',function(){
        location.hash='#/'+sp-pn;
  	    });
  }else{
    $('#page_prev')
  	  .css('display','none')
  	  .removeAttr('href')
  	  .unbind('click');
  }
  if (listing.length > ep) {
    $('#page_next')
  	  .css('display','inline')
  	  .removeAttr('href')
  	  .unbind('click')
  	  .bind('click',function(){
        location.hash='#/'+ep;
  	    });
  }else{
    $('#page_next')
  	  .css('display','none')
  	  .removeAttr('href')
  	  .unbind('click');
  }
    if(listing.length>pn) {
      $('#pager').append('<p></p>');
  	  for(i=0;i<Math.ceil(listing.length/pn);i++) {
  	    if(sp!=i*pn) {
    	  $('<a></a>')
  	        .attr('href','#/'+i*pn)
  	        .html(i+1)
  	        .appendTo('#pager > p');
  	    }else{
  	      $('<span />')
  	        .html(i+1)
  	        .appendTo('#pager > p');
  	    }
  	  }
    }
//  alert('done');
}

function preset_sort(){
  $('#sort>a').removeAttr('href');
  $('#sort>.title_order.ascend')
   .bind('click',function(){
   	 title_order = 'descend';
   	 sort_priority = 'title';
   	 nextEntries(0);
   });
  $('#sort>.title_order.descend')
   .bind('click',function(){
   	 title_order = 'ascend';
   	 sort_priority = 'title';
   	 nextEntries(0);
   });
  $('#sort>.price_order.ascend')
   .bind('click',function(){
   	 price_order = 'descend';
   	 sort_priority = 'price';
   	 nextEntries(0);
   });
  $('#sort>.price_order.descend')
   .bind('click',function(){
   	 price_order = 'ascend';
   	 sort_priority = 'price';
   	 nextEntries(0);
   });
}

function preset_selecter(){
  	var hash_query = decodeURI(location.hash);
    var fs_range_sale = $('#fs_range_sale>option').clone();
    var fs_range_rent = $('#fs_range_rent>option').clone();
    $('#fs_range>optgroup').remove();
    if($('#fs_category option:selected').val()=='properties/rentals'){
      $(fs_range_rent).appendTo('#fs_range');
    }else{
      $(fs_range_sale).appendTo('#fs_range');
    }
    $('#fs_category').change(function(){
      $('#fs_range>option[value!=""]').remove();
      if($('#fs_category option:selected').val()=='properties/rentals'){
        $(fs_range_rent).appendTo('#fs_range');
      }else{
        $(fs_range_sale).appendTo('#fs_range');
      }
    });
    var fs_range = hash_query.match(/fs_range=([^\/]+)/);
    if(fs_range!=null){
      fs_range[1] = fs_range[1].replace('%3A',':');
      $('#fs_range').val(fs_range[1]);
    }
    var fs_recommend = hash_query.match(/fs_recommend=([^\/]+)/);
    if(fs_recommend!=null){
      $('#fs_recommend').attr('checked','checked');
    }
    var fs_title = hash_query.match(/title=([^\/]+)/);
    if(fs_title!=null){
      fs_title[1] = decodeURI(fs_title[1]);
      $('#fs_title').val(fs_title[1]);
    }
}

state_sp = -1;
function refleshlisting(){
  var hash = location.hash;
  var sp = 0;
  if(hash = hash.match(/\/(\d+)$/)) {
    var sp = parseInt(hash[1]);
  }
  if(state_sp != sp) {
    nextEntries(sp);
    state_sp = sp;
  }
  setTimeout(refleshlisting,200);
}



$(document).ready(function(){
  $('#lang2en').attr('href',uri.replace(/^\/(en|ja)/,'/en'));
  $('#lang2ja').attr('href',uri.replace(/^\/(en|ja)/,'/ja'));
//  $('#headers').load('/module/banner.'+lang+'.js',function(){
  $.getScript('/module/banner.'+lang+'.js',function(){
    for(cat in sliderimages) {
      var rand = Math.floor(Math.random()*sliderimages[cat].length);
      $('#hot_'+cat+'.bnrmdl>dl>dd.thumb>a').attr('href',sliderimages[cat][rand][0]);
      $('#hot_'+cat+'.bnrmdl>dl>dd.thumb>a>img').attr('src',sliderimages[cat][rand][2]);
      $('#hot_'+cat+'.bnrmdl>dl>dt.title2').html(sliderimages[cat][rand][3]);
      $('#hot_'+cat+'.bnrmdl>dl>dd.remark').html(sliderimages[cat][rand][4]);
    }
    if(category.match(/^properties|hotel|tour$/)){
      sliderimages[category].sort(function(){
        return Math.floor(Math.random()-0.5);
      });
/*
      for(i in sliderimages[category]){
       if(sliderimages[category][i].length>0){
        $('<li />')
         .html(
          $('<img />')
           .attr('src',sliderimages[category][i][1])
           .attr('alt',sliderimages[category][i][3])
          )
         .appendTo('#slider>ul');
       }
      }
*/
        $('<li />')
         .html(
          $('<img />')
           .attr('src',sliderimages[category][0][1])
           .attr('alt',sliderimages[category][0][3])
          )
         .appendTo('#slider>ul');

    }else{
      var banners = [];
      for (cat in sliderimages){
      	for(i=0;i<sliderimages[cat].length;i++){
         if(sliderimages[cat][i].length>0){
          banners.push(sliderimages[cat][i]);
         }
      	}
      }
      banners.sort(function(){
        return Math.floor(Math.random()-0.5);
      });
/*
      for (i=0;i<5;i++) {
        $('<li />')
         .html(
          $('<img />')
           .attr('src',banners[i][1])
           .attr('alt',banners[i][3])
          )
         .appendTo('#slider>ul');
      }
*/
        $('<li />')
         .html(
          $('<img />')
           .attr('src',banners[0][1])
           .attr('alt',banners[0][3])
          )
         .appendTo('#slider>ul');

    }
    // http://cssglobe.com/post/3783/jquery-plugin-easy-image-or-content-slider
/*
    $("#slider").easySlider({
      auto: true,
      continuous: true,
      speed: 2500,
      pause: 500,
      vertical: false
    });
*/
	$('#slider>ul>li').eq(0).remove();

  });
  $('<div></div>')
   .attr('id','gmenutip')
   .html('<ul></ul>')
   .hide()
   .bind('mouseover',function(){
     $('#gmenutip').show();
   	})
   .bind('mouseout',function(){
     $('#gmenutip').hide();
   	})
   .appendTo('body');

  $.getScript('/module/menutips.'+lang+'.js');
});

$(document).ready(function(){
  if($('div').is('#listing > .entries')) {
  	preset_selecter();
  	if($('#listing > .entries').not('.nodefault').length>0){
      refleshlisting();
      preset_sort();
  	}
    $('#selecter').submit(function(){
      var hash_query = $('#selecter').serialize();
      hash_query = hash_query.replace(/\&(amp;)?/g,'/');
      if($('select').is('#fs_category')) {
        var fs_category = $('#fs_category').val();
        location.href = '/'+lang+'/'+fs_category+'/#'+hash_query+'/#0';
      }else{
      	$('#listing > .top').hide();
      	$('#listing > .entries').removeClass('nodefault');
        preset_sort();
      }
      state_sp = -1;
      refleshlisting();
      return false;
    });
  }else if( $('form').is('#selecter') ) {
    $('#selecter').submit(function(){
      var hash_query = $('#selecter').serialize();
      hash_query = hash_query.replace(/\&(amp;)?/g,'/');
      var fs_category = $('#fs_category').val();
      location.href = '/'+lang+'/'+fs_category+'/#'+hash_query+'/#0';
      return false;
    });
  }
});

$(document).ready(function(){
  if($('div').is('.accordion')) {
//  	$('.accordion > h3').addClass('clearfix');
    $('.accordion').accordion({
      autoHeight: true,
      animated: 'slide',
      event: 'mouseover'
    });
  }
});

$(document).ready(function(){
  if($('#content_wrap>div').is('#news')){
    var hash = location.hash;
    if($('.entry').is(hash)){
      $(hash).show();
    };
    $('#newslist>ul>li>a')
     .bind('click',function(){
       var ihash = $(this).attr('href');
       ihash = ihash.replace(/^[^#]*/,'');
       if($('.entry').is(ihash)){
         $('#news>.entry:visible').hide('fast',function(){
           $(ihash).show('slow',function(){
             $('html,body').animate({ scrollTop: $(ihash).offset().top }, 'slow');
           });
         });
       }
      });
  }
});

