$(function () {
	$('#user_search').bind('keyup', function(e) {
			var keyCode = (e.keyCode ? e.keyCode : e.which);
			if ( keyCode == 13 ) {
				$('#loading').remove();
				$('#user_search_mod').after('<span id="loading"></span>');
				$.post('/managers/user_search',{query : $(this).val(), mod : $('#user_search_mod').val()} ,function (data){
						$("#usersContainer").html(data);
						$('span#loading').fadeOut('fast');
						$('.paginate').remove();
					});
			}
		});
		
	$(".Messages tr").find('td:not(:first)').click(function () { 
		var id = $(this).parent().attr("id");
			if(id != ''){
				$(this).parent().removeClass("Unread");
				$('#dialog').html('در حال بارگذاری...');
				$('#dialog').dialog('open');
				$.get('/users/ReadMessage/'+id, function(data) {
					$('#dialog').html(data);
				});
				return false;
			}
    });
		
	$("#paradigm_all").click(function()				
	{
		var checked_status = this.checked;
		$("input.checkbox").each(function()
		{
			this.checked = checked_status;
		});
	});
	
	$('#phone_book_search').bind('keyup', function(e) {
			var keyCode = (e.keyCode ? e.keyCode : e.which);
			if ( keyCode == 13 ) {
				$('#loading').remove();
				$(this).after('<span id="loading"></span>');
				$.post('/users/phone_book_search',{query : $(this).val()} ,function (data){
						$("#usersContainer").html(data);
						$('span#loading').fadeOut('fast');
						$('.paginate').remove();
					});
			}
		});
	$('#transaction_search').bind('keyup', function(e) {
			var keyCode = (e.keyCode ? e.keyCode : e.which);
			if ( keyCode == 13 ) {
				$('#loading').remove();
				$(this).after('<span id="loading"></span>');
				$.post('/managers/SearchTransactions',{query : $(this).val()} ,function (data){
						$("#usersContainer").html(data);
						$('span#loading').fadeOut('fast');
						$('.paginate').remove();
					});
			}
		});
	$('#order_search').bind('keyup', function(e) {
			var keyCode = (e.keyCode ? e.keyCode : e.which);
			if ( keyCode == 13 ) {
				$('#loading').remove();
				$(this).after('<span id="loading"></span>');
				$.post('/managers/SearchOrders',{query : $(this).val()} ,function (data){
						$("#usersContainer").html(data);
						$('span#loading').fadeOut('fast');
						$('.paginate').remove();
					});
			}
		});
	$('#service_product_property').change(function(){
		$(this).after('<span id="loading"></span>');
		$.post('/managers/productproperty',{service_id : $(this).val()}, function (data) {
			$('#productproperty').html(data);
			$('span#loading').fadeOut('fast');
		}
		);
	});
	
	$('ul.slabs a').click(function () {
		$('ul.slabs .active').removeClass('active');
		$(this).addClass('active');
		$('table.active').slideUp();
		var content_show = $(this).attr('title');
		$('table.' + content_show).addClass('active');
		$('table.' + content_show).slideDown();
	});

	$('table.listTable tr:even').addClass('even');
	$('table.listTable tr:odd').addClass('odd');
	
	$('#OrderMonthly').change(function(){
		if($(this).find('option:selected').val() != "0"){
			$.get('/users/getprice/'+$('#OrderProductId').val()+'/'+$(this).find('option:selected').val(), function (data) {
				$('#price_label').html('<label>قیمت</label> '+data+' تومان'); 
			});
		}
		else
		$('#price_label').html(' ');
	}
	);
	
	$('#GroupSelect').change(function(){
		if($(this).find('option:selected').val() != ""){
			$('div.countLabel').fadeOut();
			$.get('/users/GetGroupCount/'+$(this).find('option:selected').val(), function (data) {
				$('div.countLabel').html('<label>تعداد شماره های موجود</label> '+ data).addClass('input').fadeIn();
			});
		} else {
			$('div.countLabel').html(' ').removeClass('input');
		}
	});
	
	$('input#PhonePostalStart').keyup(function(){
		$elem = $(this);
		typewatch(function () {
			if($('#GroupSelect').find('option:selected').val() != "" && $elem.val().length > 1){
				$('div.countLabel').fadeOut();
				$.get('/users/GetGroupCount/'+$('#GroupSelect').find('option:selected').val() +'/'+ $elem.val(), function (data) {
					$('div.countLabel').html('<label>تعداد شماره های موجود</label> '+ data).addClass('input').fadeIn();
				});
			} else {
				$('div.countLabel').html(' ').removeClass('input');
			}
		}, 800);
	});
	
	$('#add_property').css('cursor', 'pointer');
	
	$('#add_property').click(function () {
		var count = $("#property input:last").attr('count');
		if(!count)
			count=0;
		count++;
		$('#property').append('<span><label>مورد ' + count + ':</label> <input name="data[Service][property][' + count + ']" type="text" value="" count="' + count + '" /><br /><br /></span>');
	});
	
	$("#delete_property").click( function () {
		$("#property span:last").remove();
	});
	
	$('#services_list').change(function () {
		$('#price_label').html(' ');
		$('#service_products').after('<span id="loading"></span>');
		$.post('/users/serviceproducts/', {service_id: $(this).val()}, function (data) {
			$('#service_products').html(data);
			$('#service_products').next('span#loading').fadeOut('fast');
		});
		if ( $(this).find('option:selected').attr('monthly') == 1 )
		{
			$('#period').show();
		}
		else
		{
			$('#period').hide();
		}
		if ( $(this).find('option:selected').attr('domain') == 1 )
		{
			$('#domain').show();
		}
		else
		{
			$('#domain').hide();
		}
		return false;
	});
	
	$('#service_products').change(function(){
		if($(this).find('option:selected').attr('cost') != "0")
			$('#price_label').html('<b>  قیمت : </b>'+$(this).find('option:selected').attr('cost')+' تومان'); 
		else
			$('#price_label').html(' ');
	});
	
	$('a.newPage').click(function () {
		window.open($(this).attr('href'), "NewPage", "resizable=0,status=0,scrollbars=1,toolbar=0,width=720,height:730");
		return false;
	});
	
	$('#dialog, #help-dialog').dialog({
		autoOpen: false,
		show: "blind",
		hide: "explode",
		modal: true,
		height: 250
	});
	
	$('#help-dialog').dialog({
		autoOpen: false,
		show: "blind",
		hide: "explode",
		modal: true,
		height: 450,
		width: 800
		
	});

	$('a.delivery_details').click(function() {
		$('#dialog').html('در حال بارگذاری...');
		$('#dialog').dialog('open');
		$.get($(this).attr('href'), function(data) {
			$('#dialog').html(data);
		});
		
		return false;
	});
	
	$('#customers').Customers(3000, 300);
	
	$('ul.receivers li a').click(function (){
		if($(this).hasClass('active'))
			$(this).removeClass('active');
		else 
			$(this).addClass('active');
	});
	
	$('input#AnswerSendEmail:checked, input#AnswerSendUrl:checked, input#AnswerSendCellphone:checked, input#Text_messageSendFuture:checked, input#AnswerSaveGroup:checked, input#AnswerSetRegisterCode:checked').each(function(){
		$(this).parent().next().fadeIn();
	});

	$('input#AnswerSendEmail, input#AnswerSendUrl, input#AnswerSendCellphone, input#Text_messageSendFuture, input#AnswerSaveGroup, input#AnswerSetRegisterCode').click(function() {
		$next = $(this).parent().next();
		if($(this).is(':checked'))
			$next.fadeIn();
		else{
			$next.fadeOut();
			$next.find('input, select').val('');
		}
	});
	
	$('div.Help a').click(function() {
		$('#help-dialog').html('در حال بارگذاری...');
		$('#help-dialog').dialog('open');
		var $path = $(location).attr('pathname').split("/");
		if($path[2] != ''){
			$.get('/pages/Help/'+ $path[2], function(data) {
				$('#help-dialog').html(data);
			});
		}
		
		return false;
	});
	
	$('select#PhoneOrderType').change(function() {
		if($(this).val() == 0)
			$('div.start').fadeIn();
		else
			$('div.start').fadeOut();
	});
	
	$('#Text_messageSendSmsForm').submit(function(){
		var $sendTo = '';
		$('ul.receivers li a.active').each(function() {
			$sendTo = $sendTo + $(this).attr("title")+';';
		});
		if($sendTo.length>3){
			$('#Text_messageSendSmsForm input#Text_messageToCellphone').val($sendTo);
			return true;
		}else{
			alert('لطفا ابتدا گروه و يا شماره موردنظر را جهت ارسال مشخص نماييد');
			return false;
		}
	});
	
	$('textarea#Text_messageMessage').after($('<div></div>').addClass('counter'));
	
	$('textarea#Text_messageMessage').smsCounter('div.counter');
	
	if($('table.charttable').length > 0){
		Highcharts.visualize = function(table, options) {
			// the categories
			options.xAxis.categories = [];
			$('tbody th', table).each( function(i) {
				//alert(this.innerHTML);
				options.xAxis.categories.push(this.innerHTML);
			});
			
			// the data series
			options.series = [];
			$('tr', table).each( function(i) {
				var tr = this;
				$('th, td', tr).each( function(j) {
					if (j > 0) { // skip first column
						if (i == 0) { // get the name and init the series
							options.series[j - 1] = { 
								name: this.innerHTML,
								data: []
							};
						} else { // add values
							options.series[j - 1].data.push(parseFloat(this.innerHTML));
						}
					}
				});
			});
			
			var chart = new Highcharts.Chart(options);
		}
					
		var table = $('table.charttable'),
		options = {
			   chart: {
				  renderTo: 'container',
				  defaultSeriesType: 'column',
				  backgroundColor:'rgba(255, 255, 255, 0.1)'
			   },
			   title: {
				  text: ''
			   },
			   xAxis: {
			   },
			   yAxis: {
				  title: {
					 text: '#'
				  }
			   },
			   tooltip: {
				  formatter: function() {
					 return '<b>:'+ this.series.name +'</b> '+ this.y;
				  }
			   }
			};

		Highcharts.visualize(table, options);
	}
	
	$('#UserPacks').click(function() {
		$('#Packs').toggle();
	});
	
	
	$('a.postal_map').click(function() {
		
		$val = $('#GroupSelect').find('option:selected').val();
		if($val != ''){
			$('#map-dialog').html('در حال بارگذاری...');
			$('#map-dialog').dialog('open');
			$.get('/users/GetMap/'+$val, function(data) {
				$('#map-dialog').html(data);
				$('img[usemap]').maphilight();
				$(".postal-tip").tipTip();
			});
		} else {
			alert('ابتدا شهر مورد نظر خود را انتخاب کنيد');
		}
		
		return false;
	});
	
	$('div.datepicker input').datepicker({
		dateFormat: 'yy-mm-dd',
		autoSize: true
	});
	
	$('#map-dialog').dialog({
		autoOpen: false,
		show: "blind",
		hide: "explode",
		modal: true,
		height: 550,
		width: 1050
	});

});

	var typewatch = (function(){
		var timer = 0;
		return function(callback, ms){
			clearTimeout (timer);
			timer = setTimeout(callback, ms);
		} 
	})();

	function CustomFill() {
		link = $('<li></li>').append($('<a href="javascript:;;" title="n-'+$('#Text_messageCellphone').val()+'" class="active">شماره همراه '+$('#Text_messageCellphone').val()+'</a>').click(function (){
			if($(this).hasClass('active'))
				$(this).removeClass('active');
			else 
				$(this).addClass('active');
		}));
		$('ul.receivers').prepend(link);
	}

	//Featured Customers
	(function ($) {
		$.fn.Customers = function (interval, speed)
		{	
			var loop = 0,
				list = $(this),
				height = parseInt($(this).find('li:first').css('height')),
				total = $(this).find('li').size();
			
			return this.each(function () {
				function repeat () {
					list.find('li:first').animate({marginTop: "-" + (loop*height) + "px"}, speed);
					if ( loop < total - 1 ) 
						loop++;
					else
						loop = 0;
				}
				setInterval(repeat, interval);
			});
		}
	})(jQuery);
