function initPageHeight() {
	var lch = $(".leftnav").height(); //lch - left column height
	var pbh = $(".page-body").height(); //pbh = page body height
	var rch = $(".rightnav").height(); //rch = right column height

	if (lch > rch && lch > pbh){
		$(".page-body").css("height", lch + "px");
		$(".rightnav").css("height", lch + "px");
	}

	if (rch > lch && rch > pbh){
		$(".page-body").css("height", rch + "px");
		$(".leftnav").css("height", rch + "px");
	}

	if (pbh > rch && pbh > lch){
		$(".leftnav").css("height", pbh + "px");
		$(".rightnav").css("height", pbh + "px");
	}

	$(".fill-height").each(function() {
		var regex = new RegExp("\\D", "g");

   		$(this).height($(this).parent().height() -
   				( $(this).offset().top - $(this).parent().offset().top ) +
   				$(this).parent().css("border-top-width").replace(regex,"") * 1  +
   				( $(this).parent().css("padding-top").replace(regex,"")  * 1 +
   				  $(this).parent().css("padding-bottom").replace(regex,"")  * 1 ) -
   				( $(this).css("padding-top").replace(regex,"")  * 1   +
   				  $(this).css("padding-bottom").replace(regex,"")  * 1  ) -
   				( $(this).css("border-top-width").replace(regex,"")  * 1  +
   				  $(this).css("border-bottom-width").replace(regex,"")  * 1)
   		);
	  });

}

$(function(){
	$(".button").assignMouseEvents();
	initPageHeight();
});


// Old style functions
var searchInstructions = "Enter keyword or item #";

function submitSearchForm(theForm) {
	   if(doSearchValidation (theForm)) theForm.submit();
}

function doSearchFocus(component) {
    var searchVal = component.value;
    if (searchVal == searchInstructions) {
        component.value = "";
    }
}

function doSearchBlur(component) {
    var searchVal = component.value;
    if (strTrim(searchVal) == '') {
        component.value = searchInstructions;
    }
}

function doSearchValidation (theForm) {
	var searchVal = theForm.keyword.value ;
	if (searchVal == "" || searchVal == searchInstructions) {
		alert ("Please enter a search term and try your search again") ;
		return false ;
	}
	return true ;
}

function strTrim(s) {
    // Remove leading spaces and carriage returns
    while (s.substring(0,1) == ' ') {
        s = s.substring(1, s.length);
    }
    // Remove trailing spaces and carriage returns
    while (s.substring(s.length-1, s.length) == ' ') {
        s = s.substring(0, s.length-1);
    }
    return s;
}

/*
 * This function launches a new web browser window to a specified width, height and features.
 * Features string is a comma separated window's feature needed for this new window. For Instance
 * If a new window needs a toolbar the feature string must be "toolbar" like needs scroll bar and
 * and toolbar then it must be "toolbar,scrollbar". Note that the order of the feature is not required.
 * Also it's case insensitive. Therefore, "scrollbar,toolbar" is identical to "Toolbar,ScrollBar".
 *
 * If the features string is ommitted then all the features are turned off. To turn all the features on
 * use the word "all" for features instead of specifying each feature.
 */

function openWindow(address, width, height,features)
{
	/* Find out what features need to be enable
	 *
   */
	if(features)
		features = features.toLowerCase();
	else
		features = "";

	var toolbar = (features == "all" ? 1 : 0);
	var menubar = (features == "all" ? 1 : 0);
	var location = (features == "all" ? 1 : 0);
	var directories = (features == "all" ? 1 : 0);
	var status = (features == "all" ? 1 : 0);
	var scrollbars = (features == "all" ? 1 : 0);
	var resizable = (features == "all" ? 1 : 0);


	if(features != "all")
	{
		//split features
		var feature = features.split(",");
		for(i = 0; i < feature.length; i++)
		{
		 	if(feature[i] == "toolbar")
			   toolbar = 1;
			else if(feature[i] == "menubar")
			   menubar = 1;
			else if(feature[i] == "location")
			   location = 1;
			else if(feature[i] == "directories")
			   directories = 1;
			else if(feature[i] == "status")
			   status = 1;
			else if(feature[i] == "scrollbars")
			   scrollbars = 1;
			else if(feature[i] == "resizable")
			   resizable = 1;
		}

	}
	features = "toolbar=" + toolbar + ",";
	features += "menubar=" + menubar + ",";
	features += "location=" + location + ",";
	features += "directories=" + directories + ",";
	features += "status=" + status + ",";
	features += "scrollbars=" + scrollbars + ",";
	features += "resizable=" + resizable;

	var newWindow = window.open(address, 'Popup_Window', 'width=' + width + ',height=' + height + ',"' + features + '"');
	newWindow.focus();
}

function trim(s)
{
	// Remove leading spaces and carriage returns
	while (s.substring(0,1) == ' '){
		s = s.substring(1,s.length);
	}
	// Remove trailing spaces and carriage returns
	while (s.substring(s.length-1,s.length) == ' '){
		s = s.substring(0,s.length-1);
	}
	return s;
}
/*
$(function(){
	$("input[@type=text]").focus(function(){
		makeCurrent(this);
	});
	$("input[@type=text]").blur(function(){
		makeNormal(this);
	});
	$("textarea").focus(function(){
		makeCurrent(this);
	});
	$("textarea").blur(function(){
		makeNormal(this);
	});
});
function makeCurrent(elem){
	$(elem).css("background-color", "yellow");
}
function makeNormal(elem){
	$(elem).css("background-color", "white");
}-/

/*************************
	Footer Javascript
*************************/

function callEmailSignup() {
	var formAction = $("#subscribeForm").attr("action");
	$("#emailSignUp").html("Saving...").load(formAction, {"userEmail":$("#subscribeForm input[@name=userEmail]").val()});
}

$(function(){
	$("#subscribeForm input[@name=userEmail]").keydown(function(event) {
		if (event.keyCode == 13)
		{
			callEmailSignup();
			return false;
		}
	});

	$(".email-signup-contianer .signup-button").click(function(){
		callEmailSignup();
	});

	$(".email-signup-contianer .user-email").focus(function(){
		var userEmail = $(this).val();
		if (userEmail == "your email address"){
			$(this).val('');
		}
	});

	$(".email-signup-contianer .user-email").blur(function(){
		var userEmail = $(this).val();
		if (trim(userEmail) == ''){
			$(this).val("your email address");
		}
	});
});

$(document).ready(function(){

if($.browser.msie && $.browser.version=="6.0") { $('#caseStudyExcerpts').addClass('msie6'); } else {

	$('#caseStudyExcerpts ul li img').mouseover( function() {

		$(this).parent('a').parent('li').parent('ul').addClass('highlighted');
		$(this).parent('a').siblings('span').addClass('visibleCaseStudy');
		$(this).parent('a').parent('li').addClass('emphasized');
		$(this).parent('a').parent('li').siblings('li').children('span').removeClass('visibleCaseStudy');
		$(this).parent('a').parent('li').siblings('li').removeClass('emphasized');
		return false;

		});

	//highlighted
	//VisibleCaseStudy

	var n = 0;
	$("#caseStudyExcerpts").bind("mouseleave",function(){

		$(this).children('ul').removeClass('highlighted');
		$(this).children('ul').children('li').removeClass('emphasized');
		$(this).children('ul').children('li').children('span').removeClass('visibleCaseStudy');

	});

}
	/* mouseover functionality for clients main page */
//	$(".client").mouseover(function(){
//      $(this).css("background","#eceded");
//     }).mouseout(function(){
//       $(this).css("background","white");
//    });

	/* article detail accordion */
	$("h6.first").click(function(){
      	$(".first-info").slideToggle("slow");
			$(".second-info").hide("slow");
			$(".third-info").hide("slow");
	  });

	  $("h6.second").click(function(){
      		$(".first-info").hide("slow");
			$(".second-info").slideToggle("slow");
			$(".third-info").hide("slow");
	  });
	  $("h6.third").click(function(){
      		$(".first-info").hide("slow");
			$(".second-info").hide("slow");
			$(".third-info").slideToggle("slow");
	  });

	$(".reference").click(function() {
		var parentTag = $(this).parents().get(1).className;

		if (parentTag == "first-info") {
			$(".first-info").slideToggle("slow");
			$(".second-info").hide("slow");
			$(".third-info").hide("slow");
			alert("first");
		}

		if (parentTag == "second-info") {
			$(".first-info").hide("slow");
			$(".second-info").slideToggle("slow");
			$(".third-info").hide("slow");
			alert("second");
		}

		if (parentTag == "third-info") {
			$(".first-info").hide("slow");
			$(".second-info").slideToggle("slow");
			$(".third-info").hide("slow");
			alert("third");
		}
	});

	/* bios & partners rollover functions*/



		$(".bio").hide();
		$(".partner").hide();
		$(".bio").eq(0).show();
		$(".partner").eq(0).show();
		$(".partnerHolder .name").eq(0).children('a').addClass('active');
		$(".bioList .name").eq(0).children('a').addClass('active');

		var bioIdx = 0;

		$(".col .name a").click(function(){
			var items = $(this).parent().parent().children('li');
			var chosenItem = $(this).parent();
			var chosenList = chosenItem.parent();
			bioIdx = items.index(chosenItem);
			if(chosenList.attr('class')=='col'){
				if(chosenList.prev().attr('class')=='col'){
					bioIdx += chosenList.prev().children('li').length;
				}
			}

			$(".partnerHolder .name").children('a').removeClass('active');
			$(".bioList .name").children('a').removeClass('active');
			$(".partnerHolder .name").eq(bioIdx).children('a').addClass('active');
			$(".bioList .name").eq(bioIdx).children('a').addClass('active');

			$(".bio").each(function(){
				$(this).hide();
			});
			$(".bio").eq(bioIdx).fadeIn();
			$(".partner").each(function(){
					$(this).hide();
				});
			$(".partner").eq(bioIdx).fadeIn();
			});

		// Join Fry Photo Gallery Interaction

		$('#photoGallery ul li a').click(function(evt) {

			evt.preventDefault();


		});

		$('#photoGallery ul li a').hover(
			function () {

				var clickedPhoto = $(this).children('img').attr('src');
				var photoSource = clickedPhoto.split('d.jpg')[0];
				photoSource = photoSource.split('.jpg')[0];
				var saturatedPhoto = photoSource + '.jpg';
				var largerPhoto = photoSource + 'l.jpg';

				var returnPhoto = $('.active').children('img').attr('src');
				returnPhoto = returnPhoto.split('.jpg')[0];
				returnPhoto = returnPhoto + 'd.jpg';
				$('.active').children('img').attr('src', returnPhoto);

				$('#photoGallery ul li a').removeClass('active');
				$(this).addClass('active');
				$(this).children('img').attr('src', saturatedPhoto);
				$('#focalImage').attr('src', largerPhoto);

			},
			function () { });

    // Return boolean TRUE/FALSE for ipad/iphone/ipod users
    // display new flash content on homepage
    function isAppleMobile(){
        return (
            (navigator.platform.indexOf("iPhone") != -1) ||
            (navigator.platform.indexOf("iPod") != -1) ||
            (navigator.platform.indexOf("iPad") != -1)
            // Uncomment to test on Windows box
            // || (navigator.platform.indexOf("Win32") != -1)
        );
    }

    if(isAppleMobile()){
            $(".HomebannerSpacer").addClass('noFlash');
            $(".HomebannerTarget").hide();
        } else {
            var bannerHtml = $(".Homebanner").html();
            $(".HomebannerTarget").html(bannerHtml);
            $(".Homebanner").html("");
        }
});

var randomfeature = function(){
		var length = $("#cgyfeature li").length;
		var ran = Math.floor(Math.random()*length) + 1;
		$("#cgyfeature li:nth-child(" + ran + ")").show();
		$("#cgyfeatureimg li:nth-child(" + ran + ")").show();
	};

var currentSlide = 0;

$(function() {
/* ============================== Code for new slider ============================ */
	if ($('.scrollable').length){
		if ($('.scrollable .item').length>=2){
			$('.scrollable').before('<div id="caseStudySlides" class="sliderNav"><span class="left"></span><span class="right"></span></div>');
		}
		var transTime = 1000;
		var slides = $('.scrollable .items .item');

		if($('.sliderNav .right').length){
			$('.sliderNav .right').click(function(){
				if (currentSlide <= slides.length-2){
					stepLeft(currentSlide)
				}
			});
		}

		if($('.sliderNav .left').length){
			$('.sliderNav .left').click(function(){
				if (currentSlide >=1){
					stepRight(currentSlide);
				}
			});
		}

		function stepLeft(slideNumber){
			$(slides[slideNumber]).children('.floater').animate({'left':'-=3600','opacity':.25},transTime, 'swing');
			currentSlide +=1;
			$('.items').animate({'left':'-=1600'},transTime, 'swing');
			$(slides[slideNumber+1]).children('.floater').animate({'left':'-=3600','opacity':1},transTime, 'swing');
		}

		function stepRight(slideNumber){
			$(slides[slideNumber]).children('.floater').animate({'left':'+=3600','opacity':.25},transTime, 'swing');
			currentSlide -=1;
			$('.items').animate({'left':'+=1600'},transTime, 'swing');
			$(slides[slideNumber-1]).children('.floater').animate({'left':'+=3600','opacity':1},transTime, 'swing');
		}

//		var timeoutID = window.setTimeout(function(){
//			$('.items').animate({'left':'-=1600'},transTime, 'swing');
//			$(slides[0]).children('.floater').animate({'left':'-=3600','opacity':1},transTime, 'swing');
//		}, transTime);
	}
/* ============================== Code for case study navigation ============================ */
	var subNavOpen = true;
	$('#subNavToggle').click(function(){
		if (subNavOpen){
			$(this).removeClass('active');
			$(this).children('span').empty().text('+');
			$('#clientSubNav').slideUp();
			subNavOpen = false;
		} else {
			$(this).addClass('active');
			$(this).children('span').empty().text('-');
			$('#clientSubNav').slideDown();
			subNavOpen = true;
		}
		return false;
	});

//	$('.client a').hover(function(){
//		var oldSrc = $('img', this).attr('src');
//		var newSrc = oldSrc.replace('.','-on.');
//		$('img', this).attr('src',newSrc);
//	},function(){
//		var oldSrc = $('img', this).attr('src');
//		var newSrc = oldSrc.replace('-on.','.');
//		$('img', this).attr('src',newSrc);
//	});

	if($('#clientSubNav').length){

		var $caseStudyList = $('#clientSubNav .subNavHolder ul');
		var listWidth = (($('#clientSubNav .subNavHolder ul li').length) * 150)-2;
		var endPosition = 0-(listWidth - 925);


		$('#clientSubNav .right a').click(function(){
			if ($caseStudyList.position().left >= endPosition){
				if(($caseStudyList.position().left - endPosition)>900){
					$caseStudyList.animate({left: '-=900'},'slow','easeOutCubic');
				} else {
					$caseStudyList.animate({left: endPosition},'slow','easeOutCubic');
				}
			}
		});

		$('#clientSubNav .left a').click(function(){
			if ($caseStudyList.position().left <=-1){
				if(868<($caseStudyList.position().left - endPosition)){
					$caseStudyList.animate({left: 0},'slow');
				} else {
					$caseStudyList.animate({left: '+=900'},'slow','easeOutCubic');
				}
			}
		});

		/*var hideNav = window.setTimeout(function(){
			$('#subNavToggle').removeClass('active');
			$('#subNavToggle').children('span').empty().text('+');
			$('#clientSubNav').slideUp();
			subNavOpen = false;
		}, 1500)*/

	}

/* ============================== Code for Google Maps ============================ */

	if($('#fryMap').length){

		var latlng = new google.maps.LatLng(42, 10);
		var myOptions = {
		  zoom: 3,
		  center: latlng,
		  mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		var map = new google.maps.Map(document.getElementById("fryMap"),myOptions);

		var hqLatlng = new google.maps.LatLng(42.211206, -83.740977);
		var chLatlng = new google.maps.LatLng(41.813847, -87.953011);
		var nyLatlng = new google.maps.LatLng(40.750979, -73.984574);
		var sfLatlng = new google.maps.LatLng(37.764246, -122.401694);
		var boLatlng = new google.maps.LatLng(42.28249, -71.568518);
		var itLatlng = new google.maps.LatLng(45.626243, 9.035726);

		var hqMarker = new google.maps.Marker({
			 position: hqLatlng,
			 title:"Fry, Inc. Ann Arbor"
		});

		var chMarker = new google.maps.Marker({
			 position: chLatlng,
			 title:"Fry, Inc. Chicago"
		});

		var nyMarker = new google.maps.Marker({
			 position: nyLatlng,
			 title:"Fry, Inc. New York"
		});

		var sfMarker = new google.maps.Marker({
			 position: sfLatlng,
			 title:"Fry, Inc. San Francisco"
		});

		var boMarker = new google.maps.Marker({
			 position: boLatlng,
			title:"Fry, Inc. Boston"
		});

		var itMarker = new google.maps.Marker({
			 position: itLatlng,
			 title:"Micros-Retail Italia"
		});

		hqMarker.setMap(map);
		chMarker.setMap(map);
		nyMarker.setMap(map);
		sfMarker.setMap(map);
		boMarker.setMap(map);
		itMarker.setMap(map);

	}

/* ============================== Nav highlight cheat ============================ */

	var pathname = window.location.pathname;
	var path = pathname.split('/');
	var dest = path[path.length-3]+'/'+path[path.length-2]+'/'+path[path.length-1];
	$('.navLinks li a').each(function(){
		var linkTo = $(this).attr('href').split('/');
		var trip = linkTo[linkTo.length-3]+'/'+linkTo[linkTo.length-2]+'/'+linkTo[linkTo.length-1];
		if(trip == dest){
		$(this).css('color','#839A18');
		}
	});


});


/**
 * Processes a YUL Query and returns the results json object to the defined callback method  ( callback(results) )
 * see  http://developer.yahoo.com/yql/
**/
function yqlQuery(query, callback) {
    var yqlURL = "http://query.yahooapis.com/v1/public/yql";
    var data = {
        q: query,
        format: 'json',
        env: 'store://datatables.org/alltableswithkeys'
    }

    $.get(yqlURL, data, callback, 'jsonp');
}

/**
 *  Formats an ISO 8601 date to the following format MM.DD.YYYY
 * @param isoDate ISO 8601 date
 */
function generatePrettyDate(isoDate) {
    var d1 = new Date().setISO8601(isoDate);
    return d1.getMonth().toString() + "." + d1.getDay().toString() + "." + d1.getFullYear().toString();
}

/**
 * Truncates a string based on a max character count
 * @param string String be truncated
 */
function truncateString(string, maxCount) {
    if (string.length > maxCount) {
        return string.substring(0, maxCount) + "...";
    } else {
        return string;
    }
}
/**
 *  Allows for generic support of converting an isodate to a Date object
*/
Date.prototype.setISO8601 = function (dString)
{

    var regexp = /(\d\d\d\d)(-)?(\d\d)(-)?(\d\d)(T)?(\d\d)(:)?(\d\d)(:)?(\d\d)(\.\d+)?(Z|([+-])(\d\d)(:)?(\d\d))/;

    if (dString.toString().match(new RegExp(regexp)))
    {
        var d = dString.match(new RegExp(regexp));
        var offset = 0;

        this.setUTCDate(1);
        this.setUTCFullYear(parseInt(d[1], 10));
        this.setUTCMonth(parseInt(d[3], 10) - 1);
        this.setUTCDate(parseInt(d[5], 10));
        this.setUTCHours(parseInt(d[7], 10));
        this.setUTCMinutes(parseInt(d[9], 10));
        this.setUTCSeconds(parseInt(d[11], 10));
        if (d[12]) this.setUTCMilliseconds(parseFloat(d[12]) * 1000);
        else this.setUTCMilliseconds(0);
        if (d[13] != 'Z')
        {
            offset = (d[15] * 60) + parseInt(d[17], 10);
            offset *= ((d[14] == '-') ? -1 : 1);
            this.setTime(this.getTime() - offset * 60 * 1000);
        }
    }
    else
    {
        this.setTime(Date.parse(dString));
    }
    return this;
};

