
var changer = new Changer();
var realisation = new Realisation();
//var news = new News();

function HistoryApi(){
  var $this = this,
    isHTML5;

  this.hasHTML5Support = function(){
    if(isHTML5 !== undefined){
      return isHTML5;
    } else {
      return isHTML5 = !!(window.history && history.pushState);
    }
  }

  this.changeUrl = function(url){
    if(this.hasHTML5Support()){
      history.pushState({}, "", url);
    } else {
      $.address.value(url);
    }
  }

  this.registerOnChange = function(){
    if(this.hasHTML5Support()){
      window.onpopstate = function(event){
        loadUrl(document.location.pathname);
      }
    } else {
      var firstRun = true;
      $.address.change(function(event){
        var href = event.path;
        if($.address.baseURL()+"/" != homepage){
          document.location = homepage+"#"+document.location.pathname;
          return;
        }
        if(href == "/" && firstRun){
          // do not load anything - main page is always loaded first
          firstRun = false;
          return;
        }
        firstRun = false;

        loadUrl(href);
      });
    }
  }

  this.registerForms = function(){
    $("form.local").live("submit", function(event){
      event.preventDefault();
      var $form = $(this),
        invalid = false;
      $(".required", $form).each(function(){
        $this = $(this);
        if($this.val() == ""){
          highlightRequired($this);
          invalid = true;
        }
      });
      $('input.required[name^="hinter_"]', $form).each(function(){
        $this = $(this);
          highlightRequired($this);
          invalid = true;
      });
      if(invalid){
        return;
      }
      $.ajax({
        type: "post",
        dataType: "json",
        url: $form.attr("action"),
        data: $form.serialize(),
        success: function(data, textStatus, XMLHttpRequest){
          if(data.url != undefined){
            History.changeUrl(data.url);
            if(data.redirect != undefined){
              loadUrl(data.url);
              return;
            }
          }
          updatePage(data);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
          data = {};
          try {
            data = $.parseJSON(XMLHttpRequest.responseText);
          } catch(error){
            data.content = XMLHttpRequest.responseText;
          }
          updatePage(data);
        },
        beforeSend: function(XMLHttpRequest){
          loader.show();
        },
        complete: function(XMLHttpRequest, textStatus){
          loader.hide();
        }
      });
    });
  }

  this.registerClick = function(){
    if(this.hasHTML5Support()){
      $("a.local").live("click", function(event){
        event.preventDefault();
        href = $(this).attr("href");

        if(href != document.location.pathname){
          history.pushState({}, "", href);
        }
        loadUrl(href);
      });
    } else {
      $("a.local").address(function(){
        href = $(this).attr("href");
        if(href == $.address.value()){
          $.address.update();
        }
        else {
          return href.replace(homepage, "");
        }
      });
    }
  }

  this.initialize = function(){
    if(this.hasHTML5Support() && $.address.value() != "/"){
      document.location = $.address.value();
    }
    this.registerForms();
    this.registerOnChange();
    this.registerClick();
  }

  this.initialize();
}
var History = new HistoryApi();

//number, decimals, dec_point, thousand_sep
function number_format(n, q, r, s){
  with(Math)return(""+round(~~n*(i=pow(10,q||1)))/i).replace(/(\d)(?=(.{3})+$)/g, "$1"+(s||" "))+(q>0?(r||",")+(i=""+round((n||1)*i)).slice(i.length-q):"")
}

function Loader(){
  this.show = function(){
    $("#loader").show();
  }
  this.hide = function(){
    $("#loader").hide();
  }
}
var loader = new Loader();

function loadUrl(url, options){
  var settings = $.extend({
    type: "post",
    dataType: "json",
    noCache: false
  }, options);

  if(cachedUrl = cache.page.get(url)){
    updatePage(cachedUrl.value);
  }
  else {
    $.ajax({
      type: settings.type,
      dataType: settings.dataType,
      url: url,
      success: function(data, textStatus, XMLHttpRequest){
        if(!settings.noCache){
          cache.page.add(url, data);
        }
        updatePage(data);
      },
      error: function(XMLHttpRequest, textStatus, errorThrown){
        data = {};
        try {
          data = $.parseJSON(XMLHttpRequest.responseText);
        } catch(error){
          data.content = XMLHttpRequest.responseText;
        }
        updatePage(data);
      },
      beforeSend: function(XMLHttpRequest){
        loader.show();
      },
      complete: function(XMLHttpRequest, textStatus){
        loader.hide();
      }
    });
  }
}

function showContent(){
  $("#shadow").fadeIn();
  $("#content").show().animate({"margin-top": 0}, "slow", "linear");
  changer.stop();
}

function hideContent(){
  $("#shadow").fadeOut();
  $("#content").animate({"margin-top": -700}, "slow", "linear");
  changer.start();
}

function updatePage(data){
  if(data.title != undefined){
    document.title = data.title;
  }
  if(data.content != undefined){
    if(!data.content){
      hideContent();
    } else {
      $("#content").html(data.content);
      showContent();
      initFancyBox();
      initScroll();
    }
  }

  $menu = $("li[id^='menu_']").removeClass("active");
  if(data.menu){
    $menu.filter(function(index){
      values = $(this).attr("id").replace(/menu_/, "").split("-");
      return data.menu.left >= parseInt(values[0]) && data.menu.right <= parseInt(values[1]);
    }).addClass("active");
  }
}

var Cache = function(options){
  this.settings = $.extend({
    maxSize: 50,
    lifetime: 300
  }, options);
  var settings = this.settings;

  var data = {};
  var size = 0;

  // Creating our own shift function because associative keys in js sucks
  var shift = function(obj){
    for(i in obj){
      value = data[i];
      delete data[i];
      return value;
    }
  }

  this.add = function(key, value){
    // If cache is full, remove first value
    if(size >= settings.maxSize){
      shift(data);
      size--;
    } else if(!data[key]){
      size++;
    }
    // Add the value at the end of array
    return data[key] = {
      expiresAt: new Date().getTime() + (settings.lifetime * 1000),
      value: value
    }
  }

  this.get = function(key){
    if(data[key] && data[key].expiresAt < new Date().getTime()){
      // cache expired
      delete data[key];
      size--;
      return undefined;
    }

    return data[key];
  }
}
var cache = {};
cache.page = new Cache();
cache.img = new Cache();

/*
var newsMarquee = function(){
  var $container = $("#footer"),
  $list = $("ul", $container),
  $items = $("li", $list),
  contentWidth,
  containerWidth;

    
}

  
//  $("#footer ul").clone().insertAfter("#footer ul");
//  $("#footer ul:first").animate({"margin-left": $("#footer ul:first").outerWidth() * -1}, 1000, "linear");

  function animateNews(){
    //    console.log("bam");
    $("#footer ul li:first").animate({"margin-left": $("#footer ul li:first").outerWidth() * -1}, 1000, "linear", function(){
      $(this).css("margin-left", 0).remove().appendTo("#footer ul");
      animateNews();
    });
      //      console.log(index);
      //      console.log(parseInt(value));
//      return parseInt(value) - 1;
//    });
//    setTimeout(animateNews, 50);
  }
//  animateNews();
*/

function highlightRequired(object){
  bg = object.css("background-color");
  color = object.css("color");
  object.animate({
    "background-color": "#f00",
    "color": bg
  }).animate({
    "background-color": bg,
    "color": color
  });
}

function initScroll(){
  var $toScroll = $("#text:not(:has(.scrollbar)), .scrollbar");
  if($toScroll.length){ // hack - bug in jScrollPane when jQuery does not return any element
    $toScroll.jScrollPane({
      showArrows: true
    }).find(".jspDrag").append("<div class=\"decorator\" />");
  }
}

function initFancyBox(){
  $("a.fancy").fancybox({
    autoScale : false,
    overlayColor: "#00250a"
  });
}

function updateFloorImg(buttonObj, src){
   $("<img/>").attr("src", src).load(function(){
      $("#apartmentFloors a.active").removeClass("active");
//      $("#apartmentFloors div.image img").removeClass("active");
      buttonObj.addClass("active");
      $(this).prependTo("#apartmentFloors div.image").next("img").fadeOut("normal", function(){
         $(this).remove();
      });
   });
}
function initImgCache(){
   $("#apartmentFloors a.floor").live("click", function(event){
     event.preventDefault();

      var $this = $(this);
      if($this.hasClass("active")){
         return false;
      }
      var url = this.href+"/ajx";

      if(cachedImg = cache.img.get(url)){
         updateFloorImg($this, cachedImg.value);
      }
      else {
         $.ajax({
            type: "post",
            dataType: "text",
            url: url,
            success: function(data){
               cache.img.add(url, data);
               updateFloorImg($this, data);
            },
            beforeSend: function(){
               loader.show();
            },
            complete: function(){
               loader.hide();
            }
         });
      }
   });
}

function initAparments(priceValues, areaValues){
  $("#filter_price_min, #filter_price_max, label[for=filter_price_min], label[for=filter_price_max]").hide();
  $("#priceSlider").slider({
    range: true,
    step: 1000,
    min: priceValues["min"],
    max: priceValues["max"],
    values: [priceValues["min_current"], priceValues["max_current"]],
    slide: function(event, ui) {
      $("#filter_price_min").val(ui.values[0]);
      $("#filter_price_max").val(ui.values[1]);
      $("#price span.min_value").text(number_format(ui.values[0]), 0, ".", " ");
      $("#price span.max_value").text(number_format(ui.values[1]), 0, ".", " ");
    }
  });
  $("#price").append('<span class="min_value">'+number_format(priceValues["min_current"], 0, ".", " ")+'</span><span class="max_value">'+number_format(priceValues["max_current"], 0, ".", " ")+'</span>');

  $("#filter_area_min, #filter_area_max, label[for=filter_area_min], label[for=filter_area_max]").hide();
  $("#areaSlider").slider({
    range: true,
    step: 1,
    min: areaValues["min"],
    max: areaValues["max"],
    values: [areaValues["min_current"], areaValues["max_current"]],
    slide: function(event, ui) {
      $("#filter_area_min").val(ui.values[0]);
      $("#filter_area_max").val(ui.values[1]);
      $("#area span.min_value").text(number_format(ui.values[0]), 0, ".", " ");
      $("#area span.max_value").text(number_format(ui.values[1]), 0, ".", " ");
    }
  });
  $("#area").append('<span class="min_value">'+number_format(areaValues["min_current"], 0, ".", " ")+'</span><span class="max_value">'+number_format(areaValues["max_current"], 0, ".", " ")+'</span>');

  $("span.tip").bt({
    positions: ["top"],
    shrinkToFit: true,
    shadow: true,
    fill: "#00995D"
//    ,overlap: -3
  });
}

$(function(){
  initFancyBox();
  initScroll();
  initImgCache()
  $(".gallery a.video").live("click", function(event){
    event.preventDefault();
    $.fancybox({
      href: this.href,
      padding: 0,
      autoScale: false,
      width: 850,
      height: 510,
      overlayColor: "#00250a",
      href: this.href.replace(new RegExp("watch\\?v=", "i"), "v/"),
      type: "swf",
      swf: {
        "wmode": "transparent",
        "allowfullscreen": "true"
      }
    });
  });

  if(document.location.href == homepage){
    changer.initialize();
    changer.start();
    realisation.initialize();
  } else {
    $.ajax({
      type: "post",
      dataType: "json",
      url: homepage+"components",
      success: function(data, textStatus, XMLHttpRequest){
        $("#changer").html(data.changer);
        $("#bottomContainer").html(data.bottomBar);
        changer.initialize();
        realisation.initialize();
      }
    });
  }

});

