// Would be nice to know what this does. Blame it on Boyce®
document.observe("dom:loaded", function() 
{
  activate_submenus('#header_tabs > li');
  activate_submenus('#department_categories > li');
  select_alias('mygofer_target');
  
  var shc_sia_url = $('see_it_all') || null;
  if (shc_sia_url) see_it_all($('see_it_all'));
});

/**
 * Sets listeners to toggle display of submenus
 * @param - selector - A css selector. Should match the collection of nav trigger elements. 
 */
function activate_submenus(selector)
{
 $$(selector).each(function($li)
 {
   // ASSUMED: trigger element has a single class
   var nav_section = $li.readAttribute('class');
   var has_submenu = ($li.down('ul') != undefined);

   if (has_submenu)
   {
     Event.observe($li, 'mouseenter', function() 
     {
       $li.addClassName('hover');
       $(nav_section + '_tabs').show();
     })

     Event.observe($li, 'mouseleave', function()
     {
       $li.removeClassName('hover');
       $(nav_section + '_tabs').hide();        
     })
   }    
 });
}


/**
 * Select Alias.
 */
function select_alias(target) 
{
  if (document.createDocumentFragment && document.insertBefore) 
  {
    var $select = $(target);
    if (! $select || ! $select.visible) 
      return false;
      
    var opts     = $select.options,
        length   = opts.length,
		    i        = 0,
        fragment = document.createDocumentFragment(),
        $ul       = new Element('ul'),
        contents = '';
              
    $select.hide();    
    $ul.writeAttribute('id', target + '_alias');
    
    for (i; i < length; i++) 
    {
      var text = opts[i].text,
      selected = opts[i].selected;
      contents += '<li'
      if (selected)
        contents += ' class="selected"';

      contents += ' onclick="select_this($(this), \'' + target + '\'); return false;"' +
                  ' onmouseover="$(this).addClassName(\'hover\')"' +
                  ' onmouseout="$(this).removeClassName(\'hover\')">' + text + '</li>';
    }
    
    $ul.update(contents);
    fragment.appendChild($ul);
    $select.up('form').insertBefore(fragment, $select);
    
    return true;
  } 
  else 
  {
    return false;
  }
}


function select_this(e, target) 
{
  var select   = $(target),
      parent   = e.parentNode,
      children = parent.select('li'),
		  length   = children.length,
	  	i        = length - 1;
	  	
  if (i > 0) 
  { 
    do 
    {
      var child  = children[i];
      if (child != e) 
      {
        child.removeClassName('selected');
      } 
      else 
      {
        select.selectedIndex = i;
        child.addClassName('selected');
      }
    } 
    while (i--);
  }
  
  parent.toggleClassName('open');
}


function check_target() 
{
  var index = $('mygofer_target').selectedIndex;
  switch (index) 
  {
    case 0:
    	location.href = '/search?q=' + encodeURIComponent($('search_q').value) + '&search_type=' + $('mygofer_target').value;
      return false;
      break;
          
    case 1:
    	location.href = '/ideas/search?query=' + encodeURIComponent($('search_q').value) + '&search_type=' + $('mygofer_target').value;
      return false;
      break;
      
    case 2:
    	location.href = '/posts/search?query=' + encodeURIComponent($('search_q').value) + '&search_type=' + $('mygofer_target').value;
      return false;
      break;
      
    case 3:
      location.href = 'http://www.mygofer.com/shc/s/search_10161_21651?&amp;sid=comm_sears_header&amp;keyword=' + encodeURIComponent($('search_q').value);
      return false;
      break;
      
    default:
      return true;
      break;
  }
}


function see_it_all() {
  var t;

  /* Ready See It All drop downs. */
  var init = function(toggle,list) {
    $(toggle).observe('click', function() {
      clearTimeout(t);
      closeDDs();
      if ($$('.wazmu')[0] != $(this)) {
        $$('.wazmu')[0].removeClassName('wazmu');
        $('category_links').childElements('span').invoke('hide');
        $(this).addClassName('wazmu');
        $(list).appear({duration:0.6});
      };
    });   
  }
  init("see_shop","shop_links");
  init("see_share","share_links");
  init("see_organize","options_links");
  
  $$('#see_it_all #category_links li a').invoke('observe', 'mouseenter', function() {
    clearTimeout(t);
    closeDDs();
    var pos   = $(this).cumulativeOffset(),
        menu  = $($(this).id + 'TT');
    $(this).addClassName('active');
    menu.setStyle({
      'left': pos[0] - 155 + 'px',
      'top': pos[1] + 20 + 'px'
    }).appear({duration:0.2}).observe('mouseleave', function() {
      t = setTimeout(function() {
        closeDDs();
      }, 100);
    }).observe('mouseenter', function() {
      clearTimeout(t);
    });
  }).invoke('observe', 'mouseleave', function() {
    t = setTimeout(function() {
      closeDDs();
    }, 50);
  });

  var closeDDs = function() {
    $$('.seeTTcontainer').invoke('hide');
    $$('see_it_all .active').invoke('removeClassName', 'active');
  };
};

/**
 * Get JSON data.
 */

function JSONscriptRequest(fullUrl) {
    this.fullUrl = fullUrl; /** REST request path */
    this.noCacheIE = '&noCacheIE=' + (new Date()).getTime(); /** Keep IE from caching requests */
    this.headLoc = $$('head')[0]; /** Get the DOM location to put the script tag */
    this.scriptId = 'jsonp_' + JSONscriptRequest.scriptCounter++; /** Generate a unique script tag id */
}

/**
 * Static script ID counter
 */

JSONscriptRequest.scriptCounter = 1;

/**
 * buildScriptTag method
 *
 * Create the script element and add script object attributes.
 */

JSONscriptRequest.prototype.buildScriptTag = function () {
  this.scriptObj = new Element('script', {
    'type': 'text/javascript',
    'src': this.fullUrl + this.noCacheIE,
    'id': this.scriptId
  });
}
 
/**
 * removeScriptTag method
 *
 * Destroy the script element.
 */
 
JSONscriptRequest.prototype.removeScriptTag = function () {
  this.headLoc.removeChild(this.scriptObj);  
}

/**
 * addScriptTag method
 *
 * Append the script element to the DOM.
 */

JSONscriptRequest.prototype.addScriptTag = function () {
    this.headLoc.appendChild(this.scriptObj);
}

/**
 * Get a cookie.
 */

function getCookie(cookieName) {
    var cookieArray  = document.cookie.split('; ')
        length       = cookieArray.length,
        searchString = cookieName + '=',
        returnValue  = '',
        index        = 0;
    for (index; index < length ; index++) {
      var cookie   = cookieArray[index],
          position = cookie.indexOf(searchString);
      if (position == 0) {
        var name_value = cookie.split('='),
            name_v     = name_value[1];
        if (name_v != '') {
			    try {
            returnValue = decodeURIComponent(name_v);
          } catch(e) {
            returnValue = decodeURIComponent(encodeURIComponent(name_v));
          }
        } else {
          returnValue = '';
        }
      }
    }
	return returnValue;
}

/**
 * Clean up a string.
 */

function cleanUpValue(str) {
	if (str == null || str == '') {
	  return '';
	} else {	
	  if (str.charAt(0) == '"') {
	    str = str.substring(1);
	  }
	  if (str.charAt(str.length-1) == '"') {
	    str = str.substring(0, str.length-1);
	  }
	  return str.replace(/\\"/g, '"');
  }
}
