var gMap = null;
var gMap_defaultZoomLevel = 5;
var gMap_centered = false;
var gMap_markers = {};
var page_init = function()
{
    if (GBrowserIsCompatible()) {
        gMap = new GMap2(document.getElementById("google-map"));
        var scaleControl = new GSmallZoomControl();
        gMap.addControl(scaleControl);
        gMap.setCenter(new GLatLng(50.48, 12.29), gMap_defaultZoomLevel);
    }
    for (var i in global_items_set){setItemInfo(global_items_set[i]);}
    for (var i in global_items_get){getItemInfo(global_items_get[i].id, global_items_get[i].word, global_items_get[i].engine);}
}
window.addEvent('domready', page_init);
function getSearchword()
{
    return searchword;
}
function getEngineId()
{
    var engine = $('sfEngine');
    if (engine && engine.selectedIndex) {
        return engine.options[engine.selectedIndex].value;
    } else {
        return 77;
    }
}
var countries = {
    DE : 'Germany',
    CH : 'China',
    US : 'USA',
    FR : 'France',
    ES : 'Spain'
};
function markOnMap(item_id, country, zip, location) {
    if (gMap != null) {
        var geoquery = '';
        var country_name = countries[country] ? countries[country] : '';
        if(zip&&country){geoquery=zip+'+'+country_name;}
        else if(country){geoquery=location+'+'+country_name;}
        else if(zip&&location){geoquery=zip+'+'+location;}
        else{geoquery=location}
        var geocoder = new GClientGeocoder(null);
        geocoder.getLocations(geoquery, function(response) {
            if(response&&response.Status.code==200) {
                var place = response.Placemark[0];
//                if(place.AddressDetails.Country.CountryNameCode==country){
                if(1) {
                    var point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0])
                    var marker = new GMarker(point);
                    var link = $('Link_' + item_id);
                    if (link)
                        GEvent.addListener(marker, "click", function() {
                            window.open(link.href);
                            });
                    gMap.addOverlay(marker);
                    if(gMap_centered == false) {
                        gMap_centered = true;
                        gMap.panTo(point);
                    }
                    gMap_markers[item_id] = marker;
                    var t = document.getElementById('locate-on-map-'+item_id);
                    if(t) {
                        t.style.display = 'block';
                    }
                }
            }
        })
    }

}
function locateOnMap(item_id) {
    if(gMap != null && gMap_markers[item_id]) {
        gMap.panTo(gMap_markers[item_id].getLatLng());
    }
}
function setItemPopup(id, url) {
    if(url) {ctPopups[id] = '<' + 'img src="'+url+'" />'}
}
function resizeImage(image) {
    var W = 90;
    var H = 90;
    if (!image||!image.width||!image.height){return false}
    if (image.width > image.height) {H = parseInt(image.height*W/image.width)}
    else {W = parseInt(image.width*H/image.height)}
//    alert('Before: ' + image.width + 'x' + image.height + ', After: ' + W + 'x' + H);
    image.width = W;
    image.height = H;
    return true;
}

function getItemInfo(id,wrd, eid) {
    var engine_id = eid
    if (!engine_id) engine_id = getEngineId();
    var ItemRequest = new Request.JSON({
        url: '/ajax/item/' + engine_id + '-' + id +'/get.ajax',
        method: 'get',
        onSuccess: getItemInfoHandler
    }).get();
}

function setItemInfo(hash) {
    markOnMap(hash['EbayID'], hash['CountryCode']?hash['CountryCode']:'', hash['PostalCode']?hash['PostalCode']:'', hash['Location']?hash['Location']:'');
    var src="";
    if (hash['PictureURL']) {src = hash['PictureURL']}
    else if (hash['GalleryURL']) {src = hash['GalleryURL']}
    if(src) {
        setItemPopup(hash['EbayID'], src);
        resizeImage(document.getElementById('image_'+hash['EbayID']));
    }
}

function getItemInfoHandler(hash) {
    if (hash) {
	    if (hash['Bids']) {
	        var bids = $('Bids_'+hash['EbayID']);
	        bids.set('html',hash['Bids']);
	    }
        if (hash['Seller']) {
            var sll = $('Seller_'+hash['EbayID']);
            var sinfo = new Element('a');
            sinfo.href = hash['Seller']['URL']
            sinfo.target = '_blank'
            sinfo.set('html','<strong>'+hash['Seller']['Name'] + '</strong> ('+hash['Seller']['Rating']+')');
            sll.appendChild(sinfo)
        }
        if (hash['CategoryString'] && hash['CategoryID']) {
            var cat = $('Category_'+hash['EbayID']);
            var cn = new Element('span');
            cn.set('html',hash['CategoryString']);
            if (hash['CategoryURL'])
            {
                acn = new Element('a');
                acn.href = hash['CategoryURL'];
                acn.target = '_blank';
                acn.appendChild(cn);
                cn=acn;
            }
            cat.appendChild(cn);
        }
        var img = $('image_'+hash['EbayID']);
        if (img && hash['PictureURL']) {
            img.src = hash['PictureURL'];
            setItemPopup(hash['EbayID'], hash['PictureURL']);
        }
        setItemInfo(hash);
    }
}
function getCatStat()
{
    var req_id = $("request_url").value
    var r = new Ajax('/ajax/catstat/request'+ '-' + req_id + '/get.ajax',{
            onSuccess:getCatStatHandler
        }
    );
    r.request();
}

function getCatStatHandler(resp)
{
    //alert (resp.responseText);
    var catlist = Json.evaluate(resp.responseText);
    var parent = $("catStatContent");
    if (parent)
    {
        var header = parent.firstChild;
        var ul = new Element('ul', {
            className:"list_no_bullets"
        });
        for (var i = 0; i < catlist.length; i++)
        {
            var c = catlist[i];
            var ttl = "Suche &raquo;"+getSearchword()+"&laquo; in "+c['Name']+" auf eBay";
            var url = "?sfCategory=" + c['id']
            var a = new Element('a', {
                href: url,
                title:ttl,
                target:'_blank'
            });
            a.setHTML = c['Name']; 
            var li = new Element('li', {});
            li.appendChild(a);
            li.appendText(" ("+c.NumOfItems+")");
            li.appendChild(new Element('br'));
            for (var j = 0; j < c['Children'].length; j++)
            {
                cc = c['Children'][j];
                var ttl = "Suche &raquo;"+getSearchword()+"&laquo; in "+cc['Name']+" auf eBay";
                var curl = "?sfCategory=" + cc['id']
                var a = new Element('a', {
                    href: curl,
                    target:'_blank'
                });
                a.set('html',cc['Name']);
                var sp = new Element('span', {
                    className:'CategoryChild'
                },[a,, Builder.node('br')]);
                sp.appendChild(a);
                sp.appendText(" ("+cc.NumOfItems+")");
                sp.appendChild(new Element('br'));
                li.appendChild(sp);
            }
            ul.appendChild(li);
        }
        parent.appendChild(ul);
    }
}
