//$('body, html').hide();

$(function() {
    //$('body, html').show();
    $('body').addClass('hasJS');
    CurrentIssue.init();
    FeaturedCarousel.init(5000); // argument is duration of each slide
	WhatsHot.init(6500); // argument is duration of each headline
	Lightboxes.init();
    PrintThis.init('#print_button');
    ResizeText.init('.article_area');
	EnewsSignup.init();
	AutoReplace.init();
    ExternalLinks.init();
    CommunityPolls.init();
	FadeOutMessages.init(3000, 600); // arguments: delay before fade, duration of fade
	AutoFocus.init();

    $('ul.ingredient_list li:nth-child(odd)').addClass('alt');
    $(".article_body ol.ingredient_list li").wrapInner("<span></span>");
	
	var cf = new CustomFormElements({
            styled: 'styled',
            uniqueClassName: 'customFormElement',
            checkboxHeight: 25,
            radioHeight: 25,
            selectWidth: 161
     });
});

/* ---------------------------------------------------------------------
Cookie Functions
Original Author: Klaus Hartl (stilbuero.de)
Modified by: Anthony T
License: Dual licensed under the MIT and GPL licenses
Documentation: https://github.com/carhartl/jquery-cookie/blob/master/jquery.cookie.js

Create, Read and Erase cookies. No baking knowledge required.
------------------------------------------------------------------------ */

jQuery.cookie = function (key, value, options) {

    // key and value given, set cookie...
    if (arguments.length > 1 && (value === null || typeof value !== "object")) {
        options = jQuery.extend({}, options);

        if (value === null) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? String(value) : encodeURIComponent(String(value)),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

/* ---------------------------------------------------------------------
EnewsSignup
Author: Dan P

Simple validation for enews signup form, appearing on home page
and section pages
------------------------------------------------------------------------ */

var EnewsSignup = {
	myForm: undefined,
	myField: undefined,
	init: function() {
		var self = this;
		if ($('#enews_email').length !== 0) {
			self.myForm = $('#form_enews');
			self.myField = $('#enews_email');
			self.bind();
		}
	},
	bind: function() {
		var self = this;
		self.myForm.find('button[type=submit]').live("click",
			function(e) {
				return self.validateForm();
			}
		);
	},
	validateForm: function() {
		var self = this;
		if (self.myField.val() === '' || self.myField.val() === 'Your Email Address' || !Utils.validateEmail(self.myField.val())) {
			if (self.myForm.find('p.error').length === 0) {
				self.myForm.append('<p class="error">Please input a valid email address.</p>');
			}
			return false;
		} else {
			return true;
		}
	}
};

/* ---------------------------------------------------------------------
CurrentIssue
Author: Dan P

Controls the showing and hiding of the current issue global header
element. Binds to any anchor tags within the "#current_issue_callout"
global header element.
------------------------------------------------------------------------ */

var CurrentIssue = {
    content: undefined,
    expandedHeight: undefined,
    opened: undefined,
    init: function() {
        if ($('#current_issue').length !== 0) {
            var self = this;
            self.content = $('#current_issue').prependTo('#page_wrapper').show();
            self.opened = false;
            self.expandedHeight = self.content.outerHeight();
            //IE8 breaks if height not explicitly set on element, IE7 breaks if it is.
            //IE8 also apparently needs them both to be set in the same statement,
            // which is why we're not just setting the margin first
            if ($.browser.msie && $.browser.version == 8) {
                // If IE8, add top-margin AND height values
                self.content.css({'margin-top': -self.expandedHeight, 'height': self.content.height()});
            } else {
                // All other browsers only need the top-margin
                self.content.css('margin-top', -self.expandedHeight);
            }
            self.bind();
        }
    },
    bind: function() {
        var self = this;
        $('#current_issue_callout a, #current_issue .icon.close').live("click",
            function(e) {
                e.preventDefault();
                if (!self.opened) {
                    self.opened = true;
                    self.animations.showIssue();
                } else {
                    self.opened = false;
                    self.animations.hideIssue();
                }
            }
        );
    },
    animations: {
        showIssue: function() {
            var self = CurrentIssue;
            self.content.stop().animate({ 'margin-top': 0 }, 1100, 'easeInOutQuint',
                function() {
                    //animation finished callback
                }
            );
        },
        hideIssue: function() {
            var self = CurrentIssue;
            self.content.stop().animate({ 'margin-top': -self.expandedHeight }, 1100, 'easeInOutQuint',
                function() {
                    //animation finished callback
                }
            );
        }
    }
};

/* ---------------------------------------------------------------------
FeaturedCarousel
Author: Dan P

Animations and interactions for the featured carousel elements,
the image gallery detail page and the relish kids page
------------------------------------------------------------------------ */

var FeaturedCarousel = {
    carousel: undefined,
    slides: undefined,
    pagination: undefined,
    isTabbed: false,
	isGallery: false,
	galleryControls: undefined,
    currentItem: 1,
    items: 0,
    interval: undefined,
	height: 0,
    timer: undefined,
    
    init: function(timeout) {
        if ($('#featured_content').not('.noplay').length !== 0) {
            var self = this;
            
            // Assign values to object properties
            self.carousel = $('#featured_content').addClass('active');
            self.slides = $('<div class="slides"></div>').prependTo(self.carousel);
            self.pagination = $('<ul class="carousel_pagination"></ul>').appendTo(self.carousel);
            self.interval = timeout;
            self.isTabbed = self.carousel.hasClass('tabbed');
            self.isGallery = self.carousel.hasClass('gallery');
			self.galleryControls = $('<div class="controls"></div>');
			self.isGallery ? self.carousel.after(self.galleryControls) : self.galleryControls = undefined;
            
            // Set up carousel pagination and other DOM manipulation
            self.carousel.find('.article').each(
                function() {
                    var me = $(this);
					var height = me.height();
					
					if (height > self.height) {
						self.height = height;
						self.carousel.css('height', self.height);
					}
					
                    self.items++;
                    self.pagination.append('<li><a href="#" class="slide_' + self.items + '"><span>' + me.find('a.category').text() + '</span></a></li>');
                    self.slides.append(me.addClass('slide_' + self.items));
                    
                    if (self.isTabbed) {
                        me.find('.article_excerpt p:last-child').append(me.find('a.more'));
                        me.find('.article_footer').remove();
                        self.pagination.find('.slide_' + self.items + ' span').prepend(self.items + ". ");
                    }
					
					if (self.isGallery) {
						me.find('.caption').appendTo(me.find('.thumbnail'));
					}
                    
                }
            );
            
			// Pagination/controls for each type of carousel on site
            if (!self.isTabbed && !self.isGallery) {
                self.pagination.prepend('<li><a class="prev" href="#">Previous</a></li>');
                self.pagination.append('<li><a class="next" href="#">Next</a></li>');
                self.pagination.find('a.prev').parent().next().find('a').addClass('active');
            }
			
			if (self.isTabbed || self.isGallery) {
                self.pagination.find('li:first-child a').addClass('active');
                self.pagination.find('li:last-child a').addClass('last');
            }
			
			if (self.isGallery) {
				self.galleryControls.append(self.pagination);
				self.galleryControls.prepend($('.gallery_player a.category'));
				self.galleryControls.append('<ul class="prev_next"><li><a class="prev" href="#">&laquo; Prev</a></li><li>&nbsp;|&nbsp;</li><li><a class="next" href="#">Next &raquo;</a></li></ul>');
			}
            
            // Hide each slide other than the first one
            self.slides.find('.article').not(':first-child').css('opacity', 0);
            self.slides.find('.article:first-child').addClass('current');
			
			//Truncate Headline if necessary
			self.slides.find('.article').each(
				function() {
					var headline = $(this).find('.article_header h3');
                    var link = headline.find('a').attr('href');

					var words = headline.text();
					var space = words.length;
                    var fullText;
					headline.text(".");
					var tHeight = parseInt(headline.innerHeight(), 10);
					headline.text(words);
					var cHeight = parseInt(headline.innerHeight(), 10);
					while (cHeight > tHeight) {
						space = words.lastIndexOf(" ");
						words = words.substring(0, space);
						words += "&hellip;";
						headline.html(words);
						cHeight = parseInt(headline.height(), 10);
					}
                    headline.html('<a href="'+link+'">'+words+'</a>');
					
				}
			);
            
            // Initialization complete, bind events if more than one slide
			// otherwise, hide controls
			self.items > 1 ? self.bind() : self.disablePagination();
        }
    },
    
    bind: function() {
        var self = this;
        
        // Pagination links click events
        self.pagination.find('a').not('.prev, .next').click(
            function(e) {
                e.preventDefault();
                var me = $(this);
                var myId = parseInt(me.attr('class').replace('slide_', ''), 10);
                
                if (myId === self.currentItem) {
                    return false;
                }
                
                self.showSlide(myId);
            }
        );
        
        // "Previous" pagination link click event
        self.pagination.find('a.prev').click(
            function(e) {
                e.preventDefault();
                self.previousSlide();
            }
        );
        
        // "Next" pagination link click event
        self.pagination.find('a.next').click(
            function(e) {
                e.preventDefault();
                self.nextSlide();
            }
        );
        
        // Carousel hover event
        self.carousel.hover(
            function() {
                self.pauseSlideShow();
            },
            function() {
                self.startSlideShow();
            }
        );
		
		if (self.isGallery) {        
			// "Next" gallery pagination link click event
			self.galleryControls.find('.prev_next .next').click(
				function(e) {
					e.preventDefault();
					self.nextSlide();
				}
			);
			// "Previous" gallery pagination link click event
		   self.galleryControls.find('.prev_next .prev').click(
				function(e) {
					e.preventDefault();
					self.previousSlide();
				}
			);
			
			// Gallery controls hover event
			self.galleryControls.hover(
				function() {
					self.pauseSlideShow();
				},
				function() {
					self.startSlideShow();
				}
			);
		}
        
        // Bindings are set, begin slideshow
        self.startSlideShow();
    },
    
    startSlideShow: function() {
        var self = this;
        self.timer = setInterval(self.nextSlide, self.interval);
    },
    
    nextSlide: function() {
        var self = FeaturedCarousel;
        self.currentItem === self.items ? self.showSlide(1) : self.showSlide(self.currentItem + 1);
    },
    
    previousSlide: function() {
        var self = this;
        self.currentItem === 1 ? self.showSlide(self.items) : self.showSlide(self.currentItem - 1);
    },
    
    showSlide: function(id) {
        var self = this;
        self.currentItem = id;
        var next = self.slides.find('.slide_' + id).css('opacity', 0);
		var current = self.slides.find('.current');
		self.slides.find('.article').not(next, current).removeClass('last_slide');
        current.addClass('last_slide').removeClass('current');
        next.addClass('current').removeClass('last_slide').stop(true, true).animate({ opacity: 1}, 500, 'linear',
            function() {
				//
            }
        );
        self.pagination.find('.active').removeClass('active');
        self.pagination.find('.slide_' + id).addClass('active');
    },
    
    pauseSlideShow: function() {
        var self = this;
        clearInterval(self.timer);
    },
	
	disablePagination: function() {
		var self = this;
		self.isGallery ? self.galleryControls.hide() : self.pagination.hide();
	}
};

/* ---------------------------------------------------------------------
Print This Page Link
Author: Anthony T

Gives print functionality to print links.
------------------------------------------------------------------------ */

var PrintThis = {
    init: function(button) {
        var self = this;
        self.button = button;
        self.bind();
    },
    bind: function() {
        var self = this;
        // set the click event
        $(self.button).live("click",
            function() {
                self.addIframe();
                $('#print_view').load(function() {
                    self.printIframe();
                }); 
            }
        );

    },
    addIframe: function() {
        var self = this;
        var pageToLoad = location.href;
        pageToLoad = pageToLoad.split("~page=")
        pageToLoad = pageToLoad[0]+"/~page=all";
        $('body').append('<iframe name="print_view" id="print_view" style="visibility: hidden; position: absolute; top: 0; left: 0;"></iframe>');
        window.frames['print_view'].location.href = pageToLoad;
    },
    printIframe: function() { 
        window.frames['print_view'].focus();
        window.frames['print_view'].print();
    }

};

/* ---------------------------------------------------------------------
Text Resizing
Author: Anthony T
Modified by: Dan P

Create HTML for text resizing (for JS users only)
Change text size on click
Persist text size across article pages
------------------------------------------------------------------------ */

var ResizeText = {
    init: function(resizeTarget) {
        var self = this;
                
        // Check for a cookie value - if there isn't one set it to standard.
        if (!($.cookie('textSize'))) {
            $.cookie('textSize','large', { path: '/' });
        }
        
        // Assign values to object properties
        self.currentSize = $.cookie('textSize');
        self.resizeTarget = resizeTarget;
        
        // set the resizeTarget class property with the cookie value
        $(self.resizeTarget).addClass(self.currentSize)
		        
        // Initialization complete, bind events
        self.bind();
    },
    bind: function() {
        var self = this;
        
        // set the click event
        $('#resize_button a').live("click",
            function() {
                self.textAction = $(this).attr('class');
				var target = $(self.resizeTarget);

				target.hasClass('standard') ? self.currentSize = 'standard' :
				target.hasClass('large') ? self.currentSize = 'large' :
				target.hasClass('huge') ? self.currentSize = 'huge' :
				self.currentSize = 'large';

                self.resizeText(self.textAction);
            }
        );
    },
    resizeText: function(textAction) {
       var self = this;
       var target = $(self.resizeTarget);
       // create an expression for the switch cases
       self.textExpression = textAction + '-' + self.currentSize;
       
       switch (self.textExpression) {
            case (self.textExpression = 'reduce-standard'):
                self.setCookieValue('standard');
                break;
            case (self.textExpression = 'enlarge-standard'):
				target.removeClass('standard').addClass('large');
                self.setCookieValue('large');
                break;
            case (self.textExpression = 'reduce-large'):
				target.removeClass('large').addClass('standard');
                self.setCookieValue('standard');
                break;
            case (self.textExpression = 'enlarge-large'):
				target.removeClass('large').addClass('huge');
                self.setCookieValue('huge');
                break;
            case (self.textExpression = 'reduce-huge'):
				target.removeClass('huge').addClass('large');
                self.setCookieValue('large');
                break;
            case (self.textExpression = 'enlarge-huge'):
                self.setCookieValue('huge');
                break;
        }
       
    },
	setCookieValue: function (newCookieValue) {
        // set the new cookie value
        $.cookie('textSize',newCookieValue, { path: '/' });
    }
};

/* ---------------------------------------------------------------------
Lightboxes
Author: Dan P

Requires following markup:

<a href="#lightbox_id" class="spawn_lightbox">Will Spawn Lightbox</a>

<div id="lightbox_id" class="lightbox">Lightbox Content Here</div>

The 'id' attribute of the lightbox is used in the href attribute
of the spawning link. Be sure to include hashmark.
------------------------------------------------------------------------ */

var Lightboxes = {
    init: function() {
        if ($('.lightbox').length !== 0) {
            
			var lightbox = $('.lightbox');

            lightbox.each(
                function() {
                    var me = $(this);
                    me.html('<a href="#" class="close">Cancel</a><div class="lightbox_outer"><div class="lightbox_inner">' + me.html() + '</div></div>');
                }
            );
			
			var overlay = $('<div id="overlay"></div>');
			overlay.appendTo('body');
			overlay.hide().after(lightbox);
			lightbox.hide();
			this.bind();
        }
    },
	
    bind: function() {
        $('.lightbox .close').live('click', function(e) {
            if ($.browser.msie && $.browser.version <= 8) {
                $(this).parents('.lightbox').hide();
                $('#overlay').hide();
            } else {
                $(this).parents('.lightbox').fadeOut(400);
                $('#overlay').fadeOut(400);
            }
            e.preventDefault();
        });

        $('.spawn_lightbox').live('click', function(e) {
            var lightbox_id = $(this).attr('href');
            var lightbox = $(lightbox_id);
            Lightboxes.showLightbox(lightbox);
            e.preventDefault();
        });
    },

    showLightbox: function(lightbox) {
        var leftOffset = Math.round(lightbox.outerWidth()/2);
        var topOffset = Math.round(lightbox.outerHeight()/2);
		lightbox.css({ 'margin-left': -leftOffset, 'margin-top': -topOffset });
        if ($.browser.msie && $.browser.version <= 8) {
            lightbox.show();
            $('#overlay').show();
        } else {
            lightbox.fadeIn(400);
            $('#overlay').fadeIn(400);
        }
    }
};

/* ---------------------------------------------------------------------
Utils
Author: Dan P

Various utility functions
------------------------------------------------------------------------ */

var Utils = {
	validateEmail: function(email) {
		var reg = /^([A-Za-z0-9_\-\.\+])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		return reg.test(email);
	}
};

/* ---------------------------------------------------------------------
AutoReplace
Author: Dan P

uses the value attribute on elements with the class "auto_replace" to
auto show/hide field tips

additionally, if button is a search submit button, check that it has been
changed from default text before submitting form
------------------------------------------------------------------------ */

var AutoReplace = {
	init: function() {
		if ($('.auto_replace').length !== 0) {
			this.bind();
		}
	},
	bind: function() {
		$('.auto_replace').each(
			function() {
				var me = $(this);
				var defaultText = me.val();
				me.focus(
					function() {
						if (me.val() === defaultText) {
							me.val('');
						} 
					}
				);
				me.blur(
					function() {
						if (me.val() === '') {
							me.val(defaultText);
						}
					}
				);
				
				if (me.parents('#global_search, #form_recipe_search').length !== 0) {
					var searchForm = me.parents('#global_search, #form_recipe_search');
					searchForm.submit(
						function(e) {
							if (me.val() === defaultText || me.val() === '') {
								//return false;
							}
						}
					)
				}
			}
		);
	}
};

/* ---------------------------------------------------------------------
WhatsHot
Author: Dan P

controls the "what's hot" headline rotator
------------------------------------------------------------------------ */

var WhatsHot = {
	container: undefined,
	interval: undefined,
	timer: undefined,
	init: function(timeout) {
		if ($('#whats_hot').length !== 0) {
			var self = WhatsHot;
			self.container = $('#whats_hot');
			self.container.find('li:first-child').addClass('active');
			self.interval = timeout;
			//only continue if there is more than 1 item
			var items = self.container.find('li').length;
			if (items > 1 && items !== 0) {
				self.bind();
			}
		}
	},
	
	bind: function() {
		var self = WhatsHot;
		self.container.hover(
			function() {
				self.pauseRotator();
			},
			function() {
				self.startRotator();
			}
		);
		self.startRotator();
	},
	
	startRotator: function() {
		var self = WhatsHot;
		self.timer = setInterval(self.nextHeadline, self.interval);
	},
	
	pauseRotator: function() {
		clearInterval(this.timer);
	},
	
	nextHeadline: function() {
		var self = WhatsHot;
		var current = self.container.find('li.active');
		var next = current.next('li').length === 0 ? self.container.find('li:first-child') : current.next();
		current.fadeOut('fast').removeClass('active');
		next.fadeIn('fast').addClass('active');
	}
};

/* ---------------------------------------------------------------------
ExternalLinks
Author: Dan P

Launches links with a rel="external" in a new window
------------------------------------------------------------------------ */

var ExternalLinks = {
	init: function() {
		$('a[rel=external]').attr('target', '_blank');
	}
};


/* ---------------------------------------------------------------------
CommunityPolls
Author: Colin Fein
------------------------------------------------------------------------ */

var CommunityPolls = {
	init: function() {
        $('#content .poll-toggle-results').live('click', function(e){
            var parent = $(this).parents('.community_poll:first');
            parent.find('.poll-question-container, .poll-results-container').toggle();
            return false;
        });
	}
};

/* ---------------------------------------------------------------------
FadeOutMessages
Author: Dan P

Causes ajax messages to fade out after set amount of time
------------------------------------------------------------------------ */

var FadeOutMessages = {
	duration: undefined,
	init: function(delay, duration) {
		var self = this;
		self.duration = duration;
		if ($('.fade_out').length !== 0) {
			setTimeout(self.fadeItems, delay);
		}
	},
	fadeItems: function() {
		var self = this;
		$('.fade_out').fadeTo(self.duration, 0);
	}
};

/* ---------------------------------------------------------------------
AutoFocus
Author: Dan P

Focuses first input with .auto_focus class on page load
------------------------------------------------------------------------ */

var AutoFocus = {
	init: function() {
		$('input.auto_focus').eq(0).focus();
	}
};


/*
$('.pagination.category a').live("click", function() {
	var url = $(this).attr('href');

    parts = url.split('/');
    
    for(i = 0; i <= parts.length; i++)
    {
        if(parts[i] == "")
        {
            delete parts[i];
        }
    }
    // You would think it would be length-1 
    last_segment = parts[parts.length-2];

    // We don't have a pagination link, so stop here
    if(last_segment.substr(0, 1) != 'P')
        return;

	$.ajax({  
		type: "POST",
		url:  ctx.search_url + dataString + '&start=' + page,  
		cache: false,
		dataType: "html",
		beforeSend: function() {
			
			$('.pagination').hide();
			$('#page_loading').show();
		},
		complete: function() {
			$('#page_loading').hide();
			$('pagination').show();
		},
		success: function(data) {
			var $response=$(data);
			var result = $response.find('#recipe_results');
			$('#recipe_results').replaceWith(result);    
		}
	});
	return false;
});
*/


