//inlcuding js plugins to simplify things
//convert durationin ISO 8601 (PnYnMnDTnHnMnS) to Hours,Minutes,Seconds
jQuery.convertISO8601 = function(t) {
	var ISO8601re = new RegExp(/P(\d*Y*)(\d*M*)(\d*D*)T(\d*H*)(\d*M*)(\d*S*)/),
	time = ISO8601re.exec(t), re, S, M, H;
	time.shift();
	time = time.join('');
	re = new RegExp(/(\d*)S/);
	S = (new RegExp(/(\d*)S/)).exec(time);
	M = (new RegExp(/(\d*)M/)).exec(time);
	H = (new RegExp(/(\d*)H/)).exec(time);
	return {'H':H?H[1]:false,'M':M?M[1]:false,'S':S?S[1]:false}
}
jQuery.supplant = function(o,p) {
	return o.replace(/{([^{}]*)}/g,
		function (a, b) {
			var r = p[b];
			return typeof r === 'string' || typeof r === 'number' ? r : a;
		}
	);
}
//eduebaysearch
window.console = window.console || { 'log': function(){}};
(function($){
	var eBayAPI = {		
		buildApiRequest: function(params,opts){
			var defaults = { 
				'SHOPPING_BASE_URL': 'http://open.api.ebay.com/shopping?',
				'APPID': 'AuctivaC-3fad-47aa-98f0-4f6dc9d1d020',
				'VERSION': '539',
				'RET': 'JSON'
			};
			
			var p = $.extend({}, defaults, opts);
			var api_url = p['SHOPPING_BASE_URL']+
			"appid="+p['APPID']+
			"&version="+p['VERSION']+
			"&responseencoding="+p['RET'];
			for(n in params){
				if (params.hasOwnProperty(n)) {
					api_url += "&"+n.replace(/__/g,'-')+"="+(params[n]);
				}
			}
			return api_url;
		},		
		getSingleItem: function(i,p){
			if(!i){return;}
			p = p || {};
			p.callname = 'GetSingleItem';
			p.ItemID=i;
			p.callback=true;
			p.callbackname='_cb_BuyShield_GetSingleItem';
			return gsi = this.buildApiRequest(p);
		},
		findByQuery: function(q,p){
			if(!q){return;}
			p = p || {};
			p.callname = 'FindItemsAdvanced';
			p.QueryKeywords = q.replace(/\s/g,'+');
			return fia = this.buildApiRequest(p);
		},
		getPopularItems: function(q,p){
			if(!q){return;}
			p = p || {};
			p.QueryKeywords=q.replace(/\s/g,'+');
			p.callname = 'FindPopularItems';
			return gsi = this.buildApiRequest(p);
		}
	},
	ebg = {
		"maxEntries":10,
		"pagenumStore":1,
		'listView':'<li id="a_{ItemID}" class="sr{Zebra}" style="padding-top:5px;border-top:1px dashed #ccc;margin-left:0;padding-left:10px;"><table style="font-size:11px;"><tr><td colspan="2"><img src="{GalleryURL}" height="40" alt="" style="float:left;margin-right:5px;" /><span style="color:#1549AF;">{Title}</span></td></tr><tr><td><strong>{buynowimg} Price: \${supConvertedCurrentPrice} </strong></td><td style="text-align:right;">Ending: <span class="timeleft" style="color:red;">{endtime}</span></td></tr></table></li>',
		'listViewCss':{
			'list-style-type':'none',
			'cursor':'pointer',
			'font-size':'11px',
			'font-family':'trebuchet ms,helvetica,arial'
		},
		'trackurl':'http://rover.ebay.com/rover/1/711-53200-19255-0/1?type=2&campid=5336160947&toolid=10001&customid=&ext=250321732666&item='
	};
	
	$('a.searchebay').each(function(i,s){
		//var q = s.rel.split(',');
		$(s).hover(function(e){
			//console.log('over link '+e.pageX +', '+ e.pageY);
			//console.log(eBayAPI.findByQuery(s.rel,{"MaxEntries":ebg.maxEntries,"PageNumber":ebg.pagenumStore,'ItemSort':'EndTime'}));
			$('#ebaysearchresults').css({'top':(e.pageY-150)+'px','left':(e.pageX+20)+'px'}).fadeIn();
			//$.getScript(eBayAPI.findByQuery(s.rel,{"MaxEntries":ebg.maxEntries,"PageNumber":ebg.pagenumStore,'ItemSort':'EndTime'})+"&callback=true");
			$.getScript(eBayAPI.getPopularItems(s.rel,{'MaxEntries':'10'})+"&callback=true&callbackname=_cb_popularSearches");
		},function(){
			//console.log('off link');
		});
	});
	//create the container for the eBay search results
	var css = {
		'overflow':'hidden',
		'position':'absolute',
		'display':'none',
		'top':0,
		'left':0,
		'background-color':'transparent',
		'border':'0'
	}
	$('<div>').appendTo('body').attr('id','ebaysearchresults').css(css).append('<table border="0" cellpadding="0" cellspacing="0" style="height:300px;"><tr><td></td><td><img src="imgs/close.gif" alt="Close" id="srclose" style="float:right;cursor:pointer;" /><h1 id="searchresultsheader" style="font-size:11px;height:18px;background-color:#000;color:#fff;padding-left:10px;cursor:move;font-weight:bold;line-height:18px;">Right Now on eBay</h1></td><td></td></tr><tr><td></td><td style="background-color:#efefef;border:1px solid #666;"><div id="searchresultswrapper"></div></td><td class="srshadowr" style="background:transparent url(../images/edusearch/srshadowr.png) 0 0 no-repeat;"></td></tr><tr><td></td><td class="srshadowbot" style="background:transparent url(../images/edusearch/srshadowbot.png) 0 0 no-repeat"></td><td class="srshadowbotr" style="width:9px;height:9px;background:transparent url(../images/edusearch/srshadowbotr.png) 0 0 no-repeat;"></td></tr></table>').draggable({'handle':'#searchresultsheader'});
	$('#searchresultswrapper').css({'display':'block','width':'250px','height':'300px','overflow':'auto'}).append($('<ul>').css(ebg.listViewCss).bind('click',function(e){
		e = $(e.target).is('li')?$(e.target):$(e.target).parents('li');
		window.location.href = ebg.trackurl+(e.attr('id').substring(2));
	}));
	$('#srclose').click(function(){
		$('#ebaysearchresults').fadeOut().find('ul').find('li').unbind().end().empty();
	});
	
	_cb_FindItemsAdvanced = function(json){
		//console.log(json);
		if(json.TotalItems>0){
			$('#ebaysearchresults').children('ul').empty();
			var items = json.SearchResult[0].ItemArray.Item;
				$.each(items,function(i,t){
				//console.log(t);
				t.supConvertedBuyItNowPrice = t.BuyItNowAvailable?t.ConvertedBuyItNowPrice.Value:'';
				t.supConvertedCurrentPrice = t.ConvertedCurrentPrice.Value;
				var m = $.convertISO8601(t.TimeLeft);
				m.endtime = (m.D?(m.D+'d '):'') + (m.H?(m.H + 'h '):'') + (m.M?(m.M + 'm '):'') + (m.S?(m.S + 's'):'');
				t.Zebra = (i%2==0?' odd':'');
				t.endtime = m.endtime;
				t.buynowimg = (t.BuyItNowAvailable?'<img style="width:45px;height:13px;margin-right:3px;" src="imgs/bin.gif" alt="" /> $'+t.supConvertedBuyItNowPrice:'');
				$('#searchresultswrapper').children('ul').append($.supplant(ebg.listView,t));
			});
			$('#searchresultswrapper ul li').hover(function(){$(this).css('background-color','#ffc');},function(){$(this).css('background-color','#efefef');});
		}
	}
	
	_cb_popularSearches = function(json){
		$('#searchresultswrapper').children('ul').empty().fadeIn();
		if(json && json.ItemArray){
			//$('#searchresultswrapper').children('ul').empty().fadeIn();
			var items = json.ItemArray.Item;
				$.each(items,function(i,t){
				//console.log(t);
				t.supConvertedBuyItNowPrice = t.BuyItNowAvailable?t.ConvertedBuyItNowPrice.Value:'';
				t.supConvertedCurrentPrice = t.ConvertedCurrentPrice.Value;
				var m = $.convertISO8601(t.TimeLeft);
				m.endtime = (m.D?(m.D+'d '):'') + (m.H?(m.H + 'h '):'') + (m.M?(m.M + 'm '):'') + (m.S?(m.S + 's'):'');
				t.Zebra = (i%2==0?' odd':'');
				t.endtime = m.endtime;
				t.buynowimg = (t.BuyItNowAvailable?'<img style="width:45px;height:13px;margin-right:3px;" src="imgs/bin.gif" alt="" /> $'+t.supConvertedBuyItNowPrice:'');
				$('#searchresultswrapper').children('ul').append($.supplant(ebg.listView,t));
			
			});
			$('#searchresultswrapper ul li').hover(function(){$(this).css('background-color','#ffc');},function(){$(this).css('background-color','#efefef');});
		}
	}
	
	
})(jQuery);
var _cb_FindItemsAdvanced,_cb_popularSearches;