﻿/// <reference path="jquery-1.4.1-vsdoc.js" />

function init($, map, loader, form, login, albums, title)
{
  $.fn.parseTemplate = function (data)
  {
    var str = (this).html();
    var _tmplCache = {}
    var err = "";
    try
    {
      var func = _tmplCache[str];
      if (!func)
      {
        var strFunc =
            "var p=[],print=function(){p.push.apply(p,arguments);};" +
                        "with(obj){p.push('" +
            str.replace(/[\r\t\n]/g, " ")
               .replace(/'(?=[^#]*#>)/g, "\t")
               .split("'").join("\\'")
               .split("\t").join("'")
               .replace(/<#=(.+?)#>/g, "',$1,'")
               .split("<#").join("');")
               .split("#>").join("p.push('")
               + "');}return p.join('');";

        //alert(strFunc);
        func = new Function("obj", strFunc);
        _tmplCache[str] = func;
      }
      return func(data);
    } catch (e) { err = e.message; }
    return "< # ERROR: " + err.toString() + " # >";
  }

  $.fn.watermark = function (css, text)
  {
    return this.each(function ()
    {
      var i = $(this), w;
      i.focus(function ()
      {
        w && !(w = 0) && i.removeClass(css).data('w', 0).val('');
      })
      .blur(function ()
      {
        !i.val() && (w = 1) && i.addClass(css).data('w', 1).val(text);
      })
      .closest('form').submit(function ()
      {
        w && i.val('');
      });
      i.blur();
    });
  };
  $.fn.removeWatermark = function ()
  {
    return this.each(function ()
    {
      $(this).data('w') && $(this).val('');
    });
  };

  $(form).submit(function ()
  {
    loader.show();
    var url = $(this).attr("action").replace("_", $(login).val());
    $.ajax({
      url: url,
      dataType: 'json',
      beforeSend: function ()
      {
        $(login).removeClass("error");
        $(".source").empty();
      },
      success: function (result)
      {
        $(albums)
          .removeAttr("disabled")
          .empty()
          .focus();
        $.each(result, function (i, album)
        {
          $("<option></option>")
            .text(album.t)
            .val(album.y)
            .data("data", album)
            .appendTo(albums);
        });
      },
      error: function ()
      {
        $(login).addClass("error");
        $(albums)
          .attr("disabled", "disabled")
          .empty();
      },
      complete: function ()
      {
        $(albums).change();
      }
    });
    return false;
  });

  var types = {};
  types[YMaps.MapType.MAP.getName()] = "MAP";
  types[YMaps.MapType.SATELLITE.getName()] = "SATELLITE";
  types[YMaps.MapType.HYBRID.getName()] = "HYBRID";

  $(albums).bind("rebind", function ()
  {
    var option = $("option:selected", this);
    var rawData = option.data("data");
    var type = types[map.getType().getName()] || "MAP";
    var data = { login: rawData.l, albumId: rawData.a, name: option.text(), type: type };
    $(title).attr("href", rawData.u + "?type=" + type);
    $("script[type=text/html]").each(function (i, el)
    {
      el = $(el);
      $("." + el.attr("id")).text(el.parseTemplate(data));
    });
  });

  $(albums).change(function ()
  {
    map.removeAllOverlays();
    var alb = $(this);
    var yamapsml = alb.val();
    if (!yamapsml) { loader.hide(); return; }
    loader.show();
    var ml = new YMaps.YMapsML(yamapsml, { viewAutoApply: false });
    YMaps.Events.observe(ml, [ml.Events.Load, ml.Events.Fault], function (ml) { loader.hide(); });
    YMaps.Events.observe(ml, ml.Events.Load, function (ml, error)
    {
      map.addOverlay(ml);
      map.setBounds(ml.view.boundedBy);
    });
    alb.trigger("rebind");
  });

  YMaps.Events.observe(map, map.Events.TypeChange, function ()
  {
    $(albums).trigger("rebind");
  });
};

function Team23Control($, logo, link)
{
  this.onAddToMap = function (map, position)
  {
    this.container = $("<a href='" + (link || "http://team23.ru") + "' target='_blank'><img src='" + logo + "' alt='Team23' title='Разработано Team 23' /></a>")
    this.map = map;
    this.position = position || new YMaps.ControlPosition(YMaps.ControlPosition.BOTTOM_LEFT, new YMaps.Size(10, 10));

    // CSS-свойства, определяющие внешний вид элемента
    this.container.css(
    {
      position: "absolute",
      zIndex: YMaps.ZIndex.CONTROL,
      margin: 0
    });

    this.position.apply(this.container);

    this.container.appendTo(this.map.getContainer());
  }

  this.onRemoveFromMap = function ()
  {
    if (this.container.parent())
    {
      this.container.remove();
      this.container = null;
    }
    this.map = null;
  };
}