/**
 * @author quickest
 */

Event.observe(window, 'load', function() {
	new Shop.media('footer-buttons');
});

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>' : ''));
}

/**
 * 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('input')[1];
        this.field  = $(field);
        this.emptyText = emptyText;
		this.searchFormValidator = new Validation(this.form, {immediate : true});
		
        Event.observe(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.searchFormValidator.validate()) {
			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;
        }
		this.searchFormValidator.reset();
    }
}


// payment
/**
 * Login User
 */
Shop.userLogin = Class.create();
Shop.userLogin.prototype = {
    initialize: function(form, login, password, boxAlert, boxAlertTxt, boxUserName, boxLoading, boxesToHide, boxesToShow, loginUrl, logoutUrl, failureUrl){
        this.form = form;
		
		this.login = login;
		this.password = password;
		
		this.boxAlert = boxAlert;
		this.boxAlertTxt = boxAlertTxt;
		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) {
    		this.alert(TranslatorLogin.translate('Login must have minimum 1 character.'));
			return false;
    	}
		
		if ($(this.password).value.length < 6) {
    		this.alert(TranslatorLogin.translate('Password must have minimum 6 characters.'));
			return false;
    	}
		return true;
    },
	
	alert: function(message) {
		$(this.boxAlertTxt).innerHTML = message;
		
		new Effect.Appear($(this.boxAlert), { duration: 0.5 });
		
		setTimeout(function() {
			new Effect.Fade($(this.boxAlert), { duration: 1.0 });
		}.bind(this), 4000);
	},
	
	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){
            this.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();
            });

		this.refreshPage();
	},
	
	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();
            });
			
		this.refreshPage();
	},
	
	refreshPage: function() {
		var aCheckout = location.href.toLowerCase().match(/\S+\/checkout\/onepage\S*/);
		if(aCheckout != null)
			document.location.reload();
	}
}

/**
 * Login User
 */
Shop.Slideshow = Class.create(PeriodicalExecuter, {
	initialize: function($super, items, mainPageUrl){
        this.items = items; // [{src : '', desc: ''}]
        this.index = 1;
        this.imageName = 'intro-image';
        this.imageDesc = 'intro-desc';
        this.imageUrl = 'intro-url';
        this.mainPageUrl = mainPageUrl;
	
		$super(this.setItem, 4);
	},
	
    setItem: function() {
    	
    	var item = this.items[this.index];
    	
    	var image = new Image(); 
    	image.src = item["src"];
    	
    	var elements = [this.imageName, this.imageDesc, this.imageUrl];
    	
		elements.each(function(element) {
			new Effect.Opacity($(element), {
				duration: 0.5,
				from: 1.0,
				to: 0
			});
		});
		
		setTimeout(function() {
			$(this.imageName).setAttribute('src', item["src"]);
			$(this.imageUrl).setAttribute('href', item["url"].length > 0 ? item["url"] : this.mainPageUrl);
			$(this.imageDesc).innerHTML = item["desc"];
		
		}.bind(this), 500);
		
		setTimeout(function() {
			
			elements.each(function(element){
				new Effect.Opacity($(element), {
					duration: 0.5,
					from: 0,
					to: 1.0
				});
			}.bind(this))
		}.bind(this), 800);
		
		
		this.index++;
		this.index = this.index > (this.items.size() - 1) ? 0 : this.index;
    }
});


/**
 * Media
 */
Shop.media = Class.create({
	initialize: function(id){
		this.intervalTime = 20;
		
		this.media = $(id);
		this.transparentClass = "transparent";
		
		if(this.media != null) {
			
			this.list = this.media.select('ul').first();
			this.elements = this.media.select('li');
			
			this.widthElements = new Array();
			this.heightElements = new Array();
			for(i = 0; i < this.elements.size(); i++) {
				this.widthElements.push(this.elements[i].getWidth());
				this.heightElements.push(this.elements[i].getHeight());
			}
			
			var width = 0;
			var marginLeft = 0;
			var marginRight = 0;
			for(i = 0; i < this.elements.size(); i++) {
				this.elements[i].writeAttribute('index', i);
				this.elements[i].absolutize();
				
				marginLeft = parseInt(this.elements[i].getStyle("margin-left"));
				marginRight = parseInt(this.elements[i].getStyle("margin-right"));
				
				this.elements[i].setStyle({'left' : width + 'px', 'width' : this.widthElements[i] + 'px', 'height' : this.heightElements[i] + 'px'});
				width += this.widthElements[i] + marginLeft + marginRight;			
			}
			this.width = width;
			
			Event.observe(this.media, 'mouseover', this.stop.bindAsEventListener(this));
			Event.observe(this.media, 'mouseout', this.start.bindAsEventListener(this));
			
			// Add events
			for(i = 0; i < this.elements.size(); i++) {
				Event.observe(this.elements[i], 'mouseover', this.overElement.bindAsEventListener(this));
				Event.observe(this.elements[i], 'mouseout', this.outElement.bindAsEventListener(this));
			}
			
			this.start();
		}
	},
	overElement: function(event) {
		var element = event.element();
		element.removeClassName(this.transparentClass);
	},
	outElement: function(event) {
		var element = event.element();
		if(element.nodeName.toLowerCase() != "img") {
			element.select("img").first().addClassName(this.transparentClass);
		}
		else {
			element.addClassName(this.transparentClass);
		}
	},
	start: function(event) {
		
		this.intervalId = setInterval(function() {
			var elementsLength = this.elements.size();
			for(index = 0; index < elementsLength; index++) {
				
				var element = this.elements[index];
				var left = parseInt(element.getStyle('left'));
				
				if((left * -1) >= element.getWidth()) {
					element.setStyle({'left' : (this.width - element.getWidth()) + "px"});
				} else {
					element.setStyle({'left': (left - 1) + "px" });
				}
			}
			
		}.bind(this), this.intervalTime);
	},
	stop: function(event) {
		
		var element = event.element();
		element.removeClassName(this.transparentClass);
		
		clearInterval(this.intervalId);
	}
});


function addPostParam(sParams, sParamName, sParamValue, sSeparator) {
	if(sParams.length > 0){
		sParams += "&";
	}
	return sParams + encodeURIComponent(sParamName) + "=" + encodeURIComponent(sParamValue);
};

function addURLParam(sURL, sParamName, sParamValue, bRewrite){
	if(typeof bRewrite != "undefined" && bRewrite == true){
		sURL += (sURL.lastIndexOf("/") == sURL.length ? "" : "/");
		sURL += encodeURIComponent(sParamName) + "/" + encodeURIComponent(sParamValue);
	} else {sURL += (sURL.indexOf("?") == -1 ? "?" : "&");
		sURL += encodeURIComponent(sParamName) + "=" + encodeURIComponent(sParamValue);
	}
	return sURL;
}
