var objectEditor;
var cragID;
var peakID;
var routeOrder;
var commentObject = 'C';

function setupCrag() {
  var html = $("html");
  objectEditor = html.attr("xp:editor");
  cragID       = html.attr("xp:id");
  peakID       = html.attr("xp:peak");

  createDropdownMenu({
    id:     "addMenu",
    title:  "Dodaj ...",
    actions:
      [
       {text:"Opiši razmere",  key:"R", action: function() { $("#actState").click(); } },
       {text:"Dodaj komentar", key:"K", action: function() { $("#actComment").click(); } },
       {line: true},
       {text:$("#actPhoto").html(),key:"P", action: function() { $("#actPhoto").click(); }, ctrl:"D" },
       {text:$("#actRoute").html(),key:"S", action: function() { $("#actRoute").click(); }, ctrl:"N" },
       {line: true},
       {text:"Dodaj opozorilo",key:"O", action: function() { $("#actWarning").click(); } }
      ]
    });
    
  var editActions = new Array();
  
  if (userid == objectEditor || userHasRights(['CragEditor','CragManager'])) {
    editActions.push({text: "Podatke o "+ (peakID ? "steni":"plezališču"), key:"P", action:openCrag });
  }
  
  if (userid == objectEditor || userHasRights(['CragManager'])) {
    try { EWM.registerCtrlKey("U",editCrag); } catch(e) {};
    editActions.push({text:"Sektorje",  key:"S", action:editSectors }) ;
    editActions.push({text:"Smeri", action:editRoutes }) ;      
  }
  
  if (userHasRights(['CragManager'])) {
    editActions.push({text:"Opozorila",  key:"O", action:addAdminComments }) ;
  }

  var imgCount = 0;
  $("img").each(function() {
    var iuid = this.getAttribute("xp:uid");
    if (iuid == userid) imgCount ++;
  });
  
  if (imgCount) { 
    editActions.push({text: "Priloge", action: function() { $("#actPhoto").click(); } }); 
  }

  if (editActions.length) {
    createDropdownMenu({
      id:     "adminMenu",
      title:  "Popravi ...",
      actions: editActions});
    $("#adminMenu").show();
  } else {
    $("#adminMenu").hide();
  }
}

function setupRoutesMenu(ro) {  
//  alert("route order:" +ro);
  routeOrder = ro;
  var showMenu = {
    id:     "showMenu",
    title:  "Prikaži ...",
    actions:
      [
       {text:"Smeri od leve proti desni",  key:"L", action: function() { showRoutes(''); } },
       {text:"Smeri urejene po imenu",     key:"I", action: function() { showRoutes('n'); } },
       {text:"Smeri po težavnosti",        key:"T", action: function() { showRoutes('d'); } },
       {text:"Smeri po dolžini",           key:"D", action: function() { showRoutes('l'); } },
       {line:true},
       {text:"Moje vzpone",                action: function(){ $.login.executeAfterLogin(showClimbs);} },
       {line:true},
       {text:"Podrobne ocene",             action: function(){ showDetailedGrades()} },
       {text:"Največkrat preplezane smeri",action: function(){ location = "../public/showMostClimbed.asp?crag="+cragID; } },
       {line:true},
       {text:"Spisek smeri za prenos v Excel", action: function() { location = "../common/xml_Routes.asp?crag="+cragID+"&fmt=A&sc=yes"; } }
      ]
    };
      
/*  if (userid) { delete showMenu.actions[4]; } */
  createDropdownMenu(showMenu);
}

function openCrag()   { $.login.executeAfterLogin(function() { wo('/climbing/adm/crags/editCrag.asp?a=show&crag='+cragID,900,700) })}
function editCrag()   { $.login.executeAfterLogin(function() { wo('/climbing/adm/crags/editCrag.asp?a=edit&crag='+cragID,900,700) })}

function addRoute()   { $.login.executeAfterLogin(function() { wo('../adm/routes/editRoute.asp?a=add&crag='+cragID+(peakID ? "":"&f=short"),peakID ? 900 : 750,peakID ? 700 : 500); })}
function addAdminComments() { location = '../adm/crags/index.asp?file=editAdminComments.xml&p_id='+cragID; }

function editSectors() { wo('../adm/crags/editSectors.asp?a=show&crag='+cragID,800,700); }
function editRoutes()  { location = "../adm/routes/listRoutes.asp?crag="+cragID; }
function showRoutes(p) { location = "showCrag.asp?crag="+cragID+(p ? "&p_ord="+p : "") }

var ascentLookup;

function showClimbsFailed() {
  alert("Ne morem prikazati vzponov");
  $("#loadWait").hide();
}

function showDetailedGrades() {

  function showDetailedFailed() {
    alert("Ne morem prikazati ocen"); $("#loadWait").hide();
  }

  function showMyGrades() { showGrades($(this).attr("rid")) }
  
  function loadDetailedGrades(data) {
    var th = $("#routeTable th:nth(1)");
    if (!th.attr("ext")) th.attr("ext","true").html("Izračunana ocena<br />(Bazna ocena, razpon, število)");
    $("line",data).each(function() {
      var line = $(this);
      var rid  = line.attr("RouteID");
      var a = $("<a href='#'>"+line.attr("RouteDiff")+"</a>").click(showMyGrades).attr("rid",rid).hover(showRouteGradesTrigger,hideRouteGrades).css("cursor","pointer");
      $("#g_"+rid).empty().append(a).append(
        " ("+line.attr("BaseGrade")+", "+line.attr("MinGrade")+" &hellip; "+line.attr("MaxGrade")+", "+line.attr("CountGrade")+")");
    });
  }

  $.ajax({
    url: "../common/xml_Stub.asp?rq=rgs&crag="+cragID,
    dataType: "xml",
    timeout: 2000,
    error: showDetailedFailed,
    success: function(data) { loadDetailedGrades(data); $("#loadWait").hide(); }});
}

function loadAscentTable() {

  function createAscentTable(data) {
    ascentLookup = new Object;
    $.each(data.documentElement.getElementsByTagName("climbType"),
      function(key,ct) { ascentLookup[ct.getAttribute("id")] = ct.getAttribute("text"); }
    );
  }
  
  $.ajax({
    url: "../myClimbs/xsl/climbTypeLookup.xml",
    dataType: "xml",
    timeout: 1000,
    error: showClimbsFailed,
    success: function(data) { createAscentTable(data); loadClimbsTable(); }});
  return;
}

function showClimbs()  { 
  if(! $.cookies.get('uid')) { location = "showCrag.asp?crag="+cragID+"&my=yes"; return; }
  $("#loadWait").show();
  if (!ascentLookup) { loadAscentTable(); } else { loadClimbsTable(); }
}

function loadClimbsTable() {

  function loadClimbsData(data) {
    $("#climbTableHeader").html("Tvoj vzpon");
    $.each(data.documentElement.getElementsByTagName("climb"),
      function(key,climb) {
        $("#r_"+climb.getAttribute("routeID")+" .showClimbs")
          .html("<a href='../myClimbs/myClimbs_ListRouteClimbs.asp?routeID="+climb.getAttribute("routeID")+"'>" +
                ascentLookup[climb.getAttribute("ascent")]+"</a> "+
                "(<a href='../myClimbs/myClimbs_show.asp?back=yes&id="+climb.getAttribute("id")+"'>"+
                climb.getAttribute("date")+"</a>)");
      });
  }

  $.ajax({
    url: "../myClimbs/myClimbs_ListClimbs.asp?cragID="+cragID+"&show=routes&doXML=yes",
    dataType: "xml",
    timeout: 2000,
    error: showClimbsFailed,
    success: function(data) { loadClimbsData(data); $("#loadWait").hide(); }});
}

function showGrades(r) { wo('../common/xml_RouteGrades.asp?route='+r+'&xsl=../db/showGrades_101.xsl',100,100); }

function showRouteGradesTrigger() {
  var that = this;
  $(this).addClass("hover");
  this.triggerHandle = setTimeout(function() { showRouteGrades.apply(that); },200);
}

function showRouteGrades() {
  var showGrade = $(".showGrade",this);
  if (showGrade.length) {
    if ($("div",showGrade).length) { showGrade.fadeIn(); return; }
  } else {
    showGrade = $("<div class='dg'><div class='showGrade'></div></div>").appendTo($(this));
    showGrade = $(".showGrade",showGrade).hide();
  }
  showGrade.load("../common/xml_RouteGrades.asp?route="+this.id.replace(/g_/,"")+"&xsl=../db/showGrades_101.xsl&doXML=no .data",function() { 
      var doch = $('#body').height();
      if ($(this).parents(".hover").length) { $(this).fadeIn(); }
      var sgh = showGrade.height();
      var sgt = showGrade.offset().top;
//      alert("doch="+doch+" sgh="+sgh+" sgt="+sgt);
      if ((sgt + sgh > doch - 20) && (sgt > sgh + 20)) {
        showGrade.css({ top:"auto",bottom:"1.2em"});
      }
    });
}

function hideRouteGrades() {
  $(this).removeClass("hover");
  $(".showGrade",this).fadeOut(100);
  if (this.triggerHandle) { clearTimeout(this.triggerHandle); }
}

function showRouteCommentsTrigger() {
  var that = this;
  $(this).addClass("hover");
  this.triggerHandle = setTimeout(function() { showRouteComments.apply(that); },200);
}

function showRouteComments() {
  var cell = $(this).parents("td:first");
  var showComment = cell.find(".dg");
  if (showComment.length) {
    if (showComment.children("div").length) { showComment.children(".showGrade").fadeIn(); return; }
  } else {
    showComment = $("<div class='dg'><div class='showGrade'></div></div>").appendTo(cell).children(".showGrade");
    showComment.css({ right: "1em", width: "40em", left: "auto"}); 
    if (showComment.offset().left < 5) { showComment.css({ left: "-15em", right: "auto"}); }
    showComment.hide();
  }
  showComment.load("../common/xml_showComments.asp?inc=CS&ot=R&xsl=C&doXML=no&oid="+cell.parents("tr:first").attr("id").replace(/r_/,"")+" #main",function() { 
      var sc = $(this);
      if (sc.parents("td[.hover]").length) { 
        sc.fadeIn();
        var doch = $(document).height();
        var sgh = sc.height();
        var sgt = sc.offset().top;
        if ((sgt + sgh > doch - 20) && (sgt > sgh + 20)) {
          sc.css({ top:"auto",bottom:"1.2em"});
        }
      }
    });
}

function hideRouteComments() {
  $(this).removeClass("hover");
  $(this).parents("td:first").find(".showGrade").fadeOut(100);
  if (this.triggerHandle) { clearTimeout(this.triggerHandle); }
}

$(function(){
  $("#routeTable .grade").hover(showRouteGradesTrigger,hideRouteGrades).css("cursor","pointer");
  $("#routeTable .comment").hover(showRouteCommentsTrigger,hideRouteComments);
});