var oldGuid = null;
var oldAvailable = null;
var soundNameSellout = "";
var soundNameNewItem = "";
var container;
var statusContainer;
var configContainer;

var soundsOptions = '<option style="font-weight: bold; background-color: #EDE2D4;" value="" selected="yes">No sound</option><option value="beeprobo.mp3">Robot</option><option value="badumm.mp3">Ummm</option><option value="beeparca.mp3">Arcade game</option><option value="beepjazz.mp3">Jazz note</option><option value="phone.mp3">Old phone</option><option value="scream.mp3">Scream</option><option value="sonar.mp3">Sonar</option><option value="whoosh.mp3">Whoosh</option><option value="bark.mp3">Dog bark</option><option value="beepmult.mp3">Mult</option><option value="beepspri.mp3">Spring</option><option value="synthhor.mp3">Horn</option>';

function createChecker()
{
	container = document.createElement("div");
	container.id = "container";
	container.style.borderStyle = "dashed";
	container.style.borderWidth = "thin";
	container.style.textAlign = "center";
	container.style.width = "800px";
	container.style.height = "150px";
	container.style.padding = "10px 0";
	container.style.margin = "10px auto";
	document.getElementById("chkerContent").appendChild(container);
	container.innerHTML = "<p>Loading... please wait.</p>";
	statusContainer = document.createElement("div");
	statusContainer.style.textAlign = "center";
	statusContainer.style.width = "800px";
	statusContainer.style.margin = "0 auto";
	document.getElementById("chkerContent").appendChild(statusContainer);
	configContainer = document.createElement("div");
	configContainer.style.textAlign = "center";
	configContainer.style.width = "800px";
	configContainer.style.margin = "0 auto";
	document.getElementById("chkerContent").appendChild(configContainer);
	configContainerBuf = "<p><b>Sounds</b> - Sold-out: ";
	configContainerBuf += '<select name="soundSO" id="soundSO" onChange="changeSound(1,1);">'+soundsOptions+'</select>';
	configContainerBuf += " - New item: ";
	configContainerBuf += '<select name="soundNI" id="soundNI" onChange="changeSound(0,1);">'+soundsOptions+'</select>';
	configContainerBuf += "</p>";
	configContainer.innerHTML = configContainerBuf;
        var soundSelectorPtr = document.getElementById("soundNI");
        soundSelectorPtr.selectedIndex = 1;
	soundNameNewItem = "beeprobo.mp3";
}

function changeSound(whichOne,autoPlay)
{
	if (whichOne == 1)
	{
		var soundSelectorPtr = document.getElementById("soundSO");
		var soundSelectorIndex = soundSelectorPtr.selectedIndex;
		soundNameSellout = soundSelectorPtr.options[soundSelectorIndex].value;
		if (autoPlay == 1) playSound(soundNameSellout);
	}
	else
	{
		var soundSelectorPtr = document.getElementById("soundNI");
		var soundSelectorIndex = soundSelectorPtr.selectedIndex;
		soundNameNewItem = soundSelectorPtr.options[soundSelectorIndex].value;
		if (autoPlay == 1) playSound(soundNameNewItem);
	}
}

function playSound(soundName)
{
        if ((soundName != null) && (soundName != "")) Sound.play("/sounds/"+soundName);
}

function initChker()
{
	createChecker();

	var page = new PushPage();
	page.context.setDebugAlertsOnClientError(false);
	page.context.setRemoteAlertsOnClientError(false);
	page.context.setDomain("wootoolbox.com");

	page.onClientAlert = function(code, mess) {
	if(window.console)
		console.error("onClientAlert", mess);
	}

        page.onClientError = function(mess) {
        if(window.console)
                console.error("onClientError", mess);
        }


	page.onEngineReady = function(engine) {
		function updateStatus(status) {
		if(typeof console != 'undefined')
			console.log("Engine is now", status);
		}
		updateStatus(engine.getStatus());
	
		engine.onStatusChange = updateStatus;

	}

	page.onEngineCreation = function(engine) {
		engine.policy.setPollingInterval(2500);
		engine.connection.setLSHost("www.wootoolbox.com");
		engine.connection.setLSPort(8080);
		engine.connection.setAdapterName("WOOT");
		engine.changeStatus("STREAMING");
	}

	page.bind();
	page.createEngine("WootApp", "LS", "SHARE_SESSION");
	var group = ["wootitem"];
	var schema = ["title", "price", "shipping", "condition", "buy", "discuss", "compare", "imageThumbnail", "imageStandard", "imageDetail", "guid", "siteStatus", "saleStatus", "percentage", "minsleft"];
	var pushtable = new NonVisualTable(group, schema, "MERGE");
	pushtable.setSnapshotRequired(true);
	//pushtable.setClearOnDisconnected(true);
	pushtable.onItemUpdate = function(itemPos, updateInfo, itemName)
	{
		if((itemPos != null) && (updateInfo != null) && (itemName == "wootitem") && (updateInfo.getNewValue("title") != null))
		{
			itemTitle = updateInfo.getNewValue("title");
			itemPrice = "$"+updateInfo.getNewValue("price");
			itemShipping = "$"+updateInfo.getNewValue("shipping");
			itemCondition = updateInfo.getNewValue("condition");
			itemPercentage = updateInfo.getNewValue("percentage");
			itemPercentage = Math.floor(itemPercentage * 100);
			itemPercentage = itemPercentage / 100;
			itemMinsLeft = updateInfo.getNewValue("minsleft");
			siteStatus = updateInfo.getNewValue("siteStatus");
			itemStatus = updateInfo.getNewValue("saleStatus");
			itemImageUrl = updateInfo.getNewValue("imageThumbnail");
			itemImageDetail = updateInfo.getNewValue("imageDetail");
			compareUrl = updateInfo.getNewValue("compare");
			buyUrl = updateInfo.getNewValue("buy");
			discussUrl = updateInfo.getNewValue("discuss");

			containerHtmlBuffer = '<div style="float:left; margin: 10px; width: 150px; height: 100%;"><a target="_blank" href="'+itemImageDetail+'"><img style="border: none;" src="'+itemImageUrl+'" alt="-"></a></div>'+
				'<div style="font-size: 24px; font-weight: bold;">'+itemTitle+'</div>';
			if (siteStatus != 'normal')
			{
				itemPercentageBar = (itemStatus == 'available')?itemPercentage:'0';
				//containerHtmlBuffer += '<div style="width: 400px; border: thin solid #000; position: relative; left: 285px;"><div style="position: absolute; background-color: #ED8600; width: '+itemPercentageBar+'%;">&nbsp;</div>&nbsp;</div>';
				if (itemMinsLeft == "")
				{
					itemStatusDesc = (itemStatus == 'available')?(itemPercentage+'% left'):'SOLD OUT';
					itemStatusDescShort = (itemStatus == 'available')?(itemPercentage+'%'):'SOLD OUT';
				}
				else
				{
					itemStatusDesc = (itemStatus == 'available')?(itemPercentage+'% ('+itemMinsLeft+'mn) left'):'SOLD OUT';
					itemStatusDescShort = (itemStatus == 'available')?(itemPercentage+'%'):'SOLD OUT';
				}

				if (itemStatus != 'available')
					itemStatusColor = '#CC0000';
				else
				{
					if (itemPercentage <= 10)
					{
						itemStatusColor = '#7F7F00';
					}
					else
					{
						itemStatusColor = '#00CC00';
					}
				}
				//containerHtmlBuffer +=  '<div style="font-size: 12px;">'+itemStatusDesc+'</div>';
				document.title = itemStatusDescShort+" "+itemTitle;
			}
			else
			{
				itemStatusDesc = (itemStatus == 'available')?'Available':'SOLD OUT';
				itemStatusColor = (itemStatus == 'available')?'#00CC00':'#CC0000';
				//containerHtmlBuffer +=  '<div style="font-size: 12px;">'+itemStatusDesc+'</div>';
				document.title = "WooToolbox";
			}

			containerHtmlBuffer += '<div style="width: 100%;"><style type="text/css">table.v{margin: 0 auto; border-collapse: collapse;} .v td{border: #000000 1px solid; padding: 0 5px;}</style><table class="v"><tr><td>Price</td><td>Shipping</td><td>Condition</td><td>Availability</td></tr>'+
		                                '<tr style="font-weight: bold;"><td>'+itemPrice+'</td><td>'+itemShipping+'</td><td>'+itemCondition+'</td><td style="color: '+itemStatusColor+';">'+itemStatusDesc+'</div></td></tr></table></div>';

			containerHtmlBuffer += '<a class="ta" target="_blank" href="'+compareUrl+'">Price Comparison</a> - ';
			containerHtmlBuffer += '<a class="ta" target="_blank" href="'+buyUrl+'">Buy it</a> - ';
			containerHtmlBuffer += '<a class="ta" target="_blank" href="'+discussUrl+'">Discuss it</a>';

			container.innerHTML = containerHtmlBuffer;

			var newGuid = updateInfo.getNewValue("guid");
			if ((oldGuid != null) && (newGuid != oldGuid))
			{
				playSound(soundNameNewItem);
			}
			if ((oldAvailable == 'available') && (itemStatus != 'available'))
			{
				playSound(soundNameSellout);
			}
			oldGuid = newGuid;
			oldAvailable = itemStatus;
			
		}
		
	}

	page.addTable(pushtable, "woottable");
}

