/* name space for all of our module code */
if (window['shopping'] === undefined) window['shopping'] = {};

/* the head sets the base url */
shopping.baseUrl = '';

/* prevent errors if the console object is not present */
if (!window.console) {
	window.console = {};
	window.console.log = function() {};
    window.console.warn = function() {};
	window.console.error = function() {};
	window.console.info = function() {};
};


/* simple debug method */
function debug(sDebugMessage) {
    if (window.console) {
    	window.console.log(sDebugMessage);
    }
};

/* run some initialisation methods when the dom has loaded up */
document.observe("dom:loaded", function() {
    handleSortButton();
    initialisePriceRangeWidgetsEvents();
    shopping.addHitboxTracking();
    shopping.decorateSortButton();
    shopping.initEditorsPickModule();
    shopping.initVisitStoreButtons();
    shopping.decorateTableRows();
});


/* submit search form when options are changed start */
function handleSortButton() {
    var sortList = $('sortList');
    if (sortList != null) {
        sortList.onchange = function() {
            $('sortForm').submit();
        }
    }
};
/* submit search form when options are changed end */

/* start of price range module */
function initialisePriceRangeWidgetsEvents() {
    $$(".priceFinderLink").each(function(item) {
        item.observe('click', handleFinderClick);
     });
     
     $$(".priceRangeLink").each(function(item) {
        item.observe('click', handleRangeClick);
     });
};

function handleFinderClick(event) {
    var id = processEvent(event);
    var params = {cat: id};
    ajaxCall(params);
};

function handleRangeClick(event) {
    var id = processEvent(event);
    var li = $$("#priceFinderHeader li.selected");
    var anchor = li[0].firstDescendant();
    var catId = getSuffixId(anchor.id);
    var params = {cat: catId, range: id};
    ajaxCall(params);
};

function processEvent(event) {
    var element = event.element();
    var id = element.id
    return getSuffixId(id);    
};

function getSuffixId(id) {
    return id.substring(id.indexOf('-')+1);
};

function ajaxCall(params) {
    new Ajax.Updater('priceRange-widget', shopping.baseUrl + 'priceRange.widget', 
    {
        method:'get',
        parameters: params, 
        onSuccess: function(transport){
            var response = transport.responseText || "no response text";
        },
        onFailure: function(){ debug('failed')},
        onComplete: function(){ debug('completed...');
            shopping.addHitboxTracking("#priceRange-widget");
            initialisePriceRangeWidgetsEvents();
        }
    });
};
/* end of price range module */


/* start decorate the sort button for product listings pages */
shopping.decorateSortButton = function() {
	var oSortSelect = $('sortList');
	if (oSortSelect) {
		Event.observe(oSortSelect, 'onchange', function(eventData) {
			var oForm = $('sortForm');
			if (oForm) {
				oForm.submit();
			}
		});
	}
};
/* end decorate the sort button for product listings pages */


/* start of editors pick module code - requires the prototype library */
shopping.initEditorsPickModule = function() {
	if ($('editorsPick-widget')) {
		oEditorsPick = new shopping.editorspick();
		oEditorsPick.init();
		oEditorsPick.startAnimation();
	}
};

shopping.editorspick = function() {
	this.sModuleSelector = '#masters';
	this.sThumbWrapperSelector = '#thumbs';
	this.sThumbSelector = '#thumbs .thumb';
	this.sMasterImageSelector = '#masters .master';
	this.nAnimationSpeed = 4000; // milliseconds
};

shopping.editorspick.prototype.init = function() {
	this.pMasterImages = $$(this.sMasterImageSelector);
	if (this.pMasterImages) {
		this.sThumbNodeType = 'li';
		this.ThumbIdPrefix = 'thumb';
		this.pThumbs = $$(this.sThumbSelector);
		this.oModule = $$(this.sModuleSelector)[0];
		this.oThumbWrapper = $$(this.sThumbWrapperSelector)[0];
		Event.observe(this.oModule, 'mouseover', this.mouseOverModule.bind(this));
		Event.observe(this.oModule, 'mouseout', this.mouseOutModule.bind(this));
		Event.observe(this.oThumbWrapper, 'mouseover', this.mouseOverThumbWrapper.bind(this));
		Event.observe(this.oThumbWrapper, 'mouseout', this.mouseOutThumbWrapper.bind(this));
		this.pThumbs.each(function(node) {
			Event.observe(node, 'mouseover', this.mouseOverThumb.bind(this));
		}, this);
	} else {
		debug('There was a problem initialising the editors pick widget - no data.');
	}
};

shopping.editorspick.prototype.mouseOutModule = function(eventData) {
	Event.stop(eventData);
	this.startAnimation();
};

shopping.editorspick.prototype.mouseOverModule = function(eventData) {
	Event.stop(eventData);
	this.stopAnimation();
};

shopping.editorspick.prototype.mouseOutThumbWrapper = function(eventData) {
	var oChild = Event.element(eventData);
	var bOverThumbWrapper = Element.descendantOf(oChild, this.oThumbWrapper);
	Event.stop(eventData);
	if (!bOverThumbWrapper) {
		this.startAnimation();
	} else {
		this.stopAnimation();
	}
};

shopping.editorspick.prototype.mouseOverThumbWrapper = function(eventData) {
	Event.stop(eventData);
	this.stopAnimation();
};

shopping.editorspick.prototype.startAnimation = function() {
	if (!this.bAnimationRunning) {
		this.pAnimationTimerHandle = setTimeout(this.selectNextImageAndDisplay.bind(this), this.nAnimationSpeed);
	}
	this.bAnimationRunning = true;
};

shopping.editorspick.prototype.stopAnimation = function() {
	if (this.bAnimationRunning) {
		clearTimeout(this.pAnimationTimerHandle);
		this.pAnimationTimerHandle = null;
	}
	this.bAnimationRunning = false;
};

shopping.editorspick.prototype.selectNextImageAndDisplay = function() {
	if (this.bAnimationRunning) {
		var nNodeIndex = 0;
		var nNodeCounter = 0;
		this.pThumbs.each(function(node) {
			if (this.oRolledOverThumb == node) {
				nNodeIndex = nNodeCounter;
			}
			nNodeCounter++;
		}, this);
		var nNewThumbToShowIndex = (nNodeIndex + 1) % this.pThumbs.length;
		this.oRolledOverThumb = this.pThumbs[nNewThumbToShowIndex];;
		this.showMasterImage();
		this.updateThumbBorder();
		this.pAnimationTimerHandle = setTimeout(this.selectNextImageAndDisplay.bind(this), this.nAnimationSpeed);
	}
};

shopping.editorspick.prototype.mouseOverThumb = function(eventData) {
	var oThumb = Event.element(eventData);
	Event.stop(eventData);
	while(oThumb.nodeName.toLowerCase() != this.sThumbNodeType) {
		oThumb = oThumb.parentNode;
	}
	if (this.oRolledOverThumb != oThumb) {
		this.oRolledOverThumb = oThumb;
		this.showMasterImage();
		this.updateThumbBorder();
	}
};

shopping.editorspick.prototype.updateThumbBorder = function() {
	this.pThumbs.each(function(node) {
		if (this.oRolledOverThumb == node) {
			Element.addClassName(node, 'selected');
		} else {
			Element.removeClassName(node, 'selected');
		}
	}, this);

};

shopping.editorspick.prototype.showMasterImage = function() {
	var nThumbIndex = this.oRolledOverThumb.id.substring(this.oRolledOverThumb.id.indexOf(this.ThumbIdPrefix) + this.ThumbIdPrefix.length);
	var nNodeCounter = 0;
	this.pMasterImages.each(function(node) {
		if (nThumbIndex == nNodeCounter) {
			node.show();
		} else {
			node.hide();
		}
		nNodeCounter++;
	}, this);
};
/* end of editors pick module code */


/* start of recently viewed module code */
shopping.recentlyViewedHover = function() {
	var pModuleNodes = $$('#recentlyViewed-widget li');
	if (pModuleNodes) {
		for (var i=0; i<pModuleNodes.length; i++) {
			pModuleNodes[i].onmouseover=function() {
				this.className+=" hovered";
			}
			pModuleNodes[i].onmouseout=function() {
				this.className=this.className.replace(new RegExp(" hovered\\b"), "");
			}
		}
	}
};
if (window.attachEvent) window.attachEvent("onload", shopping.recentlyViewedHover);
/* end of recently viewed module code */


/* add hitbox tracking to tagged links and buttons */
shopping.addHitboxTracking = function(rootId) {
    // rootId indicates what element to start from, if no rootId then tag whole DOM
    rootId = rootId || "";
    // iterate over each element with a class starting 'SpSh'
    $$(rootId + ' *[class*=SpSh]').each(function(el) {
        // attach click handler to element
        el.observe('click', shopping.processHitboxClick);
    });
}

shopping.processHitboxClick = function(event) {
    // extract appropriate element class - this is used as hitbox lid
    var tag = shopping.getHitboxTag(this);
    // call hitbox
    if( _hbLink ) _hbLink(tag, "", "");
}

shopping.getHitboxTag = function(element) {
    // get first class name starting with 'SpSh'
    return element.classNames().find(function(name) { if (name.startsWith("SpSh")) return name; });
}

/* debug hitbox */
dbgHbx = function() {
    // overwrite hbx tracking call
    _hbLink = function(lid, lpos, z) { console.info("hitbox in debug mode, lid:" + lid + ", lpos:" + lpos + ", " + z); }
    // mouse over them to see hbx data
    var taggedElement = $$('a', 'input[type="image"]', 'input[type="submit"]');
    taggedElement.each(function (element) {
        if (element.classNames().find(function(name) { if (name.startsWith("SpSh")) return name; }) != null) {
            element.setStyle({border: '2px solid #0f0'});
        } else {
            element.setStyle({border: '2px solid #f0f'});
        }
        element.onmouseover = function() {
            var hbxClass = element.classNames().find(function(name) { if (name.startsWith("SpSh")) return name; });
            if (hbxClass != null) console.log("mlc:" + hbx.mlc + ", pn:" + hbx.pn + ", lid:" + hbxClass + "");
            else console.log("untracked");
        };
    })
}

/* end of recently viewed module code */


/* start of visit store button click code */
shopping.initVisitStoreButtons = function() {
	var pImageSelectors = ['div.visitStore a img', '#deepLink img', 'div.visit_store a img', 'div a img.aw_buy_now']
	pImageSelectors.each(function(sSelector) {
		var pNodes = $$(sSelector);
		pNodes.each(function(oNode) {
			while(oNode.nodeName.toLowerCase() != 'a') {
				oNode = oNode.parentNode;
			}
			Event.observe(oNode, 'mousedown', function(){
				var pImages = oNode.select('img');
				if (pImages) {
					pImages[0].src = pImages[0].src.replace('vs-unselected.gif', 'vs-selected.gif');
				}
			});
			Event.observe(oNode, 'mouseup', function(){
				var pImages = oNode.select('img');
				if (pImages) {
					pImages[0].src = pImages[0].src.replace('vs-selected.gif', 'vs-unselected.gif');
				}
			});
		});
	});
};
/* end of visit store button click code */


/* start of table row decoration code */
shopping.decorateTableRows = function() {
	var pRowNodes = $$('table.decorate-rows tbody tr');
	var nCount = 0;
	pRowNodes.each(function(oNode) {
		if (nCount % 2 == 1) {
			oNode.addClassName('alternative');
		}
		nCount++;
	});
};
/* end of table row decoration code */

