document.observe("dom:loaded", function() {
	if ($$('body')[0].hasClassName('cms-home')) {
		window.sliders = new Array();
		slideShow('left');
		slideShow('right');
	}
	if ($$('body')[0].hasClassName('catalog-product-view')) prodView();
	catView();
	catNav();
	socialLinks();
});

function catView() {
	//add another element hook to refine by style links
	$$('.refine-by-style-links li a').each(function(e){
		e.wrap(new Element('div', { 'class': 'inner' }));
	});

	// clear the refine search session var on main menu click
	$$('#nav .level0 a').each(function(e){
		e.observe('click', function(e){
			var url = '/set_refine.php';
		    var pars = 'refine=all';
		    var myAjax = new Ajax.Request(url, {
		      method: 'get',
		      parameters: pars,
		      onSuccess: function(transport) {
		      	window.location = this.readAttribute('href');
		      }
		    });
		    //Event.stop(e);
		});
	});
}

function catNav() {
	$$('#nav .nav-2 a')[0].setAttribute('href', '/everyday-collection/botanicals.html');
}

function prodView() {
	if ($$('.card-type')[0].hasClassName('petite_notes')) {
		noCustomizeOptions();
		return false;
	}
	if ($$('.also-like li').length) renderAlsoLikeImgs();
	$$('#ask-personalize', '#re-open', '.product-options', '.product-options-bottom', '.product-img-preview', '#start-over').each(function(c){c.hide()});
	$$('.product-options dl dt:nth-last-of-type(1)')[0].addClassName('last');
	$$('.product-options textarea')[0].setAttribute('disabled', 'disabled');
	var personalizedField = $$('.product-options textarea')[0].up();
	var personalizedFieldDt = $$('.last label')[0].up();
	var uploadField = $$('input[type=file]')[0].up();
	
	personalizedField.addClassName('hide');
	personalizedFieldDt.addClassName('hide');
	
	if(personalizedField.previous() != null) {
		personalizedField.previous().addClassName('hide');
	}
	
	uploadField.addClassName('hide');

	if(uploadField.previous() != null) {
		uploadField.previous().addClassName('hide');
	}
	
	$('order-now').observe('click', function(e){
		if (this.hasClassName('on')) {
			var el = Event.element(e);
			this.fade({ duration: 0.5, from: 1, to: .25 }).removeClassName('on');
			if (window.style == "photo") {
				openEditor();
				$('personalize-yes').setAttribute('checked', 'yes');
				$('product_addtocart_form').getInputs('radio', 'personalize').invoke('disable');
				setTimeout(function(){new Effect.SlideDown($('ask-personalize'), { duration: 0.5});}, 500);
			} else {
				new Effect.SlideDown($('ask-personalize'), { duration: 0.5});
			}
		}
		Event.stop(e);
	});
	
	
	$$('#personalize-yes', '#re-open a').each(function(e){
		e.observe('click', function(e){
			openEditor();
		});
	});
	
	$$('#personalize-no').each(function(e){
		e.observe('click', function(e){
			showDelivery('no customization');
		});
	});
	
	$('personalize-no').observe('click', function(e){
		$('re-open').hide();
	});
	

	/*
$('return').observe('click', function(e){
		var el = Event.element(e);
		Event.stop(e);
		showDelivery();
	});
*/
}

function renderAlsoLikeImgs() {
	/*
$$('.also-like.large')[0].setStyle({
		visibility: 'visible'
	});
*/
	$$('.also-like.large li, .also-like.large').each(function(e){
		e.hide();
	});
	$$('.also-like.minis li').each(function(e){
		var i = $$('.also-like.minis li').indexOf(e);
		e.observe('mouseover', function(f){
			$$('.also-like.large')[0].addClassName('activated').show();
			if ($$('.also-like.large li')[i]) $$('.also-like.large li')[i].show();
			var img = $$('.also-like.large li')[i].select('img')[0];
			if (img && (img.getDimensions().width > img.getDimensions().height)) {
				img.up().up().addClassName('landscape');
			} else {
				img.up().up().addClassName('portrait');
			}
			//if ($$('.also-like.large li')[i-1]) new Effect.Opacity($$('.also-like.large li')[i-1], { from: 0, to: 1, duration: 0.25 });
		});
		e.observe('mouseout', function(f){
			$$('.also-like.large')[0].removeClassName('landscape').removeClassName('portrait');
			$$('.also-like.large li, .also-like.large').each(function(g){
				g.hide();
			});
		});
		/*
var imgs = $$('.also-like.large li img');
		for (var j = 0; j < imgs.length; j++) {
			if (imgs[j] && (imgs[j].getDimensions().width > imgs[j].getDimensions().height)) {
				imgs[j].up().addClassName('landscape');
			} else {
				imgs[j].up().addClassName('portrait');
			}
		}
*/
	});
}
	
function noCustomizeOptions() {
	var options = $('modal-add', 'start-over');
	options.push($$('.product-img-preview')[0]);
	options.each(function(e){
		e.hide();
	});
	$$('.short-description')[0].insert($$('.add-to-box')[0]);
}
	
function openEditor() {
	$('re-open').show();
		var width = 944;
		if (Prototype.Browser.Gecko || Prototype.Browser.IE) width = 1014;
		Shadowbox.open({
	        content:    window.loc,
	        player:     "iframe",
	        height:     680,
	        width:      width
    	});
    	overrideClose();
    	//$('product_addtocart_form').getInputs('radio', 'personalize').invoke('disable');
}

function overrideClose() {
	$('sb-nav-close').removeAttribute('onclick');
	$('sb-nav-close').observe('click', function(e){
		var answer = confirm("Are you sure you want to stop personalizing your card? You will lose your changes.");
		if (answer){
			Shadowbox.close();
			resetPersonalize();
		}
	});
}

function resetPersonalize() {
	$('personalize-yes').checked = false;
	$('personalize-no').checked = false;
	$$('#start-over')[0].hide();
	$('product_addtocart_form').getInputs('radio', 'personalize').invoke('enable');
	new Effect.SlideUp($('ask-personalize'), { duration: 0.5});
	$('order-now').fade({ duration: 0.5, from: .25, to: 1 }).addClassName('on');
}

// call this on add to cart
function enablePersonalizedText(){
	if (!$$('.card-type')[0].hasClassName('petite_notes')) $$('.product-options textarea')[0].removeAttribute('disabled');
}

function showDelivery(noCust) {
	new Effect.SlideDown($$('.product-options')[0], { duration: 0.5});
	new Effect.SlideDown($$('.product-options-bottom')[0], { duration: 0.5});
	if (!noCust) {
		$$('#start-over')[0].show();
		$$('.product-img-box')[0].hide();
	}
}

function send(msg) {
		//alert('send' + msg);
        XD.postMessage(msg, window.loc, frames[0]);
        return false;
    }

XD.receiveMessage(function(message) {
	var options = message.data;
	var msgArray = options.split("~|~",2);
	//alert('receive: ' + options);
	if (options == 'close') {
		//if personalization is finished
	    Shadowbox.close();
	    setTimeout(function(){showDelivery();}, 200);
    } else if (options == 'wait') {
	    $('sb-loading').setAttribute('style', '');
	    $('sb-loading').setOpacity(.75);
    } else if (msgArray.length == 2) {
	    //if card params are being sent
	    setPersonalizedSessionId(msgArray[0]);
		var img = '<img src="/image.php/' + window.prodid + '_' + msgArray[0] + '_final.png?width=312&amp;height=312&amp;image=/var/personalize/' + window.sessid + '/' + window.prodid + '/' + window.prodid + '_' + msgArray[0] + '_final.png" alt="Your personalized card">';
		$$('.product-img-preview .inner')[0].update(img);
		$$('.product-options textarea')[0].value = msgArray[1];
		productPersonalizeSuccess();
		send('success');
    } 
}, 'http://personalize.hautenote.com');

function productPersonalizeSuccess() {
	$('modal-add').hide();
	//$$('.email-friend')[0].hide();
	setTimeout(function(){$$('.product-img-preview')[0].show();}, 300);
}



function setPersonalizedSessionId(sessId){
	var url = '/set_personalize.php';
    var pars = 'pers_sess=' + sessId ;
    var myAjax = new Ajax.Request(url, {
      method: 'get',
      parameters: pars,
      onSuccess: function(transport) {
         // do nothing
       }
     });
}

function socialLinks() {
	$$('.social-links li.fb a')[0].setAttribute('href', 'http://www.facebook.com/share.php?u='+window.location.href);
	$$('.social-links li.tw a')[0].setAttribute('href', 'http://twitter.com/home?status='+window.location.href);
}

function slideShow(side) {
	var imgs = $$('.slideshow.' + side + ' img');
	var caption = $$('.slideshow.' + side + ' #caption');
	window.slideMax = imgs.length;
	window[side + 'Count'] = 0;
	//Set the opacity of all images to 0
	imgs.each(function(c){
		c.setOpacity(0);
	});
	
	//Get the first image and display it (set it to full opacity)
	imgs[0].setStyle({visibility: 'visible'}).setOpacity(1);
	
	//Set the caption background to semi-transparent
	//$('.view-photo-carousel .caption').css({opacity: 1});

	//if ($('.view-photo-carousel .views-row:first').find('img').attr('rel') == '') $('.view-photo-carousel .caption').css({opacity: 0.0, height: '1px'});

	//Resize the width of the caption according to the image width
	//$('.view-photo-carousel .caption').css({width: $('.view-photo-carousel .views-row').find('img').css('width')});
	
	//Get the caption of the first image from REL attribute and display it
	if (caption.length) {
		caption[0].select('div.inner')[0].update($$('.slideshow img:first-child')[0].readAttribute('title'));
		$$('.caption-pager li a')[0].addClassName('active');
		caption[0].select('.caption-pager li').each(function(c){
			c.select('a')[0].i = $$('.caption-pager li').indexOf(c);
			c.select('a')[0].observe('click', respondToClick);
		});
	}
			
	function respondToClick(event) {
		var e = Event.element(event);
		clearInterval(window.left);
		gallery(side, caption, e.i);
	}
	//.animate({opacity: 1}, 400);
	
	//Call the gallery function to run the slideshow, 6000 = change to next image after 6 seconds
	var stagger  = Math.random()*1000;
	setTimeout(function(){
		window[side] = setInterval(function() {gallery(side, caption)},4000);
	}, stagger);
	
}

function gallery(side, caption, ix) {
	if (++window[side + 'Count'] >= window.slideMax) clearInterval(window[side]);
	var imgs = $$('.slideshow.' + side + ' img');
	if (ix == undefined) {
		var current = ($$('.slideshow.' + side + ' img.show').length) ? $$('.slideshow.' + side + ' img.show')[0] : imgs[0];
	}
	else {
		imgs.each(function(c){
			c.removeClassName('show');
		});
		var current = (ix == 0) ? imgs[imgs.length-1] : imgs[ix-1];
		
	}

	var next = ((current.next()) ? current.next() : imgs[0]);
	
	//Set the fade in effect for the next image, show class has higher z-index
	next.setOpacity(0);
	next.addClassName('show').setStyle({visibility: 'visible'});
	new Effect.Opacity(next, { from: 0, to: 1, duration: 1.0 });

	//Hide the current image
	new Effect.Opacity(current, { from: 1, to: 0, duration: 1.0 });
	current.removeClassName('show');
	
	if (caption.length) {
		var iz = (ix) ? ix : $$('.slideshow.' + side + ' img').indexOf($$('.slideshow.' + side + ' img.show')[0]);
		caption[0].select('.caption-pager li a').each(function(c){c.removeClassName('active')});
		$$('.caption-pager li a')[iz].addClassName('active');
		//Get next image caption
		var captionText = next.readAttribute('title');
		if (!Prototype.Browser.IE) caption[0].setOpacity(0);
		
		if (captionText != '') {
			setTimeout(function(){
				//Set the opacity to 0 and height to 1px
				Effect.Queues.get('captions').invoke('cancel');
				new Effect.SlideDown(caption[0], { duration: 0.5, position: 'front', scope: 'captions'});
				if (!Prototype.Browser.IE) new Effect.Opacity(caption[0], { from: 0, to: 1, duration: 0.5 });
				//Display the content
				caption[0].select('div.inner')[0].update(captionText);
			}, 300);
		}
	}
	
}

function mouseover(){ /* dummy function to catch event error */}
function mouseout(){ /* dummy function to catch event error */}
