﻿/* AJAX helper utilities */

//	jQuery AJAX error handler
function onAjaxError(XMLHttpRequest, textStatus, errorThrown) {
	if (XMLHttpRequest != undefined) {
		var errorMessage;
		if (XMLHttpRequest.responseText.indexOf("<html>") != -1) {
			//	responseText is html
			var posStart = XMLHttpRequest.responseText.indexOf("<title>");
			var posEnd = XMLHttpRequest.responseText.indexOf("</title>");
			if (posStart != -1 && posEnd != -1)
				errorMessage = XMLHttpRequest.responseText.slice(posStart + 7, posEnd - 1);
			else
				errorMessage = "Unknown AJAX error";
		}
		else {
			//	responseText is JSON object
			var error = eval("(" + XMLHttpRequest.responseText + ")");
			errorMessage = error.Message;
		}
		alert(errorMessage);
	}
}

//	Sync call web service with jQuery library
function CallWebService(serviceUrl, serviceData, successMethod, isAsync, completeMethod) {
	$.ajax({
		type: "POST",
		url: serviceUrl,
		contentType: "application/json; charset=utf-8",
		data: (serviceData),
		dataType: "json",
		success: successMethod,
		error: onAjaxError,
		async: isAsync,
		complete: completeMethod
	});
}

function insertSource(urlForHtml, insertHolderTagId) {
	$.ajax({
		type: 'GET',
		url: urlForHtml,
		//data: { 'listingId': listingId },
		dataType: 'html',
		success: function(data, textStatus) {
			$('#' + insertHolderTagId).html(data);
		}
	});
}

if(jQuery.validator){
    jQuery.validator.addMethod("notequaltoproperty", function(value, element, params) {
	    if (this.optional(element)) {
		    return true;
	    }

	    var otherPropertyControl = $("#" + params.otherProperty);
	    if (otherPropertyControl == null) {
		    return false;
	    }

	    var otherPropertyValue = otherPropertyControl[0].value;
	    return otherPropertyValue != value;
    });
}


function SetFilterType(hiddenId, value, isExtender) {

	$.cookie(value, isExtender, { expires: 365 });
	DefineCookie();
	SubmitForm(document.getElementById(hiddenId).form);
}

function DefineCookie() {
	$.cookie("defcook", 1);
	if ($.cookie("defcook") == null) {
		alert("Для корректной работы расширенного поиска, включите, пожалуйста, поддержку cookies в браузере");
		return false;
	}
	$.cookie("defcook",null );
	return true;
		
}
function SubmitForm(form) {
	form.submit();
}

function GetQueryParam(key, url) 
{
	if (!url)
		url = window.location.search;
	var re = new RegExp("[?|&]" + key + "=(.*?)&");
	var matches = re.exec(url + "&");
	if (!matches || matches.length < 2)
		return "";
	return decodeURIComponent(matches[1].replace("+", " "));
}

function SetQueryParam(key, value, url) 
{
	url = url == null ?  window.location.search : url;
	var q = url + "&";
	var re = new RegExp("[?|&]" + key + "=.*?&");
	if (!re.test(q))
		q += key + "=" + encodeURI(value);
	else
		q = q.replace(re, "&" + key + "=" + encodeURIComponent(value) + "&");
	q = q.trimStart("&").trimEnd("&");
	if (q.startsWith("http://"))
		return q;
	return q.indexOf('?') == 0 ? q : q = "?" + q;
}

String.prototype.trimEnd = function(c) {
	if (c)
		return this.replace(new RegExp(c.escapeRegExp() + "*$"), '');
	return this.replace(/\s+$/, '');
}
String.prototype.trimStart = function(c) {
	if (c)
		return this.replace(new RegExp("^" + c.escapeRegExp() + "*"), '');
	return this.replace(/^\s+/, '');
}
String.prototype.escapeRegExp = function() {
	return this.replace(/[.*+?^${}()|[\]\/\\]/g, "\\$0");
};

String.prototype.startsWith = function(str) {
	if (str == '+')
		return false;
	return (this.match("^" + str) == str)
};

function ShowToolTipForImage(control, image, text) {
	var obj = "<img src='"+ image + "' />" + text;
	ShowToolTip(control, obj, 'tooltip');
}

function ShowToolTipForList(control, text) 
{
	$(control).simpletip({
		content: text,
		baseClass: 'addressTooltipForList'
	}).show();
}

function ShowToolTip(control, text, cssName) {
	ShowToolTip(control, text, cssName, 'right');
}

function ShowToolTip(control, text, cssName, positionVal) {
	$(control).simpletip({
		position: positionVal,
		content: text,
		baseClass: cssName
	}).show();
}



function PreloadImage(control,id, url) {
	var i = new Image();
	i.src = url;
	i.id = id;
	i.style.display = "none";
	control.appendChild(i);
}
function Redirect(url) {
	window.location.href = url;
}

function RedirectGeki(url, control) {
	if (control.value != "")
		url = url + "/" + control.value;
	window.location.href = url;
}

//(следущая функция не работает без query-параметра Id в url)
function RedirectWithParamReplacement(old, val) {
	var url = window.location.href; //копирует ли содержимое - или тупо берет ссылку?
	if (url.indexOf('#') > -1)	//чистим якоря
		url = url.substring(0, url.indexOf('#'));
	if (url.indexOf(old) > -1)
		window.location.href = url.replace(old, val)
	else
		window.location.href = url + (window.location.href.search(/\/$/) > -1 ? '' : '/') + val;
}


/*FROM ADDRES.COM.UA*/
function setNotPressedSrc(img) {
	img.src = img.src.replace("Pressed.gif", ".gif").replace("Pressed.png", ".png");
	if (img.oSrc) {
		img.oSrc.src = img.oSrc.replace("Over.gif", "Pressed.gif").replace("Over.png", "Pressed.png");
	}
}
function setPressedSrc(img) {
	img.src = img.src.replace(".gif", "Pressed.gif").replace(".png", "Pressed.png");
	if (img.oSrc) {
		img.oSrc = img.oSrc.replace(".gif", "Pressed.gif").replace(".png", "Pressed.png");
	}
}

/* Realty filter */
function getFilterPriceHint(realtyType, transaction) {
	result = "Цена за месяц";
	if (transaction == "prodajut" || transaction == "pokupajut") {
		if (realtyType == "zemla")
			result = "Цена за сотку";
		else if (realtyType == "ofis")
			result = "Цена за м<sup>2</sup>";
		else
			result = "&nbsp;";
	}
	return result;
}

//_______________________________________[Hide on DDL changed]________________________________________

//Функции для прятанья элементов в зависимости от значений
//tooggles - элементы скрываются для указанных значений (и наоборот отображаются, если visible=true), А для других значений - скрываются (и наоборот отображаются, если установлено visible=true)
function HandleDdlSelIndxChanged(ddl, toggles,callback,callback_args) {
	Hide(ddl.val(), toggles);  //first time to check (maby QeruyParams have LocationTypeId parameter)
	if (typeof(callback)!="undefined")
		callback(callback_args);
	ddl.bind('change', { tags: toggles, object: ddl }, function(e) {
		Hide(e.data.object.val(), e.data.tags);
		if (typeof (callback)!="undefined")
			callback(callback_args);
	});
}
function Hide(currVal, toggles) {
	var i = 0;
	//попрячем все, что не должно высовываться
	for (; i < toggles.length; i++) {
		if (currVal != toggles[i].val) {
			if (toggles[i].visible == true)
				$('#' + toggles[i].tagId).hide();
			else $('#' + toggles[i].tagId).show();
		}
	}

	//последнее следнее слово за совпавшими
	for (i = 0; i < toggles.length; i++) {
		if (currVal == toggles[i].val) {
			if (toggles[i].visible == true)
				$('#' + toggles[i].tagId).show();
			else $('#' + toggles[i].tagId).hide();
		}
	}
}

/*  Hidding element on select index chenged for DropDownList   */
function Toggle(val, tagId, visible) {
	this.val = val;
	this.tagId = tagId;
	this.visible = visible;
}
//_______________________________________[Hide on DDL changed](END)________________________________________

function fancybox(galleryAnchorsSelector) {
	$(galleryAnchorsSelector).fancybox({
		'callbackOnStart': function() {
			//корректируем перекрытия z-index
		var startZIndex = 6010; //привышает наибольший z-index на сайте
			//DIV#fancy_overlay содержит z-index=5000
			var fancyElementsToModify = [
					'div#fancy_content',
					'div#fancy_loading_overlay', 'div#fancy_loading_icon',
					'div#fancy_bg', 'div.fancy_bg',
					'div#fancy_outer',
					'div#fancy_loadingdiv#fancy_div',
					'img#fancy_img', 'div#fancy_title',
					'a#fancy_left', 'a#fancy_right',
					'span.fancy_ico', 'div#fancy_close'
				];
			var i;
			for (i = 0; i < fancyElementsToModify.length; i++)
				$(fancyElementsToModify[i]).css('z-index', startZIndex++);
		}
	});
}
// ===================================================[ Listing Common ]===================================================

function SubmitForm()
{
    $("input[type='submit']").click();
}

function SetRStateAndSubmit(state)
{
    $("#PublicateState").val(state);
    SubmitForm();
}

function ChangeHomeInputType(spnListId, spnFieldId, IsHomeNum, hiddenId) {

	// true -- показать список
	if (!IsHomeNum) {
		$("#" + spnListId).show();
		$("#" + spnFieldId).hide();
		var input = $("#" + spnFieldId + "> input");
		input[0].value = "";
		
	}
	else {
		$("#" + spnListId).hide();
		$("#" + spnFieldId).show();
		var list = $("#" + spnListId + "> select");
		list[0].selectedIndex = 0;
	}
	$("#" + hiddenId).attr("value", IsHomeNum);
}

function chk_u_bkl(requestUrl, state)
{
    var requestStr = requestUrl + '?email=' + $("#Listing_Email").val() + '&phone=' + $("#Listing_Phone").val();

    $.getJSON(requestStr,
                                    function(result)
                                    {
                                        if (result.IsInBlackList)
                                        {
                                            $('#error_messages').html('<h3>За нарушение условий пользования сайтом ваши данные были помещены в черный список. Для выяснения обстоятельств, свяжитесь с администрацией сайта.</h3>')
                                        }
                                        else
                                        {
                                            SetRStateAndSubmit(state);
                                        }
                                    }
                                )

}

function setSrc(img,imgSource) {
	$(img).attr('src', imgSource);
}

// ===================================================[ Listing Common ](END)===================================================

//=========================тест ввода=========================
protCheckKeys = function(Enter) {
    this.isShift = false;
    this.isNumeric = function(e, myfield, isDecimal, maxsize, nextfield, dec) {
        var key;
        var keychar;
        var ret = false;
        if (window.event)
            key = window.event.keyCode;
        else if (e)
            key = e.which;

        if (key) {
            keychar = String.fromCharCode(key);
            // control keys
            if ((key == null) || (key == 0) || (key == 8) || (key == 9) || (key == 13) || (key == 27)) {
                if ((key == 13) && nextfield && maxsize && myfield.value.length == maxsize)
                    myfield.form.elements[nextfield].focus();
                else
                    ret = true;
            }
            // numbers
            else if ((("0123456789").indexOf(keychar) > -1)) {
                if (nextfield && maxsize && myfield.value.length == maxsize)
                    myfield.form.elements[nextfield].focus();
                else
                    ret = !maxsize || myfield.value.length < maxsize;
            }
            // decimal point / jump
            else if (keychar == ".")
                if (dec)
                    myfield.form.elements[dec].focus();
                else
                    ret = isDecimal && myfield.value.indexOf(keychar) < 0;
        }
        else
            ret = true;

        if (window.event)
            window.event.returnValue = ret;
        return ret;
    };
    this.isAlpha = function(e) {
        var key;
        var ret = false;
        if (window.event)
            key = window.event.keyCode;
        else if (e)
            key = e.which;

        ret = key && ((key >= 35 && key <= 46) || ((key >= 65 && key <= 90) || key == 8 || key == 9));

        if (window.event)
            window.event.returnValue = ret;
        return ret;
    };
    this.isAlphaNumeric = function(e) {
        var key;
        var ret = false;
        if (window.event)
            key = window.event.keyCode;
        else if (e)
            key = e.which;

        ret = key && ((key >= 35 && key <= 46) || (((key >= 48 && key <= 57) && isShift == false) ||
               (key >= 65 && key <= 90) || key == 8 || key == 9 ||
               (key >= 96 && key <= 105)))
        if (window.event)
            window.event.returnValue = ret;
        return ret;
    };
    this.keyUP = function(e) {
        if (window.event)
            key = window.event.keyCode;
        else if (e)
            key = e.which;
        if (key && key == 16)
            isShift = false;
    };
    this.onEnterClickElm = function(e, elm) {
        if (window.event)
            key = window.event.keyCode;
        else if (e)
            key = e.which;
        if (key && key == 13)
            $(elm).click();
    };
    this.onEnterFn = function(e, fn,elm) {
        if (window.event)
            key = window.event.keyCode;
        else if (e)
            key = e.which;
        if (key && key == 13)
            fn(elm);
    };
    this.keyDOWN = function(e) {
        if (window.event)
            key = window.event.keyCode;
        else if (e)
            key = e.which;
        if (key && key == 16)
            isShift = true;
    };
    this.IsNumericT = function(sText) {
        var ValidChars = "0123456789.";
        var IsNumber = true;
        var Char;
        for (i = 0; i < sText.length && IsNumber == true; i++) {
            Char = sText.charAt(i);
            if (ValidChars.indexOf(Char) == -1) {
                IsNumber = false;
                break;
            }
        }
        return IsNumber;
    }
    this.IsIntT = function(sText) {
        var ValidChars = "0123456789";
        var IsNumber = true;
        var Char;
        for (i = 0; i < sText.length && IsNumber == true; i++) {
            Char = sText.charAt(i);
            if (ValidChars.indexOf(Char) == -1) {
                IsNumber = false;
                break;
            }
        }
        return IsNumber;
    }
}
var keyCheck = new protCheckKeys(); 
//=========================End тест ввода=========================

//=========================Begin validator текста=========================
var validationRules = new (function() {
    var strRegMail = "^([\\w-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([\\w-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$"/*'<%= Address.Common.RegExps.Mail.Replace("\\","\\\\")%>'*/;
    var Err = false;
    var IsGroup = false;
    this.beginErrGroup = function() { IsGroup = true; Err = false; };
    this.endErrGroup = function() { IsGroup = false; return Err; };
    this.OnChangeNotEmpty = function() {
        if (IsGroup && Err)
            return false;
        else
            Err = false;
        var o = $(this);
        fieldname = o.attr("fieldname");
        var v = o.val();
        if (!(v && v > '')) {
            alert("Поле " + (fieldname ? fieldname : "") + " не должно быть пустым!");
            if (this.old) this.value = this.old;
            setTimeout(function() { o.focus(); }, 1);
            Err = true;
        }
        return !Err;
    };

    this.OnChangeExpr = function() {
        if (IsGroup && Err)
            return false;
        else
            Err = false;
        var o = $(this);
        fieldname = o.attr("fieldname");
        var v = o.val();
        var reg = new RegExp(o.attr("expr"), "ig");
        if (v.search(reg) == -1) {
            alert("Некорректно введено значение поля " + (fieldname ? fieldname : "") + " !");
            if (this.last || this.old)
                this.value = this.last ? this.last : this.old;
            setTimeout(function() { o.focus(); }, 1);
            Err = true;
        } else this.last = this.value;
        return !Err;
    };

    this.OnChangeEmail = function() {
        if (IsGroup && Err)
            return false;
        else
            Err = false;
        var o = $(this);
        fieldname = o.attr("fieldname");
        var v = o.val();
        var reg = new RegExp(strRegMail, "ig");
        if (v.search(reg) == -1) {
            alert("Некорректно введено значение поля " + (fieldname ? fieldname : "") + " !");
            if (this.last || this.old)
                this.value = this.last ? this.last : this.old;
            setTimeout(function() { o.focus(); }, 1);
            Err = true;
        } else this.last = this.value;
        return !Err;
    };

    $(document).ready(function() {
        $("[validation=regexp]").bind("change", validationRules.OnChangeExpr);
        $("[validation=email]").bind("change", validationRules.OnChangeEmail);
        $("[validation=notempty]").bind("change", validationRules.OnChangeNotEmpty);
    })
})
//=========================End validator текста=========================

//=========================наследование=========================
function extend(Child, Parent) {
    var F = function() { }
    F.prototype = Parent.prototype
    Child.prototype = new F()
    Child.prototype.constructor = Child
    Child.superclass = Parent.prototype
}
//=========================End наследования=========================

/*function SetParentHeightAfterLoad(elem2FixSelector) {
	$(elem2FixSelector).ready(function() {
		var elem2Fix = $(elem2FixSelector);
		var parent = elem2Fix.parent();
		$(parent).ready(function() {
			elem2Fix.css("height", $(parent).css("height"));
		});
	});
}*/

/*
	добавляет в урл параметр
*/
function doPost(pressedElem, getExtened, isExtParamName) {
	//do submit with parameter
	var theForm = $(pressedElem).closest('form');
	var url = $(theForm).attr('action');
	url += SetQueryParam(isExtParamName, getExtened.toString(), null);
	$(theForm).attr('action', url);
	theForm.submit();
}

/* удаляет все "IsEclusive=true" в url-ах, checkbox как параметр ~ onclick = "removeExclusive(this);" */
function removeExclusive(o) {
    if (!o.checked) {
        $("a[href$='?IsExclusive=true']").each(
            function(i, e) {
                e.href = e.href.replace('?IsExclusive=true', '');
            })
        $("a[href*='IsExclusive=true']").each(
            function(i, e) {
                e.href = e.href.replace('&IsExclusive=true', '').replace('IsExclusive=true', '');
            })
        }
       }

 /*открывает новое окно, помещает его посредине экрана, делает его активным
	width и height задано в пикселях (типа int)*/
  function openModalWindow(url, windowId, width, height) {
 	var windowFeatures = "location=0,toolbar=0,scrollbars=0,status=0,resizable=0";
	//габариты и позиция
	windowFeatures+=",width="+width+",height=" + height;
	var left = (screen.width - width) / 2;
	var top = (screen.height - height) / 2;
	windowFeatures += ', top=' + top + ', left=' + left;

	window.open(url, windowId, windowFeatures).focus();
}


function PremiumPopupOver(control) {
	/*$(control).removeAttr("style");
	$(control).addClass("premiumPopup");
	control.style.overflow = "visible";
	control.style.heigth = "300";*/
}

function PremiumPopupOut(control) {
	/*//$(control).removeAttr("style");
	//$(control).removeClass("premiumPopup");
	//control.style.overflow = control.style.position = "";*/
	 
}

function AddMapiaCount(mapiaCountUrl) {
    $.ajax({
        type: "post",
        url: mapiaCountUrl,
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    })
}

function clearValues(Ids){
	for(var i=0;i<Ids.length;i++)
		$('#'+Ids[i]).val('');
}