//Put your local scripts here

$(function() {
    //urchinTracker();

    //doFixRootPaths();
    doFlashEmbeds();
    doFeatureSlideshows();
    doCareersSlideshows();
    doNavHovers();
    doPagingLinks();
    //doDateInputs();
    doFancyBoxLinks();
    doTabNavFixes();
    doAttachmentLinks();
    doFAQModules();
    doSlideToggles();
    doDownloadForms();
    doFormResets();
    doFirstChilds();
    //doTipTip();
    doTargetBlanks();
    doReleaseTables();
    doYouTubeVideos();
    doFixHeights();
    doDeepLinks();
    doFirstclicks();
	setTopMenu();
	
	doCareersSlideshows();
	
	$('a.iframe').fancybox( {
		height: 600
	});
	$("a.youTube").live('click', function() {
		$.fancybox({
				'padding'		: 0,
				'autoScale'		: false,
				'transitionIn'	: 'none',
				'transitionOut'	: 'none',
				'title'			: this.title,
				'width'			: 680,
				'height'		: 495,
				'href'			: this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
				'type'			: 'swf',
				'swf'			: {
					 'wmode'		: 'transparent',
					'allowfullscreen'	: 'true'
				}
			});

		return false;
	});
});

function doFixRootPaths() {
    if (siteRootPath != "") {
        $("[src^='/']").each(function() {
            var src = $(this).attr("src");
            if (!src.toLowerCase().startsWith(siteRootPath.toLowerCase())) {
                $(this).attr("src", siteRootPath + src);
            }
        });

        $("[href^='/']").each(function() {
            var href = $(this).attr("href");
            if (!href.toLowerCase().startsWith(siteRootPath.toLowerCase())) {
                $(this).attr("href", siteRootPath + href);
            }
        });
    }
}

function doFlashEmbeds() {
    if ($("#site_info_brandScrollerLink").length > 0) {
        var flashVars = { xmlPath: siteRootPath + "xml/logo.xml" };
        var params = {};
        var attributes = {};

        swfobject.embedSWF(siteRootPath + "base/swf/MainPepsicoLogo.swf", "site_info_brandScrollerLink", "960", "69", "9.0.0", "", flashVars, params, attributes);
    }

    $("#site_slideshow_slideControls li a").click(function() {
        $("#site_slideshow_slideControls li a").removeClass("active");
        $(this).addClass("active");
        var html = "<div class=\"site_slideshow_slideContent\" id=\"homePageSwfHolder\">" + $(this).siblings(".alternateContent").html() + "</div>";
        html = html.replace("<!--", "").replace("-->", "");
        $("#site_slideshow_slideWrapper").html(html);

		if (this.href.match(/\.swf$/) != null && this.href.match(/\.swf/).length > 0) {
	        var swfPath = this.href;
	        var xmlName = swfPath.substr(swfPath.lastIndexOf("/") + 1).replace(".swf", "");
	        var xmlVar = siteRootPath + "xml/" + xmlName + ".xml";

	        var flashVars = { xml: xmlVar };
	        var params = { wmode: "transparent" };
	        var attributes = {};
	        swfobject.embedSWF(this.href, "homePageSwfHolder", "938", "319", "9.0.0", "", flashVars, params, attributes);
		}
		$('#homePageSwfHolder').css({visibility : 'visible'});
        return false;
    });

    if ($("#site_slideshow_slideControls li a.featured").length > 0) {
        $("#site_slideshow_slideControls li a.featured").addClass("clickMe");
    } else if ($("#site_slideshow_slideControls li a").length > 0) { 
        var slideLinks = $("#site_slideshow_slideControls li a");
        //var rand = Math.floor(Math.random() * slideLinks.length);
        slideLinks.eq(0).addClass("clickMe");
    }
}

function doFeatureSlideshows() {
    $("#feature_slides").slideshow(5000, 0, "feature_slide_previous", "feature_slide_next", "feature_slide_controls");
    $("#feature_slides2").slideshow(5000, 0, "feature_slide_previous2", "feature_slide_next2", "feature_slide_controls2");
    $("#ytSlides").slideshow(0, 0, "ytPrev", "ytNext");
    $("#flickrSlides").slideshow(0, 0, "flickrPrev", "flickrNext");
}

function doCareersSlideshows() {
    $("#content_careersPeopleSlideshowNav li a").click(function() {
        $("#content_careersPeopleSlideshowNav li a").removeClass("active");
        $(this).addClass("active");
        var html = "<div id=\"peopleSwf\">" + $(this).siblings(".alternateContent").html() + "</div>";
        html = html.replace("<!--", "").replace("-->", "");
        $("#peopleSwfHolder").html(html);

        if ($(this).attr("href").indexOf(".swf") != -1) {
            var swfPath = this.href;
            var xmlName = swfPath.substr(swfPath.lastIndexOf("/") + 1).replace(".swf", "");
            var xmlVar = siteRootPath + "swf/xml/" + xmlName + ".xml";

            var flashVars = { xml: xmlVar };
            var params = { wmode: "transparent" };
            var attributes = {};
            swfobject.embedSWF(this.href, "peopleSwf", "760", "280", "9.0.0", "", flashVars, params, attributes);
        }
        
        return false;
    });
    
    $("#content_careersPeopleSlideshowNav li a:first").trigger("click");
    
    $("#content_careersTabs").slideshow(0, 0, "", "", "content_careersTabsNav");
    $("#content_careersSlideshow").slideshow(5000, 0, "", "", "content_careersSlideshowNav");
    $("#content_careersPeopleSlideshow").slideshow(0, 0, "", "", "content_careersPeopleSlideshowNav");
    
    $(".content_leftBucketWrapper:first").each(function() {
        var leftHeight = $("#site_leftColumn").height() + 275;
        $(".site_mainContent_wrapper").css("background-position", "left " +leftHeight + "px");
    });
}

function doNavHovers() {
    $("#site_mainNav li, #site_utilityNav_globalLink").hover(function() {
        $(this).children("ol").show();
    }, function() {
        $(this).children("ol").hide();
    });
}

function doPagingLinks() {
    $(".content_pagingList a").click(function() {
        var val = $(this).attr("href").substring(1);
        $("[name=hPage]").val(val);
        $("#site_releaseForm").submit();
        return false;
    });
}

function doDateInputs() {
    $(".inputDate").datePicker({ startDate: '05/15/2007', endDate: new Date().asString() });
    $(".inputDate").click(function() {
        $(this).next(".dp-choose-date").click();
    });
}

function doFancyBoxLinks() {
    $(".content_fancyBoxLink").fancybox({
        'autoDimensions': false,
        'width': 600,
        'height': 500,
        'scrolling': 'auto',
        'titleShow': false,
        'padding': 20
    });
}

function doTabNavFixes() {
    $("#site_tabNav, .site_tabNav").each(function() {
        var width = Math.floor($(this).width() / $(this).children().length);
        var lastWidth = width + ($(this).width() - (width * $(this).children().length));
        $(this).find("li").css("width", width + "px");
        $(this).find("li:last").css("width", lastWidth + "px");

        var maxHeight = 0;
        $(this).find("li a").each(function() {
            if ($(this).height() > maxHeight) { maxHeight = $(this).height(); }
        });
        $(this).find("a").css("height", maxHeight + "px");
    });

    $("#site_tabNav a.active").attr("title", "").css("cursor", "default").click(function() { return false; });
}

function doAttachmentLinks() {
    $("#site_middleColumn a[href$=.pdf]").filter(function() { return $(this).children("img").length == 0 && $(this).parents("#site_middleColumn").find(".content_releaseTitle").length == 0; }).addClass("attachment_link");

    $("a.attachment_link").each(function() {
        var href = $(this).attr("href");
        var dot = href.lastIndexOf(".");
        if (dot != -1) {
            var ext = href.substring(dot + 1).toLowerCase();
            $(this).addClass("attachment_" + ext);
        }
    });
}

function doFAQModules() {
    var hasHeaders = false;
    var pairNum = 0;
    var treeNum = 0;
    $(".content_definitionModule_termContainer dl").children().each(function() {
        if (this.tagName == "DT") {
            pairNum++;
            if ($(this).hasClass("content_questionCategory")) {
                hasHeaders = true;
            }
        }
        $(this).attr("pair", "p" + pairNum);
    });

    if (hasHeaders) {
        $(".content_definitionModule_termContainer dl dt").filter(function() { return !$(this).hasClass("content_questionCategory"); }).hide();
    }

    $(".content_definitionModule_termContainer dl dt a").click(function() {
        if ($(this).parent().hasClass("content_questionCategory")) {
            $(".content_definitionModule_termContainer dl dt").filter(function() { return !$(this).hasClass("content_questionCategory"); }).hide();
            $(this).parent().nextUntil(".content_questionCategory").filter("dt").show();
        }

        $(".content_definitionModule_termContainer dl dt a").removeClass("active");
        $(this).addClass("active");

        if (!$(this).parent().hasClass("content_questionCategory")) {
           $(this).parent().prevAll(".content_questionCategory").first().find("a").addClass("active");
        }

        var next = $("dd[pair=" + $(this).parent().attr("pair") + "]");

        if (next.length != 0) {
            $(".content_difinitionModule_definitionCopy").html("<h3>" + $(this).text() + "</h3>" + next.html());
        }

        return false;
    });

    $(".content_definitionModule_termContainer dl dt a:first").click();
}

function doSlideToggles() {
    $(".site_accordianWrapper h4").click(function() {
        $(this).next(".content_accordianCopy").slideToggle("normal", doTabNavFixes);
        $(this).toggleClass("active");
    });
}

function doDownloadForms() {
    $(".content_downloadForm input[type=submit]").click(function() {
        var val = $(this).siblings("select").val();
        if (val != "none" && val != "") {
            open(val, "_blank");
        }
        return false;
    });
}

function doFormResets() {
    $("[type=reset]").click(function() {
        location.href = location.href;
        return false;
    });
}

function doFirstChilds() {
    $(".content_landingPage_subPageList li:first, .content_twitterFeed li:first, .site_brandAds_list li:first").addClass("first");
}

function doTipTip() {
    $(".content_smnrLink").tipTip({ defaultPosition: "top", edgeOffset: 13 });
    $("#site_slideshow_slideControls a").tipTip({ defaultPosition: "top", maxWidth: "180px", edgeOffset: 5 });
    if ($.browser.msie && $.browser.version.substring(0,1) == '6') {
    } else {
        $(".slide_item").filter(function() { return $(this).parents(".content_opportunityBucket_navTabs").length == 0; }).tipTip({ defaultPosition: "top", maxWidth: "250px" });
    }
}

function doTargetBlanks() {
    $(".attachment_link").attr("target", "_blank");
    $("[href^=http://]").filter(function() { return $(this).attr("href").indexOf("pepsico.com") == -1 }).attr("target", "_blank");
    $("[href^=https://]").attr("target", "_blank");
    $("[href$=.pdf]").attr("target", "_blank");
}

function doReleaseTables() {
    $(".content_releaseTitle").parents(".site_mainContent_wrapper").addClass("content_pressReleases");
    $(".content_releaseTitle").siblings("div").find("table").parent().addClass("content_tableWrapper");
}

function doYouTubeVideos() {
    $("[youtubeid]").each(function() {
        var w = "256";
        var h = "144";
        
        var elW = $(this).attr("w");
        var elH = $(this).attr("h");
        
        if (isDefined(elW)) { w = elW; }
        if (isDefined(elH)) { h = elH; }

        var html = '<object width="' + w + '" height="' + h + '"><param name="movie" value="http://www.youtube.com/v/' + $(this).attr("youtubeid") + '&amp;hl=en_US&amp;fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/' + $(this).attr("youtubeid") + '&amp;hl=en_US&amp;fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="' + w + '" height="' + h + '"></embed></object>';
        $(this).html(html);
    });
}

function doFixHeights() {
    $("[heightGroup]").each(function() {
        var group = $(this).attr("heightGroup");
        
        try { var x = eval("group" + group); }
        catch(e) {
            eval("group" + group + " = true");
            var maxHeight = 0;
            $("[heightGroup=" + group + "]").each(function() {
                var h = $(this).height();
                if (h > maxHeight) { maxHeight = h; }
            });
            $("[heightGroup=" + group + "]").css("height", maxHeight + "px");
        }
    });
}

function doDeepLinks() {
    var loc = location.href;
    if (loc.indexOf("#") != -1 && loc.indexOf("#") != loc.length - 1 && loc.indexOf("#search") == -1) {
        loc = loc.substring(loc.indexOf("#"));
        var el = $(loc);
        
        if (el.length > 0) {
            if (el.parent().hasClass("site_accordianWrapper") || el.hasClass("slide_item")) {
                el.addClass("clickMe");
                window.scrollTo(0,0);
            }
        }

        if (loc.indexOf("_fb") != -1) {
            loc = loc.replace("_fb", "");
            if (loc.indexOf("?") != -1) {
                loc = loc.substring(0, loc.indexOf("?"));
            }
            $("[href=" + loc + "]").addClass("clickMe");
        }
    }
}

function doFirstclicks() {
    $(".clickMe").trigger("click");
}

function doFormAppend(id_of_input, text){
    $(id_of_input).val(text + $(id_of_input).val());
	
}

function fireSearch() {
    var address = location.href;
    if (address.indexOf("s=") != -1) {
        address = address.substring(address.indexOf("s=") + 2);
        address = URLDecode(address);
        $(".gsc-input").val(address);
        $(".gsc-search-button").click();
    }
}

function setTopMenu() {
	var home_url = $('h1 a').attr('href');
	
	if (typeof home_url != 'undefined') {
		
		var home_link = $('h1 a').attr('href').split('/')[1];
		var address = location.pathname.replace('/' + home_link + '/', '/');
		address = address.split('/')[1];

		var paths = [home_link, address];
		var path = '/' + paths.join('/');
		path = path.replace('//', '/');

		$('#site_mainNav li a')
			.removeClass('active')
			.each(function(){
				if ($(this).attr('href') == path) {
					$(this).addClass('active');
				}
			});
		
	}

}

function doCareersSlideshows() {
    $("#content_careersTabs").slideshow(0, 0, "", "", "content_careersTabsNav");
    $("#content_careersSlideshow").slideshow(4000, 0, "", "", "content_careersSlideshowNav");
}

function doFormAppend(id_of_input, text) {
    if (($(id_of_input).val() == "SEARCH JOBS BY KEYWORD") || ($(id_of_input).val() == "")) {
        $(id_of_input).val(text);
    }
    else {
        $(id_of_input).val(text + "+" + $(id_of_input).val());
    }

}

function doFormAppend(id_of_input, text) {
	
	var $input = $(id_of_input);
	var base_url = $input
					.parents('form')
					.attr('action');
	
    if ($(id_of_input).val() != "SEARCH JOBS BY KEYWORD") {
        document.location.href = base_url + "&title=" + $(id_of_input).val();
    }
    else {
        document.location.href = base_url;
    }
}

// utility functions for YQL queries, twitter RSS and PepsiCo jobs RSS.
function makeYQLRequest(yql, callback) {
   	var yql_url =  'http://query.yahooapis.com/v1/public/yql?q='+escape(yql)+'&format=json&callback=?&_maxage=3600';
	$.getJSON(yql_url, callback);
			
 }

function parseTweet(tweet) {
	
	var url_regexp = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/gi;
	
	// link URLs, with or without http://
	var description = tweet.replace(
		url_regexp, function(match) {
			var url = (/^[a-z]+:/i).test(match) ? match : "http://"+match;
			return "<a href=\""+url+"\">"+match+"</a>";
	});
	// link twitter usernames
	description = description.replace(/@(\w+)/gi, "@<a href=\"http://twitter.com/$1\">$1</a>");
	// chop PepsiCoJobs off the front of the tweet
	description = description.replace(/^PepsiCoJOBS: /, '');
	
	return description;
}
// Twitter date parsing from https://github.com/seaofclouds/tweet

function parse_date(date_str) {
      // The non-search twitter APIs return inconsistently-formatted dates, which Date.parse
      // cannot handle in IE. We therefore perform the following transformation:
      // "Wed Apr 29 08:53:31 +0000 2009" => "Wed, Apr 29 2009 08:53:31 +0000"
      return Date.parse(date_str.replace(/^([a-z]{3})( [a-z]{3} \d\d?)(.*)( \d{4})$/i, '$1,$2$4$3'));
    }

function relative_time(date) {
      var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
      var delta = parseInt((relative_to.getTime() - date) / 1000, 10);
      var r = '';
      if (delta < 60) {
        r = delta + ' seconds ago';
      } else if(delta < 120) {
        r = 'a minute ago';
      } else if(delta < (45*60)) {
        r = (parseInt(delta / 60, 10)).toString() + ' minutes ago';
      } else if(delta < (2*60*60)) {
        r = 'an hour ago';
      } else if(delta < (24*60*60)) {
        r = '' + (parseInt(delta / 3600, 10)).toString() + ' hours ago';
      } else if(delta < (48*60*60)) {
        r = 'a day ago';
      } else {
        r = (parseInt(delta / 86400, 10)).toString() + ' days ago';
      }
      return 'about ' + r;
    }

function renderTwitter(data, element) {
	var items = data.query.results.item;
	
	var $ol = $('<ul class="content_sliderFollowTweets">');
	
	var append = function(item) {
		var time_ago = relative_time(
						parse_date(item.pubDate)
					);
		
					
		var description = parseTweet(item.description);
		
		
		var $li = $('<li>')
					.append($('<span>').html(description))
					.append($('<em>').text(time_ago));
		$ol.append($li);
	}
	
	
	if (items.length) {
		for (var i in items) {
			append(items[i]);
		}
	} else {
		append(items);
	}

	element.replaceWith($ol);
}

function renderRSS(data, element) {
	var items = data.query.results.item;
	
	var append = function(item) {
		
		var short_desc = $(item.description)
							.text()
							.trim()
							.substr(0, 100)
							.split(' ')
							.slice(0, -1)
							.join(' ') + '…';
							
		var $link = $('<h5>')
						.append(
							$('<a>')
								.attr('href', item.link)
								.text(item.title)
						);
		element
			.append($link)
			.append($('<p>').text(short_desc));
	}
	
	if (items.length) {
		for (var i in items) {
			append(items[i]);
		}
	} else {
		append(items);
	}
	
}

