function printpage() {
window.print();  
}


// modal window setup
$().ready(function() {

  //window.Order = new Order( );
  
  var restaurant = $("a.pop");
  var menuItem = $(".menu-item");
  var summary = $(".summary");
    
  // also add "pointer" mouseover to img
  restaurant.css ("cursor", "pointer");
  var map = $("#newregion");
  
  $('#restaurantinfo').jqm ({
    onShow: function (h) {
      h.o.fadeIn (500);
      h.w.fadeIn (500);
    },
    onHide: function (h) {
      h.o.fadeOut (200);
      h.w.fadeOut (500);
    },
    ajax: '@alt',
    target: '.body'
  })
  .jqmAddTrigger (restaurant);
  
  $('#menu-item-summary').jqm ({
    onShow: function (h) {
      h.o.fadeIn (500);
      h.w.fadeIn (500);
    },
    onHide: function (h) {
      h.o.fadeOut (200);
      h.w.fadeOut (500);
    },
	ajax: '/order/menu_item_summary.php',
    target: '.body'
  }).jqmAddTrigger (summary);
  
  $('#menu-item-details').jqm ({
    onShow: function (h) {
      h.o.fadeIn (500);
      h.w.fadeIn (500);
    },
    onHide: function (h) {
      h.o.fadeOut (200);
      h.w.fadeOut (500);
    },
    //ajax: '/dynamic/menu-item-details.php?dish_id=' + 2,
	ajax: '@name',
    target: '.body'
  });
  //.jqmAddTrigger (menuItem);

  setUpMenu();
  

    //$("label.overlabel").overlabel();

/*	$('#addreview').submit(function() {
	          // now we're going to capture *all* the fields in the
	          // form and submit it via ajax.

	          // :input is a macro that grabs all input types, select boxes
	          // textarea, etc.  Then I'm using the context of the form from 
	          // the initial '#contactForm' to narrow down our selector
	          var inputs = [];
	          $(':input', this).each(function() {
	            inputs.push(this.name + '=' + escape(this.value));
	          })
			
			
	          // now if I join our inputs using '&' we'll have a query string
	          jQuery.ajax({
	            data: inputs.join('&'),
	            url: this.action,
	            timeout: 2000,
	            error: function() {
	              console.log("Failed to submit");
	            },
	            success: function(r) { 
	              //alert(r);
				//$('#addreviewwrap').html(r);
				
	            }
	          }) // checkout http://jquery.com/api for more syntax and options on this method.


	          // re-test...
	          // by default - we'll always return false so it doesn't redirect the user.
	          return false;
	        });
*/


     /* $('.starrating').rating({
		focus: function(value, link){
			var tip = $('#startip');
			tip[0].data = tip[0].data || tip.html();
			tip.html(link.title || 'value: '+value);
		},
		blur: function(value, link){
			$('#startip').html('&nbsp;');
		} 
	}); */





});


function orderQuantity( val, field )
{
  $('#'+field).attr("value", '$'+val);
}

function refreshStock(val,cur) {
  var sel = $('#stock'+cur)[0].selectedIndex;
  $('.stock').css('display','none');
  $('#stock' + val).css('display','block');
  $('#stock' + val)[0].selectedIndex = sel;
  currentStock = val;
  updatePriceByQuantity('total1');


}

function updatePriceByQuantity(field) {
  
  var stock = $('#stock'+currentStock+' option:selected').val();
  var quantity = $('#quantitytext').val();
//  alert(currentStock + ' ' + stock + ' ' + quantity);
  $('#'+field).attr("value", '$'+addCommas(stock*quantity));

}

function changeSizeStock(val,cur) {
  updatePriceByQuantity('total1');

}

function refreshQuantity(val,cur) {
  var sel = $('#quantity'+cur)[0].selectedIndex;
  $('.quantity').css('display','none');
  $('#quantity' + val).css('display','block');
  $('#quantity' + val)[0].selectedIndex = sel;

  orderQuantity($('#quantity'+val+' option:selected').val(),'total1');

}

function addCommas(nStr)
{
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

function regionText(txt){
  $(".regionname").text (txt);
}

function swapImg (name){
  $("#california").attr("src","/images/maps/california-" + name + ".gif");
  $("#regionimg").attr("src","/images/maps/region-" + name + ".gif");
}


function clearValue(e,v) {
  if (v.test(e.value)) {
    e.value = '';
    $(e).addClass (jsColorClass);
  }
}

function replaceValue(e,v) {
  if (/^\s*$/i.test (e.value) || /^any\s*$/i.test (e.value)){
    e.value = v;
    $(e).removeClass (jsColorClass);
  }
}

function city (n,w) {
  var q = "" + $.query.set ('city', n);  
  /* var topdir = (w == 'winery' ? 'californiawines' : 'californiarestaurantguide');
  window.location.href = '/' + topdir + '/' + n + 'restaurants/' + q; */
  window.location.href = '/index.php' + q + '&type=dynamic&page=search&state=ca';
}

function checkdiff (e){
  /any/i.test(e.value) ? $(e).removeClass (jsColorClass) : $(e).addClass (jsColorClass) ;
}

function formatCurrency(num) {
  var num = num.toString().replace(/\$|\,/g,'');
  if(isNaN(num))
    num = "0";
    
  var sign = (num == (num = Math.abs(num)));
  num = Math.floor(num*100+0.50000000001);
  
  var cents = num%100;
  num = Math.floor(num/100).toString();
  
  if(cents<10)
    cents = "0" + cents;
    
  for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
    num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));
  
  return (((sign)?'':'-') + '$' + num + '.' + cents);
}


function serialize( inp ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Arpad Ray (mailto:arpad@php.net)
    // *     example 1: serialize(['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: 'a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}'
 
    var getType = function( inp ) {
        var type = typeof inp, match;
        if(type == 'object' && !inp)
        {
            return 'null';
        }
        if (type == "object") {
            if(!inp.constructor)
            {
                return 'object';
            }
            var cons = inp.constructor.toString();
            if (match = cons.match(/(\w+)\(/)) {
                cons = match[1].toLowerCase();
            }
            var types = ["boolean", "number", "string", "array"];
            for (key in types) {
                if (cons == types[key]) {
                    type = types[key];
                    break;
                }
            }
        }
        return type;
    };
 
    var type = getType(inp);
    var val;
    switch (type) {
        case "undefined":
            val = "N";
            break;
        case "boolean":
            val = "b:" + (inp ? "1" : "0");
            break;
        case "number":
            val = (Math.round(inp) == inp ? "i" : "d") + ":" + inp;
            break;
        case "string":
            val = "s:" + inp.length + ":\"" + inp + "\"";
            break;
        case "array":
            val = "a";
        case "object":
            if (type == "object") {
                var objname = inp.constructor.toString().match(/(\w+)\(\)/);
                if (objname == undefined) {
                    return;
                }
                objname[1] = serialize(objname[1]);
                val = "O" + objname[1].substring(1, objname[1].length - 1);
            }
            var count = 0;
            var vals = "";
            var okey;
            for (key in inp) {
                okey = (key.match(/^[0-9]+$/) ? parseInt(key) : key);
                vals += serialize(okey) +
                        serialize(inp[key]);
                count++;
            }
            val += ":" + count + ":{" + vals + "}";
            break;
    }
    if (type != "object" && type != "array") val += ";";
    return val;
}

var hideMenu = "";
function setUpMenu()
{
  $(".order .menutimes li").click(function(){
    $(".order .menutimes li").css("font-weight","normal");
    $(".order .menutimes li").removeClass("orange");
    
    $(this).addClass("orange");
    $(this).css("font-weight","bold");
    
    var text = $(this).text();
    text = text.substr(0,text.indexOf(" ")).toLowerCase();
    
    $("#menutime").attr("value", text);
  });
  
  
  $('.menu-item').mouseover(function(){
    $(this).css("background-color","#eeeeee");
  });
  $('.menu-item').mouseout(function(){
    $(this).css("background-color","#ffffff");
  });
  
  /*$('.menu-item').draggable({helper:'clone'});
  
  
  $("#summary-container").droppable({
  	accept: ".menu-item",
  	tolerance: 'touch',
  	activeClass: 'droppable-active',
  	hoverClass: 'droppable-hover',
  	drop: function(ev, ui) {
  		$(this).append("<br>Dropped!");
  		alert("foo!")
  	}
  });*/
  
  //$("#item-choices").jqm()
  //.jqmAddTrigger ($('#menu li:not(li.parent)'));
  
  //tabs for ordering
  //$('#menu > ul').tabs({ fx: { opacity: 'toggle' } });
  
  //$("#menu .box :nth-child(even)").toggle();
  $("#menu .box :nth-child(odd)").click(function(o){
    $($(this).attr("alt")).slideToggle();
  });
}

$(function(){
    $('input').keydown(function(e){
        if (e.keyCode == 13) {
            $(this).parents('form').submit();
            return false;
        }
    });
});

