function setCookie(c_name, value, expiredays)
{
   var exdate=new Date();
   exdate.setDate(exdate.getDate()+expiredays);
   document.cookie=c_name + "=" + escape(value) + ((expiredays==null) ? "" : ";expires=" + exdate.toUTCString());
}

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 getNumberOfSearchItemsInResponse(responseText)
{
  var searchString = "<!--ITEMS:";
  var qty = 0;
  var pos = responseText.indexOf(searchString);
  if(pos != -1)
  {
     qty = responseText.substring(pos + searchString.length);
     var pos2 = qty.indexOf("-->");
     if(pos2 != -1) qty = qty.substring(0, pos2);
  }
  return qty;
}

// Additional code for rounded corners
function addCorners() {
   //$(".aside").wrapInner('<div class="container"></div>');
   //$(".aside .container").css("background-image","url(" + $(".aside").find("img").attr("src") + ")");
   //$(".aside img").remove();
   $("#step1 #content .aside, #step1 #content .article, #content #filterSearch, #step2 #content #restaurants ul li, #step3 #content #basket").prepend('<div class="corners"><div class="tl"></div><div class="tr"></div><div class="br"></div><div class="bl"></div></div>');
   addMenuCorners();
}

function addMenuCorners() {
   $("#step3 #content #menu").prepend('<div class="corners"><div class="tl"></div><div class="tr"></div><div class="br"></div><div class="bl"></div></div>');
}

// Setup restaurant quick links
function restaurantQuickLinks() {
   $('#restaurantQuicklinks ul:not(#restaurantQuicklinks ul ul)').makeacolumnlists({cols: 3, colWidth: 186, equalHeight: false, startN: 1});
   $('#areaSearch #regionQuickLinks ul').makeacolumnlists({cols: 3, colWidth: 130, equalHeight: false, startN: 1});
   $('#restaurantQuicklinks ul li a:not(#restaurantQuicklinks ul li ul li a)').click(function(){
      rc = false;
      $(this).parent().find('ul').each(function(i) {
         if($(this).css('display') != 'none') rc = true;
      });
      
      if(!rc) {
         $('#restaurantQuicklinks ul li ul').css('display','none');
         $(this).parent().find('ul').each(function(i) {
            $(this).toggle();
         });
      }
      return rc;
   });
}

// Toggle region selector
function selectRegion() {
   $('#step1 #content .article .container #areaSearch form #regionQuickLinks').hide();
   $('#step1 #content .article .container #areaSearch form p a').click(function(){
      $('#step1 #content .article .container #areaSearch form #regionQuickLinks').toggle(0, function() {
         curvyCorners.redraw();
      });
      return false;
   });
}

// Toggle restaurant info
function restaurantInfo() {
   if(open == "true") $('#step3 #content #resultsHeader .restaurantInfo').hide();
   
   $('#step3 #content #resultsHeader .tools .expand').click(function(){
      if ($('#step3 #content #resultsHeader .restaurantInfo').is(":visible")) {
         $('#step3 #content #resultsHeader .restaurantInfo').slideUp('fast', function() {
            curvyCorners.redraw();
         });
         $(this).removeClass('expanded');
      } else {
         $('#step3 #content #resultsHeader .restaurantInfo').slideDown('fast', function() {
            curvyCorners.redraw();
         });
         $(this).addClass('expanded');
      }     
      
      return false;
   });
}

// Set the view menu links for the restaurants
function setViewMenuLinks() {
   $("#step2 #content #restaurants ul li").live('mouseenter',
      function() {
         $(this).addClass("hover");
      }).live('mouseleave',
      function() {
         $(this).removeClass("hover");
      }
   );
   $("#step2 #content #restaurants ul li").live('click', function() {
      window.location = ($(this).find("a").attr("href"));
   });
}

// Fix the basket position so that it floats whilst scrolling
function setBasketPosition() {
   $(window).scroll(function() {
      if($('#step3 #content #menu').offset()) {
         if (($('#step3 #content #menu').offset().top - $(window).scrollTop()) < 0 && $('#step3 #content #floatingColContainer').height() < $(window).height()) {       
            $('#step3 #content #floatingColContainer').addClass('fixed');
         } else {
            $('#step3 #content #floatingColContainer').removeClass('fixed');
         }
      }
   });
}

// Add image hover states
function imgHovers() {
   $("#step3 #content #basket .container table tr td #tblTotals tr td.qty a img").hover(
     function () {
      $(this).attr("src",this.src.replace(/.gif/g, '_hover.gif'));// mouse over image
     }, 
     function () {
      $(this).attr("src",this.src.replace(/_hover.gif/g, '.gif'));// mouse out image
     }
   );
}

function hideRestaurantCategories() {
   $(".catheading").toggle(function() {
      $(".cat_" + $(this).attr("catid")).slideDown();
   },
   function() {
      $(".cat_" + $(this).attr("catid")).slideUp();
   });
   $(".catrow").hide();
}

function restaurantSearch() {
   var delay = (function(){
      var timer = 0;
      return function(callback, ms){
         clearTimeout (timer);
         timer = setTimeout(callback, ms);
      };
   })();
   $("#restaurantSearch").focus(function() {
      if($(this).val() == "Search for a restaurant")
         $(this).val("");
   });
   $("#restaurantSearch").blur(function() {
      if($(this).val() == "")
         $(this).val("Search for a restaurant");
   });
   $("#restaurantSearch").keyup(function() {
      delay(function() {
         $("#searchingProgress").fadeIn("fast");
         $("#restaurants").fadeOut(5000);
         var ajaxURL = "/select-restaurant-ajax-handler.php?requestedLocation=" + requestedLocation + "&search=" + searchName + "&filter=" + $("#restaurantSearch").val();
         $.ajax({
            url: ajaxURL,
            success: function(data) {
               $("#searchingProgress").fadeOut("fast");
               $("#restaurants").stop(true, false).removeAttr("style").show();
               $('#restaurantscontainer').html(data);
               addCorners();
               updateSearchSummary(data);
            }
         });
      }, 500 );
   });
   $("#cuisineSearch").change(function() {
      $("#searchingProgress").fadeIn("fast");
      $("#restaurants").fadeOut(4000);
      var ajaxURL = "/select-restaurant-ajax-handler.php?requestedLocation=" + requestedLocation + "&search=" + searchName + "&cuisine=" + $("#cuisineSearch").val();
      $.ajax({
         url: ajaxURL,
         success: function(data) {
            $("#searchingProgress").fadeOut("fast");
            $("#restaurants").stop(true, false).removeAttr("style").show();
            $('#restaurantscontainer').html(data);
            addCorners();
            updateSearchSummary(data);
         }
      });
   });
}

function updateSearchSummary(data) {
   var items = getNumberOfSearchItemsInResponse(data);
   var countText = items + " Restaurant";
   if(items != 1) countText = countText + "s";
   $("#restaurantCount").html(countText);
}

function menuSearch() {
   var delay = (function(){
      var timer = 0;
      return function(callback, ms){
         clearTimeout (timer);
         timer = setTimeout(callback, ms);
      };
   })();
   $("#foodsearch").focus(function() {
      if($(this).val() == "Search for some food")
         $(this).val("");
   });
   $("#foodsearch").blur(function() {
      if($(this).val() == "")
         $(this).val("Search for some food");
   });
   $("input#foodsearch").keyup(function() {
      delay(function() {
         setCookie('restaurantToolTip', 'true', 10);
         $("#searchingProgress").fadeIn("fast");
         $("#menu").fadeOut(5000);
         var ajaxURL = "/restaurant-ajax-handler.php?open=" + open + "&rid=" + rid + "&filter=" + escape($("#foodsearch").val());
         $('div#menu').load(ajaxURL, function() {
            $("#searchingProgress").fadeOut("fast");
            $("#menu").stop(true, false).removeAttr("style").show();
            addMenuCorners();
            curvyCorners.redraw();
            removeAnchors();
         });         
      }, 500 );
   });
   $("#categorysearch").change(function() {
      setCookie('restaurantToolTip', 'true', 10);
      $("#searchingProgress").fadeIn("fast");
      $("#menu").fadeOut(4000);
      var ajaxURL = "/restaurant-ajax-handler.php?open=" + open + "&rid=" + rid + "&cid=" + $("#categorysearch").val();
      $('div#menu').load(ajaxURL, function() {
         $("#searchingProgress").fadeOut("fast");
         $("#menu").stop(true, false).removeAttr("style").show();
         addMenuCorners();
         curvyCorners.redraw();
         removeAnchors();
      });
   });
   
   if(getCookie('restaurantToolTip') != 'true') {
      $("#foodsearch").qtip({
         content: '<strong>Find food faster!</strong><br /><br />Start typing above and we will show you just the items that match what you typed. <br /><br /><em>For example, try typing \'chicken\'...</em>',
         show: {
            when: false, // Don't specify a show event
            ready: true // Show the tooltip when ready
         },
         hide: 'click',
         position: {
            corner: {
               target: 'bottomMiddle',
               tooltip: 'topMiddle'
            }
         },
         style: {
            name: 'green',
            tip: 'topMiddle'
         },
         api: {
            onHide: function() { 
               setCookie('restaurantToolTip', 'true', 10);
            }
         }
      });
      $(".qtip").click(function() {
         $(this).qtip('hide');
      });
   }
}

function menuButtons() {
   $('.addbasket a').live('click', function(){
      $("#cartbusy").show();
      var itemCode =  $(this).attr("id");
      var priceCode = $(this).attr("pricecode");
      var ajaxURL = "/_includes/carthandler.php?action=add&qty=1&rid=" + rid + "&item=" + $(this).attr("id") + "&cat=" + $(this).attr("category") + "&price=" + $(this).attr("pricecode");
      $('#basket .container').load(ajaxURL, function(){
         curvyCorners.redraw();
         updateCartItems();
         $("#price-" + itemCode + "-" + priceCode).addClass("alreadyincart");
      });
      
      return false;
   });
   
   $(".qty a").live('click', function() {
      $("#cartbusy").show();
      var qty = $(this).attr("qty");
      var itemCode = $(this).attr("item");
      var priceCode = $(this).attr("pricecode");
      var ajaxURL = "/_includes/carthandler.php?action=updateqty&rid=" + rid + "&qty=" + $(this).attr("qty") + "&index=" + $(this).attr("itemindex");
      $('#basket .container').load(ajaxURL, function(){
         curvyCorners.redraw();
         updateCartItems();
         if(qty == 0) $("#price-" + itemCode + "-" + priceCode).removeClass("alreadyincart");
      });
      
      return false;
   });
   
   $("#abandonOrder").click(function() {
      if(confirm("Are you sure you want to abandon your current order?")) {
         var ajaxURL = "/_includes/carthandler.php?action=emptycart&rid=" + rid;
         $.ajax({
            url: ajaxURL,
            success: function(data) {
               window.location.reload();
            }
         });
      }
      
      return false;
   });
   
   removeAnchors();
}

function updateCartItems() {
   $(".newitem").hide().fadeIn("slow", function() { $(this).effect("pulsate", { times: 1}, 600); });
   $(".updateditem").effect("pulsate", { times : 2 }, 500);
   $(".deleteditem").fadeOut(function() {
      curvyCorners.redraw();
   });
}

function removeAnchors() {
   $('.addbasket a').attr("href", "#");
}

function addAddress() {
   $("#rememberme").click(function() { $(".remember-item").toggle(function() { curvyCorners.redraw(); }); });
   $(".address-delete").click(function() {
      return confirm("Are you sure you want to delete this address?");
   });
}

function addCard() {
   $("#sameasdelivery").click(function() {
      $(".billingaddress").toggle("fast", function() {
         curvyCorners.redraw();
      });
   });
   
   var handlerFunc = function() {
      var cardType = $("#cardtype").val();
      if(cardType == "Switch" || cardType == "Solo") {
         $("#startdateli").show("fast")
         $("#issuenumberli").show("fast");
         $("#expirydateli").removeClass("alt");
      }
      else {
         $("#startdateli").hide("fast")
         $("#issuenumberli").hide("fast");
         $("#expirydateli").addClass("alt");
      }
   };
   
   $(".card-delete").click(function() {
      return confirm("Are you sure you want to delete this card?");
   });
   
   $("#cardtype").click(handlerFunc);
   handlerFunc();
}

function orderConfirmation() {
   $.blockUI.defaults.css = {};

   $(".submitbutton").click(function() {
      $('#_discount').val($("#discountcode").val());
      $('#_cvv').val($("#cardcv2").val());
      $('#_info').val($("#additionalinfo").val());
      
      $.blockUI({message: '<h1>Please wait while your order is sent to the restaurant...</h1><p id="longtime">Order submission is taking longer than expected. Please be patient and do not refresh the page.</p><img src="images/loading_white.gif" />'});
      window.setTimeout(function() {
         $("#longtime").slideDown("fast");
      }, 15000);
      
      return true;
   });
   
   $("#savecvv").click(function() {
      var cardcvv = $("#cardcv2").val();
      if(cardcvv.length != 3 || (cardcvv - 0) != cardcvv)
      {
         alert("Please enter a valid card security code. It should be made up of three numbers.");
      }
      else
      {
         $("#cardcvv-loading").show();
         var ajaxURL = "/order-confirmation-handler.php?method=setcvv&cvv=" + cardcvv;
         $.ajax({
            url: ajaxURL,
            success: function(data) {
               $("#cvvsection").slideUp("fast");
               $("#cvv-entered").show();
            }
         });
      }
      return false;
   });
   
   $("#applydiscount").live("click", function() {
      if($("#discountcode").val().length > 0) {
         var discountCode = $("#discountcode").val();
         $("#discount-loading").show();
         var ajaxURL = "/order-confirmation-handler.php?method=applydiscount&code=" + discountCode;
         $.ajax({
            url: ajaxURL,
            success: function(data) {
               $('#basket-and-code').html(data);
               $('#discount-updated').show().delay(3000).slideUp("slow");
            }
         });
      }
      return false;
   });
   
   $("#applyinfo").live("click", function() {
      var info = $("#additionalinfo").val();
      $("#info-loading").show();
      var ajaxURL = "/order-confirmation-handler.php?method=saveinfo&info=" + info;
      $.ajax({
         url: ajaxURL,
         success: function(data) {
            $('#basket-and-code').html(data);
            $('#additionalinfo-updated').show().delay(3000).slideUp("slow");
         }
      });
      return false;
   });
}

function pastOrders() {
   $('.expand-order, span.restaurant-link').live('click', function() {
      var orderId = $(this).attr("oid");
      var icon = $('#icon-' + orderId);
      
      $('#loading-' + orderId).show();
      
      if(icon.hasClass("expandicon")) {
         var ajaxURL = "/customer-prefs-handler.php?method=showorder&expand=true&oid=" + orderId;
         $('#order-' + orderId).load(ajaxURL, function() {
            $('input[@type=radio].star').rating();
            curvyCorners.redraw();
         });
      }
      else {
         var ajaxURL = "/customer-prefs-handler.php?method=showorder&oid=" + orderId;
         $('#order-' + orderId).load(ajaxURL, function() {
            $('input[@type=radio].star').rating();
            curvyCorners.redraw();
         });
      }
      return false;
   });
   
   $('.rate-order').live('click', function() {
      var orderId = $(this).attr("oid");
      var restaurantId = $(this).attr("rid");
      var inputs = document.getElementsByName("rating_" + orderId);
      var rating = 0;
      for (x = 0; x < inputs.length; x++) {
         if(inputs[x].checked) rating = inputs[x].value;
      }
      
      if(rating == 0) {
         alert("You didn't rate the order!");
         return;
      }
      
      $('#loading-' + orderId).show();
      
      var ajaxURL = "/customer-prefs-handler.php?method=rate&oid=" + orderId + "&rid=" + restaurantId + "&rating=" + rating;
      $.ajax({
         url: ajaxURL,
         success: function(data) {
            $('#ratingdiv_' + orderId + ' input',this.form).rating('disable');
            $('#buttons_' + orderId).html('<p>&nbsp;Thanks for your rating!</p>');
            $('#loading-' + orderId).hide();
         }
      });
   });
   
   $('.skip-order').live('click', function() {
      var orderId = $(this).attr("oid");
      var restaurantId = $(this).attr("rid");
      
      $('#loading-' + orderId).show();
      
      var ajaxURL = "/customer-prefs-handler.php?method=skip&oid=" + orderId + "&rid=" + restaurantId;
      $.ajax({
         url: ajaxURL,
         success: function(data) {
            $('#ratingdiv_' + orderId).hide();
            $('#loading-' + orderId).hide();
         }
      });
   });
}

function orderComplete() {
   $("#btn-printthispage").click(function() {
      window.print();
   });
}

function preLoadImages() {
   var cache = [];
   // Arguments are image paths relative to the current page.
   function preLoad()
   {
      var args_len = arguments.length;
      for (var i = args_len; i--;) {
         var cacheImage = document.createElement('img');
         cacheImage.src = arguments[i];
         cache.push(cacheImage);
      }
   }
   preLoad("/images/loading_white.gif");
   preLoad("/images/qty_plus.gif");
   preLoad("/images/qty_minus.gif");
   preLoad("/images/expand.gif");
   preLoad("/images/collapse.gif");
}

$(document).ready(function(){
   $("body").addClass("has_js");
   preLoadImages();
   restaurantQuickLinks();
   selectRegion();
   restaurantInfo();
   setViewMenuLinks();
   setBasketPosition();
   imgHovers();
   addCorners();
   restaurantSearch();
   menuSearch();
   menuButtons();
   addAddress();
   addCard();
   orderConfirmation();
   pastOrders();
   orderComplete();
   
   $('#postcode').focus();
});

function initStarRatings() {
   $('input[@type=radio].star').rating();
}
