// JavaScript Document
var loader = '<img src="/var/images/ico/loader2.gif" alt="czekaj...">';
var domain = '.ekozakupy24.pl';

 // GA
 /*
 var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-8523369-1']);
  _gaq.push(['_trackPageview']);

  (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);
  })();
  */

$(document).ready(function() {


/*
	$(function() {
			// a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore!
			$( "#dialog:ui-dialog" ).dialog( "destroy" );
		
			$( "#dialog-confirm" ).dialog({
				resizable: true,
				height:340,
				width: 245,
				modal: false,
				buttons: {
					"Delete all items": function() {
						$( this ).dialog( "close" );
					},
					Cancel: function() {
						$( this ).dialog( "close" );
					}
				}
			});
		});
*/

	// podpowiedzi
	var fresh = $('#fresh-checker').is(':checked'); 
	
	var bezCukru = '';	
	var bezJaj = '';
	var bezMleka = '';
	
	$('#search-query').click(function() {
		if($('#fresh-checker').is(':checked')) {
			fresh = 1;		
		}
		if($('#bez-cukru').is(':checked')) {
			bezCukru = 1;		
		}
		if($('#bez-jaj').is(':checked')) {
			bezJaj = 1;		
		}
		if($('#bez-mleka').is(':checked')) {
			bezMleka = 1;		
		}
		$("#search-query").keyup().autocomplete ('/application/controllers/search.php?action=autocomplete&fresh='+fresh+'', { minChars: 2 }); 	
	});
						
	// cookie
	if( $.cookie('shopping_view') != null  ) {
		if( $.cookie('shopping_view') == 'show') {
			$('#shopping').show();	
		} else {
			$('#shopping').hide();
		}
	}
	
	//$('#shopping').animate({'bottom': '-422px'}, 500 );
	var setshopp;
	$('#shopping .box-head').click(function() {	
		$('#shopping').hide();
		//$.cookie( 'shopping_view', 'hide' );
		$.cookie( 'shopping_view', 'hide', { expires: 1, path: '/', domain: domain });
//		$.cookie('preference_eko', 'lista');
	});

	$('#sum_shopping .box-head').click(function() {
		if( $('#shopping').css('display') == 'none' ) {
			$('#shopping').show();
			//$.cookie( 'shopping_view', 'show' );
			$.cookie( 'shopping_view', 'show', { expires: 1, path: '/', domain: domain });
		} else {
			$('#shopping').hide();
			//$.cookie( 'shopping_view', 'hide' );
			$.cookie( 'shopping_view', 'hide', { expires: 1, path: '/', domain: domain });			
		}

	});

	
	// plus, minus 
	$('img.plus').click(function() {
		var i = $(this).parent().children('input').val();
			i = parseInt(i);
			
		var j = $(this).parent().children('input');
			if(j.attr('name') == 'weight') {
				var a = 500;
			} else {
				var a = 1;
			}
		$(this).parent().children('input').val( i + a );
	});
	$('img.minus').click(function() {
		var i = $(this).parent().children('input').val();
			i = parseInt(i);

		var j = $(this).parent().children('input');
			if(j.attr('name') == 'weight') {
				var a = 500;
			} else {
				var a = 1;
			}
			
		if(i > 0)
			$(this).parent().children('input').val( i - a );
	});

	// dodwanie do koszyka
	$('button.add_shop').click(function() {
		var id = $(this).attr('id');
		var arrid = id.split("_");
		var type = arrid[0];
		var pid = arrid[1];
		if( $('input#how_'+pid).val() > 0 ) {
			actionShop(this, pid, 'add');
		} else {
			var msg = "Podaj liczbę sztuk lub wagę produktu który chcesz dodać do koszyka";	
			showAlertDialog('Błąd', msg);
		}
	
	});


	$('button.shopping_list').click(function() {
		window.location.href = '/koszyk.html';
	});

	// parametry w wyszukiwrce (pokaz/ukryj)
	if( $('#adv-container').val() != '' ) {
			$(".box-more").show();
	}

	$('.more').click(function() {
		 
		 if( $(".box-more").css('display') == 'block' ) {
			$(this).html('zaawansowane &raquo;'); 
		 } else {
			$(this).html('podstawowe &laquo;'); 
		 }
		 
 		 $(".box-more").toggle();
		 $("#menu-product").toggle();

	});
		
	// menu
	$('#menu-product ul.cat li.greenBold2').click(function() {
		$(this).next('li').slideToggle();
		//alert($(this).next('li').html());
	});

	//alert( $.cookie('preference_eko') );
	listShop();
});



// dodwania do koszyka
function actionShop(el, pid, action) {
	
	$("#msg_info").html( loader ).show();
	
	var action = action;				// action - typ operacji: add, del, update
	var type = 'JSON'; 					
	var productId = pid; 				// product id
	var el = el; 						// obiekt, przycisk
	var number = $('#how_'+pid); 		// ilość szt, waga zamowionego produktu	
	var quantity = 1;
	var weight = 1000;

	if( number.attr('name') == 'quantity' ) {
		var quantity = number.val();
	} else {
		var weight = number.val();
	}

	$.post("/inc/php/shop.cart.php", { 			   
			   "action": action,
			   "return": type,
			   "productId": productId,
			   "quantity": quantity,
			   "weight": weight			   
			   },
			   function(data){
				   $("#msg_info").html( data );
				   setTimeout("$('#msg_info').html('').hide();",3000);
					// wyczytaj liste
					listShop();
				
				}, "json");
}

function actionBtnShop(pid, action, units, page) {
	
	$("#msg_info").html( loader ).show();
	
	var action = action;				// action - typ operacji: add, del, update
	var type = 'JSON'; 					
	var productId = pid; 				// product id
	var page = page;
//	var el = el; 						// obiekt, przycisk
//	var number = $('#how_'+pid); 		// ilość szt, waga zamowionego produktu	
	if(units == 'quantity') {
		var quantity = 1;
		var weight = 0;
	} else {
		var quantity = 1;
		var weight = 1000;
	}

//	if( number.attr('name') == 'quantity' )
//		var quantity = number.val();
//	else 
//		var weight = number.val();

	$.post("/inc/php/shop.cart.php", { 			   
			   "action": action,
			   "return": type,
			   "productId": productId,
			   "quantity": quantity,
			   "weight": weight			   
			   },
			   function(data){
				   $("#msg_info").html( data );
				   setTimeout("$('#msg_info').html('').hide();",3000);
					// wyczytaj liste
					listShop();
									
					if(page == 'list') {
						window.location.reload(true);
					} 			
					
					//if ( $.browser.msie ) {
						//window.location.reload(true);
					 //} 

					
				
				}, "json");
}


// lista zakupów koszyk
function listShop() {
	//alert('b');				   
	//return false;
	var action = 'list-shop-ajax';				// action - typ operacji: add, del, update
	var el = $('#products_list'); 			// obiekt
	var type = 'JSON';
		
	var date = new Date();
	//date.getTime();
	
	$.getJSON("/inc/php/shop.cart.php", { 			   
			   "action": action,
			   "return": type,
			   "timestamp":date.getTime()
			   },
			   function(json){

					var list_shop ='';
					el.html('');
					
					$.each(json['info'], function(index, itemData) {

						if(itemData.is_weight == 1) {
							var no = itemData.weight +'g';
							var units = 'weight';
						} else {
							var no = itemData.quantity;
							var units = 'quantity';
						}						
						//	$('#dialog_exec_time').html('<h6>Czas wyszukiwania '+ json.data.time +' s.</h6>');

					    //listshop +='<div class="grid zebra1">';
						list_shop ='<div class="grid bold title"><a href="/produkt/'+ itemData.product_id +'/'+ itemData.www_name +'">'+ itemData.name +'</a></div>';
						list_shop +='<div class="grid_5 icon"><img src="/var/images/ico/plus0.png" alt="+" onclick="actionBtnShop('+itemData.product_id+', \'add\', \''+units+'\');"> <img src="/var/images/ico/minus1.png" alt="-" onclick="actionBtnShop('+itemData.product_id+', \'del\', \''+units+'\');"></div>';
						list_shop +='<div class="grid_11 grey">'+no+' x  '+itemData.price+' PLN</div>';
						list_shop +='<div class="grid_8 price">'+ itemData.products_price +' PLN</div>';
						//listshop +='</div>';
						
						$('<div/>').addClass('grid zebra1').html( list_shop ).appendTo( el );
						
				    });

					if(json.count.free_delivery <= 0) {
						var free_delivery = 0;	
					} else {
						var free_delivery = json.count.free_delivery;	
					}

					$('#products_value').html( json.count.products_value + ' PLN' );
					$('#free_delivery').html( free_delivery + ' PLN' );
					$('#products_count').html( json.count.products_count );

				/*

					if(data.err) {
						$('#head').animate({opacity: 1}, 500 );
						$("#footer").animate({opacity: 1}, 500 );
						$("#pass").val('');
						showMsg(data.err);
					} else {
						showMsg('Czekaj');
						if(data.page) {
							if(data.page == '/login.html') {
							location.href = "/index.php";
							} else {
							location.href = data.page;	
							}
						} else {
							location.href = "/index.php";
						}
					}
					*/

				});
}


// okno alert - toplayer UI jQuery
function showAlertDialog(title, txt, width, height, append) {
		
		$("#dialog-modal:ui-dialog").dialog("destroy");
		
		if(height)
		var _height = height;
		else 
		var _height = 'auto';
		
		if(width)
		var _width = width;
		else
		var _width = 300;
		
		$( "#dialog-message" ).dialog({
							resizable: false,
							width: _width,
							height: _height,
							modal: true,
							closeOnEscape: true,
							open: function(event, ui) { 
								if(title)
								$('span#ui-dialog-title-dialog-message').text(title);
								
								if(txt)
								$('div.dialog-context').html('<h5>'+txt+'</h5>');
								
								if(append)
								$('<div/>').addClass('grid_24').html(append).appendTo('div.dialog-context');
							},
							buttons: {
								Ok : function() {
									$( this ).dialog( "close" );
									//deleteRecord(element);
									}
							}
						});
		
}

function alertDialog (msg) {
	
	$( "#dialog:ui-dialog" ).dialog( "destroy" );
	
		$( "#dialog-message" ).dialog({
			modal: true,
			buttons: {
				Ok: function() {
					
					$('#dialog-message').html( msg );
					
					$( this ).dialog( "close" );
				}
			}
		});
}

