var currentRecipeId = currentRecipeId || '1605';
var currentRecipeTitle = currentRecipeTitle || "";

$(document).ready(function(){ 
	
	// make sure this content is not loading in an iframe;  if it is, avoid the document ready procedures
	if (window.location != window.parent.location) {
	    shareStoryPics();
	    return;
	}
	
	/* Flash needs to know if there's a mouseup if the user drags outside of the .swf .*/
	if(!!$('#flash')[0]){		
		$('body').mouseup(function(){
			try{$('#flash')[0].mouseUp()}
			catch(e){};
		});
	}
	
	$.historyInit(ajaxHistoryLoad, '/hash.html');	
	homepageReady();
	initIngredients();
	lifestyleImagesPNG();
	prepPaginate();
	seamlessMethods();
	shareStoryPics();
	socialBookmarking();
	olmCheck();
	startingPoint(); // For seamless web transitions.
});

/* Collection of methods loaded w/ each page load. Added to a method of it's own as it's also called in ajaxHistoryLoad()*/
var seamlessMethods = function(){
	flashActions();
	initAddRecipeBox();
	initRemoveRecipeBox();
	initRecipeBox();
	initReviews();	
	seamlessWeb();
	prepActions();
	ie6PNG();
	fixIEBottom();
	pageTitle();
	configAddThis();	
	parseSearch();
};


//end jQuery stuff
var initRecipeBox = function(){
	if(!$("#table-recipe-box tbody tr").size()) {
		$("#recipe-box-full").css('display','none');
		$("#recipe-box-empty").css('display','block');
	} else {
		$("#recipe-box-full").css('display','block');
		$("#recipe-box-empty").css('display','none');
		$("#table-recipe-box").css('display','block');
		$("#table-recipe-box").tableSorter({
			disableHeader: [3,4]/*	,
			headerClass: 'header',
			stripingRowClass: ['odd','even'],
			stripRowsOnStartUp: true*/
		});
	}
};


// init add to recipe box widget (wrapped in a function so we can call again when paging through search results)
  initAddRecipeBox = function() {
    $("a.add-recipe, p.add-recipe a").bind("click", function() {
      var me = $(this);
        try {
          $.ajax({
            url: me.attr("href"),
            type: "GET",
            success: function(req) {
              if(req.trim() == 'true') {
                me.before("<strong>In your recipe box</strong>");
                $(me).parent().toggleClass("add-recipe-on");
                me.remove();
              } else {
                ajaxError();
              }
            },
            error: ajaxError
          });
        } catch(err) {ajaxError(err);}
        this.blur();
        return false;
    }).css('visibility','visible');
  };
 
 
  // init remove from recipe box widget
  initRemoveRecipeBox = function() {
  
	$("a.remove-recipe").unbind('click').bind("click", function() {
    this.blur();
    $(this).parents("tr").children("td").addClass("highlight");
    if(window.confirm("Are you sure you want to remove this recipe?")) {
      var me = $(this);
      try {
        $.ajax({
          url: me.attr("href"),
          type: "GET",
          success: function(req) {
            if(req.trim() == 'true') {
              $(me).parents("tr").hide().remove();
              if(!$("#table-recipe-box tbody tr").size()) {
                $("#recipe-box-empty").css('display','block');
								$("#recipe-box-full").css('display','none');
                $("#table-recipe-box").css('display','none');
              }
            } else {
              ajaxError();
            }
          },
          error: ajaxError
        });
      } catch(err) {ajaxError(err);}
    } else {
      $(this).parents("tr").children("td").removeClass("highlight");
    }
    return false;
  }).css('visibility','visible');
 };

var monitorAjax = function(){
	return true;
}
 
	
ajaxError = function(req) {
  monitorAjax("Error");
  alert("Sorry, the server was unable to process your request. Please try again.");
  //alert(req);
};


String.prototype.trim = function () {
	return this.replace(/^\s+|\s+$/g, "");
};

String.prototype.isEmpty = function() {
  return ((this === null) || (this.length === 0) || (/^\s+$/.test(this)));
};

var newVisitor = function(){
	var showIntro = !!readCookie('rkVisited');
	if(!showIntro){
		createCookie('rkVisited',1,365);
	}
return showIntro
}

createCookie = function(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else {expires = ""};
  document.cookie = name+"="+value+expires+"; path=/";
};

readCookie = function(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') {c = c.substring(1,c.length)};
    if (c.indexOf(nameEQ) === 0) {return c.substring(nameEQ.length,c.length)};
  }
  return null;
}

parseQuery = function() {
//Updated to accept parameters.
	var returnVals = new Array();
	qString = arguments[0] || new String(window.location);
	var queryStart = qString.indexOf('?');
	if (queryStart==-1) {
		return returnVals;
	}
	var query = qString.substring(queryStart + 1, qString.length);
	var parts = query.split("&");
	for (var i=0; i<parts.length; i++) {
		bits = parts[i].split("=");
		if(bits[1]) {
			subbits = bits[1].split("#"); // added by T.D. to handle fragment identifier in URL
			returnVals[bits[0].toLowerCase()] = bits[1]; // query[] indexes are now lowercase!
		}
	}
	return returnVals;
}

var query = new parseQuery();

popUpWindow = function(URL,windowName,width,height) {
	var w = screen.availWidth;
	var h = screen.availHeight;
	var leftPos = Math.round((w-width)/2);
	var topPos = Math.round((h-height)/2);
	var defaults = "scrollbars = 0, resizable";
	var centerOnScreen = "top="+topPos+", left="+leftPos+", width="+width+", height="+height;
	var options = centerOnScreen + " ," + defaults;
	var msgWindow = window.open(URL,windowName,options);
	if(!msgWindow) {
		return false;
	} else {
		msgWindow.creator=self;
		msgWindow.focus();
	}
  return true;
};

function OutsideURLWarning(url) {
	var result = popUpWindow("bumper.html?url=" + escape(url), "bumper", 955, 520);
	return (result == false);
};

var bookmarkPage = function() {
	addthis_url = location.href;
	addthis_title = document.title;
	return addthis_sendto();
};

var printPage = function(){
	if(window.location.href.indexOf('Display') == -1){
		window.print();
	}
	else {
		var q = query['recipe_id'];
		var k = query['kic'];	
		invokeOverlay('print',q);
	};
};

var aboutVideo = function(){
	invokeOverlay('aboutvideos');
};

var sharePage = function(){
	invokeOverlay();
};

// overlays
////////////////////////////////////////
var invokeOverlay = function(x,id){
	if(typeof(id) == "undefined"){id="1605"};
	var h = document.body.clientHeight;
	var w = document.body.clientWidth;
	var d = document.createElement("div");
	d.id = "overlaycontainer";
	d.style.height = h+"px";
	d.style.width = w+"px";	
	var db = document.createElement("div");
	db.id = "overlayblock";
	window.scrollTo(0,0);

	var ins2 = document.body.insertBefore(db,document.body.firstChild);
	var ins = document.body.insertBefore(d,document.body.firstChild);
	var ts = 'ts=' + new Date().getTime();
	
	var oc; //overlayContent
	switch(x){
	case 'mom':
		oc = '/overlay_momsreviews.aspx?recipe_id='+id + '&' + ts;
		break;
	case 'recipe':
		oc = '/overlay_sharerecipe.aspx?' + ts;
		break;
	case 'story':
		oc = '/overlay_shareyourstory.aspx?' + ts;
		break;
	case 'thanks':
		oc = '/overlay_thankyou.aspx?' + ts;
		break;
	case 'aboutvideos':
		oc = '/overlay_aboutvideos.aspx?' + ts;
		break;
	case 'unfriendly':
		//id here is actually this.search object of link.
		oc = '/overlay_unfriendly.aspx'+id + '&' + ts;
		break;		
	case 'print':
		oc = '/overlay_print.aspx?recipe_id='+id + '&' + ts;
		break;	
	case 'guardian':
		oc = '/overlay_guardian.aspx?' + ts;
		break;
	case 'newsletter':
		oc = '/overlay_newsletter.aspx?' + ts;
		break;
	case 'review':
		oc = '/overlay_review.aspx?recipe_id='+id + '&' + ts;
		Kellogg.track('/action/recipedetail/writereview/openpanel/login/'+currentRecipeId)
		break;
	case 'nutrition':
		oc = '/overlay_nutrition.aspx?' + ts;
		break;
	case 'recipebox':
		oc = '/overlay_recipebox_login.aspx?recipe_id='+id + '&' +ts;
		break;
				
	default:
		oc = '/overlay_sharemagic.aspx?' + ts;
	}
	$("#overlayblock").load(oc);
}

var revokeOverlay = function() {
	$('#overlayblock').remove();
	$('#overlaycontainer').remove();
}

var toggleOverlays = function(rid){
    var invoke = function(){
        window.parent.invokeOverlay('review',rid);
    }
	var x = setTimeout(invoke,250);
	revokeOverlay();
}

$(".closeOverlay").click(function(){
	revokeOverlay;
	return false;
});

function pngToGif() {
	return true;
	/*

		if ($.browser.msie && parseInt($.browser.version, 10) < 7) {
			$("img[src$=png]").not(".ingredient-image").each(function () {
				this.src = this.src.replace(/\.png$/, ".gif");
			});
		}
		*/
}

// home page
////////////////////////////////////////
var homepageReady = function(){

	if(document.getElementsByTagName('body')[0] == 'home') {
		var pics = ['testimony1.jpg','testimony2.jpg','testimony3.jpg','testimony4.jpg'];
		var num = Math.floor(Math.random()*pics.length);
		var id = document.getElementById('testimony');
		id.firstChild.src = "/images/"+pics[num];
	}
}

////////////////////////////////////////
var lifestyleImagesPNG = function(){
	if(document.getElementById('lifestyle')){
		var pics = ['FamilyPhotoSet_1.png','FamilyPhotoSet_2.png','FamilyPhotoSet_3.png','FamilyPhotoSet_4.png','familyphotoset_5.png'];
		var num = Math.floor(Math.random()*pics.length);
                var path = "/images/" + pics[num];
                $('#lifestyle img').attr('src',path);
	}
}

// recipe submit functions
////////////////////////////////////////

initIngredients = function() {
 if(document.getElementById("ingredients")){
  var l = document.getElementById("ingredients");
	
	if(l.value) {
		var arrIngredients = l.value.split("^");
		for(var i=0; i<arrIngredients.length; i++) {
      var arrParts = arrIngredients[i].split("|");
			insertIngredientRow(arrParts[0], getUnitText(arrParts[1], arrParts[0]), arrParts[2]);
		}
	}
	}
}

var addProduct = function(x){
    if(x.options.selectedIndex > 0){
	    var i = document.getElementById('ingredient');
	    var pi = document.getElementById('productid');
	    var pn = document.getElementById('productname');

	    i.value = x.options[x.options.selectedIndex].text;
	    pn.value = x.options[x.options.selectedIndex].text;
	    pi.value = x.value;
	}
}

addIngredient = function() {
  var q = document.getElementById('quantity');
  var u = document.getElementById('unit');
  var i = document.getElementById('ingredient');
  var pi = document.getElementById('productid');
  var pn = document.getElementById('productname');
  
  // validate
	if(!q.value) {
		alert("Enter a quantity.");
    q.focus();
		return false;
	}
  if(!i.value) {
    alert("Enter an ingredient.");
		i.focus();
		return false;
	}
  
  var qc = q.value.cleanIngredient();
  var ic = i.value.cleanIngredient();
  
	// insert row	
	insertIngredientRow(qc, getUnitText(u.value, qc), ic);
  
  // user selected a product?
  if(pn.value == i.value) ic = "ID:" + pi.value;
	// update hidden value
  var l = document.getElementById("ingredients");	
	l.value = l.value ? l.value + "^" + qc + "|" + u.value + "|" + ic : qc + "|" + u.value + "|" + ic;
  
  // reset selected product values
  pi.value = "";
  pn.value = "";
	
	//alert(l.value);
	
	// reset form values
	q.value = "";
	u.selectedIndex = 0;
 	i.value = "";
	q.focus();
  return false;
}

insertIngredientRow = function(q, u, i) {
	var table = document.getElementById("tbl_ingredients");
	if(table) {
		// ingredient contains product ID?
    if(i.indexOf("ID:") > -1) i = getProductName(i.replace(/ID:/, ""));
    
    var tr = table.insertRow(table.rows.length);
		// insert the cells
		var td = new Array(1);
	  td[0] = tr.insertCell(0);
    td[1] = tr.insertCell(1);
    
    td[0].className = "ingredient";
    td[1].className = "delete";
    
		td[0].innerHTML = q + ' ' + u + ' ' + i;
		td[1].innerHTML = '<a href="#" onclick="deleteIngredientRow(this.parentNode.parentNode);this.blur();return false;"><img src="/images/trash.gif" border="0"></a>';
	}
  table.parentNode.className = "section";
  alternateRows(table);
}

deleteIngredientRow = function(tr) {
  var table = document.getElementById("tbl_ingredients");
  tr.className = "highlight";
	if(window.confirm("Delete this ingredient?")) {
	
		// update hidden values
		var i = tr.rowIndex;
		var l = document.getElementById("ingredients");
		var arrIngredients = l.value.split("^");
		
		arrIngredients.splice(i, 1);
		
		l.value = arrIngredients.join("^");
		
		//alert(l.value);
		
		// delete row
		table.deleteRow(i);
    if(!table.rows.length) table.parentNode.className = "";
	}
  alternateRows(table);
  document.getElementById("quantity").focus();
};

var getProductName = function(v) {
  var p = document.getElementById("product");
  if(p) {
    for(var i=0; i<p.length; i++) {
      if(p.options[i].value == v) {
        return p.options[i].text;
      }
    }
  }
  return "";
}

var getUnitText = function(v, q) {

  var u = document.getElementById("unit");
  if(u) {
    for(var i=0; i<u.length; i++) {
      if(u.options[i].value == v) {
        if(q == "1") {
          return u.options[i].className;
        } else {
          return u.options[i].text;
        }
      }
    }
  }
  return "";
}

String.prototype.cleanIngredient = function () {
	return this.replace(/[\^\|]/g, "");
}

showProdInfo = function(id) {
  $document.getElementById('div.product-info').each(function(el) {
    el.style.display = "none";
  });
  document.getElementById(id).style.display = "block";
}

alternateRows = function(table) {
	for(var i=0; tr=table.getElementsByTagName("tr")[i]; i++) {
		if(i % 2) {
	      tr.className = "even";
	    } else {
	      tr.className = "odd";
	    }
	}
}






// tracking functions
var Kellogg = Kellogg || {};

Kellogg.trackers = [];

Kellogg.track = function (str) {
	for (var i = 0, l = Kellogg.trackers.length; i < l; i++) {
		if (typeof Kellogg.trackers[i]._trackPageview === "function") {
			if (str) {
				Kellogg.trackers[i]._trackPageview(str);
			} else {
				Kellogg.trackers[i]._trackPageview();
			}
		}
	}
};

// tracking productname parser

function cleanName(str){
	if (str) { 
		return str.replace(/\W/g, "");
	}
}


/*Search Result Pagination*/
var pstart =0;
var plimit,results,rlength;

var prepPaginate = function(){
	results = $('.entry');
	rlength = results.length;
	
	if(document.getElementById('sel_results')){
		var sel = document.getElementById('sel_results');
		var sell = sel.length;
		if(readCookie('searchPref')){
			while(sell--){
				if(readCookie('searchPref') == sel[sell].value) {
					sel.selectedIndex = sell;
					break;
				}
			}
		}
	}
}

var paginate = function(setnum){
	plimit = setnum || (parseInt(readCookie('searchPref')) || 5);
	//console.log(rlength,results.length,$('.entry').length)
	if(pstart + plimit >= rlength){$("#bt_more_results").css('display','none');}else{$("#bt_more_results").css('display','inline');}
	if(pstart >= rlength){return true;}
	$('.entry').css('display','none')
    for(var loop=pstart; loop<plimit+pstart; loop++){
        if(rlength <= loop){break;}	
        results[loop].style.display="block";
		var x = deferredRatings[results[loop].getAttribute('rel')];
		embedRating(x.ApplicationID, x.UserID, x.Rating, x.LoggedIn, false);
    }
	pstart = pstart+plimit;
	return true;
}
/*

var shareStoryPics = function(){
	if(document.getElementById('image_selection')){
		var l = $('#image_selection').find('label');
		l.click(function(){
			l.fadeTo('fast',0.25,function(){$(this).fadeTo(250,1)});
		})
	}
	else {
		return false;
	}
}
*/

var shareStoryPics = function(){
	if(document.getElementById('image_selection')){
		var l = $('#image_selection').find('label');
		l.click(function(e){
                        var x = this.id;
			l.fadeTo(100,0.25, function(){
                            if(x == this.id){
                                $(this).fadeTo(100,1);
                            }
                        });
		});
	}
	else {
		return false;
	}
}

var socialBookmarking = function() {
	if(document.getElementById('socialbookmark-intro')) {
		var sbl = document.getElementById('socialbookmark-intro-link');
		var sbi = document.getElementById('socialbookmark-intro')
		var sbia = sbi.getElementsByTagName('a')[0];
		sbl.onmouseover = function(){sbi.style.display="block"; return false;}
		sbl.onclick = function(){return false;}	
		sbia.onclick = function(){sbi.style.display="none"; return false;}
	}
}

var scootchFlash = function(grow){
	var grow = grow || false;
	var offset = -280;
	var f = $('#flash')[0];	
	var x = $('#wrapper');
	var y = x.css('margin-top');
	var z = (!!grow) ? 0 : offset;
	x.css('marginTop',z)//animate({marginTop:z+'px'},500);
	if(!grow && typeof(f) != undefined){
		try{f.shrink();}
		catch(e){}
	}
	else{
		try{f.grow();}
		catch(e){}
    }
}

var goHome = function(){
    $.historyLoad('/Default');
    scootchFlash(1);
}

var actionPrintFlash = 0, actionReviewFlash = 0;

var actionPrint = function(){
	actionPrintFlash = 1;
}

var actionReview = function(){
	actionReviewFlash = 1
}

var actionRecipeBox = function(rid){
	var x = readCookie('rkLogin');
	if(x==1){
	    $.get('/Ajax/UpdateFavorites.aspx?action=add&kic=true&recipe_id='+rid)
	}
	else{
	    invokeOverlay('recipebox',rid);
		createCookie('rkAddToBox',rid);
	}
}

var flashActions = function(){
	if(actionPrintFlash == 1){
		invokeOverlay('print',currentRecipeId);
		actionPrintFlash = 0;
	}
	
	if(actionReviewFlash == 1){
		$('#reviews')[0].scrollIntoView();
		actionReviewFlash = 0;
	}
}

var olmCheck = function(){
	var x = query['olm'];
	if(typeof(x) != 'undefined'){
		invokeOverlay('print',currentRecipeId);
	}
}

var loginState = function(create){
	var x = create || 0;
	if(x == 1){
		createCookie('rkLogin',1);
	}
	else{
		createCookie('rkLogin',0,-1);
	}
}

/*
	Nav Actions
*/
var prepActions = function(){
	$('.immunity_release').unbind('click').click(function(){
		Kellogg.track('/action/immunitystatement/pressrelease');
		return true;
	});
	
	$('#recipeBoxLogout').unbind('click').click(function(){
		var x = this.href;
		reloadRecipeBox(x);
		return false;
	});
	
	$('#rda_review, .lnk_review').unbind('click').click(function(){
		invokeOverlay('review', currentRecipeId);
		Kellogg.track('/action/recipedetail/writereview/'+currentRecipeId);
		return false;
	});
	
	$('#rda_share').unbind('click').click(function(){
		Kellogg.track('/action/recipedetail/share/'+currentRecipeId);
	});
		

	$('#rda_print').unbind('click').click(function(){
		var x = (!!currentRecipeId) ? currentRecipeId : null;
		invokeOverlay('print',x);
		Kellogg.track('/action/recipedetail/printrecipe/openpanel/'+currentRecipeId);
		return false;
	});

	$('#nutInfoLink').unbind('click').click(function(){
		invokeOverlay('nutrition');
		return false;
	});
	
	$('#act_vids').unbind('click').click(function(){
		invokeOverlay('aboutvideos');
		return false;
	});	
	
	$('.lnk_newslettersignup').unbind('click').click(function(){
		invokeOverlay('newsletter');
		return false;
	});
	
	$('.unfriendlylink').unbind('click').click(function(){
		invokeOverlay('unfriendly',this.search);
		Kellogg.track('/recipereview/unfriendly/clicked');
		return false;
	});
	
	$('.a_recipebox').unbind('click').click(function(){
		invokeOverlay('recipebox');
		return false;
	});
	
	$("#whyUseRKlink, #whyUseRKClose").unbind('click').click(function(e){
	 	$list = $("#whyUseRKContent");
 		$list.toggle();
		return false;
	});
	
	$('.backToTop a').unbind('click').click(function(e){
	 	scrollTo(0,0);
		return false;
	});
	
	$("#reviewToggle").unbind('click').click(function(e){
		if ($("#all_reviews").css("display") === "none") {
			Kellogg.track("/recipereview/show");
		} else {
			Kellogg.track("/recipereview/hide");
		}
 		initReviews(1);
		$('#reviewToggle span').toggle()
		return false;
	});

	$("#formclose").unbind('click').click(function(e){
 		$form = $(".formexpanded");
		$form.slideUp("fast");
		return false;
	});
	
	shareStoryPics();
		
	$('.sidebar h4 a').unbind('click').click(function(e){
		$('.expanded',this.parentNode.parentNode).toggle('fast');
		$(this).toggleClass('arrowup');
		return false;
	});
	
	$('.col_header a').unbind('click').click(function(e){
		$('.expanded',this.parentNode.parentNode).toggle('fast');
		$(this).toggleClass('arrowup');
		return false;
	});
};

/*
	Seamless page transitioning.
*/
var pageTitle = function(){
	var rk = "Kellogg's® Rice Krispies®";
	var head = ($('h1#recipeHeadline').size() > 0) ? ' - ' + $('#recipeHeadline').html() : "";
	var x = (currentRecipeTitle != "") ? ' - ' + currentRecipeTitle : head;
	document.title = rk + x
}

var generateHash = function(href){
	var loc = window.location.hostname;
	var start = (href.indexOf(loc) == -1)? 0 : href.indexOf(loc)+loc.length;
	var end   = href.indexOf('.aspx');
	if(end != -1){
		return href.substring(start,end);
	}
	else{
		return '/Default';
	}
};


var swapSidebars = function(){
	if($('.sidebar_right').size() > 1) {
		$('.sidebar_right:eq(0)').remove();
	}
	
	if($('.sidebar_left').size() > 1) {	
		$('.sidebar_left:eq(0)').remove();
	}
};

function execSearch(query){
	var flash = $('#flash')[0];
	
	if(typeof(execSearch.query)){
        execSearch.query = query;
	}
	
	if(typeof(flash.search) == "function"){
		flash.search(query);
	}
	else{
		var timer = setTimeout("execSearch(execSearch.query)",100);
	}
};

var parseSearch = function(){
    var l = window.location.hash;
    var del = '/search/';
    var s = l.split(del);
	
    if(!!s[1]){
        scootchFlash(1);
        execSearch(s[1]);
    }
};

var ajaxEnabled = function(){
	/*
		Exclude entire pages where the seamless function isn't used, based on body ID.
		IDs below are the *accepted* pages.
	*/
	var bodies = ['home','recipe','recipebox','memorylane','cookingwithkids_video','cookingwithkids','contact','barbarabeery','products','onthego','playground'];
	var bl = bodies.length;
	while(bl--){
		if(document.body.id == bodies[bl]){
			return true;
		}
	}
	if(bl === -1){
		return false;
	}
}

var configAddThis = function(){
	var l = $('.addthis_button');
	var x = (l.size() > 0) ? '.addthis_button' : '#addThisDefault';
	
	addthis.button(x, {ui_click: true}, {url: window.location.host + window.location.hash.replace('#', '') + '.aspx', title: document.title});
}

var startingPoint = function(){
	if(!ajaxEnabled()){
		return false;
	}
	
	var l = window.location;
	if(l.hash.length == 0){
		$.historyLoad(generateHash(l.toString()));
	}
/*
	var logVisit = readCookie('startingPoint')
	if(!logVisit){
		var p = window.location.pathname;
		var c = generateHash(p)
		createCookie('startingPoint',c);
		$.historyLoad(c);
	}*/

}

var seamlessWeb = function(){
	if(!ajaxEnabled()){
		return false;
	}
	
	var c = $('.content_wrapper');
	var a = $('a:not(.noajax, .noajax a, .actions a, #footer a, #reviews a, .sidebar h4 a, #nutInfoLink, #whyUseRKlink, .videolist a, .unfriendlylink, .closeOverlay, .boxprint a, .boxremove a)');
	a.click(function(e){
		var url = this.href;
		if(url.indexOf(window.location.hostname) == -1){
			window.location = url;
			return false;
		}
		
		var qs = (url.indexOf('?') == -1) ? '?' : '&';
		qs += 'ajax=true';
		url += qs;
		scootchFlash();
		e.preventDefault();
		$.historyLoad(generateHash(url));
	});

};

var initReviews = function(skipX){
	var skipX = skipX || 0;
	var x = $('.review_highlight');
	if(x.length > 0 && skipX == 0){
		var ts = '&ts=' + new Date().getTime();
		//$.get('get_Reviews.aspx?recipe_id='+ currentRecipeId + ts,function(data){
		//	    $("#reviews").replaceWith(data);
		//		seamlessMethods();
		//})
		$('#reviews')[0].scrollIntoView();
		var box = $('#all_reviews');
		var rev1 = $('.review_entry:eq(0)');
		//x.insertBefore(rev1).show();
		x.show();
		$(".review_entry:not(.review_highlight)").hide("fast");	
	}
	else{
		if(x.length > 0){
			$(".review_entry:not(.review_highlight)").slideToggle("fast");						
		}
		else{
			$(".review_entry:gt(0)").slideToggle("fast");			
		}
	}
};

var ajaxHistoryLoad = function(data, dataFlag){
	var c = $('.content_wrapper');
	var callback = function(){window.scroll(0,0); swapSidebars(); seamlessMethods()}
	if(typeof(dataFlag) == 'undefined'){
		var ts = '&ts=' + new Date().getTime();
    	var hash = (typeof(data) != 'undefined') ? data : window.location.hash.substring(1);
		hash+='.aspx?ajax=true'+ts;
		c.load(hash, callback);
	}
	else{
		c.html(data, callback);
	}
}

var flashLayout = function(){
	/* Scattered throughout RK.com. Remove calls when time allows.*/
	return true;
}

var reloadRecipeBox = function(url){
	var url = url || '/get_SidebarRecipeBox.aspx';
	$.get(url,function(data){
	    $("#recipebox_box").replaceWith(data)
		if(window.location.hash == "#/RecipeBox"){
			var ts = "";
			if(document.all){
				ts = '?ts=' + new Date().getTime();
				window.location = "/" + ts + "#/Default";
			}
		    else{
				window.location.hash = "#/Default";
			}
		}
		prepActions();
	});
	return false;
};

function initAjaxForm(){
    var buttonClicked;
    $("form.ajax input[type=submit]").click(function(){
        buttonClicked = "&" + $(this).attr("name") + "=" + $(this).attr("value");
    });
    
    $("form.ajax").unbind("submit").submit(function(){
        var url = $(this).attr("action");
        url = url.charAt(0) == '/' ? url : '/' + url;
        $.post(url, $(this).serialize() + buttonClicked, function(data){
        	var c = $('#home_content').length == 0 ? $('.content_wrapper') : $('#home_content');
            c.html(data); swapSidebars(); initReviews();
        }, "text");
        return false;
    });
}

function initAjaxFormOverlay(){
    var buttonClicked;
    $("form.ajax input[type=submit]").click(function(){
        buttonClicked = "&" + $(this).attr("name") + "=" + $(this).attr("value");
    });
    
    $("form.ajax").unbind("submit").submit(function(){
        var url = $(this).attr("action");
        url = url.charAt(0) == '/' ? url : '/' + url;
        $.post(url, $(this).serialize() + buttonClicked, function(data){
        	$("#overlayblock").html(data); initReviews();
        }, "text");
        return false;
    });
};

var ie6PNG = function(){
	if(document.all && !window.XMLHttpRequest){
		DD_belatedPNG.fix('.png, #wrapper, .wrapper_parts, #lifestyle img, .sidebar h4');
		return true;
	}
	return false;
}

function fixIEBottom(){
	if(document.all){
		if(!$('#recipe_bot')[0]){
			return false;
		}
		var h = $('#content_stroke').height();
		var img = $('#recipe_bot')[0].offsetTop;
		if((h-7) != img){ //Img is 7px tall.
		   var newPos = h+'px';
		   $('#recipe_bot').css('bottom','');
			$('#recipe_bot').css('top',newPos);
		}
	}
	return true;
}