/*
 * JQuery
 */

jQuery.fn.labelOver = function(overClass) {
	return this.each(function(){
		var label = jQuery(this);
		var f = label.attr('for');
		if (f) {
			var input = jQuery('#' + f);
			this.hide = function() {
			  label.css({ textIndent: -10000 });
			}
			
			this.show = function() {
			  if (input.val() == '') label.css({ textIndent: 0 })
			}

			// handlers
			input.focus(this.hide);
			input.blur(this.show);
		    label.addClass(overClass).click(function(){ input.focus() });
			
			if (input.val() != '') this.hide(); 
		}
	})
}

/*
 * Utils
 */

Array.prototype.has=function(v) {
	for (i=0;i<this.length;i++) { if (this[i]==v) return true;}
	return false;
}


$(document).ready(function(){
    /*
     * Stuff
     */
    $('.subnav').hide();
    $("<img>").attr("src", '/media/img/menu_item_bg_on.png'); // Preload menu rollover image
    $('.label-over label').labelOver('over-apply')
    
    /*
     * Set the page heights if js is enabled
     */
    $('.rounded-bg').css('height','385px').css('overflow','hidden'); 
    $('#faqs').css('height','580px').css('overflow','hidden');

    /* 
     * Header Images
     */

    if($('.header-image').size() > 1) {
       $('.header-image').hide();
       $('.header-image:first').addClass('visible_header').show();

       function fadeHeader(){
           obj = $('.visible_header').removeClass('visible_header');
           obj.fadeOut(800, function(){ 
               if($(this).next().hasClass('.header-image')) {
                   $(this).next().addClass('visible_header').fadeIn(1000); 
               } else {
                   $('.header-image:first').addClass('visible_header').fadeIn(1000);
               }
           });
           setTimeout(fadeHeader, 7000);
       }
       setTimeout(fadeHeader, 7000);
    }

    /*
     * Navigation & Accordion
     */

    // select the menu item that matches the current url 
    $("#accordion a").filter("[href="+window.location.pathname+"]").addClass('selected')

    var COOKIE_NAME = 'gbk_navigation';
	var COOKIE_OPTIONS = { path: '/', expires: 1 };
    var prevOpen = $.cookie(COOKIE_NAME);
    if(prevOpen) {
        setTimeout(function(){ $("#accordion a:contains('"+prevOpen+"')").addClass('open').next().slideDown(); }, 400)
    }
	$('#accordion a').click(function() {
        if($(this).next().hasClass('subnav') == false) {
            if($(this).parent().hasClass('subnav') == false) {
                $.cookie(COOKIE_NAME, null, COOKIE_OPTIONS);
            }
            return true;
        } else {
            $.cookie(COOKIE_NAME, $(this).text(), COOKIE_OPTIONS);
            if($(this).attr('href') != '#') return true;
            if($(this).hasClass('open')) return false;
            $('#accordion .open').removeClass('open').next().slideUp('fast');
            $(this).addClass('open').next().slideDown('fast');
            return false;
        }
	});

    /*
     * Page Peel
     */
    
    if($("#page-peel").length > 0) {
        if(window.location.pathname != '/join-the-gang/') {
            $("#page-peel").css('visibility','visible');
            $("#page-peel span").css('backgroundImage',"url('/media/img/peel-join.jpg')").show();
            $("#page-peel").hover(function() { 
                $("#page-peel img, #page-peel span").stop()
                .animate({ 
                    width: '307px',
                    height: '308px'
                }, 300);
            } , function() {
            $("#page-peel img").stop() //On hover out, go back to original size 50x52
                .animate({
                    width: '52px',
                    height: '53px'
                }, 220);
            $("#page-peel span").stop() //On hover out, go back to original size 50x50
                .animate({
                    width: '50px',
                    height: '50px'
                }, 200); //Note this one retracts a bit faster (to prevent glitching in IE)
            });
        }
    }
    

    /*
     * Menu Facts
     */
    if($('#menu-fact')) {
        $('#menu-fact').hover(
            function() {
                $('#menu-fact-info').show(); 
            },
            function() {
                $('#menu-fact-info').hide();
            }
        );
    }
    
    /*
     * Kiwi Facts 
     */

    $("#kiwi").hover(
        function() {
            $('#kiwi-info').show(); 
        },
        function() {
            $('#kiwi-info').hide();
        }
    );

    /*
     * News
     */
    if($('.news-para').length > 0) { 
       $('.news-para').height('110px').css('overflow','hidden'); 
       $('.previous').hide().show();//fix ie bug
       $('.next').hide().show();//fix ie bug
       var showReadMode = function() {
           $('.news-para').each(function() {
                if($(this).children('div:first').height() > $(this).height()+5) {
                    $(this).next().fadeIn();
                }
           });
        }
        $('.read-more a').click(function() {
            showReadMode();
            $('.news-para').height('110px');
            $(this).parent().prev().animate({'height':'100%'}, 100, 'linear');
            $(this).hide();
            return false;
        }); 
        showReadMode();
    }

    /*
     * Links
     */
    if($('.links-para').length > 0) { 
       $('.links-para').height('110px').css('overflow','hidden'); 
       $('.previous').hide().show();//fix ie bug
       $('.next').hide().show();//fix ie bug
       var showReadMode = function() {
           $('.links-para').each(function() {
                if($(this).children('div:first').height() > $(this).height()+5) {
                    $(this).next().fadeIn();
                }
           });
        }
        $('.read-more a').click(function() {
            showReadMode();
            $('.links-para').height('110px');
            $(this).parent().prev().animate({'height':'100%'}, 100, 'linear');
            $(this).hide();
            return false;
        });
       showReadMode(); 
    }


    /*
     * Work with us
     */
    if($('.position').length > 0) {
        $('.position .description').css('height','35px').css('overflow','hidden'); 
        $('.position .read-more').css('display','block');
        $('.position .read-more').click(function() {
            $('.position .read-more').fadeIn('fast');
            $('.position .description').animate({'height':'35px'}, 100, 'linear');
            $(this).prev().animate({'height':'100%'}, 100, 'linear');
            $(this).fadeOut('fast');
            return false;
        });
    }

    /*
     * where shall we open next
     */
    if($('#wson_form').length > 0) {
        $("#wson_form").validate({
			errorElement: "div",
            errorPlacement: function(error, element) {
                error.insertAfter(element);
            },
			success: function(label) {
				label.text("ok!").addClass("success");
			},
			rules: {
				where: {
					required:true
				},
				why: {
                    required:true
                }
			}
		});
    }

    /*
     * create your own
     */
    if($('#cyo_form').length > 0) {
        $("#cyo_form").validate({
			errorElement: "div",
            errorPlacement: function(error, element) {
                error.insertBefore(element);
            },
			success: function(label) {
				label.text("ok!").addClass("success");
			},
			rules: {
				ingredient1: {
					required:true
				},
				ingredient2: {
                    required:true
                },
                ingredient3: {
                    required:true
                },
                ingredient4: {
                    required:false
                },
                ingredient5: {
                    required:false
                },
                name: {
                    required:true
                }
			}
		});
    }

    /*
     * Join the gang
     */
    if($('#jtg_form').length > 0) {
        $('.submit').hide().show();//fix ie bug
        $("#jtg_form").validate({
			errorElement: "div",
            errorPlacement: function(error, element) {
                error.insertBefore(element);
            },
			success: function(label) {
				label.text("ok!").addClass("success");
			},
			rules: {
				'CustomFields[2]': {
					required:true
				},
				'CustomFields[3]': {
                    required:true
                },
				email: {
                    required:true,
                    email: true
				},
                confirmEmail: {
                    required:true,
                    email: true,
                    equalTo:'#email'
                },
                'CustomFields[15]': {
                    required:true
                },
                'CustomFields[18]': {
                    required:true
                },
                'CustomFields[9]': {
                    required:true
                },
                'CustomFields[20][]': {
                    required:true
                }
			}
		});
    }
});

/*
 * Content Scrolling
 */

initScrolling = function(scrollAmount, endOffset, scrollDiv, arrowDown, arrowUp) {
    $(arrowUp).hide();
    $(arrowDown).hide();
    currentScrollMargin = parseFloat($(scrollDiv).css('margin-top'));
    function scrollTo(amount) {
        currentScrollMargin += amount;
        if(currentScrollMargin >= 0) currentScrollMargin = 0;
        $(scrollDiv).stop().animate({'marginTop':currentScrollMargin+'px'}, 150, 'linear', function() {
            if(currentScrollMargin >= 0) {
                $(arrowUp).hide();
            } else {
                $(arrowUp).show();
            }
            if(getOverflowBottom() <= 0) {
                $(arrowDown).hide();
            } else {
                $(arrowDown).show();
            }
        });         
    }
    function getOverflowBottom() {
        return ($(scrollDiv).height() + currentScrollMargin) - $(scrollDiv).parent().height();
    }
    if($(scrollDiv).length > 0) { 
        scrollTo(0);
        $(arrowDown).click(function() {
            if(!$(scrollDiv).is(':animated')) {
                remaining = getOverflowBottom();
                (remaining < scrollAmount) ? scrollTo(-(remaining+$(arrowDown).height())) : scrollTo(-scrollAmount);
            }
        }); 
        $(arrowUp).click(function() {
            if(!$(scrollDiv).is(':animated')) {
                scrollTo(+scrollAmount);
            }
        });
    }
}

/*
 * Google Maps
 */

initMap = function(mapID, startLat, startLong) {
    var point = new google.maps.LatLng(startLat, startLong);
    var map = new google.maps.Map2(document.getElementById(mapID));
    map.addControl(new GSmallMapControl());
    //map.addControl(new GMapTypeControl());
    map.setCenter(point, 14); 
    var gbkicon = new GIcon();
    gbkicon.image = "/media/img/marker-small.png";
    gbkicon.iconAnchor = new GPoint(20, 53);
    //gbkicon.infoWindowAnchor = new GPoint(25, 5);
    marker = new GMarker(point, { icon:gbkicon });
    map.addOverlay(marker);
}

