/* Add events to elements */
function initMenu() {
  $("searchinput").addEvent("focus", clearInitialText);
  $("searchinput").addEvent("blur", checkInitialText);
  /* Add effects to items */
  var kwicks = $$('#menu .kwick');
  var fx = new Fx.Elements(kwicks, {wait: false, duration: 300, transition: Fx.Transitions.quadOut});
  kwicks.each(function(kwick, i) {
    kwick.addEvent('mouseenter', function(e) {
      //kwick.getElementsByTagName("a")[0].style.color = "#999999";
      var obj = {};
      //Expand this menu item
      obj[i] = {
        'width': [kwick.getStyle('width').toInt(), 220]
      };
      //Contract other menu items
      kwicks.each(function(other, j) {
        if (other != kwick) {
          //kwick.getElementsByTagName("a")[0].style.color = "#CCCCCC";
          var w = other.getStyle('width').toInt();
          if (w != 140) obj[j] = {'width': [w, 140]};
        }
      });
      fx.start(obj);
    });
    kwick.addEvent('click', function(e) {
      window.location.href = kwick.getElementsByTagName("a")[0].href;
    });
  });
  $('menu').addEvent('mouseleave', function(e) {
    var obj = {};
    kwicks.each(function(kwick, j) {
      //kwick.getElementsByTagName("a")[0].style.color = "#CCCCCC";
      obj[j] = {'width': [kwick.getStyle('width').toInt(), 160]};
    });
    fx.start(obj);
  });
  
  $('searchform').addEvent('submit', function(e) {
    var searchstr = $('searchinput').value;
    if (searchstr != '' && searchstr.length > 2 && !containsSpecialChars(searchstr)) {
      replaceHtml($('content'),"<p>Searching...</p>");
      e = new Event(e).stop();
      var url = 'http://www.adglass.com/products.json';
      var request = new Json.Remote(url, {
        method: 'get',
        onComplete: function(jsonObj) {
          buildSearchResults(jsonObj, $('searchinput').value);
        }
      }).send();
    }
  });
  
  //Show the search box and contact links
  $$('a.contact').each(function(link) {
    link.style.display = "inline";
  });
  $('searchform').style.display = "inline";
}

DOMReady(initMenu);
function buildSearchResults(products, searchString) {
  var content = $('content');
  var regex = eval('/'+searchString+'/gi');
  var resultsHTML = '';
  var resultCount = 0;
  for (var i in products) {
    if (regex.test(products[i][1]) || regex.test(products[i][2])) {
      if (resultCount === 0) {
        resultsHTML += '<h3>Search Results for: '+searchString+'</h3><hr/><table class="thumbtable"><tbody><tr>';
      } 
      else if (resultCount % 4 === 0) {
        resultsHTML += '</tr><tr>';
      }
      resultsHTML += '<td><a href="javascript:void(0);" onclick="Lightbox.show(\'images/'+products[i][3]+'.jpg\',\'&lt;table class=&quot;popuptable&quot;&gt;&lt;thead&gt;&lt;tr&gt;&lt;th colspan=&quot;11&quot;&gt;'+products[i][2]+' - '+products[i][5]+'&lt;/th&gt;&lt;/tr&gt;&lt;tr&gt;&lt;th&gt;&lt;/th&gt;&lt;th&gt;36&lt;/th&gt;&lt;th&gt;72&lt;/th&gt;&lt;th&gt;144&lt;/th&gt;&lt;th&gt;288&lt;/th&gt;&lt;th&gt;576&lt;/th&gt;&lt;th&gt;1008&lt;/th&gt;&lt;th&gt;&lt;/th&gt;&lt;th&gt;Pk./Lbs.&lt;/th&gt;&lt;th&gt;H&lt;/th&gt;&lt;th&gt;W&lt;/th&gt;&lt;th&gt;WR&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td&gt;&lt;/td&gt;&lt;td&gt;$'+products[i][6]+'&lt;/td&gt;&lt;td&gt;$'+products[i][7]+'&lt;/td&gt;&lt;td&gt;$'+products[i][8]+'&lt;/td&gt;&lt;td&gt;$'+products[i][9]+'&lt;/td&gt;&lt;td&gt;$'+products[i][10]+'&lt;/td&gt;&lt;td&gt;$'+products[i][11]+'&lt;/td&gt;&lt;td&gt;6C&lt;/td&gt;&lt;td&gt;'+products[i][12]+'/'+products[i][13]+'&lt;/td&gt;&lt;td&gt;'+products[i][14]+'&quot;&lt;/td&gt;&lt;td&gt;'+products[i][15]+'&quot;&lt;/td&gt;&lt;td&gt;'+products[i][16]+'&quot;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;\')" rel="lightbox['+products[i][1]+']"><img alt="'+products[i][5]+'" src="thumbs/'+products[i][3]+' (Custom).jpg" /></a><br /><a href="javascript:void(0);" rel="lightbox['+products[i][1]+']" onclick="Lightbox.show(\'images/'+products[i][3]+'.jpg\',\'&lt;table class=&quot;popuptable&quot;&gt;&lt;thead&gt;&lt;tr&gt;&lt;th colspan=&quot;11&quot;&gt;'+products[i][2]+' - '+products[i][5]+'&lt;/th&gt;&lt;/tr&gt;&lt;tr&gt;&lt;th&gt;&lt;/th&gt;&lt;th&gt;36&lt;/th&gt;&lt;th&gt;72&lt;/th&gt;&lt;th&gt;144&lt;/th&gt;&lt;th&gt;288&lt;/th&gt;&lt;th&gt;576&lt;/th&gt;&lt;th&gt;1008&lt;/th&gt;&lt;th&gt;&lt;/th&gt;&lt;th&gt;Pk./Lbs.&lt;/th&gt;&lt;th&gt;H&lt;/th&gt;&lt;th&gt;W&lt;/th&gt;&lt;th&gt;WR&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td&gt;&lt;/td&gt;&lt;td&gt;$'+products[i][7]+'&lt;/td&gt;&lt;td&gt;$'+products[i][8]+'&lt;/td&gt;&lt;td&gt;$'+products[i][9]+'&lt;/td&gt;&lt;td&gt;$'+products[i][10]+'&lt;/td&gt;&lt;td&gt;$'+products[i][11]+'&lt;/td&gt;&lt;td&gt;$'+products[i][11]+'&lt;/td&gt;&lt;td&gt;6C&lt;/td&gt;&lt;td&gt;'+products[i][12]+'/'+products[i][13]+'&lt;/td&gt;&lt;td&gt;'+products[i][14]+'&quot;&lt;/td&gt;&lt;td&gt;'+products[i][15]+'&quot;&lt;/td&gt;&lt;td&gt;'+products[i][16]+'&quot;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;\')">' + products[i][2] + " - " + products[i][4] + '</a></td>';
      resultCount++;
    }
  }
  if (resultsHTML === '') {
    resultsHTML = '<p>Sorry, nothing matched your search for: ' + searchString + '.</p><p>Try again or choose from the menu above.</p>';  
  }
  else {
    resultsHTML += '</tr></tbody></table>';
  }
  replaceHtml(content, resultsHTML);
}

function clearInitialText(e) {
  var targ = getEventTarget(e);
  if (targ && targ.value == targ.alt) {
    targ.value = "";
    targ.className = "modifiedFormField";
  }
}
function checkInitialText(e) {
  var targ = getEventTarget(e);
  if (targ && targ.value == "" && targ.alt != null && targ.value != targ.alt) {
    targ.value = targ.alt;
    targ.className = "initialFormField";
  }
}

function containsSpecialChars(str) {
  if (/&\^\:\$\?\~\@\<\>\\\{\}\(\)\!\*\;/.test(str)) {
    return true;
  }
  return false;
}

/* Common JS Functions */
function getEventTarget(e) {
  var targ;
  if (!e) var e = window.event;
  if (e.target) targ = e.target;
  else if (e.srcElement) targ = e.srcElement;
  if (targ.nodeType == 3) // defeat Safari bug
    targ = targ.parentNode;
  return targ;
}

function DOMReady(f) {
    if (/*@cc_on!@*/true) {
        document.addEventListener('DOMContentLoaded', f, false);
    } else {
        if (document.readystate == 'complete') { //Prevent this from firing too early in IE7
            window.setTimeout(f, 0);
        } else {
            window.addEvent('load', f);
        }
    }
}

/* This is much faster than using (el.innerHTML = str) when there are many
existing descendants, because in some browsers, innerHTML spends much longer
removing existing elements than it does creating new ones. */
function replaceHtml(el, html) {
  var oldEl = (typeof el === "string" ? document.getElementById(el) : el);
  var newEl = document.createElement(oldEl.nodeName);
  // Preserve the element's id and class (other properties are lost)
  newEl.id = oldEl.id;
  newEl.className = oldEl.className;
  // Replace the old with the new
  newEl.innerHTML = html;
  oldEl.parentNode.replaceChild(newEl, oldEl);
  /* Since we just removed the old element from the DOM, return a reference
  to the new element, which can be used to restore variable references. */
  return newEl;
};

