var small_h = 40;
var big_h = 116;
var v_space = 4;
var speed = 600;
var anim_started = false;

var pages = {};
var buttons = {};
var current_page_idx = "";
var p_idx = 0;
var p_contents = {};

var disable_js = false;
internal_page = false;

$(document).ready(function() {
  wrapNavigationText();

  var hash = window.location.hash.replace(/#/g, "");

  if(!internal_page) {
    getPageType(hash);
  }

  var last_button = $('#buttons .last-level .button-big:last');
  //$("#buttons").css("height", parseInt(last_button.css("top"))+last_button.height());
});

function showPages(cat, single_page) {
  var is_single = single_page || false;
  
  $(".last-level").fadeOut(speed);

  if(is_single) {
    if($("#buttons").hasClass("side")) {
      var buttons_parent = $(".last-level:visible");
      restoreButtons(buttons_parent, true);
    }

    if($("#page-text").is(":hidden")) {
      $("#page-text").show();
    }

    $('#page-text').addClass("extended").fadeIn(speed);

    $("#page-text .main-text-box.active").fadeOut(speed).removeClass("active");
  } else {
    $('#page-text').removeClass("extended");
  }

  if(pages[cat]) {//if pages are already loaded
    $('#last-level-'+cat).fadeIn(speed);

    if(is_single) {
      $("#buttons").fadeOut(speed);
      $("#single-level-"+cat).fadeIn(speed);
      page_content = pages[cat][0];
      if(page_content) {
        $(p_contents[page_content['url']]).fadeIn(speed).addClass("active");
      }
    }
  } else {
    $.ajax({
      'url' : 'visitor_content',
      'async' : false,
      'data' : {get_pages: true, cat_id: cat, last_idx: p_idx},
      'success' : function(response) {
        var data = eval('(' + response + ')');
        pages[cat] = {};
        pages[cat] = data;

        addContentPages(data, is_single);

        var level = is_single ? "single-level" : "last-level";
        var new_buttons = "<div class=\""+level+" {'cat_id':'"+cat+"'}\" id='"+level+"-"+cat+"'>";
        $.each(data, function(i, v) {
          new_buttons += '<div onclick="return lastLevelClick(this, \''+v['url']+'\');" class="button-big but'+(i*1+1)+'">\n\
                            <table class="big"><tr><td>'+v['button_big']+'</td></tr></table>\n\
                            <table class="small"><tr><td>'+v['button_small']+'<input type="hidden" id="page_id_'+v['id']+'" class="input_page_id" value="'+v['id']+'" /></td></tr></table>\n\
                          </div>';
        });

        new_buttons += "</div>";

        html_buttons = $(new_buttons).hide();

        $("#buttons").append(html_buttons);

        if(is_single) {
          $("#buttons").fadeOut(200);
        } else {
          if($("#buttons").is(":hidden")) {
            $("#buttons").fadeIn(speed);
          }
          html_buttons.fadeIn(speed);
        }

        buttons[cat] = new_buttons;
      }
    });
  }
}

function showSinglePage(cat) {
  $("#buttons").fadeOut(200);
  $("#page-text .main-text-box.active, #page-text").hide();
  
  if(!pages[current_page_idx][0]) {//if there is no page for this category
    return false;
  }
  
  var page_content = pages[current_page_idx][0];
  
  $(p_contents[page_content['url']]).fadeIn(speed, function() {$(this).addClass('active')});
  $("#page-text").addClass('extended').show();
}

function clearInput(v, i) {
  if(i.value==v) {
    i.value="";
  }
}

function restoreInput(v, i) {
  if(i.value=="") {
    i.value=v;
  }
}

function onlyDigits(e) {
  var characterCode; // literal character code will be stored in this variable

  if (e && e.which) { //if which property of event object is supported (NN4)
    e = e;
    characterCode = e.which; //character code is contained in NN4's which property
  } else {
    e = event;
    characterCode = e.keyCode; //character code is contained in IE's keyCode property
  }

  if ((characterCode != 8) &&
    (characterCode < 46 || characterCode > 57)) {
    return false;
  }
  return true;
}

function addContentPages(page, single_page) {
  if(single_page) {
    $("#page-text").show();
  }

  $.each(page, function(i, v) {//fill the content for the homepage
    var id = (++p_idx);

    var p_text = $("<div />").addClass("main-text-box").attr("id", "main-text-box-"+id).append(v.content).hide();
    p_text.appendTo($("#page-text"));
    p_text.data("page_idx", i);

    if(single_page) {
      p_text.fadeIn(speed).addClass("active");
    }
    
    p_contents[v.url] = p_text;

    if($("#main-text-box-"+id+" .text-slideshow").find("li").size() > 1) {
      $("#main-text-box-"+id+" .text-slideshow").cycle({
        "fx": "scrollHorz",
        "timeout": 0,
        "prev": "#main-text-box-"+id+" .pagination .left",
        "next": "#main-text-box-"+id+" .pagination .right",
        "nowrap": true,
        "after": afterSlideshow
      });
    }
  });
}

function afterSlideshow(curr,next,opts, flag) {
  var page_idx = $(opts['$cont']).closest('.main-text-box').data('page_idx');
  var pagination = $(opts.next).closest('.pagination');
  pagination.show();
  
  if(opts.nextSlide < opts.currSlide) {//hide next button
    $(opts.next).hide();
  } else {
    $(opts.next).show();
//    if(pages[current_page_idx][page_idx]['descendants']) {
//      pagination.find('.right').closest("a").attr("href", pages[current_page_idx][page_idx]['descendants'][opts.currSlide]['url']);
//    }
  }

  if(opts.currSlide > 0) {//hide prev button
    $(opts.prev).show();
//    var left_url = "";
//    if(opts.currSlide > 1) {
//      if(pages[current_page_idx][page_idx]['descendants']) {
//        left_url = pages[current_page_idx][page_idx]['descendants'][opts.currSlide-2]['url'];
//      }
//    } else {
//      left_url = pages[current_page_idx][page_idx]['url'];
//    }
//    pagination.find('.left').closest("a").attr("href", left_url);
  } else {
    $(opts.prev).hide();
  }
}

function animationsEnd() {
  var last_button = $('#buttons .button-big:last');
  //$("#buttons").css("height", parseInt(last_button.css("top"))+last_button.height());
}

function wrapNavigationText() {
  $('.navigation li a').each(function() {
    var span = $(this).find("span");
    if(parseInt(span.css("line-height")) < span.height()) {
      span.css("line-height", "14px");
    }
  });

  $(".side-nav").addClass("hide");
  $("#left-column").css("visibility", "visible").hide();
}

function showButtons(cat_id, elm, url) {
//  if($(elm).hasClass("active")) {
//    return false;
//  }

  window.location = $(elm).attr("href");

  return false;

  hideSideMenu(); //hide the side navigation (if it's visible)
  hideContentBox();

  $("#top-navigation a.active").removeClass("active");
  $(elm).addClass("active");

  if($("#buttons").is(":hidden")) {//if the button is clicked from internal page hide the internal page content
    $("#buttons").show();
    $("#internal-page-text").fadeOut(speed);
    //$("#buttons").fadeIn(speed);
  }

  $('#buttons > div:visible').fadeOut(200);
  $('#buttons-box-'+cat_id).fadeIn(speed);
  
  return false;
}

function hideContentBox() {
  $("#page-text").fadeOut(speed);
}

function loadPageContent(opts) {
  if(opts.evt) {
    if(opts.evt.preventDefault) {
      opts.evt.preventDefault();
    } else {
      opts.evt.returnValue = false;
    }
  }

  window.location.hash = opts.url;

  showSideMenu(opts.main_cat, opts.item_id);

  showPages(opts.cat_id, true);

  return false;
}

function loadSubpages(opts) {
  current_page_idx = opts.cat_id;

  window.location.hash = opts.url;

  if(!opts.from_sidebar) {//if is clicked center big button
    showSideMenu(opts.main_cat, opts.item_id);
  } else {//a sidebar button is clicked
//    if($(opts.item).hasClass("active")) {
//      return false;
//    }

    if($("#buttons").is(":hidden")) {
      $("#buttons").fadeIn(speed);
    }

    $("#buttons .single-level:visible").fadeOut(200);
    $("#page-text").fadeOut(speed);
    $(".main-text-box:visible").fadeOut(speed).removeClass("active");

    $("#side-nav-"+opts.main_cat).find("a.active").removeClass("active");
    $(opts.item).addClass("active");

    if($("#buttons").hasClass("side")) {
      var buttons_parent = $(".last-level:visible");
      restoreButtons(buttons_parent);
    }
  }

  showPages(opts.cat_id);

  return false;
}

function showSideMenu(cat_id, item_id) {
  var nav = $("#side-nav-"+cat_id);

  if($("#left-column").is(":hidden")) {
    $("#left-column").fadeIn('fast').removeClass("hide");
  }
  
  nav.fadeIn(speed);
  nav.find("li a").removeClass("active");
  nav.find("li").eq(item_id-1).find("a").addClass("active");

  $(".buttons-box").fadeOut(200);
}

function hideSideMenu() {
  $(".side-nav:visible").fadeOut(speed);
}

function restoreButtons(p, st) {
  if(p.parent().hasClass("side")) {
    p.find(".button-big.active").removeClass("active");
    $.each(p.find(".button-big"), function(i, v) {
      $(this).animate({
        "top": $(this).data("position").top,
        "left": $(this).data("position").left,
        "height": big_h
      }, speed, function() {
        anim_started = false;
      });

      $(this).find(".big").fadeIn(speed);
      $(this).find(".small").fadeOut(speed);
    });

    if(!st) {
      $("#page-text").hide(speed, function() {
        animationsEnd();
      });
    }

    $("#buttons").removeClass("side").addClass("default");
  }
}

function showInternalPage(page, elm) {
  if(page != current_page) {
    return (true);
  }
  
  if($(elm).hasClass("active")) {
    return false;
  }

  $("#top-navigation a.active").removeClass("active");
  $(elm).addClass("active");

  $(".side-nav:visible").fadeOut(speed);
  $("#internal-page-text").fadeIn(speed);
  
  var buttons_parent = $("#buttons > div:visible");
  if(buttons_parent.length) {
    restoreButtons(buttons_parent);
    $("#buttons > div:visible").fadeOut(200);
    $("#buttons").fadeOut(200);
  }

  return false;
}

function lastLevelClick(item, url) {
  if(anim_started) return (false);

  window.location.hash = url;

  var parent = $(item).closest(".last-level");

  var idx = parent.find(".button-big").index(item);
  var active_idx = 0;
  var clicked_button = $(item);
  var page_content = pages[current_page_idx][idx];

  $("#page-text .main-text-box.active").hide().removeClass('active');
  $(p_contents[page_content['url']]).fadeIn(speed, function() {$(this).addClass('active')});

  if($("#buttons").hasClass("default")) {
    var prev_buttons = parent.find(".button-big:lt("+idx+")");
    var next_buttons = parent.find(".button-big:gt("+idx+")");

    var t = item;
    var top = 0;
    var h = 0;

    anim_started = true;

    $.each(parent.find(".button-big"), function(i, v) {
      $(this).data("position", {"top": $(this).css("top"), "left": $(this).css("left")});

      if($.inArray(this, prev_buttons) >= 0) {
        top = (small_h+v_space)*i;
        h = small_h;
      }

      if($.inArray(this, next_buttons) >= 0) {
        top = (small_h+v_space)*i + (big_h-small_h);
        h = small_h;
      }

      if(t == this) {
        $(this).addClass("active");
        top = (small_h+v_space)*idx;
        h = big_h;
      } else {
        $(this).find(".big").fadeOut(speed);
        $(this).find(".small").fadeIn(speed);
      }

      $(this).animate({
        "left": 0,
        "top": top,
        "height": h
      }, speed, function() {
        anim_started = false;
        $("#buttons").removeClass("default").addClass("side");
      });
    });

    $("#page-text").fadeIn(speed);
  }

  if($("#buttons").hasClass("side")) {
    anim_started = true;

    if($(item).hasClass("active")) {
      //go back to big buttons
      restoreButtons(parent);
    } else {
      var active_button = parent.find('.button-big.active');
      active_idx = parent.find(".button-big").index(active_button); //get intex of active button

      var min = Math.min(idx, active_idx);
      var max = Math.max(idx, active_idx);

      var interval = parent.find(".button-big:gt("+min+")").slice(0, (max - min - 1)); //get buttons within the active button and clicked button
      var interval_buttons_top = idx < active_idx ? "+="+(big_h-small_h) : "-="+(big_h-small_h); //find direction to move up or down the buttons from interval

      $.each(interval, function() { //move buttons from interval
        $(this).animate({
          "top": interval_buttons_top
        });
      });

      var active_button_top = idx < active_idx ? "+="+(big_h-small_h) : "+=0";

      //shrink the active button
      active_button.removeClass("active").animate({
        "top": active_button_top,
        "height": small_h
      }, speed);
      active_button.find(".big").fadeOut(speed);
      active_button.find(".small").fadeIn(speed);

      var clicked_button_top = idx > active_idx ? "-="+(big_h-small_h) : "+=0";

      //grow the clicked button
      clicked_button.addClass("active").animate({
        "top": clicked_button_top,
        "height": big_h
      }, speed, function() {
        anim_started = false;
        animationsEnd();
      });
      clicked_button.find(".big").fadeIn(speed);
      clicked_button.find(".small").fadeOut(speed);
    }
  }

  return false;
}

function getPageType(hash) {
  var main_cat_id = 0;
  var level2_cat_id = 0;
  var page_id = 0;
  
  for(cat in categories) {
    if(categories[cat]['url'] == hash) {
      main_cat_id = cat;
      break;
    } else {
      if(categories[cat]['subpages']) {
        for(sub in categories[cat]['subpages']) {
          if(categories[cat]['subpages'][sub]['url'] == hash) {
            level2_cat_id = sub;
            main_cat_id = cat;
            break;
          }
        }
      }
    }
  }

  if(!hash || !main_cat_id) {
    //get page with ajax
    $.ajax({
      'url' : 'visitor_content',
      'async' : false,
      'data' : {get_details: true, hash: hash},
      'success' : function(response) {
        var data = eval('(' + response + ')');
        main_cat_id = data.main_cat_id;
        level2_cat_id = data.level2_cat_id;
        page_id = data.page_id;
      }
    });

    if(!main_cat_id) {
      main_cat_id = 1;
    }
  }

  if(main_cat_id) {
//    console.log(main_cat_id);
    $("#buttons-box-"+main_cat_id).fadeIn(speed);
    $("#top-navigation a.active").removeClass("active");
    $(".menu"+main_cat_id).addClass("active");
  }

  if(level2_cat_id) {
    setTimeout(function() {
      $("#buttons-box-"+main_cat_id).find(".but"+level2_cat_id).trigger("click", page_id);

      if(page_id) {
        setTimeout(function() {
          $("#buttons .last-level:visible").find(".input_page_id").each(function() {
            if($(this).val() == page_id) {
              $(this).closest('.button-big').trigger("click");
            }
          });
        }, speed+100);
      }
    }, speed);
  }
}
