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();
	
	if (controller.entry == controller.ETSY)
		this.backFromEtsyLogin();
	
	
}
	
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('php/accessToken.2.0.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();
	
	if (this.currentAccount && this.currentAccount.id == 0){
		this.deleteAccount(userId);
		this.currentAccount.id = userId;
		this.serializeAccounts();
		this.checkStatus();
		return true;
	}
	
	for (var i = 0; i < this.accounts.length; i++){
		if (userId == this.accounts[i].id){
			this.currentAccount = this.accounts[i];
			this.checkStatus();
			return true;
		}
	}
	
	this.currentAccount = null
	this.checkStatus();
	return false;
}

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

etsyOauth.deleteAccount = function(id){
	for (var i = 0; i < this.accounts.length; i++){
		if (id == this.accounts[i].id){
			this.accounts.splice(i,1);
			i--;
		}
	}
}

etsyOauth.logout = function(){
	this.deleteAccount(userInfo.getUserId());
	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('php/secretToken.2.0.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(0,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);
	this.currentAccount = account;
	userInfo.privateSubmit();
	
}

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

EQuery.prototype.ajaxCallback = function(data){
	var response = eval('(' + data + ')');
	if (typeof response.ok == 'undefined')
		response.ok = true;
		
	this.obj[this.callbackStr](response);
	
}


EQuery.prototype.JSONP = 'j';
EQuery.prototype.AJAX = 'a';

EQuery.prototype.that = {};

function EQuery(method,opt){
	this.method = method;
	this.entry = (opt.entry) ? opt.entry : 'public';
	this.type = (opt.type) ? opt.type : this.JSONP;
	this.obj = (opt.obj) ? opt.obj : this;
	this.callbackStr = (opt.callbackStr) ? opt.callbackStr : 'EQuery._callback';
	this.input = opt.input;
	this.params = opt.params;
	this.includes = opt.includes;
}

EQuery.prototype.baseURL = 'http://openapi.etsy.com/v2';

EQuery.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;
}

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

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

	
}

EQuery.prototype.getIncludes = function(){
	 var incStr = this.getOptions(this.includes,':',',');
	 if (incStr != ''){
		 incStr = "includes=" + incStr + '&';
	 }
	 return incStr;
}

EQuery.prototype.includesToParams = function(){
	 var incStr = this.getOptions(this.includes,':',',');
	 if (incStr != ''){
		this.params.includes = incStr;
	 }
}

EQuery.prototype.key = 'bu3unh2w5we5fq2pm2nxfjpw';

EQuery.prototype.query = function(){
	var url;
	this.that = this;
	if (this.type == this.JSONP){
	
		url = this.baseURL + this.method + this.getInput() + '.js?' + this.getIncludes() + this.getParams() + 'callback=' + this.callbackStr;
		if (this.entry == 'either' && etsyOauth.isLogin()){
			this.entry = 'private';
		}
	
		if (this.entry != 'private'){
			url += '&api_key=';
			url += this.key;
		
		} else {
			var accessor = { consumerSecret: etsyOauth.cs, tokenSecret : etsyOauth.currentAccount.accessTokenSecret};
			var message = { method:"GET",action: url,parameters:[]};
		
			message.parameters.push(['oauth_consumer_key', this.key]);
			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"); 
		script.setAttribute("src",url);
		script.setAttribute("type","text/javascript");   
		document.body.appendChild(script);
	}
	
	else {
			
		url = this.baseURL + this.method + this.getInput();
		this.params.url = url;
		this.params.oauth_token = etsyOauth.currentAccount.accessToken;
		this.params.oauth_token_secret = etsyOauth.currentAccount.accessTokenSecret;
		var c = new AjaxConnection('php/oauthAPI.2.1.php');
		this.includesToParams();
		c.options = this.getParams();
		c.connect(this,'ajaxCallback');

	}
	

}










