/*  Yshop
 *  (c) 2009 Tobias Ouwejan
 *
 *--------------------------------------------------------------------------*/

var NO_REPONSE_CONTENT 			= "no response text";
var EMPTY_LIST 					= "empty list";

var yshop = {
    init:function(){}
}

yshop.Form = Class.create();

yshop.Form.prototype = {
    initialize:function (uri) {
    },
    add: function(e, uri, target, hide){
		var e = $(e);
		if (e) {
			var row = e.up('.form-row');
			this.clearFormRowSibblings(e, row);
		}
		// get target
		var target = (target == null) ? row.up() : $(target);
        
        if (target) target.show();
		
		
		// load the new result
		yshop.Services.loadAjax(uri, this.publishRow.bind({'target':target, 'uri': uri, 'hide':hide}), yshop.Services.ajaxFailure);
		
	},
	replace: function(e, uri, target, hide) {
		var e = $(e);
		if (e) {
			var row = e.up('.form-row');
			
			this.clearCurrentRow(e, row);
		}
		// get target
		var target = (target == null) ? row.up() : $(target);
        
        if (target) target.show();
		
		// load the new result
        if (uri) uri += ((uri.indexOf('?') == -1) ? '?' : '&') + Math.floor(Math.random()*(1000));
        
		yshop.Services.loadAjax(uri, this.publishRow.bind({'target':target, 'uri': uri,'hide': hide}), yshop.Services.ajaxFailure);
	},
	updateResult: function(e, uri) {
		var e = $(e);
		yshop.Services.loadAjax(uri, function(transport){
			var response = transport.responseText || NO_REPONSE_CONTENT;
			// create a row
	        var newRow = new Element('div');
	        newRow.update(response);
	        
	        this.up().insert(newRow);
		}.bind(e));
	},
	clearCurrentRow: function(e, row) {
		
		var currentFieldSet = row.up('fieldset');
		
		currentFieldSet.select('div').each(function(e){
			e.remove();
		});
	},
	clearFormRowSibblings: function(e, row) {

		var currentFieldSet = row.up('fieldset');
		
		currentFieldSet.nextSiblings().each(function(f){
			if (f.tagName == 'FIELDSET') {
				f.select('div').each(function(e){
					e.remove();
				});
				
				f.hide();
			}
		});
		// remove nex rows
		this.removeRows(row);
	},
	
	removeRows: function(row) {
		row.nextSiblings().each(function(e) {
			e.remove();
		});
	},
	
	publishRow: function(transport) {
		var response = transport.responseText || NO_REPONSE_CONTENT;
        // create a row
        var newRow = new Element('div');
        newRow.update(response);
		newRow.title = newRow.title + ' uri: ' + this.uri;
        $(this.target).insert(newRow);
		if (this.hide) newRow.hide();
	},
	toggleFieldsetContent:function(e) {
		var fieldSet = $(e).up('fieldset');
		
		fieldSet.toggleClassName('show');
		fieldSet.childElements().each(function(f){
			if (f.tagName != 'LEGEND') {
				f.toggle();
			}
		});
	}
	
}

yshop.Services = {
	updatePanel: function(e, uri) {
    	new Ajax.Updater($(e), uri, {'evalScripts':true});
	},
    loadAjax: function (_uri, loader, failure ) {
        uri = _uri;
        if (uri) uri += ((uri.indexOf('?') == -1) ? '?' : '&') + Math.floor(Math.random()*(1000));
        new Ajax.Request(uri, {
            method:'get',
            evalScripts: true,
            onSuccess: loader,
            onFailure: failure,
            onException: failure
        });
    },
    ajaxFailure:function(request, exception){
        alert ('could not load request (' + exception + ')');
    }

}

var checkoutForm = new yshop.Form();

//Because ie7 sucks
function checkEnter(e){ //e is event object passed from function invocation
	e = $(e);
	var characterCode; //literal character code will be stored in this variable

	if(e && e.which){ //if which property of event object is supported (NN4)
		e = e;
		characterCode = e.which; //character code is contained in NN4's which property
	} else {
		characterCode = e.keyCode; //character code is contained in IE's keyCode property	
	}

	if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
		var submitButton = (e.form).getInputs('submit');
		if (submitButton) 
			submitButton.first().click(); 

		return true; 
	}
}

// small scriptaculous extension to autocompletion so that a loading and not-available state is implemented
Ajax.Autocompleter.prototype.oldUpdateChoices =  Ajax.Autocompleter.prototype.updateChoices;
Ajax.Autocompleter.prototype.updateChoices = function (choices) {
	if (choices.blank()) {
		this.element.addClassName('not-available');
		choices = '<ul><li class="not-available">' + this.options.notAvailableMsg + '</li></ul>';
	} else {
		this.element.removeClassName('not-available');
	}

	this.oldUpdateChoices(choices);

}
Ajax.Autocompleter.prototype.loadEntries = function (element, entry) {
	this.updateChoices.delay.bind(this, 0.1,'<ul><li class="loading">' + this.options.loadingMsg + '</li></ul>');
}

if (Prototype.Browser.IE) {
    Autocompleter.Base.prototype.onBlur = function(event) {
      // needed to make click events work
      setTimeout((function(e) {
            if (this.dontBlur) {
              this.dontBlur = false;
              this.elemeent.focus();
              return;
            }
            this.hasFocus = false;
            this.active = false;
            this.hide();
      }).bind(this), 250);
    };
}

