//============================================================
//
//
//
//============================================================


//
//============================================================
function init_icons() {
  jQuery.get('/architecture/iconostasis/icons.xml', {}, icons_parser, 'xml');
}

//
//============================================================
function init_icons_en() {
  jQuery.get('/architecture/en/iconostasis/icons.xml', {}, icons_parser, 'xml');
}

//
//============================================================
function icons_parser(xdoc){

  //
  var xw = xdoc.getElementsByTagName("icons");
  var axw;

  for (var i=0; i<xw[0].childNodes.length; i++){
    if (xw[0].childNodes[i].nodeName == 'icon'){

      axw = xw[0].childNodes[i].attributes;

      // icons[i] = [ id, title, x, y, w, h, icon, iconw, iconh, url ]
      icons.push(
          new Array(
            Number(axw.getNamedItem("id").nodeValue),
            String(xw[0].childNodes[i].childNodes[0].nodeValue),
            Number(axw.getNamedItem("x").nodeValue), Number(axw.getNamedItem("y").nodeValue),
            Number(axw.getNamedItem("w").nodeValue),Number(axw.getNamedItem("h").nodeValue),
            "/architecture/" + axw.getNamedItem("icon").nodeValue, axw.getNamedItem("iconw").nodeValue, axw.getNamedItem("iconh").nodeValue,
            axw.getNamedItem("url").nodeValue,
            null
            )
          );
    }
  }

  //
  put_icons_on_scheme();

}

//
//============================================================
function put_icons_on_scheme() {

  var imap = jQuery("#iconomap");

  for (var i=0; i<icons.length; i++){

    var bb = jQuery('<a class="iconox" href="'+ icons[i][9] + '" title="'+ i + ' ' + icons[i][1] + '"></a>', imap);

    imap.append(bb);
    bb.css("position", "absolute").
      css("z-index", (10 + i)).
      css("display", "block").
      css("overflow", "hidden").
      css("border", "0px solid #888").
      css("font-size", "66%").
      css("background", "#000000").
      css("opacity", "0").
      css("color", "#000000").
      css("left", icons[i][2] + "px").
      css("top", icons[i][3] + "px").
      css("width", icons[i][4] + "px").
      css("height", icons[i][5] + "px");

    bb.mouseover(show_baloon_icon);
    bb.mouseout(hide_baloon);

  }

}


// watch the mouse
//============================================================
var px, py;
document.onmousemove = get_mouse_xy;

//
function get_mouse_xy(e) {

  if (! document.all){
    px = e.pageX;
    py = e.pageY;
  }else{
    px = event.clientX;
    py = event.clientY;
  }

}

//
//============================================================
function show_baloon_icon(e){

  var i = parseInt(e.target.title);
  var html = '<img width="'+icons[i][7]/1.5+'" height="'+icons[i][8]/1.5+'" src="'+ icons[i][6] +'"></img><b>' + icons[i][1] + '</b>';
  show_baloon(html);

}

//
//============================================================
function show_baloon(data, boxcls){

  // do not show emty results
  if (data.length<2) return;

  if (!boxcls) boxcls = '';
  else boxcls = " " + boxcls;

  // add baloon element
  hide_baloon();
  jQuery('body').append("<div id='baloon' class='baloon" + boxcls + "'></div>");

  // set text and position
  var bl = jQuery('#baloon');

  bl.html(data).hide().css('position', 'absolute');

  baloon_location(bl);

  bl.fadeIn("fast");

}

//
//============================================================
function baloon_location(bl){

  var offy,ppy;
  if ((document.all?true:false) && !window.opera) {
    offy = document.documentElement.scrollTop;
    ppy = py;
  }else{
    offy = window.pageYOffset;
    ppy = py-offy;
  }
  if (px>(2*jQuery(window).width()/3)) bl.css('left', (px-bl.width()-30));
  else bl.css('left', (px+30));

  if (ppy>(bl.height()+25)) bl.css('top', ppy-bl.height()-25 + offy + "px");
  else bl.css('top', -5 + ppy + offy + "px");

}

// remove baloon
function hide_baloon(ev){
  jQuery('#baloon').remove();
}

//
function close_pixa() {
  try { jQuery('#pixapop').remove();  }
  catch(e) {}
}

//
function show_pixa(url, w, h, label){

  //
  var ww = w;
  var hh = h;
  var winW = jQuery(window).width();
  var winH = jQuery(window).height();

  if ((w/1.5+40)>winW || (h/1.5+40)>winH) { ww=w/2; hh=h/2;}
  else if (w>winW-40 || h>winH-40) { ww=w/1.5; hh=h/1.5;} 

  close_pixa();

  jQuery('body').append("<div id='pixapop'><a href='javascript:close_pixa();'>закрыть [x]</a><img src=\'" + url + "\' width='" + ww + "' height='" + hh +"'/><span>" + label +"</span></div>");

  var offy;
  var IE = document.all?true:false;
  if (IE && !window.opera) {
    offy = document.documentElement.scrollTop;
  }else{
    offy = window.pageYOffset;
  }

  //
  jQuery('#pixapop')
    .css('top', (offy + (winH - hh - 50)/2) + 'px')
    .css('right', ((winW - ww)/2) + 'px')
    .css('width', ww + 'px')
    .click(close_pixa)
    .fadeIn("slow");

}


//
//============================================================
function init_school() {
  jQuery('a.schtool').mouseover(school_tool_baloon).mouseout(hide_baloon);

  init_comments_form("/architecture/comments/post/");
  jQuery('div#comments_form').hide();
  jQuery('#comments_form_button').click(function(e){jQuery('div#comments_form').toggle('fast'); return false;});

}

//
//============================================================
function init_comments_form(url) {

  jQuery('div#comments_form form input.submit-preview').remove();

  jQuery('div#comments_form form').submit( function(e){

      jQuery.ajax({ type: "POST",
        data: jQuery('div#comments_form form').serialize(),
        url: url,
        cache: false,
        dataType: "html",
        success: function(html, textStatus) { jQuery('div#comments_form form').replaceWith(html); init_comments_form(url);},
        error: function (XMLHttpRequest, textStatus, errorThrown) {  jQuery('div#comments_form form').replaceWith('<b>ошибка при отправке комментария</b>');}
        });

      return false;
      }
      );

}

//
//============================================================
function school_tool_baloon(e) {
  var t = this.innerHTML;
  var i = e.target.href.replace(/[^1234567890]/g, '');
  var html = '<div class="indicateurbox"><b>определитель музейных предметов</b><i>загружается '+ t + ' ...</i></div>';
  show_baloon(html, 'oprbaloon');
  jQuery.get('/collection/opr/smallcard/' + i, {}, school_tool_parser);
}

//
//============================================================
function school_tool_parser(xdoc) {

  var box = jQuery('#baloon');
  var html = '<div class="indicateurbox"><b>определитель музейных предметов</b><p>' + xdoc + '</p></div>';
  box.html(html);
  baloon_location(box);

}


//
//============================================================
function init_catalog_map() {
  googlemap_init();
  exposector_id = -1;
  jQuery.get('/architecture/catalog/woods.xml', {}, woods_parser, 'xml');
}


//
//============================================================
function init_sector_map() {
  googlemap_init();
  jQuery.get('/architecture/catalog/woods.xml', {}, woods_parser, 'xml');
}

//
//============================================================
function init_catalog_map_en() {
  googlemap_init();
  exposector_id = -1;
  jQuery.get('/architecture/en/catalog/woods.xml', {}, woods_parser, 'xml');
}


//
//============================================================
function init_sector_map_en() {
  googlemap_init();
  jQuery.get('/architecture/en/catalog/woods.xml', {}, woods_parser, 'xml');
}

var woods = new Array();

//
//============================================================
function woods_parser(xdoc){

  //
  var xw = xdoc.getElementsByTagName("woods");
  var axw;

  for (var i=0; i<xw[0].childNodes.length; i++){
    if (xw[0].childNodes[i].nodeName == 'wood'){

      axw = xw[0].childNodes[i].attributes;

      //if (secid == exposector_id)
      // woods[i] = [0-lat, 1-lng, 2-type, 3-title, 4-url, 5-icon, 6-iconw, 7-iconh, 8-sector, 9-marker]
      woods.push(
          new Array(
            Number(axw.getNamedItem("lat").nodeValue), Number(axw.getNamedItem("lng").nodeValue),
            String(axw.getNamedItem("type").nodeValue),
            xw[0].childNodes[i].childNodes[0].nodeValue,
            axw.getNamedItem("url").nodeValue,
            axw.getNamedItem("icon").nodeValue, axw.getNamedItem("iconw").nodeValue, axw.getNamedItem("iconh").nodeValue,
            Number(axw.getNamedItem("sector").nodeValue),
            null
            )
          );
    }
  }

  //
  put_woods_on_map();

}


//
//============================================================
function put_woods_on_map (scale) {

  //62.066854716186704, 35.22358417510986
  var alat=-0.0025, alng=-0.0025;
  var xo=1e9, yo=1e9, xn=0, yn=0;
  var cnt = 0;

  var gpoint, marker;

  if (!scale){ scale = 0; }

  // remove old markers from map
  for(var i=0; i<woods.length; i++){
    if (woods[i][9]){
      try {map.removeOverlay(woods[i][9]);} catch(e){}
      woods[i][9] = null;
    }
  }

  // put markers for the woods of the current sector
  // woods[i] = [0-lat, 1-lng, 2-type, 3-title, 4-url, 5-icon, 6-iconw, 7-iconh, 8-sector, 9-marker]
  for(i=0; i<woods.length; i++){

    //
    if (woods[i][8] == exposector_id || exposector_id<0){

      gpoint = new GLatLng(woods[i][0],woods[i][1]);

      xo = Math.min(woods[i][0],xo);
      yo = Math.min(woods[i][1],yo);
      xn = Math.max(woods[i][0],xn);
      yn = Math.max(woods[i][1],yn);

      alat += woods[i][0];
      alng += woods[i][1];

      cnt++;

      // create and save marker
      if (scale==0 || scale>12){
        woods[i][9] = createMarker(gpoint, i, woods[i][2], 16);
      }else{
        woods[i][9] = createMarker(gpoint, i, 'dot', 5);
      }

      map.addOverlay(woods[i][9]);

    }

  }

  // autocenter
  if (exposector_id<0 && !scale){

    map.setCenter(new GLatLng(62.066854716186704, 35.22358417510986), 16);

  }else if (!scale){

    scale = 10;
    alat /= cnt;
    alng /= cnt;

    if (Math.abs(xo-xn)>0.06 || Math.abs(yo-yn)>0.06) scale = 12;
    else if (Math.abs(xo-xn)>0.04 || Math.abs(yo-yn)>0.04) scale = 14;
    else if (Math.abs(xo-xn)>0.012 || Math.abs(yo-yn)>0.012) scale = 15;
    else scale = 16;

    map.setCenter(new GLatLng(alat, alng), scale);

  }

  // add markers for the woods from other sectors
  if (exposector_id>=0){
    for(var i=0; i<woods.length; i++){

      // 'tserkov' magic next line
      if (woods[i][8] != exposector_id && (scale>12 || woods[i][2] == 'tserkov')){

        gpoint = new GLatLng(woods[i][0],woods[i][1]);

        if (scale>14) woods[i][9] = createMarker(gpoint, i, 'in-' + woods[i][2], 16);
        else woods[i][9] = createMarker(gpoint, i, 'dot', 3);

        map.addOverlay(woods[i][9]);

      }
    }

  }

}


//
//============================================================
function createMarker(point, idx, iconfile, iconsize){

  if (!iconsize) iconsize=16;

  var BlueiconAnchor = new GPoint(iconsize/2, iconsize/2);
  var BlueIconSize = new GSize(iconsize, iconsize);
  var blueIcon = new GIcon(G_DEFAULT_ICON);
  blueIcon.image = "/architecture/include/markers/" + iconfile + '.png';
  blueIcon.shadow=null;
  blueIcon.iconSize = BlueIconSize;
  blueIcon.iconAnchor = BlueiconAnchor;

  //
  markerOptions = { icon:blueIcon, title:idx };

  //
  var marker = new GMarker(point, markerOptions);

  //
  GEvent.addListener(marker, "click", wood_marker_handler);
  GEvent.addListener(marker, "mouseover", wood_marker_handler_hover);
  GEvent.addListener(marker, "mouseout", wood_marker_handler_hout);

  return marker;

}

//
function wood_marker_handler(e){
  var i = parseInt(this.getTitle());
  window.location = woods[i][4];
}

//
function wood_marker_handler_hover(e){
  var i = parseInt(this.getTitle());
  var html = '<img src="/architecture/'+ woods[i][5] +'" width="'+woods[i][6]/1.5+'" height="'+woods[i][7]/1.5+'"></img><b>' + woods[i][3] + '</b>';
  show_baloon(html);
}

//
function wood_marker_handler_hout(){
  hide_baloon();
}


//
var map;
var mapObjects = new Array();

//
//============================================================
function googlemap_init() {

  /*@cc_on
   @if (@_jscript_version <= 5.6)
   alert('Не рекомендуется использовать устаревший браузер\nMS Internet Explorer 6\nдля просмотра страниц с картами Google.\n\nЧасть информации может отображаться некорректно.\n');
  /*@end @*/ 

  if (GBrowserIsCompatible()) {

    var mapcan = document.getElementById("google_map");
    //if (!mapcan) alert('map not found');
    map = new GMap2(mapcan);

    // custom map
    var copyright = new GCopyright(1, new GLatLngBounds(new GLatLng(62.11, 35.17), new GLatLng(62.05, 35.24)),9, "Кижи");
    var copyrightCollection = new GCopyrightCollection("kizhi.karelia.ru");

    copyrightCollection.addCopyright(copyright);

    // *
    var tilelayers = [new GTileLayer(copyrightCollection, 9, 16)];
    tilelayers[0].getTileUrl = customGetTileUrl;
    var custommap = new GMapType(tilelayers, new GMercatorProjection(18), "Кижи", {shortName:"Кижи"});
    map.addMapType(custommap);

    //
    //map.setCenter(new GLatLng(62.066854716186704, 35.22358417510986), 15);
    map.addControl(new GLargeMapControl());
    //map.addControl(new GMapTypeControl());
    //map.addControl(new GScaleControl());
    //map.removeMapType(G_NORMAL_MAP);
    //map.removeMapType(G_SATELLITE_MAP);
    //map.removeMapType(G_HYBRID_MAP);
    map.setMapType(custommap);

    // debug
    //GEvent.addListener(map, "click", function(overlay, point) { if(point != null){alert(point.toString())};});

    GEvent.addListener(map, "zoomend", map_zoom_handler);

  }else{

    alert('sorry, map is not available.');

  }

}


// a -- old level, b -- new level value
////////////////////////////////////////////////////////////////////////
function map_zoom_handler(a,b) {

  //
  if (a && b && a>=15 && b<=14){ put_woods_on_map (b); }
  if (a && b && a<=14 && b>=15){ put_woods_on_map (b); }

  //
  if (a && b && a<=12 && b>=13){ put_woods_on_map (b); }
  if (a && b && a>=13 && b<=12){ put_woods_on_map (b); }

}


//
////////////////////////////////////////////////////////////////////////
function customGetTileUrl(a,b){

  // magic numbers of the map
  if ((b==9 && a.x > 304 && a.x < 307 && a.y > 141 && a.y < 144) ||
      (b==10 && a.x > 610 && a.x < 613 && a.y > 283 && a.y < 287) ||
      (b==11 && a.x > 1221 && a.x < 1226 && a.y >568  &&  a.y <574) ||
      (b==12 && a.x > 2443 && a.x < 2451 && a.y >1137 && a.y < 1148) ||
      (b==13 && a.x > 4888 && a.x < 4901 && a.y > 2275 && a.y < 2295) ||
      (b==14 && (a.x > 9778 && a.x < 9803) && (a.y > 4551 && a.y < 4590)) ||
      (b==15 && (a.x > 19586 && a.x < 19592) && (a.y > 9118 && a.y < 9129)) ||
      (b==15 && (a.x > 19510 && a.x < 19514) && (a.y > 9177 && a.y < 9182)) ||
      (b==16 && (a.x > 39173 && a.x < 39183) && (a.y > 18237 && a.y < 18257)) ||
      (b==16 && (a.x > 39023 && a.x < 39029) && (a.y > 18357 && a.y < 18364)) ||
      (b==17 && (a.x > 78047 && a.x < 78058) && (a.y > 36716 && a.y < 36727)))
  {
    return "http://kizhi.karelia.ru/include/googlemaps/img/tile_x_"+a.x+"_y_"+a.y+"_z_"+b+"_done.png";

  } else {
    return G_NORMAL_MAP.getTileLayers()[0].getTileUrl(a,b);
  }

}


