$(document).ready(function(){
	
	/* Autocomplete */
	 function formatItem(row) {
		 return "<strong>" + row[2] + "</strong> " + row[1];
	 }	
	
	/* Apply fancybox to multiple items */
	
	$("a.screenshot").fancybox({
		'transitionIn'	:	'elastic',
		'transitionOut'	:	'elastic',
		'speedIn'		:	600, 
		'speedOut'		:	200, 
		'overlayShow'	:	false
	});

	 // find all the input elements with title attributes
     $('input[title!=""]').hint();
     
	 // Tooltip Object
	 $('[title]').qtip({
	      position: {
	         my: 'top left',
	         target: 'mouse',
	         viewport: $(window), // Keep it on-screen at all times if possible
	         adjust: {
	            x: 10,  y: 10
	         }
	      },
	      hide: {
	         fixed: true // Helps to prevent the tooltip from hiding ocassionally when tracking!
	      },
	      style: {
				classes: 'ui-tooltip-shadow', // Optional shadow...
				tip: 'top left', // Tips work nicely with the styles too!
				widget: true
			}
	   });
	 
     $(".redirect").change( function() {
    	 window.location.replace($(this).val());
     });
     
	 /* Confirm Button */
	 $('a.confirm').confirm({
		 timeout: 3000
	 });
	 	 
	 flowplayer("a.player", "/resources/flash/flowplayer/flowplayer-3.2.7.swf",{
		 clip:  {
		        autoPlay: false,
		        autoBuffering: true
		    }
	 });
	 
	 /* Tab Management*/
	 $( "#tabs" ).tabs();
	 
	 /* Search box */
	 $("#searchbox").autocomplete("/common/search/do/",{
		 delay:400,
		 minChars:2,
		 matchSubset:1,
		 matchContains:1,
		 cacheLength:10,
		 formatItem:formatItem,
		 autoFill:false
		 }
	 );	
	 
	 $('#searchbox').result(function(event, data, formatted) {
	        var uri = data[0];
	        location.href = "/" + uri + ".html";
	 });
	 
	 /* Search domain box */
	 $("#searchdomainbox").autocomplete("/common/searchdomain/do/",{
		 delay:400,
		 minChars:2,
		 matchSubset:1,
		 matchContains:1,
		 cacheLength:10,
		 formatItem:formatItem,
		 formatResult: function(row) {
			 return row[1];
		 },
		 autoFill:false
	 }
	 );	
	 
	 $('#searchdomainbox').result(function(event, data, formatted) {
	        var Id = data[0];
	        location.href = "/domains/edit/id/" + Id;
	 });
	
	  /* Password Checker */
	  $('.password-strength').password_strength({container: '.passchecker'});
	  
	$.blockUI.defaults.message = "Please wait a moment ...";
	$(document).ajaxStart($.blockUI).ajaxStop($.unblockUI);
	
	// Delete button 
	$("a.delete").click(function () {
		if (confirm("Sei sicuro di voler cancellare il record?")) {
		    document.location = $(this).attr('href');
		}
		return false;
	});

	// TOP MENU
	// ########
	$("ul.subnav").parent().append("<span></span>"); //Only shows drop down trigger when js is enabled (Adds empty span tag after ul.subnav*)

	$("ul.topnav li span").click(function() { //When trigger is clicked...

		//On hover over, add class "tophover"
		$(this).parent().find('a:first').addClass("tophover");
		
		//Following events are applied to the subnav itself (moving subnav up and down)
		$(this).parent().find("ul.subnav").slideDown('fast').show(); //Drop down the subnav on click

		$(this).parent().hover(function() {
		}, function(){
			$(this).parent().find("ul.subnav").slideUp('slow'); //When the mouse hovers out of the subnav, move it back up
			$(this).parent().find('a').removeClass("tophover"); //On hover out, remove class "tophover"
		});

		//Following events are applied to the trigger (Hover events for the trigger)
		}).hover(function() {
			$(this).addClass("subhover"); //On hover over, add class "subhover"
		}, function(){	//On Hover Out
			$(this).removeClass("subhover"); //On hover out, remove class "subhover"
	});	
	
	// Category MENU
	$("ul.catsubnav").parent().append("<span></span>");
	$("ul.topcatnav li.topcat").hover(function() {

	    if ($(this).find("ul.catsubnav").children().size()) {
	        $(this).find('a:first').addClass("cathover");
	    }
	    
	    $(this).find("ul.catsubnav").show();

	    $(this).hover(function() {}, function() {
	        $(this).parent().find("ul.catsubnav").hide();
	        $(this).parent().find('a').removeClass("cathover");
	    });

	}, function() { //On Hover Out
	    $(this).removeClass("subhover"); //On hover out, remove class "subhover"
	});

	
	// Custom Action button inside the list of the records
	$("#bulkactions").click( 
			function () {
				if($('#bulkactions').val()){
					$.post('/default/' + $('#bulkactions').attr('rel') + '/bulk/', {params: $.param($('#itemlist :checkbox:checked')) + '&do='+$('#actions').val()}, 
							function(data){
						if(data.reload !== undefined){
							window.location.href = data.reload;
						}
						
						if(data.mex !== undefined){
							$("#mex").html(data.mex).fadeIn(1000, function(){
								$(this).fadeOut(5000);         
							});
						}
					}, 'json');
				}
				return false;
			}
	); 
	
	// Custom Action button 
	$(".bulkbtnactions").click( 
		function () {
			var domain = $(this).attr('rel');
			var action = $(this).attr('act');
			$.post('/admin/domains/bulk/', {params: 'item=' + domain + '&do='+action}, 
					function(data){
						var css = domain.replace(".", "_");
						if(data.mex !== undefined){
							$(".mex_"+css).html(data.mex).fadeIn(1000, function(){
							    $(this).fadeOut(2000);         
							});
						}
			}, 'json');
			return false;
		}
	); 
	
	$("#domainslist tbody tr").each(function() {
	      var domainId = $(this).find(".link").html();  
	});

	// Select all the checkboxes
	$('.selectall').click(
		function(){
			$(this).parent().parent().parent().parent().find("input[name='item[]'], type='checkbox'").attr('checked', $(this).is(':checked'));   
		}
	);
	
	// Select all the checkboxes
	$('.selectalltlds').click(
			function(){
				$(this).parent().parent().parent().parent().find("input[name='tlds[]'], type='checkbox'").attr('checked', $(this).is(':checked'));   
			}
	);
	
	$('.zebratable tr:even').addClass('even');
	$('.zebratable tr:odd').addClass('odd');

	// TABS
	// Content box tabs:
	$('.tab-content').hide(); 
	$('.default-tab').show(); 
	
	$('ul.content-box-tabs li a').click( 
		function() { 
			$(this).parent().siblings().find("a").removeClass('current'); 
			$(this).addClass('current'); 
			var currentTab = $(this).attr('href'); 
			$(currentTab).siblings().hide(); 
			$(currentTab).show(); 
			$('#floating-box').show();
			return false; 
		}
	);
	
	/* Start Categories and Products */
	$("#categories").change(function () {
		$.post('/admin/orders/getproducts/id/' + $("#categories").val(), {}, function(data){
			$('#products').empty();
			
			if(data[1]) {
				$('#domainph').show();
				$("#domain").css({backgroundColor:"#FFE9E9"});
			}else{
				$('#domainph').hide();
				$('#domain').val('');
				$("#domain").css({backgroundColor:"none"});
			}
			$('#products').append('<option value=""></option>');
			$.each(data[0], function(name,value){
				$('#products').append('<option value="' + name + '">' + value + '</option>');
			});
		}, 'json');
	}); 
	
	$("#products").change(function () {
		$.post('/admin/orders/getproductinfo/id/' + $("#products").val(), {}, function(data){
			$('#price').empty();
			$('#description').empty();
			
			if(data.name) {
				$('#description').val(data.name);
			}
			
			if(data.price_1) {
				$('#price').val(data.price_1);
			}
			
		}, 'json');
	}); 
	
	/* End Categories and Products */
	
	$(".btn-slide").click(function(){
	    $("#panel").slideToggle("slow");
	    $(this).toggleClass("active");
	});

	
	
	$("#filters").click( 
		function () {
			var items = $('input:checkbox:checked').serializeArray();
			$.post('/domains/searchprocess/', {params: items}, 
				function(data){
					if(data.reload !== undefined){
						window.location.href = data.reload;
					}
					if(data.mex !== undefined){
						$("#mex").html(data.mex).fadeIn(1000, function(){
							$(this).fadeOut(5000);  
							window.location.reload();
						});
					}
				}, 'json');
			return false;
		}
	); 
	
	$(".www-input").click(function () {
		$(this).val('');
	});
	
	$('.highlight').each(function() {
		var options = {};
		$(this).effect('highlight', options, 2000);
	});
	
	// Cart management
	$('.checkdomain').each(function() {
		var domain = $(this).attr("rel");
	      var item = $(this);
	      $.post('/products/checkdomain/', {fulldomain: domain}, function(data){
	    	  if(data.isavailable){
	    		  item.addClass('available');
	    		  item.append('<input type="hidden" name="domstatus[]" value="1">');
	    	  }else{
	    		  item.addClass('notavailable');
	    		  item.append('<input type="hidden" name="domstatus[]" value="0">');
	    	  }
	      }, 'json');
	});
	
	
	$("#products").change(function () {
		$.post('/admin/orders/getproductinfo/id/' + $("#products").val(), {}, function(data){
			$('#price').empty();
			$('#description').empty();
			
			if(data.name) {
				$('#description').val(data.name);
			}
			
			if(data.price_1) {
				$('#price').val(data.price_1);
			}
			
		}, 'json');
	}); 
	
	$("#legalform").change(function () {
		var id = $("#legalform").val();
		if(id > 0){
			$.post('/default/cart/getcompanytypes/id/' + $("#legalform").val(), {}, function(data){
				$('#company_type_id').empty();
				$.each(data, function(name,value){
					$('#company_type_id').append('<option value="' + name + '">' + value + '</option>');
				});
			}, 'json');
		}else{
			$('#company_type_id').empty();
		}
	}); 
	
    
    tinyMCE.init({
    	// General options
    	mode : "specific_textareas",
    	editor_selector : "wysiwyg",
    	plugins : "paste",
    	theme_advanced_buttons3_add : "pastetext,pasteword,selectall",
        paste_auto_cleanup_on_paste : true,
        paste_preprocess : function(pl, o) {
            // Content string containing the HTML from the clipboard
            o.content = o.content.replace(/(<.*?>)/ig,"");
        },
        paste_postprocess : function(pl, o) {
            // Content DOM node containing the DOM structure of the clipboard
            o.node.innerHTML = o.node.innerHTML;
        },
        convert_urls : false,
    	height : "200",
    	width : "100%"
    });
    
    function removeAllHtmlInsideDiv() {
        $(".example_1").html( $(".example_1").text() );
    };
    
    removeAllHtmlInsideDiv();

    $("#gallery a").fancybox();
        
    // Center the div on the middle of the screen
    jQuery.fn.center = function () {
        this.css("position","absolute");
        this.css("top", (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px");
        this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px");
        return this;
    }
    
});

// Update the total of the product
function UpdatePrice(){
	if($(".select-billing-cycle").length){
	    $.post('/products/getprice/id/' + $(".select-billing-cycle").val(), {}, function(data){   
	        var price = data.price * data.months;
			
	        $('#priceval').empty();
	        $('#pricefreq').empty();
	        $('#priceval').append(price.toFixed(2));
	        $('#pricefreq').append(data.name);
	    }, 'json');
	}
}

