
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(){
    var firstRun = true;
    if(this.hasHTML5Support()){
      window.onpopstate = function(event){
        if(!firstRun){
          loadUrl(document.location.pathname+document.location.search);
        }
      }
    } else {
      $.address.change(function(event){
        var href = event.value;
        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;
        }

        loadUrl(href);
      });
    }
    firstRun = false;
  }

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

        if(!href) return;

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

        if(!href) return;

        if(href == $.address.value()){
          $.address.update();
        }
        else {
          return href.replace(homepage, "");
        }
      });
    }
  }

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

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

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;
    }
  }
  //   var pop = 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();
cache.client = new Cache();

function updatePage(data){
  $("#sliderTopContainer, #sliderBottomContainer, #text").html("");
  $("#submenu, #breadcrumbs, #heightFix").remove();
  clientTitle = null;

  if(data.title != undefined){
    document.title = data.title;
  }
  if(data.content != undefined){
    $("#text").html(data.content);
  }
  if(data.breadcrumbs != undefined){
    $("#content").prepend(data.breadcrumbs);
  }
  if(data.submenu != undefined){
    $("#container").prepend(data.submenu);
  }
  if(data.sliderTop != undefined){
    $("#sliderTopContainer").html(data.sliderTop);
    initializeSliderTop();
  }
  if(data.sliderBottom != undefined){
    $("#sliderBottomContainer").html(data.sliderBottom);
    initializeSliderBottom();
  }
  if(data.containerClass != undefined){
    $("#container").attr("class", data.containerClass);
  }
  if(data.contentClass != undefined){
    $("#content").attr("class", data.contentClass);
  }

  $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");
  }

  initSubmenu();

  $(document).scrollTop(0);
}

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 updateClientImg(buttonObj, src){
  $("<img/>").attr("src", src).load(function(){
    $("#client .presentation li").removeClass("active");
    buttonObj.parent().addClass("active");
    $(this).prependTo("#client .picture").next("img").fadeOut("normal", function(){
      $(this).remove();
    });
  });
}

function initSubmenu(){
  $("#submenu ul li:not(.active) div").css({
    height: 0
  });
}

function addDiagramHovers(){
  $("#dlx-start").hover(function(){
    $("#dlx-as1, #dlx-as2").stop().animate({opacity: 1});
    $("#dlx-1, #dlx-2, #dlx-3, #dlx-4, #dlx-5, #dlx-a, #dlx-b, #dlx-c").stop().animate({opacity: 0.2});
  }, function(){
    $("#dlx-as1, #dlx-as2").stop().animate({opacity: 0.2});
    $("#dlx-1, #dlx-2, #dlx-3, #dlx-4, #dlx-5, #dlx-a, #dlx-b, #dlx-c").stop().animate({opacity: 1});
  });
  $("#dlx-pot, #dlx-1, #dlx-2, #dlx-3, #dlx-4").hover(function(){
    $("#dlx-pos, #dlx-start").stop().animate({opacity: 0.2});
    $("#dlx-ap, #dlx-a1, #dlx-a2, #dlx-a3, #dlx-aa, #dlx-ab, #dlx-ac").stop().animate({opacity: 1});
  }, function(){
    $("#dlx-pos, #dlx-start").stop().animate({opacity: 1});
    $("#dlx-ap, #dlx-a1, #dlx-a2, #dlx-a3, #dlx-aa, #dlx-ab, #dlx-ac").stop().animate({opacity: 0.2});
  });
  $("#dlx-pos").hover(function(){
    $("#dlx-pot, #dlx-start, #dlx-1, #dlx-2, #dlx-3, #dlx-4").stop().animate({opacity: 0.2});
    $("#dlx-a5, #dlx-aa, #dlx-ab, #dlx-ac").stop().animate({opacity: 1});
  }, function(){
    $("#dlx-pot, #dlx-start, #dlx-1, #dlx-2, #dlx-3, #dlx-4").stop().animate({opacity: 1});
    $("#dlx-a5, #dlx-aa, #dlx-ab, #dlx-ac").stop().animate({opacity: 0.2});
  });
  $("#dlx-5").hover(function(){
    $("#dlx-pot, #dlx-start, #dlx-1, #dlx-2, #dlx-3, #dlx-4").stop().animate({opacity: 0.2});
    $("#dlx-a5, #dlx-aa, #dlx-ab, #dlx-ac").stop().animate({opacity: 1});
  }, function(){
    $("#dlx-pot, #dlx-start, #dlx-1, #dlx-2, #dlx-3, #dlx-4").stop().animate({opacity: 1});
    $("#dlx-a5, #dlx-aa, #dlx-ab, #dlx-ac").stop().animate({opacity: 0.2});
  });
  $("#dlx-a").hover(function(){
    $("#dlx-pot, #dlx-start, #dlx-1, #dlx-2, #dlx-3, #dlx-4, #dlx-b, #dlx-c").stop().animate({opacity: 0.2});
    $("#dlx-a5, #dlx-aa").stop().animate({opacity: 1});
  }, function(){
    $("#dlx-pot, #dlx-start, #dlx-1, #dlx-2, #dlx-3, #dlx-4, #dlx-b, #dlx-c").stop().animate({opacity: 1});
    $("#dlx-a5, #dlx-aa").stop().animate({opacity: 0.2});
  });
  $("#dlx-b").hover(function(){
    $("#dlx-pot, #dlx-start, #dlx-1, #dlx-2, #dlx-3, #dlx-4, #dlx-a, #dlx-c").stop().animate({opacity: 0.2});
    $("#dlx-a5, #dlx-ab").stop().animate({opacity: 1});
  }, function(){
    $("#dlx-pot, #dlx-start, #dlx-1, #dlx-2, #dlx-3, #dlx-4, #dlx-a, #dlx-c").stop().animate({opacity: 1});
    $("#dlx-a5, #dlx-ab").stop().animate({opacity: 0.2});
  });
  $("#dlx-c").hover(function(){
    $("#dlx-pot, #dlx-start, #dlx-1, #dlx-2, #dlx-3, #dlx-4, #dlx-a, #dlx-b").stop().animate({opacity: 0.2});
    $("#dlx-a5, #dlx-ac").stop().animate({opacity: 1});
  }, function(){
    $("#dlx-pot, #dlx-start, #dlx-1, #dlx-2, #dlx-3, #dlx-4, #dlx-a, #dlx-b").stop().animate({opacity: 1});
    $("#dlx-a5, #dlx-ac").stop().animate({opacity: 0.2});
  });
}

function showDiagram(){
  return;
  var speed = "normal";
  $("#diagram-bg:not(:visible)").slideDown("slow", function(){
    $("#dlx-start").fadeIn(speed, function(){
      $("#dlx-as1").show("blind", {direction: "right"}, speed, function(){
        $("#dlx-pot").fadeIn(speed, function(){
          $("#dlx-ap").slideDown(speed, function(){
            $("#dlx-1").fadeIn(speed, function(){
              $("#dlx-a1").show("blind", {direction: "right"}, speed, function(){
                $("#dlx-2").fadeIn(speed, function(){
                  $("#dlx-a2").show("blind", {direction: "left"}, speed, function(){
                    $("#dlx-3").fadeIn(speed, function(){
                      $("#dlx-a3").show("blind", {direction: "down"}, speed, function(){
                        $("#dlx-4").fadeIn(speed, function(){
                          $("#dlx-as2").slideDown(speed);
                          $("#dlx-a4").show("blind", {direction: "left"}, speed, function(){
                            $("#dlx-pos").fadeIn(speed, function(){
                              $("#dlx-a5").slideDown(speed, function(){
                                $("#dlx-5").fadeIn(speed, function(){
                                  $("#dlx-aa").slideDown(speed, function(){
                                    $("#dlx-a").fadeIn(speed, function(){
                                      $("#dlx-ab").slideDown(speed, function(){
                                        $("#dlx-b").fadeIn(speed, function(){
                                          $("#dlx-ac").slideDown(speed, function(){
                                            $("#dlx-c").fadeIn(speed, function(){
                                              $("#diagram").find(".arrow").animate({opacity: 0.2});
                                              addDiagramHovers();
                                              $("#diagram-links").fadeIn(speed, function(){
                                                $("#diagram-call").fadeIn(speed);
                                              });
                                            });
                                          });
                                        });
                                      });
                                    });
                                  });
                                });
                              });
                            });
                          });
                        });
                      });
                    });
                  });
                });
              });
            });
          });
        });
      });
    });
  });
}
function hideDiagram(){
  $("#diagram-bg").slideUp("slow", function(){
    $("#diagram-bg, #diagram-links, #diagram-call").find("[id|=dlx]").stop(true).hide();
    $("#diagram [id|=dlx], #diagram-links, #diagram-call").not("#diagram-close").hide();
    $("#dlx-start, #dlx-as1, #dlx-as2, #dlx-1, #dlx-2, #dlx-3, #dlx-4, #dlx-5, #dlx-a, #dlx-b, #dlx-c, #dlx-pot, #dlx-pos, #dlx-ap, #dlx-a1, #dlx-a2, #dlx-a3, #dlx-aa, #dlx-ab, #dlx-ac, #dlx-a5").unbind("hover");
    $("#diagram").find(".arrow").css({opacity: 1});
  });
}

$(function(){
  initializeSliderTop();
  initializeSliderBottom();
  initSubmenu();

  $("a.blank").attr("target", "_blank");

  $("#mainMenu li:eq(2) a").click(function(){
    showDiagram();
  });
  $("#diagram-close, a.local, area.local").not($("#mainMenu li:eq(2) a")).click(function(){
    hideDiagram();
  });

  $("#submenu ul li:has(ul)").live("mouseenter", function(){
    $("#submenu ul li div").stop();
    $div = $(this).find("div");
    $div.animate({
      height: $div.find("ul").height()
    });
    $("#submenu ul li:not(.active) div").not($div)
    .animate({
      height: 0
    });
  });

  $("#client .presentation a").live("click", function(){
    var $this = $(this);
    if($this.parent().hasClass("active")){
      return false;
    }
    var url = this.href+"/ajx";

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

  $("#sliderBottom.client .image a").live("click", function(){
    if(clientLock){
      return false;
    }

    var url = this.href+"/ajx";

    if(cachedClient = cache.client.get(url)){
      loadClient(cachedClient.value);
    }
    else {
      $.ajax({
        type: "post",
        dataType: "json",
        url: url,
        success: function(data){
          cache.client.add(url, data);
          loadClient(data);
        },
        beforeSend: function(){
          loader.show();
        },
        complete: function(){
          loader.hide();
        }
      });
    }
    return false;
  });
});

var clientLock = false;
var clientTitle;

function loadClient(data){
  clientLock = true;

  $("#client.ajx").hide("slide", {
    direction: "up"
  }, "normal", function(){
    $(this).remove();
  });

  if(!clientTitle){
    clientTitle = document.title;
  }

  var $client = $(data.content);

  $client.hide().appendTo("#text");

  var clientHeight = $client.outerHeight(true);
  var contentHeight = $("#text").height();

  var $heightFix = $("#heightFix");
  if(!$heightFix.length){
    $heightFix = $("<div id=\"heightFix\"/>").css({
      position: "relative",
      "float": "left"
    }).appendTo("#content");
  }


  $('html,body').animate({
    scrollTop: $("#content").offset().top - 30
  }, "normal");

  if(clientHeight < contentHeight){
    $client.height(contentHeight).show("slide", {
      direction: "down"
    }, "normal", function(){
      clientLock = false;
    });
  } else {
    $heightFix.animate({
      height: clientHeight
    }, "normal", function(){
      $client.show("slide", {
        direction: "down"
      }, "normal", function(){
        clientLock = false;
      });
    });
  }

  $client.find("a.ajx").click(function(){
    $client.hide("slide", {
      direction: "down"
    }, "normal", function(){
      $(this).remove();
      if(clientHeight > contentHeight){
        $heightFix.animate({
          height: 0
        }, "normal");
      }
    });

    $('html,body').animate({
      scrollTop: $("#sliderBottom").offset().top
    }, "normal");

    document.title = clientTitle;
    return false;
  });

  document.title = data.title;
}
$("#valuation").live("click", function(){
  $.fancybox({
    "href": valuationUrl,
    overlayColor: "#000",
    padding: 0
  });
});
$("#valuation-form").live("submit", function(event){
  event.preventDefault();
  var $form = $(this);
  $.ajax({
    type: "post",
    dataType: "html",
    url: $form.attr("action"),
    data: $form.serialize(),
    success: function(data, textStatus, XMLHttpRequest){
      if(data == "success"){
        alert("Zapytanie zostało wysłane!");
        $("#fancybox-close").click();
      } else {
        $("#fancybox-content > div").html(data);
      }
    },
    error: function(XMLHttpRequest, textStatus, errorThrown){
      alert("Wystąpił nieoczekiwany błąd! Jeśli będzie się on powtarzał, skontaktuj się proszę z nami ze strony kontakt.");
    },
    beforeSend: function(XMLHttpRequest){
      loader.show();
    },
    complete: function(XMLHttpRequest, textStatus){
      loader.hide();
    }
  });
});

$("#diagram-form").live("submit", function(event){
  event.preventDefault();
  var $form = $(this);
  $.ajax({
    type: "post",
    dataType: "html",
    url: $form.attr("action"),
    data: $form.serialize(),
    success: function(data, textStatus, XMLHttpRequest){
      if(data == "success"){
        alert("Rozmowa została zamówiona!");
        $form.find("input[type=text]").val("");
      } else {
        $("#diagram-call").html(data);
      }
    },
    error: function(XMLHttpRequest, textStatus, errorThrown){
      alert("Wystąpił nieoczekiwany błąd! Jeśli będzie się on powtarzał, skontaktuj się proszę z nami ze strony kontakt.");
    },
    beforeSend: function(XMLHttpRequest){
      loader.show();
    },
    complete: function(XMLHttpRequest, textStatus){
      loader.hide();
    }
  });
});


$("#contact form").live("submit", function(){
  $.ajax({
    type: "post",
    dataType: "json",
    url: this.action,
    data: $(this).serialize(),
    success: function(data){
      updatePage(data);
    },
    beforeSend: function(){
      loader.show();
    },
    complete: function(){
      loader.hide();
    }
  });

  return false;
});

