/*
varmatrix1[<value1>][<value2>] = <variation object>
varmatrix2[<value2>][<value1>] = 1

productimages[<imgid>].imgid
productimages[<imgid>].value1
productimages[<imgid>].value2
productimages[<imgid>].orderidx

currentimage = <imgid>
productname = <product name>
*/

function switchImage(imgid, changeDDs) {
	if (imgid == currentimage) {
		return;
	}
	currentimage = imgid;
	
	var zoom = document.getElementById('zoom');
	MagicZoom.update(zoom, '/images/1pix.gif', '/images/1pix.gif');
	MagicZoom.update(zoom, '/product_image.php?imgid='+imgid+'&minwidth=600&minheight=600', '/product_image.php?imgid='+imgid+'&width=472&height=435');
	
	if (changeDDs) {
		if (productimages[imgid].value1 != '' && document.fm.var1) {
			document.fm.var1.value = productimages[imgid].value1;
			adjustDropDowns(1);
		}
		if (productimages[imgid].value2 != '' && document.fm.var2) {
			document.fm.var2.value = productimages[imgid].value2;
			adjustDropDowns(2);
		}
		updatePriceEtc();
	}
}

function getWinSize() {
	var myWidth = 0, myHeight = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	return {width: myWidth, height: myHeight};
}

function enlargeImage() {
	winSize = getWinSize();
	var w = winSize.width-100;
	var h = winSize.height-100;
	if (currentimage.toString().substr(0, 1) == 'b') {
		tb_show(productname, '/zoom_bundle_image.php?bid='+currentimage.substr(1)+'&width='+w+'&height='+h+'&title='+encodeURIComponent(productname)+'&TB_iframe=true&width='+(w-24)+'&height='+(h-7));
	} else {
		tb_show(productname, '/zoom_image.php?imgid='+currentimage+'&width='+w+'&height='+h+'&title='+encodeURIComponent(productname)+'&TB_iframe=true&width='+(w-24)+'&height='+(h-7));
	}
}

function adjustDropDowns(whichdd, whichconstit, bNoRecurse) {
	if (whichconstit) {
		wcbits = whichconstit.split('_');
		var pid = wcbits[0];
		var idx = wcbits[1];
		var ext = '_'+whichconstit;
	} else {
		var ext = '';
	}
	
	var whichdd_el = document.fm['var'+whichdd+ext];
	var otherdd = (whichdd==1?2:1);
	var otherdd_el = document.fm['var'+otherdd+ext];
	if (!otherdd_el) {
		return;
	}
	if (whichconstit) {
		var varmatrix = (whichdd==1?varmatrix1[pid]:varmatrix2[pid]);
	} else {
		var varmatrix = (whichdd==1?varmatrix1:varmatrix2);
	}
	var i, c, onlyOption;
	
	if (whichdd_el.value == '') {
		// Reset styles of other dd
		for (i = 0; i < otherdd_el.options.length; i++) {
			otherdd_el.options[i].style.color = '#333333';
		}
	} else {
		// Grey out invalid combinations in other dd
		c = 0;
		for (i = 0; i < otherdd_el.options.length; i++) {
			if (varmatrix[whichdd_el.value][otherdd_el.options[i].value]) {
				otherdd_el.options[i].style.color = '#333333';
				c++;
				onlyOption = i;
			} else {
				otherdd_el.options[i].style.color = '#A0A0A0';
				if (otherdd_el.options[i].selected && !bNoRecurse) {
					otherdd_el.value = '';
					adjustDropDowns(otherdd, whichconstit, true);
				}
			}
		}
		// If only 1 possible option then select this
		if (c == 1 && !bNoRecurse) {
			otherdd_el.options[onlyOption].selected = true;
			adjustDropDowns(otherdd, whichconstit, true);
		}
	}
}

function updatePriceEtc() {
	if (isBundle) {
		if (hideprice == 1) {
			return;
		}
		var totalprice = 0;
		var bAllChosen = true;
		var delivery = new Object();
		var numdays;
		var maxdays = 0;
		for (var pid in varmatrix1) {
			for (var idx = 1; idx <= qtys[pid]; idx++) {
				var val1 = (document.fm['var1_'+pid+'_'+idx]?document.fm['var1_'+pid+'_'+idx].value:'');
				var val2 = (document.fm['var2_'+pid+'_'+idx]?document.fm['var2_'+pid+'_'+idx].value:'');
				var price = -1;
				for (var v1 in varmatrix1[pid]) {
					if (val1 != v1) {
						continue;
					}
					for (v2 in varmatrix1[pid][v1]) {
						if (val2 != v2) {
							continue;
						}
						price = parseFloat(varmatrix1[pid][v1][v2]['price']);
						numdays = deliverytime2days[varmatrix1[pid][v1][v2]['delivery']];
						delivery[numdays] = varmatrix1[pid][v1][v2]['delivery'];
						if (numdays > maxdays) {
							maxdays = numdays;
						}
					}
				}
				if (price == -1) {
					bAllChosen = false;
				} else {
					totalprice += price;
				}
			}
		}
		if (bAllChosen) {
			totalprice = totalprice - totalprice*bundsaving/100 - bundsavingabs;
			$('#initprice').html( '£'+formatNum(totalprice, 2, true) );
			
			deliverytime = delivery[maxdays];
			var dtime = 'Dispatch: <nobr>'+deliverytime+'</nobr>';
			if (deliverytime == standard_delivery) {
				dtime += '.<br>Next day delivery also available.';
			}
			$('#deliverytime').html( dtime );
		} else {
			deliverytime = '';
			$('#initprice').html( initialprice );
			$('#deliverytime').empty();
		}
		
	} else {
		var lowest_price = 99999999;
		var lowest_undiscprice = 99999999;
		var highest_saving = 0;
		var undiscprice, price, saving;
		var highest_price = 0;
		var val1 = (document.fm.var1?document.fm.var1.value:'');
		var val2 = (document.fm.var2?document.fm.var2.value:'');
		
		for (var v1 in varmatrix1) {
			if (val1 != '' && val1 != v1) {
				continue;
			}
			for (v2 in varmatrix1[v1]) {
				if (val2 != '' && val2 != v2) {
					continue;
				}
				price = parseFloat(varmatrix1[v1][v2]['discprice']);
				if (price == 0) {
					continue;
				}
				undiscprice = parseFloat(varmatrix1[v1][v2]['price']);
				if (price < lowest_price) {
					lowest_price = price;
					lowest_undiscprice = undiscprice;
				}
				if (price > highest_price) {
					highest_price = price;
				}
				saving = undiscprice - price;
				if (saving > highest_saving) {
					highest_saving = saving;
				}
			}
		}
		
		if (hideprice == 1) {
			price = '<a href="/G4/Contact_us" class=contactus>Contact us for price</a>';
		} else if (lowest_undiscprice-lowest_price < 0.01) {
			if (lowest_price == 99999999) {
				price = 'n/a';
			} else if (lowest_price == highest_price) {
				price = '£'+formatNum(lowest_price, 2, true);
			} else {
				price = 'from £'+formatNum(lowest_price, 2, true);
			}
		} else {
			if (lowest_price == highest_price) {
				price = "was £"+formatNum(lowest_undiscprice, 2, true)+"<br>";
				price += "<span class=dark>now £"+formatNum(lowest_price, 2, true)+"</span><br>";
				price += "<span class=red>save £"+formatNum(lowest_undiscprice-lowest_price, 2, true)+"</span>";
			} else {
				price = "was from £"+formatNum(lowest_undiscprice, 2, true)+"<br>";
				price += "<span class=dark>now from £"+formatNum(lowest_price, 2, true)+"</span><br>";
				price += "<span class=red>save up to £"+formatNum(highest_saving, 2, true)+"</span>";
			}
		}
		$('#price').html(price);
		
		$('#deliverytime').empty();
		if (varmatrix1[val1] && varmatrix1[val1][val2]) {
			var dtime = 'Dispatch: <nobr>'+varmatrix1[val1][val2]['delivery']+'</nobr>';
			if (varmatrix1[val1][val2]['delivery'] == standard_delivery) {
				dtime += '.<br>Next day delivery also available.';
			}
			$('#deliverytime').append(dtime);
			deliverytime = varmatrix1[val1][val2]['delivery'];
		}
	}
}

function ddChanged(whichdd, whichconstit) {
	// Auto adjust other drop down & update price, etc.
	adjustDropDowns(whichdd, whichconstit);
	updatePriceEtc();
	
	if (whichconstit) {
		wcbits = whichconstit.split('_');
		var pid = wcbits[0];
		var idx = wcbits[1];
		var ext = '_'+whichconstit;
		var prodimages = productimages[pid];
	} else {
		var ext = '';
		var prodimages = productimages;
	}
	
	// Find closest matching image
	var val1 = (document.fm['var1'+ext]?document.fm['var1'+ext].value:'');
	var val2 = (document.fm['var2'+ext]?document.fm['var2'+ext].value:'');
	var partial_matches = new Object;
	var bFoundMatch = false;
	for (imgid in prodimages) {
		if (val1 == prodimages[imgid].value1 && val2 == '') {
			bFoundMatch = true;
			break;
		}
		if (val2 == prodimages[imgid].value2 && val1 == '') {
			bFoundMatch = true;
			break;
		}
		if (val1 == prodimages[imgid].value1 && val2 == prodimages[imgid].value2) {
			bFoundMatch = true;
			break;
		}
		if (val1 == prodimages[imgid].value1 || val2 == prodimages[imgid].value2) {
			partial_matches[imgid] = true;
		}
	}
	if (!bFoundMatch) {
		for (imgid in prodimages) {
			if (partial_matches[imgid]) {
				bFoundMatch = true;
				break;
			}
		}
	}
	if (!bFoundMatch) {
		return;
	}
	
	switchImage(imgid);
}

function emailFriend(pid, bid) {
	var html = '<form action="/F0/Email_a_friend.php" method=post target=IFemailfriend onsubmit="UnTip();">';
	if (bid) {
		html += '<input type=hidden name=bid value="'+bid+'">';
	} else {
		html += '<input type=hidden name=pid value="'+pid+'">';
	}
	html += '<table cellspacing=0 class=emailfriend>';
	html += '<tr><td colspan=2><h2>Tell a friend about this product</h2></td></tr>';
	html += '<tr><td>Your name:</td><td><input type=text name=yourname style="width: 180px;"></td></tr>';
	html += '<tr><td>Friend\'s email address:</td><td><input type=text name=email style="width: 180px;"></td></tr>';
	html += '<tr><td colspan=2>Any message you want to accompany the email:</td></tr>';
	html += '<tr><td colspan=2><textarea name=message rows=6 style="width: 320px;"></textarea></td></tr>';
	html += '<tr><td colspan=2 class=calign><input class=button type=submit name=send value="Send" style="width: 50px;"> &nbsp; &nbsp; <input class=button type=submit name=cancel value="Cancel" style="width: 50px;" onclick="UnTip(); return false;"></td></tr>';
	html += '</table>';
	html += '</form>';
	return html;
}

var bVideoWatched = false;
function checkForm() {
	var fm = document.fm;
	if (isBundle) {
		var params = {
			bid: fm.bid.value
		};
		var bAllChosen = true;
		for (var pid in varmatrix1) {
			for (var idx = 1; idx <= qtys[pid]; idx++) {
				if (fm['var1_'+pid+'_'+idx] && fm['var1_'+pid+'_'+idx].value == '') {
					var label = $(fm['var1_'+pid+'_'+idx]).parent().prev().text().replace(/^Choose (.*):$/, '$1');
					alert('Please choose a value for '+label+'.');
					return false;
				}
				if (fm['var2_'+pid+'_'+idx] && fm['var2_'+pid+'_'+idx].value == '') {
					var label = $(fm['var2_'+pid+'_'+idx]).parent().prev().text().replace(/^Choose (.*):$/, '$1');
					alert('Please choose a value for '+label+'.');
					return false;
				}
				params['var1_'+pid+'_'+idx] = (fm['var1_'+pid+'_'+idx] ? fm['var1_'+pid+'_'+idx].value : '');
				params['var2_'+pid+'_'+idx] = (fm['var2_'+pid+'_'+idx] ? fm['var2_'+pid+'_'+idx].value : '');
			}
		}
			
	} else {
		if (fm.var1 && fm.var1.value == '' && fm.var2 && fm.var2.value == '') {
			alert('Please choose a '+variation1+' and a '+variation2+'.');
			return false;
		}
		if (fm.var1 && fm.var1.value == '') {
			alert('Please choose a '+variation1+'.');
			return false;
		}
		if (fm.var2 && fm.var2.value == '') {
			alert('Please choose a '+variation2+'.');
			return false;
		}
		var params = {
			pid: fm.pid.value,
			var1: (fm.var1?fm.var1.value:''),
			var2: (fm.var2?fm.var2.value:'')
		};
	}
	if (deliverytime == 'not available') {
		alert('Not currently available.');
		return false;
	}
	var qty = parseInt(fm.qty.value);
	if (isNaN(qty) || qty < 1) {
		alert('Please choose a quantity.');
		return false;
	}
	fm.qty.value = qty;
	params.qty = qty;
	
	if (!bVideoWatched && (product_name == 'Tripp Trapp® Classic' || product_name == 'Tripp Trapp® Trend Collection' || product_name == 'Tripp Trapp® Highchair' || product_name == 'Tripp Trapp® Exclusive Wood Collection')) {
		alert('The manufacturer would like you to watch an instructional\nvideo on using this product before purchasing.');
		tb_show(productname, 'http://www.stokke.com/layouts/siibs/movie.aspx?lang=en&q=high&mime=flash&RETURNSUCCESS='+encodeURIComponent('http://'+location.host+'/vidok.php')+'&TB_iframe=true&width=654&height=622&modal=true');
		return false;
	}
	
	var obj = $.get('/ajax/basket_add_item.php', params, addedToBasket);
	if (obj) {
		return false;
	} else {
		return true;
	}
}

function addedToBasket(res) {
	eval(res);
	$('#basket').replaceWith(basketBit);
	$('#minibasket').html(miniBasket);
	$('#minibasketcont').show(600);
}

function hideMiniBasket() {
	$('#minibasketcont').hide(600);
}

function playVideo(file) {
	if (file.match(/\.mp3/i)) {
		jwplayer('audiocont').setup({
			flashplayer: '/jwplayer/player.swf',
			file: '/files/'+file,
			width: 420,
			height: 24,
			autostart: true,
			controlbar: {position: 'bottom'}
		});
		$('#audiocont').show();
	} else {
		jwplayer('videocont').setup({
			flashplayer: '/jwplayer/player.swf',
			file: '/files/'+file,
			width: 472,
			height: 435,
			autostart: true,
			controlbar: {position: 'bottom'}
		});
		$('#videocont').show();
		$('#imgspace').hide();
	}
}
var player;
function playerReady(obj) {
	player = document.getElementById(obj.id);
	player.addModelListener('STATE', 'playerStateChanged');
}
function playerStateChanged(obj) {
	if (obj.newstate == 'COMPLETED' || obj.newstate == 'IDLE' || obj.newstate == 'PAUSED') {
		if (obj.id == 'audiocont') {
			jwplayer('audiocont').remove();
		} else {
			jwplayer('videocont').remove();
			$('#imgspace').show();
		}
	}
}

function scrollToDescr(id) {
	$('#description').scrollTop($('#'+id).position().top);
}
