var scalerOptionSplitter = /\.(?!\d)/;
//scalerOptionSplitter = /\.(?!\d)/;


var MT_iZoom = {
   el: null
  ,img: null
  ,zoom: 1
	,c: {}
	,imgMorph: null
  ,doingZoom: false
  ,doingLoad: false
  
  ,initialize: function(el)
  {
    this.el = el;
    this.el.addEvent('click', this.zoomIn.bindWithEvent(this));
		this.el.addEvent('contextmenu', this.zoomOut.bindWithEvent(this));
		
    this.c = this.el.getCoordinates();
    
    this.el.setStyles({
       position: 'absolute'
			,overflow: 'hidden'
    });
    
    this.img = new Image();
    this.img.src = /^url\((.*)\)$/.exec(this.el.getStyle('background-image'))[1];
		
		this.img.setStyles({
			 position: 'absolute'
			,top: 0
			,left: 0
		});
		
		this.el.adopt(this.img);
		
		this.imgMorph = new Fx.Morph(this.img, {wait: false, onComplete: this.didZoom.bind(this)});
  }
  
  ,zoomIn: function(e)
  {
		e.stop();
    this.zoom *= 1.5;
    var x = e.page.x - this.c.left;
    var y = e.page.y - this.c.top;
    console.log(x, y);
    this.doZoom();
  }
  
  ,changeImg: function()
  {
    if (this.doingLoad) return;
    if (this.doingZoom) return;
    
    this.img.src = this.loadingImg.src;
    this.loadingImg = null;
  }
  
  ,didZoom: function()
  {
    this.doingZoom = false;
    this.changeImg();
  }
  
  ,didLoad: function()
  {
    this.doingLoad = false;;
    this.changeImg();
  }
  
	,doZoom: function()
	{
    var w = Math.floor(this.zoom * this.c.width);
    var h = Math.floor(this.zoom * this.c.height);
    var l = this.c.width / 2 - w / 2;
    var t = this.c.height / 2 - h / 2;
		this.doingZoom = true;
    
    var url = Util.replaceScaleroption(this.img.src, 'w'+w+'.h'+h);
    this.loadingImg = new Asset.image(url, {onComplete: this.didLoad.bind(this)});
    
  		this.imgMorph.start({
			 top: t
			,left: l
			,width: w
			,height: h
		});    
	}
	
  ,zoomOut: function(e)
  {
    e.stop();
		this.zoom /= 1.5;
		
    var x = e.page.x - this.c.left;
    var y = e.page.y - this.c.top;
    console.log(x, y);
		
		this.doZoom();
  }
};
MT_iZoom = new Class(MT_iZoom);

window.addEvent('domready', function(){
  $$('.zooming').each(function(el){
    new MT_iZoom(el);
  });
});


var Util = {
	
	ucFirst: function(Str)
	{
        var F = Str.substr(0, 1);
        var R = Str.substr(1, Str.length - 1);
	    return F.toUpperCase() + R.toLowerCase();
	}
    
    ,extractUrlFromBG: function(el)
    {
      return /^url\((.*)\)$/.exec(el.getStyle('background-image')).pop().replace(/"/g, '');
    }    

    ,transferScalerOptions: function(FromURL, ToURL)
    {
        if (!arguments[0])
            throw 'FromURL fehlt';
        if (!arguments[1])
            throw 'ToURL fehlt';
            
        var Options = Util.getScalerOptions(FromURL);

        if (!Options)
            throw 'Options konnten nicht gezogen werden';

        return Util.setScalerOptions(ToURL, Options);
    }
    
    ,stripScalerOptions: function(Str)
    {
        var TempURL = [];
        var TempFile = [];
        var TempFileSplit = [];

        TempURL         = Str.split(/\//);
        if ('http:' == TempURL[0])
        {
            TempURL.shift(); // http:
            if ('' == TempURL[0]) // IE mach aus // kein Element
                TempURL.shift();
                
            TempURL.shift();
            TempURL.unshift('');
//            TempURL[0] = '';
        }
        
        TempFile        = TempURL.pop();
        TempFile        = TempFile.split(scalerOptionSplitter);
        TempFileSplit.push(TempFile.shift());
        TempFileSplit.push(TempFile.pop());
        TempFile        = TempFileSplit.join('.');
        TempURL.push(TempFile);
        TempURL         = TempURL.join('/');
        
        TempURL = TempURL.replace(/Generate\//, '');
        
        return TempURL;
    }
    
    ,getScalerOptions: function(Str)
    {
        Str = Str.split(/\//).pop();
        Str = Str.split(scalerOptionSplitter);
        Str.shift();
        Str.pop();
        return Str.join('.');
    }
    
    ,setScalerOptions: function(URL, Options)
    {
        var Base = URL.split(/\//);
        
        URL = [];
        if (Base[0] == '')
            URL.push(Base.shift());
    
        if ('http:' == URL[0])
        {
            URL.push(Base.shift());
            URL.push(Base.shift());
        }
        URL.push(Base.shift());
        URL.push(Base.shift());
        URL.push('Generate');
        
        Base.unshift(URL.join('/'));
        
        var File = Base.pop();
        console.log(scalerOptionSplitter);
        FileStrips = File.split(scalerOptionSplitter);
        console.log(FileStrips);
        
        File = [];
        
        File.push(FileStrips.shift());
        File.push(Options);
        File.push(FileStrips.pop());
        
        Base.push(File.join('.'));
        Base = '/' + Base.join('/');
        Base = Base.replace('\/\/', '/');
        Base = Base.replace('/Generate\/Generate/', '/Generate/');
        return Base;
    }
    
    ,scaleImage: function(url, opt)
    {
          var url = $pick(url, '');
          url = url.replace(/media\//, 'media/_generate/');
          url = url.replace(/img\//, 'img/_generate/');
          url = url.split(/\./);
          var ext = url.pop();
          if (arguments[1]) url.push(opt);
          url.push(ext);
  
        return url.join('.');
    }
    
    ,replaceScaleroption: function(In, New)
    {
        if (!arguments[1])
            console.trace();
        
        In      = In.split(/\//);
        if ('http:' == In[0])
        {
          In.shift();
          if ('' == In[0]) In.shift();
          In.shift();
        } 
        File    = In.pop();

        File    = File.split(scalerOptionSplitter);
        New     = New.split(scalerOptionSplitter);

        New.unshift(File.shift());
        New.push(File.pop());
        
        In.push(New.join('.'));

    		out = In.join('/').replace(/:\/([^\/])/, '://$1');
    		if (0 > out.search(/Image\/Generate\//))
    		{
    			out = out.replace(/\/Image\//, '/Image/Generate/');
    		}
        out = '/' + out;
        
        return out.replace(/\/\//g, '/');
    }
	
    ,snapTo: function(Snap, To, Style, OffSet)
    {
        if (!arguments[2])
            Style = 'lud';

        if (!arguments[3])
            OffSet = 0;

//        alert(OffSet);

        to      = {x: 0, y: 0};
        SnapTo  = Util.getPos(To);
//        c = getClientDimension();
        Screen = Util.innerDimension();
        Screen.x -= 30; // Scrollbar

        var Probe = {x: 0, y: 0};
        
        switch (Style)
        {
            case 'rud' :
                to.x    = SnapTo.x + To.offsetWidth + OffSet;
                Probe.x = to.x + Snap.offsetWidth;
                if (Probe.x > Screen.x)
                    to.x    = SnapTo.x + To.offsetWidth + OffSet - (Probe.x - Screen.x);

                to.y    = SnapTo.y - Snap.offsetHeight - OffSet;
                if (to.y < 1)
                    to.y    = SnapTo.y + To.offsetHeight + OffSet;
                break;

            case 'lud' :
                to.x    = SnapTo.x - Snap.offsetWidth - OffSet;
                if (to.x < 1)
                    to.x    = SnapTo.x - Snap.offsetWidth - OffSet + (Math.abs(to.x));

                to.y    = SnapTo.y - Snap.offsetHeight - OffSet;
                if (to.y < 1)
                    to.y    = SnapTo.y + To.offsetHeight + OffSet;
                break;

            case 'luh' :
                to.x    = SnapTo.x - Snap.offsetWidth - OffSet;
                if (to.x < 1)
                    to.x    = SnapTo.x - Snap.offsetWidth - OffSet + (Math.abs(to.x));

                to.y    = SnapTo.y;
                break;

            case 'luv' :
                to.x    = SnapTo.x;
                to.y    = SnapTo.y - OffSet - Snap.offsetHeight;
                break;

            case 'rbv' :
                to.x    = SnapTo.x + To.offsetWidth - Snap.offsetWidth;
                if (to.x < 1)
                    to.x    = 0;


                to.y    = SnapTo.y + To.offsetHeight + OffSet;
                if (to.y > Screen.y)
                    to.y    = SnapTo.y - Snap.offsetHeight - OffSet;
                break;

            case 'lbv' :
                to.x    = SnapTo.x;
                if (to.x + Snap.offsetWidth > Screen.x)
                    to.x    = Screen.x - Snap.offsetWidth;


                to.y    = SnapTo.y + To.offsetHeight + OffSet;
                if (to.y > Screen.y)
                    to.y    = SnapTo.y - Snap.offsetHeight - OffSet;
                break;

            case 'lu' :
                leftPos     = SnapTo.x + To.offsetWidth + Snap.offsetWidth;
                bottomPos   = SnapTo.y + To.offsetHeight + Snap.offsetHeight;
                
                if (leftPos > Screen.x)
                {
                    to.x = SnapTo.x - OffSet - Snap.offsetWidth;
                }
                else
                {
                    to.x = SnapTo.x + OffSet + To.offsetWidth;
                }
                
                if (bottomPos > Screen.y)
                {
                    to.y = SnapTo.y - Snap.offsetHeight + To.offsetHeight;
                }
                else
                {
                    to.y = SnapTo.y;
                }
                break;
                
            case 'lb' :
                leftPos = SnapTo.x + Snap.offsetWidth;
                bottomPos = SnapTo.y + To.offsetHeight + Snap.offsetHeight;
                
                if (leftPos > Screen.x)
                {
                    to.x = SnapTo.x + To.offsetWidth - OffSet - Snap.offsetWidth;
                }
                else
                {
                    to.x = SnapTo.x;
                }
                
                if (bottomPos > Screen.y)
                {
                    to.y = SnapTo.y - Snap.offsetHeight + To.offsetHeight;
                }
                else
                {
                    to.y = SnapTo.y + OffSet + To.offsetHeight;
                }
                break;
        }
        
        if (to.y < Util.scrollingOffset().y)
            to.y = Util.scrollingOffset().y;
        
        Snap.style.left     = to.x + 'px';
        Snap.style.top      = to.y + 'px';
        
//        Snap.innerHTML      =
//              '<div style="background: white;">'
//            + '<br/>this.Options.Snap: ' + Style
//            + '<br/>Snap.offsetWidth: ' + Snap.offsetWidth
//            + '<br/>OffSet: ' + OffSet
//            + '<br/>Snap.offsetWidth: ' + Snap.offsetWidth
//            + '<br/>Snap.offsetHeight: ' + Snap.offsetHeight
//            + '<br/>SnapTo.x: ' + SnapTo.x
//            + '<br/>SnapTo.y: ' + SnapTo.y
//            + '<br/>Screen.x: ' + Screen.x
//            + '<br/>Screen.y: ' + Screen.y
//            + '<br/>to.x: ' + to.x
//            + '<br/>to.y: ' + to.y
//            + '</div>'
//            ;
    },

    pageDimension: function()
    {
        var x,y;
        var test1 = document.body.scrollHeight;
        var test2 = document.body.offsetHeight
        if (test1 > test2) // all but Explorer Mac
        {
        	x = document.body.scrollWidth;
        	y = document.body.scrollHeight;
        }
        else // Explorer Mac;
             //would also work in Explorer 6 Strict, Mozilla and Safari
        {
        	x = document.body.offsetWidth;
        	y = document.body.offsetHeight;
        }
		
		return {x: x, y: y};
    },

	scrollingOffset: function()
	{
		var x,y;
		if (self.pageYOffset) // all except Explorer
		{
			x = self.pageXOffset;
			y = self.pageYOffset;
		}
		else if (document.documentElement && document.documentElement.scrollTop)
			// Explorer 6 Strict
		{
			x = document.documentElement.scrollLeft;
			y = document.documentElement.scrollTop;
		}
		else if (document.body) // all other Explorers
		{
			x = document.body.scrollLeft;
			y = document.body.scrollTop;
		}
		
		return {x: x, y: y};
	},
	
	innerDimension: function()
	{
		var x,y;
		if (self.innerHeight) // all except Explorer
		{
			x = self.innerWidth;
			y = self.innerHeight;
		}
		else if (document.documentElement && document.documentElement.clientHeight)
			// Explorer 6 Strict Mode
		{
			x = document.documentElement.clientWidth;
			y = document.documentElement.clientHeight;
		}
		else if (document.body) // other Explorers
		{
			x = document.body.clientWidth;
			y = document.body.clientHeight;
		}
		
		return {x: x, y: y};
	},

	/**
	 * Einem Element eine (weitere) Klasse zuweisen.
	 * Bestehende Klassen werden nicht entfernt.
	 * Aequivalent zu Element.addClassName()
	 */
	addClass: function(Elem, addClassName) {
	    Elem = document.getElement(Elem);
	    Elem.addClass(addClassName);
//		if (Elem) {
//			CurrentClass = $(Elem).className.split(' ');
//			// nicht mehrfach hinzufuegen:
//			isSet = false;
//			for (ci = 0; ci < CurrentClass.length; ci++) {
//				if (CurrentClass[ci] == addClassName) {
//					isSet = true;
//				}
//			}
//			if (!isSet) {
//				CurrentClass.push(addClassName);
//			}
//			$(Elem).className = CurrentClass.join(' ');
//		}
	},

	/**
	 * Einem Element gezielt eine Klasse entfernen, ohne eventuell
	 * weitere Klassen zu stoeren.
	 * Aequivalent zu Element.removeClassName()
	 */
	stripClass: function(Elem, stripClassName) {
		if (Elem) {
			CurrentClass = $(Elem).className.split(' ');
			for (ci = 0; ci < CurrentClass.length; ci++) {
				if (CurrentClass[ci] == stripClassName) {
					CurrentClass.splice(ci, 1);
				}
			}
			$(Elem).className = CurrentClass.join(' ');
		}
	},
	/**
	 * Innerhalb eines Elementes nach dem Child-Element suchen, 
	 * das eine bestimmte Klasse enthaelt.
	 */
	findByClass: function(Elem, ClassName) {
		ChildElement = false;
		if (Elem) {
			Elem = $(Elem);
			for (var i = 0; (Child = Elem.childNodes[i]); i++) {
				if(Element.hasClassName(Child, ClassName)) {
					ChildElement = Child;
				}
			}
		}
		return ChildElement;
	},

	
	toggleDivState: new Array(),
	toggleDivTarget: new Array(),
	toggleDivHidden: new Array(),

	/**
	 * Schalter zum Ein-/Ausblenden eines Elementes
	 * @param	string	Elem	der Schalter (Uebergabe mit this)
	 * @param	string	target	Id des Elementes, das ein-/ausgeblendet werden soll
	 * @param	string	dir		updown oder leftright
	 * @param   array	display 'block', 'inline', ... - Zustand fuer 'sichtbar'
	 * @param	bool	state	gewuenschter Anzeigestatus beim 1. Aufruf
	 * 							(danach wird Zustand hier gespeichert)
	 * @param	string	hidden	Id/Name fuer Hidden-Feld, wenn vorhanden
	 */
	toggleDiv: function(Elem, target, dir, display, state, hidden) {
		if (Util.toggleDivState[target]) {
			Util.toggleDivState[target] = !Util.toggleDivState[target];
		} else {
			Util.toggleDivState[target] = state;
			if ((targetElem = $(target))) {
				Util.toggleDivTarget[target] = targetElem;
			}
		}
		if (hidden != '' && !Util.toggleDivHidden[target]) {
			Util.toggleDivHidden[target] = $(hidden);
		}
		if (Util.toggleDivState[target]) {
			switch (dir) {
				case 'updown':
					Elem.innerHTML = '▼';
					break;
				case 'leftright':
					Elem.innerHTML = '►';
					break;
			}
			if (Util.toggleDivTarget[target]) {
				Util.toggleDivTarget[target].style.display = display;
			}
			if (Util.toggleDivHidden[target]) {
				Util.toggleDivHidden[target].value = 1;
			}
		} else {
			switch (dir) {
				case 'updown':
					Elem.innerHTML = '▲';
					break;
				case 'leftright':
					Elem.innerHTML = '◄';
					break;
			}
			if (Util.toggleDivTarget[target]) {
				Util.toggleDivTarget[target].style.display = 'none';
			}
			if (Util.toggleDivHidden[target]) {
				Util.toggleDivHidden[target].value = 0;
			}
		}
	},
	
	
	centerScreen: function(width, height)
	{
        var Screen = Util.innerDimension();
        var Scroll = Util.scrollingOffset();

		var X = (Screen.x - width) / 2;
		var Y = (Screen.y - height) / 2;
        
        Y += Scroll.y;

		return {x: X, y: Y};
	},
	
	
	centerOnScreen: function(Elem)
	{
        var Screen = Util.innerDimension();
        var Scroll = Util.scrollingOffset();
        var ScreenPadding = 20;

        var UseHeight = Elem.offsetHeight;
        var MasXeight = Screen.y - 40;
        if (UseHeight > MasXeight)
        {
            Elem.style.height = MasXeight + 'px';
            UseHeight = MasXeight;
        }


		var X = (Screen.x - Elem.offsetWidth) / 2;
		var Y = (Screen.y - UseHeight) / 2;
        
        switch (BrowserDetect.browser)
        {
            case 'Explorer' :
                Elem.style.position = 'absolute';
                Y += Scroll.y;
                break;
            default :
                Elem.style.position = 'fixed';
                break;
        }


        Elem.style.left    = X + 'px';
        Elem.style.top     = Y + 'px';
	},
	
	getPos: function(obj)
	{
		return {
			x: Util.findPosX(obj),
			y: Util.findPosY(obj)
		}
	},
	
	findPosX: function(obj)
	{
		var curleft = 0;
		if (obj.offsetParent)
		{
			while (obj.offsetParent)
			{
				curleft += obj.offsetLeft;
//				obj.style.border = '1px solid green';
				obj = obj.offsetParent;
			}
		}
		else if (obj.x)
		{
			curleft += obj.x;   
//            obj.style.border = '1px solid blue';
		}
		return curleft;
	},
	
	findPosY: function(obj)
	{
		var curtop = 0;
		if (obj.offsetParent)
		{
			while (obj.offsetParent)
			{
				curtop += obj.offsetTop
				obj = obj.offsetParent;
			}
		}
		else if (obj.y)
			curtop += obj.y;
		return curtop;
	},
	
	mousePos: function(e)
	{
		var posx = 0;
		var posy = 0;
		if (!e) var e = window.event;
		if (e.pageX || e.pageY)
		{
			posx = e.pageX;
			posy = e.pageY;
		}
		else if (e.clientX || e.clientY)
		{
			posx = e.clientX + document.body.scrollLeft;
			posy = e.clientY + document.body.scrollTop;
		}
		// posx and posy contain the mouse position relative to the document
		// Do something with this information
		
		return {x: posx, y: posy};
	},
	
	keepAlive: function() {
	    new ajax ('/plugin/de.masstisch.ajax/KeepAlive.php', {
	    });    
	},
	
	/**
	 * Weiterleitung eines Events, z.B. onDblClick, verhindern
	 */
	stopEventBubbling: function(event) {
		if (!event) var event = window.event;
	    event.cancelBubble = true;
	    if (event.stopPropagation) event.stopPropagation();
	}
}


var MT_Lightshow = {
   theBlend: null
  ,theLayer: null
  ,lastUrl: null
  ,fullClickClose: true
  
  ,hide: function()
  {
    this.theLayer.hide();
  }
  
  ,hideTest: function()
  {
    console.log('this.fullClickClose', this.fullClickClose);
    if (this.fullClickClose) this.hide();
  }
  
  ,init: function()
  {
    if (!this.theBlend)
    {
      this.theBlend = new MT_Blend();
      this.theLayer = new MT_Layer();

      window.addEvent('cartUpdated', this.reInit.bind(this));
      window.addEvent('reInitLightshow', this.reInit.bind(this));
      this.theBlend.addEvent('didOpen', this.theLayer.show.bind(this.theLayer));
      this.theBlend.addEvent('click', this.hide.bind(this));
      this.theLayer.addEvent('didClose', this.theBlend.hide.bind(this.theBlend));
      this.theLayer.addEvent('click', this.hideTest.bind(this));
      this.theLayer.addEvent('clickClose', this.hide.bind(this));
    }
    else
    {
      console.log('skipped Element-Initialisation');
    }
    
    this.reInit();
  }
  ,reInit: function()
  {
    $$('[rel^=lightshow], img.lightshow').each(this.initEl.bind(this));
  }
  
  ,initEl: function(el)
  {
    if (el.preppedMTLightshow)
    {
      return; 
    }
    el.preppedMTLightshow = true;
    
    el.setStyle('cursor', 'pointer');
    el.addEvent('click', function(e)
    {
      e.stop();
      this.blur();
      MT_Lightshow.show(this);
    }.bindWithEvent(el));
  }
  
  ,source: null
  ,layers: []
  
  
  ,contentPre: ''
  ,contentPost: ''
  
  ,contentsLoaded: function(cnt)
  {
    console.log('all loaded ...', arguments);
    if (arguments[0])
    {
      this.theLayer.setContent(cnt);
    }
    else
    {
      var adjustTo = {x: 0, y: 0};
      this.contentPre = this.contentPost = '';
      console.log(this.loadingImages);
      this.loadingImages.each(function(img)
      {
        if (Browser.Engine.trident)
        {
  	      var style = 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + img.src + '\', sizingMethod=\'scale\');';
        }
        else
        {
          var style = 'background: url(' + img.src + ') no-repeat center center;';
        }
        console.log(img);
        style += ' width: ' + img.width + 'px; height: ' + img.height + 'px;';
        adjustTo.x = Math.max(adjustTo.x, img.width);
        adjustTo.y = Math.max(adjustTo.y, img.height);
        this.contentPre += '<div style="margin: 0 auto;' + style + '">';
        this.contentPost += '</div>';
      }.bind(this));
      this.theLayer.setContent('<div style="text-align: center;">' + this.contentPre + this.contentPost + '</div>', adjustTo);
    }
  }
  
  ,contentsBroken: function()
  {
    console.log('broken ...', arguments);    
    this.hide();
  }
  
  ,validW: [160
//, 208
//, 220
//, 240
//, 256
//, 320
//, 384
//, 416
//, 432
, 480
, 640
//, 720
, 800
//, 832
//, 848
//, 852
//, 858
//, 864
//, 960
//, 964
///, 1024
//, 1072
//, 1152
///, 1200
//, 1280
///, 1360
//, 1366
//, 1376
///, 1400
//, 1440
///, 1600
//, 1680
///, 1920
]
  ,validH: [120
//, 160
//, 176
//, 180
//, 192
//, 200
//, 240
//, 272
, 320
//, 348
//, 350
//, 352
//, 360
//, 364
//, 400
, 480
//, 484
//, 540
//, 544
//, 576
, 600
//, 624
//, 640
, 720
//, 768
//, 800
//, 854
//, 864
//, 870
//, 900
//, 960
, 1024
, 1050
//, 1080
, 1200
, 1400
//, 1440

  ]
  
  ,findNearest: function(n, hs)
  {
    for (var i = hs.length; i >= 0; i--)
    {
      if (hs[i] < n)
      {
        return hs[i];
      }
    }
    
    return hs[0];
  }
  
  ,show: function(source)
  {
    var ws = window.getSize();
    var scale = 'w'+this.findNearest(ws.x - 30, this.validW)+'.h'+this.findNearest(ws.y - 30, this.validH);
    console.dir(ws);
    
    console.log('want scale: ', scale);
    this.source = source;
    this.layers = [];
    
    this.fullClickClose = true;
    $$('select').setStyle('opacity', 0);
    
    switch (source.get('tag'))
    {
      case 'a' :
        var url = source.href;
          
        if (-1 != url.search(/\.(jpg|jpeg|png|gif)$/i) || -1 != url.search(/:50000\//))
        {
          this.layers.push(Util.replaceScaleroption(url, scale));
        }
        else
        {
          this.fullClickClose = false;
          new Request({
             url: this.lastUrl = url
            ,onComplete: this.contentsLoaded.bind(this)
            ,onError: this.contentsBroken.bind(this)
          }).send();
          
          this.theBlend.show();
          return;
        }
        break;
      case 'img' :
        this.layers.push(Util.replaceScaleroption(source.get('src'), scale));
        break;
      case 'div' :
      case 'table' :
        if (-1 != source.getProperty('rel').search(/;/))
        {
          this.fullClickClose = false;
          var url = source.getProperty('rel').split(/;/).pop();
          
          if (-1 != url.search(/\.(jpg|jpeg|png|gif)$/i) || -1 != url.search(/:50000\//))
          {
            this.layers.push(Util.replaceScaleroption(url, scale));
          }
          else if ('_blank' == url)
          {
            this.theLayer.setContent('');
            this.theBlend.show();
            return;
          }
          else
          {
            new Request({
               url: this.lastUrl = url
              ,onComplete: this.contentsLoaded.bind(this)
              ,onError: this.contentsBroken.bind(this)
            }).send();
            this.theBlend.show();
            return;
          }
        }
        
        this.fullClickClose = true;
        
        if (0 == this.layers.length)
        {
          this.layers.push(Util.replaceScaleroption(/url\((.*)\)/.exec(source.getStyle('background-image'))[1], scale).replace(/"/g, '').replace(/\/\//, '/'));
        }
        
        source.getElements('.fixpng').each(function(el)
        {
          var url = el.getStyle('background-image');
          if (!url || 'none' == url)
          {
            var url = el.getStyle('filter');
            if (!url || 'none' == url) 
            {
              return;
            }
            url = /src='(.*)',/.exec(url)[1];
            if (-1 == url.search(/blind\.gif/))
            {
              this.layers.push(Util.replaceScaleroption(url, scale));
            }
          }
          else
          {
            url = /url\((.*)\)/.exec(url)[1];
            if (-1 == url.search(/blind\.gif/))
            {
              this.layers.push(Util.replaceScaleroption(url, scale).replace(/"/g, '').replace(/\/\//, '/'));
            }
          } 
        }.bind(this));
        break;
    }
    
    console.log('this.layers: ', this.layers);
    this.loadingImages = new Asset.images(this.layers, {
      onComplete: this.contentsLoaded.bind(this),
      onError: this.contentsBroken.bind(this),
      onProgress: function(){ console.log('progression ...', arguments); }
    });
    this.theBlend.show();
  }
}


var MT_Layer = {
   element: null
  ,elementInner: null
  ,fx: null
  ,fxInner: null
  ,doing: 'open'
  ,isOpen: false
  ,Implements: [Events]
  ,initialize: function()
  {
    this.element      = new Element('div', {id: 'theOuter'});
    this.elementInner = new Element('div', {id: 'theInner'});
    
    var elClose = new Element('div');
    elClose.setStyles({
       top: 0
      ,right: 0
      ,width: 16
      ,height: 16
      ,cursor: 'pointer'
      ,position: 'absolute'
    })
    if (Browser.Engine.trident4)
    {
      elClose.setStyles({
        filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'/media/Image/Icons/silk/cross.png\', sizingMethod=\'scale\''
      })
    }
    else
    {
      elClose.setStyles({
        background: 'url(/media/Image/Icons/silk/cross.png) no-repeat center center'
      }) 
    }
    elClose.addEvent('click', function(){ this.fireEvent('clickClose'); }.bind(this));
    this.element.adopt(elClose);
    
    this.element.addEvent('click', function(){
      this.fireEvent('click');
    }.bind(this));
    
    this.element.adopt(this.elementInner);
    this.fx           = new Fx.Morph(this.element, {duration: 250, property: 'opacity', wait: false, onComplete: this.evtTweenedOuter.bind(this)});
    this.fxInner      = new Fx.Tween(this.elementInner, {duration: 400, property: 'opacity', wait: false, onComplete: this.evtTweenedInner.bind(this)});
    
    this.addEvent('contentSet', this.evtContentSet.bind(this));
    this.addEvent('outerIsOpen', this.evtContentSet.bind(this));
  }
  
  ,setContent: function(cnt, reAdjust)
  {
    console.log('settingContent', cnt);
    this.elementInner.set('html', cnt);
    this.haveContent = true;
    this.needReadjust = false;
    if (arguments[1] && 0 < reAdjust.x)
    {
      this.reAdjustTo = reAdjust;
      this.needReadjust = true;
    }
    this.fireEvent('contentSet');
  }
    
  ,evtContentSet: function()
  {
    console.log('evtContentSet');
    console.log('this.isOpen', this.isOpen);
    console.log('this.haveContent', this.haveContent);
    console.log('this.needReadjust', this.needReadjust);
    if (this.isOpen && this.haveContent)
    {
      if (this.needReadjust)
      {
        var coord = window.getSize();
        this.doing = 'readjusting';
        this.elementInner.setStyles({
           width: this.reAdjustTo.x
          ,height: this.reAdjustTo.y
        });
        var x = 20 + this.reAdjustTo.x;
        var y = 20 + this.reAdjustTo.y;
        var z = {
           width: x
          ,height: y
          ,top: Math.floor((coord.y - y) / 2) + window.getScroll().y
          ,left: Math.floor((coord.x - x) / 2)
        };
        this.fx.start(z);
        console.dir(z);
        return;
      }
      
      this.fxInner.start(1);
    }
  }
  
  ,clearContent: function()
  {
    this.elementInner.set('text', ' ');
    this.haveContent = false;
  }
  
  ,evtTweenedOuter: function()
  {
    console.log('tweend the outer ...', this.doing);
    if ('close' == this.doing)
    {
      this.clearContent();
      if (this.element && document.getElement('body') === this.element.getParent()) document.getElement('body').removeChild(this.element);
      this.fireEvent('didClose'); 
    }
    else if ('readjusting' == this.doing)
    {
      this.needReadjust = false;
      this.fireEvent('outerIsOpen');
    }
    else
    {
      window.addEvent('scroll', this.relocate.bind(this));
      this.element.setStyles({
        background: 'url(/media/Image/Icons/ajax/indicator_snake.gif) white center center no-repeat'
      })
      this.elementInner.setStyles({
         height: 570
        ,width: 780
      });
      this.isOpen = true;
      this.fireEvent('outerIsOpen');
      window.fireEvent('layerFilled');
    }
  }
  
  ,evtTweenedInner: function()
  {
    if ('close' == this.doing)
    {
      coord = window.getSize();
      this.fx.start({
         top: Math.floor((coord.y) / 2) + window.getScroll().y
        ,left: Math.floor((coord.x) / 2)
        ,width: 1
        ,height: 1
        ,opacity: 0
      });
      this.clearContent();
    }
    else
    {
    }
  }
  
  ,hide: function()
  {
    window.removeEvent('scroll', this.relocate.bind(this));
    
    this.element.setStyles({
      background: 'white'
    })
    this.elementInner.setStyles({
       width: 1
      ,height: 1
    });
    this.doing = 'close';
    this.isOpen = false;
    this.haveContent = false;
    this.fxInner.start(0);
  }
  
  ,relocate: function()
  {
    coord = window.getSize();
    this.fx.set({
       top: Math.floor((coord.y - 600) / 2) + window.getScroll().y
      ,left: Math.floor((coord.x - 800) / 2)
    });
  }
  
  ,show: function()
  {
    coord = window.getSize();
    this.element.setStyles({
       position: 'absolute'
      ,top: Math.floor((coord.y) / 2) + window.getScroll().y
      ,left: Math.floor((coord.x) / 2)
      ,width: 0
      ,height: 0
      ,overflow: 'hidden'
      ,background: 'white'
      ,zIndex: 10003
    });
    
    this.elementInner.setStyles({
       margin: 0
      ,opacity: 0
      ,background: 'white'
      ,overflow: 'auto'
      ,position: 'absolute'
      ,top: 10
      ,left: 10
    });
    document.getElement('body').adopt(this.element);
    
    this.doing = 'open';
    this.fx.start({
       top: Math.floor((coord.y - 600) / 2) + window.getScroll().y
      ,left: Math.floor((coord.x - 800) / 2)
      ,width: 800
      ,height: 600
      ,opacity: 1
    });
  }
};
MT_Layer = new Class(MT_Layer);


var MT_Blend = {
   element: null
  ,fx: null
  ,doing: 'open'
  ,Implements: [Events]
  ,initialize: function()
  {
    this.element       = new Element('div');
    this.element.addEvent('click', this.evtClick.bind(this));
    this.fx = new Fx.Tween(this.element, {duration: 250, property: 'opacity', wait: false, onComplete: this.evtTweened.bind(this)});
  }
  
  ,evtTweened: function()
  {
    if ('open' == this.doing)
    {
      this.fireEvent('didOpen');
    }
    else
    {
      if (this.element) this.element.destroy();
      $$('select').setStyle('opacity', 1);
    }
  }
  
  ,hide: function()
  {
    this.doing = 'close';
    this.fx.start(0);
    this.fireEvent('closing');
  }
  
  ,evtClick: function()
  {
    this.fireEvent('click');
  }
  
  ,show: function()
  {
    coord = window.getScrollSize();
    this.element.setStyles({
       position: 'absolute'
      ,top: 0
      ,left: 0
      ,width: coord.x
      ,height: coord.y
      ,backgroundColor: 'black'
      ,opacity: 0
      ,zIndex: 10002
    });  
    document.getElement('body').adopt(this.element);
    
    this.doing = 'open';
    this.fx.start(0.7);
  }
};
MT_Blend = new Class(MT_Blend);





window.addEvent('cartUpdated', MT_Lightshow.reInit.bind(MT_Lightshow));
window.addEvent('domready', MT_Lightshow.init.bind(MT_Lightshow));