/*
 * Catwalk JavaScript for Fergs Kayaks
 * (c) 2006 tasmanstudios ltd
 * Utilises the prototype and scriptaculous libraries
 */
 
// Is the page loaded yet? Saves us having to attach listeners later
var pageLoaded = false;
Event.observe(window, 'load', function() {
		pageLoaded = true;
});

function FergsSwatchPicker(pickerID, type, leftOffset, topOffset, productData) {
	/** 
	 * Creates a picker
	 * @param string the direction it will face
	 */
	this.createRollover = function(type) {
		var pointDiv = Builder.node('div');
		var stalkImg = Builder.node('img', {alt: 'stalk'});
		if (type == 'right') {
			pointDiv.className = 'swatchRolloverPointRight';
			stalkImg.src = 'fileadmin/template/catwalk/images/swatchRolloverStalk.gif';
		} else {
			pointDiv.className = 'swatchRolloverPointLeft';
			stalkImg.src = 'fileadmin/template/catwalk/images/swatchRolloverStalk2.gif';
		}
		pointDiv.appendChild(stalkImg);
		
		var containerDiv = Builder.node('div', {className: 'swatchRolloverContainer'}, [
			Builder.node('div', {className: 'swatchHeaderTitle'}, 'STOCK AVAILABILITY'),
			Builder.node('div', {className: 'swatchTitle'}, [
				Builder.node('img', {src: 'fileadmin/template/catwalk/images/swatch.jpg', width: 13, height: 13, alt: 'Swatch Preview'}),
				'COL - SWATCH'
			]),
			Builder.node('div', {className: 'swatchContent'}),
			pointDiv
		]);
		
		// IE has issues appending to the document before it's finished loading
		if (pageLoaded) {
			document.body.appendChild(containerDiv);
		} else {
			Event.observe(window, 'load', function() {
					document.body.appendChild(containerDiv);
			});
		}

		return containerDiv;
	}
	
	this.picker = $(pickerID);
	if (!this.picker) alert('picker not found');
	this.rolloverDiv = this.createRollover(type);
	this.leftOffset = leftOffset;
	this.topOffset = topOffset;
	this.productData = productData;
	
	var po = this; // store a backreference for the events
	
	/**
	 * Handles rolling over a swatch cell
	 * Will cause the rollover div to be displayable
	 */
	this.rolloverHandler = function(evt) {
		var targetCell = Event.element(evt).containerCell;
		if (!targetCell) return;
		
		// find the product in the array that was fed by JSON
		var temp = targetCell.id.split('-');
		
		var product = po.productData[temp[1]];
		if (!product) alert('could not locate product uid ' + temp[1]);
		
		// Flip the swatch image out and change the title
		var titleDiv = po.rolloverDiv.childNodes[1];
		var swatchImg = titleDiv.firstChild;
		swatchImg.src = Event.element(evt).src; // the image src of the image under the mouse
		titleDiv.removeChild(titleDiv.childNodes[1]);
		titleDiv.appendChild(document.createTextNode(product.title));
		
		var stockString = '<p>Auckland: ' + product.stockAkl + '</p><p>Wellington: ' + product.stockWlg + '</p>';
		var textDiv = po.rolloverDiv.childNodes[2];
		textDiv.innerHTML = stockString;
		
		po.rolloverDiv.style.display = 'block';
		currentDisplayedProduct = temp[1];
	}
	
	/**
	 * Handles rolling off a swatch cell
	 * Hides the rollover div
	 */
	this.rolloutHandler = function(evt) {
		po.rolloverDiv.style.display = 'none';
	}
	
	/**
	 * Handles any movement of the mouse within this picker
	 * Moves the rollover (hidden or not) to the specified position
	 * relative to the mouse
	 */
	this.rollHandler = function(evt) {
		var temp = Event.element(evt);
		po.rolloverDiv.style.left = (Event.pointerX(evt) - leftOffset) + 'px';
		po.rolloverDiv.style.top = (Event.pointerY(evt) - topOffset) + 'px';
	}
	
	/**
	 * Delays for 500ms to ensure they're still hovered over the same id, then
	 * goes to fetch the stock level
	 * Each picker can only be fetching one stock level at a time
	 */
	var fetchingStock = false;
	var currentDisplayedProduct = -1;
	
	
	// initialise this picker
	var cells = this.picker.getElementsByTagName('td');
	for (j = 0; j < cells.length; j++) {
		// if the cell is empty, ignore it
		if (cells[j].childNodes.length == 0) continue;
		
		var swatchImage = cells[j].firstChild.firstChild;
		swatchImage.containerCell = cells[j];
		
		swatchImage.pickerObj = this;
		Event.observe(swatchImage, 'mouseover', this.rolloverHandler);
		Event.observe(swatchImage, 'mouseout', this.rolloutHandler);
		Event.observe(swatchImage, 'click', this.rolloutHandler); // hides the popup onclick
	}
	
	// Attach a mouse movement listener that will make the rollover follow the mouse
	this.picker.pickerObj = this;
	Event.observe(this.picker, 'mousemove', this.rollHandler);
}

	
function popUpProperties(inobj) {
	op = window.open();
	op.document.open('text/plain');
	for (objprop in inobj) {
	op.document.write(objprop + ' => ' + inobj[objprop] + '\n');
	}
	op.document.close();
}

function picPopUp(x, y, paramstring) {
	window.open('showpic.php?file='+filename+'&width='+x+'&height='+y, 'Image Display', 'toolbar=no,dependent=yes,directories=no,width='+x+',height='+y+',location=no,menubar=no,resizable=no,scrollbars=no,status=no,toolbar=no');
}


/* FUNCTIONS FOR THE CATEGORY SELECTION IN THE SEARCH FORM */
var selectedCategory = 0;
function catLevel1Change() {
	// build the second cat menu
	var selectedLvl1 = $F('catLvl1');
	
	$('catLvl2').options.length = 0;
	var anyOption = new Option('Any', selectedLvl1);
	$('catLvl2').options[0] = anyOption;
	$('catLvl2').selectedIndex = 0;
	catLevel2Change();
	
	if (selectedLvl1 == 0) return; // "any"
	if(!categories[selectedLvl1].children) return; // no product category for this type
	var l2Choices = categories[selectedLvl1].children;
	var idx = 1;
	for (var key in l2Choices) {
		var newOption = new Option(l2Choices[key].title, l2Choices[key].uid);
		$('catLvl2').options[idx++] = newOption;
	}
}

function catLevel2Change() {
	var selectedLvl1 = $F('catLvl1');
	var selectedLvl2 = $F('catLvl2');
	$('catLvl3').options.length = 0;
	var anyOption = new Option('Any', selectedLvl2);
	$('catLvl3').options[0] = anyOption;
	$('catLvl3').selectedIndex = 0;
	catLevel3Change();
	
	try {
		if (!categories[selectedLvl1].children[selectedLvl2].children) return;
	} catch(e) {
		return;
	}
	var l3Choices = categories[selectedLvl1].children[selectedLvl2].children;
	var idx = 1;
	for (var key in l3Choices) {
		var newOption = new Option(l3Choices[key].title, l3Choices[key].uid);
		$('catLvl3').options[idx++] = newOption;
	}
}

function catLevel3Change() {
	var selectedLvl3 = $F('catLvl3');
	selectedCategory = selectedLvl3;
}

function searchInitialise() {
	// load up the 'all categories' search form
	processSelectionChange();
	
	// look for a quicksearch, if found, fill it in and submit straight away
	if (quicksearch) {
		$('keywordsBox').value = quicksearch;
		doSearch();
	}
}

function processSelectionChange() {;
	new Ajax.Request(requestURL + 'search/form/' + selectedCategory + '/', 
		{
			method: 'get',
			onComplete: searchFormArrival
		});
	
	$('searchFormBuild').innerHTML = '<p style="text-align: center">Findings fields for that category...</p>';
	
	// Construct the title breadcrumb for the search box
	var l1 = $F('catLvl1');
	var l2 = $F('catLvl2');
	var l3 = $F('catLvl3');
	
	var breadcrumb = '';
	if (selectedCategory == 0) {
		breadcrumb = 'Search all categories';
	} else {
		if (categories[l1]) {
			breadcrumb = 'Search in: ' + categories[l1].title;
		}
		try {
			if (categories[l1].children[l2]) {
				breadcrumb += ' > ' + categories[l1].children[l2].title;
			}
			if (categories[l1].children[l2].children[l3]) {
				breadcrumb += ' > ' + categories[l1].children[l2].children[l3].title;
			}
		} catch(e) {
			// stop here
		}		
	}
	
	// TODO
	$('searchFieldsBreadcrumb').innerHTML = breadcrumb;
}

function searchFormArrival(origReq) {
	$('searchFormBuild').innerHTML = origReq.responseText;
}

function doSearch() {
	var form = $('searchFieldsForm');
	var formData = Form.serialize(form);
	$('searchResults').innerHTML = '<div align="center">Searching...</div>';
	new Ajax.Request(requestURL + 'search/results/' + selectedCategory + '/', 
		{
			method: 'post',
			parameters: formData,
			onComplete: searchResultsArrival
		});
}

function searchResultsArrival(origReq) {
	$('searchResults').innerHTML = origReq.responseText;
	//alert(origReq.responseText);
}

/* Compare stuff below */
var curLeftGroup = null;
function dropLeft(draggable, droppable, overlappercent) {
	var loadUID = draggable.id.replace('prodgroup-', '');
	ajaxLoadProduct(loadUID, null, null, 'left');
}

var curRightGroup = null;
function dropRight(draggable, droppable, overlappercent) {
	var loadUID = draggable.id.replace('prodgroup-', '');
	ajaxLoadProduct(loadUID, null, null, 'right');
}

function ajaxLoadProduct(groupUID, productUID, instanceUID, frame) {
	if (!groupUID) alert("no group UID!");
	
	var params = {
		'tx_fergscatwalkfe_pi1[prodgroup]': groupUID,
		'tx_fergscatwalkfe_pi1[frame]': frame,
		'tx_fergscatwalkfe_pi1[oppositeUID]': (frame == 'left') ? curLeftGroup : curRightGroup
	};
	
	if (productUID) {
		params['tx_fergscatwalkfe_pi1[prod]'] = productUID;
	} else if (instanceUID) {
		params['tx_fergscatwalkfe_pi1[ins]'] = instanceUID;
	}
	
	if (frame == 'left') {
		var frameDiv = $('productComp1');
		curLeftGroup = groupUID;
	}
	else {
		var frameDiv = $('productComp2');
		curRightGroup = groupUID;
	}
	$(frameDiv).innerHTML = '<div align="center">Loading...</div>';
	
	new Ajax.Updater(frameDiv, requestURL+'compare/fetch/',
		{
			method: 'post',
			onComplete: function(origReq) {
				initCompareProductBlock(frame);
			},
			parameters: params
		}
	);
}

function initCompareProductBlock(frame) {
	if (frame == 'left') var frameDiv = $('productComp1');
	else var frameDiv = $('productComp2');

	// Set up pop-up swatch picker
	if (frame == 'left') {
		var trigger = document.getElementsByClassName('swatchTrigger').first();
		var picker = document.getElementsByClassName('productStockAreaComp').first();
	} else {
		var trigger = document.getElementsByClassName('swatchTrigger').last();
		var picker = document.getElementsByClassName('productStockAreaComp').last();
	}
	
	picker.style.display = 'none';
	picker.down = true;
	
	Event.observe(trigger, 'click', function() {
			if (picker.down) {
				picker.down = false;
				trigger.firstChild.src = '/fileadmin/template/catwalk/images/stockAvailComp_close.gif';
				Effect.Appear(picker, {duration: 0.2, to: 0.9});
			} else {
				picker.down = true;
				trigger.firstChild.src = '/fileadmin/template/catwalk/images/stockAvailComp.gif';
				Effect.Fade(picker, {duration: 0.2});
			}
	});
	
	// Add a listener to every link inside the div to prevent it actually linking
	// there's a "prodlink" attribute that reads either prod-$uid or ins-$uid for this purpose
	var links = frameDiv.getElementsByTagName('a');
	var prodGroupUID = null;
	if (frame == 'left') {
		prodGroupUID = curLeftGroup;
	} else {
		prodGroupUID = curRightGroup;
	}
	
	for (i = 0; i < links.length; i++) {
		if (links[i].className) {
			if (links[i].className.indexOf('prod') != -1) {
				// links to a product
				var prodUID = links[i].className.replace('prod-', '');
				Event.observe(links[i], 'click', function(evt) {
					ajaxLoadProduct(prodGroupUID, prodUID, null, frame);
					evt.preventDefault();
				}, true);
			} else if (links[i].className.indexOf('ins') != -1) {
				// links to an instance
				var instanceUID = links[i].className.replace('ins-', '');
				Event.observe(links[i], 'click', function(evt) {
					ajaxLoadProduct(prodGroupUID, null, instanceUID, frame);
					evt.preventDefault();
				}, true);
			}
		}
	}
}

function removeCompareProduct(uid, frame) {
	// build up the URL to request for this
	var params = {
		'tx_fergscatwalkfe_pi1[remove]': uid 
	};
	
	if (frame == 'left' && curRightGroup != null) {
		params['tx_fergscatwalkfe_pi1[loadright]'] = curRightGroup;
	} else if (frame == 'right' && curLeftGroup != null) {
		params['tx_fergscatwalkfe_pi1[loadleft]'] = curLeftGroup;
	}
	
	window.location.href = requestURL + 'compare/view/?' + Hash.toQueryString(params);
}


function initDraggables() {
	var draggables = document.getElementsByClassName('draggable');
	for (i = 0; i < draggables.length; i++) {
		draggables[i].draggable = new Draggable(draggables[i], {revert: true, ghosting: true, endeffect: null, fixedoffset: true, zindex: 1500});
	}
	
	Droppables.add('productComp1', { accept: 'draggable', hoverclass: 'dropTarget', onDrop: dropLeft});
	Droppables.add('productComp2', { accept: 'draggable', hoverclass: 'dropTarget', onDrop: dropRight});
}

function triggerCompareHint() {
	// shows the compare hint bubble for 7 seconds, then fades it out
	// use setTimeout as a kind of body.onClick
	setTimeout(function() {
		$('compareHint').style.display = 'block';
		setTimeout(function() {
			new Effect.Opacity('compareHint', {
					duration: 0.5,
					transition: Effect.Transitions.sinoidal,
					from: 1.0, to: 0.0
			});
		}, 7000);
	}, 0);
}
	
function triggerCartHint() {
	// shows the cart hint bubble for 7 seconds, then fades it out
	// use setTimeout as a kind of body.onClick
	setTimeout(function() {
		$('cartHint').style.display = 'block';
		setTimeout(function() {
			new Effect.Opacity('cartHint', {
					duration: 0.5,
					transition: Effect.Transitions.sinoidal,
					from: 1.0, to: 0.0
			});
		}, 7000);
	}, 0);
}

function disable(f) {
	//var button = document.getElementById('submit');
	var button = f.elements['submit'];
	//button.value = 'processing';
	button.disabled = 'true';
	return true;
}


