var EE  = {};

function createSelect(options){
		var select = document.createElement('select');

		for (var i = 0; i < options.length; i++){
			select.options[i]=new Option(options[i],options[i]);
			select.onchange = function(e){EE.selectChange(e);}
		}

		return select;
	}

EE.selectChange = function(){
		this.query = null;

		if (this.edit.value != this.currentEdit){
			this.currentEdit = this.edit.value;
			this.drawQuery();
			return;
		}

		if (this[this.currentEdit + 'DoPreQuery'])
			this[this.currentEdit + 'DoPreQuery']();


		if (!this.validateInput()){
			this.input.value = '';
			return;
		}

		this.doQuery();
	}

EE.doQuery = function(e){

		this.query = {};
		this.query.round = 'none';

		if (this.change.value == 'checked')
			this.query.checkOnly = true;
		else this.query.checkOnly = false;

		this[this.currentEdit + 'DoQuery']();

	}

EE.priceDoPreQuery = function(){

		if (this.dir.value == 'exact value'){
			this.by.selectedIndex = 0;
			this.by.disabled = true;
		}else {
			this.by.disabled = false;
		}
		if (this.by.value == 'percentage'){
			this.validateInput = percentValidate;
		}
		else {
			this.validateInput = moneyValidate;
		}
	}

EE.priceDoQuery = function(){

		var start = parseFloat(this.input.value);

		if (this.by.value == 'percentage'){
			this.query.func = 'perc';
			start = parseInt(this.input.value);
		}
		else if (this.dir.value == 'exact value'){
			this.query.func = 'replace';
		}
		else{
			this.query.func = 'add';
		}

		if (this.dir.value == 'decrease')
			start = 0-start;

		this.query.value = start;

		if (this.round.value == 'round')
			this.query.round = 'normal'
		else if (this.round.value == 'round up')
			this.query.round = 'up';
		else if (this.round.value == 'round down')
			this.query.round = 'down';

		this.doAction('doQuery');
	}

EE.quantityDoQuery = function(){
		var start = parseInt(this.input.value);

		if (this.dir.value == 'exact value'){
			this.query.func = 'replace';
		}
		else{
			this.query.func = 'add';
		}

		if (this.dir.value == 'decrease')
			start = 0-start;

		this.query.value = start;
		this.doAction('doQuery');
	}
	
EE.titleDoQuery = function(){
		
		this.query.value = this.input.value
		
		if (this.word.value == 'matching exactly')
			this.query.func = 'replace';
		else if (this.word.value == 'adding to the end')
			this.query.func = 'add';
		else if (this.word.value == 'adding to the beginning')
			this.query.func = 'padd';
		
		this.doAction('doQuery');
	}
	
EE.descriptionDoQuery = EE.titleDoQuery;

Listing.prototype.doQuery = function(){

		if (!EE.query)
			return;

		if (EE.query.checkOnly && !this.check.checked){
			if (this.changes[EE.currentEdit]){
				this.input.value = this.data[EE.currentEdit]
				this.onInputChange();
			}
			return;
		}

		var value = this.data[EE.currentEdit];

		if (EE.currentEdit == 'price')
			value = parseFloat(value);

		if (EE.query.func == 'replace')
			value = EE.query.value;
		else if (EE.query.func == 'add')
			value += EE.query.value;
		else if (EE.query.func == 'padd')
			value = EE.query.value + value;
		else if (EE.query.func == 'perc'){
			value = (EE.query.value/100 * value) + value;
		}
		else if (EE.query.func == 'remove'){
		
			var intIndexOfMatch = value.indexOf(EE.query.value);
 
			while (intIndexOfMatch != -1){
			// Relace out the current instance.
				value = value.replace( EE.query.value, '' )
 
				// Get the index of any next matching substring.
			intIndexOfMatch = value.indexOf(EE.query.value);
			}

		}


		if (EE.query.round == 'normal'){
			value = Math.round(value);
		}
		else if (EE.query.round == 'up'){
			value = Math.ceil(value);
		}
		else if (EE.query.round == 'down'){
			value = Math.floor(value);
		}

		this.input.value = value;

		this.onInputChange();

	}

EE.init = function(){

		this.currentEdit = 'price';
		this.listings = [];
		this.sections = null;
		this.sectionsIndex = [];
		this.sectionObjs = [];
		this.commitIndex = 0;

		this.change = createSelect(['checked','all']);
		this.edit = createSelect(['price','title','description','quantity']);
		this.dir = createSelect(['increase','decrease','exact value']);
		this.by = createSelect(['dollar amount','percentage']);
		this.round = createSelect(['do not round','round','round up','round down']);
		this.word = createSelect(['matching exactly','adding to the beginning','adding to the end']);
		this.draw();
		this.findAllShopSections();

	}

EE.findAllShopSections = function(){
	var opts = {entry:'private',callbackStr:'EE.findAllShopSectionsCallback',params:{limit:100,ofset:0}};
	var q = new EQuery('/shops/' + userInfo.getUserName() + '/sections', opts);
	q.query();

}

EE.findAllShopSectionsCallback = function(response){
	
	if (!response.ok){
		supA.print();
		alert("Got an error findAllShopSectionsCallback: " + response.error);
		return;
	}

	this.sections = response.results;

	for (var i = 0; i < this.sections.length; i++){
		this.sectionsIndex[this.sections[i].shop_section_id] = this.sections[i];
		this.sections[i].listings = [];
	}

	var noSection = {title:"Items not in a section",listings:[]}
	this.sections.push(noSection);
	this.sectionsIndex[0] = noSection;
	this.findAllShopListingsActive('START');

};

EE.findAllShopListingsActive = function(status){
	
	
	if (status == 'START'){
		this.listingOffset = 0;
		if (userInfo.state != userInfo.SUCCESS){
			return;
		}
	}

	var opts = {entry:'private', params:{limit:100,offset:this.listingOffset,fields:'listing_id,title,description,price,quantity,shop_section_id',sort_on:'created',sort_order:'down'},callbackStr: 'EE.findAllShopListingsActiveCallback',includes:['Images(url_75x75):1:0']};
	var q = new EQuery('/shops/' + userInfo.getUserName() + '/listings/active',opts);
	q.query();
};

EE.findAllShopListingsActiveCallback = function(response){

	if (!response.ok){
		supA.print();
		alert("Got an error findAllShopListingsActiveCallback: " + response.error);
		return;
	}

	var results = response.results;

	for (var i = 0; i < results.length; i++){
		if (!results[i].Images[0]){
			continue;
		}

		var l = new Listing(results[i]);

		if (!results[i].shop_section_id || !this.sectionsIndex[results[i].shop_section_id]){
			this.sectionsIndex[0].listings.push(l);
		}
		else{
				this.sectionsIndex[results[i].shop_section_id].listings.push(l);
		}
		
		
		this.listings.push(l);

	}

	this.listingOffset += results.length;

	if (this.listingOffset >= response.count){
		this.drawListings();
		supA.print();
		return;
	}

	this.findAllShopListingsActive('GO');

};


EE.drawListings = function() {

	for (var i = 0; i < this.sections.length; i++){
		if (this.sections[i].listings.length <= 0)
			continue;

		var section = new Section(this.sections[i]);
		this.sectionObjs.push(section);
		for (var j = 0; j < this.sections[i].listings.length; j++)
			this.sections[i].listings[j].draw();
	}

}

EE.priceDrawQuery = function(){
		this.validateInput = moneyValidate;
		this.queryRoot.appendChild(document.createTextNode(" to "));
		this.queryRoot.appendChild(this.dir);
		this.queryRoot.appendChild(document.createTextNode(" by "));
		this.queryRoot.appendChild(this.by);
		this.queryRoot.appendChild(document.createTextNode(" and "));
		this.queryRoot.appendChild(this.round);
	}


EE.titleDrawQuery = function(){
		this.validateInput = dummy;
		this.queryRoot.appendChild(document.createTextNode(" by "));
		this.queryRoot.appendChild(this.word);
		this.queryRoot.appendChild(document.createTextNode(" the characters entered."));
	}
	
EE.descriptionDrawQuery = EE.titleDrawQuery;
		
EE.quantityDrawQuery = function(){
		alert("ETSY will charge you 20 cents per quantity increase");
		this.validateInput = intValidate
		this.queryRoot.appendChild(document.createTextNode(" to "));
		this.queryRoot.appendChild(this.dir);
		this.queryRoot.appendChild(document.createTextNode(" by amount entered."));
	}

EE.setSelect = function(value){
		for (var i = 0; i < this.sectionObjs.length; i++){
			this.sectionObjs[i].check.checked = value;
		}

		this.doAction('setSelect',value);
	}

EE.drawQuery = function(){
		while ( this.queryRoot.childNodes.length >= 1 ){
			this.queryRoot.removeChild(this.queryRoot.firstChild );
		}

		this.editingRequest.innerHTML = 'Editing ' + EE.currentEdit + ':';
		this[this.currentEdit + 'DrawQuery']();
		this.input.value = '';
		this.doAction('setEditClass');
	}

EE.updateChangeCount = function(diff){
		this.changeCount += diff;

		if (this.changeCount <= 0){
			this.changeCount = 0;
			this.changeStatus.innerHTML = '';
			return;
		}

		var p = '';
		if (this.changeCount != 1) p = 's';
		this.changeStatus.innerHTML = '' + this.changeCount + ' item' + p + ' ready to update';
	}

EE.draw = function(){
		var editor = document.createElement('div');
		var editBox = document.createElement('div');
		var queryBox = document.createElement('div');
		editor.className = 'editorBox';
		queryBox.className = 'queryBox';
		editBox.className = 'priceEdit';

		this.input = document.createElement('input');
		this.input.type = 'text';
		//this.input.setAttribute('maxlength',155);
		this.input.onkeyup = function() {EE.doQuery()};
		var that = this;
		this.input.onchange = function() {if (!that.validateInput())
											this.value = '';

										}


		this.editingRequest = document.createElement('h2');
		this.editingRequest.className = 'editTitle';
		
		editor.appendChild(queryBox);
		queryBox.appendChild(document.createTextNode("Edit "));
		queryBox.appendChild(this.change);
		queryBox.appendChild(document.createTextNode(" items to adjust their "));
		queryBox.appendChild(this.edit);

		this.queryRoot = document.createElement('span');
		queryBox.appendChild(this.queryRoot);

		this.drawQuery();

		editBox.appendChild(this.editingRequest);
		editBox.appendChild(this.input);
		
		editor.appendChild(editBox);

		controller.main.appendChild(editor);
		this.drawButtons();
	}

EE.drawButtons = function(){


		var bBox = document.createElement('div');
		bBox.className = 'buttonBox'

		this.changeStatus = document.createElement('p');
		this.changeCount = 0;
		this.updateChangeCount(0);


		var statusBox = document.createElement('div');

		this.check = document.createElement('input');
		this.check.type = 'checkbox';
		statusBox.className = 'statusBox';

		statusBox.appendChild(this.check);
		bBox.appendChild(statusBox);

		this.check.onclick = function(){EE.setSelect(this.checked);}
		bBox.appendChild(this.changeStatus);
		b = document.createElement('input');
		b.className = 'cancelButton';
		b.type = 'button';
		b.value = 'Cancel';
		b.onclick = function(){EE.input.value = '';EE.query = null; EE.doAction('revert');}
		bBox.appendChild(b);

		this.commitButton = document.createElement('input');
		this.commitButton.type = 'button';
		this.commitButton.value = 'Save Changes';

		
		this.commitButton.className = 'commitButton';
		this.commitButton.onclick = function(){this.disabled = true; EE.commitIndex = 0; EE.commit();}
		
		bBox.appendChild(this.commitButton);
		controller.main.appendChild(bBox);
	}

EE.doAction = function(actionName,edit){
		for (var i = 0; i < this.listings.length; i++){
			this.listings[i][actionName](edit);
		}
	}

EE.commit = function(){

		while (this.commitIndex < this.listings.length){

		if (this.listings[this.commitIndex].hasChange()){
			this.listings[this.commitIndex].updateListing();
			return;
		}

			this.commitIndex++;
		}

		this.commitButton.disabled = false;
		

	}

function Section(data){
		this.data = data;
		this.listings = data.listings;
		this.draw();
	}

Section.prototype.doAction = EE.doAction;

function insertAfter(node, referenceNode) {
		controller.main.insertBefore(node, referenceNode.nextSibling);
	}

Section.prototype.draw = function(){
		this.section = document.createElement('div');
		var statusBox = document.createElement('div');

		this.section.className = 'sectionBox';
		statusBox.className = 'statusBox';

		var title = this.data.title;

		this.section.innerHTML += '<p>' + title + '</p>';

		var b = document.createElement('input');
		b.type = 'button';
		b.value = 'Hide Section';
		b.className = 'collapseButton';



		this.check = document.createElement('input');
		this.check.type = 'checkbox';
		
		var that = this;
		this.check.onclick = function(){ that.doAction('setSelect',this.checked);}

		b.onclick = function(){
			if (this.value == 'Hide Section'){
				that.doAction('removefromDOM');
				this.value = 'Show Section'
			} else {
				var after = that.section;
				for (var i = 0; i < that.listings.length; i++){

					if (i != 0)
						after = that.listings[i-1].listing;

					insertAfter(that.listings[i].listing,after);
				}

				this.value = 'Hide Section'
			}


		}



		statusBox.appendChild(this.check);
		this.section.appendChild(statusBox);
		this.section.appendChild(b);

		controller.main.appendChild(this.section);
	}



function Listing(data){

		this.data = fixData(data);
		this.changes = {};
	}

var desfix = document.createElement('textarea');
function fixData(data){
		if (!isNaN(data.price)){
			data.price = '' + data.price; 
		}

		if (data.price.length >= 3 && data.price.charAt(data.price.length - 2) == '.')
			data.price += '0';
		else if (data.price.length < 3 || data.price.charAt(data.price.length - 3) != '.')
			data.price += '.00';
			
		desfix.value = data.description;
		data.description = desfix.value;
		
		return data;
	}

Listing.prototype.hasChange = function(){
	var needChange = false
	for (var i in this.changes){
		needChange = true;
		break;
	}
	return needChange;
}

Listing.prototype.updateListing = function(){

	var opts = {};
	opts.input = this.data.listing_id;
	opts.params = this.changes;
	opts.params.method = 'PUT'
	opts.entry = 'private';
	
	if (this.changes.description){
		opts.type = 'a';
		opts.obj = EE;
		opts.callbackStr = 'updateListingCallback';
		
	} else {
		opts.callbackStr = 'EE.updateListingCallback';
	
	}

	var q = new EQuery('/listings/',opts);
	q.query();

}

EE.updateListingCallback = function(response){
	if (!response.ok){
		delete this.listings[this.commitIndex].changes['method'];
		delete this.listings[this.commitIndex].changes['url'];
		delete this.listings[this.commitIndex].changes['oauth_token'];
		delete this.listings[this.commitIndex].changes['oauth_token_secret'];
	}
	
	else {
		var results = response.results;

		if (results && results.length >= 1){
			this.listings[this.commitIndex].data = fixData(results[0]);
			this.listings[this.commitIndex].revert();
			
		}
	
	}

	this.listings[this.commitIndex].setAlert(response.ok,response.error);

	this.commitIndex++;
	this.commit();
}


Listing.prototype.setSelect = function(value){
		this.check.checked = value;
		this.check.onclick();
	}

Listing.prototype.removefromDOM = function(){
		controller.main.removeChild(this.listing);
	}

Listing.prototype.removeChange = function(field){
		var start = this.hasChange();
		
		if (EE.currentEdit == field)
			this.input.value = this.data[field]
		
		delete this.changes[field];
		
		this.initValue();

		var end = this.hasChange();

		if ((start && end) || (!start && !end))
			return;

		if (end)
			EE.updateChangeCount(1);
		else
			EE.updateChangeCount(-1);
	
	}

Listing.prototype.onInputChange = function(){
		
		var start = this.hasChange();
		
		if (!this[EE.currentEdit + 'Validate']() || this.input.value == this.data[EE.currentEdit]){
			delete this.changes[EE.currentEdit];
		} else {
			this.changes[EE.currentEdit] = this.input.value;
		}
		this.initValue();

		var end = this.hasChange();

		if ((start && end) || (!start && !end))
			return;

		if (end)
			EE.updateChangeCount(1);
		else
			EE.updateChangeCount(-1);

	}

Listing.prototype.initValue = function(){

		this.drawTitle();

		this.changeResponse.innerHTML = '';
		if (this.changes[EE.currentEdit]){
			this.input.value = this.changes[EE.currentEdit];
			if (EE.currentEdit != 'title' && EE.currentEdit != 'description')
				this.changeResponse.innerHTML = 'was originally: ' + this.data[EE.currentEdit];
		} else {
			this.input.value = this.data[EE.currentEdit];
		}


		this.drawChangeLog();


	}
	
Listing.prototype.drawChangeLog = function(){
		this.changeLog.innerHTML = '';

		var first = true;
		
		var that = this;
		for (var i in this.changes){
			if (first){
				this.alert.style.visibility = 'hidden';
				this.changeLog.innerHTML = "Altered Fields: "
			}

			var b = document.createElement('input');
			b.type = 'button';
			b.onclick = function(){that.removeChange(this.value);}
			b.onmouseover = function(){this.style.backgroundColor = '#e0cfc0';}
			b.onmouseout = function(){this.style.backgroundColor = '#CEB29B';}
			b.value = i;
			this.changeLog.appendChild(b);
			first = false;
		}
	}

Listing.prototype.setEditClass = function(){
		this.editBox.removeChild(this.input);
		
		if (EE.currentEdit == 'description'){
			this.listing.style.height = '200px';
			this.input = document.createElement('textarea');
		}
		else {
			this.listing.style.height = '72px';
			this.input = document.createElement('input');
			this.input.type = 'text';
			this.input.setAttribute('maxlength',155);
		}
	
		this.editBox.className = EE.currentEdit + 'Edit';
		this.editingRequest.innerHTML = 'Editing ' + EE.currentEdit + ':';
		
		var that = this;
		
		this.input.onblur = function() {that.onInputChange()};
		this.input.onclick = function() {that.onclick();}
		
		this.editBox.insertBefore(this.input,this.changeResponse);
		this.initValue();
	}

Listing.prototype.onclick = function() {
		if (!this.hasChange()) 
			EE.updateChangeCount(1); 
		this.changes[EE.currentEdit] = ' ';  
		this.drawChangeLog(); 
		if (EE.currentEdit != 'title' && EE.currentEdit != 'description'){
			this.input.value = '';
			this.changeResponse.innerHTML = 'was originally: ' + this.data[EE.currentEdit];
		}
	}
	
Listing.prototype.setAlert = function(ok,msg){
	if (ok){
		this.alert.src = 'images/smile.png';
		this.alert.title = "Item updated successfully";
	} else {
		this.alert.src = 'images/frown.png';
		this.alert.title = msg;
	}
		
	this.alert.alt = this.alert.title;
	this.alert.style.visibility = 'visible';
}
	
Listing.prototype.draw = function(){
		this.listing = document.createElement('div');
		this.editBox = document.createElement('div');

		var statusBox = document.createElement('div');
		var infoBox = document.createElement('div');

		this.listing.className = 'listingBox';
		statusBox.className = 'statusBox';
		infoBox.className = 'infoBox';


		this.editingRequest = document.createElement('h2');
		this.editingRequest.className = 'editTitle';
		this.changeResponse = document.createElement('h2');
		this.changeResponse.className = 'editTitle';
		this.changeResponse.style.color = '#955383'

		this.changeLog = document.createElement('div');
		this.changeLog.className = 'changeLog';
		
		var url = this.data.Images[0].url_75x75;

		this.listing.appendChild(statusBox);
		
		infoBox.innerHTML += '<img alt="' + this.data.title + '"name="' + this.data.title + '" src="' + url + '"/>';
		this.title = document.createElement('h2');
		infoBox.appendChild(this.title);
		var d = document.createElement('div');
		d.innerHTML += '<p style="margin:0px;text-align:left;font-size:10px" >Listing ID: <a style="color:black;" target="_blank" href="http://www.etsy.com/listing/' + this.data.listing_id + '">' + this.data.listing_id + '</a></p>';
		infoBox.appendChild(d);
		
		

		this.listing.appendChild(infoBox);

		this.check = document.createElement('input');
		var that = this;
		this.check.onclick = function(){ if (this.checked)
											that.doQuery();
											else if (!EE.query || EE.query && EE.query.checkOnly)
											that.revert();
										}
		this.check.type = 'checkbox';
		
		this.alert = document.createElement('img');
		this.alert.style.marginTop = '30px';
		this.alert.style.visibility = 'hidden';

		statusBox.appendChild(this.check);
		statusBox.appendChild(this.alert);

		this.listing.appendChild(this.editBox);
		this.listing.appendChild(this.changeLog);
		
		this.input = document.createElement('input');
		this.input.type = 'text';
			
		
		this.editBox.appendChild(this.editingRequest);
		this.editBox.appendChild(this.input);
		this.editBox.appendChild(this.changeResponse);
		
		this.setEditClass();

		controller.main.appendChild(this.listing);
	}
	
Listing.prototype.drawTitle = function(){
		
		var t;
		
		if (this.changes.title){
			t = this.changes.title;
			this.title.className = 'listingTitleC';
			}
		else{
			t = this.data.title;
			this.title.className = 'listingTitle';
			}
			
		if (t.length > 100) this.title.style.fontSize = '10px';
		else this.title.style.fontSize = '12px';
		
		this.title.innerHTML = t;
		
	}

Listing.prototype.revert = function(){
		if (this.hasChange())
			EE.updateChangeCount(-1);
		this.changes = {};
		this.initValue();
	}

	Listing.prototype.priceValidate = moneyValidate;
	Listing.prototype.quantityValidate = intValidate;
	Listing.prototype.titleValidate = titleValidate;
	Listing.prototype.descriptionValidate = function(){
		if (this.input.value == '')
			return false;
			
		return true;
	};

	function titleValidate(){
		var newValue = this.input.value;
		
		newValue = newValue.replace(/^\s+|\s+$/g, '')

		if (newValue.length > 155)
			return false;
		
		var iChars = "!@#$^*+=[]\;{}|<>?";
		
		for (var i = 0; i < newValue.length; i++) {
			if (iChars.indexOf(newValue.charAt(i)) != -1) {
				return false;
			}
		}
		
		if (newValue == '')
			return false;
		
		this.input.value = newValue;
		return true;
	}
	
	function dummy(){return true;}

	function intValidate(){
		var newValue = parseInt(this.input.value);
		if (isNaN(newValue) || newValue <= 0)
			return false;

		this.input.value = newValue;

		return true;
	}

	function percentValidate(){
		this.func = intValidate;
		if (this.func()){
			this.input.value += '%';
			return true;
		}

		return false;
	}

	function moneyValidate(){
	
		var newValue = this.input.value;
		var decAmount = "";
		var dolAmount = "";
		var decFlag = false;
		var aChar = "";

		// ignore all but digits and decimal points.
		for(i=0; i < newValue.length; i++) {
			aChar = newValue.substring(i,i+1);
			if(aChar >= "0" && aChar <= "9") {
				if(decFlag) {
					decAmount = "" + decAmount + aChar;
				}
				else {
					dolAmount = "" + dolAmount + aChar;
				}
			}
			if(aChar == ".") {
				if(decFlag) {
					dolAmount = "";
					break;
				}
				decFlag=true;
			}
		}

		// Ensure that at least a zero appears for the dollar amount.

		if(dolAmount == "") {
			dolAmount = "0";
		}
		// Strip leading zeros.

		if(dolAmount.length > 1) {
			while(dolAmount.length > 1 && dolAmount.substring(0,1) == "0") {
				dolAmount = dolAmount.substring(1,dolAmount.length);
			}
		}

		// Round the decimal amount.
		if(decAmount.length > 2) {
			if(decAmount.substring(2,3) > "4") {
				decAmount = parseInt(decAmount.substring(0,2)) + 1;
				if(decAmount < 10) {
					decAmount = "0" + decAmount;
				}
				else {
					decAmount = "" + decAmount;
				}
			}
			else {
				decAmount = decAmount.substring(0,2);
			}
			if (decAmount == 100) {
				decAmount = "00";
				dolAmount = parseInt(dolAmount) + 1;
			}
		}

		// Pad right side of decAmount
		if(decAmount.length == 1) {
			decAmount = decAmount + "0";
		}
		if(decAmount.length == 0) {
			decAmount = decAmount + "00";
		}

		// Check for negative values and reset this.input
		if(newValue.substring(0,1) != '-' ||
				(dolAmount == "0" && decAmount == "00")) {
			this.input.value = dolAmount + "." + decAmount;

		}
		else{
			this.input.value = '-' + dolAmount + "." + decAmount;
		}

		if (parseFloat(this.input.value) <= '0.00'){
			return false;
		}

		return true;
	}
