(function($) {
	window.app = {
            init: function() {


                 $('#slideshow_thumbnails_prev, #slideshow_thumbnails_next').css('opacity','0');

                // select the drops

                $('ul#topnav li').each(function(){
                        if( $(this).find('span').length > 0 ) {
                            $(this).addClass('drop');
                        }
                });

                if (window.Touch) {
                    $('ul#topnav > li.drop > a').attr('href', '#');
                }

                if ($.browser.msie && $.browser.version < 7) {
                    $('#topnav > li')
                        .mouseover(function() {
                            $(this).addClass('over');
                        })
                        .mouseout(function() {
                            $('#topnav > li').removeClass('over');
                        })
                    ;
                } else {
                    var $shadow_wrapper = $('#shadow_wrapper');
                    // set original position of each dropdown
                    $(window).resize(function(){ // needs to be in window resize otherwise causes issues with offset on resize
                        $('#topnav ul.topnav_nested_ul').each(function () {
                            var $this = $(this);
                            var $li = $this.closest('li');
                            $this.css({'margin-top': -1 * ($(this).height()+10)});
                            var $ul = $this.closest('.nested_ul_wrapper').css('visibility', 'visible');

                            var $border = $shadow_wrapper.append('<div class="'+$li.attr('id')+' nested_ul_wrapper_border"></div>').find('.'+$this.closest('li').attr('id')+'.nested_ul_wrapper_border');

                            var li_h = $li.height();
                            $ul.css({
                               'margin-top': li_h
                            });

                            var $ul_el = $ul.find('ul');

                            var $ul_el_of = $ul_el.offset();



                            var p_top = 74;
                            var p_left = $ul_el_of.left;
                            $border.css({
                                'width': $ul.width(),
                                'top': p_top,
                                'left': p_left - 1,
                                'position': 'absolute',
                                'z-index': 15,
                                'border': '1px solid #859BD5',
                                'background-color': '#FFF',
                                'margin-top': 0

                            });

                        });
                    }).trigger('resize');



                    $('#topnav > li').hover(function () {
                        // wax on
                        var $this = $(this)
                        var $ul = $this.find('.topnav_nested_ul');
                        var $border = $shadow_wrapper.find('.'+$this.closest('li').attr('id')+'.nested_ul_wrapper_border');
                        var h = $ul.height();
                        // Calling stop() prevents animation buildup
                        $ul.stop().animate({'marginTop': 0}, {
                            step: function () {
                                var hgt = parseInt($ul.css('margin-top'), 10) + h + 8;
                                $border.css({'height': hgt < 0 ? 0 : hgt});
                            },
                            complete: function () {
                                $border.css({'height': h+8});
                            },
                            easing: 'easeInOutQuint',
                            duration: 800
                        });
                    },
                    function () {
                        // wax off
                        var $this = $(this)
                        var $ul = $this.find('.topnav_nested_ul');
                        var $border = $shadow_wrapper.find('.'+$this.closest('li').attr('id')+'.nested_ul_wrapper_border');
                        var h = $ul.height();
                        // Calling stop() prevents animation buildup
                        $ul.stop().animate({'marginTop':  -1 * ($ul.height()+10)}, {
                            step: function () {
                                var hgt = parseInt($ul.css('margin-top'), 10) + h;
                                $border.css({'height': hgt < 0 ? 0 : hgt});
                            },
                            complete: function () {
                                $border.css({'height': 0});
                            },
                            easing: 'easeInOutQuint',
                            duration: 400
                        });
                    });
                }

            },

            resize: {
                /* This function is used to monitor the window
                 * dimensions and redirect to the /l/ version of the site (and vice-versa).
                 */
                init: function() {




                    // thresholds
                    small_size = 980;
                    // Perform initial resize
                    window.app.resize.resize();

                    // Resize upon resize event..
                    $(window).resize(function() {
                        // Perform resize
                    window.app.resize.resize();
                });
            },


            resize: function() {
                /* Perform window resize upon defined threshold */

                // Current window width/height
                window_height = $(window).height();
                window_width = $(window).width();

                console.log(window_width);

                var large_size = 1450;
                var small_size = 1260; // previous value was 980

                var pathname = window.location.pathname.toString();
                var pathname_len = pathname.split('/').length;
                //console.log(pathname_len);


                var proxy_dir = pathname.slice(0,3);

                // needs to be checked if it is the homepage as it uses 3 styles
                if (pathname_len <= 3 && (pathname == '/l/' || pathname == '/s/' || pathname == '/')) {
                //console.log(window_width);
                    // add /l
                    if (window_width > large_size) {
                        if (proxy_dir != '/l/') {
                            redirect_uri = 'http://' + location.host + '/l/';
                            window.location.replace(redirect_uri);
                        }
                    }

                    // remove proxy dir
                    if (window_width > small_size && window_width < large_size) {
                            if (proxy_dir != '/') {
                              redirect_uri = 'http://' + location.host + '/';
                            window.location.replace(redirect_uri);
                            }
                    }

                    // add /s
                    if (window_width < small_size ) {
                        if (proxy_dir != '/s/') {
                            redirect_uri = 'http://' + location.host + '/s/';
                            window.location.replace(redirect_uri);
                        }
                    }
                } else {

                    var pages_width_threshold = 1273;

                    if (window_width < pages_width_threshold) {
                        if (proxy_dir != '/s/') {
                            redirect_uri = 'http://' + location.host + '/s' + pathname;
                            window.location.replace(redirect_uri);
                        }
                    }
                    else {
                        if (proxy_dir == '/s/' || proxy_dir == '/l/') {
                            new_path = pathname.substring(2);
                            redirect_uri = 'http://' + location.host + new_path;
                            window.location.replace(redirect_uri);
                        }
                    }

                }

            }
        },

        media_gallery: {
                    init: function() {
                        if (h.element_exists('#media_gallery_home')) {
                            $('#media_gallery_home .slideshow')
                                .cycle({
                                    fx:         'fade',
                                    speed:      1200,
                                    timeout:    5000,
                                    pause:      0,
                                    before:     function(currSlideElement, nextSlideElement, options) {
                                        $('#slideshow_caption').html($(this).attr('rel'));
                                        $('#media_gallery_home #slideshow_thumbnails li a').removeClass('active');
                                        $('#media_gallery_home #slideshow_thumbnails li a span').stop().hide(0).fadeTo(0, 0);

                                        next_slide_id = $(nextSlideElement).attr('id').split('pg_slide_')[1];
                                        next_slide_thumb_id = '#pg_thumb_' + next_slide_id;
                                        $(next_slide_thumb_id + ' a', '#media_gallery_home #slideshow_thumbnails').addClass('active');
                                        $(next_slide_thumb_id + ' a span', '#media_gallery_home #slideshow_thumbnails').show(0).fadeTo(200, 0.92);

                                        next_slide_thumb_container = $(next_slide_thumb_id + ' a span').closest('ul').attr('rel');
                                        if (false && next_slide_thumb_container) {
                                           // $('#media_gallery_home #slideshow_thumbnails').cycle(parseInt(next_slide_thumb_container));
                                        }
                                    }
                                });

                            $('#media_gallery_home #slideshow_thumbnails a')
                                .click(function () {
                                    //$(this).fadeTo(0, 1);
                                    $('#media_gallery_home .slideshow').cycle('pause');
                                    if ($(this).attr('rel')) {
                                        $('#media_gallery_home .slideshow').cycle(parseInt($(this).attr('rel')));
                                    }
                                    return false;
                                })
                                .mouseover(function () {
                                    //if ($(this).hasClass('active')) {
                                    //    $(this).fadeTo(0, 0.7);
                                    //} else {
                                    //    $(this).fadeTo(100, 1);
                                    //}
                                })
                                .mouseout(function () {
                                   // $(this).fadeTo(250, 0.7);
                                })
                            ;

                            $('#media_gallery_home #slideshow_thumbnails').cycle({
                                fx:      'scrollHorz',
                                speed:    2000,
                                timeout:  1000
                            });
                            $('#media_gallery_home #slideshow_thumbnails').cycle('pause');
                            $('#media_gallery_home #slideshow_thumbnails_prev a').click(function () {
                                $('#media_gallery_home .slideshow').cycle('pause');
                                $('#media_gallery_home #slideshow_thumbnails').cycle('prev');
                                return false;
                            });
                            $('#media_gallery_home #slideshow_thumbnails_next a').click(function () {
                                $('#media_gallery_home .slideshow').cycle('pause');
                                $('#media_gallery_home #slideshow_thumbnails').cycle('next');
                                return false;
                            });

                            $('#slideshow_thumbnails_container').hover(function(event){
                                event.stopPropagation();
                                $('.prev_next_disabled #slideshow_thumbnails_prev, .prev_next_disabled #slideshow_thumbnails_next').stop().animate({'opacity':0.8});
                            }, function() {
                                $('.prev_next_disabled #slideshow_thumbnails_prev, .prev_next_disabled #slideshow_thumbnails_next').stop().animate({'opacity':0});
                            });
                        }
                    }
                },




         media_gallery_1: {
                init: function() {
                    if (h.element_exists('#media_gallery_1')) {
                        $('#media_gallery_1 .slideshow')
                            .cycle({
                                fx:         'fade',
                                speed:      1200,
                                timeout:    5000,
                                pause:      0,
                                next:   '#slideshow_thumbnails_next a',
                                prev:   '#slideshow_thumbnails_prev a',
                                before:     function(currSlideElement, nextSlideElement, options) {
                                    $('#slideshow_caption').html($(this).attr('rel'));
                                    $('#media_gallery_1 #slideshow_thumbnails_1 li a').removeClass('active');
                                    $('#media_gallery_1 #slideshow_thumbnails_1 li a span').stop().hide(0).fadeTo(0, 0);

                                    next_slide_id = $(nextSlideElement).attr('id').split('pg_slide_')[1];
                                    next_slide_thumb_id = '#pg_thumb_' + next_slide_id;
                                    $(next_slide_thumb_id + ' a', '#media_gallery_1 #slideshow_thumbnails').addClass('active');
                                    $(next_slide_thumb_id + ' a span', '#media_gallery_1 #slideshow_thumbnails').show(0).fadeTo(200, 0.92);

                                    next_slide_thumb_container = $(next_slide_thumb_id + ' a span').closest('ul').attr('rel');
                                    if (next_slide_thumb_container) {
                                        //$('#media_gallery_1 #slideshow_thumbnails').cycle(parseInt(next_slide_thumb_container));
                                    }
                                }
                            });

                        $('#media_gallery_1 #slideshow_thumbnails_1 a')
                            .click(function () {
                                $('html, body').animate({ scrollTop: $("#mainContent").offset().top }, 500);
                                $(this).fadeTo(0, 1);
                                $('#media_gallery_1 .slideshow').cycle('pause');
                                if ($(this).attr('rel')) {
                                    $('#media_gallery_1 .slideshow').cycle(parseInt($(this).attr('rel')));
                                }
                                return false;
                            })
                            .mouseover(function () {
                                if ($(this).hasClass('active')) {
                                    $(this).fadeTo(0, 1);
                                } else {
                                    $(this).fadeTo(100, 0.7);
                                }
                            })
                            .mouseout(function () {
                                $(this).fadeTo(250, 1);
                            })
                        ;

                        // Stop the slideshow when they start playing with the media
                        $(window).blur(function(event) {
                          $('#media_gallery_1 .slideshow').cycle('pause');
                        });

                        $('div#media_gallery_1').hover(function(event){
                            event.stopPropagation();
                            $('#slideshow_thumbnails_prev, #slideshow_thumbnails_next').stop().animate({'opacity':0.7});
                        }, function() {
                            $('#slideshow_thumbnails_prev, #slideshow_thumbnails_next').stop().animate({'opacity':0});
                        });

                        /*
                        $('#media_gallery_1 #slideshow_thumbnails_1').cycle({
                            fx:      'scrollHorz',
                            speed:    500,
                            timeout:  1000
                        });
                        /* */
                        //$('#media_gallery_1 #slideshow_thumbnails_1').cycle('pause');
                        /* $('#media_gallery_1 #slideshow_thumbnails_prev a').click(function () {
                            $('#media_gallery_1 .slideshow').cycle('pause');
                            //$('#media_gallery_1 #slideshow_thumbnails').cycle('prev');
                            return false;
                        });
                        $('#media_gallery_1 #slideshow_thumbnails_next a').click(function () {
                            $('#media_gallery_1 .slideshow').cycle('pause');
                            //$('#media_gallery_1 #slideshow_thumbnails').cycle('next');
                            return false;
                        }); */
                    }
                }
            },


	    quicksearch: {

	        init: function() {

                    // slideshow functionality

                    var hover_count = 0;

                    //$('div#thumbnails_mask').hover(function(){

                    //});

                    $('div#thumbnails_mask').hover(
                        function(){
                            hover_count++;
                            if (hover_count == 1){
                                console.log(hover_count);
                                $('div#slideshow_thumbnails').stop(true, true).animate({'top': '-=63px'}, 'fast');
                            }
                        },
                        function(){
                            hover_count--;
                            if (hover_count == 0){
                                console.log(hover_count);
                                $('div#slideshow_thumbnails').stop(true, true).animate({'top': '+=63px'}, 'fast');
                            }
                    });
                }

            },



		quiz: {
			init: function() {
				$('.quiz .button a').click(function() {
					var this_quiz_id = $(this).closest('.quiz').attr('id');
					var answers = [];
					var loopcount = 0;
					$('.quiz .item').each(function() {
						loopcount ++;
						var v = $('input.q[name=q-' + loopcount + ']:checked').val();
						answers[answers.length] = v;
					});
					var url = '/custom/quiz';
					var params = {
						'quiz_id': this_quiz_id,
						'answers': answers.join(',')
					}
					$.ajax({
					  url: url,
					  type: "POST",
					  data: (params),
					  success: function(msg){
						 h.alert(msg);
					  }
				   });

				   return false;
				});
			}
		},
		vote: {
		    init: function() {
		    	$('#already_submitted').each(function() {
		    		var expired = 0
		    		if ($('#vote_expired').val() == '1') {
		    			var expired = 1
		    		}
		    		var url = '/custom/vote';
					var params = {
						vote_id: $('#vote_id').val(),
						vote: 0,
						expired: expired
					   }
					$.ajax({
					  url: url,
					  type: "POST",
					  data: (params),
					  success: function(msg){
						  $('#vote_form_container').hide();
						  $('#vote_results_container .results').html(msg);
						  $('#vote_results_container').show();
					  }
					});
		    	});
		        $('#vote_now_btn').click(function() {
		            // get radio button value
		            var v = $('#vote_form #chooseButton').val();
		            if (!v) {
		                h.alert("To vote, click one of the 'tick' symbols to the left of each line, then click 'Vote now'.");
		            } else {
    					var url = '/custom/vote';
    					var params = {
    						vote_id: $('#vote_id').val(),
    						vote: v
    					   }
    					$.ajax({
    					  url: url,
    					  type: "POST",
    					  data: (params),
    					  success: function(msg){
    					      $('#vote_form_container').hide();
    					      $('#vote_results_container .results').html(msg);
    					      $('#vote_results_container').show();
    					  }
    				    });
		            }
		        });
		    }

		},
		slideshow: {
			init: function() {
                                if (h.element_exists('#slideshow')) {
                                    $('#slideshow').cycle({
                                            fx:      'fade',
                                            speed:    1200,
                                            timeout:  7000,
                                            next:   '#slideshow',
                                            pause:   0
                                    });
                                    $('#slideshow.paused')
                                            .each(function () {
                                                    pausePlay();
                                            })
                                    ;
                                }
                        }
		},
		panels: {
			init: function() {
                            if (h.element_exists('#panels')) {
				function setNav() {
					$('#panelsNav td').removeClass('active');
					$('#' + this.id + '_button')
						.addClass('active')
					;
				}
				var starting_slide = $('#panels').attr('title');
                                    $('#panels')
                                            .cycle({
                                                    fx:      'scrollLeft',
                                                    speed:    600,
                                                    timeout:  0,
                                                    before: setNav,
                                                    startingSlide: parseInt(starting_slide)
                                            })
                                    ;
                                    $('#panels').removeAttr('title');
                                }
			}
		},
		slidingLinks: {
			init: function() {
				$('#links .item:first h2 a')
					.each(function () {
						$(this).addClass('active');
						$('#' + this.id + '_container').slideDown(0);
					})
				;
				$('#links .item h2 a')
					.each(function () {
						if ($(this).hasClass('active')) {
							$('#links .item .description').slideUp(0);
							$(this).addClass('active');
							$('#' + this.id + '_container').slideDown(0);
						} else {
							$('#' + this.id + '_container').hide();
						}
					})
					.click(function () {
						$('#links .item h2 a').removeClass('active');
						$(this).addClass('active');
						$('#links .item .description').slideUp(500);
						$('#' + this.id + '_container').slideDown(1000);
						return false;
					})
				;
			}
		},
		jfontsizer: {
			init: function(o) {
				// Cookie functions
				function setCookie(c_name,value,expiredays){
				var exdate=new Date();
				exdate.setDate(exdate.getDate()+expiredays);
				document.cookie=c_name+ "=" +escape(value)+
				((expiredays==null) ? "" : ";expires="+exdate.toGMTString())+";path=/";
				}
				function getCookie(c_name){
				if (document.cookie.length>0){
				  c_start=document.cookie.indexOf(c_name + "=");
				  if (c_start!=-1){
					c_start=c_start + c_name.length+1;
					c_end=document.cookie.indexOf(";",c_start);
					if (c_end==-1) c_end=document.cookie.length;
					return unescape(document.cookie.substring(c_start,c_end));
					}
				  }
				return "";
				}
				// Defaults
				var o = jQuery.extend( {
					applyTo: '#wrapper',
					changesmall: '1',
					changelarge: '2',
					expire: 90
				},o);
				var s = '';
				var m = '';
				var l = '';
				// Current
				var c = 'font_sml';
				// Check cookie
				if (getCookie('font_size') != "") {
					var c = getCookie('font_size');
					switch (c) {
						case 'font_sml':
							$('#fontSizer .icons a#font_sml').addClass('active');
						$(o.applyTo).css('font-size','1em');
							break;
						case 'font_med':
							$('#fontSizer .icons a#font_med').addClass('active');
						$(o.applyTo).css('font-size','1.'+o.changesmall+'em');
							break;
						case 'font_lrg':
							$('#fontSizer .icons a#font_lrg').addClass('active');
						$(o.applyTo).css('font-size','1.'+o.changelarge+'em');
							break;
					}
				}
				else {
					$('#fontSizer .icons a#font_sml').addClass('active');
				}
				$('#fontSizer .icons a').click(function(){
					var t = $(this).attr('id');
					setCookie('font_size',t,o.expire);
					$('#fontSizer .icons a').removeClass('active');
					$(this).addClass('active');
					var f = $(o.applyTo).css('font-size');
					switch(t){
						case 'font_sml':
							$(o.applyTo).css('font-size','1em');
							break;
						case 'font_med':
							$(o.applyTo).css('font-size','1.'+o.changesmall+'em');
							break;
						case 'font_lrg':
							$(o.applyTo).css('font-size','1.'+o.changelarge+'em');
							break;
					}
					return false;
				});
			}
		},
		styleSwitch: {
			init: function(o) {
				// Cookie functions
				function setCookie(c_name,value,expiredays){
				var exdate=new Date();
				exdate.setDate(exdate.getDate()+expiredays);
				document.cookie=c_name+ "=" +escape(value)+
				((expiredays==null) ? "" : ";expires="+exdate.toGMTString())+";path=/";
				}
				function getCookie(c_name){
				if (document.cookie.length>0){
				  c_start=document.cookie.indexOf(c_name + "=");
				  if (c_start!=-1){
					c_start=c_start + c_name.length+1;
					c_end=document.cookie.indexOf(";",c_start);
					if (c_end==-1) c_end=document.cookie.length;
					return unescape(document.cookie.substring(c_start,c_end));
					}
				  }
				return "";
				}
				// Defaults
				var o = jQuery.extend( {
					applyTo: 'body',
					changesmall: '1',
					changelarge: '2',
					expire: 90
				},o);
				var s = '';
				var m = '';
				var l = '';
				// Current
				var c = 'theme1';
				// Check cookie
				if (getCookie('contrast') != "") {
					var c = getCookie('contrast');
					switch (c) {
						case 'theme1':
							$('#contrast .icons a#font_sml').addClass('active');
						$(o.applyTo).addClass('');
							break;
						case 'theme2':
							$('#contrast .icons a#font_med').addClass('active');
						$(o.applyTo).addClass('siteTheme2');
							break;
						case 'theme3':
							$('#contrast .icons a#font_lrg').addClass('active');
						$(o.applyTo).addClass('siteTheme3');
							break;
					}
				}
				else {
					$('#contrast .icons a#theme1').addClass('active');
				}
				$('#contrast .icons a').click(function(){
					var t = $(this).attr('id');
					setCookie('contrast',t,o.expire);
					$('#contrast .icons a').removeClass('active');
					$(this).addClass('active');
					var f = $(o.applyTo).css('font-size');
					switch(t){
						case 'theme1':
							$(o.applyTo).removeClass('siteTheme2');
							$(o.applyTo).removeClass('siteTheme3');
							break;
						case 'theme2':
							$(o.applyTo).removeClass('siteTheme3');
							$(o.applyTo).addClass('siteTheme2');
							break;
						case 'theme3':
							$(o.applyTo).removeClass('siteTheme2');
							$(o.applyTo).addClass('siteTheme3');
							break;
					}
					return false;
				});
			}
		}
	};

	$(document).ready(function() {
		window.app.init();
                window.app.resize.init();
		window.app.styleSwitch.init();
		window.app.jfontsizer.init();
		window.app.quicksearch.init();
		window.app.quiz.init();
		window.app.vote.init();
                window.app.media_gallery.init();
		window.app.media_gallery_1.init();
		window.app.slideshow.init();
	});
})(jQuery);

/* Retrieved on 6/6/11 from http://ryanfait.com/resources/custom-checkboxes-and-radio-buttons/
 * "Usage: You are free to share, alter and use this script commercially. Just leave the title, my name and website in tact in the JavaScript script. This script is licensed under a Creative Commons license."
 * http://creativecommons.org/licenses/by-sa/3.0/
 * CUSTOM FORM ELEMENTS, Created by Ryan Fait: www.ryanfait.com */


var large_size = 1340;
var small_size = 1100; // previous value was 980
// Current window width/height
window_height = $(window).height();
window_width = $(window).width();

if (window_width <= small_size) {
    page_size = 'small';
} else {
    page_size = 'large';
}

if (page_size == 'small') {
    var checkboxHeight = "20";
    var radioHeight = "25";
    var selectWidth = "145";
} else {
    var checkboxHeight = "20";
    var radioHeight = "25";
    var selectWidth = "185";
}



