/*
 * All java script logic for the application.
 *
 * The code relies on the jQuery JS library to
 * be also loaded.
 */

var app = ( function(jQuery) {
	// Global dw private data goes here
	var productCompare = {
		products : [ null, null, null, null, null, null ],
		count : 0,
		emptyImgSrc : '',
		emptyImgAlt : '',
		baseButtonLabel : '',
		confirmationMessage : '',
		openUrl : '',
		addUrl : '',
		removeUrl : '',
		initialize : function(options) {
			this.products = [ null, null, null, null, null, null ];
			this.count = 0;
			this.emptyImgSrc = options.emptyImgSrc;
			this.emptyImgAlt = options.emptyImgAlt;
			this.baseButtonLabel = options.baseButtonLabel;
			this.confirmationMessage = options.confirmation;
			this.openUrl = options.openUrl;
			this.addUrl = options.addUrl;
			this.removeUrl = options.removeUrl;

			this.updateButtons();
		},
		addProduct : function(options) {
			var addIndex = productCompare.count;
			productCompare.products[addIndex] = {
				id : options.id,
				category : options.category
			};
			productCompare.count++;
			return addIndex;
		},
		setProductImage : function(options) {
			jQuery('#compareItemsProduct' + options.index).each( function() {
				var productImage = jQuery(this)[0];
				productImage.src = options.src;
				productImage.alt = options.alt;
			});

			jQuery('#compareItemsClear' + options.index).show();
		},
		updateButtons : function() {
			var buttonLabel = this.baseButtonLabel;
			if (productCompare.count > 0) {
				buttonLabel += ' (' + productCompare.count + ')';
			}

			var compareItemsButton = jQuery('#compareItemsButton');
			compareItemsButton.html(buttonLabel);
			compareItemsButton.each( function() {
				jQuery(this)[0].disabled = (productCompare.count < 2);
			});

			jQuery('#clearComparedItemsButton').each( function() {
				jQuery(this)[0].disabled = (productCompare.count < 2);
			});
		}
	};

	// TODO: hard coded strings

	return { // dw scope public
		LogRequestID : null,
		URLs : {},
		resources : null,
		containerId : "content",
		ProductCache : null,
		Templates : {}, // cache to hold html templates
		currentCursor : null, // holds the current product position within the product nav on product detail page
		productCount : null, // represents the max number of products in a search resultset
		currentPageObj : null, // holds the currently displayed objects associated with next/prev
		clearDivHtml : "<div class=\"clear\"><!-- W3C Clearing --></div>",
		dialogSettings : { // default dialog box settings
			autoOpen : false,
			buttons : {},
			modal : true,
			overlay : {
				opacity : 0.5,
				background : "black"
			},
			height : 530,
			width : 800,
			title : '',
			show : "slow",
			hide : "normal",
			resizable : false
		},

		tooltipSettings : {
			delay : 0,
			showURL : false,
			extraClass : "pretty fancy",
			top : 15,
			left : 5
		},

		AJAX : {
			Success : "success",
			currentRequests : {}, // request cache

			getJson : function(options) {
				var thisAjax = this;
				// do not bother if the request is already in progress
			// and let go null reqname
			if (!options.reqName || !this.currentRequests[options.reqName]) {
				this.currentRequests[options.reqName] = true;
				// make the server call
				jQuery.ajax( {
					//type	: "get",
					contentType : "application/json; charset=utf-8",
					dataType : "json",
					url : options.url,
					cache : false,
					data : options.data,
					success : function(response, textStatus) {
						thisAjax.currentRequests[options.reqName] = false;

						// get the request ID for log
					app.LogRequestID = response.LogRequestID;

					// handle failure
					if (!response.Success) {
						// TODO show error? or do something else
						app.printAjaxError( {}, {}, {
							url : options.url
						});
					}

					options.callback(response, textStatus);
				},

					error : function(request, textStatus, error) {
						if (textStatus === "parsererror") {
							// TODO show error? or do something else
							alert('bad response, parser error=' + request
									+ ", options.url=" + options.url);
						}
						// get the request ID for log
						// app.LogRequestID = response.LogRequestID;

						// TODO, maybe we should show a generic global error
						// message

						options.callback( {
							Success : false,
							data : {}
						});
					},

					complete : function(XMLHttpRequest, textStatus) {
					}
				});
			}
		},

		load : function(options) {

			//jQuery(options.selector).load(options.url, options.data, options.callback);

			var thisAjax = this;
			// do not bother if the request is already in progress
			// and let go null reqname
			if (!options.reqName || !this.currentRequests[options.reqName]) {
				this.currentRequests[options.reqName] = true;
				// make the server call
				jQuery.ajax( {
					//type	: "POST",
					dataType : "html",
					url : options.url,
					cache : false,
					data : options.data,
					success : function(response, textStatus) {
						thisAjax.currentRequests[options.reqName] = false;

						// get the request ID for log

					// handle failure
					/*
					 * if (!response.Success) { // TODO show error? or do
					 * something else app.printAjaxError({}, {}, {url: url}); }
					 */
					if (options.selector) {
						jQuery(options.selector).html(response);
					}
					(options.callback != undefined ? options.callback(response,
							textStatus) : null)
				},

				error : function(request, textStatus, error) {
					if (textStatus === "parsererror") {
						// TODO show error? or do something else
					alert('bad response, parser error');
				}
				// get the request ID for log
				// app.LogRequestID = response.LogRequestID;

				// TODO, maybe we should show a generic global error message

				options.callback(null, textStatus);
			},

			complete : function(XMLHttpRequest, textStatus) {
			}
				});
			}
		}
		},

		/*
		 * Support for the compare window
		 */
		ProductCompare : {
			openPopup : function(url) {
				window.open(url, 'product_compare',
						'width=800,height=600,scrollbars=yes,resizable=yes',
						true /* replace history in the popped up window */
				).focus();
			}
		},

		getProduct : function(options) { // id, source, start
			var cId = options.containerId || app.containerId;

			jQuery("#" + cId).html(app.wait(2));

			options.start = options.start || -1;
			app.AJAX.load( {
				selector : "#" + cId,
				url : (options.url ? options.url : app.URLs.getProductUrl
						+ "?pid=" + options.id)
						+ "&source="
						+ options.source
						+ "&start="
						+ (options.start - 0)
						+ "&searchUrl="
						+ app.URLs.ContinueShop,
				callback : function(responseText, textStatus) {

					if (textStatus == app.AJAX.Success) {
					}
				}
			});
		},

		/*
		 * Functionality around the mini cart.
		 */
		minicart : {
			// flag, whether cart is open or not
			state : 0,

			// during page loading, the Demandware URL is stored here
			url : '',

			// timer for automatic close of cart item view
			timer : null,

			// initializations
			init : function() {
				app.minicart.reset(); // reset all the existing event bindings

				// jQuery('#hCart').hover( function() {
				// app.minicart.cartShow();
				// },null);

				jQuery('#mCart').bind("mouseover", function() {
					clearTimeout(app.minicart.timer);
					app.minicart.timer = null;
				});

				jQuery('#mCart').bind(
						"mouseleave",
						function() {
							// after a time out automatically close it
							app.minicart.timer = setTimeout(
									'app.minicart.cartClose()', 30);
						});

				// register close button event
				/*
				 * jQuery('#minicartcontent #minicartclose').click(function() { //
				 * reset all the events bindings app.minicart.reset();
				 * app.minicart.cartClose(0); });
				 */

			},
			// reset minicart
			reset : function() {
				jQuery('#mCart').unbind("mouseenter");
				jQuery('#mCart').unbind("mouseleave");
				// jQuery('#minicartcontent #minicartclose').unbind("click");
			},
			add : function(form, progressImageSrc, postdata, callback) {

				// get the data of the form as serialized string
			var postdata = postdata || form.serialize();

			// get button reference
			var addButtons = []; // Form.getInputs(form, 'image', 'add');

			// the button to update
			var addButton = null;

			// disable form
			// Form.disable(form);

			// it is an array of buttons, but we need only one all
			// other combinations are strange so far
			if (addButtons.length == 1) {
				addButton = addButtons[0];
			}

			var previousImageSrc = null;

			// show progress indicator
			if (addButton != null) {
				previousImageSrc = addButton.src;
				addButton.src = progressImageSrc;
			}

			var handlerFunc = function(req) {
				// hide progress indicator
				if (addButton != null) {
					addButton.src = previousImageSrc;
				}
				//Form.enable(form);

				// bind all the events
				app.minicart.init();

				// replace the content
				jQuery('#minicart').html(req);

				// make the cart button show the cart again
				$('#hCart a.notempty').bind('click', function() {
					app.minicart.cartShow();
					return false;
				});

				if (app.minicart.suppressSlideDown
						&& app.minicart.suppressSlideDown()) {
					// do nothing
					// the hook 'MiniCart.suppressSlideDown()' should have done
					// the refresh
				} else {
					// show the item
					app.minicart.cartShow();
					if (callback)
						callback();
				}
			}

			var errFunc = function(req) {
				// hide progress indicator
				if (addButton != null) {
					addButton.src = previousImageSrc;
				}
				form.enable();
			}

			// close a product QuickView
			// if ( QuickView ) QuickView.closeQuickView();

			// cloes a previous mini cart
			jQuery('#mCart:visible').hide();

			// add the product
			jQuery.ajax( {
				type : "POST",
				//dataType: "json",
				url : app.minicart.url,
				cache : false,
				data : postdata,
				success : handlerFunc,
				error : errFunc
			});
		},

		cartShow : function() {
			jQuery('#mCart').fadeIn(300, function() {
				$('.miCont').slideDown(800);
			});

			// after a time out automatically close it
			app.minicart.timer = setTimeout('app.minicart.cartClose()', 10000);
		},

		cartClose : function() {

			app.minicart.reset(); // reset all the existing event bindings
			if (app.minicart.timer != null) {
				clearTimeout(app.minicart.timer);
				app.minicart.timer = null;
			}
			//Effect.SlideUp('minicartcontent');	
			jQuery('.miCont').slideUp(800, function() {
				$('#mCart').fadeOut(300);
			});

		},

		// hook which can be replaced by individual pages/page types (e.g. cart)
			suppressSlideDown : function() {
				return false;
			}
		},
		//Newsletter functionality
		newsletter : {

			url : null,

			timer : null,

			bindClickToNewsletterToggle : function() {
				$('a.emailSignUp').attr('href', 'javascript:void(0)').unbind(
						"click").bind("click", function() {
					$('#otherEmailBx').fadeIn('fast');
				});
				//$('#otherEmailBx input').defaultvalue('Enter email address');
				
				var valOtherEm = $('#otherEmailBx input').val();
				$('#otherEmailBx input').defaultvalue(valOtherEm);

				$('#otherEmailBx a').attr('href', 'javascript:void(0)').unbind(
						"click").bind("click", function() {
					if (typeof url != 'undefined')
						$('#otherEmailBx').load(url);
					$('#otherEmailBx').fadeOut('fast');
				});
				$('#otherEmailBx img.close').bind("click", function() {
					if (typeof url != 'undefined')
						$('#otherEmailBx').load(url);
					$('#otherEmailBx').fadeOut('fast');
				});

			},

			bindClickToSubmit : function() {

				$("#otherEmailFrm button").unbind("click").bind("click",
						function(e) {
							var form = $("#otherEmailFrm");
							app.newsletter.doSubscribe(form);
							return false;
						});

			},

			bindClickToFooterSubmit : function() {
				$("#fBarFrm button").unbind("click").bind("click", function(e) {
					var form = $("#fBarFrm");
					app.newsletter.doFooterSubscribe(form);
					return false;
				});

			},

			doSubscribe : function(form) {

				if (form == null)
					return;
				this.loading = true;
				$("#boxcontent").hide();
				$("div.loader").show();
				url = form.attr("action");
				var handlerFunc = function(req) {
					app.newsletter.updateBox(req);
				}
				jQuery.post(url, jQuery(form).serialize(), handlerFunc);

			},

			doFooterSubscribe : function(form) {

				if (form == null)
					return;
				this.loading = true;
				// $("#fBarFrmFdBk").show();

			$("div.loader").show();
			url = form.attr("action");
			var handlerFunc = function(req) {
				app.newsletter.updateFooterBox(req);
				jQuery('#fBarFrmFdBk').fadeIn(100, function() {
					$('#fBarFrmFdBk').slideDown(800);
				});
				app.newsletter.timer = setTimeout(
						'app.newsletter.footerClose()', 5000);
			}
			jQuery.post(url, {
				email : jQuery('#footeremail').val()
			}, handlerFunc);

		},

		updateFooterBox : function(req) {

			$("#fBarFrmFdBk").html(req);
		},

		updateBox : function(req) {

			$("#otherEmailBx").html(req, function() {
				$("div.loader").hide();
			});

		},

		footerClose : function() {

			if (app.newsletter.timer != null) {
				clearTimeout(app.newsletter.timer);
				app.newsletter.timer = null;
			}
			jQuery('#fBarFrmFdBk').fadeOut(100, function() {
				$('#fBarFrmFdBk').slideUp(800);
			});
			// $("#fBarFrmFdBk").hide();

		}

		},

		refreshCart : function() {
			jQuery('#QuickViewDialog').dialog('close');

			// refresh without posting
			location.href = location.href;
		},

		showQuickView : function(options) {
			//QuickViewDialog
			app.dialog( {
				id : 'QuickViewDialog',
				options : {
					height : 530,
					width : 800,
					dialogClass : 'quickview',
					title : 'Product Quickview',
					resizable : false
				}
			});

			jQuery('#QuickViewDialog').dialog('open');
			app.getProduct( {
				containerId : "QuickViewDialog",
				source : options.source,
				url : options.url
			});
		},

		dialog : function(options) {
			jQuery('#' + options.id).dialog(
					jQuery.extend( {}, app.dialogSettings, options.options));
		},

		tooltip : function(options) {
			if (options.id.charAt(0) !== '#') {
				options.id = "#" + options.id;
			}
			jQuery(options.id).tooltip(
					jQuery.extend( {}, app.tooltipSettings, options.options));
		},

		wait : function(size) {
			var imgSrc = app.URLs.loadingImg;
			if (size == 1) { // large image
			} else if (size == 2) { // small loading image
				imgSrc = app.URLs.loadingSamllImg;
			}

			return jQuery("<img/>").attr("src", imgSrc);
		},

		/*
			Opens a new window with the provided url and dimension. Used
			for Scene7 and other situations.

			@param url the url to open
			@param width the window width
			@param height the window height
		 */
		openPopup : function(url, width, height) {
			if (url != null) {
				if (width != null && height != null) {
					window.open(url, "", "width=" + width + ", height="
							+ height + ", scrollbars=no, resizable=yes");
				} else {
					window.open(url, "", "scrollbars=no, resizable=yes");
				}
			}
		},

		initializeCompareItems : function(options) {
			productCompare.initialize(options);

			jQuery('#compareItemsClear0').click( function() {
				app.removeComparedProduct( {
					index : 0
				});
			});
			jQuery('#compareItemsClear1').click( function() {
				app.removeComparedProduct( {
					index : 1
				});
			});
			jQuery('#compareItemsClear2').click( function() {
				app.removeComparedProduct( {
					index : 2
				});
			});
			jQuery('#compareItemsClear3').click( function() {
				app.removeComparedProduct( {
					index : 3
				});
			});
			jQuery('#compareItemsClear4').click( function() {
				app.removeComparedProduct( {
					index : 4
				});
			});
			jQuery('#compareItemsClear5').click( function() {
				app.removeComparedProduct( {
					index : 5
				});
			});

			// for (var i = 0; i < 6; i++) {
			// jQuery('#compareItemsClear' + i).click(function() {
			// app.removeComparedProduct({index: i});
			// });
			// }

			jQuery('#compareItemsButton').click( function() {
				window.location.href = options.openUrl;
			});

			jQuery('#clearComparedItemsButton').click( function() {
				for ( var i = productCompare.count - 1; i >= 0; i--) {
					app.removeComparedProduct( {
						index : i
					});
				}
			});

			for ( var i = 0; i < options.products.length; i++) {
				var product = options.products[i];
				var addIndex = productCompare.addProduct( {
					id : product.id,
					category : product.category
				});
				productCompare.setProductImage( {
					index : addIndex,
					src : product.imgSrc,
					alt : product.imgAlt
				});

				jQuery('#compareCheck' + product.id).each( function() {
					jQuery(this)[0].checked = true;
				});
			}

			productCompare.updateButtons();
		},

		compareProduct : function(options) {
			if (productCompare.count >= 6) {
				if (!confirm(productCompare.confirmationMessage)) {
					jQuery('#compareCheck' + options.id).each( function() {
						jQuery(this)[0].checked = false;
					});
					return;
				}

				app.removeComparedProduct( {
					index : 0
				});
			}

			var complete = function() {
				var addIndex = productCompare.addProduct(options);

				jQuery('#productThumbnail' + options.id).each( function() {
					var thumbnail = jQuery(this)[0];
					productCompare.setProductImage( {
						index : addIndex,
						src : thumbnail.src,
						alt : thumbnail.alt
					});
				});

				productCompare.updateButtons();
			};

			var uncheck = function() {
				jQuery('#compareCheck' + options.id).each( function() {
					jQuery(this)[0].checked = false;
				});
			};

			jQuery.ajax( {
				type : 'POST',
				url : productCompare.addUrl,
				data : {
					'pid' : options.id,
					'category' : options.category
				},
				dataType : 'json',
				success : function(data) {
					if (data.success === true) {
						complete();
					} else {
						uncheck();
					}
				},
				failure : function(data) {
					uncheck();
				}
			});
		},

		removeComparedProduct : function(options) {
			var index = null;
			if (options.index != null) {
				index = options.index;
			} else {
				for ( var i = 0; i < productCompare.count; i++) {
					if (productCompare.products[i].id === options.id) {
						index = i;
					}
				}
			}

			var clearedProduct = productCompare.products[index];

			var complete = function() {
				for ( var i = index; i < productCompare.count - 1; i++) {
					productCompare.products[i] = productCompare.products[i + 1];

					jQuery('#productThumbnail' + productCompare.products[i].id)
							.each(
									function() {
										var thumbnail = jQuery(this)[0];

										jQuery('#compareItemsProduct' + i)
												.each(
														function() {
															var productImage = jQuery(this)[0];
															productImage.src = thumbnail.src;
															productImage.alt = thumbnail.alt;
														});
									});
				}

				var clearedIndex = productCompare.count - 1;
				productCompare.products[clearedIndex] = null;
				productCompare.count--;

				jQuery('#compareCheck' + clearedProduct.id).each( function() {
					jQuery(this)[0].checked = false;
				});

				jQuery('#compareItemsProduct' + clearedIndex).each( function() {
					var productImage = jQuery(this)[0];
					productImage.src = productCompare.emptyImgSrc;
					productImage.alt = productCompare.emptyImgAlt;
				});

				jQuery('#compareItemsClear' + clearedIndex).hide();

				productCompare.updateButtons();
			};

			var check = function() {
				jQuery('#compareCheck' + clearedProduct.id).each( function() {
					jQuery(this)[0].checked = true;
				});
			};

			jQuery.ajax( {
				type : 'POST',
				url : productCompare.removeUrl,
				data : {
					'pid' : clearedProduct.id,
					'category' : clearedProduct.category
				},
				dataType : 'json',
				success : function(data) {
					if (data.success === true) {
						complete();
					} else {
						check();
					}
				},
				failure : function(data) {
					check();
				}
			});
		},

		printAjaxError : function(event, request, settings) {
			if (jQuery("#msgDiv") == null) {
				jQuery("<div/>").attr("id", "msgDiv").appendTo(document.body);
			}
			jQuery("#msgDiv")
					.append(
							"<li>Error requesting page " + settings.url
									+ "</li>")
					.append(
							"<a href='javascript:app.openDWLog();'> Open Log </a>");
		},

		openDWLog : function() {

			// generate the URL to load the log data
		var url = document.URL;
		var urlSegs = url.split("/");

		// check, if the demandware URL is complete
		if (urlSegs.length >= 6) {
			siteSegs = urlSegs[5].split("-");

			// check, if a valid site name is given
			if ((siteSegs.length > 0) && (siteSegs[0].length > 0)) {
				var logURL = "https://" + urlSegs[2] + "/" + urlSegs[3] + "/"
						+ urlSegs[4] + "/" + siteSegs[0]
						+ "-Site/-/ViewRequestLog-Start?LogRequestID="
						+ app.LogRequestID;

				// open the window
				var logWindow = window
						.open(logURL, "DemandwareLogView",
								"height=600,width=800,scrollbars=1,resizable=1,status=1");
				logWindow.focus();

				// clear the interval for delayed execution
				window.clearInterval(openDelayID);
			}
		}
	},

	// sub namespace app.util.* contains utility functions
		util : {
			// turns off browser autocompletion
			acOff : function(elemId) {
				jQuery("#" + elemId).attr("autocomplete", "off");
			},

			// trims a prefix from a given string, this can be used to trim
			// a certain prefix from DOM element IDs for further processing on
			// the ID
			trimPrefix : function(str, prefix) {
				return str.substring(prefix.length)
			},

			// appends the parameter with the given name and 
			// value to the given url and returns the changed url
			appendParamToURL : function(url, name, value) {
				var c = "?";
				if (url.indexOf(c) != -1) {
					c = "&";
				}
				return url + c + name + "=" + encodeURIComponent(value);
			}
		},

		// turns off browser autocompletion
		acOff : function(elemId) {
			jQuery("#" + elemId).attr("autocomplete", "off");
		},

		// activates primary category tabs
		pcatTabs : function() {
			$('div.pCatProds').tabs();
		},

		// trims a prefix from a given string, this can be used to trim
		// a certain prefix from DOM element IDs for further processing on the
		// ID
		trimPrefix : function(str, prefix) {
			return str.substring(prefix.length)
		},

		// get the ID of a business object according with respect to the convention
		// that the object ID is contained in the first child container <span
		// class="objectid"></span>
		// of the reference container with the given DOM element ID
		getObjectID : function(referenceCtnrID) {
			var objectID = jQuery("#" + referenceCtnrID + " > span.objectid")
					.text();
		}
	}
})(jQuery);

jQuery(document).ready(
		function() {

			/*
			 * Register initializations here
			 */

			jQuery("<div/>").attr("id", "msgDiv").html(" ").appendTo(
					document.body);
			jQuery("#msgDiv").ajaxError(app.printAjaxError);
			app.newsletter.bindClickToFooterSubmit();
			jQuery("<div/>").attr("id", "QuickViewDialog").html(" ").appendTo(
					document.body);

			// scan the dom for carousel components
			// jQuery(".carousel").jcarousel({vertical: true, scroll: 1});

			jQuery(document.body).append("<div id=\"dialogcontainer\"></div>");
		});

/**
 * TODO The following code is a legacy code, commenting it, and leaving it in
 * here for the time being. should be cleaned once determined it is no longer
 * needed.
 */

/*
 * Simple Image Trail script- By JavaScriptKit.com Visit
 * http://www.javascriptkit.com for this script and more This notice must stay
 * intact
 */
/*
 * var w=1 var h=1
 * 
 * function gettrailobj() { if (document.getElementById) return
 * document.getElementById("trailimageid").style else if (document.all) return
 * document.all.trailimagid.style }
 * 
 * function truebody() { return (!window.opera && document.compatMode &&
 * document.compatMode!="BackCompat")? document.documentElement : document.body }
 * 
 * function hidetrail() { document.onmousemove=""
 * gettrailobj().visibility="hidden" gettrailobj().left=-1000
 * gettrailobj().top=0 }
 * 
 * 
 * function showtrail(width,height,file) {
 * if(navigator.userAgent.toLowerCase().indexOf('opera') == -1) { w=width
 * h=height
 *  // followmouse()
 * 
 * document.getElementById('ttimg').src=file document.onmousemove=followmouse
 * gettrailobj().visibility="visible" gettrailobj().width=w+"px"
 * gettrailobj().height=h+"px"
 * 
 *  } }
 * 
 * 
 * function followmouse(e) {
 * 
 * if(navigator.userAgent.toLowerCase().indexOf('opera') == -1) {
 * 
 * var xcoord=20 var ycoord=20
 * 
 * if (typeof e != "undefined") { xcoord+=e.pageX ycoord+=e.pageY } else if
 * (typeof window.event !="undefined") {
 * xcoord+=truebody().scrollLeft+event.clientX
 * ycoord+=truebody().scrollTop+event.clientY }
 * 
 * var docwidth=document.all? truebody().scrollLeft+truebody().clientWidth :
 * pageXOffset+window.innerWidth-15 var docheight=document.all?
 * Math.max(truebody().scrollHeight, truebody().clientHeight) :
 * Math.max(document.body.offsetHeight, window.innerHeight)
 * 
 * if (xcoord+w+3>docwidth) xcoord=xcoord-w-(20*2)
 * 
 * if (ycoord-truebody().scrollTop+h>truebody().clientHeight)
 * ycoord=ycoord-h-20;
 * 
 * gettrailobj().left=xcoord+"px" gettrailobj().top=ycoord+"px"
 *  }
 *  }
 */


