/* Greybox Links
 * A more unobtrusive attachment to anchors matching the right class names.
 */
function dynamicLinks() {
  if (!document.getElementsByTagName)
    return false;
   var links = document.getElementsByTagName("a");
   for (var i=0; i < links.length; i++) {
  
    if (links[i].className.match('popup')) {
       links[i].onclick = function(){GB_show(this.value,this.href,550,500);return false;};
    }

    if (links[i].className.match('popup_large')) {
       links[i].onclick = function(){GB_show(this.value,this.href,700,850);return false;};
    }

    if (links[i].className.match('popup_more_views')) {
       links[i].onclick = function(){GB_show(this.value,this.href,685,800);return false;};
    }

    if (links[i].className.match('popup_medium')) {
       links[i].onclick = function(){GB_show(this.value,this.href,500,550);return false;};
    }

    if (links[i].className.match('popup_calendar')) {
       links[i].onclick = function(){GB_show(this.value,this.href,250,275);return false;};
    }

    if (links[i].className.match('remove_popup')) {
       links[i].onclick = function(){return false;};
    }

    else if (links[i].className.match('return')) {
       links[i].onclick = function(){top.window.location.replace(this.href);return false};
    }

    else if (links[i].className.match('swap_main_photo')) {
      links[i].onclick = function(){swapImageFromThumbnailById('main_photo', prepareThumbnailPath(this), this);return false};
    }
    
    else if (links[i].className.match('load_main_photo')) {
      links[i].onclick = function(){loadImageFromThumbnailById('main_photo', prepareThumbnailPath(this), this);return false};
    }
    
    else if (links[i].className.match('load_vote_photo')) {
      links[i].onclick = function(){loadVoteImageFromThumbnailById('main_photo', prepareVoteThumbnailPath(this), this);return false};
    }

   }
}

function clearAnchorSelectionByClassName(classname)
{
  if (!document.getElementsByTagName)
    return false;
  var links = document.getElementsByTagName("a");
  for (var i=0; i < links.length; i++) {
    if (links[i].className.match(classname) && links[i].className.match('selected')) {
      links[i].className = classname;
    }
  }
}

/* Swap Images (thumbnail to enlarged view)
 * This is a fairly specialized function that allows you to swap the main view with a thumbnail
 * using a set of known constants about the application. Abstraction may be nice down the road.
 */
function prepareThumbnailPath(link)
{
  var path = link.getElementsByTagName('img')[0].src
  if (link.id.match(/alt_photo_/)) {
    path = path.replace(/other_thumbs/,'other');
  }
  else if (link.id.match(/main_photo_thumb/)) {
    path = path.replace(/thumbnail/,'full');
  }
  return path;
}
function prepareVoteThumbnailPath(link)
{
  var path = link.getElementsByTagName('img')[0].src
  if (link.id.match(/alt_photo_placement/)) {
    path = path.replace(/placement_mini/,'placement');
  }
  else if (link.id.match(/main_photo_thumb/)) {
    path = path.replace(/thumbnails/,'full');
  }
  return path;
}
function loadImageFromThumbnailById(id, path, ref)
{
  image = document.getElementById(id);
  image.src = path;
  clearAnchorSelectionByClassName('load_main_photo')
  ref.className = 'load_main_photo selected';
  
  dynamicLinks();
}
function loadVoteImageFromThumbnailById(id, path, ref)
{
  image = document.getElementById(id);
  link = image.parentNode;
  if (path.match('placement')) {
    link.className = 'remove_popup';
    link.href = '#';
  }
  else if (path.match('full')) {
    link.className = 'popup_large';
    id = path.match(/full\/(\d+)/)
    link.href = '/vote/zoom/'+id[1];
  }
  
  
  image.src = path;
  clearAnchorSelectionByClassName('load_vote_photo')
  ref.className = 'load_vote_photo selected';
  
  dynamicLinks();
}

function swapImageFromThumbnailById(id, path, ref) 
{
  image = document.getElementById(id);
  thumbnail = ref.getElementsByTagName('img')[0];
  
  if (image.src.match(/full/)) {
    swap_path = image.src.replace(/full/, 'thumbnail');
    id = 'main_photo_thumb';
  }
  else if (image.src.match(/other/)) {
    swap_path = image.src.replace(/other/, 'other_thumbs');
    id = 'alt_photo_'; //stop gap, should put the actual id in here someday
  }

  thumbnail.src = swap_path;
  ref.id = id;
  image.src = path;
  
  dynamicLinks();
}



/*
Yellow Fade
*/
function YellowFade() {
  var FadeInterval = 300; // This is the amount of time (in milliseconds) that will lapse between each step in the fade

  // This is where the fade will start, if you want it to be faster and start with a lighter color, make this number smaller
  // It corresponds directly to the FadeSteps below
  var StartFadeAt = 7;
    
  DoFade(StartFadeAt, 'notice', FadeInterval);
}

function DoFade(colorId, targetId, FadeInterval) {
  var FadeSteps = new Array();
    FadeSteps[1] = "ff";
    FadeSteps[2] = "ee";
    FadeSteps[3] = "dd";
    FadeSteps[4] = "cc";
    FadeSteps[5] = "bb";
    FadeSteps[6] = "aa";
    FadeSteps[7] = "99";
    
  if (colorId >= 1) {
    if (document.getElementById(targetId)) {
      document.getElementById(targetId).style.backgroundColor = "#ffff" + FadeSteps[colorId];

      colorId--;
    
      // Wait a little bit and fade another shade
      setTimeout("DoFade("+colorId+",'"+targetId+"',"+FadeInterval+")", FadeInterval);
   }
  }
}

/*
Google Analytics 
(requires <script src="http://www.google-analytics.com/urchin.js" type="text/javascript"></script> in the head)
*/
function loadGA()
{
  // Check to make sure it's loaded before trying to call it
  if (typeof urchinTracker == "function") {
    _uacct = "UA-2139549-1";
    urchinTracker();
  }
}

/* 
Generic Dynamic Load Script
*/

function loadScript(id, url)
{
  if (!document.getElementById) return;
  target = document.getElementById(id);
  
  s = document.createElement('script');
  s.src = url;
  s.type = 'text/javascript';
  
  target.appendChild(s);
}


/*
Unobtrusive onload event function
Author: Simon Wilson - http://simonwillison.net/2004/May/26/addLoadEvent/
*/
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

addLoadEvent(dynamicLinks);
addLoadEvent(YellowFade);
addLoadEvent(loadGA);

function loadShipping(event) {
  new Ajax.Request('/shop/calculate_shipping', {
    asynchronous:true,
    evalScripts:true,
    onComplete:function(request){
      setupShipping();
    },
    onLoading:function(request){
      $('shipping').innerHTML = '<p style="font-size:18px">Loading shipping options…<img src="/images/ajax-loader1.gif" /></p>';
      Element.show('calculating');
    },
    parameters:Form.serialize($('shipping-billing'))});
}

function setupShipping() {
  a = new Array();
//  a.push($('shop_order_shipping_state_prov'));
  a.push($('shop_order_shipping_postal_code'));
  a.push($('shop_order_shipping_country'));
  a.push($('shop_order_shipping_po_box'));
  /*a.push($('shop_order_promo_code'));
  a.push($('dbhDollars'));*/
  updateTotals = function(event) {
    shipping = parseFloat($('price_' + event.element().id).innerHTML.gsub('\\$','').gsub('Free!', '0.00'));
    subtotal = parseFloat($('cart-subtotal').innerHTML.gsub('\\$',''));
    tax = parseFloat($('cart-tax').innerHTML.gsub('\\$',''));
    if ($('shop_order_shipping_state_prov').getValue() == 'CA') {
      tax = (subtotal + shipping) * 0.0775;
      $('cart-tax').innerHTML = '$' + tax.toFixed(2);
    }
    $('shipping-cost').innerHTML = '$' + shipping.toFixed(2);
    $('cart-total').innerHTML = '$' + (subtotal + tax + shipping).toFixed(2);
  }
  a.each(function (e) {
    if (e) {
      e.observe('change', loadShipping);
    }
  });
  $$('#shipping input').each(function (e) {
    e.observe('change', updateTotals);
  });

}

var firstSetup = true;
document.observe('dom:loaded', function () {
  if(!firstSetup) {
    return;
  }
  firstSetup = false;
  if($('shipping-billing')) {
    setupShipping();
  }
  if($('fims-scanner')) {
    $('order_id').focus();
    $('order_id').observe('keyup', function(event) {
      if (ids.indexOf($('order_id').getValue().gsub('^0+','')) != -1) {
        window.open('/admin/orders/fims_label?order[id]=' + $('order_id').getValue());
        ids = ids.without($('order_id').getValue().gsub('^0+',''));
        count = parseInt($('fims-count').innerHTML, 10);
        $('fims-count').innerHTML = count - 1;
        $('order_id').value = '';
      }
    });
  }
});

