var xmlrpc = importModule('xmlrpc');
function $() 
{
	 var elements = new Array();
	 for (var i = 0; i < arguments.length; i++) 
	 {
		  var element = arguments[i];
		  if (typeof element == 'string')
		  {
			   element = document.getElementById(element);
		  }
		  if (arguments.length == 1)
		  {
			   return element;
		  }
		  elements.push(element);
	 }
	 return elements;
}

function getCookie( check_name ) 
{
	 // first we'll split this cookie up into name/value pairs
	 // note: document.cookie only returns name=value, not the other components
	 var a_all_cookies = document.cookie.split( ';' );
	 var a_temp_cookie = '';
	 var cookie_name = '';
	 var cookie_value = '';
	 var b_cookie_found = false; // set boolean t/f default f
	
	 for ( i = 0; i < a_all_cookies.length; i++ )
	 {
		  // now we'll split apart each name=value pair
		  a_temp_cookie = a_all_cookies[i].split( '=' );
		
		
		  // and trim left/right whitespace while we're at it
		  cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
		  // if the extracted name matches passed check_name
		  if ( cookie_name == check_name )
		  {
			   b_cookie_found = true;
			   // we need to handle case where cookie has no value but exists (no = sign, that is):
			   if ( a_temp_cookie.length > 1 )
			   {
					cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			   }
			   // note that in cases where cookie is initialized but no value, null is returned
			   return cookie_value;
			   break;
		  }
		  a_temp_cookie = null;
		  cookie_name = '';
	 }
	 if ( !b_cookie_found )
	 {
		  return null;
	 }
}				

serverURL = '';
var ptCount = Array();
var ptDefaults = [];
var usedDefaults = [];
var lastCategory = '';
var lastSubCategory = '';
var lastColour = '';

var checkForSessionExpiration = function(scr){
	 if(typeof scr.redirect != 'undefined' && scr.redirect){ //response has a redirect property and it is true; redirect, return.
	 	 window.location = '/';
	 	 return;
	 } else{ //response does not have a redirect property, orresponse has redirect property, but it is false; return
	 	 return;
	 }
}

function getSubCategories(restId, menuId, catId)
{
	 scs = getEl('subcategorystrip');
	 um = scs.getUpdateManager();
	 um.update('/mp/pub/getSubCategories', {restid:restId, menuid_in:menuId, current_catid:catId});
	 
}

function loadSubCategory(obj, catId, menuId)
{
	 var restid = Request.QueryString("restid");
   
	 if(lastSubCategory)
	 {
		  var pn = getEl(lastSubCategory.parentNode);
		  pn.removeClass('on');
	 }
	 var pn = getEl(obj.parentNode);
	 pn.addClass('on');
	 lastSubCategory = obj;

	 if (menuId == -2) {
		  window.location = '/mp/management/redirector?catid=' + catId;
		  return;
	 }
	 if (menuId == -3) {
		  window.location = '/mp/patrons/userPage/index?catid=' + catId;
		  return;
	 }

	 updateCategoryTitle(catId);
	 gallery = getEl('contentBody');
	 gum = gallery.getUpdateManager();
	 gum.update(
		  '/mp/patrons/getCategoryItemsList?restid='+restid+'&catid='+catId+'&menuid='+menuId, '',
		  function() {
			   try { enableTooltips("thumbs"); } catch(e) {;}
			   pizza = $('itemDetails');
			   if(pizza)
			   {
					try {
						 pizza.innerHTML = ''; /* *** item detail will go here *** */
					} catch(e) { ; }
					
			   }
		  }
		  );
}

function updateCategoryTitle(catid)
{
	 scs = getEl('main_panel_title');
	 um = scs.getUpdateManager();
	 um.update('/mp/patrons/getCategoryTitle?catid='+catid);
}

function loadCategory(obj, catId, menuId)
{
	 var restid = Request.QueryString("restid");
	 if(catId == 65531){
		  window.location = '/mp/patrons/ordering?restid=' + restid;
		  return;
	 }
	 var service = new xmlrpc.ServiceProxy(serverURL, ['getCategoryTitle', 'getCategoryItemsList', 'getSubCategories']);

	 if(lastCategory)
	 {
		  var pn = getEl(lastCategory.parentNode);
		  pn.removeClass('on');
		  scStrip = $('subcategorystrip');
		  scStrip.innerHTML = '';
		  scStrip.style.display = 'none';
	 }
	 var pn = getEl(obj.parentNode);
	 pn.addClass('on');
	 lastCategory = obj;
	 lastSubCategory = '';

	 if (menuId == -2) {
		  window.location = '/mp/management/redirector?catid=' + catId;
		  return;
	 }
	 if (menuId == -3) {
		  window.location = '/mp/patrons/userPage/index?catid=' + catId;
		  return;
	 }

	 updateCategoryTitle(catId);

	 subCatResults = service.getSubCategories(restid, catId, menuId);
	 checkForSessionExpiration(subCatResults);
	 if(subCatResults.html)
	 {
		  scStrip = $('subcategorystrip');
		  scStrip.innerHTML = subCatResults.html;
		  scStrip.style.display = '';
		  active = subCatResults.active;
		  ele = $(active);
		  objs = active.split('_');
		  loadSubCategory(ele, objs[3], objs[2]);
	 }
	 else
	 {		  
		  gallery = getEl('contentBody');
		  gum = gallery.getUpdateManager();
		  gum.update(
			   '/mp/patrons/getCategoryItemsList?restid='+restid+'&catid='+catId+'&menuid='+menuId, '',
			   function(){
					enableTooltips("thumbs");
					try {
						 pizza = $('itemDetails');
						 pizza.innerHTML = ''; /* *** item detail will go here *** */
					} catch (e) {
						 ;
					}
			   }
			   );
	 }
}

function postRound()
{
	 scroll(0,0);
	 Nifty('div.titleSide');
	 Nifty('div.titleSide2');
	 Nifty('ul.bcheckout a,ul.bvieworder a',"small transparent");
	 Nifty('div.orderSummary');
	 initialRun();
}


function reloadCart(miniCartHTML)
{
	 var miniCart;
	 miniCart = $('MiniCartSection');
	 miniCart.innerHTML = miniCartHTML;
}


num_onAddItemActions = 0;
onAddItemActions = new Array( 100 );

var minCounts;

function add_onAddItemAction( func ) {
	 alert(func);
	 onAddItemActions[num_onAddItemActions] = func;
	 num_onAddItemActions++;
}

function checkFormItem(ids, minCount, setName, setType)
{
	 var currentCount = 0;
	 var i = 0;

	 if(setType == 'radio')
	 {
		  var vals = document.getElementsByName(setType+'_'+ids);
		  for(i = 0; i < vals.length; ++i)
		  {
			   if(vals[i].checked)
			   {
					currentCount += 1;
					break;
			   }
		  }
	 }
	 else if(setType == 'droplist')
	 {
		  var vals = $(setType+'_'+ids);
		  var val = vals.options[vals.selectedIndex];
		  val = parseInt(vals.value);
		  if(val > 0)
		  {
			   currentCount += 1;
		  }
     
	 }
	 else if(setType == 'check')
	 {
		  for(i = 0; i < ids.length; ++i)
		  {
			   var vals = $(setType+'_'+ids[i]);
			   if(vals.checked)
			   {
					currentCount += 1;
			   }
		  }
	 }

	 else if (setType == 'styze')
	 {
		  var vals = document.getElementsByName(ids);
		  for(i = 0; i < vals.length; ++i)
		  {
			   if(vals[i].type == "select-one")
			   {
					if(vals[i].options[vals[i].selectedIndex].value)
					{
						 currentCount += 1;
					}
			   }
         
			   else if(vals[i].checked)
			   {
					currentCount += 1;
			   }
		  } 
	 }
	 else
	 {
		  for(i = 0; i < ids.length; ++i)
		  {
			   if(setType != 'droplist' && setType != 'pizzatopping')
			   {
					if($(setType+'_'+ids[i]).checked)
					{
						 currentCount++;
					}
			   }
			   else if (setType != 'pizzatopping')
			   {
					if($(setType+'_'+ids/*[i]*/).selected)
					{
						 currentCount++;
					}
			   }
		  }
	 }

	 if(currentCount < minCount)
	 {
		  if(setType != 'styze')
		  {
			   if (minCount == 1)
			   {
					alert('Please choose a ' + setName + '.' );
			   }
			   else
			   {
					alert('Please choose at least ' + minCount + ' ' + setName + '.');
			   }
		  }
		  else
		  {
			   alert('Please choose ' + setName + '.');
		  }
		  return false;
	 }
	 return true;
}

function orderingAddItemCallback(element, success)
{
	 loadCart();

	 if(!success)
	 {
		  alert("Problem with item");
	 }

}
function exec_onAddItemActions() 
{
	 for(var i = 0; i < minCounts.length; i++)
	 {
		  var ids = minCounts[i][0];
		  var minCount = minCounts[i][1];
		  var setName = minCounts[i][2];
		  var setType = minCounts[i][3];

		  try
		  {
			   if(!checkFormItem(ids, minCount, setName, setType))
			   {
					return false;
			   }
		  }
		  catch(e)
		  {
			   alert(e);
			   return false;
		  }
	 }
	 // document.forms['ordering_add_form'].submit();
	 return true;
}

function clear_onItemActions()
{
	 num_onAddItemActions = 0;
	 minCounts = new Array(0);
	 onAddItemActions = new Array( 100 );
	 ptCount[0] = new Array( 4 );
	 ptCount[1] = new Array( 4 );
	 ptCount[0]['l'] = 0;
	 ptCount[0]['r'] = 0;
	 ptCount[0]['w'] = 0;
	 ptCount[0]['d'] = 0;

	 ptCount[1]['l'] = 0;
	 ptCount[1]['r'] = 0;
	 ptCount[1]['w'] = 0;
	 ptCount[1]['d'] = 0;
	 ptDefaults = [];
	 usedDefaults = [];
}

function checkCheckBoxCount(obj, minCount, maxCount, setName, elements)
{
	 var currentCount = 0;
	 var e;

	 for(var i = 0; i < elements.length; ++i)
	 {
		  if(obj.form['check_'+elements[i]].checked)
		  {
			   currentCount++;
		  }
	 }
	 if(currentCount > maxCount)
	 {
		  alert('Please choose '+maxCount+' '+setName+' or less.');
		  obj.checked = false;
		  return false;
	 }
	 return true;
}

var lastItem;
var lastCat;
var lastMenu;
var saveDetail;
var saveScripts;

var previous_size = '';

function getDivsByClassName(divClassName) 
{
	 var allDivs = document.getElementsByTagName('div');
	 var matchingDivs = new Array();
	 var currentDiv;
	 for (var i = 0; i < allDivs.length; i++)
	 {
		  if ((currentDiv = allDivs[i]).className.search(divClassName) > -1)
		  {
			   matchingDivs.push(currentDiv);
		  }
	 }
	 return matchingDivs;
}

function clearModifierSizes()
{
	 if(!previous_size)
	 {
		  return;
	 }
	 var ids = getDivsByClassName('mod_size_'+previous_size);
	 for (var i = 0; i < ids.length; i++)
	 {
		  ids[i].style.display="none"; 
	 }
}

function updateModifierSizes(sizeId)
{
	 clearModifierSizes();
	 ids = getDivsByClassName('mod_size_'+sizeId);
	 for (var i = 0; i < ids.length; i++)
	 {
		  ids[i].style.display="inline"; 
	 } 
	 previous_size=sizeId;
}

function getItemSizePrice(itemId, catId, menuId, restId, isdelivery, sizeId, radioOption)
{
	 if(sizeId){
		  var service = new xmlrpc.ServiceProxy(serverURL, ['getItemPrice_xtd_xmlrpc']);
		  var itemPrice = service.getItemPrice_xtd_xmlrpc(itemId, catId, menuId, restId, isdelivery, sizeId);
		  var itemPriceTag = $('nameAndPricePrice');
		  itemPriceTag.innerHTML = '';
		  if(itemPrice)
		  {
			   itemPriceTag.innerHTML = itemPrice;
			   updateModifierSizes(sizeId);
			   return true;
		  }
		  return true; // Allow them to select a size anyway 
	 }
	 return true; // Allow them to select a size anyway
}

function getRelatedItems(itemId, catId, menuId, restId)
{
	 var service = new xmlrpc.ServiceProxy(serverURL, ['getRelatedItems']);
	 var detail_html = service.getRelatedItems(itemId, catId, menuId, restId);

	 loadCart();

	 if(detail_html[0])
	 {
		  details = $('itemDetails');
		  details.innerHTML = detail_html;
	 }
}

function getItemDetail(itemId,catId,menuId)
{
	 var restid = Request.QueryString("restid");
	 var service = new xmlrpc.ServiceProxy(serverURL, ['getItemDetail']);

	 var detail_html = service.getItemDetail("" + restid, itemId, catId, menuId);

	 fState = true;

	 if(detail_html[0])
	 {
		  // var pizza = YAHOO.ext.DomHelper;
		  // pizza.overwrite('itemDetails', {html: detail_html[0]});
		  pizza = $('itemDetails');
		  pizza.innerHTML = detail_html[0];
		  saveDetail = detail_html[0];
		  clear_onItemActions();
		  minCounts = detail_html[1];
		  lastItem = itemId;
		  lastCat = catId;
		  lastMenu = menuId;   
		  var scripts = detail_html[2];
		  if(scripts)
		  {
			   saveScripts = scripts;
			   eval(scripts);
		  }
		  else
		  {
			   saveScripts = '';
		  }
		  if(getCookie('__ac')) { // Don't do button stuff if we're not logged in
			   btn.init();
		  }
	 }
	 else
	 {
		  window.location.reload();
	 }
}


function loadCart()
{
	 var pizza = $('itemDetails');
	 if(pizza)
	 {
		  try { 
			   pizza.innerHTML = ''; 
		  } 
		  catch(e) { ; }
	 }

	 cart = getEl('MiniCartSection');
	 if(cart)
	 {
		  um = cart.getUpdateManager();
		  if(um)
		  {
			   um.update('/mp/patrons/getMiniCart2000', {}, postRound);
		  }
	 }
	 return true;
}

function setOurServerURL(server)
{
	 serverURL = server;
}

// ptCount is a global dictionary

ptCount[0] = new Array( 4 );
ptCount[1] = new Array( 4 );

ptCount[0]['l'] = 0;
ptCount[0]['r'] = 0;
ptCount[0]['w'] = 0;
ptCount[0]['d'] = 0; // default

ptCount[1]['l'] = 0;
ptCount[1]['r'] = 0;
ptCount[1]['w'] = 0;
ptCount[1]['d'] = 0;


function isDefault(optid)
{
	 for(var i = 0; i < ptDefaults.length; ++i)
	 {
		  if(String(ptDefaults[i]) == String(optid))
		  {
			   return(!usedDefaults[String(optid)]);
		  }
	 }
	 return(false);
}

function isUsedDefault(optid)
{
	 for(var i = 0; i < ptDefaults.length; ++i)
	 {
		  if(String(ptDefaults[i]) == String(optid))
		  {
			   return(usedDefaults[String(optid)]);
		  }
	 }
	 return(false);
}

function setPizzaToppingDefaults(defaults)
{

	 usedDefaults = new Array(defaults.length);
	 for(var i = 0; i < defaults.length; ++i)
	 {
		  usedDefaults[String(defaults[i][0])] = true;
		  ptDefaults[i] = defaults[i][0];
		  aval = document.getElementById('wpt' + defaults[i][1] + '_' + i + '_val');
		  aval.value = defaults[i][0];
	 }
}

function pt_addTopping( section, option, maxCount, optid, optname, sets)
{
	 var val_ids = new Array(maxCount + ptDefaults.length);

	 var defaultItem = isDefault(optid);
	 if (ptCount[sets][section] >= maxCount)
	 {
		  if(section != 'w')
		  { 
			   return;
		  }
		  if(!defaultItem)
		  {
			   return;
		  }
	 }

	 for(var i = 0; i < maxCount + ptDefaults.length; ++i)
	 {
		  val_ids[i] = section + 'pt' + option + '_' + i + '_val';
	 }

	 var pickList = $(section+'PizzaSelect_'+sets);
	 var pickOptions = pickList.options;
	 var pickOLength = pickOptions.length;
	 pickOptions[pickOLength] = new Option(optname);

	 if(defaultItem)
	 {
		  // section = 'd';
		  usedDefaults[String(optid)] = true;
	 }
	 var aval;
	 for(i = 0; i < val_ids.length; ++i)
	 {
		  aval = document.getElementById(val_ids[i]);
		  if (String(aval.value) == "-1")
		  {
			   break;
		  }
	 }
	 pickOptions[pickOLength].value = val_ids[ptCount[sets][section]];
	 // aval = document.getElementById( val_ids[ ptCount[sets][section] ] );
	 aval.value = optid;
	 if(!defaultItem)
	 {
		  ptCount[sets][section]++;
	 }
}

function pt_onDelete( section, sets )
{
	 var pickList = $(section+'PizzaSelect_'+sets);
	 var pickOptions = pickList.options;
	 var pickIndex = pickList.selectedIndex;
	 if(pickIndex > -1)
	 {
		  var optValue = pickOptions[pickIndex].value;
		  pickOptions[pickIndex] = null;
		  var aval = document.getElementById( optValue );

		  if (section == 'w' && isUsedDefault(String(aval.value)))
		  {
			   usedDefaults[String(aval.value)] = false;
		  }
		  else
		  {
			   ptCount[sets][section]--;
		  }
		  aval.value = -1;  
	 }
}

function cancelItemOrder()
{
	 try {
		  var pizza = $('itemDetails');
		  pizza.innerHTML = '';
	 } catch(e) {
		  ;
	 }

	 scroll(0, 0);
}
