var Juggler = Class.create({
	// Default params
	defaults: $H({
		prevId:      'prev_btn',
		nextId:      'next_btn',
		itemsToMove: 1,
		itemsToShow: 1,
		horizontal:    true,
		duration:    0.5,
		delay:       3.0,
		autoMove:    false,
		autoRewind:  false,
		itemSize:    0,
		itemsInRow:  1,
		itemsMax: 10
	    }),
	initialize: function(element, options) {
	    this.container = $(element);
	    if(!this.container) { return false; }
	    // this.id      = (element.id == null || element.id == '') ? this.generateRandomId() : element.id;
	    this.params  = this.defaults.merge(options);
	    Object.extend(this, this.params);
	    this.init();
	}
    });

Juggler.fn = Juggler.prototype;

Juggler.fn.generateRandomId = function() {
    var chars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
    var stringLength = 10;
    var randomString = '';
    for (var i = 0; i < stringLength; i++) {
	var rnum = Math.floor(Math.random() * chars.length);
	randomString += chars.substring(rnum, rnum + 1);
    }
    return randomString;
};

Juggler.fn.getItemSize = function() {
    var size = 0;
    if(this.params.get('itemSize') != 0) {
	size = this.params.get('itemSize');
    } else {
	if(this.params.get('horizontal')) {
	    size = this.itemWidth();
	} else {
	    size = this.itemHeight();
	}
    }
    this.params.set('itemSize', size);
};

Juggler.fn.itemWidth = function() {
    var e = this.items.first().childElements().first();
    var width = 0;
    width += e.getWidth();
    width += parseInt(e.getStyles().marginLeft);
    width += parseInt(e.getStyles().marginRight);
    return width;
};

Juggler.fn.itemHeight = function() {
    var e = this.items.first().childElements().first();
    var height = 0;
    height += e.getHeight();
    height += parseInt(e.getStyles().marginTop);
    height += parseInt(e.getStyles().marginBottom);
    return height;
};

Juggler.fn.init = function() {
    this.allowMove = true;
    this.activeTab = 1;
    this.juggler = $(this.container.down('ul'));
    this.juggler.setStyle('position: relative; left: 0px; top: 0px; overflow: hidden;');
    this.items = this.juggler.childElements();
    this.container.setStyle('overflow: hidden; position: relative;');
    this.params.set('itemsCount', this.items.size());
    this.getItemSize();
    this.items.each(function(el) { el.setStyle('float:left;') });
    if (this.params.get('horizontal')) {
        this.juggler.setStyle('width:' + (this.params.get('itemSize') * this.params.get('itemsCount')) + 'px;');
        this.container.setStyle('width:' + (this.params.get('itemSize') * this.params.get('itemsToShow')) + 'px;');
    } else {
        this.juggler.setStyle('height:' + (this.params.get('itemSize') * this.params.get('itemsCount')) + 'px;');
        this.container.setStyle('height:' + (this.params.get('itemSize') * this.params.get('itemsToShow')) + 'px;');
        if (this.container.style.width == '')
            this.container.setStyle('width:' + (this.itemWidth() * this.params.get('itemsInRow')) + 'px;');
    }
    this.moveSize = this.params.get('itemSize') * this.params.get('itemsToMove');
    this.jugglerSize = this.params.get('itemSize') * Math.ceil(this.params.get('itemsCount') / this.params.get('itemsInRow'))
    this.maxToMove = this.jugglerSize - this.params.get('itemSize') * this.params.get('itemsToShow');
    this.createHandlers();
    $((this._object.widget_id == null ? "" : this._object.widget_id) + 'juggler_nav').insert(this.createNav());
    $((this._object.widget_id == null ? "" : this._object.widget_id) + 'juggler_details').insert(this.createNavDetails());
    this.markActiveNavImage(1);
    this.autoMove(0);
};

Juggler.fn.autoMove = function(delay) {
    var d = (this.params.get('delay') + delay) * 1000
    if(this.params.get('autoMove')) {
	setTimeout(function() {
		this.nextItem();
	    }.bind(this), d);
    }
};

Juggler.fn.addHandlers = function() {
    if(this.get('itemsCount') > this.params.get('itemsToShow')) {
		this.nextBtn.onclick = function() {this.nextItem();return false;}.bind(this);
		this.prevBtn.onclick = function() {this.prevItem();return false;}.bind(this);
    } else {
		this.prevBtn.onclick = function() {return false;};
		this.nextBtn.onclick = function() {return false;};
		this.nextBtn.addClassName('next-inactive');
    }
    this.prevBtn.addClassName('prev-inactive');
};

Juggler.fn.createHandlers = function() {
    this.prevBtn = $(this.params.get('prevId'));
    this.nextBtn = $(this.params.get('nextId'));
    if(!this.prevBtn) {
		this.prevBtn = new Element('a', {'id': (this._object.widget_id == null ? "" : this._object.widget_id)+'prev_btn','href':'#'}).update('&lt;');
    }
    if(!this.nextBtn) {
		this.nextBtn = new Element('a', {'id': (this._object.widget_id == null ? "" : this._object.widget_id)+'next_btn','href':'#'}).update('&gt;');
    }
    this.addHandlers();
};

var f = function(i) {
	alert(i);
}

Juggler.fn.createNav = function() {
    this.mainNav = new Element('ul').setOpacity(0.75);
    var li = new Element('li').update(this.prevBtn);
    this.mainNav.insert(li);
    for (var i = 0; i < this.params.get('itemsMax'); i++) {
        var a = new Element('a', { 'href': '#' }).update(i + 1);

        (function(i, scope) {
            a.onclick = function() {
                scope.rewind(i + 1);
                if ($('juggler_thumbs'))
                    $('juggler_thumbs').update('').hide();
                $$('.view-close-button').invoke('update', '[view detail]');
                return false;
            } .bind(scope);
        })(i, this);

        li = new Element('li').insert(a);
        this.mainNav.insert(li);
    }
    li = new Element('li').update(this.nextBtn);
    this.mainNav.insert(li);
    return this.mainNav;
}

Juggler.fn.createNavDetails = function() {

    this.navDetails = new Element('ul');
    for (var i = 0; i < this.params.get('itemsMax'); i++) {
        var li = new Element('li');
        var alt = this.items[i].down('img').alt;
        if (alt != "") {
            var a = new Element('a', { 'href': '#', 'id': 'view-close-button-' + i.toString(), 'class': 'view-close-button' }).update("[view detail]");

            (function(i, scope) {
                var src = scope.items[i].down('img').src.split('/').last().gsub('back', 'thumb');
                var thumb = new Element('img', { 'src': '/Images/org/' + src });
                a.onclick = function() {
                    if ($('juggler_thumbs'))
                        $('juggler_thumbs').update('').insert(thumb).toggle();
                    var button = $('view-close-button-' + i.toString()); // added
                    if (button.text == '[view detail]') {
                        button.update('[hide detail]');
                    } else {
                        button.update('[view detail]');
                    }
                    return false;
                } .bind(scope);
            })(i, this);

            li.update(alt).insert(a);
        }
        this.navDetails.insert(li);
    }
    return this.navDetails;
}

Juggler.fn.currentPosition = function() {
    return this.params.get('horizontal') ? parseInt(this.juggler.getStyle('left')) : parseInt(this.juggler.getStyle('top'));
};

Juggler.fn.animate = function(directions) {
    new Effect.Move(this.juggler, { x: directions.first(),
        y: directions.last(),
        mode: 'relative',
        transition: Effect.Transitions.sinoidal,
        duration: this.params.get('duration'),
        fps: 50,
        beforeStart: function() {
            $$('.writing-content').each(function(el) {
                el.setStyle({ 'overflowY': 'hidden' });
            });    
        },
        afterFinish: function() {
            $$('.writing-content').each(function(el) {
                el.setStyle({ 'overflowY': 'auto' });
            });
        }
    });
};

Juggler.fn.rewind = function(activeNavImage) {
    if (this.allowMove) {
        this.blockMovement();

        if (typeof (activeNavImage) == "undefined")
            activeNavImage = 1;
        this.activeTab = activeNavImage;

        var scrollValue = -this.currentPosition() - ((activeNavImage - 1) * this.moveSize);
        var directions = this.params.get('horizontal') ? [scrollValue, 0] : [0, scrollValue];

        this.animate(directions);
        this.autoMove(this.params.get('duration'));

        this.nextBtn.removeClassName('next-inactive');
        this.prevBtn.addClassName('prev-inactive');
        this.markActiveNavImage(activeNavImage);

        //DESC
        var list = $$('#'+(this._object.widget_id == null ? "" : this._object.widget_id)+'juggler_description li');
        if (list && list.size() > 0) {
            list.each(function(el) {
                el.removeClassName('active');
            });
            list[this.activeTab - 1].addClassName('active');

        }
    }
};

Juggler.fn.blockMovement = function() {
    this.allowMove = false;
    var d = (this.params.get('duration')) * 1000
    setTimeout(function() {
        this.allowMove = true;
    } .bind(this), d);
   
}

Juggler.fn.markActiveNavImage = function(directionOrNavImageIndex) {
	var currentItem = directionOrNavImageIndex;
	var pos = this.currentPosition();
	if(directionOrNavImageIndex == 'up') {
		currentItem = -Math.round((pos)/this.moveSize) + 2;
	} else if(directionOrNavImageIndex == 'down') {
		currentItem = -Math.round((pos)/this.moveSize);
	}
	if (currentItem < 1 || currentItem > this.params.get('itemsMax'))
		currentItem = 1;
	
	this.mainNav.select('a').each(function(e){
		e.removeClassName('active');
	});
	this.navDetails.select('li').each(function(e){
		e.removeClassName('active');
	});
	
	this.navDetails.select('li')[currentItem-1].addClassName('active');
	this.mainNav.select('a')[currentItem].addClassName('active');
}

Juggler.fn.nextItem = function() {
    if (this.allowMove) {
        this.markActiveNavImage('up');
        var pos = this.currentPosition();
        if (pos > -this.maxToMove) {
            this.blockMovement();
            var scrollValue = (this.maxToMove + pos < this.moveSize) ? (this.maxToMove + pos) : this.moveSize;
            var directions = this.params.get('horizontal') ? [-scrollValue, 0] : [0, -scrollValue];
            this.animate(directions);
            this.autoMove(this.params.get('duration'));
            this.prevBtn.removeClassName('prev-inactive');
            if (pos - this.moveSize <= -this.maxToMove) { this.nextBtn.addClassName('next-inactive'); }

            //DESC
            var list = $$('#'+(this._object.widget_id == null ? "" : this._object.widget_id)+'juggler_description li');
            if (list && list.size() > 0) {
                list.each(function(el) {
                    el.removeClassName('active');
                });
                list[this.activeTab].addClassName('active');
                this.activeTab += 1;
            }
        } else {
            if (this.params.get('autoRewind')) { this.rewind(); }
        }
        if ($('juggler_thumbs'))
            $('juggler_thumbs').update('').hide();
        $$('.view-close-button').invoke('update', '[view detail]');
    }
};

Juggler.fn.prevItem = function() {
    if (this.allowMove) {
        this.blockMovement();
        this.markActiveNavImage('down');

        var pos = this.currentPosition();
        if (pos < 0) {
            var scrollValue = (pos + this.moveSize > 0) ? (-pos) : this.moveSize;
            var directions = this.params.get('horizontal') ? [scrollValue, 0] : [0, scrollValue];

            this.animate(directions);
            this.params.set('autoMove', false);
            this.nextBtn.removeClassName('next-inactive');
            //DESC
            var list = $$('#'+(this._object.widget_id == null ? "" : this._object.widget_id)+'juggler_description li');
            if (list && list.size() > 0) {
                list.each(function(el) {
                    el.removeClassName('active');
                });
                this.activeTab -= 1;
                list[this.activeTab - 1].addClassName('active');
            }
        }
        if (pos + this.moveSize >= 0) { this.prevBtn.addClassName('prev-inactive'); }
        if ($('juggler_thumbs'))
                $('juggler_thumbs').update('').hide();
        $$('.view-close-button').invoke('update', '[view detail]');
    }
};


var GalleryWidget = Class.create({
    defaults: $H({
        awards: ["EMPTY"],
        categories: ["EMPTY"],
        middleschool: false,
        portfolios: true,
        state: "All States",
        type: "x"
    }),
    initialize: function(element, options) {
        this.container = $(element);
        this.params = this.defaults.merge(options);
        this.init();
    },
    works: [],
    student: $H({
        name: "",
        age: "",
        school: "",
        grade: ""
    }),
    isPortfolio: false,
    widgetItemsIds: []
});

GalleryWidget.fn = GalleryWidget.prototype;

GalleryWidget.fn.init = function() {
    var params = this.params.toQueryString();
    var success = this.setGalleryWork.bind(this);
    new Ajax.Request("/ORGGalleries/Widget",
        {
            method: 'post',
            parameters: params,
            onSuccess: success
        }
    );
};

GalleryWidget.fn.setGalleryWork = function(transport) {
    this.works = transport.responseJSON.works;
    this.firstWork = this.works.first();
    this.workType = transport.responseJSON.workType;
    this.isPortfolio = this.works.size() > 1;
    
    this.student.name = transport.responseJSON.studentName;
    this.student.age = transport.responseJSON.studentAge;
    this.student.grade = transport.responseJSON.studentGrade;
    this.student.school = transport.responseJSON.schoolInfo;
    
    if(transport.responseJSON.widgetItemsIds != null) {
        this.widgetItemsIds = transport.responseJSON.widgetItemsIds.split(',');
    }
    this.createWidgetArea();
    if (this.isPortfolio)
        this.createJuggler();
};

GalleryWidget.fn.showWork = function(direction) {
    var id = 0;
    if(direction == 'prev') 
        id = this.prevNextItemIds()[0];
    else
        id = this.prevNextItemIds()[1];
        
    var success = this.setGalleryWork.bind(this);
    new Ajax.Request("/ORGGalleries/ShowWidgetWork/" + id,
        {
            method: 'get',
            onSuccess: success
        }
    );    
};

GalleryWidget.fn.expandWidgetArea = function() {
    this.container.down('.expand_up').toggleClassName('expand_down')
    $$("#" + this.container.id + ' .writing_content').each(function(el) {
        el.toggleClassName('expand');
    });
    this.container.down('.gallery_widget_work_info').toggle();
    this.container.down('.gallery_widget_work_title').toggle();
};

GalleryWidget.fn.createWidgetArea = function() {
    var main_div = new Element('div', { 'class': 'gallery_widget' });
    var content_div = new Element('div', { 'class': 'gallery_widget_content', style: 'width:170px;' });
    var next_btn = new Element('a', { href: '#', 'class': 'gallery_widget_next' }).update('<img alt="next" src="/Images/org/arrow-next.png">');
    var prev_btn = new Element('a', { href: '#', 'class': 'gallery_widget_prev' }).update('<img alt="prev" src="/Images/org/arrow-prev.png">');
    var clear = new Element('div', { style: 'clear:both' });
    var c = new Element('div');

    next_btn.onclick = function() { this.showWork('next'); return false; } .bind(this);
    prev_btn.onclick = function() { this.showWork('prev'); return false; } .bind(this);

    var expand_link = new Element('a', { href: '#', style: 'float:right', 'class': 'expand_up' });
    expand_link.onclick = function() { this.expandWidgetArea(); return false; } .bind(this);

    if (this.isPortfolio) {
        var ul = new Element('ul');
        var type = this.workType;
        this.works.each(function(el) {
            var li = new Element('li', { style: 'width:170px;' })
            if (type == 'a') {
                li.insert(new Element('img', { src: el.workImageUrl, alt: el.workTitle + ", " + el.workCategory }));
            } else {
                var expand_link = new Element('a', { href: '#', style: 'float:right', 'class': 'expand_up' });
                expand_link.onclick = function() { this.expandWidgetArea(); return false; } .bind(this);
                li.insert(new Element('img', { src: '', style: 'display:none;', alt: el.workTitle + ", " + el.workCategory }));
                li.insert(new Element('div', { 'class': 'writing_header', style: 'background-color:rgb(' + el.workColor + ')' }).insert(expand_link).insert(el.workCategory + '<b>' + el.workTitle + '</b>'));
                li.insert(new Element('div', { 'class': 'writing_content', style: "overflow-y:auto;" }).update(el.workBody));
            }
            ul.insert(li);
        }.bind(this));
        this.juggler_content = new Element('div').insert(ul);        
        var info = new Element('div', { 'class': 'gallery_widget_work_info' }).update('<div id="' + this.container.id + 'juggler_nav" class="juggler_nav"></div>');
        //<img class="ico-star24x24" src="/Images/org/ico-star24x24.png" width="24" height="24" alt="Portfolio" />
      
        info.insert(new Element('b').update(this.student.name));
        info.insert('Age: ' + this.student.age + ', Grade: ' + this.student.grade + '<br />');
        info.insert(this.student.school);

        var ul2 = new Element('ul', { 'id': this.container.id + 'juggler_description', 'class': 'juggler_description' });
        var first = true;
        this.works.each(function(el) {
            var li = new Element('li');
            if (first)
                li.addClassName('active');
            li.insert('Teacher: ' + el.teacherName + '<br />');
            li.insert('Regional Affiliate: ' + el.affiliateName + '<br />');
            li.insert(el.workAward + ', ' + el.workYear);
            ul2.insert(li);
            first = false;
        });
        info.insert(ul2);
        content_div.insert('<div id="'+this.container.id+'juggler_details" class="gallery_widget_work_title juggler_details"></div>').insert(this.juggler_content).insert(info);

    } else {
        var title = new Element('div', { 'class': 'gallery_widget_work_title' }).update(this.firstWork.workTitle + ", " + this.firstWork.workCategory);
        var workContent = new Element('div');
        if (this.workType == 'a') {
            workContent.insert(new Element('img', { src: this.firstWork.workImageUrl, alt: this.firstWork.workTitle }));
        } else {
            workContent.insert(new Element('div', { 'class': 'writing_header', style: 'background-color:rgb(' + this.firstWork.workColor + ')' }).insert(expand_link).insert(this.firstWork.workCategory + '<b>' + this.firstWork.workTitle + '</b>'));
            workContent.insert(new Element('div', { 'class': 'writing_content', style: "overflow-y:auto;" }).update(this.firstWork.workBody));
        }
        var info = new Element('div', { 'class': 'gallery_widget_work_info' });
        info.insert(new Element('b').update(this.student.name));
        info.insert('Age: ' + this.student.age + ', Grade: ' + this.student.grade + '<br />');
        info.insert(this.student.school + '<br />');
        info.insert('Teacher: ' + this.firstWork.teacherName + '<br />');
        info.insert('Regional Affiliate: ' + this.firstWork.affiliateName + '<br />');
        info.insert(this.firstWork.workAward + ', ' + this.firstWork.workYear);

        content_div.insert(title).insert(workContent).insert(info);
    }

    main_div.insert(prev_btn).insert(content_div).insert(next_btn).insert(clear);
    this.container.update(main_div);
};

GalleryWidget.fn.createJuggler = function() {
        var count = this.works.size();
        new Juggler(this.juggler_content, { itemsInRow: 1, itemsToMove: 1, itemsToShow: 1, horizontal: true, autoRewind: true, autoMove: false, duration: 1.0, itemSize: 170, itemsMax: count, widget_id: this.container.id });
}

GalleryWidget.fn.prevNextItemIds = function() {
    for (var i = 0; i < this.widgetItemsIds.length; i++) {
        if (this.widgetItemsIds[i] == this.firstWork.widgetItemId) {
            var prevId = 0;
            if (this.widgetItemsIds[i - 1] == null) {
                prevId = this.widgetItemsIds[this.widgetItemsIds.length - 1];
            } else {
                prevId = this.widgetItemsIds[i - 1];
            }
            
            var nextId = 0;
            if (this.widgetItemsIds[i + 1] == null) {
                nextId = this.widgetItemsIds[0];
            } else {
                nextId = this.widgetItemsIds[i + 1];
            }
            return [prevId, nextId];
        }
    }
};
