$(function(){
    Backbone.sync = function(method, model) {
      $.ajaxSetup({
          timeout: 40000
      });
      if(model.name == "dates"){          
          conditions = appState.attributes;
          conditions.name = model.name;

          $.ajax({
                url: model.url,
                data: conditions,
                type: "post",
                success: function(data){model.success(data);},
                error: function(data) {model.error(data);}
            });
      } else {
          //var m = JSON.stringify(model);
          //console.log(model.attributes);
          //start ajax for form data
            $.ajax({
                url: "php/search.php",

                data: model.attributes,
                type: "post",
                success: function(data){model.success(data);},
                error: function(data) {model.error(data);}
            });
            //start ajax for serch result
            $.ajax({
                url: "php/search_result.php",
                data: model.attributes,
                type: "post",
                success: function(data){model.success_result(data);},
                error: function(data) {model.error_result(data);},
                beforeSend: function() {model.beforeSend_result();},
                complete: function() {model.complete_result();}
            });
        }
    };

  window.AppState = Backbone.Model.extend({
    defaults: function() {
      return {
          //set by default France
          country:  773,
          name: 'startup'
//        region: false,
//        city: false,
//        type: false,
//        arrival_date: false,
//        price_from: false,
//        price_to: false,
//        page: 1
      };
    },
    initialize: function(){
            
    },
    url: "php/search.php",
    success: function(data){
        //console.log(data);
        if(data == "") return;
        try {
            data = eval('(' + data + ')')
        } catch(e) {
            
        }
        
        $(data).each(function(i, obj){
            $("#sf_"+obj.field, this.el).html(obj.value);
            if(obj.field == "types")
                $("#sf_"+obj.field, this.el).trigger("liszt:updated");
        });
        
        if(appState.get("name"))
            appState.unset("name");
    },
    error: function(data){
        console.log("error!");
        console.log(data);
    },
    
    success_result: function(data){
        data = eval('(' + data + ')');

        App.render(data);
    },
    error_result: function(data){
        console.log("error!");
        console.log(data);
    },
    
    beforeSend_result: function(){
        $("#result_area").html("").append("Loading...");
    },
    
    complete_result: function() {
        
    }
  });

  var appState = new AppState();
  
window.PossibleDates = Backbone.Model.extend({
    defaults: function(){
      return {
          possibleDates: []
      };
    },
    url: "php/search.php",
    name: "dates",

    success: function(data){
      if(data != ""){
        try {
            data = eval('(' + data + ')')
        } catch(e) {
            console.log("Some erros. Please try your search again.");
        }
            possibleDates.set({possibleDates: data});
      }
      //when we receive data we are run <show> command for datepicker
      //TODO: try to change this moment
      App.showDatepicker();
    },
    error: function(data){
      console.log("error!");
      console.log(data);
    }
});
  
var possibleDates = new PossibleDates();
  
window.Router = Backbone.Router.extend({
    routes: {
      "!/:query" : "dispatcher"
    },

    dispatcher: function(q){
      // use this function for "back" button

      var parts = q.split("&"), args = {};
      
      
      for(var i = 0; i < parts.length; i++){
          
              args[parts[i].split("=")[0]] = parts[i].split("=")[1];
              
          
      }
          
      //console.log("we get all params");
      appState.set(args);
      
      //console.log("router (dispatcher) finished!");
      
    },
    initialize: function(options){
        //console.log("Router init");
        
    }
});
  
var router = new Router();

    window.AppView = Backbone.View.extend({

        el: $("#ajaxApp"),

        template: _.template($("#item_template").html()),

        paginator: _.template($("#paginator_template").html()),
        
        total_founded: _.template($("#total_founded_template").html()),

        resultArea: $("#result_area"),

        paginationArea: $(".paginator"),
        
        totalArea: $("#total_founded"),

        datepickerOptions: {
                minDate: new Date(),
                dateFormat: "dd-mm-yy",
                firstDay: 1,
                beforeShowDay: function(date) { 
                    var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
                    d = (d < 10)? "0" + d: d;
                    m = (++m < 10)? "0" + m: m;
                    if($.inArray(d + '-' +  m + '-' + y, possibleDates.get("possibleDates")) == -1)
                        return [false, 'not_available'];
                    else 
                        return [true, 'available'];
                },
                onClose: function(){ 
                    var DP_date =  $(this).datepicker( "getDate" );

                    if(DP_date != null){
                        appState.set({
                            arrival_date: DP_date.getFullYear() + "-" + (DP_date.getMonth() + 1) + "-" + DP_date.getDate()
                        });

                        //show "delete" button
                        //TODO: move to different function
                        var container = $(this).parent()

                        $(container).append("<a href='javascript: void(0)' id='delete_date' class='delete_date'><img src='css/images/bullet_cross.png' /></a>");
                        appState.fetch();
                    }
                    $(this).datepicker("destroy");
                    
                    
                }
        },

        events: {
          "change #sf_country":  "changeCountry",
          "change #sf_region" :  "changeRegion",
          "change #sf_city"   :  "changeCity",
          "change #sf_types": "changeType",
          "click #sf_arrival_date": "openDatepicker",
          "click #delete_date": "hideDeleteButton",
          "change #sf_categories": "changeCategory",
          "change #sf_persons": "changePersons",
          "change #sf_sort": "changeSort",
          "change #sf_price_from": "changePriceFrom",
          "change #sf_price_to" : "changePriceTo"
        },

        initialize: function() {
            //console.log("view init started!");
            
            
        
            
            $("#sf_sort").html(_.template($("#sorting_select_template").html()));
            //console.log("view init finished!");
        },

        render: function(items) { 
            var tpl = this;
            var test = appState.attributes;

            //clear result area
            this.resultArea.html("");
            //console.log(items.pagination);
            //if no result, show message
            if(items.values == false){
                this.resultArea.html("No results!");
                this.paginationArea.html("");
                return;
            }

            _.each(items.values, function(value, i){ 
                //console.log(i, value.id, value.prices);
                tpl.resultArea.append(tpl.template({
                                                        i: i,
                                                        title: value.title,
                                                        country: value.country,
                                                        region: value.region,
                                                        city: value.city,
                                                        beds: value.beds,
                                                        stars: value.sterren,
                                                        persone: value.persone,
                                                        id: value.id,
                                                        type: value.type,
                                                        image: value.image,
                                                        price: value.prices,
                                                        zee: value.zee,
                                                        country_id: value.country_id,
                                                        region_id: value.region_id,
                                                        city_id: value.city_id
                                                      }));
            });
            
            this.paginationArea.html(tpl.paginator({
                pages: items.pagination.pages,
                curpage: items.pagination.curpage,
                LRrange: 5
            }));
            
            
            this.totalArea.html(
                tpl.total_founded({
                    total: items.pagination.total
                })
            );


        },
        changeCountry: function(){
            
            appState.set({
                country: $("#sf_country", this.el).val(),
                
                page: 1
            });
            appState.unset("region");
            appState.unset("city");
            appState.fetch();
        },

        changeRegion: function(){
            appState.set({
                region: $("#sf_region").val(),
                city: false,
                page: 1
            });
            appState.fetch();
        },

        changeCity: function(){
            appState.set({
                city: $("#sf_city").val(),
                page: 1
            });
            appState.fetch();
        },

        changeType: function(){        
            appState.set({type: $("#sf_types").val()});
            appState.fetch(); 
        },

        openDatepicker: function(){
            var container = $(".datepicker_container", this.el);

            $("input", container).addClass("loading");
            $("img", container).css({
                                    "display": "block",
                                    "left": ($("input", container).width() - $("img", container).width())/2 + "px"
            });

            possibleDates.fetch();
        },

        showDatepicker: function(){
            var container = $(".datepicker_container", this.el);
            var datepickerEl = $("input", container)
            datepickerEl.removeClass("loading");
            $("img", container).css("display", "none");

            datepickerEl.datepicker(this.datepickerOptions);
            datepickerEl.datepicker("show");
        },
        
        hideDeleteButton: function(){
            appState.set({
                arrival_date: false
            });
            $("#sf_arrival_date").val("").parent().find("a").eq(0).remove();
            
            appState.fetch();
        },
        
        changeCategory: function(){
            appState.set({
                category: $("#sf_categories").val()
            });
            
            appState.fetch();
            
        },
        
        changePersons: function (){
            appState.set({
                persons: $("#sf_persons").val()
            });
            
            appState.fetch();
        },
        
        changeSort: function(){
            appState.set({
                sort: $("#sf_sort").val()
            });
            
            appState.fetch();
        }, 
        
        changePriceFrom: function(){
            appState.set({
                price_from: $("#sf_price_from", this.el).val()
            });
            
            appState.fetch();
        },
        
        changePriceTo: function(){
            appState.set({
                price_to: $("#sf_price_to", this.el).val()
            });
            
            appState.fetch();
        }
        
    });

    window.App = new AppView({
        model: appState
    });

    //if path is changed we fetch new data  from server.
    router.bind("all", function(route){
        //console.log("router event started");
        appState.fetch();
    });

    //if any param is changed we change path of our app and make navigation
    appState.bind("all", function(){
        var navipath = "#!/";
        
        _.each(this.attributes, function(value, key){
            
            if(value != "false" && value != false ){
                
                navipath += key + "=" + value + "&"
            }
                
        });
        
        //console.log(navipath);
        // remove last "&" character
        navipath = navipath.slice(0, -1);
        
        router.navigate(navipath, false);

    });
    
    
    
    Backbone.history.start(); 
    
});
