/*
 * 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(){
    /*
     * color h1 tags
     */
    $('h1').each(function(){
        var words = $(this).text();
        var parts = words.split(' ');
        var total = parts.length;
        if(total > 1) {
            var half = Math.ceil(total / 2);
            var no_wrap = parts.splice(0,half).join(' ')
            var to_wrap = "<span>"+parts.join(' ')+"</span>";
            $(this).html(no_wrap +" "+ to_wrap);
        }
    });

    /*
     * Trigger Cufon AFTER replacing header contents
     */
    Cufon.replace('h1');
    Cufon.replace('h2');
    Cufon.replace('.cufon');
    Cufon.now();

    /*
     * Stuff
     */
    $('.subnav').hide();
    $("<img>").attr("src", '/media/img/menu_item_bg_on.png'); // Preload menu rollover image
    $('.label-over label').labelOver('over-apply')
    
    /*
     * 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;
        }
	});
	
	/*
	 * Async Analytics
	 */
	
	var _gaq = _gaq || [];
	_gaq.push(['_setAccount', 'UA-6127892-1']);
	_gaq.push(['_trackPageview']);
	(function() {
		var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
		ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
		(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga);
	})();

    /*
     * 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
     */
    window.showSwfBubble = function() {
        $('#menu-fact-info').show();
    }
    window.hideSwfBubble = function() {
        $('#menu-fact-info').hide();
    }
    if($('#menu-fact')) {
        $('#menu-fact-info').hide(); 
    }
    
    /*
     * Kiwi Facts 
     */

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

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

       $(".read-more a").toggle(function() {
    	   showReadMode();
    	   $(this).parent().prev().css('height', 'auto').css('overflow', 'visible');
    	   $(this).parent().hide();
       }, function(){});
    }



    /*
     * where shall we open next
     */
    if($('#wson_form').length > 0) {
        $("#wson_form").validate({
			errorElement: "div",
            errorPlacement: function(error, element) {
                error.insertBefore(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
                }
			}
		});
    }

    /*
     * Work with us
     */
    if($('#application_form').length > 0) {
        $("#application_form").validate({
			errorElement: "div",
            errorPlacement: function(error, element) {
                error.insertBefore(element);
            },
			success: function(label) {
				label.text("ok!").addClass("success");
			},
			rules: {
				name: {
					required:true
				},
				email: {
                    required:true,
                    email: true
                },
                restaurant: {
                    required:true
                },
                cv: {
                    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
                }
			}
		});
    }
});

/*
 * Headers
 */

headerIndex = 0;
loopHeaders = function(images) {

    var fadeHeader = function(){
        headerIndex ++;
        if(headerIndex > (images.length-1))
            headerIndex = 0;

        var nextHeaderImage = new Image();
        $(nextHeaderImage).attr('src',images[headerIndex]);
        $(nextHeaderImage).load(function(){

            $(this).hide();
            $('#header img').fadeOut(500, function(){
                $("#header").append(nextHeaderImage);
                $(nextHeaderImage).fadeIn(500); 
                $(this).remove();
                setTimeout(fadeHeader, 7000);
            });
             
        });
    }

    if(images.length) {
        setTimeout(fadeHeader, 7000);
    }
}

/*
 * 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);
}

