﻿


var Mian = {}
Mian.Lib = {}
//Dictionary Class
//=========================================================================
Mian.Lib.Dictionary = function(){ this.InnerArray = new Array();}
Mian.Lib.Dictionary.COLUMN_KEY = 0;
Mian.Lib.Dictionary.COLUMN_VALUE = 1;
Mian.Lib.Dictionary.prototype.Length = function(){ return this.InnerArray.length; }
Mian.Lib.Dictionary.prototype.Add = function(key, value) {
    this.InnerArray.push([key, value]); 
}
Mian.Lib.Dictionary.prototype.Clear = function(){ this.InnerArray.splice(0, this.InnerArray.length); }
Mian.Lib.Dictionary.prototype.GetKeyByIndex = function(index){ return this.InnerArray[index][Mian.Lib.Dictionary.COLUMN_KEY]; }
Mian.Lib.Dictionary.prototype.GetValueByIndex = function(index){ return this.InnerArray[index][Mian.Lib.Dictionary.COLUMN_VALUE]; }
Mian.Lib.Dictionary.prototype.SetValueByIndex = function(index,value){ this.InnerArray[index][Mian.Lib.Dictionary.COLUMN_VALUE] = value; }
Mian.Lib.Dictionary.prototype.GetValueByKey = function(key){
    var index = this.GetIndexByKey(key);
    if(index != -1) return this.GetValueByIndex(index);
    return null;
}
Mian.Lib.Dictionary.prototype.SetValueByKey = function(key){
    var index = this.GetIndexByKey(key);
    if(index != -1) return this.GetValueByIndex(index);
    return null;
}
Mian.Lib.Dictionary.prototype.DeleteByKey = function(key){
    var index = this.GetIndexByKey(key);
    if(index != -1) return this.InnerArray.splice(index,1);
    return null;
}

Mian.Lib.Dictionary.prototype.GetIndexByKey = function(key){ return this.FindRowIndex(Mian.Lib.Dictionary.COLUMN_KEY, key); }
Mian.Lib.Dictionary.prototype.GetIndexByValue = function(value){ return this.FindRowIndex(Mian.Lib.Dictionary.COLUMN_VALUE, value); }
Mian.Lib.Dictionary.prototype.ContainsKey = function(key){ return this.GetIndexByKey(key) != -1; }
Mian.Lib.Dictionary.prototype.ContainsValue = function(value){return this.GetIndexByValue(value) != -1;}
Mian.Lib.Dictionary.prototype.FindRowIndex = function(columnNo, value) {
    for(var index in this.InnerArray) 
    if(this.InnerArray[index][columnNo] == value) return index;
    return -1;
}
Mian.Lib.Dictionary.prototype.GetValues = function(){
    var values = new Array();
    for(var index in this.InnerArray) values.push(this.GetValueByIndex(index));
    return values;
}
//String Functions
//=========================================================================
Mian.Lib.DeserializeFromJSON = function(jsonString) {
    if (jsonString == null || jsonString == '') return null;
    try {
        eval("var object = " + jsonString);
        return object;
    }
    catch (error) {
        return null;
    }
}
Mian.Lib.GetLocalNumberString = function(number){
    var numberString = new Number(number).toLocaleString();
    return numberString.substr(0, numberString.length - 3);
}
Mian.Lib.ParseToInt = function(str){
    if(str==null || str =='') return '';
    var onlyDigits = Mian.Lib.String.Replace(str,'[^+-0123456789]','')
    return parseInt(onlyDigits);
}
Mian.Lib.ParseToIntDefault = function(str,def) {
if (str == null || str == '') return def;
    var onlyDigits = Mian.Lib.String.Replace(str, '[^+-0123456789]', '')
    return parseInt(onlyDigits);
}
Mian.Lib.String = {}
Mian.Lib.String.Replace = function(text, findString, replaceString){
    var regEx = new RegExp(findString, "g");
    return text.replace(regEx, replaceString);
}
//not tested
//function replace_string(text, findString, replaceString){
//    var findStringLength =  findString.length;
//    for (var replaceIndex = text.indexOf(findString); replaceIndex != -1; replaceIndex = text.indexOf(findString)){ 
//            text = text.substr(0, replaceIndex) + replaceString + text.substr(replaceIndex + findStringLength);
//    }
//    return text;
//}
//RequestXMLHttp Class
//=========================================================================
Mian.Lib.HttpRequest = function(){}
Mian.Lib.HttpRequest.prototype.CreateRequest = function(){
    if (window.XMLHttpRequest) {
        this.Request = new XMLHttpRequest(); 
    } else if (window.ActiveXObject) {
        this.Request = new ActiveXObject('Msxml2.XMLHTTP');
        if(!this.Request) this.Request = new ActiveXObject("Microsoft.XMLHTTP");
    }    
}
Mian.Lib.HttpRequest.prototype.IsLoading = function(){
    return this.Request != null;
}
Mian.Lib.HttpRequest.prototype.Send = function(method, url, callback, parameters) {
    if (this.Request) this.Request.abort();
    this.CreateRequest();
    this.Request.onreadystatechange = callback;
    this.Request.open(method, url, true);
    this.Request.send(null);
}
Mian.Lib.HttpRequest.prototype.Receive = function(callbacks, options){
    if(this.Request){
        if (this.Request.readyState == 4){
            if (this.Request.status == 200){
                if(callbacks && callbacks.success!=null){ 
                    callbacks.success(options && options.isJSON ? Mian.Lib.DeserializeFromJSON(this.Request.responseText) : this.Request.responseText);
                }
            } else {
                if(callbacks && callbacks.error != null) callbacks.error();
            }
            this.Request = null;
        }
    }
}
Mian.Lib.HttpRequest.prototype.Get = function(url, callbacks) {
    var thisObject = this;
    if(callbacks && callbacks.loading!=null) callbacks.loading();
    this.Send("GET", url, function(){ thisObject.Receive(callbacks, {isJSON : false}); });
}
Mian.Lib.HttpRequest.prototype.GetJSON = function(url, callbacks) {
    var thisObject = this;
    if(callbacks && callbacks.loading!=null) callbacks.loading();
    this.Send("GET", url, function(){ thisObject.Receive(callbacks, {isJSON : true}); });
}

///Brouser
//======================================================================================
Mian.Lib.Browser = new function() {
    var d = this;

    var n = navigator;
    var dua = n.userAgent;
    var dav = n.appVersion;
    var tv = parseFloat(dav);

    d.isOpera = (dua.indexOf("Opera") >= 0) ? tv : 0;
    d.isKhtml = (dav.indexOf("Konqueror") >= 0) || (dav.indexOf("Safari") >= 0) ? tv : 0;
    d.isSafari = (dav.indexOf("Safari") >= 0) ? tv : 0;
    var geckoPos = dua.indexOf("Gecko");
    d.isMozilla = ((geckoPos >= 0) && (!d.isKhtml)) ? tv : 0;
    d.isFF = 0;
    d.isIE = 0;
    try {
        if (d.isMozilla) {
            d.isFF = parseFloat(dua.split("Firefox/")[1].split(" ")[0]);
        }
        if ((document.all) && (!d.isOpera)) {
            d.isIE = parseFloat(dav.split("MSIE ")[1].split(";")[0]);
        }
    } catch (e) { }
}


//Event Manager Class
//=========================================================================
Mian.Lib.EventManager = function(){
    this.Objects = new Mian.Lib.Dictionary();
}
Mian.Lib.EventManager.prototype.GetEventHandlers = function(eventName, targetObject){
    var objectEventHandlers = this.Objects.GetValueByKey(targetObject);
    if(objectEventHandlers == null) return null;
    return objectEventHandlers.GetValueByKey(eventName);
}
Mian.Lib.EventManager.prototype.GetOrCreateEventHandlers = function(eventName, targetObject){
    if(!this.Objects.ContainsKey(targetObject)) this.Objects.Add(targetObject, new Mian.Lib.Dictionary());
    var objectEventHandlers = this.Objects.GetValueByKey(targetObject);
    if(!objectEventHandlers.ContainsKey(eventName)) objectEventHandlers.Add(eventName, new Array());
    return objectEventHandlers.GetValueByKey(eventName);
}
Mian.Lib.EventManager.prototype.AddEventHandler = function(eventName, targetObject, handler){
    var eventHandlers = this.GetOrCreateEventHandlers(eventName, targetObject);
    eventHandlers.push(handler);
}
Mian.Lib.EventManager.prototype.RemoveEventHandler = function(eventName, targetObject, handler, isRemoveAll){
    var eventHandlers = this.GetEventHandlers(eventName, targetObject);
    for(var index in eventHandlers){ 
        if(handler == eventHandlers[index]){
            eventHandlers.slice(index, index);
            if(isRemoveAll != true) return;
        }
    }
}
Mian.Lib.EventManager.prototype.RaiseEvent = function(eventName, targetObject, eventArgs){
    var eventHandlers = this.GetEventHandlers(eventName, targetObject);
    for(var index in eventHandlers) eventHandlers[index](eventArgs);
}
//static
Mian.Lib.EventManager.Instance = new Mian.Lib.EventManager();

Mian.Lib.GetElementByTagName = function(parent,tagName)
{
    for(var index in parent.childNodes)
    {
        var cur = parent.childNodes[index];
        var child =   Mian.Lib.GetElementByTagName(cur,tagName);  
        if(child!=null && child.tagName == tagName) return child;
        var cur = parent.childNodes[index];
        if(cur.tagName == tagName) return cur;
    
    }
    return null;
}
Mian.Lib.Advertise = {}
Mian.Lib.Advertise.Adv = function(objectID) {
    this.Container = document.getElementById(objectID);
    
}
Mian.Lib.Advertise.Adv.prototype.ResizeBanner = function(width, height) {
if (this.Container != null) {
        if (window.navigator.userAgent.indexOf("MSIE") >= 0 && window.navigator.userAgent.substr(window.navigator.userAgent.indexOf("MSIE") + 5, 3) == "6.0") {
            this.Container.style.height = '1%';
        } else {
            if(width != "") this.Container.style.width = width + 'px';
            if(height != "") this.Container.style.height = height + 'px';
        }
    }
}

Mian.Lib.Advertise.Adv.prototype.Load = function() {
    Mian.Lib.AdvertiseManager.Instance.NextBannerLoad();
}

Mian.Lib.AdvertiseManager = function() {
    this.Objects = new Mian.Lib.Dictionary();
}

Mian.Lib.AdvertiseManager.prototype.AddAdventise = function(objectID, guid, fileUrl, width, height, rank) {
    var advObj = new Object();
    advObj.fileUrl = fileUrl;
    advObj.width = width;
    advObj.height = height;
    advObj.rank = rank;
    advObj.containerID = objectID;
    this.Objects.Add(guid, advObj);
}

Mian.Lib.AdvertiseManager.prototype.LoadBanner = function(objectID) {
    if (!this.Objects.ContainsKey(objectID)) return;
    var thisobject = this;
    var advObj = this.Objects.GetValueByKey(objectID);
    var container = document.getElementById(advObj.containerID);
    var newdiv = Mian.Lib.CreateElement('div', { 'id': objectID }, { 'width': advObj.width + 'px', 'height': advObj.height + 'px' });
    Mian.Lib.EventManager.Instance.AddEventHandler("BeginLoad", newdiv, function() { ; })
    Mian.Lib.EventManager.Instance.AddEventHandler("LoadComplite", newdiv, function() { thisobject.NextBannerLoad(); })
    container.appendChild(newdiv);
    var so = new SWFObject(advObj.fileUrl, "sotester", "'" + advObj.width + "'", "'" + advObj.height + "'", "8", "#FFFFFF");
    so.addVariable("banner", objectID);
    so.write(objectID);
}

Mian.Lib.AdvertiseManager.prototype.BeginLoadBanners = function() {
    var z = '';
    this.cur_index = 0;
    this.beginTime = new Date();
    this.NextBannerLoad();
}

Mian.Lib.AdvertiseManager.prototype.NextBannerLoad = function() {
    var endTime = new Date();
    var raz = endTime - this.beginTime;
    if (raz > 600) return;
    this.beginTime = new Date();
    if (this.Objects.Length() > this.cur_index) {
        var bannerID = this.Objects.InnerArray[this.cur_index][0];
        this.LoadBanner(bannerID);
        this.cur_index++;
    }
}

Mian.Lib.AdvertiseManager.Instance = new Mian.Lib.AdvertiseManager();


Mian.Lib.HttpIFrameRequest = function() { this.loading = false; }
Mian.Lib.HttpIFrameRequest.prototype.CreateIFrame = function(fname) {
    if (this.m_iframe != null) return this.m_iframe;
    var ifrstr = Mian.Lib.Browser.isIE ? '<iframe name="' + fname + '" src="javascript:">' : 'iframe'
    var cframe = document.createElement(ifrstr);

    with (cframe) {
        name = fname
        setAttribute("name", fname)
        id = fname
    }
    document.body.appendChild(cframe);
    with (cframe.style) {
        if (!Mian.Lib.Browser.isSafari) {
            position = "absolute";
        }
        left = top = "0px";
        height = width = "1px";
        visibility = "hidden";
    }
    this.m_iframe = cframe;
    return cframe;
}

Mian.Lib.HttpIFrameRequest.prototype.GetIframeDocument = function(iframeNode) {
    if (iframeNode.contentDocument) return iframeNode.contentDocument
    if (iframeNode.contentWindow) return iframeNode.contentWindow.document
    return iframeNode.document
}

Mian.Lib.HttpIFrameRequest.prototype.IsLoading = function() {
    return this.loading;
}

Mian.Lib.HttpIFrameRequest.prototype.Send = function(url, callbacks, options) {
    var iframe = this.CreateIFrame('IFrameRequestForTransport');
    var thisobject = new Object();
    thisobject.parent = this;
    thisobject.callbacks = callbacks;
    thisobject.options = options;
    thisobject.iframe = iframe;
    window.deliver = function(url) {
        var iframe = thisobject.parent.GetIframeDocument(thisobject.iframe);
        thisobject.parent.loading = false;
        if (thisobject.callbacks && thisobject.callbacks.success != null) {
            thisobject.callbacks.success(thisobject.options && thisobject.options.isJSON ? Mian.Lib.DeserializeFromJSON(iframe.firstChild.lastChild.innerHTML) : iframe.firstChild.lastChild.innerHTML);
            if (thisobject.callbacks.update != null) thisobject.callbacks.update(url);
        }
    }
    this.loading = true;
    this.SetIframeSrc(iframe, url, callbacks);
}

Mian.Lib.HttpIFrameRequest.prototype.SetIframeSrc = function(iframe, src, callbacks) {
    if (callbacks != null) callbacks.loading();
    //document.domain = "mian.ru";
    iframe.src = src;
}

Mian.Lib.HttpIFrameRequest.prototype.Get = function(url, callbacks) {
    var thisObject = this;
    if (callbacks && callbacks.loading != null) callbacks.loading();
    this.Send(url,callbacks,{ isJSON: false });
}
Mian.Lib.HttpIFrameRequest.prototype.GetJSON = function(url, callbacks) {
    var thisObject = this;
    if (callbacks && callbacks.loading != null) callbacks.loading();
    this.Send(url, callbacks, { isJSON: true });
}


    Mian.History = function()
    {
        this.IsHistory = false;
        this.ieSupportBack = false;
    };

    Mian.History.prototype.Check = function() {
        var h = document.location.hash;
        if (h != this.hash) {
            this.hash = h;
            Mian.Lib.EventManager.Instance.RaiseEvent("HashChanged", this, this.hash);
        }
    }

    Mian.History.prototype.Init = function() {
        this.IsHistory = true;
        this.ieSupportBack = true;
        this.hash = document.location.hash;
        this.m_framename = "iframe_" + Math.ceil(Math.random()*1000);

        if (Mian.Lib.Browser.isIE && this.ieSupportBack) {
            var frame = document.createElement("iframe");
            frame.id = this.m_framename;
            frame.style.display = "none";
            document.body.appendChild(frame);
        }
        var self = this;
        if ("onpropertychange" in document && "attachEvent" in document) {
            document.attachEvent("onpropertychange", function() {
                if (event.propertyName == "location") {
                    self.Check();
                }
            });
        }
        window.setInterval(function() { self.Check() }, 1000);
    }
    Mian.History.prototype.SetHash = function(_hash) {
        if (!this.IsHistory) return;
        // Mozilla always adds an entry to the history
        if (Mian.Lib.Browser.isIE && this.ieSupportBack) {
            this.WriteFrame(_hash);
        }
        document.location.hash = _hash;
    }
    Mian.History.prototype.GetHash = function() {
        return document.location.hash;
    }
    Mian.History.prototype.WriteFrame = function(_hash) {
        if(!this.IsHistory) return;
        var f = document.getElementById(this.m_framename);
        var d = f.contentDocument || f.contentWindow.document;
        d.open();
        d.write("<script>window._hash = '" + _hash + "'; window.onload = parent.Mian.History.Instance.SyncHash;<\/script>");
        d.close();
    }
    Mian.History.prototype.SyncHash = function() {
        var s = this._hash;
        if (s != document.location.hash) {
            document.location.hash = s;
        }
    }
   
    Mian.History.Instance = new Mian.History;
    
    Mian.Lib.CreateElement = function(name, attrs, style, text) 
    {
            var e = document.createElement(name);
            if (attrs) {
                for (key in attrs) {
                    if (key == 'class') {
                        e.className = attrs[key];
                    } else if (key == 'id') {
                        e.id = attrs[key];
                    } else {
                        e.setAttribute(key, attrs[key]);
                    }
                }
            }
            if (style) {
                for (key in style) {
                    e.style[key] = style[key];
                }
            }
            if (text) {
                e.appendChild(document.createTextNode(text));
            }
            return e;
    }
    Mian.Lib.getElementsByName = function(tag, name) {

        var elem = document.getElementsByTagName(tag);
        var arr = new Array();
        for (i = 0, iarr = 0; i < elem.length; i++) {
            att = elem[i].getAttribute("name");
            if (att == name) {
                arr[iarr] = elem[i];
                iarr++;
            }
        }
        return arr;
    }
    
    
    Mian.Lib.Cart = function()
    {
        this.m_carts = new Mian.Lib.Dictionary();
    }
    Mian.Lib.Cart.prototype.InsertArray = function(items) {
        this.m_carts.Clear();
        for (var index in items) {
            id = items[index];
            if (!this.m_carts.ContainsKey(id)) this.m_carts.Add(id, 1);
        }
        this.OutValueCountCart();
    }

    Mian.Lib.Cart.prototype.SetElementToOutValueCountCart = function(id)
    {
        this.m_outValueId = id;
    }
    Mian.Lib.Cart.prototype.OutValueCountCart = function() {
        if (!this.m_outValueId || !this.m_carts) return;
        var element = document.getElementById(this.m_outValueId);
        if (element) {
                element.innerHTML = this.m_carts.Length();
        }
    }

    Mian.Lib.Cart.prototype.InsertItem = function(objectID, isInsert) {
        //init and create short-cut name for Web service
        //cartSvc = document.getElementById("cartSvc");
        var carts = Array();
        var ajax = new Mian.Lib.HttpRequest();
        if (isInsert) {
            ajax.Get('http://www.mian.ru/HttpHandlers/CartInsertObjectRealty.ashx?id=' + objectID, null);
            //ajax.Get('http://localhost:64776/HttpHandlers/CartInsertObjectRealty.ashx?id=' + objectID, null);
            if (!this.m_carts.ContainsKey(objectID)) this.m_carts.Add(objectID, 1);
            this.OutValueCountCart();
            return true;
        } else {
        ajax.Get('http://www.mian.ru/HttpHandlers/CartDeleteObjectRealty.ashx?id=' + objectID, null);
        //ajax.Get('http://localhost:64776/HttpHandlers/CartDeleteObjectRealty.ashx?id=' + objectID, null);
            this.m_carts.DeleteByKey(objectID);
            this.OutValueCountCart();
            return false;
        }
    }
    Mian.Lib.Cart.prototype.IsInsertCart = function(objectID) {
        var z = 0;
        if (this.m_carts.GetValueByKey(objectID) == null) return false;
        return true;
    }

    Mian.Lib.Cart.Instanse = new Mian.Lib.Cart();

    Mian.Lib.StyleSheet = function() { }

    Mian.Lib.StyleSheet.prototype.AddStyleSheet = function(url) {
        // Создаём элемент LINK/STYLE и добавляем в документ
        var style;
        if (typeof url == 'undefined') {
            style = document.createElement('style');
        }
        else {
            style = document.createElement('link');
            style.rel = 'stylesheet';
            style.type = 'text/css';
            style.href = url;
        }
        document.getElementsByTagName('head')[0].appendChild(style);

        // Находим новый стиль в коллекции styleSheets
        style = document.styleSheets[document.styleSheets.length - 1];

        // Делаем объект совместимыми с W3C DOM2 (для IE)
        return this.StyleSheet_makeCompatible(style);
    }

    Mian.Lib.StyleSheet.prototype.StyleSheet_makeCompatible = function(style) {
        // Mozilla не даёт доступа к cssRules до загрузки стиля
        try {
            style.cssRules;
        }
        catch (e) {
            return style;
        }

        // Создаём CSSStyleSheet.cssRules
        if (typeof style.cssRules == 'undefined' && typeof style.rules != 'undefined')
            style.cssRules = style.rules;

        // Создаём CSSStyleSheet.insertRule и CSSStyleSheet.deleteRule
        if (typeof style.insertRule == 'undefined' && typeof style.addRule != 'undefined')
            style.insertRule = this.StyleSheet_insertRule;
        if (typeof style.deleteRule == 'undefined' && typeof style.removeRule != 'undefined')
            style.deleteRule = style.removeRule;

        // Проверяем, существуют ли все нужные свойства
        if (typeof style.cssRules == 'undefined' || typeof style.insertRule == 'undefined'
      || typeof style.deleteRule == 'undefined')
            return null;
        else
            return style;
    }

    Mian.Lib.StyleSheet.prototype.StyleSheet_insertRule = function(rule, index) {
        // Выделяем селектор и стиль из параметра
        if (rule.match(/^([^{]+)\{(.*)\}\s*$/)) {
            this.addRule(RegExp.$1, RegExp.$2, index);
            return index;
        }
        throw "Syntax error in CSS rule to be added";
    }

    Mian.Lib.StyleSheet.Instanse = new Mian.Lib.StyleSheet();

    // c-tor
    Mian.Lib.PropertyExtractor = function(propName) {
        this.PropertyName = propName;
        this.Extract = function(object) {
                if (object == null)
                    return null;
                if (this.PropertyName in object)
                    return object[this.PropertyName];
                return null;
            }
        }
        // static helpers
        Mian.Lib.PropertyExtractor.Extract = function(obj, propName) {
            return (new Mian.Lib.PropertyExtractor(propName)).Extract(obj);
        }
