/* Function needed for beautifing buttons */
function buttonEndings(){
  if(!document.getElementsByTagName) {
    return false;
  }
  
  /* loop through all buttons and attach a div */
  $('<div class="buttonEnding"></div>').insertAfter($(".button"));
  $('<div class="buttonEnding"></div>').insertAfter($(".buttonBuy"));
}
/* Function needed for beautifing buttons */

// Track Google analytics event (no need to wait for document being ready)
(function() {
	var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
	ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
	var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
// End of analytics tracking

$(document).ready(function(){
	// Save cid value
	main.cid = cid;
	
	// Assign url to onclick in category menu
	$('#menuCategories div a').each(function (i){
		$(this).parent().attr('href', $(this).attr('href'));
		
		// Adding event to upper element <DIV>
		$(this).parent().click(function () { 
		  document.location.href = $(this).attr('href');
		});
	});
	
//	initZoom();
	
	if($('#country').length > 0 && $('#country').val()){
		$('#country').change(); // Call onchange event to execute all needed procedures
	}
});

/* Main object */
var main = {
	removeProductFromCart: function(id, variant_id){ // Remove product from cart
		$.get('bin.php?cid=' + main.cid + '&lang_id=en', {'action': 'shop.removeProduct', 'product_id': id, 'variant_id': variant_id}, function(data, textStatus){
			if(data.contents){
				for(i in data.contents){
					$('#' + i).slideUp('fast', function(){
						$('#' + i).html(data.contents[i]).slideDown('fast');
						
						// Add button endings
						buttonEndings();
					});
				}
			}
		}, 'json');
		return;
	
		var h = document.location.href;
		document.location.href = h + (h.indexOf('?') == -1 ? '?' : '&') + 'action=shop.removeProduct&product_id='+parseInt(id);
		return false;
	},
	
	addProductToCart: function(id, quantity, variant_id, overwriteQS){ // Add product to cart
		var qs = 'action=shop.addProduct';
		
		$.get('bin.php?cid=' + main.cid + '&lang_id=en&' + qs, {'product_id': id, 'variant_id': variant_id, 'quantity': quantity}, function(data, textStatus){
			if(data.contents){
				for(i in data.contents){
					$('#' + i).slideUp('fast', redrawBlock(i, data.contents[i]));
				}
			}
		}, 'json');
		return;
	},
	
	setCurrency: function(currency){ // Remove product from cart
		var h = document.location.href;
		document.location.href = h + (h.indexOf('?') == -1 ? '?' : '&') + 'action=shop.setCurrency&currency='+currency;
		return false;
	},
	
	selectLogistic: function(region){
		var shown; 
		$('.logistic').slideUp();
		if(region){
			$('.deliveryMethodLabel').slideDown();
		
			for(logistic in region){
				if(prices[region[logistic]] == 0){ // Skip logistics where we cannot deliver (price set to 0)
					continue;
				}
				
				$('.lid' + logistic).slideDown();
				$('#price' + logistic).text(prices[region[logistic]]);
				$('#description' + logistic).text(descriptions[region[logistic]]);
				$('#logistic' + logistic).val(region[logistic]);
				
				if(!shown){
					$('.lid' + logistic + ' input[type="radio"]').attr("checked", "checked");
					main.selectDeliveryType($('.lid' + logistic + ' input[type="radio"]').val()); // Calculate price of first zone
					shown = true;
				}
			}
		}
		
		// Remove default zone after first selection. it is unneeded to select
		$('#country').find('option[value=""]').remove();
		$('#readonlyCountry').val($('#country').val());
	},
	
	selectDeliveryType: function(zoneId){
		$('#totalPrice').text($.format('{0:.2f}', cartValue + parseFloat(prices[zoneId])) + ' ' + currency);
		$('#zoneId').val(zoneId);
		if(!main.deliverySelected){
			main.deliverySelected = true; // Cache it and don't do again for performance
			$('#totalOrderPriceLabel').slideDown('fast');
		}
	},
	
	validate: function(form){
		var valid = true;
		
		$(form).find('.required').each(function(){
			if(!this.value){
				$(this).attr('style', 'background-color: #FFF8EC');
				valid = false;
			}
		});
		
		$(form).find('.required.email').each(function(){
			if(!this.value.match(/^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/)){
				$(this).attr('style', 'background-color: #FFF8EC');
				valid = false;
			}
		});
		
		return valid;
	},
	
	saveFormToCookie: function(form){
		jQuery.each($(form).serializeArray(), function(){
			$.cookie(this.name, this.value, { expires: 100000 }); 
		});
	}
}

function txt(label){
	return txts[label] ? txts[label] : '{no label "'+label+'"}';
}

function redrawBlock(i, html){
	return function(){
		$('#' + i).html(html);
		$('#' + i).slideDown('fast');
		
		// Add button endings
		buttonEndings();
	}
}

/* Add button endings */
buttonEndings();