(function ($){
  $.fn.extend ({
    mylightboxPlugin : function (options)
    {
      if (!$.event._mylightboxCleanup) $.event._mylightboxCleanup = [];

            // default options
            options = $.extend( {
//                template : "<div class=\"headline\"></div><div class=\"close\"> [X] </div><div class=\"image\"> <img style=\"margin: auto;\" src=\"\" alt=\"\" /> </div><div class=\"imageno\"> </div><div class=\"text\"> </div><div style=\"display: none;\" class=\"morepics\"> </div>",
                template : '<div>'+
                           '  <div style=""><h1 style="text-align: left; margin-left: 25px;"></h1></div>'+
                           '  <div class="clearfix">'+
                           '    <div class="lb-text" style="display: none; margin-right: 20px; text-align: left; font-family: Helvetica; font-size: 11px; color: #666666; float: right; margin-top: 10px; margin-left: 20x; width: 170px; height: 307px;"></div>'+
                           '    <div class="lb-image" style="float: left; display: block; margin-top: 10px; margin-left: 25px; width: 550px;"><img src="" width="550" alt="" /></div>'+
                           '    <div class="lb-imagestrip clearfix" style="float: left; clear: left; margin-left: 25px; ">'+
                           '  </div>'+
                           '</div>',
                textfieldWidth : 190,
                imagestripHeight : 90,
                popupWidth : 820-190,
                popupHeight : 605-90,
                useDefaultOnClick : false,
                imagestripMouseoverSelector : null

            },
            options );

      return this.each (function () {
        if (!this._mylightboxController) {
          this._mylightboxController = new MylightboxPlugin (this);
          $.event._mylightboxCleanup[$.event.guid] = this._mylightboxController;
          $.event._mylightboxCleanup[$.event.guid++].init (options);
        }
      });
    },

        myLightboxSetImage : function (imagePath, caption, $textcontainer, $imageStrip)
        {
            return _eachCall.call (this, 'show', imagePath, caption,  $textcontainer, $imageStrip);
        },
        myLightboxSetSubPicSelector : function (selector)
        {
//            return _eachCall.call (this, 'setSubPicSelector', selector);
        },

        mylightboxShow : function (closeCallback)
        {
//            if (this[0]._mylightboxController)
//                return this[0]._mylightboxController.showKLightbox (closeCallback);
            return false;
        },

    _mylightboxDestroy : function ()
    {
      return _eachCall.call (this, 'cleanup');
    }
  });


  var _eachCall = function (f, a1, a2, a3, a4)
  {
    return this.each (function () {
      if (this._mylightboxController)
        this._mylightboxController[f](a1, a2, a3, a4);
    });
  };


  $(window).bind('unload', function() {
    var els = $.event._mylightboxCleanup || [];
    for (var i in els) {
      $(els[i].ele)._mylightboxDestroy();
    }
  });


  function MylightboxPlugin(ele)
  {
    this.ele = ele;
    this.$ele = $(this.ele);
  };
  $.extend(MylightboxPlugin.prototype, {
    bindToObj: function(fn) {
      var self = this;
      return function() {
        return fn.apply(self, arguments)
      };
    },

    init : function(s)
    {
      this.template = s.template;
      this.popupWidth = s.popupWidth;
      this.popupHeight = s.popupHeight;
      this.textfieldWidth = s.textfieldWidth;
      this.imagestripHeight = s.imagestripHeight;
      this.useDefaultOnClick = s.useDefaultOnClick;
      this.$imagestripMouseoverSelector = s.imagestripMouseoverSelector;

      if (this.useDefaultOnClick)
        this.$ele.bind("click", this.defaultOnClick);

      if (this.$imagestripMouseoverSelector != null)
        this.$imagestripMouseoverSelector.bind("mouseover", this.defaultISmouseover);
    },

    show : function (image, caption, $textcontainer, $imageStrip) {
      var $lb = $(this.template).clone(); //#route-to-template").clone();
      $lb.attr("class", "knipplightbox");

      $("div.lb-image img:first", $lb).attr("src", image);

      if (caption != undefined)
        $("h1", $lb).text(caption);

      var textfieldVisible = false;
      if ($textcontainer != undefined && ($textcontainer.length >0) &&$textcontainer.html()!=""){
        $("div.lb-text", $lb).html($textcontainer.html()).show();
        textfieldVisible = true;
      }

      var imagestripVisible = false;
      if ($imageStrip != undefined&& ($imageStrip.length >0))
      {
        imagestripVisible = true;
        $("div.lb-imagestrip", $lb).append($imageStrip.html());
        this.$is = $("div.lb-imagestrip", $lb);

        this.$is.show();

        $("li", this.$is).click(this.bindToObj(this.imagestripClick));
        $("div.lb-imagestrip-left", this.$is).click(this.bindToObj(this.imagestripClickLeft));
        $("div.lb-imagestrip-right", this.$is).click(this.bindToObj(this.imagestripClickRight));

        this.firstShown = 1;
        this.picCount = $(".lb-imagestrip-ulcontainer ul:first", this.$is).children("li").length;
//        C.log("picCount:" + this.picCount);

        this.picsVisibleInUl = 3;
//  C.enable();
//        C.log("KK");
//        C.log(textfieldVisible);
      if (textfieldVisible==false)
//        this.$ele.addClass("small");

        $("div.lb-imagestrip-ulcontainer", $lb).css("width", "540px");

      }
//      $lb.attr("id","lightbox");

      $lb.dialog({
        modal: true,
        resizable: false,
        close: this.bindToObj(this.hide),
        width: this.popupWidth+(textfieldVisible ? this.textfieldWidth : 0),
        height: this.popupHeight+(imagestripVisible ? this.imagestripHeight : 0)
      });
      this.$lb = $('div.knipplightbox:last');
    },

    hide : function() {
      $('#route-to').remove();
    },

    imagestripClickLeft : function(evt) {
//      console.log(this.firstShown);
      if (this.firstShown <= 1)
        return;
      this.firstShown--;
      var $newFirst = $("ul li:nth-child("+this.firstShown+")",this.$is);
      var left = -$newFirst.position().left;
      $("ul",this.$is).animate({"margin-left": left},500);
//      $("ul",this.$lb).animate({"margin-left": left},500);
//      console.log($newFirst.position());
    },

    imagestripClickRight : function(evt) {
//      console.log(this.firstShown);
//      C.log($("ul",this.$is));
      if (this.firstShown > this.picCount - this.picsVisibleInUl )
        return;
      this.firstShown++;
      var $newFirst = $("ul li:nth-child("+this.firstShown+")",this.$is);
      var left = -$newFirst.position().left;
      $("ul",this.$is).animate({"margin-left": left},500);
    },

    imagestripClick : function(evt) {
//      alert(evt.target);
//      console.log();
      var $img = $(evt.target);

      if (! $img.is("img"))
        return;

      $img.parent().siblings().removeClass("lb-imagestrip-active");
      $img.parent().addClass("lb-imagestrip-active");

      var $desc = $img.siblings("div.lb-imagestrip-description");
      var $title = $img.siblings("div.lb-imagestrip-title");
      var $zoom = $img.siblings("div.lb-imagestrip-zoomavailable");
      $("div.lb-image img:first", this.$lb).attr("src", $img.attr("large"));
      $("div.lb-text", this.$lb).html($desc.html());
      $("h1", this.$lb).html($title.html());
    },


    defaultOnClick : function(evt) {
      evt.preventDefault();
      var $tgt = $(evt.target);
      var $is = $("#prod-imagestrip");
//      var $is = $(".lb-imagestrip", $tgt);
      var $act = $("li.lb-imagestrip-active", $is);

C.enable();
      C.log($tgt);
//      C.log($is);
//      C.log($("div.lb-description", $act));
//      C.log($act);
//      C.log($("div.lb-imagestrip-title", $act).text());

      $tgt.myLightboxSetImage($("img:first", $act).attr("large"),
                              $("div.lb-imagestrip-title", $act).text(),
                              $("div.lb-imagestrip-description", $act),
                              $is);
      return;
    },

  defaultISmouseover : function(evt){
        var $tgt = $(evt.target);
        if (! $tgt.is("img"))
            return;
         $(".lb-imagestrip-active",$tgt.parents("ul:first")).removeClass("lb-imagestrip-active");
        $tgt.parent("li").addClass("lb-imagestrip-active");
        $(".pd-image img").attr("src", $tgt.attr("preview"));
    },

    cleanup : function()
    {
    },

    getText : function ()
    {
      return this.optionA + this.optionB;
    }
  });
})(jQuery);

