// Most code copyright designjunction.net
// but do what you like with it. 
var IE6 = false;
function fold(row,ele) {
	if($(ele).down().classNames()=='closed'){
		$(ele).down().removeClassName('closed');
	}else{
		$(ele).down().className='closed'
	}
	var r = $('fold_'+row)
	r.toggle();
	new Ajax.Request('/shopper/setprefs', {asynchronous:true, method:'post', postBody:'row='+row+'&visible='+r.visible()});
}


function shop_message(m) {
	var w = show_message(m, message_delay(m));
	Event.observe(window, 'load', function() {fade_shop_message(w, message_delay(m));});
}

function shop_notification(m) {
	var w = show_message(m);
	fade_shop_message(w, message_delay(m));
}

function message_delay(m) {
	var base = 1.5;
	var words = m.split(/ /);
	words = Math.max(0, words.length - 4);
	return base + ((words / 6.0));
}

function fade_shop_message(w, d) {
	if (IE6) {
		// ie6 has the iframe hack to remove too and that doesnt fade out
		window.setTimeout(function() { w.remove(); }, d + 0.5)
	} else {
		new Effect.Opacity(w,
			{ duration: 0.5, 
		  transition: Effect.Transitions.linear, 
		  from: 1.0, to: 0.0, delay: d, afterFinish:function(){try { w.remove();} catch (e) {}} });
	 }
}

function show_message(m) {
	var home = $('shop_messages');
	var w = $(document.createElement('div'));
	w.id = "message_popup";
	w.className = "wrapper";
	w.hide();
	var a = $(document.createElement('div'));
	a.className = "top"
	var b = $(document.createElement('div'));
	b.className = "middle"
	b.innerHTML = '<h3>' + m + '</h3>';
	var c = $(document.createElement('div'));
	c.className = "bottom";
	w.appendChild(a)
	w.appendChild(b)
	w.appendChild(c)
	home.appendChild(w);
	var ie6_iframe = false;
	w._old_remove = w.remove;
	w.remove = function(event) {
		try { Event.stop(event); } catch (e) {;}
		this._old_remove();
		if (this.ie6fix) this.ie6fix.remove();
	}
	w.onclick = function(event) {
		this.remove(event);
	}
	
	w.show();
	
	if(IE6){
		ie6_iframe = document.createElement('iframe');
		ie6_iframe = $(ie6_iframe);
		ie6_iframe.setAttribute("src", "");
		ie6_iframe.setAttribute("frameborder", "0");
		ie6_iframe.setAttribute("id", "ie6_iframe");
		ie6_iframe.style.position="absolute";
		ie6_iframe.style.left =w.offsetLeft + 10 +'px';
		ie6_iframe.style.top =w.offsetTop + 10 + 'px';
		ie6_iframe.style.width =w.offsetWidth - 20 + 'px';
		ie6_iframe.style.height =w.offsetHeight - 60 + 'px';
		ie6_iframe.style.border = "none";
		home.appendChild(ie6_iframe);
		w.ie6fix = ie6_iframe;
	}
	return w;
}

// individual product
function colour_flip(id) {
	// var id = select.value;
	selected_colour = id;
	set_default_product_image(id);
	
	$('stock_status').innerHTML = $('stock_status_'+id).innerHTML;
}
// product images

function show_image(id) {
	show_enlarge_button(id);
	if (id == default_product_image_id) {
		show_default_product_image();
	} else {
		set_product_image(id);
	}
	select_id(id);
}


function set_default_product_image(id) {
	current_product_image_id = id;
	show_default_product_image();
}
function show_default_product_image() {
	set_product_image(current_product_image_id);
	show_enlarge_button(current_product_image_id);
	select_id(default_product_image_id);
}

function set_product_image(id) {
	var c = $('image_canvas');
	c.innerHTML = $('product_image_'+id).innerHTML;
}
function reset_image_selector() { // sets the image selector back to '1'
	show_enlarge_button(default_product_image_id);
	select_id(default_product_image_id);
}

function show_enlarge_button(id) {
	var i = all_images[id];
	var e = $('enlarge');
	if (i.big) {
		e.show();
		e.image_id = i.id;
		e.onclick = function() {
			enlarge(this.image_id);
		}
	} else {
		e.hide();
	}
}
function generate_select(root) {
	return function(id) {
		if ($(root+active_ids[root])) $(root+active_ids[root]).removeClassName('active');
		if ($(root+id)) $(root+id).addClassName('active');
		active_ids[root] = id;
	}
}

var select_id = generate_select('show_');
var enlarged_select_id = generate_select('enlarged_');

function enlarge(id) {
	var body = document.getElementsByTagName("body").item(0);
	var o = $('overlay');
	if (!o) {
		o = document.createElement("div");
		o.setAttribute('id','overlay');
		o.style.display = 'none';
	}
	var arrayPageSize = getPageSize();
	Element.setWidth(o, arrayPageSize[0]);
	Element.setHeight(o, arrayPageSize[1]);
	body.appendChild(o);
	var l = $('lightbox')
	o.appendChild(l);
	hideFlash1();
	l.show();
	if (enlarged_image_count <= 1) $('enlarged_gallery_nav').hide();
// 	var i = document.createElement("iframe");
// 	var body = document.getElementsByTagName("body").item(0);
// 	i.setAttribute('id','blocking-frame');
// 	i.style.display = 'none';
// 	i.style.position = 'absolute';
// 	i.style.border = 'solid 1px red';
// 	i.style.zIndex = 9000;
// 	i.style.top = '0';
// 	i.style.left = '0';
// 	i.src = 'javascript:false';
// 	
// 	var arrayPageSize = getPageSize();
// 	Element.setWidth(i, arrayPageSize[0]);
// 	Element.setHeight(i, arrayPageSize[1]);
	
	// i.style.display = 'none';
	// body.appendChild(i);
	new Effect.Appear(o, { duration: 0.2, from: 0.0, to: 1, afterFinish: function() {
		hideSelectBoxes();
		hideFlash2();
			// i.style.display = 'block';

		show_enlarged(id);
	} });
}

function close_enlarge() {
	var l = $('lightbox');
	l.hide();
	new Effect.Fade('overlay', { duration: 0.2, afterFinish: function() {
		showFlash2();
		$('overlay').hide();
		var canvas = $('fullscreen_canvas');
		canvas.innerHTML = '';
	}});
	showSelectBoxes();
	showFlash1();	
}

function show_enlarged(id) {
	var canvas = $('fullscreen_canvas');
	if (id == default_product_image_id) {
		id = current_product_image_id;
	}
	var image = all_images[id];
	var img = document.createElement('img');
	img.src = image.big.src;
	img.width = image.big.width;
	img.height = image.big.height;
	img.style.paddingTop = (695 - image.big.height)/2 + 'px';
	/*img.style.paddingLeft = (695 - image.big.width)/2 + 'px';*/
	img.onclick = function() { close_enlarge(); };
	canvas.innerHTML = '';
	canvas.appendChild(img);
	if (id == current_product_image_id) {
		enlarged_select_id(default_product_image_id);
	} else {
		enlarged_select_id(id);
	}
}
// product icoh

function blow_bubbles(insert_id, swf, width, height, params) {
	var so = new SWFObject(swf, "mymovie", width, height, "7", "#ffffff");
	so.addParam("wmode", "transparent");
	so.addVariable("browser", '1');
	for (k in params) {
		so.addVariable(k, params[k]);
	}
	so.write(insert_id);

}

// some code below taken from:
// -----------------------------------------------------------------------------------
//
//	Lightbox v2.03.3
//	by Lokesh Dhakar - http://www.huddletogether.com
//	5/21/06
//
//	For more information on this script, visit:
//	http://huddletogether.com/projects/lightbox2/
//
//	Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
//	
//	Credit also due to those who have helped, inspired, and made their code available to the public.
//	Including: Scott Upton(uptonic.com), Peter-Paul Koch(quirksmode.com), Thomas Fuchs(mir.aculo.us), and others.
//
//
// -----------------------------------------------------------------------------------

Object.extend(Element, {
	getWidth: function(element) {
	   	element = $(element);
	   	return element.offsetWidth; 
	},
	setWidth: function(element,w) {
	   	element = $(element);
    	element.style.width = w +"px";
	},
	setHeight: function(element,h) {
   		element = $(element);
    	element.style.height = h +"px";
	},
	setTop: function(element,t) {
	   	element = $(element);
    	element.style.top = t +"px";
	},
	setLeft: function(element,l) {
	   	element = $(element);
    	element.style.left = l +"px";
	},
	setSrc: function(element,src) {
    	element = $(element);
    	element.src = src; 
	},
	setHref: function(element,href) {
    	element = $(element);
    	element.href = href; 
	},
	setInnerHTML: function(element,content) {
		element = $(element);
		element.innerHTML = content;
	}
});
function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	
//	console.log(self.innerWidth);
//	console.log(document.documentElement.clientWidth);

	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

//	console.log("xScroll " + xScroll)
//	console.log("windowWidth " + windowWidth)

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
//	console.log("pageWidth " + pageWidth)

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

// ---------------------------------------------------

function showSelectBoxes(){
	var selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "visible";
	}
}

// ---------------------------------------------------

function hideSelectBoxes(){
	var selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "hidden";
	}
}

// ---------------------------------------------------

function showFlash1(){
	var ff = document.getElementsByTagName("object");
	for (i = 0; i < ff.length; i++) {
		ff[i].style.display = "";
	}

	ff = document.getElementsByTagName("embed");
	for (i = 0; i < ff.length; i++) {
		ff[i].style.display = "";
	}
	$('breadcrumb').style.visibility = "visible";
}
function showFlash2(){
	var ff = document.getElementsByTagName("object");
	for (i = 0; i < ff.length; i++) {
		ff[i].style.visibility = "visible";
	}

	ff = document.getElementsByTagName("embed");
	for (i = 0; i < ff.length; i++) {
		ff[i].style.visibility = "visible";
	}
}

// ---------------------------------------------------

function hideFlash1(){
	var ff = document.getElementsByTagName("object");
	for (i = 0; i < ff.length; i++) {
		ff[i].style.visibility = "hidden";
		if (isWebKit()) ff[i].style.display = "none";
		
	}

	ff = document.getElementsByTagName("embed");
	for (i = 0; i < ff.length; i++) {
		ff[i].style.visibility = "hidden";
		if (isWebKit()) ff[i].style.display = "none";
	}
	// $('breadcrumb').onmouseover = function(event) { Event.stop(event); }
}
function hideFlash2(){
	var ff = document.getElementsByTagName("object");
	for (i = 0; i < ff.length; i++) {
		ff[i].style.display = "none";
	}

	ff = document.getElementsByTagName("embed");
	for (i = 0; i < ff.length; i++) {
		ff[i].style.display = "none";
	}
}


// ---------------------------------------------------

Object.extend(Object.extend(Effect.Opacity.prototype, Effect.Opacity.prototype), {
  finish: function(position) {
	if(Math.round(this.element.getOpacity()*10)==10){
		this.element.setStyle({
		  '-moz-opacity': 1
		});	
	}
  }
});


function isWebKit() {
	return RegExp(" AppleWebKit/").test(navigator.userAgent);
}

function attachButtonHover(){
	
	if(document.all){
		if ($('page')) {
			var buttons = $('page').getElementsBySelector('button');
			
			buttons.each(function (button){
				var tag_name = button.tagName.toUpperCase();
				if(tag_name!='SPAN'){
					var o = button;
					button=button.down();
					if (!button) button = o;
				}
				Event.observe(button, 'mouseover', function(event){
					button.setStyle({
					  backgroundPosition: '0 0'
					});
				 });
				Event.observe(button, 'mouseout', function(event){
					button.setStyle({
					  backgroundPosition: '0 -48px'
					});
				 });
			});
		}
	}
}


function attachDrag(){
	if ($('sorted')) {
		Sortable.create('sorted', {
			tag:'div',
			only:'sortme',
			handle:'move',
			onUpdate: function() {
				new Ajax.Request('/shopper/setprefs', {asynchronous:true, method:'post', postBody:Sortable.serialize('sorted')});
			}
		});
		if(document.all){
			//mw fix IE6
			if($('row_other')){
				new Effect.Opacity($('row_other'), {duration:0, from:1.0, to:1.0});
			}
			if($('row_related')){
				new Effect.Opacity($('row_related'), {duration:0, from:1.0, to:1.0});
			}
			if($('row_recent')){
				new Effect.Opacity($('row_recent'), {duration:0, from:1.0, to:1.0});
			}
		}
	}
	
}

function attachArrowHover(){
	
	if(document.all){
		if ($('nav')) {
			var links = $('nav').getElementsBySelector('a');
			links.each(function (a) {
			a.observe('mouseover', function(event){
				var li = a.up();
				var tag_name = li.tagName.toUpperCase();
				if(tag_name!='LI'){
					li=li.up();
				}
				
				tag_name = li.tagName.toUpperCase();
				if(tag_name=='LI'){
					if(li.hasClassName('active')){
						li.addClassName('stay_active');
					}else{
						li.addClassName('active');
					}
				}
				
			});
			a.observe('mouseout', function(event){
		  	var li = a.up();
				var tag_name = li.tagName.toUpperCase();
				if(tag_name!='LI'){
					li=li.up();
				}
				tag_name = li.tagName.toUpperCase();
				if(tag_name=='LI'&&li.hasClassName('active')){
					if(li.hasClassName('stay_active')){
						li.removeClassName('stay_active');
					}else{
						li.removeClassName('active');
					}
				}
			 });
		});
		
		}
	}
}

function set_up_limited_product_description() {
    var debug_active = false;
    function debug(s) { if (debug_active && console) console.log(s) }
    var read_more_wrapper = $('read-more-wrapper');
    var read_more_button = $('read-more-button');
    var word_count = 0, max_words = 70;
    var parag, parag_text, parag_words, parag_word_count;
    var description = $('description-content');
    var full_content = description.innerHTML, limited_content = "";

    function words(elem) { return elem.textContent.strip().split(/\s+/); }
    function readLess() {
        description.innerHTML = limited_content;
        read_more_button.onclick = readMore;
        read_more_button.innerHTML = "Read more";
        debug("readLess()");
        return false;
    }
    function readMore() {
        description.innerHTML = full_content;
        read_more_button.onclick = readLess;
        read_more_button.innerHTML = "Read less";
        debug("readMore()");
        return false;
    }
    function get_limited_content(description) {
        var paragraphs = description.childElements();

        for (var i = 0; i < paragraphs.length; ++i) {
            parag = paragraphs[i];
            parag_words = words(parag);
            parag_word_count = parag_words.length;
            word_count += parag_word_count;
            limited_content += '<p>' + parag.innerHTML + '</p>';
            debug(word_count);

            if (word_count > max_words) {
                debug("Stop at " + word_count + " words");
                break;
            }
        }
        return limited_content;
    }
    debug("Total number of words: " + words(description).length);
    if (words(description).length > max_words) {
        description.innerHTML = get_limited_content(description);
        read_more_wrapper.show();
        read_more_button.onclick = readMore;
    }

}

function dbg(s) { 
    if (window.console) console.log(s); 
}

function attachCategoryPagination() {
    if ($('pagination')) {
        $('pagination').show();
    }
    var container = $('fold_other');
    if(!container) return;
    var wrapper = $('fixed-width-wrapper');
    var prevLink = $$('.prev a')[0];
    var nextLink = $$('.next a')[0];
    var showAllLink = $$('.show_all a')[0];
    var paginationItems = $$('#pagination-inner .p');
    var itemCount = $$('#fold_other .item').length;
    var currentScroll = 0;
    var widgetWidth = 724;
    var totalWidth = Math.ceil(itemCount / 4.0) * widgetWidth;
    if ($$('.current-page')) {
        var currentPageCount = $$('.current-page')[0];
        if (currentPageCount) {
            currentPageCount.innerHTML = "1";
        }
    }
    dbg("totalWidth: " + totalWidth);
    function setLinkColors() {
        dbg('setLinkColors');
        var currentPageIndex = currentScroll / widgetWidth;
        paginationItems.each(function(item) {
            item.style.color = '#34CE41';
        });
        if (paginationItems[currentPageIndex]) {
            paginationItems[currentPageIndex].style.color = '#73737A';
        }
        if (currentPageCount) {
            currentPageCount.innerHTML = currentPageIndex + 1;
        }
        function markEnabled(elem) {
            elem.setStyle({ backgroundPosition: '0 0' });
        }
        function markDisabled(elem) {
            elem.setStyle({ backgroundPosition: '0 -87px' });
        }
        var prevSpan = $$('.prev span')[0];
        if (currentScroll === 0) {
            markDisabled(prevSpan);
        } else {
            markEnabled(prevSpan);
        }
        var nextSpan = $$('.next span')[0];
        if (currentScroll === (totalWidth - widgetWidth)) {
            markDisabled(nextSpan);
        } else {
            markEnabled(nextSpan);
        }
    }
    function doNotShowAll(evt) {
        dbg('doNotShowAll');
        Event.stop(evt);
        container.style.width = (totalWidth + 27) + 'px';
        dbg("width:"+container.style.width);
        showAllLink.stopObserving('click', doNotShowAll);
        showAllLink.observe('click', showAll);
        $('pagination-inner').show()
    }
    function showAll(evt) {
        dbg('showAll');
        Event.stop(evt);
        currentScroll = 0;
        wrapper.scrollLeft = 0;
        container.style.width = null;
        showAllLink.stopObserving('click', showAll);
        showAllLink.observe('click', doNotShowAll);
        $('pagination-inner').hide()
        setLinkColors();
    }
    showAllLink.observe('click', showAll);

    function showNext(evt) {
        Event.stop(evt);
        dbg("currentScroll:" + currentScroll + " totalWidth: " + totalWidth);
        if ((currentScroll + widgetWidth) < totalWidth) {
            currentScroll += widgetWidth;
            wrapper.scrollLeft = currentScroll;
        }
        dbg("newScroll:" + currentScroll);
        setLinkColors();
    }
    nextLink.observe('click', showNext);

    function showPrev(evt) {
        Event.stop(evt);
        if (currentScroll > 0) {
            currentScroll -= widgetWidth;
            wrapper.scrollLeft = currentScroll;
        }
        setLinkColors();
    }
    prevLink.observe('click', showPrev);

    paginationItems.each(function(elem, i) {
        elem.observe('click', function(evt) {
            Event.stop(evt);
            currentScroll = i * widgetWidth;
            wrapper.scrollLeft = currentScroll;
            setLinkColors();
        });
    });

}

Event.observe(window, 'load', attachButtonHover);
Event.observe(window, 'load', attachDrag);
Event.observe(window, 'load', attachArrowHover);
Event.observe(window, 'load', attachCategoryPagination);

function track_transactions() {
	// place holder for analytics tracking of orders
	// overwritten in receipt page
}
