/*!
 * Copyright (c) 2009-2011 ENCOM Sp. z o.o.
 */

// extensions
Number.prototype.toUnit = function(options) {
 options = $.extend({precision: 0, unit: '', separator: ',', delimiter: ' '}, options);
 var n = this, c=options.precision, d = options.separator, t = options.delimiter, i = parseInt(n = (+n || 0).toFixed(c)) + '', j = (j = i.length) > 3 ? j % 3 : 0;
 return (j ? i.substr(0, j) + t : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + (n - i).toFixed(c).slice(2) : '') + options.unit;
};

jQuery.fn.dataTableExt.oSort['formatted-num-asc'] = function(x,y){
 x = x.replace(/[^\d\-\.\/]/g,'');
 y = y.replace(/[^\d\-\.\/]/g,'');
 if(x.indexOf('/')>=0)x = eval(x);
 if(y.indexOf('/')>=0)y = eval(y);
 return x/1 - y/1;
};

Array.prototype.skipBlank = function() {
  return $.grep(this, function(n, i) {
    return typeof(n) !== 'undefined' && n != null && n !== '';
  })
};

jQuery.fn.dataTableExt.oSort['formatted-num-desc'] = function(x,y){
 x = x.replace(/[^\d\-\.\/]/g,'');
 y = y.replace(/[^\d\-\.\/]/g,'');
 if(x.indexOf('/')>=0)x = eval(x);
 if(y.indexOf('/')>=0)y = eval(y);
 return y/1 - x/1;
};

// global vars
var title = document.title,
    calcUrl = 'calculator.html?iframe=true&width=425&height=375',
    apiHost = 'http://94.42.141.241',
    apiKey = 'E4E59719-6D10-174F-73AA-BF879E7388F8',
    //apiHost = 'http://ren24_api.local',
    //apiKey = '71BC9DCA-0970-72A4-41FB-A851FE936477',
    agentTransl = [['name', ''], ['phone', 'tel.: '], ['mobile', 'tel. kom.: '], ['email', 'email: '], ['license_no', 'nr licencji: ']],
    dataTableI18nPL = {
      "sProcessing":   "Proszę czekać...",
      "sLengthMenu":   "Pokaż _MENU_ pozycji",
      // "sLengthMenu":   '<select size="1" >'+
      //                  '<option value="10">10 ofert na stronie</option>'+
      //                  '<option value="20">20 ofert na stronie</option>'+
      //                  '<option value="50">50 ofert na stronie</option>'+
      //                  '</select>',
      "sZeroRecords":  "Nie znaleziono żadnych ofert spełniających kryteria wyszukiwania",
      "sInfo":         "Oferty od _START_ do _END_ z _TOTAL_ znalezionych",
      "sInfoEmpty":    "Ofert 0 z 0 dostępnych",
      "sInfoFiltered": "(filtrowanie spośród _MAX_ dostępnych ofert)",
      "sInfoPostFix":  "",
      "sSearch":       "Filtruj wg. frazy: ",
      "sUrl":          "",
      "oPaginate": {
        "sFirst":    "Pierwsza",
        "sPrevious": "Poprzednia",
        "sNext":     "Następna",
        "sLast":     "Ostatnia"
      }
    },
    previousQueryString = '',
    transCategory = {1: 'mieszkania', 2: 'domu', 3: 'działki', 4: 'lokalu usługowego', 5: 'obiektu'},
    transBargain = {1: 'Oferty sprzedaży', 3: 'Oferty wynajmu'},
    oTable = null;

// global functions
function composePageTitle(pathNames) {
  if (pathNames[1]) {
    $.address.title(title + ' - oferta ' + $('#offers_'+pathNames[1]+' h3.title').text());
  } else {
    $.address.title(title + ' - znalezione oferty');
  }
};

function setCurrentMenuItem(pathNames) {
    var address;
    $('#menu ul > li.current').removeClass('current');
    switch(pathNames[0]) {
      case 'about':
        address = ''; break;
      case 'search': case 'offers':
        address = 'search'; break;
      default:
        address = pathNames[0]; break;
    }
    $('#menu ul > li:has(a[rel=address:/'+address+'])').addClass('current');
};

function streetPart(offer, pre, post) {
  return offer.address_street && pre+offer.address_street+post || '';
};

function cityPart(offer, pre, post, sep) {
  return (offer.city_name || offer.district_name) && pre+[offer.city_name, offer.district_name].skipBlank().join(sep || ', ')+post || '';
};

function pricePart(offer, pre, post) {
  return offer.price && pre+offer.price.toUnit({unit:' PLN'})+post || '';
};

function sqmPricePart(offer, pre, post) {
  return offer.price && offer.area && pre+Math.round(offer.price/offer.area).toUnit({unit:' PLN/m<sup>2</sup>'})+post || '';
};

function areaPart(offer, pre, post) {
  return offer.area && pre+offer.area.toUnit({unit: ' m<sup>2</sup>'})+post || '';
};

function roomCountPart(offer, pre, post) {
  return offer.room_count && pre+offer.room_count+post || '';
};

function lotAreaPart(offer, pre, post) {
  return offer.lot_area && pre+offer.lot_area.toUnit({unit: ' m<sup>2</sup>'})+post || '';
};

function descriptionPart(offer, pre, post) {
  return offer.description && pre+offer.description+post || '';
};

function detailsPart(offer, pre, post) {
  return offer.details &&
      pre + offer.details
        .replace(/,/g, ' &#8226; ')
        .replace(/\n(.+):\n/g, '<br /><b>$1</b> &#8226; ')
        .replace(/\(m2\)/g, '(m<sup>2</sup>)')
        .replace(/:\stak/g, ': &#8730;')
        .replace(/<br\s*\/>/, '') + post || '';
};

function buildOfferList(data) {
  if (data.length != 0) {
    var tblData = $.map(data, function(n, i) {
      var photo, identifier, region, city, street, area, price, sqmprice;
      photo = n.offer.photo_path ?
        '<img src="'+apiHost+n.offer.photo_path.replace(/.\w+$/, '_square$&')+'" alt="" />' :
        '<img src="img/no_photo_square.png" />';
      identifier = '<a href="#" rel="address:/offers/'+n.offer.id+'">'+n.offer.identifier+'</a>';
      region = n.offer.region.split(', ');
      city = n.offer.city_name || '';
      city += '<small><br/>' + region[0] + '<br/>' + region[1] + '<br/>' + region[2] + '</small>';
      street = n.offer.address_street || '';
      area = n.offer.area ? n.offer.area.toUnit() : '';
      price = n.offer.price ? n.offer.price.toUnit() : '';
      sqmprice = n.offer.price && n.offer.area ? Math.round(n.offer.price/n.offer.area).toUnit() : '';
      return [[photo, identifier, city, street, area, price, sqmprice, n.offer.id]];
    })
    oTable.fnClearTable(0);
    oTable.fnAddData(tblData);
  } else {
    oTable.fnClearTable(1);
  };
};

function setOfferListInfo(params) {
  $('#offers > h3').text(transBargain[params['bargain_id']] + ' ' + transCategory[params['category_id']]);
};

function buildOffer(data) {
  var offer = data.offer,
              containerId = ['offers', offer.id].join('_'),
              container = $('#offer_template').clone().attr('id', containerId).appendTo('#ren24'),
              location, features,
              agent = '<h4>Osoba do kontaktu</h4><p>';
  
  $('h3.title', container).text(offer.identifier+' ('+[offer.category, offer.bargain].join(' - ')+')');
  
  location = streetPart(offer, '<span>', '</span><br />');
  location += cityPart(offer, '<span>', '</span><br />');
  location += offer.region;
  $('p.location', container).html(location);
  
  features = pricePart(offer, '<h2>', '</h2>');
  features += areaPart(offer, '<h2>', ' <span>(');
  features += sqmPricePart(offer, '', ')</span></h2>');
  features += roomCountPart(offer, 'Liczba pokoi: ', '<br />');
  features += lotAreaPart(offer, 'Powierzchnia działki: ', '');
  $('div.features', container).html(features);
  
  $.each(agentTransl, function(i, o) {
    if (offer.agent[o[0]]) agent += o[1] + offer.agent[o[0]] + '<br />';
  });
  if (!offer.agent.license_no) {
    agent += '<br /><b>Pośrednik odpowiedzialny</b><br />' +
      offer.agent.broker_name + ', nr licencji: ' + offer.agent.broker_license_no;
  }
  agent += '</p>'
  $('div.agent', container).html(agent);
  
  $('div.description', container)
    .html(descriptionPart(offer, '<p>', '</p>'))
    .append(detailsPart(offer, '<p>', '</p>'));
  
  container.show();
  
  // buttons
  $('a.back', container).click(function() {window.history.back(); return false;});
  
  $('div.links', container)
    .append('<a href="'+composeGmapsUrl(offer)+'" class="map" rel="prettyPhoto[iframes_'+containerId+']" title="Przybliżona lokalizacja oferty">MAPA</a>')
    .append('<a href="'+calcUrl+'" class="calculator" rel="prettyPhoto" title="Kalkulator opłat">KALKULATOR</a>');
  
  // photos
  if (offer.photos && offer.photos.length != 0) {
    buildGallery(offer)
      .appendTo($('div.photos',container))
      .galleryView({
        nav_theme: 'dark',
        panel_width: 400,
        panel_height: 300,
        frame_width: 75,
        frame_height: 75,
        transition_interval: 15000,
        background_color: '#ECEFE9',
        // border: '1px solid #D7D7D7',
        border: '1px solid #ECEFE9',
        // transition_speed: 1200,
        filmstrip_position: 'top',
        // easing: 'easeInOutBack',
        pause_on_hover: true
      });
  }
  
  // init prettyPhotos
  $('a[rel^=prettyPhoto]', container).prettyPhoto({
    theme:'light_square',
    changepicturecallback: function() {
      $('div.pp_details div.pp_nav > a').each(function(i, el) {
        el = $(el);
        if(el.hasClass('disabled')) {
          el.hide();
        } else {
          el.show();
        }
      });
    }
  });
  
  // email form
  $('.email form label', container).each(function(i, el) {
    el = $(el);
    var suffix = el.attr('for'),
        id = containerId+'_email_'+suffix;
    el.attr('for', id);
    $('[name='+suffix+']', container).attr('id', id);
  });
  
  $('.email form', container).ajaxForm({
    url: 'send.php',
    data: {identifier: offer.identifier, url: window.location.href},
    dataType: 'jsonp',
    type: 'GET',
    jsonp: 'callback',
    beforeSubmit: function() {
      $('form input[type=submit]', container)
        .attr('disabled', 'true')
        .oneTime('5s', function() {$(this).removeAttr('disabled')});
    },
    success: function(data) {
      $('.email .notice', container).html('<p class="'+data.status+'">'+data.message+'</p>');
      $('.email .notice p', container)
        .click(function() { $(this).fadeOut('slow');})
        .oneTime('5s', function() {$(this).fadeOut('slow');});
    }
  });
  
};

function buildGallery(offer) {
  var galleryId = 'gallery_' + offer.id,
      gallery = $('<div id="'+galleryId+'" class="galleryview"></div>'),
      filmstrip = $('<ul class="filmstrip"></ul>');
  $.each(offer.photos, function(i, o) {
    var filename = apiHost+o.public_filename;
    $('<div class="panel"></div>')
      .append('<a title="'+(o.description || '')+'" href="'+filename+'" rel="prettyPhoto['+galleryId+']">'+
        '<img src="'+filename.replace(/.\w+$/, '_medium$&')+'" alt="" /></a>')
      .append(o.description ? '<div class="panel-overlay"><p>'+o.description+'</p></div>' : '')
      .appendTo(gallery);
    filmstrip.append('<li><img src="'+filename.replace(/.\w+$/, '_square$&')+'" alt="" /></li>');
  });
  return gallery.append(filmstrip);
};

function composeGmapsUrl(offer) {
  // TODO zoom & query, region gsubem
  var location = offer.region.replace(/(woj.|gm.)\s*/g, '').split(', ');
  location.splice(1,1);
  if (offer.city_name) location[0] = offer.city_name;
  if (offer.address_street) {
    location.unshift(offer.address_street);
  } else if (offer.district_name) {
    location.unshift(offer.district_name);
  }
  var url = 'http://maps.google.pl/maps?f=q&source=s_q&hl=pl&geocode=&q=';
  url += encodeURIComponent(location.join(',+'));
  url += '&iwloc=&mrt=loc&z=14&output=embed&iframe=true&width=625&height=375';
  return url;
}

$.ajaxSetup({
  'beforeSend': function(xhr) {
    xhr.setRequestHeader("Accept", "text/javascript, text/html, application/xml, text/xml, */*");
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  }
});


$(function() {
  
  oTable = $('#offer_table').dataTable({
//        bFilter: false,
//        bStateSave: true,
    sPaginationType: 'full_numbers',
    bAutoWidth: false,
    sDom: '<"clearfix top"lf>rt<"clearfix bottom"ip>',
    aoColumns: [
      {bSortable: false, bSearchable: false, sClass: 'photo'},
      {sTitle: "Identyfikator", sClass: 'identifier'},
      {sTitle: "Miejscowość"},
      {sTitle: "Ulica/Okolica"},
      {sTitle: "Pow. (m<sup>2</sup>)", sClass: 'ralign', sType: 'formatted-num'},
      {sTitle: "Cena (PLN)", sClass: 'ralign', sType: 'formatted-num'},
      {sTitle: "Cena/m<sup>2</sup>", sClass: 'ralign', sType: 'formatted-num'},
      {bVisible: false, bSearchable: false, bSortable: false} // id
    ],
    aaSorting: [[5, 'asc']],
    fnRowCallback: function(nRow, aData, iDisplayIndex) {
      $(nRow).click(function(e) {
        e.preventDefault();
        $.address.value('/offers/'+aData[7]);
      })
      return nRow;
    },
    // fnDrawCallback: function(e) {
    //   $('.identifier > a').address();
      // check if has events
      // $('.identifier > a').each(function(i, o) {
      //   o = $(o);
      //   if (o.data('events') == null) {
      //     console.info('registering address event')
      //     o.address();
      //   }
      // })
    // },
    oLanguage: dataTableI18nPL
  });
  
//   $('#search_form').ajaxForm({
//     url: [apiHost, 'offers.json'].join('/'),
//     data: {api_key: apiKey},
//     dataType: 'jsonp',
//     type: 'GET',
//     jsonp: 'callback',
//     success: function(data) {
//       $('#notification').hide();
//       buildOfferList(data);
//       previousQueryString = '';
//       $.address.value('/offers');
//     }
//   });
//   
//   $('#search_form').submit(function() {
//     $('#notification').show();
//   });
//   
//   $('#form_clearer').click(function(e) {
//     e.preventDefault();
// //    $('#search_form').clearForm();
//     $('#search_form').resetForm();
// //    return false;
//   });
  
  $.address.change(function(event) {
    
    // console.info(event.pathNames);
    // console.info(event.queryString);
    // console.info(event.parameters);
    
    var names = event.pathNames,
        section = $('#ren24 #'+names.join('_'));
    
    // show requested section
    $('#ren24 > div').hide();
    switch(names.length) {
      case 1: //offer list
        section.show();
        // query api only if additional parameters && different values
        if (event.parameterNames.length > 0 && event.queryString !== previousQueryString) {
          $('#notification').show();
          $.ajax({
            url: [apiHost, 'offers.json'].join('/'),
            data: jQuery.extend(event.parameters, {api_key: apiKey}),
            dataType: 'jsonp',
            type: 'GET',
            jsonp: 'callback',
            success: function(data) {
              $('#notification').hide();
              buildOfferList(data);
              setOfferListInfo(event.parameters);
              previousQueryString = event.queryString;
            }
          });
        }
        composePageTitle(names);
        break;
      case 2: //offer presentation
        if (section.size() == 0) { // fetch from server
          $('#notification').show();
          $.ajax({
            url: [apiHost, names[0], names[1]].join('/') + '.json',
            data: {api_key: apiKey},
            dataType: 'jsonp',
            type: 'GET',
            jsonp: 'callback',
            success: function(data) {
              $('#notification').hide();
              buildOffer(data);
              composePageTitle(names);
            }
          });
        } else { // already fetched - just show
          section.show();
          composePageTitle(names);
        }
        break;
    }
    // setCurrentMenuItem(names);
  });
  
  // featured offers
  // $.ajax({
  //   url: apiHost + '/offers.json',
  //   data: {api_key: apiKey, with_photo_only: true, recent: 3},
  //   dataType: 'jsonp',
  //   type: 'GET',
  //   jsonp: 'callback',
  //   success: function(data) {
  //     if (data.length != 0) {
  //       var tblData = $.map(data, function(n, i) {
  //         var html = (i == 0) ? '<div class="first">' : '<div>';
  //         html += '<img src="'+apiHost+n.offer.photo_path.replace(/.\w+$/, '_small$&')+'" alt="" />'
  //         html += areaPart(n.offer, '<p class="area">', '</p>');
  //         html += pricePart(n.offer, '<p class="price">', '</p>');
  //         html += streetPart(n.offer, '<p>', '</p>');
  //         html += cityPart(n.offer, '<p>', '</p>', ' &#8226; ');
  //         html += '</div>';
  //         $(html).appendTo('#featured_offers').click(function(e) {
  //           e.preventDefault();
  //           $.address.value('/offers/'+n.offer.id);
  //         });
  //       });
  //     }
  //   }
  // });
    
  // $('#time_period').change(function() {
  //   if ($("#time_period option:selected").val() === '') $('#new_only').attr('checked', false);
  // });
});
