/*


Dynamic Application of Functions to DOM
*/
var _debugMode = true;
Event.observe(document, 'dom:loaded', init);
Event.observe(window, 'load', initAfterImages);


function init () {
  new Gallery();

  var scaleImage = $$('#feature > a > img')[0];
  if (scaleImage) $('feature').setStyle({opacity: '0'});
  
  $$('.homeColumn').equalizeHeights();

  if ($('SlideShow')) new SlideShow('SlideShow', { interval: 4, fadeTime: 2.5 });
  
  if ($('contact_us_comments') && readCookie('artworkTitle')) {
    $$('.recentlyViewed')[0].setOpacity(0);
    $('contact_us_comments').update('I am interested in ' + readCookie('artworkTitle') + '.\n');
  }
  if ($('formSubmit'))  
    $('formSubmit').observe('click', function() {
      $('galleryForm').request({
        onSuccess: function() { window.location = '/Thank-You' } 
      });
    })
  
  $('deleteCookie').observe('click', function() { 
    eraseCookie('artworkTitle');
    eraseCookie('picturePath');
    });
    
  if ($$('#textColumn > object')[0]) $('imageRight').hide(); 

  // pricelist alternating tables
  if($('price_list_table')) {
    $$('#price_list_table tr:nth-child(odd)').invoke('addClassName', 'odd');
    $$('#price_list_table tr:nth-child(even)').invoke('addClassName', 'even');
  }
  
}  

function initAfterImages () {
  var scaleImage = $$('#feature > a > img')[0];
  
  if (scaleImage) {
    scaleImage.uniformScale(300, 'vertical');
    $('feature').appear();
  }
  
  
  if ($('contact_us_comments') && readCookie('picturePath')) {
    $$('.recentlyViewed img')[0].writeAttribute({src: readCookie('picturePath')});
    $$('.recentlyViewed')[0].appear({delay: 1});
  }
} 

function addHover() {
  $$('#imageRight > a > span')[0].show().setStyle({opacity: '.7'});
}

function removeHover() {
  $$('#imageRight > a > span')[0].hide();
}

Element.addMethods('img', {
  uniformScale: function(el, scaledSize, aspectRatio) {
    var el = $(el);
    var height = el.getHeight();
    var width = el.getWidth();
    var ratio = (height > width) ? width/height : height/width;
    var scaledSize = scaledSize || 300;
    
    var base = scaledSize + 'px';
    var modified = scaledSize * ratio + 'px';
    
    switch (aspectRatio) {
      case 'vertical':
        if (width > height) {
          ratio = scaledSize/height;
          modified = width * ratio + 'px';
          el.setStyle({ height: base, width: modified });
        }
         else el.setStyle({ height: base, width: modified });
        break;
      // case 'horizontal':
      //   console.log('here');
      //   break
      default:
        if (height > width) el.setStyle({ height: base, width: modified });
        else el.setStyle({ width: base, height: modified });
    }
    return el;  
  }
});

Object.extend(Array.prototype, {
  equalizeHeights: function(tolerance){
    //equalize the heights of columns
    if (this.any(function(el){
      return Object.isElement(el)
    }))
      this.invoke('setStyle', {
        height: this.map(function(el){
          return el.getHeight()
        }).max() + 'px'
      });
    return this;
  }
});


function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
  var rv = -1; // Return value assumes failure.
  if (navigator.appName == 'Microsoft Internet Explorer')
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}




// PORTFOLIO FUNCTIONS
function updateGalleryNav(current_gallery_url) {
  var url = "/portfolio-data";
  var updateGalleryAjax = new Ajax.Request(url, {
    onSuccess: function(transport) {
      gallery_list = transport.responseText.evalJSON();
      nav_galleries = portfolioPrevNext(gallery_list,current_gallery_url);
      updateGalleryContainer(nav_galleries);
    }
  });
}

function portfolioPrevNext(gallery_list,current_gallery_url) {
  
  // ITERATE THROUGH LIST
  var nav_galleries = new Array(null,null); // place holders for each gallery object to be inserted
  for (var i=0; i<gallery_list.length; i++) {
    if(current_gallery_url == gallery_list[i].gallery.url) {
      if(i-1 > -1) {                  nav_galleries[0]  = gallery_list[i-1]; } // previous
      if(i+1 < gallery_list.length) { nav_galleries[1]  = gallery_list[i+1]; } // next
    }
  }
  
  return nav_galleries;
  
}

function updateGalleryContainer(nav_galleries) {
  if($('gallery_nextprev')) {
    html = '';
    if(nav_galleries[0] != null) {
      html += "<div class=\"gallery_nav_button\" id=\"gallery_prev\"><h6><a href=\""+nav_galleries[0].gallery.url+"\" title=\""+nav_galleries[0].gallery.name+"\">&lt; Previous</a></h6></div>";
    }
    if(nav_galleries[1] != null) {
      html += "<div class=\"gallery_nav_button\" id=\"gallery_next\"><h6><a href=\""+nav_galleries[1].gallery.url+"\" title=\""+nav_galleries[1].gallery.name+"\">Next &gt;</a></h6></div>";     
    }
    html += "<div class=\"clear\"></div>";
    $('gallery_nextprev').update(html); // update gallery nav container
  }
}