//======================================================================
var soundEmbed = null;
//======================================================================
function soundPlay(which)
{
  if (!soundEmbed)
  {
    soundEmbed = document.createElement("embed");
    soundEmbed.setAttribute("src", "/sounds/"+which+".mp3");
    soundEmbed.setAttribute("hidden", true);
    soundEmbed.setAttribute("autostart", true);
  }
  else
  {
    document.body.removeChild(soundEmbed);
    soundEmbed.removed = true;
    soundEmbed = null;
    soundEmbed = document.createElement("embed");
    soundEmbed.setAttribute("src", "/sounds/"+which+".mp3");
    soundEmbed.setAttribute("hidden", true);
    soundEmbed.setAttribute("autostart", true);
  }
  soundEmbed.removed = false;
  document.body.appendChild(soundEmbed);
}
//======================================================================

function dn_sound_new_orders()
{
  soundPlay('new_orders');
}

function tinyMCE_removeHTMLCommentsOnSave(ed) {
  ed.onPostProcess.add(function(ed, o) {
      o.content = o.content.replace(/<(!--)([\s\S]*)(--)>/gi, '');
  });
}

function tinyMCE_trimSaveContent(element_id, html, body) {
  html = html.replace(/<!--.*?-->/g,'');
  return html;
}

$.ajaxSetup ({
    /* Disable caching of AJAX responses */
    cache: false
});

function dn_ajax_pager_link()
{
  var parent = $(this).parents('.ajax-page');
  $(parent).find('.ajax-loader:first').show();
  $(parent).load($(this).attr('href'));

  return false;
}

function dn_remove_order_item(a)
{
  $(a).parent('li').css('backgroundColor', '#FFF035');

  if (!confirm('Are you sure you want to remove the order item?'))
  {
    $(a).parent('li').css('backgroundColor', '');
    return false;
  }

  $('#myorderloading').show();

  jQuery.ajax({
    type: 'GET',
    url: a.href,
    processData: false,
    cache: false,
    success: function(html){
      $('#myorder').html(html);
      $('#myorderloading').hide();
    }
  });

  return false;
}

function menu_smooth_scroll(a)
{
  try
  {
    if ($('.flat-menu .the-menu:visible').scrollTo)
    {
      $('.flat-menu .the-menu:visible').scrollTo(a.hash, 2000);
      return false;
    }
    else
    {
      // some how the function isn't loaded, let the browser takes care of this
      return true;
    }
  }
  catch (e)
  {
    // something is wrong, let the browser takes care of this
    return true;
  }
  
  return true;
}

function dn_reload_myorder(a)
{
  $('#myorderloading').show();

  jQuery.ajax({
    type: 'GET',
    url: a.href,
    processData: false,
    cache: false,
    success: function(html){
      $('#myorder').html(html);
      $('#myorderloading').hide();
    }
  });

  return false;
}

/**
 * Bind elements
 * @param scope (e.g.: if '#facebox' means only bind children of #facebook element)
 */
function dn_binding(scope)
{
  // bind city_id combo to refresh suburbs list when a city is selected
  $(scope+' select.city_id').bind('change', reloadSubComboBox).each(function(){
    $(this).after(' <img id="'+this.id+'_loader" src="/images/ajax-loader.gif" style="display: none;" />');
  });

  // bind order-later-type to refresh the date and time list
  $(scope+' select.order-later-type').bind('change', reloadOrderLaterDate).each(function(){
    $(this).after(' <img id="'+this.id+'_loader" src="/images/ajax-loader.gif" style="display: none;" />');
  });

  // bind order-later-date to refresh the time list
  $(scope+' select.order-later-date').bind('change', reloadOrderLaterTime).each(function(){
    $(this).after(' <img id="'+this.id+'_loader" src="/images/ajax-loader.gif" style="display: none;" />');
  });

  // bind order-later-date to refresh the time list
  $(scope+' select.order-later-menu').bind('change', reloadOrderLaterTime).each(function(){
    $(this).after(' <img id="'+this.id+'_loader" src="/images/ajax-loader.gif" style="display: none;" />');
  });

  // add * (star) to required fields
  $(scope+' label.required').each(dn_required_signs);
  
  // find textarea form row and add css class to the formRow
  $(scope+' .formRow textarea').parents('.formRow').attr('class', 'formRow formTextareaRow');

  // find checkbox form row and add css class to the formRow
  $(scope+' .formRow input[type=checkbox]').parents('.formRow').attr('class', 'formRow formCheckboxRow');
  
  // add up arrow to fieldHelp
  $(scope+' .fieldHelp').each(function(){
    if ($(this).find('em').length <= 0) $(this).prepend('<em>&uarr; </em>');
  });
  
  $(scope+' ul.dropdown > li').bind('mouseover', jsddm_open);
  $(scope+' ul.dropdown > li').bind('mouseout',  jsddm_timer);
  $(scope+' ul.dropdown').show();
  $(scope+' .menu-action-loader').hide();
  
  // tree structure
  var config = dn_default_tree_config();
  
  $(scope+' .menutree').each(function(){
    if ($(this).attr('rel') != 'dont-auto-load')
    {
      config.script = '/'+this.id;
      $(this).fileTree(config /*, dn_tree_node_onclick*/);
    }
  });
  
  $(scope+' a[rel*=facebox]').facebox();
  
  $(scope+' a.use-loading-overlay').bind('click', dn_use_loading_overlay);
  
  $(scope+' input[type=text], '+scope+' input[type=password]').addClass('text');
  
  $(scope+" .sortable-menu").each(function()
  {
    $(this).sortable();
  });
  
  $(scope+' .formField input.pkWidgetFormInputFilePersistent[type=file]').bind('change', function(){
    $(this).parent().find('img, p').hide();
  });
  
  $(scope+' .accordion').each(function(){
    $(this).accordion({autoHeight: false, collapsible: true, active: false});
  });

  $(scope+' table.stripes-lightgray').each(dn_table_stripes_lightgray);
  $(scope+' .fade-to-gray').each(dn_fade_to_gray);
  $(scope+' .twitter-timeline').each(dn_twitter_timeline);
}

function dn_twitter_timeline()
{
  var element = this;
  jQuery.ajax({
    type: 'POST',
    url: '/twitter/timeline',
    cache: false,
    success: function(html){
      $(element).html(html);
    }
  });
}

function dn_fade_to_gray()
{
  $(this).animate({opacity: 0.30}, 5000, 'swing', function(){
    $(this).css({backgroundColor:'#efefef', color: '#999', border: '1px solid #999'});
  });
}

function dn_table_stripes_lightgray()
{
  var i=0;

  $(this).find('tbody tr, tr').each(function(){
    if (i % 2 == 0)
    {
      $(this).css('backgroundColor', '#EFEFEF');
    }
    i++;
  });
}

/**
 * Reload the displayed search filter labels from the facebox (not from form).
 */
function dn_reload_search_filter_labels_from_facebox()
{
  dn_reload_search_filter_labels('#facebox_search-tags');
  
  dn_transfer_form_field_values($('#facebox_search-tags'), '#search-tags');
}

/**
 * Reload the displayed search filter labels from the form (not from facebox).
 */
function dn_reload_search_filter_labels_from_form()
{
  dn_reload_search_filter_labels('#search-tags');
}

/**
 * Reload the displayed search filter labels.
 * 
 * @param source (where to reload this from, e.g.: #facebox_search-tags or #search-tags)
 */
function dn_reload_search_filter_labels(source)
{
  var the_html = '';
  
  
  // get checked checkboxes
  $(source).find('input[@type=checkbox]:checked').each(function(){
    $(source).find('label[for='+this.id+']').each(function(){
      the_html += '<li>'+$(this).html()+'</li>';
    });
  });
  
  if (the_html != '') the_html = '<ul class="tick-list">'+the_html+'</ul>';
  
  $("#search-tags-labels").html(the_html);
}

function dn_open_form_partial(element_id)
{
  jQuery.facebox('<div id="facebox_'+element_id+'" class="form-partial" rel="'+element_id+'">'+jQuery("#"+element_id).html()+'</div>');
  
  var target_id = '#facebox_'+element_id;
  $('#'+element_id).each(function(){
    dn_transfer_form_field_values(this, target_id);
  });
  
  $(target_id).ready(function(){
    $(target_id).find('input[type=checkbox]').click(dn_reload_search_filter_labels_from_facebox);
  });
  
  return false; // false to prevent event from being processed further
}

function dn_facebox_closed()
{
  $('#facebox .form-partial').each(function(){
    var target_id = '#'+$(this).attr('rel');
    dn_transfer_form_field_values(this, target_id);
  });
}

function dn_transfer_form_field_values(source_object, target_id)
{
  $(source_object).find('select, input, textarea').each(function(){
    var the_source = $(this);
    var the_source_id = this.id;
    var the_type = $(this).attr('type');
    
    $(target_id).find('#'+the_source_id).each(function(){
      if (the_type == 'checkbox' || the_type == 'radio')
      {
        $(this).attr('checked', the_source.attr('checked'));
      }
      else
      {
        $(this).val(the_source.val());
      }
    });
  });
}

function dn_use_loading_overlay()
{
  jQuery.facebox('<h3>'+$(this).html()+'</h3><img src="/images/ajax-loader-bar.gif" />');
  return true;
}

function dn_tree_node_onclick(item_id)
{
  var selector = '#menu-item-info-'+item_id;

  if ($(selector))
  {
    if ($(selector).is(":hidden"))
    {
      $(selector).slideDown("fast");
    }
    else
    {
      $(selector).slideUp("fast");
    }
  }
  
  return false;
}

function dn_default_tree_config()
{
  return {
      expandSpeed: 500,
      collapseSpeed: 500,
      multiFolder: true,
      loadMessage: '<img src="/images/ajax-loader.gif" />'
    };
}

/**
 * Do binding on the elements inside facebox overlay.
 */
function dn_facebox_binding()
{
  dn_binding('#facebox');
}

/**
 * Reload the menu group tree on the main screen
 */
function dn_menu_group_reload(id, tree_url)
{
  var menunode;
  var the_script;
  
  if (id==0)
  {
    menunode = '.menutree';
    the_script = $('.menutree').get(0).id;
  }
  else
  {
    menunode = '#menugroup'+id;
    the_script = $('#menugroup'+id).parents('.menutree').get(0).id;
  }

  jQuery.ajax({
    type: 'POST',
    url: tree_url,
    processData: false,
    data: 'dir='+id,
    cache: false,
    success: function(html){
      $(menunode+' ul.jqueryFileTree:first').remove();
      $(menunode).append(html);

		  // bind the new tree nodes
		  var config = dn_default_tree_config();
		  config.script = '/'+the_script;
		  config.bindOnly = true;
      $(menunode+' ul.jqueryFileTree:first').fileTree(config/*, dn_tree_node_onclick*/);
    }
  });
}

/**
 * Reload menu item info div (e.g.: after editing picture/description.)
 */
function dn_update_menu_item_info(item_id, url_for, show_more_info)
{
  jQuery.ajax({
    type: 'POST',
    url: url_for,
    processData: false,
    data: 'id='+item_id,
    cache: false,
    success: function(html){
      $('#menu-item-info-'+item_id).html(html).slideDown("fast");

      if (show_more_info)
      {
        $('#menu-item-info-toggle-'+item_id).show();
      }
      else
      {
        $('#menu-item-info-toggle-'+item_id).hide();
      }
    }
  });
}

function dn_close_overlay()
{
  jQuery(document).trigger('close.facebox');
  $('.myOverlay').jqmHide();
}

/**
 * Expands menu group if it is collapsed before opening overlay.
 * @param a (the <a> element clicked)
 */
function dn_menugroup_open_overlay(a)
{
  var li = $(a).parents('.directory').get(0);
  
  // if directory is collapsed, open it first
  if ($(li).hasClass('collapsed'))
  {
    $(li).children('a.jqueryFileTreeLink').click();
  }

  return dn_open_overlay(a);
}

/**
 * Handling add/remove favourite
 */
function dn_favourite(a, updateID, loaderID)
{
  $('#'+loaderID).show();

  jQuery.ajax({
    type: 'POST',
    url: a.href,
    processData: false,
    cache: false,
    success: function(html){
      $('#'+updateID).html(html);
      dn_binding('#'+updateID);
      $('#'+loaderID).hide();
    }
  });

  return false;
}

/**
 * Submit form remotely via ajax call.
 * @param form (the form element object)
 * @param updateID (the element ID to update)
 */
function dn_submit_remotely(form, updateID)
{
  $('#'+updateID).find('.ajax-loader').show();

  jQuery.ajax({
    type: 'POST',
    url: form.action,
    processData: false,
    data: $(form).serialize(),
    cache: false,
    success: function(html){
      $('#'+updateID).replaceWith(html);
      dn_binding('#'+updateID);
    }
  });
  
  return false;
}

function dn_required_signs()
{
  var parentNode = $(this.parentNode);

  if (parentNode.find('em.required').length <= 0)
  {
    if (parentNode.css('text-align') == 'right') {
      parentNode.prepend('<em class="required">* </em>');
    } else {
      parentNode.append('<em class="required"> *</em>');
    }
  }
}

function dn_view_pdf(doc_id, access_key)
{
  jQuery.facebox(
    '<object codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" align="middle"	height="500" width="680" >'+
    '<param name="movie" value="http://d1.scribdassets.com/ScribdViewer.swf?document_id='+doc_id+'&access_key='+access_key+'&page=1&version=1&viewMode=list">'+
    '<param name="quality" value="high">'+
    '<param name="play" value="true">'+
    '<param name="loop" value="true">'+
    '<param name="scale" value="showall">'+
    '<param name="wmode" value="opaque">'+
    '<param name="devicefont" value="false">'+
    '<param name="bgcolor" value="#ffffff">'+
    '<param name="menu" value="true">'+
    '<param name="allowFullScreen" value="true">'+
    '<param name="allowScriptAccess" value="always">'+
    '<param name="salign" value="">'+
    '<param name="mode" value="list">'+
    '<embed src="http://d1.scribdassets.com/ScribdViewer.swf?document_id='+doc_id+'&access_key='+access_key+'&page=1&version=1&viewMode=list" '+
    'quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" '+
    'play="true" loop="true" scale="showall" wmode="opaque" devicefont="false" '+
    'bgcolor="#ffffff" menu="true" allowfullscreen="true" allowscriptaccess="always" '+
    'salign="" type="application/x-shockwave-flash" align="middle" mode="list" height="500" width="680">'+
    '</embed></object>');
  return false;
}

function dn_open_overlay_image(a)
{
  jQuery.facebox('<img src="'+a.href+'" />');

  return false;
}

function dn_open_overlay(a)
{
  jQuery.facebox(function() { 
    jQuery.ajax({
      url: a.href,
      type: 'GET',
      cache: false,
      error: function (xhr, textStatus, ex)
      {
        // repost so that the error page will be displayed
        jQuery.post(a.href, function(data){jQuery.facebox(data);});
      },
      success: function(data, textStatus) {
        jQuery.facebox(data);
        $('#facebox input:visible:enabled:first').focus();
      }
    });
    
  });

  return false;
}

/* List to drop down generator */
var timeout    = 500;
var closetimer = 0;
var ddmenuitem = 0;
function jsddm_open()
{jsddm_canceltimer();
   jsddm_close();
   ddmenuitem = $(this).find('ul').css('visibility', 'visible');}
function jsddm_close()
{if(ddmenuitem) ddmenuitem.css('visibility', 'hidden');}
function jsddm_timer()
{closetimer = window.setTimeout(jsddm_close, timeout);}
function jsddm_canceltimer()
{if(closetimer)
   {window.clearTimeout(closetimer);
      closetimer = null;}}
document.onclick = jsddm_close;
/* END List to drop down generator */

function reloadOrderLaterTime()
{
  var loader = $('#'+this.id+'_loader');
  var form = $('#'+this.id).parents('form').get(0);
  var oid = $(form).find('.order-later-oid:first').val();
  var d = $(form).find('.order-later-type:first').val();
  var date = $(form).find('.order-later-date:first').val();
  var m = $(form).find('.order-later-menu:first').val();
  var timebox = $(form).find('.order-later-time:first');

  // empty the combo box
  $(timebox).empty();

  // add empty option
  $("<option />").appendTo($(timebox));

  loader.show();

  var url = "/list/orderLaterTimes?date="+date+'&oid='+oid+'&d='+d+'&menu_id='+m;

  $.getJSON(url, function(data){

    // add the rest of the other options
    for (var i=0; i < data.length; i++) {
      $("<option />").val(data[i][0]).text(data[i][1]).appendTo($(timebox));
    }

    loader.hide();
  });

  return false;
}

function reloadOrderLaterDate()
{
  var loader = $('#'+this.id+'_loader');
  var form = $('#'+this.id).parents('form').get(0);
  var oid = $(form).find('.order-later-oid:first').val();
  var datebox = $(form).find('.order-later-date:first');
  var timebox = $(form).find('.order-later-time:first');
  var zonediv = $(form).find('.order-later-zone:first').parents('.formRow').get(0);

  if (this.value == 'delivery')
  {
    $(zonediv).show();
    // insert * sign if not already there
    var label = $(zonediv).find('label:first');
    if ($(label).attr('class') != 'required')
    {
      $(label).attr('class', 'required');
      if ($(label).parent().css('text-align') == 'right') {
        $(label).parent().prepend('<em class="required">* </em>');
      } else {
        $(label).parent().append('<em class="required"> *</em>');
      }
    }
  }
  else
  {
    $(zonediv).hide();
  }

  // empty the combo box
  $(datebox).empty();
  $(timebox).empty();

  // add empty option
  $("<option />").appendTo($(datebox));
  $("<option />").appendTo($(timebox));

  loader.show();

  var url = "/list/orderLaterDates?d="+this.value+'&oid='+oid;

  $.getJSON(url, function(data){

    // add the rest of the other options
    for (var i=0; i < data.length; i++) {
      $("<option />").val(data[i][0]).text(data[i][1]).appendTo($(datebox));
    }

    loader.hide();
  });

  return false;
}

/* function to reload sub combo boxes */
function reloadSubComboBox() {

  var loader = $('#'+this.id+'_loader');
  var form = $('#'+this.id).parents('form').get(0);
  var suburb = $(form).find('.suburb_id, #filters_suburb_id');
  
  // empty the combo box
  $(suburb).empty();
  
  // add empty option
  $("<option />").appendTo($(suburb));
  
  loader.show();

  var url = "/list/suburbs?city_id="+this.value;

  if (form.action.indexOf('outlet/search') != -1)
  {
    url += '&nb_outlets=1';
  }

  $.getJSON(url, function(data){
    
    // add the rest of the other options
    for (var i=0; i < data.length; i++) {
      $("<option />").val(data[i][0]).text(data[i][1]).appendTo($(suburb));
    }
    
    loader.hide();
  });
  
  return false;
}

function dn_copy_menu_item_option(item_id)
{
  dn_copy_paste.set_menu_item_id(item_id);
  alert('Copied! Don\'t forget to save the options.');
  return false;
}

function dn_paste_menu_item_option(oid)
{
  var menu_item_id = dn_copy_paste.get_menu_item_id();

  // make sure there's a menu item option copied
  if (menu_item_id == 0)
  {
    alert('Oops, please copy a menu item option first.');
    return false;
  }

  // make sure there are menu items selected
  if ($(".menuitem-checkbox:checked").length <= 0)
  {
    alert('Oops, please tick one or more menu items to paste option into.');
    return false;
  }

  dn_copy_paste.paste_options(oid);

  return false;
}

var dn_copy_paste = {

  group_ids:[],  // group ids that have been copied/cut
  item_ids:[],   // item ids that have been copied/cut
  is_cut: false, // if true this is cut, otherwise copy
  is_global: false,
  menu_item_id: 0, // store menu item id, for example to later copy the options
  
  clear: function()
  {
    this.group_ids = [];
    this.item_ids = [];
    this.is_cut = false;
  },
  
  uncheck_all: function()
  {
    $(".menugroup-checkbox:checked").each(function(){
      $(this).attr('checked', false);
    });

    $(".menuitem-checkbox:checked").each(function(){
      $(this).attr('checked', false);
    });
  },

  get_menu_item_id: function()
  {
    return this.menu_item_id;
  },

  set_menu_item_id: function(item_id)
  {
    this.menu_item_id = item_id;
  },

  store: function(is_cut, is_global)
  {
    var me = this;
    
    this.clear();
    
    this.is_cut = is_cut;
  
    var i = 0;
    var total = 0;
    
    $(".menugroup-checkbox:checked").each(function(){
      me.group_ids[i++] = this.value;
    });
    total = i;
	  
    i = 0;
    $(".menuitem-checkbox:checked").each(function(){
      me.item_ids[i++] = this.value;
    });
    total += i;

    if (is_global)
    {
      $.ajax({
        url: '/global_copy',
        cache: false,
        type: 'POST',
        data: {'group_ids[]': me.group_ids, 'item_ids[]': me.item_ids}
      });

      // clear after send
      this.clear();
    }

    return total;
  },

  paste_options: function(oid)
  {
    var item_ids = [];
    var source_item_id = this.get_menu_item_id();
    var i = 0;
    var total = 0;

    $(".menuitem-checkbox:checked").each(function(){
      item_ids[i++] = this.value;
    });
    total += i;

    if (i <= 0 || source_item_id <= 0) return false;
    $('.outlet-menu-loader').show();
    $.ajax({
      url: '/paste_options/'+oid,
      cache: false,
      type: 'POST',
      data: {'item_ids[]': item_ids, 'source': source_item_id},
      success: function()
      {
        alert('Done!');
      },
      complete: function()
      {
        $('.outlet-menu-loader').hide();
      }
    });

    return false;
  },

  paste: function(group_id, oid)
  {
    var params = {
      is_cut: ((this.is_cut)?1:0),
      pid: group_id,
      oid: oid,
      'group_ids[]': this.group_ids,
      'item_ids[]': this.item_ids
    };
    
    $('.outlet-menu-loader').show();
    
    jQuery.ajax({
	    type: 'POST',
	    url: '/outletmenu/paste',
	    data: params,
	    cache: false,
	    success: function(html){
	      $('.outlet-menu-loader').hide();
	      $('#menutree-ajax-result').html(html);
	    }
	  });
	  
	  this.clear();
	  this.uncheck_all();
  }
};

function dn_menutree_uncheck_all()
{
  dn_copy_paste.uncheck_all();
  
  return false;
}

function dn_menutree_copy()
{
  dn_copy_paste.store(false, false);
  
  return false;
}

function dn_menutree_global_copy()
{
  dn_copy_paste.store(false, true);

  return false;
}

function dn_menutree_cut()
{
  dn_copy_paste.store(true, false);

  return false;
}

/**
 * @param group_id (the destination group id to paste to)
 * @param oid (the outlet id)
 */
function dn_menutree_paste(group_id, oid)
{
  dn_copy_paste.paste(group_id, oid);

  return false;
}

function dn_load_menu(a, divID)
{
  $('.outlet-menu-loader').show();
  
  jQuery.ajax({
    type: 'POST',
    url: a.href,
    cache: false,
    success: function(html){
      $('.outlet-menu-loader').hide();
      $('#'+divID).html(html);
    }
  });
  
  return false;
}

/**
 * Handles slot type combo box on changed event
 * 
 * @param cbo (e.g.: #slot_type in outlet slot form)
 * @return void
 */
function dn_slot_type_changed(cbo)
{
  if ($(cbo).val()==1)
  {
    $('#slotContentText').show();
    $('#slotContentPicture').hide();
  }
  else
  {
    $('#slotContentText').hide();
    $('#slotContentPicture').show();
  }
}

/**
 * Reload outlet slot (e.g.: after add/edit/delete slot)
 * 
 * @param url (ajax url)
 * @param oid (outlet uniqid)
 * @param display_order
 * @return void
 */
function dn_reload_outlet_slot(url, oid, display_order)
{
  jQuery.ajax({
    type: 'POST',
    url: url,
    cache: false,
    data: {oid: oid, i: display_order},
    success: function(html){
      var element = $('#outletslot_'+display_order);
      element.after(html);
      element.remove();
    }
  });
}
