var cSt = {kw:'',lc:'',ds:'',cn:'',ct:'',pg:1};
var DefaultKeywordInstances = [];
function init()
{
	if (GBrowserIsCompatible())
	{
		BigMap = new GMap2(document.getElementById("Map"));
		BigMap.setCenter(new GLatLng(48.842125,10.077381), globalZoomLevel);
		var BigMapControl = new GSmallMapControl();
		var scaleControl = new GScaleControl()
		BigMap.addControl(BigMapControl);
		BigMap.addControl(scaleControl);
	}
	var i = document.getElementById('inSFKeyword');
	if (i)
	{
		addEvent(i, "keydown", onKeywordInput);
	}
	showSimilarKeywords();
	checkPermalink();
}
function onKeywordInput(event)
{
	var timeout = 800;
	switch(event.keyCode)
	{
		case 13:
			onSearchClicked(false);
			break;
/*		case 38:
		case 40:
			event.preventDefault();
			break;*/
		default:
			clearTimeout(KeywordLoader);
			KeywordLoader = setTimeout("showSimilarKeywords()", timeout);
	}
	return true;
}

function showSimilarKeywords()
{
	var t = getElementValueById('inSFKeyword');
	var el = document.getElementById('spSFExamples');
	if (t && KeywordLoaderRequest)
	{
		var url = "/ajax/similarkeywords.json?input=" + escape(t);
		KeywordLoaderRequest.onreadystatechange = function()
		{
			if (KeywordLoaderRequest.readyState && (KeywordLoaderRequest.readyState == 4 || KeywordLoaderRequest.readyState == "complete"))
			{
				var keywords = eval("(" + KeywordLoaderRequest.responseText + ")" ).result;
				if (!keywords || keywords.length == 0)
				{
					return;
				}
				emptyNode(el); var rel = [];
				for(var i=0; i<keywords.length; i++)
				{

					var a = {
					    tag: 'a',
					    attr: {
						id:('aInstanceKeyword' + i),
						href:"javascript:addToInput(getElementValueById('aInstanceKeyword"+i+"'),'inSFKeyword');",
						title: ''
					    },
					    content: keywords[i]
					};
					rel.push(a);
					if (i+1 < keywords.length)
					{
					    rel.push(', ');
					}
				}
				if (rel.length)constructElement(el,rel);
			}
		}
		KeywordLoaderRequest.open('GET', url, true);
		KeywordLoaderRequest.send(null);
	}
	else if(DefaultKeywordInstances)
	{
		emptyNode(el);
		for(var i=0; i<DefaultKeywordInstances.length; i++)
		{
			var a = document.createElement('a');
			a.appendChild(document.createTextNode(DefaultKeywordInstances[i]));
			a.id = 'aInstanceKeyword' + i;
			a.href = "javascript:document.getElementById('inSFKeyword').value = getElementValueById('aInstanceKeyword"+i+"');void(0);";
			el.appendChild(a);
			if (i+1 < DefaultKeywordInstances.length)
			{
				el.appendChild(document.createTextNode(', '));
			}
		}
	}
}

function onSearchClicked(permalink,s)
{
	var keyword, location, distance, country, category, pagenumber;
	pagenumber=1;
	if (permalink)
	{
		keyword  = getUrlParameter('s');
		location = getUrlParameter('l');
		distance = getUrlParameter('d');
		country  = getUrlParameter('c');
		category = getUrlParameter('ct');
	}
	else if (s&&typeof s=='object')
	{
		keyword    = s.kw;
		location   = s.lc;
		distance   = s.ds;
		country    = s.cn;
		category   = s.ct;
		pagenumber = s.pg;
	}
	else
	{
		keyword  = getElementValueById('inSFKeyword');
		location = getElementValueById('inSFLocation');
		distance = getElementValueById('inSFDistance');
		country  = getElementValueById('inSFCountry');
		category = getElementValueById('inSFCategory');
	}
	if (!keyword)
	{
		alert('Please, enter search keyword!');
		return;
	}
	if (!location)
	{
		alert('Bitte geben Sie Ihre Postleitzahl ein');
		return;
	}
	if (!country) country = 'DE';
	if (!distance) distance = 100;
	setElementValueById('inSFKeyword',keyword);
	setElementValueById('inSFDistance',distance);
	setElementValueById('inSFCountry',country);
	setElementValueById('inSFLocation',location);
	setElementValueById('inSFCategory',category);
	var geocoder = new GClientGeocoder();
	geocoder.getLatLng(location + '+' + country, function(point)
						{
							if (point)
							{
								BigMap.panTo(point);
							}
						}
						)
	GetSearchResults(keyword, location, distance, country, category, pagenumber);
}
/* Functions */
function setPermalink(keyword, location, range, country, category, pagenumber)
{
	var plink = 'http://'+document.domain + "/search.html";
	plink +="?permalink=true&s=" + escape(keyword) + '&l=' + escape(location) +
		'&d=' + range  + '&c=' + escape(country) + '&p' + escape(pagenumber);
	if(category != '')
	{
		plink += '&ct=' + category;
	}
	pldiv = document.getElementById('permalink');

	var anchor = {
		tag:'a', attr:{href:plink},
		content: [
			{
				tag:'img',
				attr : {src:'/media/images/bar_icon_link.gif',align:'absmiddle',border:'0px'}
			},
			' Link to this page'
		]
	}
	emptyNode(pldiv);
	constructElement(pldiv,anchor);
}

function GetSearchResults(keyword, location, range, country, category, pagenumber)
{
	cSt.kw = keyword;
	cSt.lc = location;
	cSt.ds = range;
	cSt.cn = country;
	cSt.ct = category;
	cSt.pg = pagenumber;
	HideError();
	var listBox = document.getElementById('productList');
	clearProducts(listBox);
	hideElementById('dvWelcomeMessage');
	hideElementById('dvProductList');
	showElementById('dvLoadingThrobber');
	disableElements(document.getElementById('dvSF'));
	if(cSt.kw)
	{
	    SearchRequest = getXmlHttpObject();
	}
	if (SearchRequest == null)
	{
		alert ("Your browser does not support HTTP Request")
		disableElements(document.getElementById('dvSF'), true);
		return false;
	}
	var url = "/ajax/search.json?searchword=" + escape(keyword) + '&location=' + escape(location) +
		'&distance=' + range  + '&countryCode=' + escape(country) + '&amount=' + 10 + '&page=' + pagenumber;
	if(category != '')
	{
		url += '&categoryid=' + category;
	}
	setPermalink(keyword, location, range, country, category, pagenumber);
	SearchRequest.onreadystatechange = function()
	{
		if (SearchRequest.readyState && (SearchRequest.readyState == 4 || SearchRequest.readyState == "complete"))
		{
			hideElementById('dvLoadingThrobber');
			var ebayObj = eval("(" + SearchRequest.responseText + ")" ).result;
			var error = ebayObj.Errors;
			if (error && error.ErrorCode)
			{
				ShowError(error.LongMessage + ' (' + error.ErrorCode + ')');
				hideElementById('dvPager');
			}
			else if (ebayObj != null)
			{
				showElementById('dvProductList');
				if (ebayObj.PaginationResult.TotalNumberOfEntries == 0)
				{
					showElementById('dvNothingFound');
					hideElementById('dvPager');
				}
				else
				{
					document.getElementById('dvNothingFound').style.display = 'none';
					var ra = ebayObj.SearchResultItemArray.SearchResultItem;
					listBox.start = (cSt.pg - 1) * ebayObj.ItemsPerPage + 1;
					setElementValueById('inPageNumber', cSt.pg);
					emptyNode(listBox);
					if(!ra.length){ra=[ra];}
					for(k in ra)
					{
						var item = ra[k].Item;
						if (item && item.ItemID)
						{
							global_items["'"+item.ItemID+"'"] = item;
							if(listBox != null)
							{
								addProduct(item, listBox);
							}
							locateProduct(item, {kw:cSt.kw,lc:cSt.lc,ds:cSt.ds,cn:cSt.cs,ct:cSt.ct,pg:cSt.pg});
						}
					}
					showElementById('dvPager');
					var pp = createAdvancedPager(ebayObj.PaginationResult.TotalNumberOfPages, cSt.pg,'GehezuSeite');
//					pp.className='pagerList';
					emptyNode(document.getElementById('dvPager'));
					document.getElementById('dvPager').appendChild(pp);
				}
			}
			disableElements(document.getElementById('dvSF'), true);
		}
	}
	SearchRequest.open("GET", url, true);
	SearchRequest.send(null);
}
function GehezuSeite(n)
{
	n=n?n:1;GetSearchResults(cSt.kw, cSt.lc, cSt.ds, cSt.cn, cSt.ct, n);
}
function locateProduct(item, s)
{
	var countries = {DE: 'Germany'};
	SetProductState(item, 'Load');
	var req2 = getXmlHttpObject();
	if (req2)
	{
		var url2 = "/ajax/item.json?itemid=" + item.ItemID;
		req2.onreadystatechange = function()
		{
			if (req2.readyState && (req2.readyState == 4 || req2.readyState == 'complete'))
			{
				var itemObj = eval('('+req2.responseText+')').result;
				var itemdetails = itemObj.Item;
				if (itemdetails == null)
				{
					SetProductState(item, 'Fail');
					return;
				}
				var country = itemdetails.Country;
				var zip = itemdetails.PostalCode;
				var location = itemdetails.Location;
				var geoquery = '';
				if (zip && country)
				{
					geoquery = zip + '+' + countries[country];
				}
				else if (country)
				{
					geoquery = location + '+' + countries[country];
				}
				else
				{
					geoquery = location;
				}
				if (BigMap != null)
				{
					var geocoder = new GClientGeocoder(null);
					geocoder.getLocations(geoquery, function(response)
					{
						if (!response || response.Status.code != 200)
						{
							SetProductState(item, 'Fail');
						}
						else
						{
							var place = response.Placemark[0];

							if(place.AddressDetails.Country.CountryNameCode != country)
							{
								SetProductState(item, 'Fail');
							}
							else
							{
								var point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);
								item.Coords = point;
								var marker = new GMarker(point);
								var info = constructInfo(itemdetails);
								global_infos["'"+item.ItemID+"'"] = info;
								GEvent.addListener(marker, "click", function()
										{
											marker.openInfoWindowHtml(info.innerHTML);
										});
								global_markers["'" + item.ItemID + "'"] = marker;
								if(s.kw==cSt.kw&&s.pg==cSt.pg)//&&s.lc==cSt.lc&&s.ds==cSt.ds&&s.cn==cSt.cn&&s.ct==cSt.st)
								{
									BigMap.addOverlay(marker);
								}
								SetProductState(item, 'Ok');

							}
						}
					});
				}
			}
			else{return;}
		}
		req2.open('GET', url2, true);
		req2.send(null);
	}
}
function constructInfo(item)
{
	if (global_infos["'" +item.ItemID + "'"])
	{
		return global_infos["'" +item.ItemID + "'"];
	}
        var b = '';
	if (item.ListingDetails.BuyItNowAvailable || item.ListingType == 'FixedPriceItem' || item.ListingType =='StoresFixedPrice' || item.BuyItNowPrice.content  > 0)
	{
            b = {
                tag:'a',attr:{href:item.ListingDetails.ViewItemURL,className:'buyNow',target:'_blank'},
                content : {
                    tag:'span',attr:{className:'productBuyNow'},
                    content : [
                        {
                            tag:'img',
                            attr:{src:'http://pics.ebaystatic.com/aw/pics/de/bin_15x54.gif',align:'absmiddle',className:'buyNowImage'}
                        },
                        (item.BuyItNowPrice.content>0)?[{tag : 'br'},item.BuyItNowPrice.content+" "+item.Currency]:''
                    ]
                }
            };
        }
        var s = {
        tag:'div',
        content:{
            tag:'table',attr:{className:'productInfoBox'},
            content:[
                {
                    tag:'tr',attr:{},
                    content:[
                        {
                            tag:'td',attr:{rowSpan:3},
                            content: {
                                tag:'a',attr:{href:item.ListingDetails.ViewItemURL,target:'_blank'},
                                content : {
                                    tag:'img',
                                    attr:{src:item.PictureDetails.PictureURL,align:'absmiddle',className:'productImage'}
                                }
                            }
                        },
                        {
                            tag:'td',attr:{colSpan:2},
                            content:{
                                tag:'span',attr:{className:'productTitle'},
                                content:{
                                    tag:'a',attr:{href:item.ListingDetails.ViewItemURL,target:'_blank'},
                                    content:item.Title
                                }
                            }
                        }
                    ]
                },
                {
                    tag:'tr',attr:{},
                    content:[
                        {
                            tag:'td',attr:{},
                            content:[
                                'Preis: ',
                                {
                                    tag:'span',attr:{className:'productPrice'},
                                    content:{
                                        tag:'a',attr:{href:item.ListingDetails.ViewItemURL,target:'_blank'},
                                        content:item.SellingStatus.CurrentPrice.content+' '+item.Currency+' inkl. Mwst.'
                                    }
                                }
                            ]
                        },
                        {
                            tag:'td',attr:{},
                            content:b
                        }
                    ]
                },
                {
                    tag:'tr',attr:{},
                    content:[
                        {
                            tag:'td',attr:{},
                            content:[
                                'Ende Zeit: ',
                                {
                                    tag:'span',attr:{className: 'productEndTime'},
                                    content:item.ListingDetails.EndTime
                                }
                            ]
                        },
                        {
                            tag:'td',attr:{},
                            content : [
                                'Gebote: ',
                                {
                                    tag:'span',attr:{className : 'productBids'},
                                    content:item.SellingStatus.BidCount
                                }
                            ]
                        }
                    ]
                }
            ]
        }
        };
        var box = createElementByTemplate(s);
	var dv = document.createElement('div');
	dv.appendChild(box);
	return dv;
}

function addProduct(item, parent)
{
	var a = {
		tag : 'li',
		attr: {
			id: 'liSRListItem' + item.ItemID,
			originalClassName: 'liSRListItem',
			className: 'liSRListItem'
		},
		content: [
		{
			tag: 'a',
			attr : {
				href : "javascript:void(0);",
				className: 'liSRListItemLink'
			},
			content: item.Title
		},
		" ",
		{
			tag: 'a',
			attr : {
				href : item.ListingDetails.ViewItemURL,
				target: '_blank',
				title: 'Link to eBay'
			},
			content:
			{
				tag: 'img',
				attr : {
					src : '/media/images/ext_link_anim.gif',
					align : 'absmiddle',
					border: '0px',
					alt: 'Link to eBay'
				}
			}
		}
		],
		event:{'mouseover' : "if (this.style) this.style.className = 'liSRListItem_hovered';",
				'mouseout' : "if (this.style) this.style.className = 'liSRListItem';"}
	}
	constructElement(parent,a);
}
function SetProductState(item, state)
{
	var e = document.getElementById('liSRListItem' + item.ItemID);
	if (e && e.originalClassName)
	{
		e.className = e.originalClassName + state;
		if (state == 'Ok')
		{
			var info = global_infos["'" +item.ItemID +"'"].innerHTML;
			var l = getElementsByClass('liSRListItemLink', e, 'a')[0];
			if (l)
			{
				l.href = "javascript:expandProduct('"+item.ItemID+"');";
				addEvent(l,'mouseover',function(){
				    return coolTip(info, FULLHTML, DELAY, 500, NOANCHORWARN, 1, STICKY, ANCHOR, 'liSRListItem'+item.ItemID, ANCHORALIGN, 'ur','ul', TIMEOUT, 5000, FADEIN);
				});
				addEvent(l,'mouseout',"nd();");
			}
		}
	}
}
