/**
 * @author quickest
 */
function setLocation(url){
    window.location.href = url;
}

function addToFavourites(sName, sUrl) {
	if(window.sidebar)
		window.sidebar.addPanel(sName, sUrl , "");
	else if(window.external)
		window.external.AddFavorite(sUrl, sName)
}

function mail(sUser, sSite, bUrl) {
	document.write(bUrl ? '<a href=\"mailto:' + sUser + '@' + sSite + '\">' : '');
	document.write(sUser + '@' + sSite + (bUrl ? '</a>' : ''));
}

function mailLong(sUser, sSite, sSiteLong, bUrl) {
	document.write(bUrl ? '<a href=\"mailto:' + sUser + '@' + sSiteLong + '\">' : '');
	document.write(sUser + '@' + sSite + (bUrl ? '</a>' : ''));
}

/**
 * Set "odd", "even", "first" and "last" CSS classes for table rows and cells
 */
function decorateTable(table){
    table = $(table);
    if(table){
        var allRows = table.getElementsBySelector('tr')
        var bodyRows = table.getElementsBySelector('tbody tr');
        var headRows = table.getElementsBySelector('thead tr');
        var footRows = table.getElementsBySelector('tfoot tr');

        for(var i=0; i<bodyRows.length; i++){
            if((i+1)%2==0) {
                bodyRows[i].addClassName('even');
            }
            else {
                bodyRows[i].addClassName('odd');
            }
        }

        if(headRows.length) {
        	headRows[0].addClassName('first');
        	headRows[headRows.length-1].addClassName('last');
        }
        if(bodyRows.length) {
        	bodyRows[0].addClassName('first');
        	bodyRows[bodyRows.length-1].addClassName('last');
        }
        if(footRows.length) {
        	footRows[0].addClassName('first');
        	footRows[footRows.length-1].addClassName('last');
        }
        if(allRows.length) {
            for(var i=0;i<allRows.length;i++){
                var cols =allRows[i].getElementsByTagName('TD');
                if(cols.length) {
                    Element.addClassName(cols[cols.length-1], 'last');
                };
            }
        }
    }
}


/**
 * Set "first" CSS classes for list items
 */
function decorateDataList(table){
	
	table = $(table);
	
	if(table){
        var allRows = table.getElementsBySelector('tr')
		var firstColumns = allRows[0].getElementsBySelector('td');
		
		for(var i=0; i<firstColumns.length; i++){
			firstColumns[i].addClassName('first');
		}
	}
}

/**
 * Set "first" CSS classes for grid items
 */
function decorateDataGrid(table){
	
	table = $(table);
	
	if(table){
        var allRows = table.getElementsBySelector('tr')
		
		for(var i=0; i<allRows.length; i++){
			
			var allColumns = allRows[i].getElementsBySelector('td');
			
			if(allColumns.length) allColumns[allColumns.length-1].addClassName('last');
		}
		
		if(allRows.length) allRows[allRows.length-1].addClassName('last');
	}
}

/**
 * Quick Search form client model
 */
Shop = Class.create();
Shop.searchForm = Class.create();
Shop.searchForm.prototype = {
    initialize : function(form, field, emptyText){
        this.form   = $(form);
		this.button = this.form.getElementsByTagName('button')[0];
        this.field  = $(field);
        this.emptyText = emptyText;

        Event.observe(this.form,  'submit', this.submit.bind(this));        
        Event.observe(this.button,  'click', this.click.bind(this));        
		Event.observe(this.field, 'focus', this.focus.bind(this));
        Event.observe(this.field, 'blur', this.blur.bind(this));
        this.blur();
    },

    submit : function(event){
        if (this.field.value == this.emptyText || this.field.value == ''){
            Event.stop(event);
            return false;
        }
        return true;
    },
	
	click : function(event) {
		if(this.submit(event))
			this.form.submit();
	},

    focus : function(event){
        if(this.field.value==this.emptyText){
            this.field.value='';
        }

    },

    blur : function(event){
        if(this.field.value==''){
            this.field.value=this.emptyText;
        }
    }
}


// payment
/**
 * Login User
 */
Shop.userLogin = Class.create();
Shop.userLogin.prototype = {
    initialize: function(form, login, password, boxUserName, boxLoading, boxesToHide, boxesToShow, loginUrl, logoutUrl, failureUrl){
        this.form = form;
		
		this.login = login;
		this.password = password;
		
		this.boxLoading = boxLoading;
		this.boxUserName = boxUserName;
		
		this.boxesToHide = boxesToHide;
		this.boxesToShow = boxesToShow;
		
        this.loginUrl = loginUrl;
		this.logoutUrl = logoutUrl;
		this.failureUrl = failureUrl;
        
		this.onLoginSave = this.loginSave.bindAsEventListener(this);
        this.onLoginComplete = this.loginComplete.bindAsEventListener(this);
		
		this.onLogoutSave = this.logoutShowBoxes.bindAsEventListener(this);
		
		this.onFailure = this.ajaxFailure.bindAsEventListener(this);
		
		Event.observe($(login),'keydown',this.keydown.bindAsEventListener(this));
		Event.observe($(password),'keydown',this.keydown.bindAsEventListener(this));
    },
	
	keydown: function(oEvent) {
		if(oEvent.keyCode == 13)
			this.loginAction();
	},
	
	ajaxFailure: function(){
		location.href = this.failureUrl;
	},

    loginValidate: function() {		
    	if ($(this.login).value.length < 1) {
    		alert(TranslatorLogin.translate('Login must have minimum 1 character.'));
    		return false;
    	}
		
		if ($(this.password).value.length < 6) {
    		alert(TranslatorLogin.translate('Password must have minimum 6 characters.'));
    		return false;
    	}
		return true;
    },
	
	setLoadWaiting: function(loading) {
		/*
		if(loading)
			Element.show(this.boxLoading);
		else
			Element.hide(this.boxLoading);
		*/
	},

    loginAction: function(){
        if (this.loginValidate()) {
            this.setLoadWaiting(true);
            var request = new Ajax.Request(
                this.loginUrl,
                {
                    method:'post',
                    onComplete: this.onLoginComplete,
                    onSuccess: this.onLoginSave,
					onFailure: this.ajaxFailure,
                    parameters: Form.serialize(this.form)
                }
            );
        }
    },
	
	loginComplete: function(){
		this.setLoadWaiting(false)
	},

    loginSave: function(transport){
    	if (transport && transport.responseText){
            try{
                response = eval('(' + transport.responseText + ')');
            }
            catch (e) {
                response = {};
            }
        }
		if (response.error){
            alert(response.message);
            return false;
        }
        if (response.redirect) {
            location.href = response.redirect;
            return;
        }
		if(response.user_name) {
			$(this.boxUserName).innerHTML = TranslatorLogin.translate('User name') + ': ' + response.user_name;
		}
		$(this.login).value = "";
		$(this.password).value = "";
        this.loginShowBoxes();
    },
	
	loginShowBoxes: function() {
		
		this.boxesToHide.each(function(item){
				new Effect.Fade($(item));
				//$(item).hide();
            });
		this.boxesToShow.each(function(item){
                new Effect.Appear($(item));
				//$(item).show();
            });
	},
	
	logoutAction: function() {
		var request = new Ajax.Request(
                this.logoutUrl,
                {
                    method:'get',
                    onSuccess: this.onLogoutSave,
					onFailure: this.ajaxFailure
                }
            );
	},
	
	logoutShowBoxes: function() {
		this.boxesToShow.each(function(item){
                new Effect.Fade($(item));
				//$(item).hide();
            });
		this.boxesToHide.each(function(item){
                new Effect.Appear($(item));
				//$(item).show();
            });
	}
}

Shop.menu = Class.create();
Shop.menu.prototype = {
	"initialize" : function(catalogHeader, catalog, shopHeader, shop, actualActive) {
		this.catalogHeader = catalogHeader;
		this.catalog = catalog;
		this.shopHeader = shopHeader;
		this.shop = shop;
		this.actualActive = actualActive; // 0 - catalog, 1 - shop
		
		Event.observe($(catalogHeader),'click',this.catalogClicked.bindAsEventListener(this));
		Event.observe($(shopHeader),'click',this.shopClicked.bindAsEventListener(this));
	},
	"catalogClicked" : function() {
		if(this.actualActive == 1) { 
			new Effect.BlindDown($(this.catalog), {'duration' : 1});
			new Effect.BlindUp($(this.shop), {'duration' : 1});
			this.actualActive = 0;
		}
	},
	"shopClicked" : function() {
		if(this.actualActive == 0) { 
			new Effect.BlindUp($(this.catalog), {'duration' : 1});
			new Effect.BlindDown($(this.shop), {'duration' : 1});
			this.actualActive = 1;
		}
	}
}

function showAdminPopup(adminId, name, email, phone, phoneMobile, photo, vcard, qrcode) {
	var content = '<div class="header">' +
					'<div class="p-12">' + 
						'#{photo}' + 
						'<div class="personal">' + 
							'<h3>#{name}</h3>' + 
							'#{phone}' + 
							'#{phoneMobile}' + 
							'<a href="mailto:#{email}">#{email}</a>' + 
						'</div>' + 
						'<div class="get-vcard">#{vcard}</div>' + 
					'</div>' + 
				'</div>' + 
				'<div class="content">#{qrcode}</div>' + 
				'<div class="close">' + 
					'<a href="#">zamknij okno</a>' + 
				'</div>';
	
		
		var popup = $('popup');
		
		var popupInner = popup.getElementsByClassName('border-box')[0];
		popupInner.update(content.interpolate({
			'name' : name,
			'email' : email,
			'phone' : phone != false ? 'tel. ' + phone + '<br />' : '',
			'phoneMobile' : phoneMobile != false ? 'tel. kom. ' + phoneMobile + '<br />' : '',
			'photo' : photo != false ? '<div class="photo"><img src="' + photo + '" /></div>' : '',
			'vcard' : vcard != false ? '<span class="vcard-text">Kliknij aby porabć VCARD</span><span class="arrow"></span><a class="vcard-button" href="' + vcard + '">vcard</a>' : '',
			'qrcode' : qrcode != false ? '<div class="scan-qr-code"><span>Zeskanuj Kod QR z obrazka</span></div><div class="qr"><img src="' + qrcode + '" /></div>' : ''
		}));
		
		var popupCloseButton = popup.getElementsByClassName('close')[0];
		var popupOverlay = popup.getElementsByClassName('overlay-window')[0];
		
		// Zamknij kiedy zdarzenia nastąpiło z: overlay-window
		Event.observe(popupOverlay, 'click', function(event) {
			var target = event.srcElement || event.target;
			if(target.getAttribute('class') == 'overlay-window') {
				popup.hide();
				Event.stop(event);
			}
		});
		
		// Lub z przycisku zamknięcia
		Event.observe(popupCloseButton, 'click', function(event) {
			popup.hide();
			Event.stop(event);
		});
		
		// Badź poprzez przyciśnięcie na klawiaturze: ESC
		Event.observe(document, 'keydown', function(event) {
			if(event.which == 27) {
				popup.hide();
			}
		});
		
		popup.show();
}


String.prototype.interpolate = function(object) {
	var str = this;
	for(property in object) {
		str = str.replace(new RegExp("#{"+ property +"}", "g"), object[property]);
	}
	return str;
};
