//jadmin buttons
jQuery.fn.button = function(options) {
    return this.each(function() {
        $(this).disableTextSelect();
        $(this).mousedown(function() {
            $(this).addClass("pushed");
        });
        $(this).mouseup(function() {
            $(this).removeClass("pushed");
        });
        $(this).hover(function() {
            $(this).addClass("hover");
        }, function() {
            $(this).removeClass("hover pushed");
        });
    });    
};

//jadmin tabs
jQuery.fn.tabs = function(options) {
    var options = jQuery.extend({
    }, options);
    return this.each(function() {
        $(this).find(".head a").disableTextSelect();
        $(this).find(".head a").click(function() {
            $(this).closest(".head").find("a").removeClass("active");
            $(this).addClass("active");
            $(this).closest(".head").parent().find(".content .tab").hide();
            var id = $(this).attr("rel");
            $(id).show();
            return false;
        });
        $(this).find(".head a.active").click();
    });    
};

//jadmin select
jQuery.fn.select = function(options) {
    var options = jQuery.extend({
    	onchange : function() {},
    }, options);
    return this.each(function() {
    	var Select = $(this);
    	var Value = $(this).find("span.value");
    	var List = $(this).find(".list");
    	var Input = $(this).find("input");
    	
        Select.disableTextSelect();
        
        Value.click(function() {
			List.fadeIn(180);
        });
        
        List.find("a").click(function() {
			Input.val($(this).attr("rel"));
			Value.text($(this).text());
			List.fadeOut(180);
			options.onchange($(this).attr("rel"));
        });
        
        // устанавливаем начальное значение
        var a = $(this).find('a[rel="' + Input.val() + '"]');
		Input.val(a.attr("rel"));
		Value.text(a.text());
    });    
};

//jadmin ajaxselect
jQuery.fn.ajaxselect = function(options) {
    var options = jQuery.extend({
    	onchange : function() {},
    	getsome : false,
    }, options);
    return this.each(function() {

    	// оборачиваем исходный инпут в нужную конструкцию
		var Value = $(this).wrap("<div />");
  		var Select = Value.parent();
  		Select.addClass(Value.attr("class"));
  		Select.append('<input type="text" class="view" value="' + Value.attr("title") + '" />');
  		Select.append('<div class="list" />');
  		var View = Select.find("input.view");
  		View.addClass(Value.attr("class"));
  		View.attr("style", Value.attr("style"));
    	var List = Select.find(".list");
    	var Loader = Select.find(".loader");
    	var FixedValueText;
    	var FixedValueVal;
    	var SearchTime;
    	var HideTime;
    	var ActivePos;
    	var SearchText;
    	var Initialized = false;
    	
    	/*
    	 * При нажатии на сцылку в листе происходит вызов этой функции
    	 */
    	function ChangeValue(a) {
			Value.val(a.attr('rel'));
			View.val(a.attr('caption'));
			FixedValueText = View.val();
			FixedValueVal = Value.val();
			options.onchange(Value, FixedValueVal);
    	}

        /*
         * После обновления списка, нужно повесить на его сцылки события
         */
        function InitListEvents() {
	        List.find("a").mousedown(function() {
	        	clearTimeout(HideTime);
				ChangeValue($(this));
				List.fadeOut(60);
	        });
        }
    	
    	function SetActivePos(pos) {
			$(List.find("a").get(ActivePos)).removeClass("active");
			ActivePos = pos;
			$(List.find("a").get(pos)).addClass("active");
    	}
    	
    	/*
    	 * Построение списка
    	 */
        function InitListPositions(search) {
        	Loader.show();
			$.post(Value.attr("rel"), 
			    {'search': search},
				function(data) {
			    	List.html(data);
			    	InitListEvents();
			    	Initialized = true;
			    	Loader.hide();
			    	SetActivePos(0);
				}, "json");
        }
   	
    	// при нажатии клавиши засылаем пост запрос и получаем в ответ
    	// список позиций
        View.keydown(function(event) {
        	if (event.which == 13) {
				ChangeValue($(List.find("a").get(ActivePos)));
				List.hide();
				InitListPositions('');
				return false;
			}
			else if(event.which == 38) {
				SetActivePos(ActivePos - 1);
				return true;
			}
			else if(event.which == 40) {
				SetActivePos(ActivePos + 1);
				return true;
			}
        	else {
        		if (View.val() != SearchText) {
        			clearTimeout(SearchTime);
        			SearchTime = setTimeout(function(){InitListPositions(View.val())}, 300);
        			List.fadeIn(60);
        		}
        	}
        });
        
        // при снятии фокуса - прячем список и восстанавливаем прошлый вид
        View.blur(function () {
			HideTime = setTimeout(function() {List.fadeOut(60)}, 100);
			Value.val(FixedValueVal);
			View.val(FixedValueText);
        })
        
        // при получении фокуса - открываем список
        View.focus(function () {
        	clearTimeout(HideTime);
        	if ((!Initialized) || (View.val() != SearchText) || (options.getsome)) InitListPositions('');
			List.fadeIn(60);
        })
        
		FixedValueText = View.val();
		SearchText = View.val();
		FixedValueVal = Value.val();
		options.onchange(Value, FixedValueVal);
    });    
};


/* ===========================================================================
 * checkbox
 * оборачивает стандартный инпут типа checkbox дивом,
 * вешает события на клик мышки
 * по клику переключает класс checked и меняет значение инпута
 * ===========================================================================*/ 
jQuery.fn.checkbox = function(options) {
    var options = jQuery.extend({
    	onchange : function() {},
    }, options);
  		    
    return this.each(function() {
    	// оборачиваем, задаем аттрибуты
    	var Input = $(this);
  		Input.wrap("<div />");
  		var Box = Input.parent();
  		Box.addClass(Input.attr("class")).prepend(Input.attr("title")).attr("style", Input.attr("style"));
    	
    	// выключаем выделение текста для всего чекбокса
    	Box.disableTextSelect();
    	
    	// вешаем обработку на клик мышки
    	Box.click(function() {
    		if (!Box.hasClass("locked")) {
    			if (Box.hasClass("checked")) {
    				Box.removeClass("checked");
    				Input.val(0);
    				options.onchange();
    			} else {
    				Box.addClass("checked");
    				Input.val(1);
    				options.onchange();
    			}
    		}
    	});
    	
    	// начальный запуск, если инпут имеет значение 1, то сразу выставляем класс checked
    	if (Input.val() == "1") {
    		Box.addClass("checked");
    	}
    	
    });    
};

//jadmin counter
jQuery.fn.counter = function(options) {
    var options = jQuery.extend({
    }, options);
    return this.each(function() {
    	var Counter = $(this);
    	var Input = Counter.find("input");
    	var Text = Counter.find(".text");
    	var Up = Counter.find(".up");
    	var Down = Counter.find(".down");
    	
    	Counter.disableTextSelect();
    	
    	// вешаем событие
    	Up.click(function() {
    		val = parseInt(Input.val());
    		if (val < 10) {
    			Input.val(val + 1);
    			Text.text(val + 1);
    		}
    	});

    	// вешаем событие
    	Down.click(function() {
    		val = parseInt(Input.val());
    		if (val > -10) {
    			Input.val(val - 1);
    			Text.text(val - 1);
    		}
    	});
    });    
};

//j image uploader
jQuery.fn.imageUploader = function(options) {
	return this.each(function() {
		var elem = $(this);
		var wrapper = $('<div class="divfile"><form id="uploadform" action="' + options.action + '" target="upload_target" method="post" enctype="multipart/form-data"></form></div>');
		elem.css({"display": "block"}).wrap(wrapper);
		var iframe = $('<iframe style="display: none;" name="upload_target" id="upload_target"></iframe>');				
		var img = elem.attr("rel");
		elem.before('<img src="' + img + '" alt="" />');
		elem.after(iframe);
	    elem.change(function() {
	        $("#upload_target").unbind('load');
	        $("#upload_target").load(function() {
	        	$(".divfile").find("img").remove();
	            $(".divfile").append($(this).contents().find("#__upload").html());
	            $(this).contents().find("#__upload").html("");
	        });
	        $("#uploadform").submit();
	    });
	});
};

//jadmin disable text select
if ($.browser.mozilla) {
    $.fn.disableTextSelect = function() {
        return this.each(function() {
            $(this).css({
                'MozUserSelect' : 'none'
            });
        });
    };
    $.fn.enableTextSelect = function() {
        return this.each(function() {
            $(this).css({
                'MozUserSelect' : ''
            });
        });
    };
} else if ($.browser.msie) {
    $.fn.disableTextSelect = function() {
        return this.each(function() {
            $(this).bind('selectstart.disableTextSelect', function() {
                return false;
            });
        });
    };
    $.fn.enableTextSelect = function() {
        return this.each(function() {
            $(this).unbind('selectstart.disableTextSelect');
        });
    };
} else {
    $.fn.disableTextSelect = function() {
        return this.each(function() {
            $(this).bind('mousedown.disableTextSelect', function() {
                return false;
            });
        });
    };
    $.fn.enableTextSelect = function() {
        return this.each(function() {
            $(this).unbind('mousedown.disableTextSelect');
        });
    };
}

/*
 * Автоматическое составление массива по элементам формы
 */
function GetFormData(form) {
    var a = {};
    form.find("*").map(function() {
		if ($(this).attr("name") != "") {
			a[$(this).attr("name")] = $(this).val();
		}
    });
    return a;
}

// возвращает cookie если есть или undefined
function getCookie(name) {
	var matches = document.cookie.match(new RegExp("(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"));
	return matches ? decodeURIComponent(matches[1]) : undefined;
}

// уcтанавливает cookie
function setCookie(name, value, props) {
	props = props || {};
	var exp = props.expires;
	if (typeof exp == "number" && exp) {
		var d = new Date();
		d.setTime(d.getTime() + exp*1000);
		exp = props.expires = d;
	} else {
		var d = new Date();
		d.setTime(d.getTime() + 3000*1000);
		exp = props.expires = d;
	}
	if (exp && exp.toUTCString) {
		props.expires = exp.toUTCString();
	}

	value = encodeURIComponent(value);
	var updatedCookie = name + "=" + value;
	for (var propName in props) {
		updatedCookie += "; " + propName;
		var propValue = props[propName];
		if (propValue !== true) {
			updatedCookie += "=" + propValue; 
		}
	}
	document.cookie = updatedCookie
}

// удаляет cookie
function deleteCookie(name) {
	setCookie(name, null, { expires: -1 });
}

