/**
 * Javascript library for template ExtremeMagento
 * @copyright 2007 Quick Solution LTD. All rights reserved.
 * @author Giao L. Trinh <giao.trinh@quicksolutiongroup.com>
 */

(function() {
	
// EM.tools {{{
	
if (typeof BLANK_IMG == 'undefined') 
	var BLANK_IMG = '';

// declare namespace() method
String.prototype.namespace = function(separator) {
  this.split(separator || '.').inject(window, function(parent, child) {
    var o = parent[child] = { }; return o;
  });
};


'EM.tools'.namespace();

EM.tools.roundedCorner = function (selector) {
	$$(selector).each(function(el) {
		$(el).addClassName('em-rounded');
		$(el).insert({
			top: '<span class="tl"> </span><span class="tm"> </span><span class="tr"> </span><span class="ml"> </span><span class="mm"> </span><span class="mr"> </span><span class="bl"> </span><span class="bm"> </span><span class="br"> </span>'
		});
	});
};
EM.tools.roundedCornerTextBox = function () {
	$$('.input-text').each(function(el) {
		if (Element.visible(el) && !el.hasClassName('qty')) {
			$(el).relativize();
			$(el.parentNode).addClassName('em-rounded');
			$(el.parentNode).insert({
				top: '<span class="tl"> </span><span class="tm"> </span><span class="tr"> </span><span class="ml"> </span><span class="mm"> </span><span class="mr"> </span><span class="bl"> </span><span class="bm"> </span><span class="br"> </span>'
			});
		}
	});
};

EM.tools.decorateProductsSlideshow = function(el) {
	var ul = el.select('.products-grid')[0];
	var $$li = ul.childElements();
	var prev = el.select('.previous')[0];
	var next = el.select('.next')[0];
	
	
	$$li.invoke('hide').invoke('setStyle', 'position:absolute');
	ul.down().show().addClassName('current');
	ul.setStyle('position:relative;height:'+ul.down().getHeight()+'px');
	
	if (ul.childElements().length > 1)
		next.addClassName('active');
		
	next.observe('click', function(event) {
		Event.stop(event);
		if (!ul.down('.last').hasClassName('current'))
			nextSlide();
	});
	
	prev.observe('click', function(event) {
		Event.stop(event);
		if (!ul.down('.first').hasClassName('current'))
			prevSlide();
	});
	
	var effect = null;
	var last_li1, last_li2;
	
	function nextSlide() {
		var li = ul.down('.current').removeClassName('current');
		var next_li = li.next().addClassName('current');
		
		if (next_li.hasClassName('last')) next.removeClassName('active');
		if (li.hasClassName('first')) prev.addClassName('active');
		
		sliding(li, next_li);
	}
	
	function prevSlide() {
		var li = ul.down('.current').removeClassName('current');
		var prev_li = li.previous().addClassName('current');
		
		if (prev_li.hasClassName('first')) prev.removeClassName('active');
		if (li.hasClassName('last')) next.addClassName('active');
		
		sliding(li, prev_li);
	}
	
	function sliding(fade_li, appear_li) {
		if (effect != null) { 
			effect.cancel();
			effect = null;
			last_li1.hide();
			last_li2.show();
		}
		
		last_li1 = fade_li;
		last_li2 = appear_li;
		
		effect = new Effect.Parallel([
			new Effect.Fade(fade_li, { sync:true }),
			new Effect.Appear(appear_li, { sync:true })
		], { 
			beforeStart: function() {
				ul.setStyle('height:'+appear_li.getHeight()+'px');
			}, 
			afterFinish: function() {
				effect = null;
			}
		});
	}
	
};


EM.tools.decorateHorizontalSlider = function(div, autoSlide) {
	if (typeof div == 'undefined' || div == null) return;
	
	if (typeof autoSlide == 'undefined')
		autoSlide = true;
	
	var ul = div.down('ul');
	var paging_ul = ul.next();
	var paging_pre_li = paging_ul.down();
	var paging_next_li = paging_pre_li.next();
	var paging_prev_a = paging_pre_li.down();
	var paging_next_a = paging_next_li.down();
	var step_width = ul.down().getWidth();
	var ul_width = 0;
	
	// set UL width
	ul.childElements().each(function(li) {
		ul_width += li.getWidth();
	});
	ul.setStyle({'width': ul_width+'px'});
	
	// active next button if need
	if (ul.getWidth() > div.getWidth()) {
		paging_next_a.addClassName('active');
	}
	
	var manualSliding = false;
	var slideInterval = 3;
	var direction = 1;
	
	function slideNext() {
		var offset = ul.positionedOffset(ul);
		var movable_x = ul.getWidth() - div.getWidth() + offset.left;
		var dx = Math.min(movable_x, step_width);
		
		if (movable_x <= step_width) {
			paging_next_a.removeClassName('active');
			direction = -1;
		}
	
		if (dx > 0)
			paging_prev_a.addClassName('active');
		
		new Effect.Move(ul, { 
			x: -dx,
			mode: 'relative',
			queue: 'end',
			duration: 1.0
		});
	}
	
	function slidePrev() {
		var offset = ul.positionedOffset(ul);
		var dx = Math.min(-offset.left, step_width);
		
		if (-offset.left <= step_width) {
			paging_prev_a.removeClassName('active');
			direction = 1;
		}
			
		if (dx > 0)
			paging_next_a.addClassName('active');
		
		new Effect.Move(ul, { 
			x: dx,
			mode: 'relative',
			queue: 'end',
			duration: 1.0
		});
	}
	
	paging_next_a.observe('click', function(event) {
		Event.stop(event);
		manualSliding = true;
		direction = 1;
		slideNext();
	});
	
	paging_prev_a.observe('click', function(event) {
		Event.stop(event);
		manualSliding = true;
		direction = -1;
		slidePrev();
	});
	
	// auto run slideshow
	if (autoSlide) 
		new PeriodicalExecuter(function() {
			if (!manualSliding) {
				direction > 0 ? slideNext() : slidePrev();
			}
			manualSliding = false;
		}, slideInterval);
};


Effect.BlindRight = function(element) {
  element = $(element);
  var elementDimensions = element.getDimensions();
  return new Effect.Scale(element, 100, Object.extend({
    scaleContent: false,
    scaleY: false,
    scaleFrom: 0,
    scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
    restoreAfterFinish: true,
    afterSetup: function(effect) {
      effect.element.makeClipping().setStyle({width: '0px'}).show();
    },  
    afterFinishInternal: function(effect) {
      effect.element.undoClipping();
    }
  }, arguments[1] || { }));
};

Effect.BlindLeft = function(element) {
  element = $(element);
  element.makeClipping();
  return new Effect.Scale(element, 0,
    Object.extend({ scaleContent: false,
      scaleY: false,
      restoreAfterFinish: true,
      afterFinishInternal: function(effect) {
        effect.element.hide().undoClipping();
      }
    }, arguments[1] || { })
  );
};


// ExtremeMagento.com {{{
	
function decorateCollateralTabs() {
	var collateral = $$('.product-collateral');
	if (collateral.length > 0) {
		collateral = collateral[0];
		
		// create tabs div
		var tabs = new Element('ul');
		tabs.addClassName('tabs-collateral');
		collateral.insert({ top: tabs });
		
		var boxes = $$('.product-collateral .box-collateral');
		boxes.each(function(div, i) {
			var li = new Element('li');
			var a = new Element('a', { href: '#' });
			var span = new Element('span');

			span.innerHTML = div.down('h2').innerHTML;
			a.contentDiv = div;

			a.insert(span);
			li.insert(a);
			tabs.insert(li);

			if (i > 0)
				div.hide();
			else
				li.addClassName('tab-active');
			
			a.observe('click', function(event) {
				boxes.invoke('hide');
				this.contentDiv.show();
				
				this.up('ul').down('li.tab-active').removeClassName('tab-active');
				this.up('li').addClassName('tab-active');
				
				Event.stop(event);
			}.bind(a));
		});
	}
}

function decorateNav() {
	//var path = window.location.pathname.replace(/^\/?(index.php)?\/?/, '');
	var url = window.location.href.replace('http://', '').replace('https://', '');
	var isHome = window.location.pathname.replace(/^\/?(index.php)?\/?/, '') == '';
	var nav = $('nav');
	nav.select('a').each(function(a) {
		var href = a.getAttribute('href').replace('http://', '').replace('https://', '').replace(/\?(.*)$/, '').replace(/#(.*)$/, '').replace('.html', '');
		var isHomeLink = false;

		// check current href is home page url
		var i = href.indexOf(window.location.host);
		if (i != -1 && href.substr(i).substr(window.location.host.length).replace(/^\/(index.php)?\/?/, '') == '')
			isHomeLink = true;
		
		if (isHome && isHomeLink || url.substr(0, href.length) == href && !isHome && !isHomeLink) {
			var el = a;
			while (el != nav) {
				if (el.tagName == 'A' || el.tagName == 'LI')
					Element.addClassName(el, 'active');
				el = el.parentNode;
			}
		}
	});
	
}

function decorateSlideshow() {
	var slideshow = $('slideshow');
	if (slideshow) {
		var current_idx = 0;
		var effectDuration = 1;
		var effectInterval = 6;
		var delay = 5;
		var manualAppear = false;
		var preventAppear = false;
		
		var ul = slideshow.select('.slideshow-box ul')[0];
		if (!ul) return;
		var $$li = ul.select('li');
		$$li.invoke('hide');
		$$li[current_idx].addClassName('current').show();
		
		ul.select('img').each(function(img) {
			var $img = $(img);
			$img.setStyle({ background:'url('+$img.readAttribute('src')+') 0 0 no-repeat'});
			$img.writeAttribute('src', EM_SLIDESHOW_OVERLAY_IMG);
		});
		
		slideshow.down('a.previous').observe('click', function(event) {
			Event.stop(event);
			manualAppear = true;
			if (current_idx > 0) 
				appear(current_idx-1);
			else
				appear($$li.length-1);
		});
		
		slideshow.down('a.next').observe('click', function(event) {
			Event.stop(event);
			manualAppear = true;
			if (current_idx < $$li.length - 1) 
				appear(current_idx+1);
			else
				appear(0);
		});
		
		function appear(i) {
			//if (preventAppear) return;
			//preventAppear = true;
			
			if (typeof i == 'undefined') 
				i = current_idx < $$li.length - 1 ? current_idx+1 : 0;
			
			var hide_li = $$li[current_idx];
			var show_li = $$li[i];
			
			current_idx = i;
			
			new Effect.Parallel([
				new Effect.Fade(hide_li, { sync: true }),
				new Effect.Appear(show_li, { sync: true })
			], {
				queue: { position:'end', scope:'slideshow' },
				duration: effectDuration,
				afterFinish: function() {
					Element.removeClassName(hide_li, 'current');
					Element.addClassName(show_li, 'current');
					//preventAppear = false;
				}
			});
		}
		
		// auto run slideshow
		window.setTimeout(function() {
			new PeriodicalExecuter(function() {
				if (!manualAppear) appear();
				manualAppear = false;
			}, effectInterval);
		}, delay * 1000);
		
	}
}

function decorateProductOverlay() {
	$$('.products-grid').each(function(ul) {
		ul.childElements().each(function(li) {
			var img = li.down('.product-image');
			var overlay = li.down('.overlay');
			if (img && overlay) {
				var showed = false;
				var effect = null;
				function show() {
					if (showed) return;
					showed = true;
					
					var pos = img.positionedOffset();
					overlay.setStyle({'left': pos.left+'px', 'top': pos.top+'px'});
					
					if (effect != null) effect.cancel();
					effect = new Effect.Appear(overlay, { 
						duration: 0.4,
						afterFinish: function() {
							effect = null;
						}
					});
				}
				function hide() {
					if (!showed) return;
					showed = false;
					
					if (effect != null) effect.cancel();
					effect = new Effect.Fade(overlay, { 
						duration: 0.4,
						afterFinish: function() {
							effect = null;
						} });
				}
				var timing = null;
				function delaying(fn) {
					if (timing != null) {
						clearTimeout(timing);
						timing = null;
					}
					timing = setTimeout(function() {
						timing = null;
						fn.call(this);
					}, 100);
				}
				
				// attach events to show/hide the Overlay div
				img.observe('mouseover', function() { delaying(show); })
					.observe('mouseout', function() { delaying(hide); });
				overlay.observe('mouseover', function() { delaying(show); })
					.observe('mouseout', function() { delaying(hide); });
				
				// show images when click on screenshots-link 
				var a = overlay.down('a.screenshots-link');
				var loaded = false;
				var loader = overlay.down('.loader').hide();
				a.observe('click', function(event) {
					Event.stop(event);
					var div = $(a.href);
					if (!div) {
						div = new Element('div', {id: a.href, className: 'hidden'});
						document.body.insert(div);
					}
					if (loaded)
						lightbox.start(div.down());
					else {
						loader.show();
						a.hide();
						new Ajax.Request(a.href, {
							method: 'get',
							onSuccess: function(response) {
								div.update(response.responseText);
								loaded = true;
								lightbox.start(div.down());
							},
							onComplete: function() {
								loader.hide();
								a.show();
							}
						});
					}
				});
				
				// hide Overlay div
				overlay.hide();
				
			}
		});
	});
}


function skybanner_init() {
	try {
		$$('.header-container .sky-banner img')[0].setStyle({ 'visibility':'hidden' });
	} catch(e) {
		// banner doesn't exist, do nothing
	}
}

function skybanner() {
	try {
		var banner = $$('.header-container .sky-banner')[0];
		var img = banner.down('img');

		var offset = banner.positionedOffset();
		var width = banner.getWidth();
		var height = banner.getHeight();
	
		banner.setStyle({ 'top':'0px', 'left':'0px' });
		img.setStyle({ 'width':(width*4)+'px', 'visibility':'visible'}).hide();
	
		new Effect.Parallel([
			new Effect.Appear(img, { sync:true }),
			new Effect.Scale(img, 25, { sync:true }),
			new Effect.Move(banner, { sync:true, x:offset.left, y:offset.top })
		], {
			duration: 1,
			delay: 2,
			transition: Effect.Transitions.spring/*,
			afterFinish: function() {
				new Effect.Shake(img, { distance:5, duration:0.8 });
			}*/
		});
	} catch(e) {
		// banner doesn't exist, do nothing
	}
	
}

document.observe('dom:loaded', function() {		
	function main() {
		decorateNav();
		//decorateCollateralTabs();
		decorateSlideshow();
		decorateProductOverlay();
		skybanner_init();
	}
	
	// work around dom:loaded bug on IE8
	if (Prototype.Browser.IE && Prototype.Version < '1.6.1')
		window.setTimeout(main, 100);
	else
		main();
});

Event.observe(window, 'load', function() {
	skybanner();
});

// }}}

})();
