var $J = jQuery.noConflict();
var $C = Class.$noConflict();

/*** main application ***/

var App = $C.$extend({
	__init__ : function(){

		this.siteAdminBar = false;
		this.carosels = false;
		this.slideshows = false;
		this.categoryPage = false;
		this.categoryPicker = false;
		this.productPicker = false;
		this.addToCartForm = false;
        this.socialMediaModule = false;
        this.homeFeaturedProduct = false;
        this.shareModule = false;
        this.moreInfoModule = false;
        this.ourStory = false;
        this.faqPage = false;
        this.newsModule = false;

	},

	init: function(){

		// site admin bar (singleton)
		if($J('#siteAdminBar').length > 0) {
			this.siteAdminBar = new SiteAdminBar();
			this.siteAdminBar.init();
		}

		// carosels
		if($J('.carosel').length > 0) {
			this.carosels = new Array();
			$J('.carosel').each(function(index){
				BBL.carosels.push(new Carosel($J(this), index));
			});
			var i = 0;
			var len = this.carosels.length;
			for(i;i<len;i++){
				this.carosels[i].init();
			}
		}

		//slideshows
		if($J('.slideshow').length > 0) {
			this.slideshows = new Array();
			$J('.slideshow').each(function(index){
				BBL.slideshows.push(new Slideshow($J(this), index));
			});
			var i = 0;
			var len = this.slideshows.length;
			for(i;i<len;i++){
				this.slideshows[i].init();
			}
		}

		// category picker, product picker, product glamour image & add to cart form (all singletons) - cross-dependent
		// cat & prod pickers alter hidden fields in add to cart form and update UI off of those fields
		// NOTE: carosel functionality in cat picker & prod picker handled by Carosel class
		if($J('body.catalog-category-view').length > 0) {
			this.categoryPage = new CategoryPage();
			this.categoryPicker = new CategoryPicker();
			this.productPicker = new ProductPicker();
			this.addToCartForm = new AddToCartForm();
			this.productGlamour = new ProductGlamour();
			this.addToCartForm.init(); // init this before the rest!
			this.categoryPicker.init();
			this.productPicker.init();
			this.productGlamour.init();
			this.categoryPage.init();

		}

		// news & social module
		if($J('.news-social-module, .facebook-updates-module').length > 0) {
            this.socialMediaModule = new SocialMediaModule();
            this.socialMediaModule.init();
        }

		// homepage featured product
		//if($J('#homeFeaturedProduct').length > 0) {
		//	this.homeFeaturedProduct = new HomeFeaturedProduct();
		//	this.homeFeaturedProduct.init();
		//}

		// share module (cat / product page)
		if($J('#shareModule').length > 0) {
			this.shareModule = new ShareModule();
			this.shareModule.init();
		};

		if($J('.more-information-module').length > 0) {
			this.moreInfoModule = new MoreInfoModule();
			this.moreInfoModule.init();
		}

        if($J('.media-view-switcher').length > 0)
        {
            this.newsModule = new NewsModule();
            this.newsModule.init();
        }
        
        // our story page
        if($J('.our-story').length > 0) {
        	this.ourStory = new OurStory();
        	this.ourStory.init($J('.our-story'));
        }
        
        // faq page
        if($J('.faq-page').length > 0) {
        	this.faqPage = new FAQPage();
        	this.faqPage.init($J('.faq-page'));
        }
        
        // main nav
        $J('.nav-products-link').click(function(e){
        	e.preventDefault();
        	document.location = '/all-products';
        });
	}

});


/*** site admin bar - links at far upper right of all pages ***/

var SiteAdminBar = $C.$extend({
	__init__ : function(){
		this.el = false; // main wrapping element - use for dom scope
		this.cartLink = false;
		this.flyout = false;

		this.cartCloseTimer = -1;
	},

	init: function(){
		this.el = $J('#siteAdminBar');
		this.cartLink = $J('.cart', this.el);
		this.cartFlyout = $J('.block-cart', this.el);

		this.cartLink.mouseenter(function(){
			BBL.siteAdminBar.cartLinkEnter();
		});
		this.cartLink.mouseleave(function(){
			BBL.siteAdminBar.cartLinkLeave();
		});

		this.cartFlyout.mouseenter(function(){
			BBL.siteAdminBar.cartLinkEnter();
		});
		this.cartFlyout.mouseleave(function(){
			BBL.siteAdminBar.cartLinkLeave();
		});
	},

	cartLinkEnter: function() {
		this.stopCartCloseTimer();
		this.cartFlyout.show();
	},

	cartLinkLeave: function(){
		this.startCartCloseTimer();
	},

	startCartCloseTimer: function(){
		this.cartCloseTimer = setTimeout('BBL.siteAdminBar.closeCartFlyout()', 1000);
	},

	stopCartCloseTimer: function(){
		clearTimeout(this.cartCloseTimer);
	},

	closeCartFlyout: function() {
		this.cartFlyout.hide();
	}

});


var Carosel = $C.$extend({
	__init__ : function(el, index){
		this.el = el; // main wrapping element - use for dom scope
		this.masterIndex = index; //index in app.carosels collection
		this.prevBtn = false;
		this.nextBtn = false;

		this.slidesMask = false;
		this.slidesWrap = false;
		this.slides = false;
		this.slideIndex = false;
		this.maxSlide = false;


	},

	init: function(){
		//console.log('carosel '+this.masterIndex+' init');

		this.prevBtn = $J('.cntl-prev', this.el);
		this.nextBtn = $J('.cntl-next', this.el);
		this.slidesMask = $J('.slides-mask', this.el);


		this.slidesWrap = $J('.slides', this.el);
		this.setSlides();

		this.prevBtn.click({'owner':this}, function(e){
			e.preventDefault();
			var owner = e.data.owner;
			owner.slideTo(-1);
		});

		this.nextBtn.click({'owner':this}, function(e){
			e.preventDefault();
			var owner = e.data.owner;
			owner.slideTo(1);
		});


	},

	slideTo: function(dir){
		//console.log('slideTo: '+dir);
		var next = this.slideIndex + dir;
		if(next < 0) {
			next = this.maxSlide;
		} else if(next > this.maxSlide) {
			next = 0;
		}
		var newLeft = -($J(this.slides[next]).position().left);
		this.slidesWrap.stop(true,true).animate({'left':newLeft}, 'fast');
		this.slideIndex = next;
	},

	setSlides: function(){
		//console.log('setSlides');
		this.slides = $J('.slide', this.el);
		this.slideIndex = 0;

		// set slide wrap width to accomodate all slides
		var wrapWidth = 0;
		var i = 0;
		var len = this.slides.length;
		for(i;i<len;i++){
			wrapWidth += $J(this.slides[i]).width();
		}
		this.slidesWrap.css({ 'width':wrapWidth+'px', 'left':'0px' });

		// determine maxSlide - highest visual slide index carosel should slide to
		var maxSlidePx = (wrapWidth - this.slidesMask.width() > 0) ? wrapWidth - this.slidesMask.width() : 0;
		i = 0;
		for(i;i<len;i++){
			//console.log('slide '+i+' left: '+$J(this.slides[i]).position().left+' maskWidth: '+this.slidesMaskWidth+' maxSlidePx: '+maxSlidePx+ ' tMax: '+tMax );
			if($J(this.slides[i]).position().left < (maxSlidePx + $J(this.slides[i]).width())) {
				this.maxSlide = i;
			} else {
				i = len; // exit
			}
		}
		//console.log('maxSlide: '+this.maxSlide);

		// add or remove centered class based on number of products
		this.el.removeClass('carosel-centered');
		this.slidesMask.css({'width':'','left':''});
		if(wrapWidth <= this.slidesMask.width()) {
			this.el.addClass('carosel-centered');
			//this.el.addClass('carosel-centered-'+len);
			var left = (this.el.width() - wrapWidth) / 2;
			this.slidesMask.css({'width':wrapWidth+'px','left':left+'px'});
		}


	}

});


var Slideshow = $C.$extend({
	__init__ : function(el, index){
		this.el = el; // main wrapping element - use for dom scope
		this.masterIndex = index; //index in app.slideshows collection

		this.slides = false;
		this.slidedots = false;
		this.glamImgEl = false; // the big div whose BG changes per slide 
		
		this.playTimeout = false; // setInterval assignee
		this.playDuration = 8000; // ms for setInterval
		
		this.lastSlide = 0;
		this.nextSlide = 0;

	},

	init: function(){
		//console.log('slideshow '+this.masterIndex+' init');
		this.slides = $J('.slide', this.el);
		this.slidedots = $J('.slidedot', this.el);
		this.glamImgEl = $J('.cms-home .col-left');
		
		var i = 0;
		var len = this.slidedots.length;
		for(i;i<len;i++){

			$J('a', $(this.slidedots[i]) ).click({'owner':this,'index':i}, function(e){
				e.preventDefault();
				e.data.owner.pause();
				e.data.owner.slideTo(e.data.index);
			});
		}
		
		$J('.modal-launch-link', this.el).each(function(){
			$J(this).click(function(e){
				e.preventDefault();
				BBL.slideshows[0].pause();
				var options = {
						'opacity' : .8,
						'overlayClose' : true,
						'minWidth' : '656',
						'minHeight' : '200'
					};
				var modalID = $J(this).attr('rel');
				$J('.'+modalID).modal(options);
				$J('#simplemodal-container').css('height', 'auto');
			});
		});

        $J('a', $(this.slidedots[0]) ).click();
        
        this.playTimeout = setTimeout('BBL.slideshows['+this.masterIndex+'].play()', this.playDuration);

	},

	slideTo: function(index) {
		this.nextSlide = index;
		$J(this.glamImgEl).fadeTo(800,0, function(){
			BBL.slideshows[0].slideToStep2();
		});
	},
	
	slideToStep2: function() {

		this.slides.each(function(){
			$J(this).removeClass('slide-sel');
		});
		this.slidedots.each(function(){
			$J(this).removeClass('slidedot-sel');
		});
		
		var bgsrc = $J(this.slides[this.nextSlide]).attr('rel');
        
        this.glamImgEl.css('background-image', 'url('+bgsrc+')');
		
		$J(this.slides[this.nextSlide]).addClass('slide-sel');
		$J(this.slidedots[this.nextSlide]).addClass('slidedot-sel');
		
		$J(this.glamImgEl).fadeTo(800,1);
		
		this.lastSlide = this.nextSlide;
	},
	
	play: function() {
		var next = ( this.lastSlide+1 > this.slides.length-1 ) ? 0 : this.lastSlide+1;
		this.slideTo(next);
		this.playTimeout = setTimeout('BBL.slideshows['+this.masterIndex+'].play()', this.playDuration);
	},
	
	pause: function() {
		clearTimeout(this.playTimeout);
	}

});

/* currently only controls toggling site-page classnames when products are selected */
var CategoryPage = $C.$extend({
	__init__ : function(){
		this.el = false; // main wrapping element - use for dom scope
		this.category = false;
		this.product = false;
	},

	init: function(){
		this.el = $J('body.catalog-category-view .site-page');
		// check initial URL for cat/product data and update display if extant

		// add listener for updating URL based on cat / product selection
		BBL.addToCartForm.prodField.change({'owner':this}, function(e){
			//console.log('catPicker: catField change '+e.data.cid);
			e.data.owner.updateWrapClass();
		});
	},
	updateWrapClass: function(cid) {		
		this.category = BBL.addToCartForm.catField.val();
		var className = 'site-page category-'+BobbleCategories.getCatById(this.category).slug;
		this.el.attr('class', className);
	}
});


var CategoryPicker = $C.$extend({
	__init__ : function(){
		this.el = false; // main wrapping element - use for dom scope
		this.catWraps = false;
		this.catLinks = false;

	},

	init: function(){
		//console.log('category picker init');
		this.el = $J('.category-picker');
		this.catWraps = $J('.item', this.el);
		this.catLinks = $J('.cat-link', this.el);

		var i = 0;
		var len = this.catLinks.length;
		for(i; i<len; i++){
			$J(this.catLinks[i]).click({'cid':$J(this.catLinks[i]).attr('rel')},function(e){
				e.preventDefault();
				//e.data.owner.selectCat(e.data.pid, e.data.index);
				BBL.addToCartForm.updateCategory(e.data.cid);
			});
		}

		// add listener to change of addToCart category hidden field
		BBL.addToCartForm.catField.change({'owner':this}, function(e){
			//console.log('catPicker: catField change');
			e.data.owner.selectCat($J(e.target).val());
		});

	},

	selectCat: function(cid) {
		//console.log('cid: '+cid);
		var t;
		this.catWraps.each(function(){
			t = $J(this);
			t.removeClass('item-sel');
		});
		$J('#cat_'+cid).addClass('item-sel');
	}

});

//NOTE: cat/prod json established in global scope as "BobbleCategories"
var ProductPicker = $C.$extend({
	__init__ : function(){
		this.el = false; // main wrapping element - use for dom scope
		this.carosel = false;
		this.slidesWrap = false;
		this.slidesTmpl = false;
		this.caroselClass = false; // pointer to carosel class that corresponds to this picker
	},

	init: function(){
		//console.log('product picker init');
		this.el = $J('.product-picker');

		/* find the carosel class that corresponds to this picker's carosel */
		var cid = $J('.carosel', this.el).attr('id');
		var i = 0;
		var len = BBL.carosels.length;
		for(i;i<len;i++) {
			if($J(BBL.carosels[i].el).attr('id') == cid) {
				this.caroselClass = BBL.carosels[i];
			}
		}

		this.carosel = $J('.carosel', this.el);
		this.slidesWrap = $J('#productSlidesWrap');
		this.slidesTmpl = $J('#productCaroselSlideTmpl');


		BBL.productPicker.wireThumbs();

		// add listener to change of addToCart category & product hidden fields
		BBL.addToCartForm.catField.change({'owner':this}, function(e){
			//console.log('prodPicker: catField change');
			e.data.owner.switchCarosel($J(e.target).val());
		});
		BBL.addToCartForm.prodField.change({'owner':this},function(e){
			//console.log('prodPicker: prodField change');
			e.data.owner.switchProduct($J(e.target).val());
		});

	},

	// wires clicks on individual products
	wireThumbs: function(){
		$J('.slide', this.el).each(function(){
			$J(this).click({'pid':$J(this).attr('rel')},function(e){
				e.preventDefault();
				BBL.addToCartForm.updateProduct(e.data.pid);
			});;
		});
	},

	switchCarosel: function(id){
		//console.log('prodPicker switchCarosel: '+id);

		var catData = BobbleCategories.getCatById(id);

		this.slidesWrap.html('');
		this.slidesTmpl.tmpl(catData.products).appendTo(this.slidesWrap);

		// change selection to first product in new carosel
		var first = $J('.slide', this.el)[0];
		if(first) {
			$J(first).addClass('slide-sel');
			BBL.addToCartForm.updateProduct(catData.products[0].id);
		}

		this.wireThumbs();
		this.caroselClass.setSlides();

	},

	switchProduct: function(id){
		//console.log('prodPicker selectProduct: '+id);
		$J('.slide-sel', this.el).removeClass('slide-sel');
		$J('#prod_'+id).addClass('slide-sel');

	}

});


var ProductGlamour = $C.$extend({
	__init__ : function(){
		this.el = false; // main wrapping element - use for dom scope
		this.glamImg = false;
		this.nextImg = false;
	},

	init: function(){
		this.el = $J('.product-glamour-image');
		this.glamImg = $J('#productGlamourImg');

		// add listener to change of addToCart product hidden field
		BBL.addToCartForm.prodField.change({'owner':this},function(e){
			e.data.owner.switchImage($J(e.target).val());
		});

		// load listener on img handles fading in new imgs after they load
		this.glamImg.load(function(){
			BBL.productGlamour.imageLoaded();
		});
	},

	switchImage: function(id) {
		var product = BobbleCategories.getProdById(id);
		this.nextImg = product.basesrc;
		this.glamImg.fadeTo('fast', 0, function(){
			$(BBL.productGlamour.glamImg).attr('src', BBL.productGlamour.nextImg);
		});
	},

	imageLoaded: function() {
		this.glamImg.fadeTo('fast', 1);
	}

});


var AddToCartForm = $C.$extend({
	__init__ : function(){
		this.el = false; // main wrapping element - use for dom scope
		this.catField = false;
		this.prodField = false;
		this.qtyField = false;

	},

	init: function(){
		this.el = $J('.add-to-cart-form');
		this.catField = $J('#categoryId');
		this.prodField = $J('#productId');
		this.prodNameField = $J('#productName');
		this.prodUrlField = $J('#productUrl');
		this.qtyField = $J('#qty');

		//TODO: test this... not sure its working
		this.qtyField.change(function(){
			var val = $J(this).val();
			if(parseInt(val) < 1) {
				$J(this).val('1');
			}
		});
	},

	// change selected category storage to provided id and broadcast change event
	updateCategory: function(id) {
		//console.log('addToCart updateCategory: '+id);
		if(id != this.catField.val()) {
			this.catField.val(id);
			this.catField.change(); // broadcast change event
		}
	},

	// change selected product storage to provided id and broadcast change event
	updateProduct: function(id) {
		//console.log('addToCart updateProduct: '+id);
		if(id != this.prodField.val()) {
			this.prodField.val(id);
			var tProd = BobbleCategories.getProdById(id);
			this.prodNameField.val(tProd.name);
			this.prodUrlField.val(tProd.url);
			this.prodField.change(); // broadcast change event
		}
	}

});

var SocialMediaModule = $C.$extend({
	__init__ : function(){
		this.twitterContainer = false; // main wrapping element - use for dom scope
		this.facebookContainer = false;
        this.twitterLink = false;
        this.facebookLink = false;
        this.twitterItemTemplate = false;
        this.fbItemTemplate = false;
		this.apiURL = "/genomeengine/API/content";

	},

	init: function(){
		this.twitterContainer = $J('.news-social-module .latestTweet');
		this.facebookContainer = $J('.news-social-module .latestFB');
        this.twitterLink = $J('.news-social-module .latestTweetURL');
        this.facebookLink = $J('.news-social-module .latestFBURL');
        if(this.twitterContainer.length > 0)
        {
            this.getLatestTweet();
            this.getLatestFBPost();
        }
        else
        {
            this.twitterContainer = $J('.twitter-updates-module');
            this.facebookContainer = $J('.facebook-updates-module');
            this.fbItemTemplate = $J("#facebookItemTmpl");
            this.twitterItemTemplate = $J('#twitterItemTmpl');
            this.getLatestTweets(4);
            this.getLatestFBPosts(4);


        }
	},


    getLatestTweet: function()
    {
        var container = this.twitterContainer;
        var link = this.twitterLink;
        $J.ajax({
          url: this.apiURL+"?limit=1&type_include=twitter",
          success: function(response)
            {
                if(response && response.data.length > 0)
                {
                    var data = response.data[0];
                    data['date'] = timeConverter(data['date']);
                    container.html(data.date + "<br/> "+data.title+" <a href='"+data.url+"'>Link &gt;</a>");
                    link.attr("href","http://twitter.com/#!/waterbobble");
                }
                else
                {
                    container.html("Error getting data from Twitter");
                }
            },
          dataType: 'json'
        });

    },
    getLatestFBPost: function()
    {
        var container = this.facebookContainer;
        var link = this.facebookLink;
        $J.ajax({
          url: this.apiURL+"?limit=1&type_include=facebookpost",
          success: function(response)
            {
                if(response && response.data.length > 0)
                {
                    var data = response.data[0];
                    data['date'] = timeConverter(data['date']);
                    container.html(data.date + "<br/>bobble "+data.title+" <a href='"+data.url+"'>Link &gt;</a>");
                    link.attr("href","http://www.facebook.com/Bobble?sk=wall");
                }
                else
                {
                    container.html("Error getting data from Facebook");
                }
            },
          dataType: 'json'
        });

    },
    getLatestTweets: function(limit)
    {
        var container = this.twitterContainer;
        var itemTmpl = this.twitterItemTemplate;

        $J.ajax({
          url: this.apiURL+"?limit="+limit+"&type_include=twitter",
          success: function(response)
            {
                if(response && response.data.length > 0)
                {
                    for(var i = 0; i<response.data.length; i++)
                    {
                        var data = response.data[i];

                        data['date'] = timeConverter(data['date']);
                        itemTmpl.tmpl(data).appendTo(container);

                    }
                }
                else
                {
                    itemTmpl.tmpl([{title:"Error getting data from Twitter"}]).appendTo(container);
                }
            },
          dataType: 'json'
        });

    },
    getLatestFBPosts: function(limit)
    {
        var container = this.facebookContainer;
        var itemTmpl = this.fbItemTemplate;

        $J.ajax({
          url: this.apiURL+"?limit="+limit+"&type_include=facebookpost",
          success: function(response)
            {
                if(response && response.data.length > 0)
                {
                    for(var i = 0; i<response.data.length; i++)
                    {
                        var data = response.data[i];

                        data['date'] = timeConverter(data['date']);
                        itemTmpl.tmpl(data).appendTo(container);

                    }
                }
                else
                {
                    itemTmpl.tmpl([{title:"Error getting data from Facebook."}]).appendTo(container);
                }
            },
          dataType: 'json'
        });

    }


});


var HomeFeaturedProduct = $C.$extend({
	__init__ : function(){
		this.el = false; // main wrapping element - use for dom scope
		this.glamImgEl = false; // element whose background becomes big product image
	},

	init: function(){
		this.el = $J('#homeFeaturedProduct');
		this.glamImgEl = $J('.cms-home .col-left');
		var bgsrc = $J('.slideshow .slide-sel').attr('rel');
		this.glamImgEl.css('background-image', 'url('+bgsrc+')');
	}

});

var ShareModule = $C.$extend({
	__init__ : function(){
		this.el = false; // main wrapping element - use for dom scope
		this.FBlink = false;
		this.TWTlink = false;
		this.shareUrl = false;
		this.shareTitle = false;
	},

	init: function(){
		this.el = $J('#shareModule');
		this.FBlink = $J('#shareToFBLink');
		this.TWTlink = $J('#shareToTWTLink');

		// if add to cart form also on page, add listener for auto-updating links on product change
		if(BBL.addToCartForm != false) {
			BBL.addToCartForm.prodField.change({'owner':this}, function(e){
				e.data.owner.setData( BBL.addToCartForm.prodUrlField.val(), BBL.addToCartForm.prodNameField.val() );
			});
		}
	},

	setData: function(url, title) {
		this.shareUrl = encodeURI(url);
		this.shareTitle = encodeURI(title);
		this.updateLinks();
	},

	updateLinks: function() {
		this.FBlink.attr('href','http://www.facebook.com/sharer.php?u='+this.shareUrl+'&t='+this.shareTitle);
		this.TWTlink.attr('href', 'http://twitter.com/share?url='+this.shareUrl);
	}

});


var MoreInfoModule = $C.$extend({
	__init__ : function(){
		this.el = false; // main wrapping element - use for dom scope
		this.catContent = false;
		this.prodContent = false;
		this.blockContent = false;
		this.flyout = false;

	},

	init: function(){
		this.el = $J('.more-information-module');
		this.catContent = $J('.cat-content', this.el);
		this.prodContent = $J('.product-content', this.el);
		this.blockContent = $J('.block-content', this.el);
		this.flyout = $J('.flyout', this.el);

		this.wire();
		
		// add listener for category change - replace module content with new cat content
		BBL.addToCartForm.catField.change({'owner':this}, function(e){
			//console.log('catPicker: catField change');
			e.data.owner.changeCat($J(e.target).val());
		});
		
		// add listener for product change - replace module content with new product content
		BBL.addToCartForm.prodField.change({'owner':this}, function(e){
			//console.log('catPicker: prodField change');
			e.data.owner.changeProd($J(e.target).val());
		});
	},
	
	wire: function() {
		$J('.icons a', this.el).each(function(){
			$J(this).click(function(e){
				e.preventDefault();
			});
			$J(this).hover(function(){
				BBL.moreInfoModule.showFlyout(this);
			}, function(){
				BBL.moreInfoModule.hideFlyout();
			});
		});


		$J('.modal-launch-link', this.el).each(function(){
			$J(this).click(function(e){
				e.preventDefault();
				var options = {
						'opacity' : .8,
						'overlayClose' : true,
						'minWidth' : '716px',
						'minHeight' : '400px'
					};
				var modalID = $J(this).attr('rel');
				if(modalID == 'howtouse-modal-jug') {
					options.minHeight = '600px';
				}
				$J('.'+modalID).modal(options);
				$J('#simplemodal-container').css('height', 'auto');
			});
		});
	},

	showFlyout: function(el){
		this.flyout.html($J(el).attr('rel'));
		this.flyout.show();
	},

	hideFlyout: function(){
		this.flyout.hide();
	},
	
	changeCat: function(id){
		this.catContent.html(BobbleCategories.getCatById(id).description);
		this.blockContent.html(BobbleCategories.getCatById(id).moreInfo);
		this.wire(); // rewire for modals & flyouts
	},
	
	changeProd: function(id){
		this.prodContent.html(BobbleCategories.getProdById(id).desc);
	}
	
	
});

var NewsModule = $C.$extend({
	__init__ : function(){
        this.newsDisplay = false;
        this.socialDisplay = false;
        this.switchLink = false;
        this.showNewsText = "";
        this.showSocialMediaText = "";
        this.currentlyDisplayed = "";
        this.apiURL = "/genomeengine/API/content";
        this.socialPostsContainer = false;
        this.fbItemTemplate = false;
        this.twitterItemTemplate = false;
    },

    init: function(){
        this.newsDisplay = $J(".news-list-module");
        this.socialDisplay = $J(".social-media-list-module");
        //this.socialDisplay.hide();

        this.socialPostsContainer = this.socialDisplay.find(".posts-container");

        this.fbItemTemplate = $J("#fullFacebookItemTmpl");
        this.twitterItemTemplate = $J('#fullTwitterItemTmpl');

        this.currentlyDisplayed = "news";
        this.switchLink = $J(".media-view-switcher a");
        this.showSocialMediaText = this.switchLink.text();
        this.showNewsText = this.switchLink.attr("rel");
        var that = this;
        this.switchLink.click(function(e){
            e.preventDefault();

            if($J('body').toggleClass('news-social-view'));

            if(that.currentlyDisplayed == "news")
            {
                that.currentlyDisplayed = "social";
                that.switchLink.text(that.showNewsText);
                that.getLatestSocialMediaPosts();
            }
            else
            {
                that.currentlyDisplayed = "news";
                that.switchLink.text(that.showSocialMediaText);

            }

            $J(document).scrollTop(0);

        });
        
        // if on blog index, switch to news view before anchoring to news item on top stories / latest stories link clicks
        if($J('.blog-index-index').length > 0) {
        	$J('.top-stories-module a').each(function(){
        		$J(this).click(function(e){
        			e.preventDefault();
        			BBL.newsModule.sidebarNewsModuleClick($J(this).attr('href'));
        		});
        	});
        	$J('.news-updates-module a').each(function(){
        		$J(this).click(function(e){
        			e.preventDefault();
        			BBL.newsModule.sidebarNewsModuleClick($J(this).attr('href'));
        		});
        	});
        }

    },
    sidebarNewsModuleClick: function(href) {
		if(this.currentlyDisplayed != 'news'){
			$J('body').toggleClass('news-social-view');
			this.currentlyDisplayed = 'news';
			this.switchLink.text(this.showSocialMediaText);
		}
		document.location = href;
    },
    getLatestSocialMediaPosts: function()
    {
        var container = this.socialPostsContainer;
        var twitterItemTmpl = this.twitterItemTemplate;
        var fbItemTmpl = this.fbItemTemplate;

        $J.ajax({
          url: this.apiURL+"?limit=20&cacheBuster="+Math.random(),
          success: function(response)
            {
                container.empty();
                if(response && response.data.length > 0)
                {
                    for(var i = 0; i<response.data.length; i++)
                    {
                        var data = response.data[i];

                        data['date'] = timeConverter(data['date']);
                        switch(data["content_type"])
                        {
                            case "twitter":
                                twitterItemTmpl.tmpl(data).appendTo(container);
                            break;

                            case "facebookpost":
                                fbItemTmpl.tmpl(data).appendTo(container);
                            break;


                        }
                    }
                }
                else
                {
                    twitterItemTmpl.tmpl([{title:"Error getting data from Social Media API"}]).appendTo(container);
                }
            },
          dataType: 'json'
        });

    }
});

var OurStory = $C.$extend({
	__init__ : function(){
		this.el = false; // main wrapping element - use for dom scope
		this.cartLink = false;
		this.flyout = false;

		this.cartCloseTimer = -1;
	},

	init: function(el){
		this.el = el;
		
		$J('.more-link', this.el).click(function(e){
			e.preventDefault();
			var row = $J(this).parent().parent().parent();
			$J('.intro', row).toggle();
			$J('.more-content', row).toggle();
		});
	}
});

var FAQPage = $C.$extend({
	__init__ : function(){
		this.el = false; // main wrapping element - use for dom scope
		this.sectionLinks = false; // expand section links 

	},

	init: function(el){
		this.el = el;
		this.sectionLinks = $J('.toggler', this.el);

		this.sectionLinks.each(function(e){
			$J(this).click(function(e){
				e.preventDefault();
				var rel = $J(this).attr('rel');
				$J('#faqcnt'+rel, this.el).toggle();
				if($J(this).hasClass('open')) {
					$J(this).removeClass('open');
					if($J(this).hasClass('more-link')) {
						$J(this).html('read more');
					}
				} else {
					$J(this).addClass('open');
					if($J(this).hasClass('more-link')) {
						$J(this).html('read less');
					}
				}
			});

		});
	}
});


/* ==================== application initialization ==================== */

var BBL;

$J(document).ready(function($){
	BBL = new App();
	BBL.init();
});


// utilized on cat / prod pages for json data storage
// in-lined & global for php access to populate data
var BobbleCategories = {
	isTopLevel : false,
	data : false,

	getCatById : function(id){
		var i = 0;
		var len = this.data.length;
		for(i;i<len;i++){
			if(this.data[i].id == id) {
				return this.data[i];
			}
		}
		return false;
	},

	getProdById : function(id){
		var i = 0;
		var len = this.data.length;
		for(i;i<len;i++){
			var c = 0;
			var lenn = this.data[i].products.length;
			for(c;c<lenn;c++){
				if(this.data[i].products[c].id == id) {
					return this.data[i].products[c];
				}
			}
		}
		return false;
	}

};


function timeConverter(UNIX_timestamp){
 var a = new Date(UNIX_timestamp*1000);
 var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
     var year = a.getFullYear();
     var month = months[a.getMonth()];
     var date = a.getDate();
     var hour = a.getHours();
     var min = a.getMinutes();
     var sec = a.getSeconds();
     var time = month+' '+date+' '+year ;
     return time;
 }








