$('.close , .closeModal').live('click',function () {
    $(this).parents(".modal").modal('hide');
});



$(function(){
	$("body").ajaxError(function(a,xhr) {
		if(xhr.responseText == 'logout')
			location.reload();
		else if(xhr.responseText == 'noAdmin')
			location.href = "/";
	});
	$('.modal input').keypress(function(e) {
        if(e.which == 13) {
            $(this).blur();
            $(this).parents(".modal").find(".submit").focus().click();
        }
   });
   $(".modal").modal({
      backdrop: true,
      modal: true
  });
  var fillCategorieSelect = function (categories) {
		$.each(categories, function (i, categorie) {
			var optgroup = $('<optgroup>', {
				label: categorie.naam
			});
			$.each(categorie.children, function (i, subCategorie) {
				optgroup.append(
					$('<option>', {
						text: subCategorie.naam,
						value: subCategorie.id
					})
				);
			});

			$("#userSettingsWindow  fieldset.notifications select").append(optgroup);
		});
		$("#userSettingsWindow  fieldset.notifications select").multiselect({});
	}
	
	
	
  $("#settingsMenuItem").click(function(){
  	 $("#userSettingsWindow").modal('show');
  	 $("#userSettingsWindow  fieldset.notifications div").remove();
  	 $.ajax({
            url: '?ajax=true&action=getUserSettings&module=user',
            dataType: 'json',
            success: function (data) {
            	$("#userSettingsWindow #settingsUserName").val(data.user.name);
                $("#userSettingsWindow #settingsUserEmail").val(data.user.email);
                $("#userSettingsWindow #emailRate").val(data.user.emailRate);
                
            	$.each(data.brands,function(i,brand){
            		$("#userSettingsWindow  fieldset.notifications").append('<div class="clearfix"><label for="userPassword">'+brand.name+'</label><div class="input"><select  name="notification['+brand.id+']" multiple="multiple" brandId="'+brand.id+'"></select></div></div>');
            	});
            	fillCategorieSelect(data.categories);
            	
            	
            	$.each(data.selectedNotifications,function(i,notification){
            		$("select[brandId="+notification.brandId+"]").multiselect("widget").find(":checkbox[value="+notification.categoryId+"]").click();
            	});
            }
     });
	$("#userSettingsWindow .submit").unbind('click').click(function () {
		var categories = {}
		$("#userSettingsWindow").modal('hide');
		$("#userSettingsWindow  fieldset.notifications select").each(function(i,select){
			var select = $(this);
			var selected = $.map(select.multiselect("widget").find("input:checked"), function(checkbox){return checkbox.value;}).join(",");
			if(selected.length > 0)
				categories[$(this).attr("brandId")] = selected;
		});
		$.ajax({
            url: '?ajax=true&module=user&action=editUserSettings',
            type: "POST",
            data: $("#userSettingsWindow form .send").serialize() + '&notifications=' + $.toJSON(categories),
            dataType: 'json',
            success: function (data) {
				
                //updateUserTable();
            }
        });
                    
	});  
  });
   
 	$("li.notifications").click(function(){
		$("#notificationsPopover").toggle();
		if($("#notificationsPopover:visible").length){
			$("#notificationsCount").text(0);
			$("#notificationsPopover .content").empty()
			$.ajax({
		        url: '?ajax=true&module=products&action=getNotifications',
		        type: "POST",
		        dataType: 'json',
		        success: function (data) {
					//var html = '<table class="zebra-striped">';
					var table = $("<table>",{'class':'zebra-striped'});
                  	$.each(data.changes, function (i, change) {
                  		var tr = $("<tr>");
                  		
                      	var html = '<td class="'+change.priceClass+'">&euro;&nbsp;' + change.price+'</td>';
                      	html += '<td class="'+change.portoClass+'">';
                      	if (change.porto > 0){
                      		html += '+&euro;&nbsp;' + change.porto;
                      	}
                      	html += '</td>';
						html += '<td>' + change.brandName+' ' + change.productName+' ' + change.colorName+'</td>';
						html += '<td>' + change.companyName+'</td>';
						tr.html(html).hover(
							function(e){
								var tdposition = $(e.target).offset();
								var tableposition = $('#notificationsPopover').offset();
								$('#notificationsPopoverExtra').css({
									top:tdposition.top-6,
									left:tableposition.left-$('#notificationsPopoverExtra').width()
								});
								$('#notificationsPopoverExtra').show();
								$('#notificationsPopoverExtra .content').empty();
								var price = "removed";
								if(change.priceClass != 'removed'){
									price = '&euro;&nbsp;' + change.price;
									if (change.porto > 0){
										price += '&nbsp;&euro;&nbsp;' + change.porto;	
									}
								}
								var oldPrice = "new";
								if(change.priceClass != 'new'){
									oldPrice = '&euro;&nbsp;' + change.oldPrice;
									if (change.porto > 0){
										oldPrice += '&nbsp;&euro;&nbsp;' + change.oldPorto;	
									}
								}
								
								$('#notificationsPopoverExtra .content').append($('<table>').append(
									$('<tr><td>Product</td><td>' + change.brandName+' ' + change.productName+' ' + change.colorName+'</td></tr>'),
									$('<tr><td>Bedrijf</td><td>' + change.companyName+'</td></tr>'),
									$('<tr><td>Tijd wijziging</td><td>' + change.timeString+'</td></tr>'),
									$('<tr><td>Website</td><td>' + change.crawlerName+'</td></tr>'),
									$('<tr><td>Huidige prijs</td><td>' + price+'</td></tr>'),
									$('<tr><td>Vorige prijs</td><td>'+oldPrice+'</td></tr>')
								));
							},
							function(){
								$('#notificationsPopoverExtra').hide();
							}
						);
						table.append(tr);
                  	});
                  	$("#notificationsPopover .content").append(table);;
		        }
		    });
			}
		
	});
	$("body").click(function(e){
		if($("#notificationsPopover:visible").length  && !$(e.target).parents(".popover").length && !$(e.target).parents("li.notifications").length){
			$("#notificationsPopover").hide();
		}
	});
	if($("#notificationsCount").length){
		var refreshCounter = 0;
		var updatetimer= function () {
			setTimeout(function (){
				refreshCounter++;
				if(refreshCounter >700){
				    location.reload();
				}   	
			   	getNotificationsCount();
				updatetimer();
			}, 20000);
		};
		updatetimer();
		getNotificationsCount();
	} 
	
	  
});
var getNotificationsCount = function(){
	$.ajax({
		url: '?action=getNotificationsCount&module=products&ajax=true',
	  	dataType: 'json',
	  	success: function (data) {
	  		$("#notificationsCount").text(data.count);
	  	}
	});
}

//dropdown Menu
!function( $ ){
  $.fn.dropdown = function ( selector ) {
    return this.each(function () {
      $(this).delegate(selector || d, 'click', function (e) {
        var li = $(this).parent('li')
          , isActive = li.hasClass('open')

        clearMenus()
        !isActive && li.toggleClass('open')
        return false
      })
    })
  }
  var d = 'a.menu, .dropdown-toggle'
  function clearMenus() {
    $(d).parent('li').removeClass('open')
  }
  $(function () {
    $('html').bind("click", clearMenus)
    $('body').dropdown( '[data-dropdown] a.menu, [data-dropdown] .dropdown-toggle' )
  })
}( window.jQuery || window.ender );
	  	 
	  	 








