var css_ref_id;
if (css_ref_id == null) css_ref_id=1;

function ShopWidget()
{
	this.designId = "gallery";
	this.height = "280";
	this.width = "100%";
	this.domain = "ads.shopping.com";
	//this.domain = getHostname(document.getElementById('sdcWidgetGenerator').getAttribute('src'));

	this.requestParameters = new Object();
	this.requestParameters.apiKey = "";
	this.requestParameters.trackingId = "";

	this.isValid = false;
}

ShopWidget.prototype.validate = function()
{
	// Is this a valid component
	this.isValid = false;

	try
	{
		// check for valid design
		var validDesign = false;
		if (this.designId == "gallery") {
			validDesign = true;
		}
		else if (this.designId == "listinglike") {
			validDesign = true;
		}
		else if (this.designId == "textlike") {
			this.designId = "googlelikewithprice";
			validDesign = true;
		}

		if (!validDesign)
			throw "Need valid designId";	

		// check for valid input
		var validInput = false;

		// get random position for rotation of dynamic nav parameters
		var numKeywords = this.requestParameters.keyword ? this.requestParameters.keyword.length : 0;
		var numCategories = this.requestParameters.categoryId ? this.requestParameters.categoryId.length : 0;
		if (numKeywords || numCategories) {
			var index = Math.floor(Math.random() * Math.max(numKeywords, numCategories));

			var keyword = numKeywords > index ? this.requestParameters.keyword[index] : undefined;
			this.requestParameters.keyword = keyword;
			if (keyword && keyword.length)
				validInput = true;

			var categoryId = numCategories > index ? this.requestParameters.categoryId[index] : undefined;
			this.requestParameters.categoryId = categoryId;
			if (categoryId && categoryId.length)
				validInput = true;

			var numAttributeValues = this.requestParameters.attributeValue ? this.requestParameters.attributeValue.length : 0;
			var attributeValue = numAttributeValues > index ? this.requestParameters.attributeValue[index] : undefined;
			this.requestParameters.attributeValue = attributeValue;
		}
		else {
			this.requestParameters.keyword = undefined;
			this.requestParameters.categoryId = undefined;
			this.requestParameters.attributeValue = undefined;
		}

		if (this.requestParameters.productId && this.requestParameters.productId.length > 0)
		{
			// get random position for rotation of product IDs
			var index = Math.floor(Math.random() * this.requestParameters.productId.length);
			var productId = this.requestParameters.productId[index];
			this.requestParameters.productId = productId;
			if (productId && productId.length > 0)
				validInput = true;
		}

		if (this.requestParameters.offerId && this.requestParameters.offerId.length > 0)
		{
			// get random position for rotation of offer IDs
			var index = Math.floor(Math.random() * this.requestParameters.offerId.length);
			var offerId = this.requestParameters.offerId[index];
			this.requestParameters.offerId = offerId;
			if (offerId && offerId.length > 0)
				validInput = true;
		}

		if (!validInput)
			throw "Need valid search parameter";
	}
	catch(e)
	{
		this.errorMessage = e;
		this.isValid = false;
		return false;
	}

	// If we have the necessary parameters, we can render an ad.  
	this.errorMessage = null;
	this.isValid = true;
	return true;
}

ShopWidget.prototype.render = function()
{
	var widgetUrl;

	// Unless we already have a URL, validate other parameters, and build URL
	if (this.url && this.url.length) {
		widgetUrl = this.url;
	}
	else {
		this.validate();
		if (!this.isValid) return;

		// base request URL
		widgetUrl = "http://" + this.domain + "/AdSearchService/adSearch?showProductOffers=true";
		widgetUrl += "&designId=" + encodeURIComponent(this.designId);

		// loop through request parameters
		for (var property in this.requestParameters) {
			if (this.requestParameters.hasOwnProperty(property)) {
				// loop through values if multiple (separated by '||')
				if (this.requestParameters[property]) {
					var paramValues = this.requestParameters[property].split("||");
					for (var index = 0; index < paramValues.length; index++) {
						widgetUrl += "&" + property + "=" + encodeURIComponent(paramValues[index]);
					}
				}
			}
		}
	}

	var re = new RegExp('internet explorer', 'i');
	if (navigator.appName.match(re)) {
		// IE support for object is broken - need to use iframes still
		document.getElementById('sdcWidgetContent').innerHTML = 
			"<iframe id='sdcWidget' style='overflow: hidden; border: 0px;' frameborder='0' scrolling='no' src='" + 
			widgetUrl + "' height='" + this.height + "' width='" + this.width + "' />";
	}
	else {
		document.getElementById('sdcWidgetContent').innerHTML = 
			"<object id='sdcWidget' style='overflow: hidden' type='text/html' data='" + 
			widgetUrl + "' height='" + this.height + "' width='" + this.width + "' />";
	}

	//httpRequest("GET", widgetUrl, true);
}

// ----------------------------------------
// Wrapper function for constructing a request object.
// Parameters:
// reqType: The HTTP request type, such as GET or POST.
// url: The URL of the server program.
// asynch: Whether to send the request asynchronously or not.
// ----------------------------------------
function httpRequest(reqType,url,asynch) {

	var request;

	// Mozilla-based browsers
	if (window.XMLHttpRequest) {
		request = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		request = new ActiveXObject("Msxml2.XMLHTTP");
		if (!request) {
			request = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}

	// Request could still be null if neither ActiveXObject
	// initialization succeeded
	if (request) {
		// If the reqType param is POST, then the fifth arg is the POSTed data
		if (reqType.toLowerCase() != "post") {
			initReq(request, reqType, url, asynch);
		} else {
			// The POSTed data
			var args = arguments[4];
			if (args != null && args.length > 0) {
				initReq(request, reqType, url, asynch, args);
			}
		}
	} else {
		//alert("Your browser does not permit the use of all " +
		//      "of this application's features!");
	}
}

// ----------------------------------------
// Initialize a request object that is already constructed
// ----------------------------------------
function initReq(request, reqType, url, asynch) {
	try {
		// Specify the function that will handle the HTTP response
		request.onreadystatechange = function() {
   			if (request.readyState == 4) {
				if (request.status == 200) {
					document.getElementById('sdcWidgetContent').innerHTML = request.responseText;
				}
			}
		}
		request.open(reqType, url, asynch);

		// If the reqType param is POST, then the
		// fifth argument to the function is the POSTed data
		if (reqType.toLowerCase() == "post") {
			// Set the Content-Type header for a POST request
			request.setRequestHeader("Content-Type", "application/x-ww-form-urlencoded; charset=UTF-8");
			request.send(arguments[4]);
		} else {
			request.send(null);
		}
	} catch (errv) {
		//alert("The application cannot contact the server at the moment. " +
		//      "Please try again in a few seconds.\n" +
		//      "Error detail: " + errv.message);
	}
}

// ----------------------------------------
// Get the hostname of this script
// ----------------------------------------
function getHostname(str) {
	var hostname = '';
	var re = new RegExp('^(?:http(?:s)\://)?([^/]+)/', 'im');
	if (str.match(re)) {
		hostname = RegExp.$1.toString();
	}
	
	return hostname;
}
