var Dir = '';
function RemoveSomeMenu(thisID) {
    $('a#p' + thisID).removeClass('now');
    $('#m' + thisID).fadeOut(0);
}

var navigation = function () {
    var thisID = '';

	$('li#p1').hover(
    		function () {
        		$('#menulink1').addClass('now');
        		$('#m1').fadeIn(0);
		},
		function() {
			$('#menulink1').removeClass('now');
        		$('#m1').fadeOut(0);
        	}
        );

	$('li#p2').hover(
    		function () {
        		$('#menulink2').addClass('now');
        		$('#m2').fadeIn(0);
		},
		function() {
			$('#menulink2').removeClass('now');
        		$('#m2').fadeOut(0);
        	}
        );

	$('li#p3').hover(
    		function () {
        		$('#menulink3').addClass('now');
        		$('#m3').fadeIn(0);
		},
		function() {
			$('#menulink3').removeClass('now');
        		$('#m3').fadeOut(0);
        	}
        );
        
        $('li#p4').hover(
    		function () {
        		$('#menulink4').addClass('now');
        		$('#m4').fadeIn(0);
		},
		function() {
			$('#menulink4').removeClass('now');
        		$('#m4').fadeOut(0);
        	}
        );
        
        $('li#p5').hover(
    		function () {
        		$('#menulink5').addClass('now');
        		$('#m5').fadeIn(0);
		},
		function() {
			$('#menulink5').removeClass('now');
        		$('#m5').fadeOut(0);
        	}
        );
        
	$('li#p6').hover(
    		function () {
        		$('#menulink6').addClass('now');
        		$('#m6').fadeIn(0);
		},
		function() {
			$('#menulink6').removeClass('now');
        		$('#m6').fadeOut(0);
        	}
        );
        
    $('#all, #header, #input_search').mousemove(function () {
        RemoveSomeMenu(thisID);
    });
};

    $(window).load(navigation);
	

function startNavigation() {
	focusNavigation();
    $('.navigationBlock').click(function(e) {
		$(this).removeClass('navigationBlock').addClass('preloaderMini');
		goNavigation(function() {
			$('.preloaderMini').removeClass('preloaderMini').addClass('navigationBlock');
			startNavigation();
		});
	});
}

$(document).ready(function() {
	startNavigation();
});

function focusNavigation() {
$(window).scroll(function () { 
	var scroll = $(window).height() + $(document).scrollTop(), ptop = $('.navigationBlock').offset().top;
	if(ptop == 0) return;
	if (ptop <= scroll) {
		$('.navigationBlock').removeClass('navigationBlock').addClass('preloaderMini');
		goNavigation(function() {
			$('.preloaderMini').removeClass('preloaderMini').addClass('navigationBlock');
			startNavigation();
		});
	}
});
}
    
function elementSupportsAttribute(element, attribute) {
	var test = document.createElement(element);
	if (attribute in test) {
		return true;
	} else {
		return false;
	}
}

var documentFunctions = {
	mouseWait: function() {
		document.body.style.cursor = 'wait';
	},
	mouseNormal: function() {
		document.body.style.cursor = 'default';
	},
	getId: function(param) {
		return document.getElementById(param);
	},
	inputCheck: function(params) {
		
		windowsManager.windowsError = false;
		
		for (var key in params) {
			
			id = params[key];
			
			ajaxRequest.dataToSend += params[key].replace('#', '') + '=' + this.inputValue(id) + '&';
			
			if(this.inputValue(id) != "") continue;
			
			//documentFunctions.inputError(id);
			
			windowsManager.windowsError = true;
		}
		
		if(windowsManager.windowsError)
		documentFunctions.inputError();
	},
  formError: function(field, params) {
    $('span[class*='+field+'T]').html(params.error);
    $('div[class*='+field+']').fadeIn(300);
    setTimeout('$("div[class*=field-error]").fadeOut(300)', 5000);
  },
	inputError: function(/*id*/) {
		ajaxRequest.error({error:'Indicated not all the necessary information'});return;
		/*$(id).css({'border':'1px red solid','opacity':'0.1'}).fadeTo(2000,1).fadeTo("slow",0.1, function() {
			$(id).css({'border':'1px #cccccc solid','opacity':'1'});
		});*/
	},
	inputValue: function(id) {
		return $(id).val();
	},
	pageRefresh: function() {
		setInterval('location.reload(true)', 1000);
	},
	microtime: function(get_as_float) {
		var now = new Date().getTime() / 1000;
		var s = parseInt(now, 10);
 
		return (get_as_float) ? now : (Math.round((now - s) * 1000) / 1000) + ' ' + s;
	}
}

var infoLine = {

	microtime: documentFunctions.microtime(true),
	
	info: function(e) {
		this.microtime = documentFunctions.microtime(true);
		$('#debug').html(e).fadeIn('slow');
	},
	close: function() {
		if((documentFunctions.microtime(true) - this.microtime) > 3 ) {
			$('#debug').fadeOut('slow');
		}
		setTimeout('infoLine.close()', 6000);
	}
};

var ajaxRequest = {

	dataToSend: '',

	error: function(e) {
		infoLine.info(e.error);
	},
	send: function(Params) {
		$.ajax({
			url: Dir + Params.url,
			type: 'POST',
  		dataType: 'json',
			data: Params.data,
			async: true,
			success: function(e) {
				if(Params.success) {
					Params.success(e);
				}
			},
			error: function(e) {alert(print_r(e));
				if(Params.error) {
					Params.error(e);
				} else {
					ajaxRequest.error(e);
				}
			},
			complete: function(e) {
				
				setTimeout('windowsManager.windowsTrying = false', 100);
				
				infoLine.close();
				
				if(Params.complete) {
					Params.complete(e);
				}
			}
		});
	}
}

var windowsManager = {	
	windowHeight: $(window).height(),
	windowWidth:  $(window).width(),
	
	id:   '#modal',
	mask: '#mask',
	
	target: '',
	module: '',
	params: '',
	
	maximaze: false,
	
	counter: 0,
	
	windowsError: false,
	windowsTrying: false,
	
	windowData: new Array(),
	
	windowsReady: function(e) {
		$('a[class*=modal]').unbind();
		/* $( ".window" ).draggable({
			cursor: 'auto',
      containment: 'body'
		}); Bad work */
		$(window).keypress(function(e) {
			if (e.keyCode == 27 || e.keyCode == 96)  {
				windowsManager.close();
			}
		});
		$('a[class*=modal]').click(function(e) {
			e.preventDefault();
			windowsManager.windowsRestore();
			
			windowsManager.target = $(this).attr('name');
			windowsManager.module = $(this).attr('module');
			windowsManager.params = $(this).attr('params');
			
			windowsManager.fadeMask();
			
			windowsManager.windowsCenter();
			
			$(windowsManager.id).fadeIn(0, function() {
				windowsManager.fadeWindowMask();
				windowsManager.windowsButtons();
				
				windowsManager.counter++;
				documentFunctions.mouseWait();
				
				windowsManager.windowsTrying = true;
				
				ajaxRequest.send({
					url: '/forms.php',
					data: 'target=' + windowsManager.target + "&module=" + windowsManager.module + "&params=" + windowsManager.params,
					success: function(e) {
						windowsManager.windowsSaveData();
						
						windowsManager.windowsSetData(e);
						windowsManager.windowsCenter();
						windowsManager.windowsCreateButtons(e);
						
						windowsManager.windowsButtons();
						
						documentFunctions.mouseNormal();
						
						$('a[class*=modal]').unbind();
						windowsManager.windowsReady();
						
						windowsManager.windowLoad();
					}
				});
			});
		});
	},
	open: function(Properties) {
		if(Properties) {
			if(!documentFunctions.getId('newWindow'))
				newWindow = document.createElement('a'); 
			else
				newWindow = documentFunctions.getId('newWindow');
				
			newWindow.setAttribute('class', 'modal'); 		
			newWindow.setAttribute('id', 'newWindow'); 
			
			newWindow.setAttribute('name', Properties.name); 	
			newWindow.setAttribute('module', Properties.module); 	
			newWindow.setAttribute('params', Properties.params); 
			
			document.getElementById('boxes').appendChild( newWindow );
		}
		
		windowsManager.windowsReady();
		
		$('#newWindow').click();
	},
	close: function() {
		$(windowsManager.mask).fadeOut(0);
		$('.windowMask').fadeOut(0);
		$('.window').fadeOut(0, function() {
			documentFunctions.mouseNormal();		
			windowsManager.windowsRestore();
		});
	},
	windowsSaveData: function() {
		windowsManager.windowData.oldTitle 		= $('#' + $(windowsManager.id).attr('topic')).html();
  		windowsManager.windowData.oldText 		= $('#' + $(windowsManager.id).attr('text')).html();
  		windowsManager.windowData.oldData 		= $('#' + $(windowsManager.id).attr('data')).html();
  		windowsManager.windowData.oldButtons	= $('#' + $(windowsManager.id).attr('buttons')).html();
  		windowsManager.windowData.oldWidth 		= $(windowsManager.id).width();
  		windowsManager.windowData.oldHeight 	= $(windowsManager.id).height();
	},
	windowsRestore: function() {
		if(windowsManager.counter<1)
			return false;
			
		$('#' + $(windowsManager.id).attr('topic')).html(windowsManager.windowData.oldTitle);
  		$('#' + $(windowsManager.id).attr('text')).html(windowsManager.windowData.oldText);
  		$('#' + $(windowsManager.id).attr('data')).html(windowsManager.windowData.oldData);
  		$('#' + $(windowsManager.id).attr('buttons')).html(windowsManager.windowData.oldButtons);
  		$(windowsManager.id).css({'width':windowsManager.windowData.oldWidth, 'height':windowsManager.windowData.oldHeight});
  		
		$("#dialogMask").css({
			'top': windowsManager.windowHeight/2 - $(windowsManager.id).height()/2 - 10,
			'left': windowsManager.windowWidth/2 - $(windowsManager.id).width()/2 - 10
		});
		
		$("#dialogMask").css({'width':windowsManager.windowData.oldWidth+20, 'height':windowsManager.windowData.oldHeight+20});
		$('#' + $(windowsManager.id).attr('topic')).css({'width':windowsManager.windowData.oldWidth-10});
	},
	windowsSetData: function(e) {
		$('#' + $(windowsManager.id).attr('topic')).html(e.title);
  		$('#' + $(windowsManager.id).attr('text')).html(e.text);
  		$('#' + $(windowsManager.id).attr('data')).html(e.data);
  		$('#' + $(windowsManager.id).attr('buttons')).html(e.buttons);
		
		$('#' + $(windowsManager.id).attr('topic')).css({'width': parseInt(e.windowWidth)-10});
  		$(windowsManager.id).css({
			'width': parseInt(e.windowWidth),
			'height': parseInt(e.windowHeight),
			'top': windowsManager.windowHeight/2 - parseInt(e.windowHeight)/2,
			'left': windowsManager.windowWidth/2 - parseInt(e.windowWidth)/2 
		}); 
		windowsManager.fadeWindowMask(e);
	},
	windowsCenter: function() {
		$(windowsManager.id).css({'top': (windowsManager.windowHeight/2 - $(windowsManager.id).height()/2), 'left': (windowsManager.windowWidth/2-$(windowsManager.id).width()/2)});
	},
	windowsButtons: function() {
		this.buttonsEvents();
		
		this.buttonClose();
		this.buttonMaximize();
	},
	windowsCreateButtons: function(e) {
		if(e.close)
			$('<div class="topbuttons close" title="Закрыть"></div>').appendTo('#' + $(windowsManager.id).attr('topic'));
  		if(e.maximaze) {
  			$('<div class="topbuttons maximaze" title="Развернуть"></div>').appendTo('#' + $(windowsManager.id).attr('topic'));
			windowsManager.maximaze = e.maximaze;
  		}
	},
	buttonsEvents: function() {	
		$('div.topbuttons').hover(function() {
        	$(this).fadeTo('fast', 1);
		},
		function() {
			$(this).fadeTo('fast', 0.5);
        });
	},
	buttonClose: function() {
		$('.window .close').click(function (e) {
			e.preventDefault();
			
			$(windowsManager.mask).fadeOut(0);
			$('.windowMask').fadeOut(0);
			$('.window').fadeOut(0, function() {
				documentFunctions.mouseNormal();		
				windowsManager.windowsRestore();
			});
		});
	},
	buttonMaximize: function() {
		$('.window .maximaze').click(function (e) {
			e.preventDefault();
			
			document.location = windowsManager.maximaze;
		});	
	},
	fadeMask: function(e) {
  $(this.mask).css({'width': this.windowWidth, 'height': this.windowHeight});		
		$(this.mask).fadeIn(0);
	},
	fadeWindowMask: function(e) {		
	 $("#dialogMask").css({
			'top': windowsManager.windowHeight/2 - $(windowsManager.id).height()/2 - 10,
			'left': windowsManager.windowWidth/2 - $(windowsManager.id).width()/2 - 10
		});	
			
		if(e) {			
			$("#dialogMask").css({
				'width': parseInt(e.windowWidth) + 20,
				'height': parseInt(e.windowHeight) + 20
			});	
		}
		
		$("#dialogMask").fadeIn(0);
	},
	windowLoad: function() {
		windowInit();
	}
}

var fileTransfer = {

	dropZone: '',
  maxFileSize: 0,
  func: false,
  
	init: function(Zone, maxSize) {
    dropZone = $(Zone),
    maxFileSize = maxSize;
    
    if (typeof(window.FileReader) == 'undefined') {
      dropZone.text('Not supported by your browser!');
      dropZone.addClass('error');
    }
    
    dropZone[0].ondragover = function() {
      dropZone.addClass('hover');
      return false;
    };
    
    dropZone[0].ondragleave = function() {
      dropZone.removeClass('hover');
      return false;
    };
  },
  ondrop: function(f) {
  
    fileTransfer.func = f;
    
    dropZone[0].ondrop = function() {
      event.preventDefault();
      dropZone.removeClass('hover');
      dropZone.addClass('drop');
      
      var file = event.dataTransfer.files[0];
          
      if (file.size > maxFileSize) {
        dropZone.text('File is too big!');
        dropZone.addClass('error');
        return false;
      }
      
      var xhr = new XMLHttpRequest();
      xhr.upload.addEventListener('progress', fileTransfer.uploadProgress, false);
      xhr.onreadystatechange = fileTransfer.stateChange;
      xhr.open('POST', Dir + '/upload.php');
      xhr.setRequestHeader('X-FILE-NAME', file.name);
      var fd = new FormData;
      fd.append("file", file);
      xhr.send(fd);
    }
  },
  uploadProgress: function(event) {
    var percent = parseInt(event.loaded / event.total * 100);
    dropZone.text('Loading: ' + percent + '%');
  },
  stateChange: function(event) {
      if (event.target.readyState == 4) {
        if (event.target.status == 200) {
            dropZone.text('Download completed successfully!');
            fileTransfer.func(event.target.responseText);
        } else {
            dropZone.text('An error occurred!');
            dropZone.addClass('error');
        }
      }
    }
}
  
$(document).ready(function() {
	windowsManager.windowsReady();
  function setupLabel() {
        if ($('.label_check input').length) {
            $('.label_check').each(function(){ 
                $(this).removeClass('c_on');
            });
            $('.label_check input:checked').each(function(){ 
                $(this).parent('label').addClass('c_on');
            });                
        };
        if ($('.label_radio input').length) {
            $('.label_radio').each(function(){ 
                $(this).removeClass('r_on');
            });
            $('.label_radio input:checked').each(function(){ 
                $(this).parent('label').addClass('r_on');
            });
        };
    };
    $(document).ready(function(){
        $('.label_check, .label_radio').click(function(){
            setupLabel();
        });
        setupLabel(); 
    });
});

function visible(){}
function print_r(arr, level) {
    var print_red_text = "";
    if(!level) level = 0;
    var level_padding = "";
    for(var j=0; j<level+1; j++) level_padding += "    ";
    if(typeof(arr) == 'object') {
        for(var item in arr) {
            var value = arr[item];
            if(typeof(value) == 'object') {
                print_red_text += level_padding + "'" + item + "' :\n";
                print_red_text += print_r(value,level+1);
		} 
            else 
                print_red_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
        }
    } 

    else  print_red_text = "===>"+arr+"<===("+typeof(arr)+")";
    return print_red_text;
}
