/*
**********************************************************************************
*  HFF.CallOutHover
*  Right Col Call-outs Hover
**********************************************************************************
*/
HFF.CallOutHover = function (container, hoverElement) {
    container.hover(function () {
        hoverElement.show();
    }, function () {
        hoverElement.hide();
    });
};

/*
**********************************************************************************
*  HFF.ModuleHover
*  About Module Hover
**********************************************************************************
*/
HFF.ModuleHover = function (module) {   
        module.hover(function () {
            $(this).toggleClass('hover');
            return true;
        }).click(function () {
            var href = $(this).find('a').attr('href');
            if(href) {
                window.location = href;
            }
        });
};

/*
**********************************************************************************
*  HFF.SwapContent
*  Events page swap content depending on the event
**********************************************************************************
*/
HFF.SwapContent = function () {
    $('#Regions .state').each(function (index) {
        $(this).click(function () {
            var event = $(this).attr('id').toLowerCase() + "date";
            HFF.SwapFunction(event);
        });
    });

    $('#Regions .cta-link a').each(function (index) {
        $(this).click(function () {
            var event = $(this).parent().parent().parent().attr('id').toLowerCase();            
            HFF.SwapFunction(event);
            HFF.DisplayGoogleMap(event);
        });
    });

$('.event-dates .date').each(function (index) {
    $(this).hover(function () {
        $('.event-dates .date').removeClass('active');
        var event = $(this).attr('class').split(' ').slice(-2, -1); // .toString();
        $('#PomonaDate').hide();
        $('#DallasDate').hide();
        $('#AtlantaDate').hide();
        $('#PhillyDate').hide();
        //$('#NewYorkDate').hide();
        if (event == 'pomonadate') {
            $('#PomonaDate').show();
        }
        if (event == 'dallasdate') {
            $('#DallasDate').show();
        }
        if (event == 'atlantadate') {
            $('#AtlantaDate').show();
        }
        if (event == 'phillydate') {
            $('#PhillyDate').show();
        }
        if (event == 'newyorkdate') {
            //$('#NewYorkDate').show();
        }
        $('.event-dates').find('.' + event).addClass('active');
        // HFF.SwapFunction(event);
    }, function() {
        $(this).addClass('active');
    });
    $(this).click(function () {
        var event_click = $(this).attr('class').split(' ').slice(0, 1); // .toString();
        $('#EventInfo .event-details').hide();
        $('#EventInfo .' + event_click).show();   
        // HFF.SwapFunction(event);
        });
    });
};

HFF.SwapFunction = function (event) {
    $('.event-dates .date').removeClass('active');    
    if (event == 'date') {
        return false;
    }
    else {
        $('.event-dates').find('.' + event).addClass('active');
        $('#EventInfo .event-details').hide();
        $('#EventInfo .' + event).show();               
    }
};

HFF.DisplayGoogleMap = function (event) {
    $('.gmap').css({ 'height': '300px', 'border': '1px solid #83C0DB' });
    switch (event) {
        case 'pomonadate': HFF.GoogleMap('Fairplex 1101 W. McKinley Ave Pomona, CA 91768'); break;
        case 'dallasdate': HFF.GoogleMap('3921 Martin Luther King Jr Bl Dallas, TX 75210-1003'); break;
        case 'atlantadate': HFF.GoogleMap('75 5th Street Atlanta, GA 30308'); break;
        case 'phillydate': HFF.GoogleMap('Peddler\'s Village Routes 202 & 263 Lahaska, Bucks County, PA'); break;
    }
};

/*
**********************************************************************************
*  HFF.DateStateSwitch
*  Events page swap content depending on the event
**********************************************************************************
*/
HFF.DateStateSwitch = function (wrapper, date, state) {    
    wrapper.each(function (index) {
        $(this).hover(function () {
            $('#PomonaDate').hide();
            $('#DallasDate').hide();
            $('#AtlantaDate').hide();
            $('#PhillyDate').hide();
            $(this).find(date).show();
            //$(this).find(state).hide();
        }, function () {
            //$(this).find(date).hide();
           // $(this).find(state).show();
        });
    });
};

/*
**********************************************************************************
*  HFF.PreventSubmit
*  Events page swap content depending on the event
**********************************************************************************
*/
HFF.PreventSubmit = function () {
    $('form input:not([type="submit"])').keydown(function (e) {
        if (e.keyCode == 13) {
            var inputs = $(this).parents("form").eq(0).find(":input");
            if (inputs[inputs.index(this) + 1] != null) {
                inputs[inputs.index(this) + 1].focus();
            }
            e.preventDefault();
            return false;
        }
    });
};

/*
**********************************************************************************
*  HFF.GoogleMap
*  Events page google map
**********************************************************************************
*/
HFF.GoogleMap = function (add) {
    var icon = {
        image: 'images/icons/purple-star-large.png',
        shadow: false,
        iconsize: [26, 25],
        shadowsize: false,
        iconanchor: [0, 19],
        infowindowanchor: [15, 1]
    };


    $('#map').gMap({
        zoom: 14,
        autozoom: false,
        maptype: G_NORMAL_MAP,
        scrollwheel: false,
        icon: icon,
        controls: [
              'GLargeMapControl3D',
              'GMenuMapTypeControl',
              'GOverviewMapControl',
              'GNavLabelControl'
            ],
        markers: [
            {
                address: add,
                html: add,
                icon:
              {
                  image: icon['image'],
                  shadow: icon['shadow'],
                  iconsize: icon['iconsize'],
                  shadowsize: icon['shadowsize'],
                  iconanchor: icon['iconanchor'],
                  infowindowanchor: icon['infowindowanchor']
              }
            }
            ]
    });
};

/*
**********************************************************************************
*  Google page tracking  
**********************************************************************************
*/
HFF.trackPageVisit = function (pageNameHere) {
    _gaq.push(['_trackPageview', pageNameHere]);
};

/*
**********************************************************************************
*  HFF.Tabs
*  Events page swap content depending on the event
**********************************************************************************
*/
HFF.Tabs = function (content, tabs) {
    content.hide(); //Hide all content
    tabs.first().addClass("active").show(); //Activate first tab
    content.first().show(); //Show first tab content

    //On Click Event
    tabs.click(function () {
        //remove this IF ELSE when we have bobby's recipes
//        var id = $(this).attr('id');
//        if (id == "BobbysTab") {
//            $('.close-button, #Ingredients, #Directions, .recipe-print-button, .recipe-share-button').hide();
//        }
//        else {
//            $('.close-button, #Ingredients, #Directions, .recipe-print-button, .recipe-share-button').show();
//        }
        //End if else

        tabs.removeClass("active"); //Remove any "active" class
        $(this).addClass("active"); //Add "active" class to selected tab
        content.hide(); //Hide all tab content
        var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
        $(activeTab).fadeIn(); //Fade in the active content
        return false;
    });
};

/*
**********************************************************************************
*  HFF.LoadTabs  
*  Test Kitchen - load specific tabs on click
**********************************************************************************
*/
HFF.LoadTabs = function (trigger, tab, content) {
    trigger.click(function () {
        //remove this IF ELSE when we have bobby's recipes
//        var id = tab.attr('id');
//        if (id == "BobbysTab") {
//            $('.close-button, #Ingredients, #Directions, .recipe-print-button, .recipe-share-button').hide();
//        }
//        else {
//            $('.close-button, #Ingredients, #Directions, .recipe-print-button, .recipe-share-button').show();
//        }
        //End if else

        $('ul.tabs li').removeClass("active"); //Remove any "active" class
        tab.addClass("active"); //Add "active" class to selected tab
        $(".tab_content").hide(); //Hide all tab content        
        content.show(); //Fade in the active content

        HFF.LoadRecipe();
    });
    $("ul.tabs li").click(function () {
        HFF.LoadRecipe();
    });
};

HFF.LoadRecipe = function () {    
        var activeTab = $('.tabs li.active a').attr('href');
        $('#RecipeModal .recipe').hide();
        $(activeTab + ' .recipe:first').show();
        return false;
    };

HFF.RecipeInit = function () {
    $('.recipe-list .recipe-callout:nth-child(odd)').addClass('blue'); //On Click Event to change recipes

    $(".recipe-list .recipe-callout").each(
	function (intIndex) {
	    $(this).bind(
			"click",
			function () {
			    if ($(this).hasClass('blue')) {
			        var recipe = $(this).attr('class').split(' ').slice(-3, -2).toString();
			    }
			    else {
			        var recipe = $(this).attr('class').split(' ').slice(-2, -1).toString();
			    }
			    $(".recipe").hide();
			    $("#" + recipe).fadeIn();
			    return false;
			});
		});

    //recipe-name subheader
    HFF.CharLimit($('.recipe .recipe-name-sub'), '140');

    //recipe-name hover
    $('.recipe-callout .recipe-name').each(function (index) {
        $(this).hover(
          function () {
              $(this).addClass('hover');
          },
          function () {
              $(this).removeClass('hover');
          }
        );

    });
};

HFF.CharLimit = function (content, charlimit) {
    //recipe list description char limit
    content.each(function (index) {
        var string = $(this).text();
        var limit = charlimit;
        var stringlength = string.length;
        if (stringlength > limit) {
            $(this).text($(this).text().substring(0, limit) + '...');
        }
    });
};


/*
**********************************************************************************
*  HFF.FlashModalInit  
*  Flash modal on Test Kitchen page
**********************************************************************************
*/
HFF.FlashModalInit = function () {
    //modals set up
    $('a.recipeModal').click(function () {
        $('#RecipeModalContainer').jqm().jqmShow();
        return false;
    });

    var stopVideo = function (hash) {
        hash.w.fadeOut('2000', function () {
        hash.o.remove();
        sendToActionScript();
        swfobject.removeSWF("VideoPlayerTestKitchen");
        $('#FlashModalContainer').append('<div id="Flash"><a href="http://www.adobe.com/go/getflashplayer" target="_blank"><img src="/images/home/homepage.jpg" alt="Get Adobe Flash player" /></a></div>');
        }); /*add stopvideo function here*/
    };

    $('a.videoModal.bobby-tips0').click(function () {
         embed_bobby_video("0");
        $('#FlashModalContainer').jqm({ onHide: stopVideo }).jqmShow();
        return false;
    });

    $('a.videoModal.bobby-tips1').click(function () {
        embed_bobby_video("1");
        $('#FlashModalContainer').jqm({ onHide: stopVideo }).jqmShow();
        return false;
    });

    //stop the video from playing on modal close click
    $('#FlashModalContainer .jqmClose').click(function () {
        stopVideo;
    });





    $('a.analyzerModal').click(function () {
        $('#analyzerModalContainer').jqm().jqmShow();
        return false;
    });
    
    $('a.fast_foodModal').click(function () {
        $('#fast_foodModalContainer').jqm().jqmShow();
        $('.fast_food_alternatives').css("display", "none");
        $('.fast_food_choices').css("display", "block");
        return false;
    });

    $('a.usdaModal').click(function () {
        $('#usdaModalContainer').jqm().jqmShow();
        return false;
    });


};


function embed_bobby_video(start_tab) {
	var flashvars = { xmlURL: "/Flash/xml/tipsvideos.xml", gaAccount: "UA-25022228-1", gaCategory: "Video", startTab: start_tab};
	
	var params = {allowScriptAccess: "always", wmode: "transparent"};
	
	var attributes = { id: "VideoPlayerTestKitchen", name: "VideoPlayerTestKitchen" };
	
	swfobject.embedSWF("/Flash/VideoPlayerTestKitchen.swf", "Flash", "660", "614", "9.0.124", "/Flash/js/expressInstall.swf", flashvars, params, attributes);
}

function sendToActionScript() {
	document.getElementById("VideoPlayerTestKitchen").closeVideoFromHtml();
}


function kitchen_scroll(target) {
	switch(target) {
		case "1":
			$('#options_window_inner').animate({left: "0px"},1000);
			$('#arrows_page1').attr("class","arrows_page_on");
			$('#arrows_page2').attr("class","arrows_page_off");
			$('#arrows_page3').attr("class","arrows_page_off");
			break;
		case "2":
			$('#options_window_inner').animate({left: "-342px"},1000);
			$('#arrows_page1').attr("class","arrows_page_off");
			$('#arrows_page2').attr("class","arrows_page_on");
			$('#arrows_page3').attr("class","arrows_page_off");
			break;
		case "3":
			$('#options_window_inner').animate({left: "-660px"},1000);
			$('#arrows_page1').attr("class","arrows_page_off");
			$('#arrows_page2').attr("class","arrows_page_off");
			$('#arrows_page3').attr("class","arrows_page_on");
			break;
		default:
			break;
	}
}


function fast_food_alternative(target) {
	switch(target) {
		case "fries":
			$('.fast_food_choices').css("display","none");
			$('#fast_food_alternative_fries').css("display","block");
			break;
		case "burger":
			$('.fast_food_choices').css("display","none");
			$('#fast_food_alternative_burger').css("display","block");
			break;
		case "biscuit":
			$('.fast_food_choices').css("display","none");
			$('#fast_food_alternative_biscuit').css("display","block");
			break;
		case "pizza":
			$('.fast_food_choices').css("display","none");
			$('#fast_food_alternative_pizza').css("display","block");
			break;
		case "tostado":
			$('.fast_food_choices').css("display","none");
			$('#fast_food_alternative_tostado').css("display","block");
			break;
		case "chicken":
			$('.fast_food_choices').css("display","none");
			$('#fast_food_alternative_chicken').css("display","block");
			break;
		default:
			break;
	}
}



$('document').ready(function() {

	$('#arrow_back').click(function () {
		if($('#arrows_page1').hasClass('arrows_page_on')) {
			kitchen_scroll("1");
		}
		else if($('#arrows_page2').hasClass('arrows_page_on')) {
			kitchen_scroll("1");
		}
		else if($('#arrows_page3').hasClass('arrows_page_on')) {
			kitchen_scroll("2");
		}
	});

	$('#arrow_forward').click(function () {
		if($('#arrows_page1').hasClass('arrows_page_on')) {
			kitchen_scroll("2");
		}
		else if($('#arrows_page2').hasClass('arrows_page_on')) {
			kitchen_scroll("3");
		}
		else if($('#arrows_page3').hasClass('arrows_page_on')) {
			kitchen_scroll("3");
		}
	});



	$('#arrows_page1').click(function () {
		kitchen_scroll("1");
	});
	$('#arrows_page2').click(function () {
		kitchen_scroll("2");
	});
	$('#arrows_page3').click(function () {
		kitchen_scroll("3");
	});
	
	$('#arrows_page1').click();




	$('.fast_food_button_back').click(function () {
		$('.fast_food_alternatives').css("display","none");
		$('.fast_food_choices').css("display","block");
	});


});













/*
**********************************************************************************
*  HFF.Tooltip
*  Tooltip Init
**********************************************************************************
*/
HFF.MapTooltip = function (map, date, location) {    
    map.tooltip({
        effect: 'slide',
        tip: date,
        offset: [0, 0],
        predelay: 200,
        delay: 200
    });
};


/*
**********************************************************************************
*  HFF.HomeHoverInit
*  Homepage Across Country Module Hover Init
**********************************************************************************
*/
HFF.HomeHoverInit = function () {
    $('#AcrossCountry .location').hide();

    HFF.MapTooltip($("#PomonaMap"), '#PomonaDate', $('#AcrossCountry .pomonamap'));
    HFF.MapTooltip($("#DallasMap"), '#DallasDate', $('#AcrossCountry .dallasmap'));
    HFF.MapTooltip($("#AtlantaMap"), '#AtlantaDate', $('#AcrossCountry .atlantamap'));
    HFF.MapTooltip($("#PhillyMap"), '#PhillyDate', $('#AcrossCountry .phillymap'));
};


/*
**********************************************************************************
*  HFF.FormatWords
*  ViewMore/Hide on the Test Kitchen. Accept a paragraph and return a formatted 
*  paragraph with additional html tags
**********************************************************************************
*/
HFF.ApplyViewMore = function (excerpt) {
    // Grab all the excerpt class
    excerpt.each(function () {
        // Run formatWord function and specify the length of words display to viewer
        $(this).html(HFF.FormatWords($(this).html(), 10));

        // Hide the extra words
        $(this).children('span').hide();

        // Apply click event to read more link
    }).click(function () {

        // Grab the hidden span and anchor
        var more_text = $(this).children('span.more_text');
        var more_link = $(this).children('a.more_link');

        // Toggle visibility using hasClass
        // I know you can use is(':visible') but it doesn't work in IE8 somehow...
        if (more_text.hasClass('hide')) {
            more_text.show();
            more_link.html(' &raquo; hide');
            more_text.removeClass('hide');
        } else {
            more_text.hide();
            more_link.html(' &laquo; more');
            more_text.addClass('hide');
        }
        return false;
    });
};

HFF.FormatWords = function (sentence, show) {
    // split all the words and store it in an array
    var words = sentence.split(' ');
    var new_sentence = '';

    // loop through each word
    for (i = 0; i < words.length; i++) {

        // process words that will visible to viewer
        if (i <= show) {
            new_sentence += words[i] + ' ';

            // process the rest of the words
        } else {

            // add a span at start
            if (i == (show + 1)) new_sentence += '... <span class="more_text hide">';

            new_sentence += words[i] + ' ';

            // close the span tag and add read more link in the very end
            if (words[i + 1] == null) new_sentence += '</span><a href="#" class="more_link"> &raquo; more</a>';
        }
    }

    return new_sentence;
};


/*
**********************************************************************************
*  HFF.getUrlVars
*  Recipe Contest URL
**********************************************************************************
*/
HFF.getUrlVars = function () {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
};


/*
**********************************************************************************
*  methods to run on DOM ready for every page
*  page specific JS methods are instantiated on individual pages
**********************************************************************************
*/
(function ($) {   
    //share click tracking
    $('#atic_facebook').click(function () {
        _gaq.push(['_trackEvent', 'Share', 'Facebook']);   
    });

    $('#atic_twitter').click(function () {
        _gaq.push(['_trackEvent', 'Share', 'Twitter']);   
    });    

})(this.jQuery);

