/*

Author - RAG

First Javascript Project Ever :P
Based Goodgallery by Ryan Rampersad

*/
var Gallery = new Class({
	
	buttonsWeb:null,
	buttonsMotion:null,
    container: null,
    inner: null,
	overlay:null,
	currentRel:null,
	currentTarget:null,
	currentLink:null,
	currentWidth:null,
	currentHeight:null,
	projectInfo:null,
	projectName:null,
    animate: null,
    nav: null,
    data: null,
    timer: null,
    ticks: 0,
	firstTime:true,

    options: {
        width: 1105,
        height: 342,
        delay: 5100,
        duration: 1500,
        transition: Fx.Transitions.Sine.easeInOut,
        structure: {
            header: "h3",
            data: ".gallery-data",
            link: "p a",
            img: "img",
			buttonContainer: ".buttonOut"
        },
        data: null
    },

    Implements: [Options],
	
	
	
    initialize: function (container, buttonsWeb, buttonsMotion, options) {
		
        this.setOptions(options);
		this.buttonsWeb = document.id(buttonsWeb);
		this.buttonsMotion = document.id(buttonsMotion);
        this.container = document.id(container);
		this.projectName = document.id("projectName");
		this.overlay = document.id("overlay");
		this.projectName = document.id("projectInfo");
        this.parseData();
        this.setup();
		
    },

    parseData: function () {

        var data = [];
        if (this.options.data == null) {
			
			var info = $(document.body).getElements("div.projectNameElement").each(function (el, i) {
				$("projectName").grab(el);	
			},
            this);
			
			var role = $(document.body).getElements("div.projectInfoElement").each(function (el, i) {
				$("projectInfo").grab(el);	
			},
            this);

			
            this.container.getElements(this.options.structure.data).each(function (el, i) {
                var slide = {},
                link = el.getElement(this.options.structure.link),
                img = el.getElement(this.options.structure.img);
                slide.title = el.getElement(this.options.structure.header).get("text");
                slide.desc = link.get("text");
                slide.url = link.get("href");
				slide.target= link.get("target");
                slide.img = img.get("src");
                slide.alt = img.get("title");
				slide.type = el.getElement(this.options.structure.buttonContainer).get("name");
                slide.rel = link.get("rel");
				slide.width=link.get("width");
				slide.height=link.get("height");
				slide.button = el.getElement(this.options.structure.buttonContainer).get("src");
				slide.buttonwidth = el.getElement(this.options.structure.buttonContainer).get("width");
                slide.index = i;
                data.push(slide); // Because I don't trust data[] = slide; in js.
            },
            this);
        }

        this.data = data;
		
        this.container.empty();

    },

    setup: function () {

        /*
			I didn't want to make this a String method so I'll make my own private method.
			elementize: return an element based on a string.
		*/
        function elementize(string) {
            return new Element("div", {
                html: string
            }).getFirst();
        }
		$('overlay').set("opacity","0.01");
		
        // Set the container's width, add class
        this.container.setStyle("width", this.options.width).addClass("gallery");

        // Make an inner container, set width and height.
        this.inner = new Element("div", {
            "class": "gallery-inner",
            "styles": {
                "width": this.options.width,
                "height": this.options.height
            }
        });
		
		this.navWeb = new Element("ul", {
            "class": "gallery-nav"
        });
		
		this.navMotion = new Element("ul", {
            "class": "gallery-nav"
        });
		
		
        this.buttonsWeb.grab(this.navWeb);
		this.buttonsMotion.grab(this.navMotion);
		
        // Container grabs inner. 
        this.container.grab(this.inner);
		// Make the under-slide navigation bar.
        
        // Make the animate div.
        this.animate = new Element("div", {
            "class": "gallery-animate",
            "styles": {
                "width": this.options.width
            }
        }).set("tween", {
            duration: this.options.duration,
            transition: this.options.transition
        });
		
        // Inner Container grabs this one.
        this.inner.grab(this.animate);

        // Get the link elements in the container.
        var slides = this.data;

        /*
			So we know how much space to allot.
		*/
        this.animate.setStyle("width", this.options.width * slides.length);
	
		
		$('overlay').addEvents({
    		'mouseover': function(){
				this.tween("opacity","1");
   		 },
  		  	'mouseout': function(){
				this.tween("opacity","0.01");
 		 },
		  
  		  	'click': function(){
				
				var link=this.getElements("a.overlayLink");
				
				switch(currentRel){
					case "video":
						Shadowbox.open({
							content:   currentLink,
							player:     "swf",
							width:		currentWidth,
							height:		currentHeight
						});
						link.setProperties({href:"#",target:"_self"});
					break;
					case "image":
					break;
					case "nofollow":
						link.setProperties({
						href:currentLink,
						rel:currentRel,
						target:currentTarget	
						});
					break;
					case "imageGallery":
					var arr = currentLink.split(",");
					var finalArr=[];
					arr.each(function (el, i) {
						 var img = {
							player:     'img',
							content:    el
						 }; 
						 finalArr.include(img);
					},
					this);
					
						Shadowbox.open(finalArr,{});
						link.setProperties({href:"#",target:"_self"});
					break;
					default:
						Shadowbox.open({
							content:   currentLink,
							player:     "iframe",
							width:		"1600",
							height:		"800"
						});
						link.setProperties({href:"#",target:"_self"});
						/*
						link.setProperties({
						href:currentLink,
						rel:currentRel,
						target:currentTarget	
						});
						*/
					break;	
					
				}
 		 }
		});

        // Make the separate blocks here.
        slides.each(function (data, i) {
            var biglink_data = {
                img: data.img,
                height: this.options.height,
                width: this.options.width,
                desc: data.desc
            },
            biglink = ('<a class="gallery-item" href="{url}"><img src="{img}" height="{height}" width="{width}" border="0" /><span class="gallery-item-info"><strong><span> </span></strong><br /></span></a>').substitute(biglink_data);
            biglink = elementize(biglink);

            biglink.setStyle("width", this.options.width).set("rel", data.rel);

            this.animate.grab(biglink);

            //======
            // Again, using substitue.
            var nav_data = {
                link: data.url,
                title: data.title,
				button:data.button,
				buttonwidth:data.buttonwidth,
				type:data.type
            },

			nav = ('<li name="nav"><div id="gallery-link" name="over" style="cursor:pointer;width:{buttonwidth}px;height:20px;background-image:url({button}_over.png);"></div><div id="gallery-link"  name="out" style="margin-top:-20px;cursor:pointer;width:{buttonwidth}px;height:20px;background-image:url({button}_out.png);"></div></li>').substitute(nav_data);
            nav = elementize(nav);

            nav.store("data", data).getFirst().set("rel", data.rel);

            // By default, first block is selected.
            if (i === 0) {
				firstTime=false;
                nav.addClass("selected");
				currentTarget=data.target;
				currentLink=data.url;
				currentRel=data.rel;
				currentWidth=data.width;
				currentHeight=data.height;
            }
            // Notice the stupid links.length-1? Arrays index from 0 even in foreach!
            // Last class takes off the borders and other things.
            if (i === (slides.length - 1)) {
                nav.addClass("last");
            }

            // Add the mouseenter/leave events.
            nav.addEvents({
                "mousedown": this.events.down.bind(this),
                "mouseleave": this.events.out.bind(this),
				"mouseover": this.events.over.bind(this)
            });
			
			
            // Let the nav grab the element.
			//this.navWeb.grab(nav)
           nav_data.type=="interactive" ? this.navWeb.grab(nav) : this.navMotion.grab(nav);

        },
        this); // This links.each loop is bound to _THIS_.
		
	
		 
        this.tick(); // Start it up.
    },

    /*
		The recuring function that triggers the slides to move.
			Removes selected class
			Adds selected class to whatever needs it
			Runs the tween
	*/
    tick: function () {

        // Get the links in nav.
        //var links = this.navWeb.getElements("li");
		var links = $(document.body).getElements("div[name=out]");
        // selected is on one of them, so take it off, then add it back.
        links.removeClass("selected").each(function (el, i) {
			var myFx = new Fx.Tween(el);
			
            if (this.ticks === i) {
				
                el.addClass("selected");
				el.fade('out');
            }else{
				el.fade('in');
			}
		
        },
        this);
			
			hideAbout();
			// Slide now.
       		this.slide();
        	// Increment.
       		this.ticks++; 
    },

    events: {
        down: function (event) {
            // Mouseenter: when they move over the block.
            var data = event.target.getParent().retrieve("data", {
                index: 0
            });
			currentTarget=data.target;
			currentLink=data.url;
			currentRel=data.rel;
			currentWidth=data.width;
			currentHeight=data.height;
            // Set tick to the current block.
            this.ticks = data.index;
            this.tick();
        },
        out: function (event) {
			 var data = event.target.getParent().retrieve("data", {
                index: 0
            });
            var me = event.target.getParent().getElements("div[name=out]");
			var you = event.target.getParent().getElements("div[name=over]");
			me.set('tween', {duration: 'normal'});
			you.set('tween', {duration: 'normal'});
			if(data.index!=this.ticks-1){
				me.fade('in');
				//you.fade('out');
			}
        },
		over: function (event) {
 			var me = event.target.getParent().getElements("div[name=out]");
			var you = event.target.getParent().getElements("div[name=over]");
			me.set('tween', {duration: '300'});
			you.set('tween', {duration: '300'});
			me.fade('out');
			//you.fade('in');
        }
    },

    slide: function () {
        // This animates the slides
        this.animate.tween("left", 0 - (this.ticks * this.options.width));
		
		
		//animate name fadeout-change place-fadein
		var changeName = new Fx.Tween($("projectName"), {link:"chain",duration:"500"});
		changeName.start("opacity",0);
		changeName.start("margin-top", this.ticks *-27);
		changeName.start("opacity",1);
		
		var changeInfo = new Fx.Tween($("projectInfo"), {link:"chain",duration:"500"});
		changeInfo.start("opacity",0);
		changeInfo.start("margin-top", this.ticks *-16);
		changeInfo.start("opacity",1);
		
		//projectName.tween('margin-top', this.ticks *-27);
		//projectInfo.tween('margin-top', this.ticks *-16);
    }

});
