/**
 * Раскраска таблиц под "Зебру
 */
var zebra = function (e) {
	var rows = document.getElementsByTagName('TR');
	var rows_quant = rows.length;
	for (var i = 0; i < rows_quant; ++i) {
		if ((i + 1) % 2) {
			rows[i].className += ' bg'
		};
	}
}
/*var init = function () {
	zebra();
}
if (window.addEventListener) {
	window.addEventListener('load', init, false);
} else if (window.attachEvent) {
	window.attachEvent('onload', init);
}*/
/**
 * /Раскраска таблиц под "Зебру"
 */

/**
 * Вадим
 */

function elama_top_menu_on($id) {
	document.getElementById($id).style.backgroundImage = 'url(/bitrix/templates/elama/img/mlinkr1.gif)';
}

function elama_top_menu_off($id) {
	if (document.getElementById($id).className != 'mlink_div_active' && document.getElementById($id).className != 'mlink_fdiv') {
		document.getElementById($id).style.backgroundImage = 'url(/bitrix/templates/elama/img/mlinkr.gif)';
	}
	if (document.getElementById($id).className == 'mlink_fdiv') {
		document.getElementById($id).style.backgroundImage = 'none';
	}
}

function elama_top_menu_off_f($id) {
	if (document.getElementById($id).className != 'mlink_div_active') {
		document.getElementById($id).style.backgroundImage = 'none';
	}
}

function elama_js_search_1_on(menu_position) {
	var object = document.getElementById("elama_js_search_1");
	object.style.display = "block";
	object.style.top = menu_position["bottom"];
	object.style.left = menu_position["left"];
	jsUtils.addEvent(document, "click", elama_js_search_1_check_click_f);
	jsUtils.addEvent(document, "keypress", elama_js_search_1_on_key_press_f);
}

function elama_js_search_1_off() {
	var object = document.getElementById("elama_js_search_1");
	object.style.display = "none";
	jsUtils.removeEvent(document, "click", elama_js_search_1_check_click_f);
	jsUtils.removeEvent(document, "keypress", elama_js_search_1_on_key_press_f);
}
elama_js_search_1_check_click_f = function elama_js_search_1_check_click(e) {
	if (!e) e = window.event
	if (!e) return;
	var object = document.getElementById("elama_js_search_1");
	var object_link = document.getElementById("elama_js_search_1_link");
	var object_icon = document.getElementById("elama_js_search_1_icon");
	var windowSize = jsUtils.GetWindowSize();
	var x = e.clientX + windowSize.scrollLeft;
	var y = e.clientY + windowSize.scrollTop;
	var pos = jsUtils.GetRealPos(object);
	var posLeft = parseInt(pos["left"]);
	var posTop = parseInt(pos["top"])
	var posRight = posLeft + object.offsetWidth;
	var posBottom = posTop + object.offsetHeight;
	if (x >= posLeft && x <= posRight && y >= posTop && y <= posBottom) return;
	var pos_link = jsUtils.GetRealPos(object_link);
	if (x >= pos_link['left'] && x <= pos_link['right'] && y >= pos_link['top'] && y <= pos_link['bottom']) return;
	var pos_icon = jsUtils.GetRealPos(object_icon);
	if (x >= pos_icon['left'] && x <= pos_icon['right'] && y >= pos_icon['top'] && y <= pos_icon['bottom']) return;
	elama_js_search_1_off();
}
elama_js_search_1_on_key_press_f = function elama_js_search_1_on_key_press(e) {
	if (!e) e = window.event
	if (!e) return;
	if (e.keyCode == 27) elama_js_search_1_off();
}

function elama_js_search_2_on(menu_position) {
	var object = document.getElementById("elama_js_search_2");
	object.style.display = "block";
	object.style.top = menu_position["bottom"];
	object.style.left = menu_position["left"];
	jsUtils.addEvent(document, "click", elama_js_search_2_check_click_f);
	jsUtils.addEvent(document, "keypress", elama_js_search_2_on_key_press_f);
}

function elama_js_search_2_off() {
	var object = document.getElementById("elama_js_search_2");
	object.style.display = "none";
	jsUtils.removeEvent(document, "click", elama_js_search_2_check_click_f);
	jsUtils.removeEvent(document, "keypress", elama_js_search_2_on_key_press_f);
}
elama_js_search_2_check_click_f = function elama_js_search_2_check_click(e) {
	if (!e) e = window.event
	if (!e) return;
	var object = document.getElementById("elama_js_search_2");
	var object_link = document.getElementById("elama_js_search_2_link");
	var object_icon = document.getElementById("elama_js_search_2_icon");
	var object_calendar = document.getElementById("calendar_float_div");
	var windowSize = jsUtils.GetWindowSize();
	var x = e.clientX + windowSize.scrollLeft;
	var y = e.clientY + windowSize.scrollTop;
	var pos = jsUtils.GetRealPos(object);
	var posLeft = parseInt(pos["left"]);
	var posTop = parseInt(pos["top"])
	var posRight = posLeft + object.offsetWidth;
	var posBottom = posTop + object.offsetHeight;
	if (x >= posLeft && x <= posRight && y >= posTop && y <= posBottom) return;
	var pos_link = jsUtils.GetRealPos(object_link);
	if (x >= pos_link['left'] && x <= pos_link['right'] && y >= pos_link['top'] && y <= pos_link['bottom']) return;
	var pos_icon = jsUtils.GetRealPos(object_icon);
	if (x >= pos_icon['left'] && x <= pos_icon['right'] && y >= pos_icon['top'] && y <= pos_icon['bottom']) return;
	var pos_calendar = jsUtils.GetRealPos(object_calendar);
	if (x >= pos_calendar['left'] && x <= pos_calendar['right'] && y >= pos_calendar['top'] && y <= pos_calendar['bottom']) return;
	elama_js_search_2_off();
}
elama_js_search_2_on_key_press_f = function elama_js_search_2_on_key_press(e) {
	if (!e) e = window.event
	if (!e) return;
	if (e.keyCode == 27) elama_js_search_2_off();
}
/**
 * /Р’Р°РґРёРј
 */

/**
 * @author sergeyk
 */
jQuery(document).ready(function () {
	initialization();
})

function initialization() {
	zebra();
	jQuery('#word-choice').attr('target', '_blank');
	jQuery('#word-choice').attr('title', 'Открыть в новом окне');
	jQuery('#word-choice').mousedown(function (event) {
		event.preventDefault();
	})
	// загружаем картинки для select с выбором типа удержания
	var jqImgTop_1 = $('<img id="ImgTop_1" class="keep_slider_option" src="'+W_IMAGES+'top_1.png" style="z-index:1000" />');
	var jqImgTop_3 = $('<img id="ImgTop_3" class="keep_slider_option" src="'+W_IMAGES+'top_3.png" style="z-index:1000" />');
	var jqImgRight_1 = $('<img id="ImgRight_1" class="keep_slider_option" src="'+W_IMAGES+'right_1.png" style="z-index:1000" />');
	var jqImgRight_2345 = $('<img id="ImgRight_2345" class="keep_slider_option" src="'+W_IMAGES+'right_2_3_4_5.png" style="z-index:1000" />');
/*jQuery('.ad-campaign').each(function(){
        jQuery('.expander',jQuery(this)).toggle(function(){
            jQuery('.slider',jQuery(this).parents('.ad-campaign')).slideDown(400);
            jQuery(this).addClass('expanded').removeClass('collapsed');
        },function(){
            jQuery('.slider',jQuery(this).parents('.ad-campaign')).slideUp(400);
            jQuery(this).addClass('collapsed').removeClass('expanded');
        })
    })*/
	jQuery('.menu-l .expander, .filter .expander').each(function () {
		loadCollapse(jQuery(this));
		jQuery(this).toggle(function () {
			expand(jQuery(this));
		}, function () {
			collapse(jQuery(this));
		})
	});
	jQuery('.expander', '.ad-campaign').each(function () {
		jQuery(this).toggle(function () {
			collapse(jQuery(this));
		}, function () {
			expand(jQuery(this));
		})
	})
	// для +/-	от удержание позиций
	jQuery('.keep_expander', '.keep_pos .keep_expander_container').each(function () {
		$(this).bind('click', keep_toggle)
	})	
	// для заголовка
	jQuery('.keep_title', '.keep_pos .keep_expander_container').each(function () {
		$(this).bind('click', keep_toggle)
	})

	function keep_toggle() {
		if ($('.keep_slider', $(this).parents('.keep_pos')).is(':hidden')){
			keep_expand($(this));
		} else {
			keep_collapse($(this));
		}
	}

/*	jQuery('.keep_expander', '.keep_pos').each(function () {
		if (jQuery('.keep_slider', jQuery(this).parents('.keep_pos')).is(':hidden')) {	
			jQuery(this).parent().toggle(function () {
				keep_expand(jQuery(this));
			}, function () {
				keep_collapse(jQuery(this));
			})
		} else {
			jQuery(this).parent().toggle(function () {
				keep_collapse(jQuery(this));
			}, function () {
				keep_expand(jQuery(this));
			})
		}
	})*/

	function expand(id) {
		jQuery('.slider', jQuery(id).parents('.slide')).slideDown(400);
		jQuery(id).addClass('expanded').removeClass('collapsed');
	}

	function collapse(id) {
		jQuery('.slider', jQuery(id).parents('.slide')).slideUp(400);
		jQuery(id).addClass('collapsed').removeClass('expanded');
	}

	function keep_expand(id) {
		jQuery('.keep_slider', jQuery(id).parents('.keep_pos')).slideDown(400);
		jQuery(".ico", jQuery(id).parent()).addClass('expanded').removeClass('collapsed');
		// для cusel
		// пока там всего два дива, но все может измениться //// потом переделать
		idKeepSimple = jQuery('.keep_slider', jQuery(id).parents('.keep_pos')).find('div:first').attr('id');
		idKeepExtended = jQuery('.keep_slider', jQuery(id).parents('.keep_pos')).find('div:last').attr('id');
		// вызывать, если показывается скрытый select
		initCusel(idKeepSimple); // init or reinit select for simple keeps
	}

	function keep_collapse(id) {
		jQuery('.keep_slider', jQuery(id).parents('.keep_pos')).slideUp(400);
		jQuery(".ico", jQuery(id).parent()).addClass('collapsed').removeClass('expanded');
	}

	function loadCollapse(id) {
		if (!jQuery('.slider', jQuery(id).parents('.slide')).hasClass('filter_on')) {
			jQuery('.slider', jQuery(id).parents('.slide')).hide();
			jQuery(id).addClass('collapsed').removeClass('expanded');
		}
	}
	
	//var maxLimit = jQuery('#maxLimit');
	jQuery(':text.maxx', '.ad-campaign').each(function () {
		//var coords = jQuery(this).offset();
		jQuery(this).focus(function () {
			jQuery('.max-transfer', jQuery(this).parent()).css('display', 'block');
		})
		jQuery(this).blur(function () {
			jQuery('.max-transfer', jQuery(this).parent()).css('display', 'none');
		})
	})
	
	//	init_selects ( cusel )
	// находим все не скрытые блоки с расширенным или обычны удержанием и активируем cusel
	$(".keep_slider div").each(function(i){
		matches = $(this).attr("id").match(/(^keep_simple_|^keep_extended_)(\d*)/i);
		if (matches) {
//			console.log("cusel_" + (i+1))
			// в matches[0] - keep_price_max_8449707
			// в matches[1] - keep_simple_ или keep_extended_
			// в matches[2] - 8449707 ( id кампании )
			simple = false;
			extended = false;
			if (matches[1] == "keep_simple_") simple = true;
			else if (matches[1] == "keep_extended_") extended = true;
			idCampaign = parseInt(matches[2]);
			// если не скрыт сам элемент или его родитель, то инициализируем
			if (!$(this).is(":hidden"))
				if (!$(this).parent().is(":hidden"))
					initCusel(matches[0])
			if (simple){
				// заодно инициализируем перевод значения ставки в простом удержании из у.е. в рубли
				// так он срабатывает только на onfocus и onkeyup keep_price_max_8449707			
				// находим input max_price
				convertue($("#keep_price_max_"+idCampaign, this), CCurrency);
			}	
		}
	});
}

// инициализируем замененные cusel`ем селекты
function initCusel(id_keep) {
	if(window.disableCuSel != undefined && disableCuSel) return;
//	console.log("in cusel_=" +id_keep)
	if ($(".keep_slider select").size() > 0){
		$("#"+id_keep + " select").each(function(i){
			id = getUniqueId(id_keep, i);
			$(this).attr("id", id);
//			console.log(id)
			var params = {
				changedEl: "#"+id+"",
				visRows: 5,
				scrollArrows: true
			}
			cuSel(params);	
		if ($.browser.msie)
			$("#cuselFrame-"+id).css("display", "inline");					
		});
		// обработка для картинок с яндекса
		init_tips($("#"+id_keep));
	}		
}

// присвоение уникального id для select
function getUniqueId(id_keep, i) {
	id = $("#"+id_keep+" select").attr("id");
	if (!id) {
		// будет уникальным в пределах id_keep
		id = "keep_position_extend_" + id_keep + "_" + i;
		while ($("#"+id).size()){
//			console.log(i)
			i++;
			id = "keep_position_extend_" + id_keep + "_" + i;
		}
	}
	return id;	
}

// обработка для картинок с яндекса
// подходит для simple, для extended добавить соответсвенно свои case
// parent_node для simple и extend разные
function init_tips(parent_node){
	// загружаем картинки для select с выбором типа удержания
	var jqImgTop_1 = $('<img id="ImgTop_1" class="keep_slider_option" src="'+W_IMAGES+'top_1.png" style="z-index:1000" />');
	var jqImgTop_3 = $('<img id="ImgTop_3" class="keep_slider_option" src="'+W_IMAGES+'top_3.png" style="z-index:1000" />');
	var jqImgRight_1 = $('<img id="ImgRight_1" class="keep_slider_option" src="'+W_IMAGES+'right_1.png" style="z-index:1000" />');
	var jqImgRight_2345 = $('<img id="ImgRight_2345" class="keep_slider_option" src="'+W_IMAGES+'right_2_3_4_5.png" style="z-index:1000" />');	
	
	$('.cusel span', parent_node).each(function(){
//			$(this).click(function(){alert(2)})
		$(this).bind('mouseover', function(){
//				console.log(this);
			// выбор картинки для show
			coords = new Array();
			coords.left = getPosX(this);
			coords.top = getPosY(this);
			coords.left += this.offsetWidth;
			coords.left += 2; // не учлись margin-left right по 1px 
			// модернизировать, чтобы учитывалось все автоматом - есть в jquery
			switch ($(this).attr('value')){
				case '29':
					// было с простым селектом :insertAfter $(this).parent()
//						console.log($(parent_node).attr('id'));
//						console.log(jqImgTop_1);
					jqImgTop_1.appendTo(parent_node);
					jqImgTop_1.css({position: "absolute", top: coords.top, left: coords.left})
					break;
				case '30':
					jqImgTop_3.appendTo(parent_node);
					jqImgTop_3.css({position: "absolute", top: coords.top, left: coords.left})
					break;
				case '31':
					jqImgRight_1.appendTo(parent_node);
					jqImgRight_1.css({position: "absolute", top: coords.top, left: coords.left})
					break;
				case '32':
					jqImgRight_2345.appendTo(parent_node);
					jqImgRight_2345.css({position: "absolute", top: coords.top, left: coords.left})
					break;													
				default:
//					console.log('def');
					$('.keep_slider_option', $('.keep_slider')).remove();
					break;
			}
		})
		$(this).mouseout(function(){
			// общая функция hide картинки
//			console.log('EXIT');
			$('.keep_slider_option', parent_node).remove();
		})
	})		
}

// функция получает информацию о свойствах объекта
function fnShowProps(obj, objName) {
	var result = "The properties for the " + objName + " object:" + "\n";
	for (var i in obj) {
		result += i + " = " + obj[i] + "\n";
	}
	console.log(result);
}

/**
 * get object X coord
 */
function getPosX(obj) {
	var curleft = 0;
	if (obj.offsetParent) {
		if ($.browser.msie) {
			while (obj.offsetParent && obj.offsetParent.tagName.toLowerCase() != "html") {
				curleft += obj.offsetLeft;
				obj = obj.offsetParent;
			}
		} else {
			while (obj.offsetParent.tagName.toLowerCase() != "body") {
				curleft += obj.offsetLeft;
				obj = obj.offsetParent;
			}
		}

	} else if (obj.x) {
		curleft += obj.x;
	}
	return curleft;
}
/**
 * get object Y coord
 */
function getPosY(obj) {
	var curtop = 0;
	if (obj.offsetParent) {
		if ($.browser.msie) {
			while (obj.offsetParent && obj.offsetParent.tagName.toLowerCase() != "html") {
				curtop += obj.offsetTop;
				obj = obj.offsetParent;
			}
		} else {
			while (obj.offsetParent.tagName.toLowerCase() != "body") {
				curtop += obj.offsetTop;
				obj = obj.offsetParent;
			}
		}
	} else if (obj.y) {
		curtop += obj.y;
	}
	return curtop;
}
/**
 * Фокус в текстареа
 */

function ticketFocus(oText) {
	if (oText && oText.value == oText.defaultValue) {
		oText.value = '';
	}
}
/**
 * Потеря фокуса в текстареа
 */

function ticketBlur(oText) {
	if (oText && oText.value == '') {
		oText.value = oText.defaultValue;
	}
}
/**
 * Фокус в инпут
 */

function ticketEmailFocus(oInput) {
	if (oInput && oInput.value == oInput.defaultValue) {
		oInput.value = '';
	}
}
/**
 * Потеря фокуса в инпуте
 */

function ticketEmailBlur(oInput) {
	if (oInput && oInput.value == '') {
		oInput.value = oInput.defaultValue;
	}
}
/**
 * Проверка и отправка сообщения
 */

function ticketSubmit(oForm) {
	if (oForm) {
		var oText = oForm.elements['ticket_text'];
		//var oText = oForm.elements[0];
		if (oText && oText.type == 'textarea' && oText.value != '' && oText.value != oText.defaultValue) {
			oForm.submit();
		} else {
			alert('Напишите сообщение');
			return false;
		}
	}
	return false;
}

var gMinBit = 0;
var gBudget = 0;
/**
 * Валидируем все и всех!
 * Форма с классом "dog-yur-face"
 */
jQuery(document).ready(function () {
	var requiredMsg = 'Это обязательное поле';
	var inCorrectMsg = jQuery.format("Необходимо ввести {0} символов"); //'Поле заполнено неверно';
	var digitsMsg = 'Можно вводить только цифры';
	jQuery('#dog-yur-face').validate({
		rules: {
			name: 'required',
			email: {
				required: true,
				email: true
			},
			contact: 'required',
			contact_name: 'required',
			contact_mname: 'required',
			contact_fname: 'required',
			contact_phone: 'required',
			company: 'required',
			ur_address: 'required',
			fiz_address: 'required',
			inn: {
				required: true,
				digits: true //,
				//rangelength: [10,10]
			},
/*kpp:
            {
                required: true,
                digits: true,
                rangelength: [9,9]
            },*/
			rs: {
				required: true,
				digits: true,
				rangelength: [20, 20]
			},
			ks: {
				required: true,
				digits: true,
				rangelength: [20, 20]
			},
			bik: {
				required: true,
				digits: true,
				rangelength: [9, 9]
			},
			okpo: {
				required: true,
				digits: true,
				rangelength: [8, 8]
			},
			okonh: {
				required: true,
				digits: true
			},
			money: {
				required: true,
				digits: true,
				min: 6
			},
			contract_id: 'required'
		},
		messages: {
			inn: {
				rangelength: inCorrectMsg,
				digits: digitsMsg
			},
			kpp: {
				rangelength: inCorrectMsg,
				digits: digitsMsg
			},
			rs: {
				rangelength: inCorrectMsg,
				digits: digitsMsg
			},
			ks: {
				rangelength: inCorrectMsg,
				digits: digitsMsg
			},
			bik: {
				rangelength: inCorrectMsg,
				digits: digitsMsg
			},
			okpo: {
				rangelength: inCorrectMsg,
				digits: digitsMsg
			},
			money: {
				min: 'Необходимо добавить не менее 600 рублей'
			}
		}
	});
	jQuery('#for-account-config-validator').validate({
		rules: {
			min_bit: {
				required: true,
				number: true,
				min: gMinBit
			},
			budget: {
				required: true,
				number: true,
				min: gBudget
			},
			name: {
				required: {
					/**
					 * Зависимость!
					 * Проверяет, чтобы пользователь ввел Имя новой кампании или выбрал Существующую.
					 */
					depends: function (element) {
						return $('#old_campaign_id').val() > 0 ? false : true;
					}
				}
			}
		},
		messages: {
			min_bit: {
				number: digitsMsg,
				min: jQuery.format("Минимальная ставка должна быть не менее {0}")
			},
			budget: {
				number: digitsMsg,
				min: jQuery.format("Бюджет должен быть не менее {0}")
			},
			name: {
				required: 'Необходимо заполнить данное поле или выбрать существующую кампанию ниже'
			}
		}
	});
})



function isDisabled(btnSelector) {
	return $(btnSelector).hasClass('disable');
}

function disableButton(btnSelector) {
	$(btnSelector).addClass('disable');
}

function unDisableButton(btnSelector) {
	$(btnSelector).removeClass('disable');
}

//Это из wordstat.js
var Objects = new Array();
