// JQuery Code

$(document).ready(function(){
	
	// Loader Management
	var $loading = $('#loading');

	$loading.ajaxStart(function() {
		 $.blockUI({ 
	            centerY: 0, 
	            message: 'Attendere prego...',
	            fadeIn: 700, 
	            fadeOut: 700, 
	            showOverlay: true, 
	            centerY: false, 
	            css: { 
	        		width: '150px', 
	        		height: '30px', 
	                top: '10px', 
	                left: '', 
	                right: '10px', 
	                border: 'none', 
	                padding: '5px', 
	                backgroundColor: '#000', 
	                '-webkit-border-radius': '10px', 
	                '-moz-border-radius': '10px', 
	                opacity: .6, 
	                color: '#fff'
	            } 
	        }); 
	});

	$loading.ajaxStop(function() {
		$.unblockUI();
	});
	
	$(".button").click(function () {
		 $.blockUI({ 
           centerY: 0, 
           message: 'Elaborazione in corso, Attendere prego...',
           fadeIn: 700, 
           fadeOut: 700, 
           showOverlay: true, 
           centerY: true, 
           centerX: true, 
           timeout: 100, 
           css: { 
       		width: '350px', 
       		height: '30px', 
           border: 'none', 
           padding: '5px', 
           backgroundColor: '#000', 
           '-webkit-border-radius': '10px', 
           '-moz-border-radius': '10px', 
           opacity: .6, 
           color: '#fff'
           } 
       }); 
	});
	
	// Delete button 
	$(".companyselector").change(function () {
		 $.blockUI({ 
            centerY: 0, 
            message: 'Attendere prego...',
            fadeIn: 700, 
            fadeOut: 700, 
            showOverlay: true, 
            centerY: false, 
            css: { 
        		width: '150px', 
        		height: '30px', 
                top: '10px', 
                left: '', 
                right: '10px', 
                border: 'none', 
                padding: '5px', 
                backgroundColor: '#000', 
                '-webkit-border-radius': '10px', 
                '-moz-border-radius': '10px', 
                opacity: .6, 
                color: '#fff'
            } 
        }); 
		document.location = '/usercp/' + $('.companyselector').attr('rel') + '/edit/' + $('.companyselector').val();
		return false;
	});
	
	/* ###################### Address Management #########################*/
	// Save Address
	$(".address_save").click(function () {
		var form = $("#address").serialize();
		$.post('/usercp/profile/saveaddress/', {data: form}, function(data){
			if(data.result == 1){
				$('#addresslist').find('tr:first').after('<tr rel="'+data.record.id+'"><td>'+data.record.id+'</td><td>'+data.record.address+'</td><td>'+data.record.code+'</td><td>'+data.record.region+'</td><td>'+data.record.province+'</td><td>'+data.record.city+'</td><td><a rel="'+data.record.id+'" href="#" onclick="return false;" class="address_delete" title="Cancella"><img src="/commons/images/usercp/cross.png" alt="Delete"></a> </td></tr>'); 
			}
		}, 'json');
	}); 
	
	
	/* ###################### Orders Management #########################*/
	// Orders selector
	$(".orderselector").change(function () {
		if($('.orderselector option:selected').val() != ""){
			location.href = '/usercp/orders/edit/' + $('.orderselector option:selected').val();
		}else{
			location.href = '/usercp/orders/';	
		}
	}); 
	
	
	// Delete Address
	$(".address_delete").live("click", function () {
		var idaddress = $(this).attr('rel');
		$.post('/usercp/profile/deleteaddress/', {id: idaddress}, function(data){
			if(data.result == 1){
				$('#addresslist').find('[rel='+idaddress+']').remove();
			}
		}, 'json');
	}); 
	
	
	/* ###################### Contact Management #########################*/
	// Save Contact
	$(".contact_save").click(function () {
		var form = $("#contacts").serialize();
		$.post('/usercp/profile/savecontact/', {data: form}, function(data){
			if(data.result == 1){
				$('#contactlist').find('tr:first').after('<tr rel="'+data.record.id+'"><td>'+data.record.id+'</td><td>'+data.record.type+'</td><td>'+data.record.value+'</td><td><a rel="'+data.record.id+'" href="#" onclick="return false;" class="contact_delete" title="Cancella"><img src="/commons/images/usercp/cross.png" alt="Delete"></a> </td></tr>'); 
			}
		}, 'json');
	}); 
	
	// Delete Contact
	$(".contact_delete").live("click", function () {
		var idcontact = $(this).attr('rel');
		$.post('/usercp/profile/deletecontact/', {id: idcontact}, function(data){
			if(data.result == 1){
				$('#contactlist').find('[rel='+idcontact+']').remove();
			}
		}, 'json');
	}); 
	
	
	/* ###################### File Management #########################*/
	
	// Delete File
	$(".file_delete").live("click", function () {
		var idfile = $(this).attr('rel');
		$.post('/usercp/profile/deletefile/', {id: idfile}, function(data){
			if(data.result == 1){
				$('#filelist').find('[rel='+idfile+']').remove();
			}
		}, 'json');
	}); 
	
	// Macrocategory management
	$(".macrocategory").change(function () {
		$.post('/usercp/common/getmicrobymacro/', { id: $('.macrocategory').val()}, function(data){
			$('.microcategory').empty();
			$.each(data, function(name,value){
				$('.microcategory').append('<option value="' + name + '">' + value + '</option>')
			})
		}, 'json');
	}); 
	
	// Subdomain management
	$(".subdomainchecker").click(function () {
		var message;
		if($('.subdomain').val()){
			$.post('/usercp/common/checksubdomain/', { subdomain: $('.subdomain').val(), iduser: $('[name=iduser]').val()}, function(data){
				
			    if(data >= 1){
			    	message = "Il sottodominio non è disponibile.";
			    	$('.subdomain').attr('value', '');
			    }else{
			    	message = "Disponibile";
			    }
			    alert(message);
			    
			}, 'json');
		}else{
			alert('Inserisci il sottodominio desiderato e fare click sul bottone Controlla Disponibilità')
			$('.phsubdomain').effect("highlight", {}, 3000);
		}
	}); 
	
	$(".contactype").focus(function () {
		$.post('/usercp/common/getcontactype/', {}, function(data){
			$('.contactype').empty();
			$.each(data, function(name,value){
				$('.contactype').append('<option value="' + name + '">' + value + '</option>')
			})
		}, 'json');
	}); 
	
	$(".filesectiontype").focus(function () {
		$.post('/usercp/common/getfilesectiontype/', {}, function(data){
			$('.filesectiontype').empty();
			$.each(data, function(name,value){
				$('.filesectiontype').append('<option value="' + name + '">' + value + '</option>')
			})
		}, 'json');
	}); 
	
	
	// Region, Provinces, Cities Management
	$(".region").focus(function () {
		$.post('/usercp/common/getregions/', {}, function(data){
			$('.region').empty();
			$('.province').empty();
			$('.city').empty();
			$('.region').append('<option value="">Seleziona ...</option>')
			$('.province').append('<option value="">Seleziona ...</option>')
			$.each(data, function(name,value){
				$('.region').append('<option value="' + name + '">' + value + '</option>')
			})
		}, 'json');
	}); 
	
	$(".region").change(function () {
		$.post('/usercp/common/getprovinces/', { id: $('.region').val()}, function(data){
			$(".country").attr("checked", false);
			$('.province').empty();
			$('.city').empty();
			$('.province').append('<option value="">Seleziona ...</option>')
			$.each(data, function(name,value){
				$('.province').append('<option value="' + name + '">' + value + '</option>')
			})
		}, 'json');
	}); 
	
	$(".province").change(function () {
		$.post('/usercp/common/getcities/', { id: $('.province').val()}, function(data){
			$(".country").attr("checked", false);
			$('.city').empty();
			$('.city').append('<option value="">Seleziona ...</option>')
			$.each(data, function(name,value){
				$('.city').append('<option value="' + name + '">' + value + '</option>')
			})
		}, 'json');
	}); 
	
	// Get all the profiles
	$(".getprofiles").change(function () {
		$.post('/usercp/common/getprofiles/', { id: $('.getprofiles').val() }, function(data){
			$('.profile').empty();
			$.each(data, function(name,value){
				$('.profile').append('<option value="' + name + '">' + value + '</option>')
			})
		}, 'json');
	}); 
	
	$("span.sort").each(function () {
		
		var path = $("#tablelist").attr('rel');
		var asc = "<a href='" + path + "/sort/" + $(this).attr('rel') + "/asc'><img src='/commons/images/usercp/icons/asc.gif' alt='asc'></a>";
		var desc = "<a href='" + path + "/sort/" + $(this).attr('rel') + "/desc'><img src='/commons/images/usercp/icons/desc.gif' alt='desc'></a>";
		
		$(this).html(asc + desc);
	});
	
	
	
	// Date Calender addon
	$(function(){
		$.dpText = {
				TEXT_PREV_YEAR		:	'Anno precedente',
				TEXT_PREV_MONTH		:	'Mese precedente',
				TEXT_NEXT_YEAR		:	'Anno successivo',
				TEXT_NEXT_MONTH		:	'Mese successivo',
				TEXT_CLOSE			:	'Chiudi',
				TEXT_CHOOSE_DATE	:	'Chiudi data'
			}

		$('.date-pick').datePicker({clickInput:true})
	});
	
	// Tab Label Control
	$("#module").html($('a.default-tab.current').html());
	$("ul.content-box-tabs a").click(function () {
		$("#module").html($(this).html());
	});
	
	// Delete button 
	$("a.delete").click(function () {
		if (confirm("Sei sicuro di voler cancellare il record?")) {
		    document.location = $(this).attr('href');
		}
		return false;
	});

	// Custom Action button inside the list of the records
	$("#custombutton").click( // When a menu item with no sub menu is clicked...
		function () {
			if($('#customactions').val()){
				$.post('/usercp/' + $('#customactions').attr('rel') + '/customcommands/' + $('#customactions').val(), { params: $.param($('#tablelist :checkbox:checked'))}, function(data){
					if(data.reload != ""){
						window.location.href = data.reload;
					}
				}, 'json');
			}
			return false;
		}
	); 
	
	$("#showall").click( // When a menu item with no sub menu is clicked...
		function () {
			$.post('/usercp/' + $('#showall').attr('rel') + '/customcommands/showall', { params: 'clear'}, function(data){
			if(data.reload != ""){
				window.location.href = data.reload;
			}
		}, 'json');
	}); 
	
	// Paging Action button inside the list of the records
	$("#pagerbutton").click( // When a menu item with no sub menu is clicked...
		function () {
			if($('#pagingactions').val()){
				$.post('/usercp/' + $('#pagingactions').attr('rel') + '/customcommands/paging', { params: $('#pagingactions').val()}, function(data){
					if(data.reload != ""){
						window.location.href = data.reload;
					}
				}, 'json');
			}
			return false;
		}
	); 
	
	//Sidebar Accordion Menu:
		
		$("#main-nav li ul").hide(); //Hide all sub menus
		$("#main-nav li a.current").parent().find("ul").slideToggle("slow"); // Slide down the current menu item's sub menu
		
		$("#main-nav li a.nav-top-item").click( // When a top menu item is clicked...
			function () {
				$(this).parent().siblings().find("ul").slideUp("normal"); // Slide up all sub menus except the one clicked
				$(this).next().slideToggle("normal"); // Slide down the clicked sub menu
				return false;
			}
		);
		
		$("#main-nav li a.no-submenu").click( // When a menu item with no sub menu is clicked...
			function () {
				window.location.href=(this.href); // Just open the link instead of a sub menu
				return false;
			}
		); 

    // Sidebar Accordion Menu Hover Effect:
		
		$("#main-nav li .nav-top-item").hover(
			function () {
				$(this).animate({ paddingRight: "25px" }, 200);
			}, 
			function () {
				$(this).animate({ paddingRight: "15px" });
			}
		);

    //Minimize Content Box
	$(".content-box-header h3").css({ "cursor":"s-resize" }); // Give the h3 in Content Box Header a different cursor
	$(".content-box-header-toggled").next().hide(); // Hide the content of the header if it has the class "content-box-header-toggled"
	
	$(".content-box-header h3").click( // When the h3 is clicked...
		function () {
		  $(this).parent().parent().find(".content-box-content").toggle(); // Toggle the Content Box
		  $(this).parent().toggleClass("content-box-header-toggled"); // Give the Content Box Header a special class for styling and hiding
		  $(this).parent().find(".content-box-tabs").toggle(); // Toggle the tabs
		}
	);

	
    // Content box tabs:
	$('.content-box .content-box-content div.tab-content').hide(); // Hide the content divs
	$('.content-box-content div.default-tab').show(); // Show the div with class "default-tab"
	$('ul.content-box-tabs li a.default-tab').addClass('current'); // Set the class of the default tab link to "current"
	
	$('.content-box ul.content-box-tabs li a').click( //When a tab is clicked...
		function() { 
			$(this).parent().siblings().find("a").removeClass('current'); // Remove "current" class from all tabs
			$(this).addClass('current'); // Add class "current" to clicked tab
			var currentTab = $(this).attr('href'); // Set variable "currentTab" to the value of href of clicked tab
			$(currentTab).siblings().hide(); // Hide all content divs
			$(currentTab).show(); // Show the content div with the id equal to the id of clicked tab
			var selectedItem = $(this).attr('id');
			$.cookie('seltab', selectedItem, { expires: 7 });
			return false; 
		}
	);

	// Content box selection
	var selTab = $.cookie('seltab');
	if(selTab != ""){
		$('#'+selTab).addClass('current');
		$('#'+selTab).parent().siblings().find("a").removeClass('current');
		var currentTab = $('#'+selTab).attr('href');
		$(currentTab).siblings().hide();
		$(currentTab).show();
	}
	
    //Close button:
	$(".close").click(
		function () {
			$(this).parent().fadeTo(400, 0, function () { // Links with the class "close" will close parent
				$(this).slideUp(600);
			});
			return false;
		}
	);

    // Alternating table rows:
	$('tbody tr:even').addClass("alt-row"); // Add class "alt-row" to even table rows

    // Check all checkboxes when the one in a table head is checked:
	$('.check-all').click(
		function(){
			$(this).parent().parent().parent().parent().find("input[type='checkbox']").attr('checked', $(this).is(':checked'));   
		}
	)

    // Initialise Facebox Modal window:
	$('a[rel*=modal]').facebox(); // Applies modal window to any link with attribute rel="modal"
	$(".thumb").facebox();
	
    // Initialise jQuery WYSIWYG:
	$(".wysiwyg").wysiwyg();

	// Toggling of the child items inside a table
	$('.parent').click(function () { $('.child').toggle(); });
});

function confirmDelete(message, delUrl) {
	  if (confirm(message)) {
	    document.location = delUrl;
	  }
	}
  
  
  
