

var etsyOauth = {}

function Account(id,accessToken,accessTokenSecret){
	this.id = id;
	this.accessToken = accessToken;
	this.accessTokenSecret = accessTokenSecret;
}
 
etsyOauth.init = function(){
	this.params = {};
	this.accounts = [];               
	this.currentAccount = null;
	this.deserializeAccounts();
}
	
etsyOauth.backFromEtsyLogin = function() {
	var p = controller.params;
	if (p.secretToken && p.oauth_token && p.oauth_verifier){
		this.params.secretToken = p.secretToken;
		this.params.token = p.oauth_token;
		var c = new AjaxConnection('accessToken.php');
		c.setOptions(['token=' + p.oauth_token,'secretToken='+ p.secretToken,'verifier='+ p.oauth_verifier]);
		c.connect(this.accessTokenCallback);
	} 
}

etsyOauth.cs = 'HXgMfdp99P';

etsyOauth.isLogin = function(){
	return this.currentAccount && this.currentAccount.id == userInfo.getUserId();
}

etsyOauth.setSelect = function (){
	var userId = userInfo.getUserId();
	
	for (var i = 0; i < this.accounts.length; i++){
		if (userId == this.accounts[i].id){
			this.currentAccount = this.accounts[i];
			this.checkStatus();
			//document.getElementById('OAUTH_select').innerHTML = userInfo.getUserName();
			return true;
		}
	}
	
	this.currentAccount = null
	this.checkStatus();
	return false;
}

etsyOauth.secretTokenCallback = function(content) {
	//alert('secretTokenCallback:' + content);
	etsyOauth.params = eval('(' + content + ')');
	var url = etsyOauth.params.loginURL + '?oauth_consumer_key=' + etsyOauth.params.consumerKey + '&oauth_token=' + etsyOauth.params.token;
	controller.setCookie();
	window.location = url;
								
}

etsyOauth.logout = function(){
	if (this.currentAccount) {
		for (var i = 0; i < this.accounts.length; i++){
			if (this.currentAccount.id == this.accounts[i].id){
				this.accounts.splice(i,1);
				break;
			}
		}
	}
	
	this.serializeAccounts();
	this.currentAccount = null;
	this.checkStatus();
	userInfo.done();
	
	
	
}

etsyOauth.checkStatus = function(){
	var button = document.getElementById('oauthButton');
	var profiles = document.getElementById('OAUTH_profiles');
	if (this.isLogin()) {
		button.innerHTML='Log Out';
		profiles.innerHTML = '<h2>Set Profile:</h2><div style="width:130px;font-weight:normal;font-size: 8pt;" id="OAUTH_select">' + userInfo.getUserName() + '</div>';
		var that = this;
		button.onclick = function(){
					that.logout();
				}
	}
	else {
		button.innerHTML='Import Etsy';
		profiles.innerHTML = controller.info[controller.currentTab.name].OAUTHstr;
		button.onclick = function(){
			var c = new AjaxConnection('secretToken.php');
			c.connect(etsyOauth.secretTokenCallback);
				}
								
	}
 
}


etsyOauth.serializeAccounts = function(){
	var v = '';
	
	for (var i = 0; i < this.accounts.length; i++){
		if (i!=0) v += ':';
			v += this.accounts[i].id + ',' + this.accounts[i].accessToken + ',' + this.accounts[i].accessTokenSecret;
	}
	
	controller.createCookie('craftO',v,30);
}

etsyOauth.deserializeAccounts = function(){
	var v = controller.getCookie('craftO');
	if (v == '')
		return;
		
	var a = v.split(':');
	for (var i = 0; i < a.length; i++){
		p = a[i].split(',');
		this.accounts.push(new Account(p[0],p[1],p[2]));
	}
	
}

etsyOauth.accessTokenCallback = function(content){
	var params = eval('(' + content + ')');
	var account = new Account(userInfo.getUserId(),params.accessToken,params.accessTokenSecret)
	var p = controller.params;
	etsyOauth.params.secretToken = null;
	p.secretToken = null;
	p.oauth_token = null;
	p.oauth_verifier = null;
	etsyOauth.accounts.push(account);
	etsyOauth.serializeAccounts();
	etsyOauth.setSelect();
	userInfo.done();
}


ETSYQuery._callback = function(data){
	ETSYQuery.that.callback(data);
}

function ETSYQuery(version,method,input,includes,params){
	this.version = version-1;
	this.entry = (this.version==0) ? '' : 'public';
	this.method = method;
	this.input = input;
	this.params = params;
	this.includes = includes;
	this.callbackStr = 'ETSYQuery._callback';
}

ETSYQuery.prototype.baseURLs = ['http://beta-api.etsy.com/v1/','http://openapi.etsy.com/v2/'];



ETSYQuery.prototype.getOptions = function(opt,inner,outer){
	 if (!opt)
		return '';
	
	 if (opt instanceof Array){
		var options = '';
	 
		for(i=0; i < opt.length; i++){
			if (opt[i] instanceof Array) 
				opt[i] = opt[i].join(inner);
		}
	
		options = opt.join(outer);
		return options;
	}
	return opt;
}

ETSYQuery.prototype.getInput = function(){
	 return this.getOptions(this.input,',',':');
}

ETSYQuery.prototype.getParams = function(){
	if (!this.params)
		return '';
	
	var paramStr = ''
	for (var p in this.params) {
		paramStr += p + '=' + this.params[p] + '&';
	}
	
	return paramStr;

	
}

ETSYQuery.prototype.getIncludes = function(){
	 var incStr = this.getOptions(this.includes,':',(this.version==0)? '&' :',');
	 if (incStr != ''){
		if (this.version == 1) incStr = "includes=" + incStr + '&';
		else incStr += '&';
	 }
	 return incStr;
}

ETSYQuery.prototype.keys = ['qnj98ajbudqpqkbewnadezbx','bu3unh2w5we5fq2pm2nxfjpw'];

ETSYQuery.prototype.query = function(){
	

	var url = this.baseURLs[this.version] + this.entry + this.method + this.getInput() + '.js?' + this.getIncludes() + this.getParams() + 'callback=' + this.callbackStr;
	
	if (this.entry != 'private'){
		url += '&api_key=';
		url += this.keys[this.version]
		
	} else {
		var accessor = { consumerSecret: etsyOauth.cs, tokenSecret : etsyOauth.currentAccount.accessTokenSecret};
		var message = { method:"GET",action: url,parameters:[]};
		
		message.parameters.push(['oauth_consumer_key', this.keys[this.version]]);
		message.parameters.push(['oauth_nonce', OAuth.nonce(11)]);
		message.parameters.push(['oauth_signature_method', 'HMAC-SHA1']);
		message.parameters.push(['oauth_timestamp', OAuth.timestamp()]);
		message.parameters.push(['oauth_token', etsyOauth.currentAccount.accessToken]);
		message.parameters.push(['oauth_version', '1.0']);
		
		OAuth.SignatureMethod.sign(message, accessor);
		
		for (var i = 0; i < 6; i++)
			url += '&' + message.parameters[i][0] + '=' + message.parameters[i][1];
		
		url += '&oauth_signature=' + encodeURIComponent(OAuth.getParameter(message.parameters, "oauth_signature"));
	}
	
	var script = document.createElement("script"); 
	//document.body.innerHTML += '<div>' + url + '</div>';
	script.setAttribute("src",url);
	script.setAttribute("type","text/javascript");   
	ETSYQuery.that = this;
	document.body.appendChild(script);
	

}










