var SLQuery = {};

SLQuery.init = function(){

	this.state = 'START';
	
	var sl = document.createElement('div');
	sl.id='stats';
	controller.main.appendChild(sl);
	var flashvars = {};
	var params = {wmode:'transparent'};
	var attributes = {
		id: "ShopStats",
		name: "ShopStats"
	};
	swfobject.embedSWF("ShopStats1.6.swf", "stats", "725", "900", "10.0.0","expressInstall.swf", flashvars, params, attributes,SLQuery.loaded);
	
};

SLQuery.loaded = function(e){
	supA.print();
};



SLQuery.getMonthViews = function(startDate,endDate){
	
	if (userInfo.state != userInfo.SUCCESS){
			swfobject.getObjectById("ShopStats").setMonthViews(0,0,0);
			return;
	}	

	var q = new GAQuery();
	q.setOptions(['dimensions=ga:date','sort=ga:date','metrics=ga:visits,ga:pageviews','max-results=10000','start-date=' + startDate,'end-date=' + endDate]);
	q.callback = SLQuery.monthViewsCallback;
	q.errorHandler = SLQuery.monthViewsError;
	q.query();
};

SLQuery.findAllShopHearts = function(status){
	if (status == 'START'){
		this.heartOffset = 0;
		if (userInfo.state != userInfo.SUCCESS){
			swfobject.getObjectById("ShopStats").setShopHearts('',0,0);
			return;
		}	
	}
	
	var q = new EQuery('/users/' + userInfo.getUserId() + '/favored-by',{entry:'either',includes:['User(login_name)/Profile(avatar_id)'],params:{limit:100,offset:this.heartOffset},callbackStr: 'SLQuery.findAllShopHeartsCallback'});
	q.query();
};

SLQuery.findAllShopHeartsCallback = function(response){
	var obj = swfobject.getObjectById("ShopStats");
	
	if (!response.ok){
		alert("Got an error findAllShopHeartsCallback: " + response.error);
		return;
	}
	
	var results = response.results;
	
	for (var i = 0; i < results.length; i++){
		var c = results[i].creation_tsz;
		var l = (results[i].User && results[i].User.login_name)?results[i].User.login_name:'Secret Admirer';
		var a = (results[i].User && results[i].User.Profile && results[i].User.Profile.avatar_id)?results[i].User.Profile.avatar_id:0;
		obj.setShopHearts(l,a,c);
		}
	
	this.heartOffset += results.length;
	
	if (this.heartOffset >= response.count){
		obj.setShopHearts('',0,0);
	}
	else {
		obj.setShopHearts('-',0,0);
	}
	
};

SLQuery.findAllShopListingsActive = function(status){
	if (status == 'START'){
		this.listingOffset = 0;
		if (userInfo.state != userInfo.SUCCESS){
			swfobject.getObjectById("ShopStats").setAllListings(0,0,'',0);
			return;
		}	
	}
	
	var q = new EQuery('/shops/' + userInfo.getUserName() + '/listings/active',{entry:'either',includes:['Images(url_75x75):1:0'],params:{limit:100,offset:this.listingOffset,fields:'listing_id,title,ending_tsz',sort_on:'created',sort_order:'down'},callbackStr:'SLQuery.findAllShopListingsActiveCallback'});
	q.query();
};

SLQuery.listingsFavoredByCallback = function(response){
	var obj = swfobject.getObjectById("ShopStats");
	
	if (!response.ok){
		alert("listingsFavoredByCallback: " + response.error);
		obj.setAllListings(0,'','',0);
		return;
	}
	
	var favs = response.results;
	var listingId = response.params.listing_id;
	
		if (favs){
			for (var j = 0; j < favs.length; j++){
				var c = favs[j].create_date;
				var l = (favs[j].User && favs[j].User.login_name)?favs[j].User.login_name:'Secret Admirer';
				var a = (favs[j].User && favs[j].User.Profile && favs[j].User.Profile.avatar_id)?favs[j].User.Profile.avatar_id:0;
				//alert("" + listingId + " " + l + " " + a + " " + c);
				obj.setAllListingsFavorite(listingId,l,a,c);
			}
		}
		
		
		if (listingId == SLQuery.lastId){
			obj.setAllListings(0,'','',0);
		}
	
}

_.rateLimit = function(func, rate, async) {
  var queue = [];
  var timeOutRef = false;
  var currentlyEmptyingQueue = false;
  
  var emptyQueue = function() {
    if (queue.length) {
      currentlyEmptyingQueue = true;
      _.delay(function() {
        if (async) {
          _.defer(function() { queue.shift().call(); });
        } else {
          queue.shift().call();
        }
        emptyQueue();
      }, rate);
    } else {
      currentlyEmptyingQueue = false;
    }
  };
  
  return function() {
    var args = _.map(arguments, function(e) { return e; }); // get arguments into an array
    queue.push( _.bind.apply(this, [func, this].concat(args)) ); // call apply so that we can pass in arguments as parameters as opposed to an array
    if (!currentlyEmptyingQueue) { emptyQueue(); }
  };
};

SLQuery.findFavs = function(listingId){
	var q = new EQuery('/listings/' + listingId + '/favored-by',{entry:
		'public',includes:['User(login_name)/Profile(avatar_id)'],params:{limit:100,offset:0,fields:'listing_id,create_date'},callbackStr:'SLQuery.listingsFavoredByCallback'});
		q.query();
}

var findFavsRateLimited = _.rateLimit(SLQuery.findFavs,100,false);


SLQuery.findAllShopListingsActiveCallback = function(response){
	var obj = swfobject.getObjectById("ShopStats");
	
	if (!response.ok){
		alert("Got an error findAllShopListingsActiveCallback: " + response.error);
		obj.setAllListings(0,'','',0);
		return;
	}
	
	var results = response.results;
	
	this.listingOffset += results.length;
	
	if (this.listingOffset >= response.count){
		this.lastId = results[results.length-1].listing_id;
	}
	
	for (var i = 0; i < results.length; i++){
		var listingId = results[i].listing_id;
		
		if (!results[i].Images || !results[i].Images[0]){
			continue;
		}
		
		obj.setAllListings(listingId,results[i].Images[0].url_75x75,results[i].title,results[i].ending_tsz + 86400);
		
		//SLQuery.findFavs(listingId);
		findFavsRateLimited(listingId);
		
	}
	
	if (this.listingOffset >= response.count){
		return;
	}
	
	this.findAllShopListingsActive('GO');

};

SLQuery.getMonthSales = function(year,month){
	
	var month2 = month + 1;
	var year2 = year;
	if (month2 == 12){
		month2 = 0;
		year2++;
	}
	
	this.startDate = new Date(year,month,1) / 1000;
	this.endDate = new Date(year2,month2,1) / 1000;
	
	this.getAllShopTransactions();
};


SLQuery.getAllShopTransactions = function(){
	if (userInfo.state != userInfo.SUCCESS){
			swfobject.getObjectById("ShopStats").setMonthSales(0,'',0,'','','',0,0);
			return;
	}	

	if (this.state == 'START'){
		this.trans = [];
	}
	
	if (this.state == 'START' || this.state == 'GO'){
		this.getShopTransactions();
	}
	
	if (this.state == 'END'){
	
		var obj = swfobject.getObjectById("ShopStats");
		
		for (var i = 0; i < this.trans.length; i++){
			
			if (this.trans[i].creation_tsz >= this.endDate)
				continue;
			
			if (this.trans[i].creation_tsz  < this.startDate)
				break;

		
			
			var l = (this.trans[i].Buyer && this.trans[i].Buyer.login_name)?this.trans[i].Buyer.login_name:'Deleted User';
			var a = (this.trans[i].Buyer && this.trans[i].Buyer.Profile && this.trans[i].Buyer.Profile.avatar_id)?this.trans[i].Buyer.Profile.avatar_id:0;
			
			obj.setMonthSales(new Date(this.trans[i].creation_tsz * 1000).getDate(),this.trans[i].price * this.trans[i].quantity,this.trans[i].listing_id,'http://ny-image0.etsy.com/il_75x75.' + this.trans[i].image_listing_id + '.jpg',this.trans[i].title, l, a, this.trans[i].creation_tsz);
		
		}
		
		
		obj.setMonthSales(0,'',0,'','','',0,0);
		
		
	}
	

};

SLQuery.renewListing = function(id){
	var q = new EQuery('/listings/',{input:id,params:{renew:'true',method:'PUT'},entry:'private',callbackStr:'SLQuery.renewListingCallback'});
	q.query();
	
}

SLQuery.renewListingCallback = function(response){
	if (!response.ok){
		alert("Got an error renewListingCallback: " + response.error);
		return;
	}
	
	var obj = swfobject.getObjectById("ShopStats");
	var results = response.results;
	
	for (var i = 0; i < results.length; i++){
		obj.confirmRenew(results[i].listing_id,results[i].ending_tsz + 86400);
	}
}


SLQuery.getShopTransactions = function(){
	var q = new EQuery('/shops/' + userInfo.getUserName() + '/transactions',{includes:['Buyer(login_name)/Profile(avatar_id)'],params:{limit:100,offset:this.trans.length,fields:'creation_tsz,price,quantity,listing_id,image_listing_id,title'},entry:'private',callbackStr:'SLQuery.shopTransactionsCallback'});
	q.query();
	

};

SLQuery.shopTransactionsCallback = function(response){
	if (!response.ok){
		alert("Got an error shopTransactionsCallback: " + response.error);
		return;
	}
	
	var results = response.results;
	
	for (var i = 0; i < results.length; i++){
		this.trans.push(results[i]);
	}
	
	if (this.trans.length >= response.count){
		this.state = 'END';
	}
	else {
		this.state = 'GO';
	}
		
	this.getAllShopTransactions();

};

SLQuery.monthViewsCallback = function(result){
	var entries = result.feed.getEntries();
	var obj = swfobject.getObjectById("ShopStats");
	for (var i = 0; i < entries.length; i++){
		obj.setMonthViews(i+1,entries[i].getValueOf('ga:visits'),entries[i].getValueOf('ga:pageviews'));
	}
	obj.setMonthViews(0,0,0);
 };
 
SLQuery.monthViewsError = function(e){
	var obj = swfobject.getObjectById("ShopStats");
	obj.setMonthViews(0,0,0);
	etsyGoogle.handleError(e);
};
 
 SLQuery.getDayViews = function(date){
	if (userInfo.state != userInfo.SUCCESS){
		swfobject.getObjectById("ShopStats").setDayViews(0,0);
		return;
	}	
	
	var q = new GAQuery();
	q.setOptions(['dimensions=ga:pagePath','filters=ga:pagePath=@listing','metrics=ga:pageviews','max-results=10000','start-date=' + date,'end-date=' + date]);
	q.callback = SLQuery.dayViewsCallback;
	q.errorHandler = SLQuery.dayViewsError;
	q.query();
};

 SLQuery.getItemId = function(url){
	var pos = url.indexOf('listing/');
	var start,end;
	if (pos != -1)
	{
		start = pos+8;
		end = url.indexOf('/',start);
		if (end == -1) end = url.length;
		return url.substring(start,end);
	}
	else {
		pos = url.indexOf('listing_id=')
			if (pos != -1){
				start = pos+11;
				end = url.indexOf('&',start);
				if (end == -1) end = url.length;
				return url.substring(start,end);
		}
	
	}

	return '';
 };

SLQuery.dayViewsCallback = function(result){	
	var entries = result.feed.getEntries();
	var obj = swfobject.getObjectById("ShopStats");
	var listings = {};
	for (var i = 0; i < entries.length; i++){
		var id = SLQuery.getItemId(entries[i].getValueOf('ga:pagePath'));
		if (!listings[id]) listings[id] = 0;
		listings[id] += entries[i].getValueOf('ga:pageviews');
	}

	for (var x in listings){
		obj.setDayViews(x,listings[x]);
	}
	
	obj.setDayViews(0,0);
};

SLQuery.dayViewsError = function(e){
	var obj = swfobject.getObjectById("ShopStats");
	obj.setDayViews(0,0);
	etsyGoogle.handleError(e);
};


