// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

var shipping_costs = new Hash();

function calculate_order_total(radio){
	$('order_total_cell').update(number_to_currency(order_total_without_shipping + shipping_costs.get(radio.value)));
}

function number_to_currency(number, options) {
	try {
 		var options   = options || {};
		var precision = options["precision"] || 2;
 		var unit      = options["unit"] || "$";
 		var separator = precision > 0 ? options["separator"] || "." : "";
		var delimiter = options["delimiter"] || ",";
   
 		var parts = parseFloat(number).toFixed(precision).split('.');
		return unit + number_with_delimiter(parts[0], delimiter) + separator + parts[1].toString();
	} catch(e) {
		return number
	}
 }

function number_with_delimiter(number, delimiter, separator) {
	try {
		var delimiter = delimiter || ",";
 		var separator = separator || ".";

		var parts = number.toString().split('.');
		parts[0] = parts[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1" + delimiter);
		return parts.join(separator);
	} catch(e) {
		return number;
	}
}

artImageIndex = 0;
shoppingCartOpen = false;

function getArtImages(next_previous) {
  artImageIndex += (next_previous == 0) ? -18 : 18;
  var url = "/art_images/get_images/X?start="+artImageIndex;
  var options = {};
  options.asynchronous  = true;
  options.evalScripts  = true;
  options.defaultParams = options.parameters || null;
  options.method = 'get'
  new Ajax.Request(url, options);  
}

function showArtImageOverlay(id, index) {
  var overallIndex = artImageIndex + index
  var url = "/art_images/get_detail/"+id+"?index="+overallIndex
  var options = {};
  options.asynchronous  = true;
  options.evalScripts  = true;
  options.defaultParams = options.parameters || null;
  options.method = 'get'
  new Ajax.Request(url, options);  
}

function hideDetail() {
  $("thumbnailOverlayWrapper").style.display = "none";
}

function prevNextDetailImage(id, index, next_previous) {
  var overallIndex = artImageIndex + index
    var url = "/art_images/" + (parseInt(index) + next_previous) + '/at'
  var options = {};
  options.asynchronous  = true;
  options.evalScripts  = true;
  options.defaultParams = options.parameters || null;
  options.method = 'get'
  new Ajax.Request(url, options);  
}

function toggleTagsOverlay() {
    if(!$("thumbnailTagsOverlayWrapper").visible()) {
	$('filterPagesLink').setStyle({background: 'url(/images/look-inside-overlay.png)'}); 
	$("filterPagesLink").down().setStyle({color: "#FFF"})
	$('thumbnailTagsOverlayWrapper').appear({ duration: 0.3 });
    }
}

function openCart () {
  if (!shoppingCartOpen) {
	$("shopping_cart_wrapper").visualEffect("slide_down", "shopping_cart_slide", {easing: "Sine.ease.in"});
    shoppingCartOpen = true;
    window.location.hash = "cart";
  }  
}

function closeCart () {
  if (shoppingCartOpen) { 
    $("shopping_cart_wrapper").visualEffect("slide_up", "shopping_cart_slide", {easing: "Sine.ease.in"});
    shoppingCartOpen = false;
    window.location.hash = "";
  }  
}

function toggleTagsOverlayOld() {
  if(!$("thumbnailTagsOverlayWrapper").visible()) {
    $('filterPagesLink').setStyle({backgroundColor: '#000'}); 
    var url = "/art_images/get_tag_categories/X";
    var options = {};
    options.asynchronous  = true;
    options.evalScripts  = true;
    options.defaultParams = options.parameters || null;
    options.method = 'get'
    new Ajax.Request(url, options);  
    
    $("filterPagesLink").setStyle({backgroundColor: "#000"})
    $("filterPagesLink").down().setStyle({color: "#FFF"})
  }
  else {
    $("thumbnailTagsOverlayWrapper").hide();
    $("filterPagesLink").setStyle({backgroundColor: null})
    $("filterPagesLink").down().setStyle({color: "#000"})
  }
}

function getTagsWithCategory(id, index) {
  $$('.tag-category-link').each(function(el) {
    //alert(index+'vvvv');  
    el.setStyle({textDecoration: 'none'});

  });

  $('tag-category-link-'+index).setStyle({textDecoration: 'underline'});
  
  var url = "/art_images/show_tags_for_category/X?category_id="+id;
  var options = {};
  options.asynchronous  = true;
  options.evalScripts  = true;
  options.defaultParams = options.parameters || null;
  options.method = 'get'
  new Ajax.Request(url, options);    
}

function changeLocale(locale) {
  document.location = "/locale/set?locale="+locale;
}

function sortByTag(id) {
  var url = "/art_images/sort_by_tag/X?tag_id="+id.replace('art_image_tag_ids_', '');
  var options = {};
  options.asynchronous  = true;
  options.evalScripts  = true;
  options.defaultParams = options.parameters || null;
  options.method = 'get'
  new Ajax.Request(url, options);  
}

function showSelectedTags() {
  var url = "/art_images/show_selected_tags/X";
  var options = {};
  options.asynchronous  = true;
  options.evalScripts  = true;
  options.defaultParams = options.parameters || null;
  options.method = 'get'
  new Ajax.Request(url, options);
}
function clearAllSelectedTags() {
  
}

function changeBook(el, id, color, instock) {
  $$('#colors a').each(function(e) {
    e.removeClassName("active");
  });

  $('mainBook').src = "/images/products/"+color+".png";
  el.addClassName("active");
  
  if (!instock) {
	$("featuredProductAddToCart").down("a").hide();
	$("mainBookSoldOut").style.display = "inline";
  }else{
	$("featuredProductAddToCart").down("a").show();
	$("variants_book").name = "variants["+id+"]";
	$("mainBookSoldOut").style.display = "none";
  }
}

function addToCart(el) {
	$(el).up('form').onsubmit();
}

function showGeneralToteDetail(imgSrc) {
  $("promoToteDetailImg").src = imgSrc;
  if ($("promoInfo")!=null) $("promoInfo").hide();
  if ($("promoInfoJP")!=null) $("promoInfoJP").hide();
  $("promoToteDetail").show();
}

function showToteDetail(imgSrc) {
  $("promoToteDetailImg").src = imgSrc;
  if ($("promoInfo")!=null) $("promoInfo").hide();
  if ($("promoInfoJP")!=null) $("promoInfoJP").hide();
  $("promoToteDetail").show();
}

function closeToteDetail() {
	$('promoToteDetail').hide();
  if ($("promoInfo")!=null) $("promoInfo").show();
  if ($("promoInfoJP")!=null) $("promoInfoJP").show();
}

var customersABItemsLength;
var customersABLastElementId = 0;

function renderCustomersAB(srcobj) {
var htmlBlock = "";
customersABItemsLength = srcobj.length;
for (var i=0; i<customersABItemsLength; i++) {
	htmlBlock += '\n<div class="customersABSelection">';
	
	//title
	htmlBlock += ' <div class="customersABSelectionTitle">';
	htmlBlock += '  <h3>'+srcobj[i]["title"]+'</h3>';
	htmlBlock += ' </div><!--customersABSelectionTitle -->';
	
	//img
	htmlBlock += ' <div class="customersABSelectionImage">';
	htmlBlock += '  <img class="thumbnailTagsPic" src="'+srcobj[i]["image"]+'">';
	htmlBlock += ' </div><!--customersABSelectionImage -->';
	
	//author
	if (srcobj[i]["author"].length < 130) {
	htmlBlock += ' <div class="customersABSelectionAuthor">';
	htmlBlock += '  <p>by '+srcobj[i]["author"]+'</p>';
	htmlBlock += ' </div><!--customersABSelectionAuthor -->';
	}
	
	//price
	htmlBlock += ' <div class="customersABSelectionPrice">';
	htmlBlock += '  <p>'+srcobj[i]["price"]+'</p>';
	htmlBlock += ' </div><!--customersABSelectionPrice -->';	
	
	//buy
	htmlBlock += ' <div class="customersABSelectionBuy">';
	htmlBlock += '  <a href="'+srcobj[i]["link"]+'" target="_blank">→ '+buy_now+'</a>';
	htmlBlock += ' </div><!--customersABSelectionBuy -->';			
	
	//end Block
	htmlBlock += "</div>";				
}

htmlBlock += "<div class='clear'></div>";
$("customersABItemsContainer").innerHTML = htmlBlock;	
}

function moveTo(container, element){
	Position.prepare();
	container_x = Position.cumulativeOffset($(container))[0];
	element_x = Position.cumulativeOffset($(element))[0];
	new Effect.Scroll(container, {x:element_x-container_x, y:0} );
	return false;
}


function customersABNextButtonPressed() {
	if ($$(".customersABSelection")[customersABLastElementId+5]!=null) customersABLastElementId += 5;
	else return false;

	$$("#customersAB .prev-button")[0].style.display = "inline";
	var element = $$(".customersABSelection")[customersABLastElementId];
	var elwrapper = $("customersABItemsWrapper");
	moveTo(elwrapper,element);

	return false;
}

function customersABPrevButtonPressed() {
	if (customersABLastElementId>0) customersABLastElementId -= 5;
	else return false;
	
	if (customersABLastElementId==0) {
		$$("#customersAB .prev-button")[0].style.display = "none";
	}
	
	var element = $$(".customersABSelection")[customersABLastElementId];
	var elwrapper = $("customersABItemsWrapper");
	moveTo(elwrapper,element);	

	return false;
}

var exhibitionSlideshowLastElementId = 0

function exhibitionSlideshowNextPressed() {
	if ($$(".exhibiton-slideshow-wrapper img")[exhibitionSlideshowLastElementId+1]!=null) exhibitionSlideshowLastElementId += 1;
	else return false;

	$$("#exhibition_info .prev-button")[0].style.display = "inline";
	var element = $$("#exhibiton-slideshow img")[exhibitionSlideshowLastElementId];
	var elwrapper = $("exhibiton-slideshow");
	moveTo(elwrapper,element);
	
	$("exhibition-slideshow-current-page").innerHTML = exhibitionSlideshowLastElementId+1;

	return false;	
}

function exhibitionSlideshowPrevPressed() {
	if (exhibitionSlideshowLastElementId>0) exhibitionSlideshowLastElementId -= 1;
	else return false;
	
	if (exhibitionSlideshowLastElementId==0) {
		$$("#exhibition_info .prev-button")[0].style.display = "none";
	}
	
	var element = $$("#exhibiton-slideshow img")[exhibitionSlideshowLastElementId];
	var elwrapper = $("exhibiton-slideshow");
	moveTo(elwrapper,element);	
	
	$("exhibition-slideshow-current-page").innerHTML = exhibitionSlideshowLastElementId+1;

	return false;	
}

function openEditorialExtraPar() {
	$("continueReading").hide();
	$("editorialExtraPar").style.display = "block";
}

function select_review_set(type) {
  $$('.reviews_set').each(function (el) {
    el.hide();
  });
  $$('#review_btns a').each(function (el) {
    el.removeClassName("active");
    if(el.id == type+"_btn") el.addClassName("active"); 
  });
  $(type+"_reviews").show();
}

function submitReview(el) {
	var ok = true;
	var form = $("new_review");
	
	if (form.spam_bot.value!="is") {
		$("customerReviewFormError").style.color = "red";
		$("customerReviewFormError").innerHTML = "You filled in the blank incorrectly. Please try again.";
		ok = false;			
		return;
	}
	
	var required = ['review[author]',"email","review[subject]","review[review_text]"];
	for (var i=0; i < required.length; i++) {
		if (form[required[i]].value=="") {
			$("customerReviewFormError").style.color = "red";
			$("customerReviewFormError").innerHTML = "All fields are required.";
			ok = false;
			return;
		}
	};
	
	if (ok) $(el).up('form').submit();		
}

// }

// from: http://github.com/madrobby/prototype_helpers/blob/master/deferUntil/deferuntil.js
Function.prototype.deferUntil = function(condition){
  this.interval = setInterval(function(){
    if (!condition()) return;
    clearInterval(this.interval);
    this();
  }.bind(this), 50);
};

var Preloader = {
    load: function() {
	var args = $A(arguments);
	var callback = Object.isFunction(args.last()) ? args.pop() : Prototype.emptyFunction;
	var urls = Object.isArray(args[0]) ? $A(args[0]) : args;
	var loaded = 0;
	var images = $A();

	var onload = function() {
	    loaded++;
	    if (loaded == urls.length) {
		callback();

		// cleanup
		images.each(function(i) { delete i });
		images = callback = urls = null;
	    }
	};

	urls.each(function(url) {
	    var image = new Image();
	    image.onload = image.onerror = onload;
	    image.src = url;
	    images.push(image);
	});
    }
};

var ImageFilter = Behavior.create({
    initialize: function(tags) {
	// set-up the internal state
	this.selected_tags = $A(tags);
	this.server_tags = $A(tags);
    },

    updater: function() {
	if (this.server_tags.inspect() != this.selected_tags.inspect()) {
	    var params = this.selected_tags.collect(function(tag) {
			return "tags[]=" + tag;
	    }).join("&");

	    new Ajax.Request('/art_image_tags/select.js', {
		method: 'post',
		parameters: params,
		onSuccess: function(response) {
		    var data = response.responseJSON;
		    this.server_tags = $A(data['tags']);
		    $('selected_total').update(data['selected']);
		    $('results_total').update(data['images']);
		}.bind(this)
	    });
	}
    },

    force: function() {
	this.executer.stop();
	this.updater();
    },

    categories: function(event) {
	event.stop();

	this.underline(event.findElement('a'), $$('.tags-for'));

	if ($('tag_cats_list_wrapper').visible() == false)
	    new Effect.SlideDown('tag_cats_list_wrapper');
    },

    tag: function(event) {
	if (checkbox = event.findElement('input')) {
	    var selected = parseInt($('selected_total').innerHTML);
	    $('results_total').update('<img src="/images/tag-waiter.gif"/>');
	    $$('#detail_menu_3 .results').invoke('setStyle', { textDecoration: null });

	    if ($F(checkbox) == null) {
		var id = checkbox.id.split(/_/).last();
		$('selected_total').update(selected - 1);
		if ((pos = this.selected_tags.indexOf(id)) >= 0)
		    this.selected_tags.splice(pos, 1)
	    }
	    else {
		this.selected_tags.push($F(checkbox));
		$('selected_total').update(selected + 1);
	    }
	}
    },

    clear: function(event) {
	this.selected_tags.clear();
	$('results_total').update('0');
	$('selected_total').update('0');
	$$('.tag input').invoke('setValue', null);
	$('viewing-type').update("");
	event.stop();
    },

    cancel: function(event) {
	event.stop();

	if(!$("thumbnailTagsOverlayWrapper").visible())
	    $('thumbnailTags').startWaiting('bigWaiting');

	this.clear(event);
	this.force();

	this.close_and_load.bind(this).deferUntil(function() {
	    return this.selected_tags.inspect() == this.server_tags.inspect();
	}.bind(this));
    },

    close_and_load: function() {
	var wait_target = $('thumbnailTags');
	this.close();
	if (!wait_target._waiting) wait_target.startWaiting('bigWaiting');
	this.load_images(function() {
	    wait_target.stopWaiting();
	});
    },

    close: function() {
	if (arguments[0] && arguments[0]['stop']) arguments[0].stop();

	$('thumbnailTagsOverlayWrapper').fade({
	    duration: 0.3,
	    afterFinish: function() {
		$('filterPagesLink').setStyle({ background: '#fff' });
	    }
	});
    },

    search: function(event) {
    },

    tags_for: function(event) {
	event.stop();
	var link = event.findElement('a');
	this.underline(link, $$('.tags-for').concat($$('.categories')));

	// don't switch to the selected tags if there aren't any
	if (link.hasClassName('selected') &&
	    $('selected_total').innerHTML == "0") return;

	// open or close the categories
	if (Object.isUndefined(event.findElement('#tag_cats_list'))) {
	    if ($('tag_cats_list_wrapper').visible())
		new Effect.SlideUp('tag_cats_list_wrapper');
	}

	var params = '';
	if (link.hasClassName('selected')) params = 'selected=1';
	else if (link.hasClassName('most-frequent')) params = 'frequent=1';
	else params = 'category=' + link.readAttribute('rel');

	$('tags_for_category').startWaiting('clearWaiting');

	// load the tags
	new Ajax.Request('/art_image_tags', {
	    method: 'get',
	    parameters: params
	});
    },

    underline: function(target, others) {
	others.invoke('setStyle', { textDecoration: "none" });
	target.setStyle({ textDecoration: 'underline' });
    },

    load_images: function(callback) {
	new Ajax.Request('/art_images', {
	    method: 'get',
	    onSuccess: function(response) {
		var data = response.responseText.evalJSON();
		Thumbnail.loader(data['count'], data['images'],
				 function() {
				     $('look-inside-current-page').update(1);
				     $('look_inside').fire('thumbnail:refresh');
				     callback();
				 }.bind(this));
	    }.bind(this)
	});
    },

    results: function(event) {
	event.stop();

	if (parseInt($('results_total').innerHTML) == 0) {
	    event.findElement('a').setStyle({ textDecoration: 'line-through' });
	    return;
	}

	if (this.server_tags.length == 0 && this.selected_tags.length == 0) {
	    this.close();
	    return;
	}

	$('viewing-type').update('Viewing Filtered (<a href="#" class="cancel">clear results</a>)');
	this.close_and_load();
    },

    open: function(event) {
	if(!$("thumbnailTagsOverlayWrapper").visible()) {
	    event.stop();

	    // kick off the timed updater
	    if (this.executer) this.executer.stop();
	    this.executer = new PeriodicalExecuter(this.updater.bind(this), 2);

	    $('filterPagesLink').setStyle({background: 'url(/images/look-inside-overlay.png)'}); 
	    $('thumbnailTagsOverlayWrapper').appear({ duration: 0.3 });
	}
	else this.close();
    },

    onclick: Event.delegate({
	'.clear': function(e) { this.clear(e) },
	'.cancel': function(e) { this.cancel(e) },
	'.search': function(e) { this.search(e) },
	'.tags-for': function(e) { this.tags_for(e) },
	'.categories': function(e) { this.categories(e) },
	'.results': function(e) { this.results(e) },
	'.open': function(e) { this.open(e) },
	'.close': function(e) { this.close(e) }
    }),

    onchange: Event.delegate({
	'.tag-checkbox': function(e) { this.tag(e) }
    })
});

var Thumbnail = {
    PAGE_SIZE: 18,

    loader: function() {
	var args = $A(arguments);

	// the first argument passed in is the total images which need
	// to be paged through
	var total = args.shift();

	// the middle arguments are the art_image json's for this page
	// of data, but before that, we check if the last argument is
	// a function, and if so, we grab it as a callback to run at
	// the end
	var callback = Object.isFunction(args.last()) ?
	    args.pop() : Prototype.emptyFunction;
	var images = Object.isArray(args.first()) ? $A(args.first()) : args;

	// update the total number of pages
	var root = $('thumbnailImages');
	var pages = Math.ceil(total / Thumbnail.PAGE_SIZE);
	$('look-inside-total-pages').update(pages);

	// get the thumbnail urls so we can preload 'em
	var thumbs = images.collect(function(image) {
	    return image['art_image']['thumb'];
	});

	Preloader.load(thumbs, function() {
	    root.select('a').each(function(link, index) {
		// if we don't have a full page of images, we'll have
		// to hide the rest of 'em
		if (image = images[index]) {
		    image = image['art_image'];
		    link.writeAttribute('rel', image['full']);
		    link.down('img').writeAttribute('src', image['thumb']);
		    link.show();
		}
		else link.hide();
	    });

	    callback();
	});
    },

    Gallery: Behavior.create({
	initialize: function() {
	    this.element.observe('thumbnail:refresh',
				 this.refresh.bindAsEventListener(this));
	},

	next: function(event) {
	    this.load(this.current() + 1);
	    event.stop();
	},

	prev: function(event) {
	    this.load(this.current() - 1);
	    event.stop();
	},

	load: function(page) {
	    var wait_target = $('thumbnailTags');
	    var callback = function() {
		$('look-inside-current-page').update(page);
		wait_target.stopWaiting();
		this.refresh();
	    }.bind(this);

	    new Ajax.Request('/art_images', {
		method: 'get',
		parameters: { page: page },
		onSuccess: function(response) {
		    var data = response.responseText.evalJSON();
		    Thumbnail.loader(data['count'], data['images'],
				     callback);
		}.bind(this)
	    });

	    wait_target.startWaiting('bigWaiting');
	},

	view: function(event) {
	    event.stop();

	    var index = ((this.current()-1) * Thumbnail.PAGE_SIZE) +
		this.element.select('.thumb').indexOf(event.findElement('.thumb')); 

	    new Ajax.Request('/art_images/' + index + '/at', {
		method: 'get'
	    });
	},

	current: function() {
	    return parseInt($('look-inside-current-page').innerHTML);
	},

	total: function() {
	    return parseInt($('look-inside-total-pages').innerHTML);
	},

	refresh: function() {
	    if (this.current() == 1) $('look-inside-prev').hide();
	    else $('look-inside-prev').show();

	    if (this.current() == this.total()) $('look-inside-next').hide();
	    else $('look-inside-next').show();
	},

	onclick: Event.delegate({
	    '#look-inside-prev': function(e) { this.prev(e) },
	    '#look-inside-next': function(e) { this.next(e) },
	    '.thumb': function(e) { this.view(e) }
	})

    }),

    Viewer: Behavior.create({
	next: function() {
	    
	},

	prev: function() {
	}
    })
};

Event.addBehavior({
    '#look_inside': Thumbnail.Gallery
});
