/**
 * --------------------------------------------------------------------
 * jQuery-Plugin "toggleElements"
 * Version: 1.3, 11.09.2007
 * by Andreas Eberhard, andreas.eberhard@gmail.com
 *                      http://jquery.andreaseberhard.de/
 *
 * Copyright (c) 2007 Andreas Eberhard
 * Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
 *
 * Changelog:
 *    11.09.2007 Version 1.3
 *    - removed noConflict
 *    - added 'opened'-state via additional class 'opened'
 *    02.07.2007 Version 1.2.1
 *    - changed blur to work with jQuery 1.1.3
 *    - added packed version
 *    27.06.2007 Version 1.2
 *    - suppress multiple animations
 *    15.06.2007 Version 1.1
 *    - added callbacks onClick, onShow, onHide
 *    - added option showTitle
 *    31.05.2007 initial Version 1.0
 * --------------------------------------------------------------------
 * @example $(function(){$('div.toggler-1').toggleElements( );});
 * @desc Toggles the div with class 'toggler-1' into closed state on document.ready
 *
 * @example $(function(){$('fieldset.toggler-9').toggleElements( { fxAnimation:'show', fxSpeed:1000, className:'toggler', onClick:doOnClick, onHide:doOnHide, onShow:doOnShow } );});
 * @desc Toggles the fieldset with class 'toggler-9' into closed state on document.ready
 *       Animation show with speed 1000 ms is used, for the different states the css-class-prefix 'toggler-' will be used
 *       Events OnClick, OnHide, OnShow will call your JavaScript-functions
 * --------------------------------------------------------------------
 */

var toggleElements_animating = false;

(function(jQuery) {

jQuery.fn.toggleElements = function(settings) {

	// Settings
	settings = jQuery.extend({
		fxAnimation: "slide",   // slide, show, fade
		fxSpeed: "normal",   // slow, normal, fast or number of milliseconds
		className: "toggler",
		removeTitle: true,
		showTitle: true,
		onClick: null,
		onHide: null,
		onShow: null
	}, settings);

	var onClick = settings.onClick, onHide = settings.onHide, onShow = settings.onShow;

	if ((settings.fxAnimation!='slide')&&(settings.fxAnimation!='show')&&(settings.fxAnimation!='fade'))
		settings.fxAnimation='slide';

	// First hide all elements without class 'opened'
	this.each(function(){
		if (jQuery(this).attr('class').indexOf("opened")==-1){
			jQuery(this).hide();
		}
	});

	// Add Toggle-Links before elements
	this.each(function(){

		wtitle='';
		wlinktext=jQuery(this).attr('title');
		var img1 = jQuery(this).parent().attr('image');
		if(!img1 || img1=="assets/images/notarius-01.jpg") img1 = jQuery(this).attr('image');
		
		
//		var docs = jQuery(this).parent().attr('docs');
		 docs = jQuery(this).attr('docs');
		
		
//		var consultation = jQuery(this).parent().attr('consultation');
		consultation = jQuery(this).attr('consultation');

		if(docs) docs = '<a href="'+docs+'">Документи</a>'; else docs='';
		if(consultation) consultation = '<a href="'+consultation+'">Консультації</a>'; else consultation='';

		
		var add= docs+''+consultation+' ';  
		
		
		if (settings.showTitle==true) wtitle=wlinktext;
		if (settings.removeTitle==true) jQuery(this).attr('title','');
		if (jQuery(this).attr('class').indexOf("opened")!=-1){
			jQuery(this).before('<div class="dop">'+add+'</div>'+'<a class="'+settings.className+' '+settings.className+'-opened" href="#" title="'+ wtitle +'" image="'+img1+'">' + wlinktext + '</a>');
			jQuery(this).addClass(settings.className+'-c-opened');
		} else {
			jQuery(this).before('<div class="dop">'+add+'</div>'+'<a class="'+settings.className+' '+settings.className+'-closed" href="#" title="'+ wtitle +'" image="'+img1+'">' + wlinktext + '</a>');
			jQuery(this).addClass(settings.className+'-c-closed');
		}
//		jQuery(this).after();
//		<div class="dop">'+add+'</div>
		// Click-Function for Toggle-Link
		jQuery(this).prev('a.'+settings.className).click(function() {
			if (toggleElements_animating) return false;

			thelink = this;
			jQuery(thelink)[0].blur();
			if (thelink.animating||toggleElements_animating) return false;
			toggleElements_animating = true;
			thelink.animating = true;

			// Callback onClick
			if ( typeof onClick == 'function' && onClick(thelink) === false) {
				toggleElements_animating = false;
				thelink.animating = false;
				return false;
			}

			// Hide Element
			if (jQuery(this).next().css('display')=='block') {
				jQuery(this).next().each(function(){
					if (settings.fxAnimation == 'slide') jQuery(this).slideUp(settings.fxSpeed,function(){
						jQuery.toggleElementsHidden(this,settings.className,onHide,thelink);
					});
					if (settings.fxAnimation == 'show') jQuery(this).hide(settings.fxSpeed,function(){
						jQuery.toggleElementsHidden(this,settings.className,onHide,thelink);
					});
					if (settings.fxAnimation == 'fade') jQuery(this).fadeOut(settings.fxSpeed,function(){
						jQuery.toggleElementsHidden(this,settings.className,onHide,thelink);
					});
				});
			// Show Element
			} else {
				jQuery(this).next().each(function(){
					if (settings.fxAnimation == 'slide') jQuery(this).slideDown(settings.fxSpeed,function(){
						jQuery.toggleElementsShown(this,settings.className,onShow,thelink);
					});
					if (settings.fxAnimation == 'show')  jQuery(this).show(settings.fxSpeed,function(){
						jQuery.toggleElementsShown(this,settings.className,onShow,thelink);
					});
					if (settings.fxAnimation == 'fade')  jQuery(this).fadeIn(settings.fxSpeed,function(){
						jQuery.toggleElementsShown(this,settings.className,onShow,thelink);
					});
				});
			}
			return false;

		});

	});

};

// Remove/Add classes to Toggler-Link
jQuery.toggleElementsHidden = function(el,cname,onHide,thelink) {
	jQuery(el).prev('a.'+cname).removeClass(cname+'-opened').addClass(cname+'-closed').blur();
	if ( typeof onHide == 'function') onHide(this); // Callback onHide
	jQuery(el).removeClass(cname+'-c-opened').addClass(cname+'-c-closed');
	toggleElements_animating = false;
	thelink.animating = false;
};
jQuery.toggleElementsShown = function(el,cname,onShow,thelink) {
	jQuery(el).prev('a.'+cname).removeClass(cname+'-closed').addClass(cname+'-opened').blur();
	if ( typeof onShow == 'function') onShow(this); // Callback onShow
	jQuery(el).removeClass(cname+'-c-closed').addClass(cname+'-c-opened');
	toggleElements_animating = false;
	thelink.animating = false;
};

})(jQuery);



jQuery.fn.helpInput = function(o){
	/** Устанавливаются стандартные значения опций */
	var o = jQuery.extend({
		/** Поддержка втозаполнения полей */
		autoComplete: true,
		/** Класс div-муляжа */
		dummyClass: 'divInput',
		/** Класс выделенного text или password объекта */
		selectedTextFileClass: 'selectedInput',
		/** Класс иного выделенного объекта */
		selectedAnotherFileClass: 'selectedAnother'
	},o);

	/** Функция для нахождения следующего доступного для фокусв элемента(с проверкой на видимость) */
	function goToTab(obj,next){
		/** Если элемент видимый - делаем на него фокус */
		if(obj.is(':visible'))
			obj.focus();
		/** Если объект text или password и его муляж видимый - делаем фокус на input */
		else if(obj.data('tp') && obj.next().is(':visible'))
			obj.show().focus().next().hide();
		/** Иначе объект скрыт и мы переходим на следующий объект */
		else if(next)
			goToTab(obj.data('nt'),true);
		else
			goToTab(obj.data('pt'),false);
	}

	return this.each(function(e,form){
		/** Список всех элементов формы */
		var allObj = jQuery('input,textarea',form);
		/** Кол-во всех элементов формы */
		var objCount = allObj.length;
		/** Каждому объекту из списка устанавливаем события и свойства */
		allObj.each(function(e,i){
			var obj = jQuery(i);
			/** tabindex элемента */
			var tabIndex = +obj.attr('tabindex');
			/** Следующий tabindex */
			var nextTabIndex = (tabIndex+1>objCount)?1:tabIndex+1;
			/** Следующий элемент */
			var nextTab = jQuery('*[tabindex='+nextTabIndex+']',form);	
			obj.data('nt',nextTab);
			nextTab.data('pt',obj);
			if (obj.is('[type=text]')||obj.is('[type=password]')){
				obj .data('tp',true)
					.focus(function(){
						obj.addClass(o.selectedTextFileClass);
					})
					.blur(function(){
						if (obj.val().length) {
							obj.removeClass(o.selectedTextFileClass);
						} else {
							obj.hide().next().show();
						}
					})
					.keydown(function(event){
						/** Переопределяется событие клавиши Tab */
						if (event.keyCode == 9) {
							obj.blur();
							/** Зажата ли кнопка Tab */
							if(event.shiftKey){
								goToTab(obj.data('pt'),false);
							}else{
								goToTab(nextTab,true);
							}
							return false;
						} 
					})
					.hide()
					.next()
					.addClass(o.dummyClass)
					.addClass(obj.attr('class'))
					.show();
					
				/** По щелчку на div-муляж, прячем его и показывает input */
				obj.next().click(function(){
					jQuery(this).hide();
					obj.show().focus();
				});
				
				if(o.autoComplete){
					if(obj.val().length) 
						obj.next().click();
				}else{
					obj.val('');
				}
			} else {
				obj .data('tp',false)
					.focus(function(){
						obj.addClass(o.selectedAnotherFileClass);
					})
					.blur(function(){
						obj.removeClass(o.selectedAnotherFileClass);
					})
					.keydown(function(event){
						if (event.keyCode == 9) {
							obj.blur();
							if(event.shiftKey){
								goToTab(obj.data('pt'),false);
							}else{
								goToTab(nextTab,true);
							}
							return false;
						} 
				});			
			}
		});
	});
}



/* SITE SCRIPTS */

$(function() {
	$("div.acc").toggleElements( { fxAnimation:'slide', fxSpeed:'fast', className:'toggler2'});
	
	$('div#acc a.toggler2').click(function(){
		var img=$(this).attr('image');
		//if(img=="assets/images/notarius-01.jpg" || (img!='undefined' && !img)) {img = $(this).parent().parent().attr('image');}
		var cur_img = $('.image_wrapper img').eq(0).attr('src');
		//if(img!='undefined') {if(img!=cur_img) {$('.col3').html('<img src="phpthumb/phpThumb.php?f=jpeg&amp;q=199;w=200&amp;src=/new/'+img+'" class="pngfix">');}}
		if(img=='undefined'){return false;}
		else
		{
		if(img!='' && img!='phpthumb/phpThumb.php?f=jpeg&amp;w=215&amp;src=/'+cur_img) {
					$('.image_wrapper').html('<img src="phpthumb/phpThumb.php?f=jpeg&amp;w=215&amp;src=/'+img+'" class="pngfix">');
			}
			else
			{
					$('.image_wrapper').html('<img src="assets/images/notarius-01.jpg" class="pngfix">');
			}
		}
	}); 
	
	$("#cf form").helpInput();
	
    $('.image_wrapper img').each(function() {
        var maxWidth = 215; // Max width for the image
        var maxHeight = 379;    // Max height for the image
        var ratio = 0;  // Used for aspect ratio
        var width = $(this).width();    // Current image width
        var height = $(this).height();  // Current image height
 
        // Check if the current width is larger than the max
        if(width > maxWidth){
            ratio = maxWidth / width;   // get ratio for scaling image
            $(this).css("width", maxWidth); // Set new width
            $(this).css("height", height * ratio);  // Scale height based on ratio
            height = height * ratio;    // Reset height to match scaled image
            width = width * ratio;    // Reset width to match scaled image
        }
 
        // Check if current height is larger than max
        if(height > maxHeight){
            ratio = maxHeight / height; // get ratio for scaling image
            $(this).css("height", maxHeight);   // Set new height
            $(this).css("width", width * ratio);    // Scale width based on ratio
            width = width * ratio;    // Reset width to match scaled image
        }
        });

	
});

function popUp(URL) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=1,menubar=1,resizable=1,width=500,height=500,left = 470,top = 200');");
}


/*$(document).ready(function(){
	$("#cf form").helpInput();
	
});
*/
