var APF = {
    log: function(v) {
    }
};

APF.Namespace = {
    register: function(ns){
        var nsParts = ns.split(".");
        var root = window;
        for (var i = 0; i < nsParts.length; i++) {
            if (typeof root[nsParts[i]] == "undefined") {
                root[nsParts[i]] = new Object();
            }
            root = root[nsParts[i]];
        }
    }
}

APF.Utils = {
    getWindowSize: function() {
        var myWidth = 0, myHeight = 0;
            if( typeof( window.innerWidth ) == 'number' ) {
            //Non-IE
            myWidth = window.innerWidth;
            myHeight = window.innerHeight;
        } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
            //IE 6+ in 'standards compliant mode'
            myWidth = document.documentElement.clientWidth;
            myHeight = document.documentElement.clientHeight;
        } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
            //IE 4 compatible
            myWidth = document.body.clientWidth;
            myHeight = document.body.clientHeight;
        }
        return {
            width: myWidth,
            height: myHeight
        };
    },

    getScroll: function() {
        var scrOfX = 0, scrOfY = 0;
        if( typeof( window.pageYOffset ) == 'number' ) {
            //Netscape compliant
            scrOfY = window.pageYOffset;
            scrOfX = window.pageXOffset;
        } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
            //DOM compliant
            scrOfY = document.body.scrollTop;
            scrOfX = document.body.scrollLeft;
        } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
            //IE6 standards compliant mode
            scrOfY = document.documentElement.scrollTop;
            scrOfX = document.documentElement.scrollLeft;
        }
        return {
            left: scrOfX,
            top: scrOfY
        };
    },

    // http://techpatterns.com/downloads/javascript_cookies.php
    setCookie: function(name, value, expires, path, domain, secure) {
        // set time, it's in milliseconds
        var today = new Date();
        today.setTime(today.getTime());
        /*
            if the expires variable is set, make the correct
            expires time, the current script below will set
            it for x number of days, to make it for hours,
            delete * 24, for minutes, delete * 60 * 24
        */
        if (expires) {
            expires = expires * 1000 * 60 * 60 * 24;
        }
        var expires_date = new Date(today.getTime() + (expires));

        document.cookie = name + "=" +escape(value) +
            ((expires) ? ";expires=" + expires_date.toGMTString() : "") +
            ((path) ? ";path=" + path : "") +
            ((domain) ? ";domain=" + domain : "" ) +
            ((secure) ? ";secure" : "" );
    },

    // this fixes an issue with the old method, ambiguous values
    // with this test document.cookie.indexOf( name + "=" );
    getCookie: function(check_name) {
        // first we'll split this cookie up into name/value pairs
        // note: document.cookie only returns name=value, not the other components
        var a_all_cookies = document.cookie.split( ';' );
        var a_temp_cookie = '';
        var cookie_name = '';
        var cookie_value = '';
        var b_cookie_found = false; // set boolean t/f default f

        for (i = 0; i < a_all_cookies.length; i++) {
            // now we'll split apart each name=value pair
            a_temp_cookie = a_all_cookies[i].split( '=' );

            // and trim left/right whitespace while we're at it
            cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

            // if the extracted name matches passed check_name
            if (cookie_name == check_name) {
                b_cookie_found = true;
                // we need to handle case where cookie has no value but exists (no = sign, that is):
                if (a_temp_cookie.length > 1) {
                    cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
                }
                // note that in cases where cookie is initialized but no value, null is returned
                return cookie_value;
                break;
            }
            a_temp_cookie = null;
            cookie_name = '';
        }
        if (!b_cookie_found) {
            return null;
        }
    },

    // this deletes the cookie when called
    deleteCookie: function(name, path, domain) {
        if (this.getCookie(name)) {
            document.cookie = name + "=" +
            ((path) ? ";path=" + path : "") +
            ((domain) ? ";domain=" + domain : "") + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
        }
    }
}
APF.Namespace.register("anjuke.global.header");

anjuke.global.header.CitySelector = Class.create({
    initialize: function(selectorId, panelId, hideTimeout) {
        this.selector = $(selectorId);
        this.panelId = panelId;
        this.hideTimeout = hideTimeout;

        var panel = $(panelId);
        this.iframe = panel.select("iframe").first();

        this.iframe.setStyle({width:panel.getWidth()+'px', height:panel.getHeight()+"px"});

        this.selector.observe('mouseover', function() {
            window.clearTimeout(this.timeoutHandle);
            $(this.panelId).show();
        }.bind(this));

        this.selector.observe('mouseout', function() {
            window.clearTimeout(this.timeoutHandle);
            this.timeoutHandle = window.setTimeout("$('" + this.panelId + "').hide()", this.hideTimeout);
        }.bind(this));
        var el = this.selector.select('a').first();
        if (el != undefined) {
            el.observe('click', function(event) {
                event.preventDefault();
            });
        }
    }
});APF.Namespace.register("anjuke.global.header");

anjuke.global.header.CornerLinks = Class.create({
    initialize: function(element) {
        this.element = $(element);
    },
    
    test:function(panelId,selector){
    	$(panelId).hide();
    	selector.className = 'myanjuke';
    },

    bindEvents: function(selectorId, panelId, hideTimeout) {
    	this.selector = $(selectorId);
        this.panelId = panelId;
        this.panel = $(panelId);
        this.hideTimeout = hideTimeout;

        this.selector.observe('mouseover', function(e) {
            window.clearTimeout(this.timeoutHandle);
            this.panel.style.display = 'block';
            this.selector.addClassName('myanjuke_hover');
        }.bind(this));

        this.panel.observe('mouseover', function() {
            window.clearTimeout(this.timeoutHandle);
            this.selector.addClassName('myanjuke_hover');
        }.bind(this));

        this.panel.observe('mouseout', function() {
            window.clearTimeout(this.timeoutHandle);
            this.timeoutHandle = window.setTimeout("$('"+this.panelId+"').hide();$('"+selectorId+"').removeClassName('myanjuke_hover');", this.hideTimeout);
        }.bind(this));
        
        this.selector.observe('mouseout', function() {
            window.clearTimeout(this.timeoutHandle);
            this.timeoutHandle = window.setTimeout("$('"+this.panelId+"').hide();$('"+selectorId+"').removeClassName('myanjuke_hover');", this.hideTimeout);
        }.bind(this));
    }
});APF.Namespace.register("anjuke.global.search");

anjuke.global.search.Autocompleter = Class.create(Ajax.Autocompleter, {
    initialize: function($super, element, update, url, options) {
        $super(element, update, url, options);
        this.index = -1;
        this._fixChineseInputMethodProblem();
    },

    // 中文输入法可能没有'keyDown'事件，改用轮询检测输入框的变化来实现
    _fixChineseInputMethodProblem: function() {
        var timeout = window.setInterval(function() {
            if (this.oldElementValue == this.element.value) {
                return;
            }
            this.oldElementValue = this.element.value;
            if (this.observer) {
                clearTimeout(this.observer);
            }
            this.observer = setTimeout(this.onObserverEvent.bind(this), 0);
        }.bind(this), this.options.frequency * 1000);
    },

    // avoid useless ajax call
    selectEntry: function($super) {
        this.oldElementValue = this.element.value;
        if (this.observer) {
            clearTimeout(this.observer);
        }
        $super();
    },

    // force this.index = -1
    updateChoices: function($super, choices) {
        if (!this.changed && this.hasFocus) {
            this.update.innerHTML = choices;
            Element.cleanWhitespace(this.update);
            Element.cleanWhitespace(this.update.down());

            if (this.update.firstChild && this.update.down().childNodes) {
                this.entryCount = this.update.down().childNodes.length;
                for (var i = 0; i < this.entryCount; i++) {
                    var entry = this.getEntry(i);
                    entry.autocompleteIndex = i;
                    this.addObservers(entry);
                }
            } else {
                this.entryCount = 0;
            }

            this.stopIndicator();
            this.index = -1;

            if(this.entryCount==1 && this.options.autoSelect) {
                this.selectEntry();
                this.hide();
            } else {
                this.render();
            }
        }
    },

    // overwrite from Ajax.Autocompleter. Skips ajax call on key press to avoid duplicated ajax call;
    onKeyPress : function(event) {
        if (this.observer) {
            clearTimeout(this.observer);
            this.observer = null;
        }

        if (this.active) {
            switch (event.keyCode) {
                case Event.KEY_RETURN:
                    if (this.index < 0) {
                        return;
                    }
                    this.selectEntry();
                    Event.stop(event);
                case Event.KEY_TAB:
                case Event.KEY_ESC:
                    this.hide();
                    this.active = false;
                    Event.stop(event);
                    return;
                case Event.KEY_LEFT:
                case Event.KEY_RIGHT:
                    return;
                case Event.KEY_UP:
                    this.markPrevious();
                    this.render();
                    Event.stop(event);
                    return;
                case Event.KEY_DOWN:
                    this.markNext();
                    this.render();
                    Event.stop(event);
                    return;
            }
        } else if (event.keyCode == Event.KEY_TAB
                || event.keyCode == Event.KEY_RETURN
                || (Prototype.Browser.WebKit > 0 && event.keyCode == 0)) {
            return;
        }

        this.changed = true;
        this.hasFocus = true;
    },

    // Overwrite from Ajax.Autocompleter.
    // Reduces 2px of the width of update element. so that the border should display correctly
    show: function($super) {
        $super();
        this.update.setStyle({width: this.update.getWidth() - 2 + 'px'});
    },

    // Overwrite from Ajax.Autocompleter. Seems to fix KEY_UP problem
    markPrevious: function() {
        if (this.index > 0) {
            this.index--;
        } else {
            this.index = this.entryCount - 1;
        }
        this.getEntry(this.index).scrollIntoView(false);
    },

    //
    getUpdatedChoices: function($super) {
        this.startIndicator();

        var entry = encodeURIComponent(this.options.paramName) + '=' + encodeURIComponent(this.getToken());

        this.options.parameters = this.options.callback
            ? this.options.callback(this.element, entry)
            : entry;

        if (this.options.defaultParams) {
            this.options.parameters += '&' + this.options.defaultParams;
        }

        var request = new Ajax.Request(this.url, this.options);
        this.requestingURL = request.url;
    },

    onComplete: function(request) {
        if (this.requestingURL == request.request.url) {
            this.requestingURL = null;
            this.updateChoices(request.responseText);
        }
    }
});

anjuke.global.search.SearchSuggestion = Class.create({
    initialize:function (element, url, options) {
        this.options = options || {};
        this.element = $(element);
        this.update = this.options.update ? $(this.options.update) : this._createUpdateElement();
        this.url = url;
        this.useSuggestion = false;

        this.autocompleter = new anjuke.global.search.Autocompleter(this.element, this.update, this.url, {
            method: 'GET',
            frequency: 0.2,
            minChars: 1,

            afterUpdateElement: function(element, selectedElement) {
                element.value = selectedElement.firstDescendant().innerHTML;
                var form = this._findParentForm(element);
                if (form) {
                    /*
                     * us=1 means user selected a provided keyword.
                     * GlobalSearchController should also handle this
                     *
                    var input = document.createElement('input');
                    input.setAttribute("type", "hidden");
                    input.setAttribute("name", "us");
                    input.setAttribute("value", "1");
                    form.appendChild(input);
                    */
                    form.submit();
                }
            }.bind(this),

            callback: function(element, entry) {
                if (!this.options.onParameters) {
                    return entry;
                }
                var params = this.options.onParameters(entry);
                if (params && 'function' == typeof(params.toQueryString)) {
                    return params.toQueryString();
                } else {
                    return params;
                }
            }.bind(this)
        });
    },

    _findParentForm: function(element) {
        var e = element;
        while (e) {
            if (e.tagName == 'FORM') {
                break;
            }
            e = e.parentNode;
        }
        return e;
    },

    _createUpdateElement: function() {
        var element = $(document.createElement('div'));
        this.options.className = this.options.className || 'SearchSuggestion';
        element.addClassName(this.options.className);
        var ie = this._getInternetExplorerVersion();
        if (ie > 0 && ie <= 7) {
        	var ele = this.element.ancestors();
            Element.insert(ele[0], {after: element});
        } else {
            Element.insert(document.body, {top: element});
        }

        return element;
    },

    _getInternetExplorerVersion: function() {
        var rv = -1; // Return value assumes failure.
        if (navigator.appName == 'Microsoft Internet Explorer') {
            var ua = navigator.userAgent;
            var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
            if (re.exec(ua) != null) {
                rv = parseFloat(RegExp.$1);
            }
        }
        return rv;
    }
});APF.Namespace.register("anjuke.global.header");

anjuke.global.header.OptionList = Class.create({
    initialize: function(triggerId, panelId, current_optionId, textboxId, txtkwid, formid) {
        this.trigger = $(triggerId);
        this.panel = $(panelId);
        var panel = $(panelId);
        var textbox = $(textboxId);
        var current_option = $(current_optionId);
        var form = $(formid);
        this.trigger.observe('click', function(){
            if(this.panel.style.display=='none'){
                this.panel.style.display='block';
            }else{
                this.panel.style.display='none';
            }
        }.bind(this));

        current_option.observe('mouseover', function() {
            current_option.addClassName("current_option_hover");
        });
        current_option.observe('mouseout', function() {
            if (panel.visible()) {
                return;
            }
            current_option.removeClassName("current_option_hover");
        });

        // opera not works
        current_option.observe('blur', function(e){
            var explicitOriginalTarget = e.explicitOriginalTarget == undefined ? document.activeElement : e.explicitOriginalTarget;
            // if (this.descendantOfPanel(explicitOriginalTarget)) {
            if (Element.descendantOf(explicitOriginalTarget, this.panel)) {
                current_option.focus();
                return;
            }
            current_option.removeClassName("current_option_hover");
            panel.hide();
        }.bind(this));

        this.panel.getElementsBySelector('span').each(function(obj) {

            obj.observe('click', function() {
                current_option.innerHTML = obj.innerHTML;
                textbox.value=obj.getAttribute('v');
                if(textbox.value == "5"){
                	$(txtkwid).value = "请输入房源特征,地点或楼盘名...";
                }else if(textbox.value == "3"){
                	$(txtkwid).value = "请输入小区名或路名...";
                }else{
                	$(txtkwid).value = "请输入房源特征,地点或小区名...";
                }
                if(textbox.value == "1"){
                	form.target = "";
                }else{
                	form.target = "_blank";
                }
                if(textbox.value == "3"){
                	$("sbtn").className = "btn2";
                }else{
                	$("sbtn").className = "btn";
                }
                current_option.removeClassName("current_option_hover");
                panel.hide();

                Element.fire(document, 'SearchBar:OptionList', textbox.value);

                panel.getElementsBySelector('span').each(function(obj2){
                    obj2.setAttribute('s', 'none');
                    obj2.setAttribute('class', 'item');         //for firefox
                    obj2.setAttribute('className', 'item');     //for IE
                })
                obj.setAttribute('s', 'selected');
                obj.setAttribute('class', 'selected');
                obj.setAttribute('className', 'selected');
            });

            obj.observe('mouseover', function() {
                if(obj.getAttribute('s')!='selected'){
                    obj.setAttribute('class', 'mousehover');
                    obj.setAttribute('className', 'mousehover');
                }
            });
            obj.observe('mouseout', function() {
                if(obj.getAttribute('s')!='selected'){
                    obj.setAttribute('class', 'item');
                    obj.setAttribute('className', 'item');
                }
            });


        });


    },

    descendantOfPanel: function(e) {
        if (e == null) {
            return false;
        }
        if (e == this.panel) {
            return true;
        }
        return this.descendantOfPanel(e.parentNode);
    }

});APF.Namespace.register('anjuke.global.topnav');

anjuke.global.topnav = Class.create({
    initialize: function(p_strMyAnjukeID,p_strListID,p_strSelectorID,p_intTimeout,p_intUserType) {
		this.divAnjuke=$(p_strMyAnjukeID);
		this.divList=$(p_strListID);
		this.aSelector=$(p_strSelectorID);
		this.intTimeout=p_intTimeout;
		this.intUserType=p_intUserType;
		this.arrLis=this.divList.getElementsByTagName('li');

		this.divAnjuke.observe('mouseover',function(){
			window.clearTimeout(this.timeoutHandle);
			this.aSelector.className='ba_s';
			if(2==this.intUserType){
				this.divAnjuke.className='myanjuke_b_s';
			}else{
				this.divAnjuke.className='myanjuke_s';
			}
		}.bind(this));
		
		this.divList.observe('mouseover',function(){
			window.clearTimeout(this.timeoutHandle);
		}.bind(this));
		
		this.divList.observe('mouseout',function(){
			window.clearTimeout(this.timeoutHandle);
			this.timeoutHandle=window.setTimeout(function(){
				if(2==this.intUserType){
					this.divAnjuke.className='myanjuke_b';
				}else{
					this.divAnjuke.className='myanjuke';
				}
				this.aSelector.className='ba';
			}.bind(this), this.intTimeout);
		}.bind(this));
		
		this.divAnjuke.observe('mouseout',function(){
			window.clearTimeout(this.timeoutHandle);
			this.timeoutHandle=window.setTimeout(function(){
				if(2==this.intUserType){
					this.divAnjuke.className='myanjuke_b';
				}else{
					this.divAnjuke.className='myanjuke';
				}
				this.aSelector.className='ba';
			}.bind(this), this.intTimeout);
		}.bind(this));

    }
});APF.Namespace.register("anjuke.bbs.post.List");
anjuke.bbs.post.List = Class.create({
    initialize: function(upload_server,display_server,submit_target) {
        $('c_button').observe('click',function(){
            this.checkValue();
        }.bind(this));

        $('i_content').observe('keydown',function (event){
            event = event || window.event;
            var e = event.keyCode || event.which;
            if (e==13 && event.ctrlKey == true) {
                this.checkValue();
            }
        }.bind(this));
        $('insert_bt').observe('click',function(){
            var src = $('display_content').getAttribute("ref") || null;
            if(src){
                sHtml="<a href='"+ src +"'><img src='"+src+"'/></a>";
                xheditor.pasteHTML(sHtml);
            }

            $('picture').value = 0;
            $('display_content').src = '';
            $('display_div').style.display = 'none';
            $('upload_div').style.display = 'block';
        });

        $('del_bt').observe('click',function(){
            $('picture').value = 0;
            $('display_content').src = '';
            $('display_div').style.display = 'none';
            $('upload_div').style.display = 'block';
        });

        this.bt_post_submit = $('c_button');
        this.upload_form = $('form_1');
        this.upload_form_action = upload_server;
        this.display_server = display_server;
        this.submit_target = submit_target;
        this.upload_div = $('upload_div');
        this.upload_input_id =$('upload_input');
        this.upload_form_target = $('upload_frame');

        this.reset_input_box();

    },

    reset_input_box:function(){
        Element.remove($('upload_input'));
        var input_obj = document.createElement("input");
        input_obj.setAttribute("type","file");
        input_obj.setAttribute("name","file");
        input_obj.setAttribute("size","30");
        input_obj.setAttribute("id","upload_input");
        $('input_div').appendChild(input_obj);

        Element.observe($('upload_input'),"change",function(){
            if(!this.checkFileExt($('upload_input').value)){
               alert("您上传的图片类型不符合规则！");
               this.reset_input_box();
            }else{
                this.upload_img();
            }
        }.bind(this));
    },

    upload_img:function(){
            this.bt_post_submit.disabled = true;
            this.upload_form.setAttribute("target",'upload_frame');
            this.upload_form.setAttribute("action",this.upload_form_action);
            this.upload_form.submit();
            this.upload_form.setAttribute("target",'');
            this.upload_form.setAttribute("action",this.submit_target);
    },

    upload_finish: function(params) {
        this.bt_post_submit.disabled = false;
        var p = eval('('+params+')');
        if(p.status == 'ok' &&  p.image.size < 1258292){
            var img_url = this.display_server + 'bbs/' + p.image.id + '-150x150.jpg';
            var ref_url = this.display_server + 'bbs/' + p.image.id + '-700x0.jpg';
            $('upload_div').style.display = 'none';
            $('display_content').src = img_url;
            $('display_content').setAttribute("ref",ref_url);
            $('display_div').style.display = 'block';
            $('picture').value = p.image.id;
            this.reset_input_box();
        }else{
             alert("您上传的图片大小不符合规则");
             this.reset_input_box();
        }
    },

    checkFileExt:function(filename){
        var allow_ext = new  Array('.jpg','.jpeg','.gif','.png');
        var ext = filename.substr(filename.lastIndexOf(".")).toLowerCase();
        if(allow_ext.indexOf(ext) != -1){
            return true;
        }
        return false;
     },

    checkValue:function(){
        xheditor.getSource();
        var content = $('i_content').value.strip();
        if(content.length < 2 || content.length > 30000){
            alert('回复内容需要在2～30000字！');
             return false;
        }else{
            $('p_action').value = 1;
            $('form_1').submit();
            return false;
        }
    },

   _theEnd: undefined
});

function reply_content(floor,username){
    var str = "[b][i]回复 "+floor+" 楼 "+username+" [/i][/b]：\r\n";
    var obj = document.getElementById('i_content');
    xheditor.setSource(str);
    xheditor.focus();
}

function quote_content(url,id){
     var get_url = url + '?id='+id;
     get_url = encodeURI(get_url);
     var ajax = new Ajax.Request(
                   get_url,
                {
                    method:'get',
                    onSuccess: function(transport){
                    var response = transport.responseText.evalJSON(true);
                    var quote_str = response.quote_content || '';
                    xheditor.setSource(quote_str);
                    xheditor.focus();
                  }
                }
              );
}

