﻿function NewAjaxObject() {

	// Create AJAX object
      	var xmlHttp;
      	var strresponse;
      	
      	try { // Firefox, Opera 8.0+, Safari
        		xmlHttp=new XMLHttpRequest();
        	}
        	
      	catch (e) { // Internet Explorer
        
        		try {
          			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        		}
        		
        		catch (e) {
        		
          			try {
            				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
            			}
            			
          			catch (e) {
          			
            				alert("Your browser does not support AJAX!");
            				return false;
            				
            			}
            			
          		}
          		
        	}
        	
        return xmlHttp;

}

// ===================================================================================================================================================================================================================================================
// ===================================================================================================================================================================================================================================================

// Retrieves products based on category and format
function GetListingProducts(ultarget) {

	// If they've entered any characters
	if (document.getElementById('product').value != "") {

		// Create new Ajax object
		var xmlHttp = NewAjaxObject();
		  	
		// Code for processing server response
		xmlHttp.onreadystatechange = function()	{
			
			// Once the request is complete
			if (xmlHttp.readyState == 4) {
					
				try  { //Internet Explorer
				
					xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
					xmlDoc.async = false;
					xmlDoc.loadXML(xmlHttp.responseText);
					
				}
				
				catch(e) {
				
					try { //Firefox, Mozilla, Opera, etc.
					
						var parser = new DOMParser();
						xmlDoc = parser.parseFromString(xmlHttp.responseText, "text/xml");
				    		xmlDoc.async = false;
				    		
				    	}
				    	
				  	catch(e) {
				  	
				    		alert(e.message);
				    		return;
				    		
				    	}
				}
				
				// Get target list
				var ulsuggestions = document.getElementById(ultarget);
				
				// Clear any existing suggestions
				while (ulsuggestions.hasChildNodes()) { ulsuggestions.removeChild(ulsuggestions.firstChild); }
				
				// Loop through each product
				for (var i = 0; i <= xmlDoc.getElementsByTagName("Results")[0].childNodes.length - 1; i++) {
				
					// Create the link
					var myanchor = document.createElement("a");
					myanchor.setAttribute("href", "#");
					myanchor.setAttribute("onclick", "product_selected('" + ultarget + "', this, " + xmlDoc.getElementsByTagName("Results")[0].childNodes[i].attributes.getNamedItem("ID").value + "); return false;");
					var mytext = document.createTextNode(xmlDoc.getElementsByTagName("Results")[0].childNodes[i].firstChild.nodeValue);
					myanchor.appendChild(mytext);
					
					// Create the list item
					var myli = document.createElement("li");
					myli.appendChild(myanchor);
					
					// Insert it into the document
					ulsuggestions.appendChild(myli);
				
				}
				
				// Show the suggestions
				document.getElementById(ultarget).style.display = "block";
				
				// Highlight the keywords
				//myregexp = new RegExp(">(.*)(" + document.getElementById('keywords').value + ")(.*)<", "gi");
				//document.getElementById(ultarget).innerHTML = strresponse.replace(myregexp, ">$1<strong>$2</strong>$3<");
				
			}
		  			
		}
	    	
	    	var ddlcats = document.getElementById('categories');
	    	var ddlformats = document.getElementById('formats');
	    	
	    	// Make the request
	    	xmlHttp.open("GET", "xml_products.aspx?catid=" + ddlcats.options[ddlcats.selectedIndex].value + "&formatid=" + ddlformats.options[ddlformats.selectedIndex].value + "&keywords=" + document.getElementById('product').value, true);
	    	xmlHttp.send(null);
	    	
	}

}

// Retrieves listings based on product id
function GetListings(tbodytarget) {


		// Create new Ajax object
		var xmlHttp = NewAjaxObject();
		  	
		// Code for processing server response
		xmlHttp.onreadystatechange = function()	{
			
			// Once the request is complete
			if (xmlHttp.readyState == 4) {
					
				try  { //Internet Explorer
				
					xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
					xmlDoc.async = false;
					xmlDoc.loadXML(xmlHttp.responseText);
					
				}
				
				catch(e) {
				
					try { //Firefox, Mozilla, Opera, etc.
					
						var parser = new DOMParser();
						xmlDoc = parser.parseFromString(xmlHttp.responseText, "text/xml");
				    		xmlDoc.async = false;
				    		
				    	}
				    	
				  	catch(e) {
				  	
				    		alert(e.message);
				    		return;
				    		
				    	}
				}
				
				// Get target tbody
				var tbody = document.getElementById(tbodytarget);
				
				// Clear any existing suggestions
				while (tbody.hasChildNodes()) { tbody.removeChild(tbody.firstChild); }
				
				// Loop through each result
				for (var i = 0; i <= xmlDoc.getElementsByTagName("Results")[0].childNodes.length - 1; i++) {
					
					// Create pic cell
					var picimg = document.createElement("td");
					picimg.setAttribute("src", "/pics/" + xmlDoc.getElementsByTagName("Pic")[0].childNodes[i].value);
					var pictd = document.createElement("td");
					pictd.appendChild(picimg);
					
					// Create table row
					var mytr = document.createElement("tr");
					mytr.appendChild(pictd);
					
					
					
					//var myanchor = document.createElement("a");
					//myanchor.setAttribute("href", "#");
					//myanchor.setAttribute("onclick", "product_selected('" + ultarget + "', this, " + xmlDoc.getElementsByTagName("Results")[0].childNodes[i].attributes.getNamedItem("ID").value + "); return false;");
					//var mytext = document.createTextNode(xmlDoc.getElementsByTagName("Results")[0].childNodes[i].firstChild.nodeValue);
					//myanchor.appendChild(mytext);
					
					
					
					
					
					
					// Insert it into the document
					tbody.appendChild(mytr);
				
				}
				
			}
		  			
		}
	    	
	    	// Make the request
	    	xmlHttp.open("GET", "xml_listings.aspx?pid=5114", true);
	    	xmlHttp.send(null);

}

// Called once a product change has been applied
function product_applied(ptitle) {

	// Disable the search box (until change link is clicked)
	document.getElementById("categories").disabled = true;
	document.getElementById("formats").disabled = true;
	document.getElementById("product").disabled = true;
	document.getElementById("product").className = "readonly";
	
	// Show change/cancel link
	document.getElementById("change").style.display = "inline";
	
	// Show other tabs
	document.getElementById("tab-other-listings").style.display = "block";
	document.getElementById("tab-bins").style.display = "block";
	document.getElementById("tab-auctions").style.display = "block";
	document.getElementById("tab-completed").style.display = "block";
	
	// Enable and set eBay keywords for editing
	document.getElementById("ebaykeywords").disabled = false;
	document.getElementById("ebayrefresh").disabled = false;
	document.getElementById("ebaykeywords").value = document.getElementById("formats").options[document.getElementById("formats").selectedIndex].text.toLowerCase() + " " + ptitle.toLowerCase();

}

// Called when a suggested product is clicked
function product_selected(ultarget, myanchor, productid) {

	// Save the selection
	document.getElementById("product").value = myanchor.innerHTML;
	document.getElementById("pid").value = productid;
	
	// Hide the suggestions
	document.getElementById(ultarget).style.display = "none";
	
	// Retrieve existing listings
	GetListings("listingsview");
	
	product_applied(myanchor.innerHTML);
	
}

// Called when the change item link is clicked
function product_cleared() {

	// Clear previous selection
	document.getElementById("product").value = "";
	document.getElementById("pid").value = "0";
	document.getElementById("ebaykeywords").value = "";
	document.getElementById("ebaykeywords").disabled = true;
	document.getElementById("ebayrefresh").disabled = true;
	
	// Enable and focus the input
	document.getElementById("categories").disabled = false;
	document.getElementById("formats").disabled = false;
	document.getElementById("product").disabled = false;
	document.getElementById("product").className = "";
	document.getElementById("product").focus;
	
	// Hide change/cancel link
	document.getElementById("change").style.display = "none";
	
	// Hide other tabs
	document.getElementById("tab-other-listings").style.display = "none";
	document.getElementById("tab-bins").style.display = "none";
	document.getElementById("tab-auctions").style.display = "none";
	document.getElementById("tab-completed").style.display = "none";
	
}

// ===================================================================================================================================================================================================================================================
// ===================================================================================================================================================================================================================================================

// Changes the tab/data displayed
function change_tab(targettab) {

	// De-activate them all first
	document.getElementById("this-listing").style.display = "none";
	document.getElementById("other-listings").style.display = "none";
	document.getElementById("ebay-bins").style.display = "none";
	document.getElementById("ebay-auctions").style.display = "none";

	// Then activate the target
	document.getElementById(targettab).style.display = "block";

}

// Binds eBay listings to a target by type
function GetEbayListings(listingtype, targetcontainer) {

	// Create new Ajax object
	var xmlHttp = NewAjaxObject();
	  	
	// Code for processing server response
	xmlHttp.onreadystatechange = function()	{
		
		// Once the request is complete
		if (xmlHttp.readyState == 4) {
				
			try  { //Internet Explorer
			
				xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
				xmlDoc.async = false;
				xmlDoc.loadXML(xmlHttp.responseText);
				
			}
			
			catch(e) {
			
				try { //Firefox, Mozilla, Opera, etc.
				
					var parser = new DOMParser();
					xmlDoc = parser.parseFromString(xmlHttp.responseText, "text/xml");
			    		xmlDoc.async = false;
			    		
			    	}
			    	
			  	catch(e) {
			  	
			    		alert(e.message);
			    		return;
			    		
			    	}
			}
			
			// Get target container (tbody)
			var mycontainer = document.getElementById(targetcontainer);
			
			// Clear any existing table rows
			while (mycontainer.hasChildNodes()) { mycontainer.removeChild(mycontainer.firstChild); }
			
			// Get the data
			var nodes_title = xmlDoc.getElementsByTagName("Title");
			var nodes_url = xmlDoc.getElementsByTagName("ViewItemURLForNaturalSearch");
			var nodes_picture = xmlDoc.getElementsByTagName("GalleryURL");
			var nodes_auctionprice = xmlDoc.getElementsByTagName("AuctionPrice");
			var nodes_binprice = xmlDoc.getElementsByTagName("BuyNowPrice");
			var nodes_timeleft = xmlDoc.getElementsByTagName("TimeLeft");
			
			// Loop through each product
			for (var i = 0; i < nodes_title.length; i++) {
			
				// Create image in its own cell
				var imagecell = document.createElement("td");
				var myimageanchor = document.createElement("a");
				myimageanchor.setAttribute("href", nodes_url[i].firstChild.nodeValue);
				myimageanchor.setAttribute("onclick", "window.open(this.href); return false;");
				var itemimage = document.createElement("img");
				itemimage.setAttribute("src", nodes_picture[i].firstChild.nodeValue);
				itemimage.setAttribute("alt", nodes_title[i].firstChild.nodeValue);
				
				// Put image cell stuff together
				myimageanchor.appendChild(itemimage);
				imagecell.appendChild(myimageanchor);
				
				// Create main description cell
				var maincell = document.createElement("td");
				var mytitle = document.createElement("p");
				var mytitleanchor = document.createElement("a");
				mytitleanchor.setAttribute("href", nodes_url[i].firstChild.nodeValue);
				mytitleanchor.setAttribute("onclick", "window.open(this.href); return false;");
				
				// Put main cell stuff together
				mytitleanchor.appendChild(document.createTextNode(nodes_title[i].firstChild.nodeValue));
				mytitle.appendChild(mytitleanchor);
				maincell.appendChild(mytitle);
				
				// Create auction price cell
				var auctionpricecell = document.createElement("td");
				var auctionprice = document.createElement("p");
				if (nodes_auctionprice[i].firstChild.nodeValue > 0) auctionprice.appendChild(document.createTextNode("£" + parseFloat(nodes_auctionprice[i].firstChild.nodeValue).toFixed(2)));
				auctionpricecell.appendChild(auctionprice);
				
				// Create buy now price price cell
				var binpricecell = document.createElement("td");
				// If we have a bin price
				if (nodes_binprice[i].firstChild.nodeValue > 0) { 
					var binprice = document.createElement("p");
					binprice.appendChild(document.createTextNode("£" + parseFloat(nodes_binprice[i].firstChild.nodeValue).toFixed(2)));
					var binimage = document.createElement("img");
					binimage.setAttribute("src", "/images/ebay-buy-now.gif");
					binimage.setAttribute("alt", "Buy It Now");
					binprice.appendChild(binimage);
					binpricecell.appendChild(binprice);
				}
				
				// Create time left cell
				var timeleftcell = document.createElement("td");
				var timeleft = document.createElement("p");
				timeleftcell.appendChild(document.createTextNode(nodes_timeleft[i].firstChild.nodeValue));
				
				// Create the row and add all the cells to it
				var myrow = document.createElement("tr");
				myrow.appendChild(imagecell);
				myrow.appendChild(maincell);
				myrow.appendChild(auctionpricecell);
				myrow.appendChild(binpricecell);
				myrow.appendChild(timeleftcell);
				
				// Insert the new row into the table body
				mycontainer.appendChild(myrow);
			}
			
		}
	  			
	}

	// Make the request
	xmlHttp.open("GET", "xml_ebay.aspx?type=" + listingtype + "&keywords=" + document.getElementById("ebaykeywords").value, true);
	xmlHttp.send(null);

}

// Called when New Listing tab is clicked
function listings_this() {

	change_tab("this-listing");

}

// Called when Other Listings tab is clicked
function listings_other() {

	change_tab("other-listings");
	
	// Update iframe
	window.frames["myiframe"].location = "iframe_listings.aspx?itemid=" + document.getElementById("pid").value;

}

// Called when Buy Now tab is clicked
var previousbinkeywords;
function listings_bin() {

	change_tab("ebay-bins");
		
	// If the keywords have changed
	if (document.getElementById("ebaykeywords").value != previousbinkeywords) {
	
		// Bind Buy Now listings
		GetEbayListings("bins", "bin-listings");
		
		// Save keywords
		previousbinkeywords = document.getElementById("ebaykeywords").value;
	
	}

}

// Called when Auctions tab is clicked
var previousauctionskeywords;
function listings_auctions() {

	change_tab("ebay-auctions");
	
	// If keywords have changed
	if (document.getElementById("ebaykeywords").value != previousauctionskeywords) {
	
		// Bind auctions
		GetEbayListings("auctions", "auction-listings");
		
		// Save keywords
		previousauctionskeywords = document.getElementById("ebaykeywords").value;
	
	}

}

// Called when Completed Listings tab is clicked
function listings_completed(mylink) {

	window.open(mylink.href + document.getElementById("ebaykeywords").value);

}

// Called by inline script tag directly below product fields
function ProductFieldsLoaded() {

	// Get any product title that was specified server side
	var ptitle = document.getElementById("ptitle").value;
	
	// If we have an item to edit
	if (ptitle != "") {
	
		// Apply it
		document.getElementById("categories")
		document.getElementById("formats")
		document.getElementById("product").value = ptitle;
	
		// Disable search facility and shows tabs
		product_applied(ptitle);

	}

}