if (typeof Application == 'undefined') Application = {};

jQuery(document).ready(function() {
    Application.init();
});

Application = {
//	systemTime: new Date(),
		
    init: function() {
    	// initializing clock timer
    	if (jQuery('#system-clock').length != 0) {
	    	if (jQuery('#system-clock').html().length == 0) {
	    		Application.updateClock();
	    	}
	    	setInterval(Application.updateClock, 1000);
		}
    	
    	if (jQuery('#move-to-directory-current-message').length != 0) {
    		Application.updateDirectoryList();
    	}
    	
    	if (jQuery('#move-to-directory-current-message').length != 0) {
    		jQuery('#move-to-directory-current-message').change(function () {
    			var dest = jQuery(this).val();
    			var destName = jQuery('#move-to-directory-current-message option:selected').html();
    			var messageList = new Array();
    			messageList.push(jQuery('#current-message-id').val());
   				if (confirm('Перенести это сообщение в "' + destName + '"?')) {
   					Application.moveToDirectory(dest, messageList);
   				}
    		});
    	}
    	
    	// communicator, move messages to directories
    	if (jQuery('#move-to-directory').length != 0) {
    		jQuery('#move-to-directory').change(function () {
    			var dest = jQuery(this).val();
    			var destName = jQuery('#move-to-directory option:selected').html();
    			var messageList = new Array();
    			var messageDict = new Array(' сообщения ', ' сообщений ');
   				jQuery('.communicator-table tbody input[type="checkbox"]:checked').each(function () {
   					messageList.push(jQuery(this).val());
   				});
   				if (messageList.length > 0 && confirm('Перенести ' + messageList.length + messageDict[((messageList.length < 4 || messageList.length % 2 == 0) ? 0 : 1)] + 'в "' + destName + '"?')) {
   					Application.moveToDirectory(dest, messageList);
   				}
    		});
    		
    		jQuery('.communicator-table input[type="checkbox"]').change(function() {
       			jQuery('#move-to-directory').css('display', (jQuery('.communicator-table input[type="checkbox"]:checked').attr('id') != undefined && jQuery('#move-to-directory option').length != 0) ? 'inline' : 'none');
    		});
    	}
    	
    	
    	/* MyLand common layout servers change */
    	if (jQuery('#metabaze-layout-select1-id').length != 0) {
    		jQuery('#metabaze-layout-select1-id').change(function () {
    			var server_id = jQuery(this).val();
    			jQuery.ajax({
        			type: 'post',
        			url: '/m202/C008/serverchange',
        			data: { 
        				'server_id': server_id
        			},
        			success: function(data) {
        				 window.location.reload();
        			}
        		});
    		});
    	}
    	
    	// init datepicker
    	if (jQuery('#date-picker').length != 0) {
    		jQuery('#date-picker').datepicker({
    			dateFormat: 'yy.mm.dd'
    		});
    	}
    	
	    if (jQuery('#delete-button').length != 0) {
	    	jQuery('#delete-button').click(function() {
	        	return confirm('Удалить выбранные элементы?');
	    	});
	    }
	    if (jQuery('#select-all').length != 0) {
	    	jQuery('#select-all').click(function() {
	    		jQuery('.communicator-table input[type="checkbox"]').each(function() {
	    			jQuery(this).attr('checked', jQuery('#select-all').attr('checked'));
	    		});
	    	});
	    }
	    if (jQuery('.action-button').length != 0) {
	    	jQuery('.action-button').click(function() {
	    		var url = jQuery(this).attr('anlarr:url');
	    		jQuery(location).attr('href', url);
	    	});
	    }
        if (jQuery('.text-editor').length != 0) {
        	Application.initWysiwyg(jQuery('.text-editor'));
        }
        if (jQuery('.cancel-compose').length != 0) {
        	jQuery('.cancel-compose').click(function() {
        		return confirm('Отменить написание сообщения?');
        	});	
        }
        
        /*******************************************************************
         * communicator
         */
        
        Application.updateDirectoryList();
        
        if (jQuery('.communicator-table').length != 0) {
    		jQuery.get('/user/updateonlinestatus');
    		jQuery('#contact-list').load('/communicator/contact/online', {'showAll': false});
        	setInterval(function() {
        		var showAll = jQuery('#show-offline-contacts').is(':checked');
        		jQuery.get('/user/updateonlinestatus');
        		jQuery('#contact-list').load(
       				'/communicator/contact/online', 
       				{ 'showAll': showAll }
        		);
        	}, 60000);
        	
	        jQuery('#new-directory-name').keyup(function(event) {
	        	switch (event.keyCode) {
	        	case 27:
	        		jQuery('#new-directory-container').css('display', 'none');
	        		jQuery('#new-directory-name').attr('value', '');
	       			break;
	        	case 13:
	        		// @todo
	        		break;
	       		default:
	       			break;
	        	}
	        });
	        
	        if (jQuery('#delete-message-directory-action').length != 0) {
	        	jQuery('#delete-message-directory-action').click(function() {
	        		jQuery('.directory-list input[type="checkbox"]:checked').each(function() {
	        			var directoryType = jQuery('#directory-type').val();
		        		jQuery.ajax({
		        			type: 'post',
		        			url: '/communicator/message/deletedirectory',
		        			data: { 
		        				'id': jQuery(this).val(),
		        				'type': directoryType
		        			},
		        			success: function(data) {
//		            			window.location.href = '/communicator/message/' + ((directoryType == 'ingoing') ? 'inbox' : 'outgoing');
		        				Application.updateDirectoryList();
		        			}
		        		});
	        		});
	        	});
	        }
	        
	        if (jQuery('#create-message-directory-action').length != 0) {
	        	jQuery('#create-message-directory-action').click(function() {
	        		jQuery('#new-directory-container').css('display', 'inline');
	        		jQuery('#new-directory-name').focus();
	        	});
	        	jQuery('#create-directory').click(function() {
	        		if (jQuery('#new-directory-name').val() != '') {
	        			var directoryType = jQuery('#directory-type').val();
		        		jQuery.ajax({
		        			type: 'post',
		        			url: '/communicator/message/createdirectory',
		        			data: { 
		        				'new-directory': jQuery('#new-directory-name').val(),
		        				'type': directoryType
		        			},
		        			success: function(data) {
		    	        		jQuery('#new-directory-container').css('display', 'none');
		    	        		jQuery('#new-directory-name').attr('value', '');
		    	        		/*
		    	        		jQuery(location).attr('href', '/communicator/message/' + 
		    	        				(directoryType == 'ingoing') ? 'inbox' : 'outgoing'
		    	        		);
		    	        		*/
		    	        		jQuery('.directory-list').css('display', 'block');
		    	        		Application.updateDirectoryList();
		        			}
		        		});
	        		}
	        	});
	        }
        }
        
        if (jQuery('#file-attachments').length != 0) {
        	var new_file_attachment_html = '<div><input type="file" name="attached-files[]" />&nbsp;&nbsp;&nbsp;<a onclick="jQuery(this).parent().remove();" href="#">Убрать этот файл</a></div>';
        	jQuery('#add-attachment-file').click(function() {
        		jQuery('#file-attachments').append(new_file_attachment_html);
        	});
        }
        
        /*******************************************************************
         * infochannels
         */
        if (jQuery("a[id^='communicator_infochannel_']").length != 0)
        {
        	jQuery("a[id^='communicator_infochannel_']").click(function() {
        		 var group_id = this.getAttribute("group_id");
        		 var inText = (typeof($(this)[0].textContent) != "undefined") ? $(this)[0].textContent : $(this)[0].innerText;
        		 if(inText == 'on')
        		 {
        			 Application.setUserToChannel('off', group_id);
        			 $(this).removeClass("communicator_infochannel_on"); 
                     $(this).addClass("communicator_infochannel_off"); 
                     (typeof($(this)[0].textContent) != "undefined") ? $(this)[0].textContent = 'off' : $(this)[0].innerText = 'off';
        		 }
        		 else if(inText == 'off')
        		 {
        			 Application.setUserToChannel('on', group_id);
        			 $(this).removeClass("communicator_infochannel_off"); 
                     $(this).addClass("communicator_infochannel_on"); 
                     (typeof($(this)[0].textContent) != "undefined") ? $(this)[0].textContent = 'on' : $(this)[0].innerText = 'on';
        		 }
        	});
        }
        
        if (jQuery('.communicator-infochannel-info-link').length != 0) {
        	jQuery('.communicator-infochannel-info-link').click(function() {
        		var group_id = this.getAttribute("group_id");
        		
        		var windowWidth = 900;
        		var windowHeight = 550;
        		var centerWidth = (window.screen.width - windowWidth) / 2;
        	    var centerHeight = (window.screen.height - windowHeight) / 2;

        	    var prdesc = window.open('/infochannels/' + group_id + '.html', 'winname', 'resizable=0, scrollbars=1, width=' + windowWidth + 
        	        ',height=' + windowHeight + 
        	        ',left=' + centerWidth + 
        	        ',top=' + centerHeight);

        	    prdesc.focus();
        		return false;
        	});
        }
        
        
        /*******************************************************************
         * anlarr2010
         */
        
        if (jQuery('.delete-anlarr2010-comment').length != 0) {
        	jQuery('.delete-anlarr2010-comment').click(function() {
        		var commentId = jQuery(this).attr('anlarr:comment-id');
        		jQuery.get('/anlarr2010/history/deletecomment/commentId/' + commentId);
        		jQuery(this).parent().parent().remove();
        	});
        }
        
        if (jQuery('.comment-rate-choice').length != 0) {
        	jQuery('.comment-rate-choice').each(function() {
        		var comment_author = jQuery(this).attr('anlarr:comment-author');
        		var history_id = jQuery(this).attr('anlarr:history-id');
        		var comment_id = jQuery(this).attr('anlarr:comment-id');
        		jQuery(this).change(function() {
        			var __container = '#comment-author-' + comment_author + '-container';
        			var __url = '/anlarr2010/history/ratecomment';
        			var __data = {
        					'comment_author': comment_author, 
        					'rate': jQuery(this).val(),
        					'history_id': history_id,
        					'comment_id': comment_id
        					};
        			jQuery(__container).load(__url, __data);
        			jQuery(this).parent().parent().attr('class', 'comment-header bg-commented');
        		});
        	});
        }
        
        /********************************************************************
         * bank
         */
        if (jQuery('#bank-currency-value').length != 0) {
        	jQuery('#bank-currency-value').keyup(function() {
        		var internalCurrencyBalance = parseFloat(jQuery('#internal-currency-balance').val());
        		var externalCurrencyBalance = parseFloat(jQuery('#external-currency-balance').val());
        		var externalCurrencyRate	= parseFloat(jQuery('#external-currency-rate').val());
        		var proposedAmount			= parseFloat(jQuery(this).val());
        		var conversionResult 		= parseFloat(proposedAmount * externalCurrencyRate);
        		var highlight = (proposedAmount <= externalCurrencyBalance)
	    			? '#004080'
	    			: '#ff0000';
        		jQuery(this).css('color', highlight);
        		if (conversionResult <= 0 || jQuery(this).val() == '') {
            		jQuery(this).css('color', '#000000');
        			jQuery('#bank-currency-output-preview').val('0.00');
        		} else {
            		jQuery('#bank-currency-output-preview').val(conversionResult.toFixed(2));
        		}
        	});
        }
        
        /*********************************************************************
         * shop
         */
        if (jQuery('.cancel-product-acquisition').length != 0) {
        	jQuery('.cancel-product-acquisition').click(function() {
        		var decValue = jQuery(this).attr('anlarr:price-marker');
            	jQuery(this).parent().parent().remove();
            	jQuery('#shop-summary-product-count').html(parseInt(jQuery('#shop-summary-product-count').html()) - 1);
            	jQuery('#shop-summary-product-sum').html((parseFloat(jQuery('#shop-summary-product-sum').html()) - decValue).toFixed(2));
            	if (jQuery('.cancel-product-acquisition').length <= 0) {
            		var currencyId = jQuery('#currency-id').val();
            		alert('Вы удалили все выбранные элементы. Перенаправляем обратно к списку продуктов.');
            		window.location.replace('/shop/product/' + currencyId.toLowerCase());
            	}
        	});
        }
        
        if (jQuery('#shop-items-selected').length != 0) {
            jQuery('.report-table tbody input').click(function() {
            	var itemSelectedPrice = 0.00;
            	var itemSelected 	  = jQuery('.report-table tbody input:checked');
            	var itemSelectedCount = itemSelected.length;
            	jQuery('#shop-items-selected').html(itemSelectedCount);
            	
            	itemSelected.each(function() {
            		itemSelectedPrice += parseFloat(jQuery(this).attr('anlarr:price-marker'));
            	});
            	
            	jQuery('#shop-current-items-price').html(itemSelectedPrice.toFixed(2));
            });
        }
        
        if (jQuery('.shop-group-container').length != 0) {
        	jQuery('.shop-group-container select').change(function() {
        		var selectedGroup = jQuery(this).val();
        		var currencyId = jQuery('#currency-id').val();
        		if (selectedGroup != 0) {
            		window.location.replace('/shop/product/' + currencyId.toLowerCase() + '/product-group/' + selectedGroup);
        		}
        	});
        }
        
        if (jQuery('.shop-product-info-link').length != 0) {
        	jQuery('.shop-product-info-link').click(function() {
        		var productUnique_id = this.getAttribute("product_id");
        		
        		var windowWidth = 900;
        		var windowHeight = 550;
        		var centerWidth = (window.screen.width - windowWidth) / 2;
        	    var centerHeight = (window.screen.height - windowHeight) / 2;

        	    var prdesc = window.open('/products/' + productUnique_id + '.html', 'winname', 'resizable=0, scrollbars=1, width=' + windowWidth + 
        	        ',height=' + windowHeight + 
        	        ',left=' + centerWidth + 
        	        ',top=' + centerHeight);

        	    prdesc.focus();
        		return false;
        	});
        }
        
        if (jQuery('.shop-product-type-order-desc').length != 0) {
        	jQuery('.shop-product-type-order-desc').click(function() {
        		
        		var windowWidth = 600;
        		var windowHeight = 350;
        		var centerWidth = (window.screen.width - windowWidth) / 2;
        	    var centerHeight = (window.screen.height - windowHeight) / 2;

        	    var ordesc = window.open('/products/order_type_description.html', 'winname', 'resizable=0, scrollbars=1, width=' + windowWidth + 
        	        ',height=' + windowHeight + 
        	        ',left=' + centerWidth + 
        	        ',top=' + centerHeight);

        	    ordesc.focus();
        		return false;
        	});
        }
        
        if (jQuery('#shop-product-acquire-button-submit').length != 0) {
        	jQuery('#shop-product-acquire-button-submit').click(function() {
        		var $priceElement = jQuery('#shop-product-type-order-custom-price').val();
        		var newElement = '<input type="hidden" value="'+ $priceElement +'" name="product_price"/>';
        		var newbuttonElement = '<input type="hidden" value="Подтвердить и совершить покупку" name="PRODUCT-ACQUISITION-CONFIRMED"/>';
        		
        		jQuery('#shop-product-acquire-form').append(newbuttonElement);
        		jQuery('#shop-product-acquire-form').append(newElement);
        		jQuery('#shop-product-acquire-form').submit();
        	});
        }
    },
    
    moveToDirectory: function(dest, messages) {
    	var type = jQuery('#directory-type').val();
    	if (type != '')
    	jQuery.ajax({
    		type: 'post',
    		url: '/communicator/message/movetodirectory',
    		data: {'dest': dest, 'messages': messages, 'type': type},
    		success: function(response) {
    			window.location.href = '/communicator/message/' + ((type == 'ingoing') ? 'inbox' : 'outgoing');
    		}
    	});
    },
    
    updateDirectoryList: function() {
    	var dirType = jQuery('#directory-type').val();
    	if (jQuery('.directory-list').length != 0) {
	    	jQuery('.directory-list').load(
	    		'/communicator/message/updatedirectorylist',
	    		{ type: dirType, renderType: 'list' }
	    	);
    	}
    	
    	if (jQuery('#move-to-directory').length != 0) {
	    	jQuery('#move-to-directory').load(
        		'/communicator/message/updatedirectorylist',
        		{ type: dirType, renderType: 'options' }
        	);
	    	if (jQuery('#move-to-directory option').length == 0) {
	    		jQuery('#move-to-directory').css('display', 'none');
	    	}
    	}
    	
    	if (jQuery('#move-to-directory-current-message').length != 0) {
        	jQuery.ajax({
        		type: 'post',
        		url: '/communicator/message/updatedirectorylist',
        		data: { type: dirType, renderType: 'options'},
        		success: function(response) {
        			jQuery('#move-to-directory-current-message').html(response);
        	    	if (jQuery('#move-to-directory-current-message option').length < 1) {
        	    		jQuery('#move-to-directory-current-message').css('display', 'none');
        	    	}
        		}
        	});
       	}
    	if (jQuery('#move-to-directory-current-message option').length < 1) {
    		jQuery('#move-to-directory-current-message').css('display', 'none');
    	}
    },
    
    setUserToChannel: function(status, group_id){
    	jQuery.ajax({
    		type: 'post',
    		url: '/communicator/infochannel/setusertochannel',
    		data: {'status': status, 'group_id': group_id},
    		//async:false,
    		success: function(response) {
    		}
    	});
    },
    
    updateClock: function() {
    	anlarrSystemTime.setTime(anlarrSystemTime.getTime() + 1000);
		jQuery('#system-clock').html(anlarrSystemTime.format('UTC:yyyy.mm.dd HH.MM.ss'));
    },
    
	initWysiwyg: function(elem) {
    	 /* Установка ширины редактора по ширине контейнера для модуля метабазы */
    	/*
    	if (jQuery('#mbborderwrap').length != 0) {
    		var width = jQuery('#mbborderwrap').width();
    		if (jQuery('#message-body').length != 0) {
    			 jQuery('#message-body').width(width);
    		}
    	}
    	*/
    	if (jQuery('.content-main').length != 0) {
            var width = jQuery('.content-main').width();
            if (jQuery('#larrd-description').length != 0) {
                 jQuery('#larrd-description').width(width - 250);
            }
        }
    	
		var wysiwyg = new nicEditor().panelInstance(elem.attr('id'));
	}
};
