
// add product to cart
addtocart = function(idProduct, el, attributes, redirectlink) {
    
	// to json not allowed
	// try hack
	var a = {};
	for (var i = 0, len = attributes.length; i < len; i++) {
		a['attributes[' + i + ']'] = attributes[i];
	}

    $(el).effect("transfer", {
        className: 'ui-effects-transfer',
        to: "div#cart-storage"
    }, 1500);
    
	a.idProduct = idProduct;
	a.retrieve = !redirectlink;
	
    jQuery.post(
        Core.basepath + '/json/default/cart/addToCart/',
		a, 
        function(response) {
            if (response.success == true) {
				if (redirectlink) {
					window.location.href = Core.basepath + redirectlink;
				}
				
				var dl = $("div#cart-storage > dl");
				dl.find('dd').remove();
				var dds = [];
				for(var i = 0; i < response.basketCollection.length; i++) {
					var dd = response.basketCollection[i];
					dds.push('<dd><a href="' + dd.link + '">' + dd.title + ' x ' + dd.count + '</a></dd>');
				}
				dl.append(dds.join("\n"));
            }
        }, 
    'json');
};

price_recalculate = function() {
    var a = $("select[name^=attribute]");
    var price = 0;
    a.each(function(i, cmp) {
            var option = $(cmp.options[cmp.selectedIndex]);
            var value = parseInt(option.attr('price'), 10);
            if (!isNaN(value)) {
                price += value;
            }   
    });
    var value = parseInt($('input#start_product_price').val(), 10);
    if (!isNaN(value)) {
        $('span#product_price').html(value + price);
    }
};

collect_attribute_values = function() {
	var a = $("select[name^=attribute]");
    var values = [];
    a.each(function(i, cmp) {
            values.push($(cmp).val());
    });
    return values;
};

Product = function() {
	return {
		addToCompare: function(id, totalId, groupCls) {
			jQuery.post(Core.basepath + '/json/default/compare/add/', {
				idProduct: id
			}, 
            function(response) {
                $('#' + totalId).html(String(response.total));
				$('.' + groupCls).toggle();
            }, 
            'json');
		},
		
		removeFromCompare: function(id, totalId, groupCls) {
            jQuery.post(Core.basepath + '/json/default/compare/deleteAjax/', {
				idProduct: id
			}, 
            function(response) {
                $('#' + totalId).html(String(response.total));
                $('.' + groupCls).toggle();
            }, 
            'json');
		},
		
		fancybox: function(){
			// change product photo
			var list = $('ul#product-image-gallery');
			var active = $($('ul#product-image-gallery > li').get(0));
			active.addClass('current');
			var image = $('img#product-full-image');
			var a = $('ul#product-image-gallery > li > a');
			a.click(function(){
				image.attr('src', this.href);
				active.removeClass('current');
				var parent = $(this).parent();
				parent.addClass('current');
				active = parent;
				return false;
			});
			image.attr('src', active.find('a').attr('href'));
			image.fancybox({
				'itemLoadCallback': function(opts){
					var imgUrl = active.find('span').html();
					opts.itemArray.push({
						url: imgUrl,
						title: active.find('img').attr('alt') || undefined
					});
					
					a.each(function(i){
						var url = $(this).parent().find('span').html();
						if (imgUrl == url) 
							return true;
						opts.itemArray.push({
							url: url,
							title: $(this).parent().find('img').attr('alt') || undefined
						});
					});
				}
			});
		},
		
		rate: function(rate, idProduct) {
			jQuery.post(Core.basepath + '/json/default/rating/rate/', {
				rate: rate,
                idProduct: idProduct
            }, 
            function(response) {
				var ul = $('#ratig-layer-' + idProduct + ' > div > ul');
				$(ul).find('li').each(function(i, li) {
	                if (!$(li).hasClass('current-rating')) {
						$(li).remove();
					} else if (true == response.success) {
						var rating = response.rating;
						$(li).width(17 * rating);
						$(li).html(rating);
					}
				});
            }, 
            'json');
		}
	};
}();

Location = {};
Location.combo = function(cfg) {
	
	this.otherCaption = null;
	this.otherId = null;
	
	this.countryOriginal = null;
	this.regionOriginal = null;
	this.cityOriginal = null;
	this.autoLoad = false;
	
	cfg = cfg || {};
	// something like Ext.applyIf
	for(var i in cfg) {
		if (!this[i]) {
			this[i] = cfg[i];
		}
	}
	
	this.country = $('#combocountry');
	this.region = $('#comboregion');
	this.city = $('#combocity');
	
	this.altcountry = $('#alternatecountry');
	this.altregion = $('#alternateregion');
	this.altcity = $('#alternatecity');
	
	var self = this;
	
	this.country.change(function(e) {
		if (self.otherId == self.country.val()) {
		    self.disableRegion();
			self.showAltCountry();
//			Shipping.clear();
		} else {
			self.enableRegion();
			self.hideAltCountry();
			self.loadRegions(self.country.val());
		}
	});

    this.region.change(function(e) {
		if (self.otherId == self.region.val()) {
			self.showAltRegion();
			self.disableCity();
		} else {
			self.enableCity();
			self.hideAltRegion();
			self.loadCities(self.country.val(), self.region.val());
		}
//		Shipping.clear();
	});	
	
	this.city.change(function() {
		if (self.otherId == self.city.val()) {
			self.showAltCity();
		} else {
			self.hideAltCity();
		}
//		Shipping.clear();
	});
        
    if (this.autoLoad) {
		this.country.one('load', function() {
			self.loadCountries();
		});
	}    
    Location.combo.constructor.call(this);
};


Location.combo.prototype = {
	
	disableRegion: function() {
		this.region.attr('disabled', true);
        this.showAltRegion();
		this.region.empty();
		this.region.get(0).options.add(new Option(this.otherCaption, this.otherId));
		this.disableCity();
	},
	
	enableRegion: function() {
		this.region.removeAttr('disabled');
		if (this.otherId == this.region.val()) {
			this.showAltRegion();
		} else if (this.region.get(0).options.length > 0) {
			this.hideAltRegion();
		}
	},
        
    disableCity: function() {
        this.city.attr('disabled', true);
        this.city.empty();
        this.city.get(0).options.add(new Option(this.otherCaption, this.otherId));
        this.showAltCity();
    },
    
    enableCity: function() {
        this.city.removeAttr('disabled');
        if (this.otherId == this.city.val()) {
            this.showAltCity();
        } else if (this.city.get(0).options.length > 0) {
            this.hideAltCity();
        }
    },
	
	showAltCountry: function() {
		this.altcountry.show();
        this.altcountry.removeAttr('disabled');
	},
	
	hideAltCountry: function() {
		this.altcountry.hide();
		this.altcountry.val("");
        this.altcountry.attr('disabled', true);
	},
	
	showAltRegion: function() {
		this.altregion.show();
        this.altregion.removeAttr('disabled');
	},
	
	hideAltRegion: function() {
		this.altregion.hide();
		this.altregion.val("");
        this.altregion.attr('disabled', true);
	},
	
	showAltCity: function() {
		this.altcity.show();
		this.altcity.removeAttr('disabled');
	},
	
	hideAltCity: function() {
		this.altcity.hide();
        this.altcity.val("");
        this.altcity.attr('disabled', true);
	},
	
	loadCountries: function() {
		
		var country = this.country;
		var value = this.countryOriginal;
		var self = this;
        
		jQuery.post(Core.basepath + '/json/default/location/getCountries/', {}, 
		function(response) {
            country.empty();
            var dom = country.get(0);
            var selected = false;
			var hasSelected = false;
            jQuery.each(response.rows, function(i, row) {
                if ((value == row.country_id)
				 || (!value && row.selected == true)
				 ) {
				 	hasSelected = true;
                    selected = true;
                } else {
					selected = false;
				}

                var o = new Option(row.name, row.country_id, null, selected);
                dom.options.add(o);
            });
            dom.options.add(new Option(self.otherCaption, self.otherId, null, !hasSelected));
            country.trigger('change');
        }, 
        'json');
	},
	
	loadRegions: function(idCountry) {
		var region = this.region;
		var value = this.regionOriginal;
		var self = this;

		jQuery.post(Core.basepath + '/json/default/location/getRegions/', {
			countryId: idCountry
		}, function(response) {
			region.empty();
			var dom = region.get(0);
			var selected = false;
			var hasSelected = false;
			jQuery.each(response.rows, function(i, row) {
				if (value == row.region_id || (!value && row.selected == true)) {
					hasSelected = true;
					selected = true;
				} else {
					selected = false;
				}
				var o = new Option(row.name, row.region_id, null, selected);
				dom.options.add(o);
			});
			dom.options.add(new Option(self.otherCaption, self.otherId, null, !hasSelected));
			region.trigger('change');
		}, 
		'json');
	},

    loadCities: function(idCountry, idRegion) {
	    var city = this.city;
		var self = this;
		var value = this.cityOriginal;
		jQuery.post(Core.basepath + '/json/default/location/getCities/', {
            countryId: idCountry,
			regionId: idRegion
        }, function(response) {
			city.empty();
            var dom = city.get(0);
			var selected = false;
			var hasSelected = false;
            jQuery.each(response.rows, function(i, row) {
				if (value == row.city_id || (!value && row.selected == true)) {
					hasSelected = true;
					selected = true;
				} else {
					selected = false;
				}
                var o = new Option(row.name, row.city_id, null, selected);
                dom.options.add(o);
            });
			dom.options.add(new Option(self.otherCaption, self.otherId, null, !hasSelected));
			city.trigger('change');
        }, 
        'json');
	}
};

Shipping = function() {
	
	return {
		
		fetch: function() {
			return $('#shippingtypes input[name=shippings]');
		},
		
		fetchPriceCaption: function(id) {
			return $('#shipping_price_' + id);
		},
		
		check: function(location) {
//			this.clearAll();
			var self = this;
			var p = {};
			if (location) {
				p = {
					country: location.country.val(),
	                region: location.region.val(),
	                city: location.city.val()
				};
			}
			jQuery.post(Core.basepath + '/json/default/order/shippingtype/', p, 
			function(o, success){
				self.checkCallback(o, success);
			}, 'json');
		},
		
		checkCallback: function(o, success) {
			if (true !== o.success) {
                this.clearAll();
                this.disableAll();
                return;
            }
			
            var types = o.types;
			var self = this;
			
            this.fetch().each(function(i, el) {
                var input = $(el);
				var id = parseInt(input.val(), 10);
				var disabled = true;
				var price = 0;

				for (var i = 0, len = types.length; i < len; i++) {
					
	                if (id == types[i].id) {
						disabled = false;
						price = types[i].price;
					}
	            }
				
				self.fetchPriceCaption(input.val()).html(String(price) + ' ' + o.abbreviation);
				if (disabled) {
					input.removeAttr('checked');
					input.attr('disabled', true);
				} else {
					input.removeAttr('disabled');
				}
		    });
		},
		
		disableAll: function() {
			this.fetch().each(function(i, el) {
                $(el).attr('disabled', true);
            });
		},
		
		clearAll: function() {
			this.fetch().each(function(i, el) {
				$(el).attr('checked', false);
			});
		},
		
		save: function(radio) {
			jQuery.post(Core.basepath + '/json/default/order/shipping/', {
		        shipping: $(radio).val()
		    }, function(o, success) {}, 'json');
		},
		
		saveAddress: function() {
		    var form = $('[name=location]');
		    var params = {};
		    form.find('input,select').each(function(i, el) {
		            var element = $(el);
		            if (element.attr('disabled') || -1 == element.val()) {
		                return;
		            }
		
		            params['address[' + element.attr('name') + ']'] = element.val();
		    });
		
		    jQuery.post(Core.basepath + '/json/default/order/contact/', 
		        params, 
		        function(o, success) {
		        if (o.success == true) {
		            $('#order_address').html(o.completeAddress);
		            $('#order_address_helper > div').toggle();
		        }
		    }, 'json');
		}
	};
}();

Payments = function() {
	
	return {
		savePayments: function(radio){
            
			jQuery.post(Core.basepath + '/json/default/order/payments/', {
				payments: $(radio).val()
			}, function(o, success){
				if (true !== o.success) {
					$(radio).attr('checked', false);
				}
				
				$('input[name=payments]').each(function(i, input) {
                    var c = $(input);
					var checked = $(radio).val() == c.val();
					$('#payment_' + c.val()).find('input[type=radio]').each(function(j, item) {
						if (checked) {
						   $(this).removeAttr('disabled');	
						} else {
							$(this).attr('disabled', true);
							$(this).attr('checked', false);
						}
                    });
                });
			}, 'json');
		},
		
		savePurse: function(radio){
			
			jQuery.post(Core.basepath + '/json/default/order/payments/', {
				purseid: $(radio).val()
			}, function(o, success){
				if (true !== o.success) {
					$(radio).attr('checked', false);
				}
			}, 'json');
		},
		
		saveCashless: function(radio) {
			
			jQuery.post(Core.basepath + '/json/default/order/payments/', {
                cashlesstypeid: $(radio).val()
            }, function(o, success){
                if (true !== o.success) {
                    $(radio).attr('checked', false);
                }
            }, 'json');
		}
	};
}();

Commentary = function() {
	return {
		click: function(element, showEl, hideEl) {
			
			var parent = $(element).parent();
			if (parent.hasClass('current')) {
				return;
			}
			
			$('#' + showEl).hide();
			$('#' + hideEl).show();
			parent.parent().children().each(function(i, el) {
                $(el).removeClass('current');
            });
			parent.addClass('current');
		}
	};
}();

