/**
 * LightBox3dot
 * 
 * @author Vladimir Shushkov <vladimir@shushkov.ru>
 */

if (!cm) {
	var cm = {};
	cm.addEvent = function(el, type, fn) {
		if (cm.isArray(el)) {
			for (var i = 0, l = el.length; i < l; i++) {
				cm.addEvent(el[i], type, fn);
			}
			return;
		}
		if (el.attachEvent) {
			el['e'+ type + fn] = fn;
			el[type + fn] = function() {
				el['e'+ type + fn](window.event);
			};
			el.attachEvent('on'+ type, el[type+fn]);
		} else {
			el.addEventListener(type, fn, false);
		}
	};
	cm.stopEvent = function(e) {

		if (document.all) {
			e.cancelBubble = false;
			e.returnValue = false;
			return;
		}
		e.preventDefault();
		e.stopPropagation();
		e.stopped = true;
	};
}


var LightBox3dot = {
    
    init: function(options) {
        
        var collections = {
            __common__: []
        };
        var popUp = new LightBox3dot.PopUp;
        
        var showCollection = function(event) {
            cm.stopEvent(event);
            popUp.close();
            
            if (this.rel.indexOf('lightbox[') !== -1) {
                popUp.setCollection(collections[this.collectionName], this.collectionIndex);
            } else {
                popUp.setCollection([{url: this.href, title: this.title}], this.collectionIndex);
            }
            popUp.start();
        };
        
		var links = document.getElementsByTagName('a'), item;
		for (var i = 0; item = links[i]; i++) {
            if (!item.rel || item.rel.indexOf('lightbox') === -1) {
                continue;
            }
            var isCommon = item.rel.indexOf('lightbox[') === -1;
            var collectionName = isCommon ?  '__common__' : item.rel;
            if (collections[collectionName] === undefined) {
                collections[collectionName] = [];
            }
            item.collectionName = collectionName;
            item.collectionIndex = isCommon ? 0 : collections[collectionName].length;
			cm.addEvent(item, 'click', showCollection);
            collections[collectionName].push({url: item.href, title: item.title});
		}

		if (cm && typeof cm.getAncestors == 'function') {
			cm.addEvent(document, 'click', function(e) {
				var target = e.target || e.srcElement;
				if (/lightBox3dot/.test(target.className)
					|| cm.getAncestors(target, 'div', false, 'lightBox3dot')
					|| document.all
				) {
					return;
				}
				popUp.close();
			});
		}
    }
    
};

LightBox3dot.PopUp = function() {

	this._col = [];
	this._i = 0;
	this._box = null;
	this._shadow = null;
	this._img = null;
	this._imgBox = null;
	this._descBox = null;
	this._btnPrev = null;
	this._btnNext = null;

	var self = this;
    
    this.setCollection = function(collection, index) {
        this._col = collection;
        if (index !== undefined) {
            this._i = parseInt(index);
        }
        this._tweakBtn();
    };
    
    this.getCurrentItem = function() {
        return this._col[this._i];
    };
    
    this.close = function() {
        this.empty();
        this.getBox().style.width = '';
        this.getImgBox().style.height = '';
        if (this._box !== null && this._box.parentNode) {
            this.getBox().parentNode.removeChild(this.getBox());
        }
		if (this._shadow && this._shadow.parentNode) {
			this._shadow.parentNode.removeChild(this._shadow);
		}
    };
    
    this.start = function() {
        document.body.appendChild(this.getBox());
        document.body.appendChild(this._shadow);
        this._show();
        
    };
    
    this._show = function() {
        this._setPreload(true);
        this._center();
        this._setDesc(this.getCurrentItem().title);
        this.getImg().onload = _hImageLoad;
        this.getImg().src = this.getCurrentItem().url;
    };
    
    this._resize = function() {
        this.getBox().style.width = this.getImg().offsetWidth +'px';
        this.getImgBox().style.height = this.getImg().offsetHeight +'px';
        this.getBtnPrev().style.height =
        this.getBtnNext().style.height = this.getImg().offsetHeight +'px';
        this._center();
    };
    
    this._center = function() {
        this.getBox().style.marginTop = '-'+ (this.getBox().offsetHeight / 2) +'px';
        this.getBox().style.marginLeft = '-'+ (this.getBox().offsetWidth / 2) +'px';
    };
    
    this._setPreload = function(state) {
        this.getBox().firstChild.className = state == true ? 'wrapBox preload' : 'wrapBox';
    };
    
    this._tweakBtn = function() {
        this.getBtnPrev().style.display = this._i === 0 ? 'none' : 'block';
        this.getBtnNext().style.display = this._i === (this._col.length - 1) ? 'none' : 'block';
    };
    
    this._setDesc = function(value) {
        if (!value) {
            this.getDescBox().innerHTML = '';
            this.getDescBox().style.display = 'none';
        } else {
            this.getDescBox().innerHTML = value;
            this.getDescBox().style.display = 'block';
        }
    };
    
    this.getBox = function() {
        if (this._box === null) {
            this._box = document.createElement('div');
            this._box.className = 'lightBox3dot';

            this._shadow = document.createElement('div');
            this._shadow.className = 'lightBox3dotShadow';
            
            var wrap = this._box.appendChild(document.createElement('div'));
            wrap.className = 'wrapBox';
            
            var btnClose = wrap.appendChild(document.createElement('div'));
            btnClose.className = 'btnClose';
            
            var navLinks = wrap.appendChild(document.createElement('div'));
            navLinks.className = 'navLinks';
            
            this._btnPrev = navLinks.appendChild(document.createElement('a'));
            this._btnPrev.href = '#';
            this._btnPrev.className = 'btnPrev';
            this._btnPrev.style.display = 'none';
            
            this._btnNext = navLinks.appendChild(document.createElement('a'));
            this._btnNext.href = '#';
            this._btnNext.className = 'btnNext';
            this._btnPrev.style.display = 'none';
            
            this._imgBox = wrap.appendChild(document.createElement('div'));
            this._imgBox.className = 'imageBox';
            
            this._img = this._imgBox.appendChild(document.createElement('img'));
            
            this._descBox = wrap.appendChild(document.createElement('div'));
            this._descBox.className = 'description';
            this._descBox.style.display = 'none';

			cm.addEvent(this._btnPrev, 'click', _hBtnPrev);
			cm.addEvent(this._btnNext, 'click', _hBtnNext);
			cm.addEvent(btnClose, 'click', _hBtnClose);
			cm.addEvent(this._shadow, 'click', _hBtnClose);

        }
        return this._box;
    };
	
	this.getBtnPrev = function() {
		if (this._btnPrev === null) {
			this.getBox();
		}
		return this._btnPrev;
	};
	
	this.getBtnNext = function() {
		if (this._btnNext === null) {
			this.getBox();
		}
		return this._btnNext;
	};

	this.getImgBox = function() {
		if (this._imgBox === null) {
			this.getBox();
		}
		return this._imgBox;
	};

	this.getImg = function() {
		if (this._img === null) {
			this.getBox();
		}
		return this._img;
	};

	this.getDescBox = function() {
		if (this._descBox === null) {
			this.getBox();
		}
		return this._descBox;
	};
	
	this.empty = function() {
		this._col = [];
		this._i = 0;
	};
    
    var _hImageLoad = function(event) {
        self._img.onLoad = null;
        self._setPreload(false);
        self._resize();
    };
    
    var _hBtnPrev = function(event) {
        cm.stopEvent(event);
        if (self._i <= 0) {
            return;
        }
        self._i--;
        self._setDesc();
        self._tweakBtn();
        self._show();
    };
    
    var _hBtnNext = function(event) {
        cm.stopEvent(event);
        if (self._i >= (self._col.length - 1)) {
            return;
        }
        self._i++;
        self._setDesc();
        self._tweakBtn();
        self._show();
    };
    
    var _hBtnClose = function(event) {
        cm.stopEvent(event);
        self.close();
    };
    
};

LightBox3dot.init();