/**
 *	SMC Main JavaScript file that holds app-wide classes and methods
 *	@author Marcel Eichner // Ephigenia <love at ephigenia dot de>, modified by Martin Piske
 *	@since 2008-02-18
 */
function updateShoppingList() {
		$.ajax({
			 	 type: 'POST'
				,url: '/ajax/countShoppingList/'
				,dataType: 'json'
				,timeout: 1000
				,cache: true
				,success: function(response) {
					
					if(response == 0) {
						
						$('#countShoppingList').html('0');
					}
					else {
						$('#countShoppingList').html('<strong>'+response+'</strong>');
					}
				}
				
					
					
			});
	}
	function addToShoppingList(id,type) {
		
			$.ajax({
			 	 type: 'POST'
				,url: '/ajax/addToShoppingList/' + id + '/'
				,dataType: 'json'
				,timeout: 1000
				,cache: true
				,success: function(response) {
					
					
					if(response == 'saved') {
						updateShoppingList();
						
						$('#addToShoppingList'+id).html('<span style="padding:3px;font-size:10px;font-weight:bold;color:#fff;background-color:#b3d400;">gespeichert</span>');
						
					}
				}
					
					
					
			});
			
			
		}

// change userZip
function changeUserZip(zip) {
		
			$.ajax({
			 	 type: 'POST'
				,url: '/ajax/changeUserZip/' + zip + '/'
				,dataType: 'json'
				,timeout: 1000
				,cache: true
				,success: function(response) {
					
					
					if(response == 'saved') {
						
						
						$('#userZipMessage').html('<span style="padding:3px;font-size:10px;font-weight:bold;color:#fff;background-color:#b3d400;border:1px solid #fff;">gespeichert</span>');
						
						window.setTimeout("$('#userZipMessage').html('')", 2000);
						
						location.reload();
					}
				}
					
					
					
			});
			
			
}

$(document).ready(function() {
	
	updateShoppingList();
	
	/** simple sanitizing for strings **/
	function sanitize(input) {
		input = input.replace(/(^\s+|\s+$)/g, '');
		input = input.replace(/[^-\._A-Za-z0-9 ßöäüÖÄÜéèÉÈáàÁÀóòÓÒúùÚÙíìÍÌ]/g, '');
		input = input.replace(/\s{2,}|_/g, ' ');
		return input;
	}
	
	/** Delayed keyup event **/
	$.fn.keyupDelayed = function (timeout, callopen, callclose) {
		return this.each(function() {
			var t;
			$(this).keyup(function() {
				if ($(this).val().length > 0) {
					t = setTimeout(callopen, timeout);
				} else {
					clearTimeout(t);
					if (callclose) {
						callclose();
					}
				}
			});
			$(this).keydown(function() {
				clearTimeout(t);
			});
		});
	}
	
	
	
	/** SupermarketSearchBar JS **/
	$('#supermarketSearchBar form').submit(function() {
		supermarketSearchSubmit('bar');
		return false;
	});
	$('#chainSupermarketSearch form').submit(function() {		
		supermarketSearchSubmit('chain');
		return false;
	});
	$('#productSupermarketSearch form').submit(function() {		
		supermarketSearchSubmit('product');
		return false;
	});
	function supermarketSearchSubmit(sourceForm) {
		if (sourceForm == "bar") {
			var street = sanitize($('#SearchStreet').val());
			var cityOrZip = sanitize($('#SearchCityOrZip').val());
		}
		else if (sourceForm == "chain") {
			var street = sanitize($('#SearchStreet2').val());
			var cityOrZip = sanitize($('#SearchCityOrZip2').val());
			var chainId = sanitize($('#SearchChainId').val());
		}
		else if (sourceForm == "product") {
			var cityOrZip = sanitize($('#SearchCityOrZip2').val());
			var chainId = $('#SearchChainId').val();
		}
		else {
			var street = "";
			var cityOrZip = "";
		}
		
		if (street == 'Straße Nr. optional') street = '';
		if (cityOrZip.substr(0,3) == 'PLZ') cityOrZip = '';
		// parse stuff to beautify the search query
		if (cityOrZip.match(/^\d+$/)) {
			var zip = cityOrZip;
		} else if (cityOrZip.match(/^([\D]+(\s+)?)+$/)) {
			var city = cityOrZip; 
		} else if (found = cityOrZip.match(/(?:\s+)?(\d+)?[-,._\s]?([\D\s]+)?(?:\s+)?(\d+)?/)) {
			if (!isEmpty(found[1])) {
				var zip = found[1];
			}
			if (!isEmpty(found[2])) {
				var city = found[2];
			}
			if (!isEmpty(found[3])) {
				var zip = found[3];
			}
		}
		var q = '';
		if (!isEmpty(street)) {
			q = street;
		}
		if (!isEmpty(zip)) {
			if (isEmpty(q)) {
				q += 'DE '+zip;
			} else {
				q += ', ' + zip;
			}
		}
		if (!isEmpty(city)) {
			if (isEmpty(q)) {
				q += city;
			} else {
				q += ', ' + city;
			}
		}
		if (isEmpty(q)) return false;
		$('#supermarketSearchBar #load').css('display', 'inline');
		var GMap = new GClientGeocoder(false);
		GMap.getLatLng(q, function(result) {
			$('#supermarketSearchBar #load').hide();
			if (!result) {
				document.location.href = '/supermaerkte/suche/leer/';
				return false;
			}
			newURL = new AppURLBuilder('/supermaerkte/suche/');
			newURL.data['lng'] = result.lng();
			newURL.data['lat'] = result.lat();
			if (!isEmpty(street)) {
				newURL.data['street'] = street;
			}
			if (!isEmpty(zip)) {
				newURL.data['zip'] = zip;
			}
			if (!isEmpty(city)) {
				newURL.data['city'] = city;
			}
			if (sourceForm == "chain") {
				newURL.data['chain'] = chainId;
			}
			if (sourceForm == "product") {
				newURL.data['chain'] = chainId;
				newURL.data['view'] = 'mapOnly';
			}
			var urlToOpen = newURL.toString();
			if (sourceForm == "product") {
				
				overlay.load(urlToOpen);
			}
			else {
			
				document.location.href = urlToOpen;
			}
		});
		return false;
	}
	
	/** supermarketSearchBar **/
	function emptyFocusBlur() {
		if ($(this).val().substring(0,3) == 'PLZ' || $(this).val() == 'Straße / Nr. (optional)') {
			if (!isEmpty($(this).val())) {
				this.lastVal = $(this).val();
			}
			$(this).val('');
			$(this).addClass('active');
			$(this).blur(function() {
				if (!isEmpty(this.lastVal) && isEmpty($(this).val())) {
					$(this).val(this.lastVal);
					if ($(this).val().substring(0,3) == 'PLZ' || $(this).val() == 'Straße / Nr. (optional)') {
						$(this).removeClass('active');
					}
				}
			});
		}
	}
	
	
	
	if ($('#SearchCityOrZip').length > 0) {
		$('#SearchCityOrZip').focus(emptyFocusBlur);
		$('#SearchStreet').focus(emptyFocusBlur);
		if ($('#SearchCityOrZip').val().substring(0,3) != 'PLZ') {
			$('#SearchCityOrZip').addClass('active');
		}
		if ($('#SearchStreet').val() != 'Straße / Nr. (optional)') {
			$('#SearchStreet').addClass('active');
		}
	}
	
	/** url builder **/
	var AppURLBuilder = function(url) {

		this.data = new Object();
		this.url = (url) ? url : '';
		
		this.toString = function() {
			if (this.url.substr(-1,1) != '/') {
				this.url += '/';
			}
			return this.url + this.buildQueryString();
		}
		
		this.buildQueryString = function(data) {
			if (!data) {
				data = this.data;
			}
			if (data.length == 0) {
				return '';
			}
			var ret = '';
			for (index in data) {
				var val = String(data[index]);
				ret += index + ':' + val.replace(/\s/g, '+') + '/';
			}
			return ret;
		}
	}
	
	
	
});
/** product details tab functions **/
function pictureTab(source,id) {
	$('#pictureTabsContent').load('/product/picture-tab/'+source+'/'+id+'/');
	if(source == 1) {
		$('#pictureTabProducer').removeClass();
		$('#pictureTabUser').addClass('active');
	}
	else if(source == 2) {
		$('#pictureTabUser').removeClass();
		$('#pictureTabProducer').addClass('active');
	}
}
function opinionTab(tab,id) {
	if(tab == 1) {
		$('#opinionTabsContent').load('/product/opinion-tab-user/'+id+'/');
		$('#opinionTabTest').removeClass();
		$('#opinionTabUser').addClass('active');
	}
	else if(tab == 2) {
		$('#opinionTabsContent').load('/product/opinion-tab-test/'+id+'/');
		$('#opinionTabUser').removeClass();
		$('#opinionTabTest').addClass('active');
	}
}
function priceTab(id) {
	$('#priceTabsContent').load('/product/price-tab/'+id+'/');
	$('#priceSummaryTab').removeClass();
	$('#priceTab').addClass('active');
}

function priceSummaryTab(id) {
	$('#priceTabsContent').load('/product/price-summary-tab/'+id+'/');
	$('#priceTab').removeClass();
	$('#priceSummaryTab').addClass('active');
}



function productsProducerFormChanged()
{

	//$("#productsForm").submit();
}

function productsChainFormChanged()
{
	var f = $("#productsForm");
}

function productsFormChanged()
{
	var f = $("#productsForm");
	
	var produid  = $('#formProducerId').val();
	var chainid  = $('#formChainId').val();
	var packid   = $('#formPackageId').val();
	var url      = $('#productsFormLink').val();
		
	if (produid != -1)
	{
		url += 'producer_id:' + produid + '/';
	}
	
	if (chainid != -1)
	{
		url += 'chain_id:' + chainid + '/'; 
	}
	
	if (packid != -1)
	{
		url += 'package_id:' + packid + '/';
	}
	
	document.location.href = url;
	
}



/**
* productSearch focus
*/

var productSearchBarDefaultText = 'z.B. Pizza oder Dr. Oetker';

function productSearchBarFocusChange()
{
	$('#productSearchBar form #q').val = 'hello';
}

function productSearchBarOnFocus()
{
	var q = $('#productSearchBar form #q');
	
	//if default helptext, clear on focus
	if ( q.val() == productSearchBarDefaultText || q.val() == '' )
	{
		//clear field
		q.val('');
		q.addClass('active');
	}	
}

function productSearchBarOnBlur()
{
	var q = $('#productSearchBar form #q');
	
	//if its empty, set to default helptext
	if ( q.val() == '' )
	{
		q.val(productSearchBarDefaultText);
		q.removeClass('active');
	}
}

function productSearchBarOnClick()
{
	var q = $('#productSearchBar form #q');

	if ( q.val() == productSearchBarDefaultText )
	{
		q.val('');
	}

}

// Price Loader
function showPrice(id,type) {
	if(type == 'rise') {
		var div = '#priceRiseBox';
	}
	else {
		var div = '#priceReductionBox';
	}
	if(id == 0) {
		var strId = '';
	}
	else {
		var strId = '/id:' + id;
	}
	$(div).load('/price/view' + strId + '/type:' + type + '/', function() { 
		$(div).fadeIn("slow"); 
	});
}


