function getCookie(c_name)
{
	if (document.cookie.length>0)
	  {
	  c_start=document.cookie.indexOf(c_name + "=");
	  if (c_start!=-1)
		{ 
		c_start=c_start + c_name.length+1; 
		c_end=document.cookie.indexOf(";",c_start);
		if (c_end==-1) c_end=document.cookie.length;
		return unescape(document.cookie.substring(c_start,c_end));
		} 
	  }
	return "";
}

function initNewsletter(){
	var newsletter_wrp = $("#newsletter-wdgt");
	var newsletter = $("div.content",newsletter_wrp);
	var homepage = $("body").hasClass("homepage");
	var news_email_width = "268px";
	var news_email_width_orig = "196px";
	var news_email_inner_width = "250px";
	var news_email_inner_width_orig = "171px";
	var news_email_height = "53px";
	var news_email_height_orig = homepage ? 131 : 170;
	if($.browser.msie) news_email_height = "53px";
	$("#newsletter_email").origText();

	newsletter_wrp.click(function(e){ 
		e.stopPropagation(); 
		if(newsletter.height() != news_email_height_orig){
			mp_event({"name":"Newsletter Click","type":"click","este":this});
			newsletter.animate({"height": news_email_height_orig + "px"},300,function(){ $("dl",newsletter).fadeIn("fast"); });
			if(!homepage){
				$("#newsletter_email").parent().animate({"width":news_email_width},600,function(){
					$("#newsletter_email").css("width",news_email_inner_width);
				});
			}
			
	
			$("body").click(function(){
				$("dl",newsletter).fadeOut("fast",function(){
					newsletter.animate({"height":news_email_height},400);
					if(!homepage) $("#newsletter_email").css("width",news_email_inner_width_orig).parent().animate({"width":news_email_width_orig},250);
				});
				$(this).unbind("click");
			});
		}
	});

	$("#newsletter_email").focus(function(){ newsletter_wrp.click(); });
	
	$("div.sign-up a",newsletter).click(function(){
		var newsletter_email = document.getElementById("newsletter_email");
		var daily_food_news = document.getElementById("daily_food_news");
		var validEmail = (newsletter_email.value.search(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i) >= 0) ? true : false;
		var jqT = $(newsletter_email);
		
		if(newsletter_email.value == ""){
			callError(jqT, "Please enter Email");
		} else if(!validEmail) {
			callError(jqT, "Please enter valid Email");
		} else {
			$(".loading",newsletter).show();
			$.get("/newsletter/subscribe",$("form",newsletter).serialize(),function(r){
				if(r[32]=="0"){
					$("form",newsletter).fadeOut("slow",function(){
						newsletter.unbind("click").animate({"height":"125px"},500);
						$(".thanks",newsletter).fadeIn("fast");
					});
					newsletter_wrp.unbind("click");
					$("body").unbind("click");
				} else {
					callError(jqT, "Email is already registered");
				}
				$(".loading",newsletter).hide();
			});
		}

		return false;
	});
	
	function callError(input, msg){
		input.val(msg).addClass("error").focus(function(){
			this.value = "";
			input.removeClass("error");
		});
	}

}

location.querystring = (function() {  
  
    // The return is a collection of key/value pairs  
  
    var result = {  
	    toString: function() {  
	        var querystring = "?";  
	        for (var key in location.querystring)  
	        {  
	            if (key && key != "toString" && location.querystring[key] != null) {
	                querystring += key + "=" + location.querystring[key] + "&";  
	             }
	        }  
	        // remove trailing &
	        return querystring.substr(0, querystring.length-1);  
	    }  
	};	  
  
    // Gets the query string with a preceeding '?'  
  
    var querystring = location.search;  
  
    // document.location.search is empty if a query string is absent  
  
    if (!querystring)  
        return result;  
  
    // substring(1) to remove the '?'  
  
    var pairs = querystring.substring(1).split("&");  
    var splitPair;  
  
    // Load the key/values of the return collection  
  
    for (var i = 0; i < pairs.length; i++) {  
        splitPair = pairs[i].split("=");  
        result[splitPair[0]] = splitPair[1];  
    }  
  
    return result;  
})();

var iaz_preserved_elements = [];
var iaz_preserved_zindexes = [];
function ie_apply_zindex(element_id, zindex, context_id) {
   // default values
   if (undefined == zindex) { zindex = 1; }
   var context = (undefined == context_id) ? $(context_id) : $("body");
   var element = $(element_id);

   for (i = iaz_preserved_elements.length-1; i >= 0; i--) {
      iaz_preserved_elements[i].css({'z-index': iaz_preserved_zindexes[i]});
   }
   iaz_preserved_elements = [];
   iaz_preserved_zindexes = [];


   // find relative-positioned ancestors of element within context
   element.parents().each(
      function(ancestor) {
         if ('relative' == $(this).css('position')) {
            // apply z-index to ancestor
			iaz_preserved_elements.push($(this));
			iaz_preserved_zindexes.push( $(this).css('z-index') );

 			$(this).css({'z-index': zindex});
         }
         if ($(this) == context) { throw $break; }
      }
   );
}

/*
* This function handles the query string management
* for search results sorting
*/
function funcSort(strParam){
    loc = location.toString();
    var ns = null;

    if (loc.indexOf("/sort") > 1){
        orig = loc.substr(0, loc.indexOf("sort"));
	   ns = loc.substr(loc.indexOf("/sort"), loc.length);
    
		// if same param is coming in, change sort val
		if (ns.indexOf('-') > -1 && ns.indexOf(strParam) == -1){
		  strParam = strParam + "-1";
		} else if ((ns.indexOf('0') > -1)) {
		  strParam = strParam + "-1";
		}
		else {
		  // else just default new param to asc
	      strParam = strParam + "-0";
		}
	}else {
	    orig = window.location;
 		strParam = strParam + "-1";
	}
	window.location = orig + "sort/" + strParam + "/";
}

function changeMealTag(id){
    var mt = document.getElementById(id).value;
    window.location = mt;
}


function changeRpp(){
	var rpp = document.getElementById("rppSelect").value;
	window.location = "/restaurants/rpp?rpp=" + rpp + "&location=" + location;
}

function changePage(pageNum){
	location.querystring["pnum"] = pageNum
	location.search = location.querystring.toString();
}

// Set the cookie
function setCookie(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+";";
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}



function onTypeAheadKeyDown(e){
   DOWN_ARROW = 40;
   var KeyID = (window.event) ? e.keyCode : e.keyCode;
   if (KeyID == DOWN_ARROW){
        taId++;
        res = document.getElementById('ta' + taId);    
   }
}

var taId = 0

function headerSearch(){
    window.location= "/restaurants/" + document.getElementById('txtHeaderSearch').value;
}

/*
* this function handles the ajax restaurant add
*/
function addMenu(restaurantId, loggedin){
	if (loggedin == 'False'){
		window.location.href="/mymenupages/login?ref=" + location.href;
	} else {
		$('#addMenu').load('/mymenupages/add?rid=' + restaurantId);
		$('#addMenu').addClass("added");
	}
	
	return false;
}


function showMoreHoods(divId, code, moreId){

	$("#" + moreId).parent().html("<li class=\"loading\"><img src=\"/gfx/loading-small.gif\" />&nbsp;loading&hellip;</li>");
	$.get("/home/getMoreHoods?code=" + code, function(html) { 
             $("#" + divId).append(html); 
			 $("#" + divId + " .loading").remove();
			 $("#" + divId + " .show-more-link").remove();
        });
 //   document.getElementById(moreId).style.display = 'none';    
 return false;
}

/*
* this function handles toggling of the dimension list
*/
function toggleDimList(id){
	// append # for jquery identifier
	jid = "#" + id;
	cdTog = document.getElementById(id+"Toggle");
	if (document.getElementById(id).style.display == 'none'){
		$(jid).slideDown();
		cdTog.innerHTML = cdTog.innerHTML.replace("expand", "collapse");
	} else {
		$(jid).slideUp();
		cdTog.innerHTML = cdTog.innerHTML.replace("collapse", "expand");
	}
}

/*
* this pops up a small help dialog
*/
function showpopupHelp(URL)
{
	var strURL="";
	strURL = URL;
	SearchWindow=window.open(strURL,'Offer','width=370,height=200,toolbar=no,location=no,directories=no,resizable=yes,status=no,menubar=no,scrollbars=yes,left=100,top=300,screenX=80,screenY=80');
	if (window.focus) {SearchWindow.focus()}
}

function showpopup()
{
	var strURL="";
	strURL = "/searchrestaurants";
	SearchWindow=window.open(strURL,'Offer','width=490,height=490,toolbar=no,location=no,directories=no,resizable=yes,status=no,menubar=no,scrollbars=yes,left=40,top=100,screenX=80,screenY=30');
	if (window.focus) {SearchWindow.focus()}
}

function showpricepopup()
{
	SearchWindow=window.open('/pricedetails','Price Details','width=500,height=160,toolbar=no,location=no,directories=no,resizable=yes,status=no,menubar=no,scrollbars=yes,left=40,top=100,screenX=80,screenY=30');
	if (window.focus) {SearchWindow.focus()}
}

function showpopupUrl(url, title)
{

	SearchWindow=window.open(url,title,'width=490,height=490,toolbar=no,location=no,directories=no,resizable=yes,status=no,menubar=no,scrollbars=yes,left=40,top=100,screenX=80,screenY=30');
	if (window.focus) {SearchWindow.focus()}
}

//.toggleText
jQuery.fn.toggleText = function(a, b) {
	return this.each(function() {
	jQuery(this).text(jQuery(this).text() == a ? b : a);
	});
};


$(document).ready(function(){
	//Switched SEO friendly links to normal ones
	$("#change-city ul li a").each(function(){ this.href = "/changecity/" + $(this).parent().attr("class"); });

	if($("#change-city .hide a").length > 0){
		$("#change-city .hide a").click(function(){
			$("#change-city").animate(
				{"height":"1px"},
				500, 
				function callback(){ 
					$(this).hide(); 
					
					}
			);
			return false;
		})[0].href="#";
	}
		
	$("#show-changecity").click(function(){
		$("#change-city").show().animate({"height":city_height},500);
		return false;
	});

	$("#change-city ul li:eq(" + (parseInt(current_city)-1) + ")").addClass("active");
	if(current_city != "")
		$("#change-city ul li:eq(" + (parseInt(current_city)-1) + ")").addClass("active");
	else {
		setTimeout("$('#show-changecity').click()",750);
		setCookie("cdvid","1");
	}
	
	$("div.info-wrp").hover(function(){
	  $(this).children("div.msg-wrp").fadeIn("fast"); 
	  if($.browser.msie) ie_apply_zindex(this,1);
	},function () {
	  $(this).children("div.msg-wrp").fadeOut("fast"); 
	});
});
function ApplyFormStyles()  
     {  
         $(':text,:password,textarea,select').focus(function() {
			 $(this).parents('li').children('.focus-msg').fadeIn("300"); 
			 $(this).parents('li').addClass('focus');
         }).blur(function() {   
			 $(this).parents('li').children('.focus-msg').hide(); 
			 $(this).parents('li').removeClass('focus');
         });  
     }  
     $(document).ready(ApplyFormStyles);  

function emailScramble () {
	$('a.scramble').each(function(){
	e = this.rel.replace('/','@');
	this.href = 'mailto:' + e;
});
}
$(document).ready(emailScramble);

function openHTMLWinSimple(t){
	HTMLWindow=window.open(t,'_blank','width=770,height=700,toolbar=no,location=no,directories=no,resizable=yes,status=no,menubar=no,scrollbars=yes,left=150,top=10,screenX=200,screenY=30');
	if (window.focus) {HTMLWindow.focus()}
}
		
function openPDFWinSimple(t){
	NewWindow=window.open(t,'_blank');
	if (window.focus) {NewWindow.focus()}
	var restaurant = document.getElementsByName("content.restaurant")[0];
	if((typeof restaurant != "undefined") && (typeof mp_event == "function")) {
		mp_event({
			"name" : restaurant.content,
			"type" : "pdfmenu",
			"este" : this
		});
	}
}

function openDisclaimer(){
	NewWindow=window.open('/disclaimer','disclaimer','width=380,height=140');
	if (window.focus) {NewWindow.focus()}
}

//function mp_openPARTNERWinSimple(t){
//	HTMLWindow=window.open(t,'partners','width=770,height=700,toolbar=no,location=no,directories=no,resizable=yes,status=no,menubar=no,scrollbars=yes,left=150,top=10,screenX=200,screenY=30');
//	if (window.focus) {HTMLWindow.focus()}
//}

function openWinSimple(pageName, pageTitle){
	NewWindow=window.open(pageName,pageTitle,'width=600,height=220');
}

jQuery.fn.origText = function(a) {
	return this.each(function() {
		var t = this.value;
		$(this).bind("blur",function(){ if(this.value=="") this.value=t; });
		$(this).bind("focus",function(){ if(this.value==t) this.value=""; });
	});
};


var partners = new Array();
partners['p5'] = {"url":"http://metromix.com", "gfx":"/images/menupages_728x60.jpg"};