var last_submenu = 'myblog';
function showSubMenu( sub ) {
    if( document.getElementById('sub-menu-'+sub) ) {
        document.getElementById('sub-menu-'+last_submenu).style.display = 'none';
        document.getElementById('sub-menu-'+sub).style.display = 'block';
        last_submenu = sub;
    }
}

function confirmDelete() {

    if (typeof(msg_confirm_del) == 'undefined') {
        msg_confirm_del = 'Ви насправді хочете видалити?';
    }

    if ( confirm( msg_confirm_del ) ) {
        return true;
    } else {
        return false;
    }
}

function bindConfirmDelete(selector) {
    $(selector).click(function() {
        return confirmDelete();
    });
}

/************************************************************************************************************
*	DHTML modal dialog box
*
*	Created:						August, 26th, 2006
*	@class Purpose of class:		Display a modal dialog box on the screen.
*
*	Css files used by this script:	modal-message.css
*
*	Demos of this class:			demo-modal-message-1.html
*
* 	Update log:
*
************************************************************************************************************/


/**
* @constructor
*/

DHTML_modalMessage = function()
{
    var url;								// url of modal message
    var htmlOfModalMessage;					// html of modal message

    var divs_transparentDiv;				// Transparent div covering page content
    var divs_content;						// Modal message div.
    var iframe;								// Iframe used in ie
    var layoutCss;							// Name of css file;
    var width;								// Width of message box
    var height;								// Height of message box

    var existingBodyOverFlowStyle;			// Existing body overflow css
    var dynContentObj;						// Reference to dynamic content object
    var cssClassOfMessageBox;				// Alternative css class of message box - in case you want a different appearance on one of them
    var shadowDivVisible;					// Shadow div visible ?
    var shadowOffset; 						// X and Y offset of shadow(pixels from content box)
    var MSIE;

    this.url = '';							// Default url is blank
    this.htmlOfModalMessage = '';			// Default message is blank
    this.layoutCss = 'modal-message.css';	// Default CSS file
    this.height = '100%';						// Default height of modal message
    this.width = 400;						// Default width of modal message
    this.cssClassOfMessageBox = false;		// Default alternative css class for the message box
    this.shadowDivVisible = true;			// Shadow div is visible by default
    this.shadowOffset = 5;					// Default shadow offset.
    this.MSIE = false;
    if(navigator.userAgent.indexOf('MSIE')>=0) this.MSIE = true;


}

DHTML_modalMessage.prototype = {
    // {{{ setSource(urlOfSource)
    /**
    *	Set source of the modal dialog box
    *
    *
    * @public
    */
    setSource : function(urlOfSource)
    {
        this.url = urlOfSource;

    }
    // }}}
    ,
    // {{{ setHtmlContent(newHtmlContent)
    /**
    *	Setting static HTML content for the modal dialog box.
    *
    *	@param String newHtmlContent = Static HTML content of box
    *
    * @public
    */
    setHtmlContent : function(newHtmlContent)
    {
        this.htmlOfModalMessage = newHtmlContent;

    }
    // }}}
    ,
    // {{{ setSize(width,height)
    /**
    *	Set the size of the modal dialog box
    *
    *	@param int width = width of box
    *	@param int height = height of box
    *
    * @public
    */
    setSize : function(width,height)
    {
        if(width)this.width = width;
        if(height)this.height = height;
    }
    // }}}
    ,
    // {{{ setCssClassMessageBox(newCssClass)
    /**
    *	Assign the message box to a new css class.(in case you wants a different appearance on one of them)
    *
    *	@param String newCssClass = Name of new css class (Pass false if you want to change back to default)
    *
    * @public
    */
    setCssClassMessageBox : function(newCssClass)
    {
        this.cssClassOfMessageBox = newCssClass;
        if(this.divs_content){
            if(this.cssClassOfMessageBox)
            this.divs_content.className=this.cssClassOfMessageBox;
            else
            this.divs_content.className='modalDialog_contentDiv';
        }

    }
    // }}}
    ,
    // {{{ setShadowOffset(newShadowOffset)
    /**
    *	Specify the size of shadow
    *
    *	@param Int newShadowOffset = Offset of shadow div(in pixels from message box - x and y)
    *
    * @public
    */
    setShadowOffset : function(newShadowOffset)
    {
        this.shadowOffset = newShadowOffset

    }
    // }}}
    ,
    // {{{ display()
    /**
    *	Display the modal dialog box
    *
    *
    * @public
    */
    display : function()
    {
        if(!this.divs_transparentDiv){
            this.__createDivs();
        }

        // Redisplaying divs
        this.divs_transparentDiv.style.display='block';
        this.divs_content.style.display='block';
        this.divs_shadow.style.display='block';
        if(this.MSIE)this.iframe.style.display='block';
        this.__resizeDivs();

        /* Call the __resizeDivs method twice in case the css file has changed. The first execution of this method may not catch these changes */
        window.refToThisModalBoxObj = this;
        setTimeout('window.refToThisModalBoxObj.__resizeDivs()',150);

        this.__insertContent();	// Calling method which inserts content into the message div.
    }
    // }}}
    ,
    // {{{ ()
    /**
    *	Display the modal dialog box
    *
    *
    * @public
    */
    setShadowDivVisible : function(visible)
    {
        this.shadowDivVisible = visible;
    }
    // }}}
    ,
    // {{{ close()
    /**
    *	Close the modal dialog box
    *
    *
    * @public
    */
    close : function()
    {
        //document.documentElement.style.overflow = '';	// Setting the CSS overflow attribute of the <html> tag back to default.

        /* Hiding divs */
        this.divs_transparentDiv.style.display='none';
        this.divs_content.style.display='none';
        this.divs_shadow.style.display='none';
        if(this.MSIE)this.iframe.style.display='none';

    }
    // }}}
    ,
    // {{{ __addEvent()
    /**
    *	Add event
    *
    *
    * @private
    */
    addEvent : function(whichObject,eventType,functionName,suffix)
    {
        if(!suffix)suffix = '';
        if(whichObject.attachEvent){
            whichObject['e'+eventType+functionName+suffix] = functionName;
            whichObject[eventType+functionName+suffix] = function(){whichObject['e'+eventType+functionName+suffix]( window.event );}
            whichObject.attachEvent( 'on'+eventType, whichObject[eventType+functionName+suffix] );
        } else
        whichObject.addEventListener(eventType,functionName,false);
    }
    // }}}
    ,
    // {{{ __createDivs()
    /**
    *	Create the divs for the modal dialog box
    *
    *
    * @private
    */
    __createDivs : function()
    {
        // Creating transparent div
        this.divs_transparentDiv = document.createElement('DIV');
        this.divs_transparentDiv.className='modalDialog_transparentDivs';
        this.divs_transparentDiv.style.left = '0px';
        this.divs_transparentDiv.style.top = '0px';

        document.body.appendChild(this.divs_transparentDiv);
        // Creating content div
        this.divs_content = document.createElement('DIV');
        this.divs_content.className = 'modalDialog_contentDiv';
        this.divs_content.id = 'DHTMLSuite_modalBox_contentDiv';
        this.divs_content.style.zIndex = 100000;

        if(this.MSIE){
            this.iframe = document.createElement('<IFRAME src="about:blank" frameborder=0>');
            this.iframe.style.zIndex = 90000;
            this.iframe.style.position = 'absolute';
            document.body.appendChild(this.iframe);
        }

        document.body.appendChild(this.divs_content);
        // Creating shadow div
        this.divs_shadow = document.createElement('DIV');
        this.divs_shadow.className = 'modalDialog_contentDiv_shadow';
        this.divs_shadow.style.zIndex = 95000;
        document.body.appendChild(this.divs_shadow);
        window.refToModMessage = this;
        this.addEvent(window,'scroll',function(e){ window.refToModMessage.__repositionTransparentDiv() });
        this.addEvent(window,'resize',function(e){ window.refToModMessage.__repositionTransparentDiv() });


    }
    // }}}
    ,
    // {{{ __getBrowserSize()
    /**
    *	Get browser size
    *
    *
    * @private
    */
    __getBrowserSize : function()
    {
        var bodyWidth = document.documentElement.clientWidth;
        var bodyHeight = document.documentElement.clientHeight;

        var bodyWidth, bodyHeight;
        if (self.innerHeight){ // all except Explorer

            bodyWidth = self.innerWidth;
            bodyHeight = self.innerHeight;
        }  else if (document.documentElement && document.documentElement.clientHeight) {
            // Explorer 6 Strict Mode
            bodyWidth = document.documentElement.clientWidth;
            bodyHeight = document.documentElement.clientHeight;
        } else if (document.body) {// other Explorers
            bodyWidth = document.body.clientWidth;
            bodyHeight = document.body.clientHeight;
        }
        return [bodyWidth,bodyHeight];

    }
    // }}}
    ,
    // {{{ __resizeDivs()
    /**
    *	Resize the message divs
    *
    *
    * @private
    */
    __resizeDivs : function()
    {

        var topOffset = Math.max(document.body.scrollTop,document.documentElement.scrollTop);

        if(this.cssClassOfMessageBox)
        this.divs_content.className=this.cssClassOfMessageBox;
        else
        this.divs_content.className='modalDialog_contentDiv';

        if(!this.divs_transparentDiv)return;

        // Preserve scroll position
        var st = Math.max(document.body.scrollTop,document.documentElement.scrollTop);
        var sl = Math.max(document.body.scrollLeft,document.documentElement.scrollLeft);

        window.scrollTo(sl,st);
        setTimeout('window.scrollTo(' + sl + ',' + st + ');',10);

        this.__repositionTransparentDiv();


        var brSize = this.__getBrowserSize();
        var bodyWidth = brSize[0];
        var bodyHeight = brSize[1];

        // Setting width and height of content div
        this.divs_content.style.width = this.width + 'px';
        this.divs_content.style.height= this.height + 'px';

        // Creating temporary width variables since the actual width of the content div could be larger than this.width and this.height(i.e. padding and border)
        var tmpWidth = this.divs_content.offsetWidth;
        var tmpHeight = this.divs_content.offsetHeight;


        // Setting width and height of left transparent div






        this.divs_content.style.left = Math.ceil((bodyWidth - tmpWidth) / 2) + 'px';;
        this.divs_content.style.top = (Math.ceil((bodyHeight - tmpHeight) / 2) +  topOffset) + 'px';

        if(this.MSIE){
            this.iframe.style.left = this.divs_content.style.left;
            this.iframe.style.top = this.divs_content.style.top;
            this.iframe.style.width = this.divs_content.style.width;
            this.iframe.style.height = this.divs_content.style.height;
        }

        this.divs_shadow.style.left = (this.divs_content.style.left.replace('px','')/1 + this.shadowOffset) + 'px';
        this.divs_shadow.style.top = (this.divs_content.style.top.replace('px','')/1 + this.shadowOffset) + 'px';
        this.divs_shadow.style.height = tmpHeight + 'px';
        this.divs_shadow.style.width = tmpWidth + 'px';



        if(!this.shadowDivVisible)this.divs_shadow.style.display='none';	// Hiding shadow if it has been disabled


    }
    // }}}
    ,
    // {{{ __insertContent()
    /**
    *	Insert content into the content div
    *
    *
    * @private
    */
    __repositionTransparentDiv : function()
    {
        this.divs_transparentDiv.style.top = Math.max(document.body.scrollTop,document.documentElement.scrollTop) + 'px';
        this.divs_transparentDiv.style.left = Math.max(document.body.scrollLeft,document.documentElement.scrollLeft) + 'px';
        var brSize = this.__getBrowserSize();
        var bodyWidth = brSize[0];
        var bodyHeight = brSize[1];
        this.divs_transparentDiv.style.width = bodyWidth + 'px';
        this.divs_transparentDiv.style.height = bodyHeight + 'px';

    }
    // }}}
    ,
    // {{{ __insertContent()
    /**
    *	Insert content into the content div
    *
    *
    * @private
    */
    __insertContent : function()
    {
        if(this.url){	// url specified - load content dynamically
            ajax_loadContent('DHTMLSuite_modalBox_contentDiv',this.url);
        }else{	// no url set, put static content inside the message box
            this.divs_content.innerHTML = this.htmlOfModalMessage;
        }
    }
}

/* Simple AJAX Code-Kit (SACK) v1.6.1 */
/* ©2005 Gregory Wild-Smith */
/* www.twilightuniverse.com */
/* Software licenced under a modified X11 licence,
see documentation or authors website for more details */

function sack(file) {
    this.xmlhttp = null;

    this.resetData = function() {
        this.method = "POST";
        this.queryStringSeparator = "?";
        this.argumentSeparator = "&";
        this.URLString = "";
        this.encodeURIString = true;
        this.execute = false;
        this.element = null;
        this.elementObj = null;
        this.requestFile = file;
        this.vars = new Object();
        this.responseStatus = new Array(2);
    };

    this.resetFunctions = function() {
        this.onLoading = function() { };
        this.onLoaded = function() { };
        this.onInteractive = function() { };
        this.onCompletion = function() { };
        this.onError = function() { };
        this.onFail = function() { };
    };

    this.reset = function() {
        this.resetFunctions();
        this.resetData();
    };

    this.createAJAX = function() {
        try {
            this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e1) {
            try {
                this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e2) {
                this.xmlhttp = null;
            }
        }

        if (! this.xmlhttp) {
            if (typeof XMLHttpRequest != "undefined") {
                this.xmlhttp = new XMLHttpRequest();
            } else {
                this.failed = true;
            }
        }
    };

    this.setVar = function(name, value){
        this.vars[name] = Array(value, false);
    };

    this.encVar = function(name, value, returnvars) {
        if (true == returnvars) {
            return Array(encodeURIComponent(name), encodeURIComponent(value));
        } else {
            this.vars[encodeURIComponent(name)] = Array(encodeURIComponent(value), true);
        }
    }

    this.processURLString = function(string, encode) {
        encoded = encodeURIComponent(this.argumentSeparator);
        regexp = new RegExp(this.argumentSeparator + "|" + encoded);
        varArray = string.split(regexp);
        for (i = 0; i < varArray.length; i++){
            urlVars = varArray[i].split("=");
            if (true == encode){
                this.encVar(urlVars[0], urlVars[1]);
            } else {
                this.setVar(urlVars[0], urlVars[1]);
            }
        }
    }

    this.createURLString = function(urlstring) {
        if (this.encodeURIString && this.URLString.length) {
            this.processURLString(this.URLString, true);
        }

        if (urlstring) {
            if (this.URLString.length) {
                this.URLString += this.argumentSeparator + urlstring;
            } else {
                this.URLString = urlstring;
            }
        }

        // prevents caching of URLString
        this.setVar("rndval", new Date().getTime());

        urlstringtemp = new Array();
        for (key in this.vars) {
            if (false == this.vars[key][1] && true == this.encodeURIString) {
                encoded = this.encVar(key, this.vars[key][0], true);
                delete this.vars[key];
                this.vars[encoded[0]] = Array(encoded[1], true);
                key = encoded[0];
            }

            urlstringtemp[urlstringtemp.length] = key + "=" + this.vars[key][0];
        }
        if (urlstring){
            this.URLString += this.argumentSeparator + urlstringtemp.join(this.argumentSeparator);
        } else {
            this.URLString += urlstringtemp.join(this.argumentSeparator);
        }
    }

    this.runResponse = function() {
        eval(this.response);
    }

    this.runAJAX = function(urlstring) {
        if (this.failed) {
            this.onFail();
        } else {
            this.createURLString(urlstring);
            if (this.element) {
                this.elementObj = document.getElementById(this.element);
            }
            if (this.xmlhttp) {
                var self = this;
                if (this.method == "GET") {
                    totalurlstring = this.requestFile + this.queryStringSeparator + this.URLString;
                    this.xmlhttp.open(this.method, totalurlstring, true);
                } else {
                    this.xmlhttp.open(this.method, this.requestFile, true);
                    try {
                        this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
                    } catch (e) { }
                }

                this.xmlhttp.onreadystatechange = function() {
                    switch (self.xmlhttp.readyState) {
                        case 1:
                        self.onLoading();
                        break;
                        case 2:
                        self.onLoaded();
                        break;
                        case 3:
                        self.onInteractive();
                        break;
                        case 4:
                        self.response = self.xmlhttp.responseText;
                        self.responseXML = self.xmlhttp.responseXML;
                        self.responseStatus[0] = self.xmlhttp.status;
                        self.responseStatus[1] = self.xmlhttp.statusText;

                        if (self.execute) {
                            self.runResponse();
                        }

                        if (self.elementObj) {
                            elemNodeName = self.elementObj.nodeName;
                            elemNodeName.toLowerCase();
                            if (elemNodeName == "input"
                            || elemNodeName == "select"
                            || elemNodeName == "option"
                            || elemNodeName == "textarea") {
                                self.elementObj.value = self.response;
                            } else {
                                self.elementObj.innerHTML = self.response;
                            }
                        }
                        if (self.responseStatus[0] == "200") {
                            self.onCompletion();
                        } else {
                            self.onError();
                        }

                        self.URLString = "";
                        break;
                    }
                };

                this.xmlhttp.send(this.URLString);
            }
        }
    };

    this.reset();
    this.createAJAX();
}


/************************************************************************************************************
Ajax dynamic content
Copyright (C) 2006  DTHMLGoodies.com, Alf Magne Kalleland

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

Dhtmlgoodies.com., hereby disclaims all copyright interest in this script
written by Alf Magne Kalleland.

Alf Magne Kalleland, 2006
Owner of DHTMLgoodies.com


************************************************************************************************************/

var enableCache = true;
var jsCache = new Array();

var dynamicContent_ajaxObjects = new Array();

function ajax_showContent(divId,ajaxIndex,url)
{
    var targetObj = document.getElementById(divId);
    targetObj.innerHTML = dynamicContent_ajaxObjects[ajaxIndex].response;
    if(enableCache){
        jsCache[url] = 	dynamicContent_ajaxObjects[ajaxIndex].response;
    }
    dynamicContent_ajaxObjects[ajaxIndex] = false;

    ajax_parseJs(targetObj)
}

function ajax_loadContent(divId,url)
{
    if(enableCache && jsCache[url]){
        document.getElementById(divId).innerHTML = jsCache[url];
        return;
    }

    var ajaxIndex = dynamicContent_ajaxObjects.length;
    document.getElementById(divId).innerHTML = '<img src="/images/progress.gif" alt="" border="0">';
    dynamicContent_ajaxObjects[ajaxIndex] = new sack();
    dynamicContent_ajaxObjects[ajaxIndex].requestFile = url;	// Specifying which file to get
    dynamicContent_ajaxObjects[ajaxIndex].onCompletion = function(){ ajax_showContent(divId,ajaxIndex,url); };	// Specify function that will be executed after file has been found
    dynamicContent_ajaxObjects[ajaxIndex].runAJAX();		// Execute AJAX function


}

function ajax_parseJs(obj)
{
    var scriptTags = obj.getElementsByTagName('SCRIPT');
    var string = '';
    var jsCode = '';
    for(var no=0;no<scriptTags.length;no++){
        if(scriptTags[no].src){
            var head = document.getElementsByTagName("head")[0];
            var scriptObj = document.createElement("script");

            scriptObj.setAttribute("type", "text/javascript");
            scriptObj.setAttribute("src", scriptTags[no].src);
        }else{
            if(navigator.userAgent.indexOf('Opera')>=0){
                jsCode = jsCode + scriptTags[no].text + '\n';
            }
            else
            jsCode = jsCode + scriptTags[no].innerHTML;
        }

    }

    if(jsCode)ajax_installScript(jsCode);
}


function ajax_installScript(script)
{
    if (!script)
    return;
    if (window.execScript){
        window.execScript(script)
    }else if(window.jQuery && jQuery.browser.safari){ // safari detection in jQuery
        window.setTimeout(script,0);
    }else{
        window.setTimeout( script, 0 );
    }
}

/* modal message end */

messageObj = new DHTML_modalMessage();	// We only create one object of this class
messageObj.setShadowOffset(5);	// Large shadow

function displayMessage(url) {
    messageObj.setSource(url);
    messageObj.setCssClassMessageBox(false);

    if (messageObj.width == '400' && messageObj.height == '100%') {
        messageObj.setSize(600,450);
    }

    messageObj.setShadowDivVisible(true);	// Enable shadow for these boxes
    messageObj.display();
}

function closeMessage() {
    messageObj.close();
}

IndexPage = {};
IndexPage.tabs = new Array();
IndexPage.tabs['bloggersBlock']    = new Array('popular-bloggers', 'last-bloggers');
IndexPage.tabs['communitiesBlock'] = new Array('last-community', 'popular-community');
IndexPage.tabs['fotosBlock']       = new Array('last-albums', 'pop-albums');
IndexPage.tabs['topPosts']         = new Array('most-recomended-post', 'most-commented-post', 'most-viewed-post');
IndexPage.tabs['videoBlock']       = new Array('last-video', 'pop-video');
IndexPage.tabs['tagsBlock']        = new Array('list-interest', 'list-tags');
IndexPage.tabs['lastPosts']        = new Array('last-post', 'friends-post', 'offtopic-post');

IndexPage.showTab = function(ul, li, showTab) {
    var ul = document.getElementById(ul);

    $('#'+ul.id+' > li').removeClass('current');
    $('#'+ul.id+' > li a').removeClass('active');

    $('#li-'+showTab+' > a').addClass('active');
    $('#li-'+showTab).addClass('current');


    for (var i in IndexPage.tabs[ul.id]) {
        $('#'+IndexPage.tabs[ul.id][i]).hide();

        if (IndexPage.tabs[ul.id][i] == showTab) {
            $('#'+showTab).show();
        }
    }

    if ($("#"+ul.id+'Link')) {
        var href = $('#li-'+showTab+' > a').attr('href');
        $('#'+ul.id+'Link').attr('href', href);
    }

    return false;
}


IndexPage.showGenderPopup = function() {

    var time = new Date();
    var show = 1;
    var cookieDate = readCookie('genderPopup');



    if (cookieDate && cookieDate != time.toDateString()) {
        show = 0;
    }

    if (show == 1) {
        var content = "<h1>"+genderMsg_2+"</h1>";
        content += "<p><label><input type=\"radio\" name=\"gender\" id=\"sex_1\" value=\"m\" onclick='return IndexPage.saveGender(this);' />"+genderMsg_3+"</label>";
        content += "<label><input type=\"radio\" name=\"gender\" id=\"sex_2\" value=\"f\" onclick='return IndexPage.saveGender(this);' />"+genderMsg_4+"</label></p>";
        content += '<p><a href="javascript:void(0);" onclick=\"return IndexPage.hideGenderPopup();\" style="color:Gray;">'+genderMsg_1+'</a></p>';

        messageObj.setHtmlContent(content);
        messageObj.setSize(300,100);
        messageObj.setShadowDivVisible(true);
        messageObj.display();
    }

}

IndexPage.saveGender = function(dom) {

    var gotError = function(err) {
        return;
    }

    var gotInfo = function(data) {
        if (data.error == 1) {
            IndexPage.hideGenderPopup();
        }
        if( data.error == 0 ) {
            IndexPage.hideGenderPopup();
        }
        return;
    }

    poststr = "&key=gender&value="+dom.value+"&perm=0";
    var url = '/profile/_save_profile.html';

    $.ajax({
        type: "POST",
        url: url,
        data: poststr,
        dataType: "json",
        success: gotInfo,
        error: gotError
    });
}

IndexPage.hideGenderPopup = function() {
    var time = new Date();
    var day = 30 + (30 - time.getUTCDate());
    time.setDate(day);

    createCookie('genderPopup', time.toDateString(), 40);
    messageObj.close();

    return false;
}


Post = {};

Post.deleteImage = function(dom, number, id) {

    var gotError = function(err) {
        return;
    }

    var gotInfo = function(data) {
        if (data.success == 1) {
            $("#post-img-"+number).hide();
            $("#post-comm-"+number).hide();
        }
        if( data.success == 0 ) {
            alert('Ooops');
        }
        return;
    }

    $.ajax({
        type: "POST",
        url: HIVAR.currentJournalBase+'delete_image/?id='+id+'&ajax=1',
        data: {},
        dataType: "json",
        success: gotInfo,
        error: gotError
    });

    return false;
}

Settings = {};
Settings.addMenuField = function(button) {

    var tr, td;

    var tableRef = document.getElementById('table-menu-settings');
    var tbody = document.getElementById('table-body-menu-settings');

    var menu_fields = tbody.rows.length - 1;

    if (menu_fields == 10) {
        return false;
    }

    tr = tbody.insertRow(tbody.rows.length);
    var i = tbody.rows.length - 1;
    td = tr.insertCell(tr.cells.length);
    td.align = 'center';
    td.innerHTML = '<input type="text" name="menu[ui][sorter][]" size="2" value="'+i+'" />';

    td = tr.insertCell(tr.cells.length);
    td.innerHTML = '<label class="text">'+msg_title+' <input type="text" size="50" name="menu[ui][name][]" maxlength="150" class="text" value="" /></label> <label class="text">'+msg_url+' <input type="text" size="50" name="menu[ui][url][]" maxlength="255" class="text" value="" /></label>';

    td = tr.insertCell(tr.cells.length);
    td.align = 'center';
    td.innerHTML = '<input type="checkbox" name="menu[ui][is_active][]" checked="checked" value="1" />';

    if (i == 10) {
        $(button).hide();
    }

    return false;
}

DatingPage = {};
DatingPage.tabs = new Array();
DatingPage.photos = new Array();
DatingPage.currentPhoto = 1;
DatingPage.tabs['datingInfo'] = new Array('for-boys', 'for-girls');

DatingPage.next = function(currnet) {

    var PhotosQty = DatingPage.photos.length;
    if (typeof(current) != 'undefined') DatingPage.currentPhoto  = current;

    DatingPage.currentPhoto += 1;

    if (DatingPage.currentPhoto > PhotosQty) DatingPage.currentPhoto = PhotosQty;

    $("#photo_body").html('<img src="'+DatingPage.photos[DatingPage.currentPhoto-1]+'" alt="" class="d_photo" />');
    $("#current_photo_number").html(DatingPage.currentPhoto);
}

DatingPage.prev = function(currnet) {

    var PhotosQty = DatingPage.photos.length;
    if (typeof(current) != 'undefined') DatingPage.currentPhoto  = current;

    DatingPage.currentPhoto -= 1;

    if (DatingPage.currentPhoto < 1) DatingPage.currentPhoto = 1;

    $("#photo_body").html('<img src="'+DatingPage.photos[DatingPage.currentPhoto-1]+'" alt="" class="d_photo" />');
    $("#current_photo_number").html(DatingPage.currentPhoto);
}

DatingPage.showTab = function(ul, li, showTab) {
    var ul = document.getElementById(ul);

    $('#'+ul.id+' > li').removeClass('current');
    $('#'+ul.id+' > li span').removeClass('active');

    $('#li-'+showTab+' > span').addClass('active');
    $('#li-'+showTab).addClass('current');


    for (var i in DatingPage.tabs[ul.id]) {
        $('#'+DatingPage.tabs[ul.id][i]).hide();

        if (DatingPage.tabs[ul.id][i] == showTab) {
            $('#'+showTab).show();
        }
    }

    return false;
}


DatingPage.validate = function(err_msg) {
    var Return = true;

    if ($('#gender_f').attr('checked') != true && $('#gender_m').attr('checked') != true) {
        Return = false;
    }

    if (document.getElementById('year').value == '') {
        Return = false;
    }

    if (document.getElementById('city').value == '0') {
        Return = false;
    }

    if ($('#name').val() == '') {
        Return = false;
    }

    if ($('#file_1').val() == '' && $('#file_2').val() == '') {
        Return = false;
    }

    if (!Return) alert(err_msg);

    return Return;
}


function subscribeToBlog() {

    var gotError = function(err) {
        document.getElementById('id_error_subscr_msg').innerHTML = data.error_msg;
        return;
    }
    var gotInfo = function(data) {
        if ( data.success == 1 ) {
            document.getElementById('id_subscribe_field').innerHTML = data.content;
            document.getElementById('id_error_subscr_msg').innerHTML = "";
        }
        if( data.success == 0 ) {
            document.getElementById('id_error_subscr_msg').innerHTML = data.error_msg;
            if( data.error_code == '1062' ) {
                document.getElementById('id_subcrs_submit').value = data.add_msg+'?';
                document.getElementById('id_action_type').value = 0;
                document.getElementById('id_error_subscr_msg').innerHTML = data.error_msg;
            }
        }
        return;
    }

    var action_type = '';
    var subscribe_blog = '';
    var subscriber_contact = '';
    var subscribe_url = '';
    if(document.getElementById('id_subscribe_blog')) subscribe_blog = document.getElementById('id_subscribe_blog').value;
    if(document.getElementById('id_subscriber_contact')) subscriber_contact = document.getElementById('id_subscriber_contact').value;
    if(document.getElementById('id_subscribe_url')) subscribe_url = document.getElementById('id_subscribe_url').value;
    if(document.getElementById('id_action_type')) action_type = document.getElementById('id_action_type').value;

    poststr = "blog=" + subscribe_blog + "&contact=" + subscriber_contact+'&action='+action_type;

    $.ajax({
        type: "POST",
        url: subscribe_url,
        data: poststr,
        dataType: "json",
        success: gotInfo,
        error: gotError
    });

    return false;
}

var datingFileCount = 2;
function datingBind(domElement) {
    if(datingFileCount < 5){
        $("#more_photos").append('<div><input type="file" name="photo[]" value="" class="file"/></div>');
        datingFileCount++;
    }
    if (datingFileCount == 5) $(domElement).hide();
}

/* Cookie Control */

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}


function unBanPost(dom) {

    if (confirm(msg_adm_activate_post)) {

        var callBackError = function( data ) {
            alert('error');
            return false;
        }

        var callBack = function(data) {
            if(data.success) {
                dom.href = data.url;
                $(dom).html(msg_hooray);
                $(dom).fadeOut("slow");
            }
            return false;
        }

        $.ajax({
            type: "POST",
            url: dom.href,
            data: {ajax:1, type:'unban'},
            dataType: "json",
            success: callBack,
            error: callBackError
        });

    }

    return false;
}


function unDeletePost(dom) {

    if (confirm(msg_undelete_post)) {

        var callBackError = function( data ) {
            alert('error');
            return false;
        }

        var callBack = function(data) {
            if(data.success) {
                dom.href = data.url;
                $(dom).html(msg_hooray);
                $(dom).fadeOut("slow");
            }
            return false;
        }

        $.ajax({
            type: "POST",
            url: dom.href,
            data: {ajax:1, type:'undelete'},
            dataType: "json",
            success: callBack,
            error: callBackError
        });

    }

    return false;
}


function unBanBlogger(dom) {

    if (confirm(msg_cancel_ban)) {
        var callBackError = function( data ) {
            alert('error');
            return false;
        }

        var callBack = function(data) {
            if(data.success) {
                $(dom).html(msg_hooray);
                $(dom).fadeOut("slow");
            }
            return false;
        }

        $.ajax({
            type: "POST",
            url: dom.href,
            data: {ajax:1, type:'unban'},
            dataType: "json",
            success: callBack,
            error: callBackError
        });
    }

    return false;

}

/* pollings control */
function activate( id ) {

    var gotError = function(err) {
        alert(msg_error);
        return;
    }

    var gotInfo = function(data) {
        if( data.error == 0 && data.succes ==1 ) {
            var cntn = '<span id="poll_ad_'+id+'"><a href="#" onclick="deActivate(\''+id+'\');return!1;" title="'+msg_polling_deactivate+'"><img src="/images/icons/control_stop.png" alt="'+msg_polling_deactivate+'" /></a></span>';
            $('#poll_ad_'+id).html(cntn);
        }
        return;
    }


    var url = "/pollings/is_in_side_block";
    var poststr = "id="+id+"&action=1";

    $.ajax({
        type: "POST",
        url: url,
        data: poststr,
        dataType: "json",
        success: gotInfo,
        error: gotError
    });
}

function deActivate( id ) {

    var gotError = function(err) {
        alert(msg_error);
        return;
    }

    var gotInfo = function(data) {
        if( data.error == 0 && data.succes ==1 ) {
            var cntn = '<span id="poll_ad_'+id+'"><a href="#" onclick="activate(\''+id+'\');return!1;" title="'+msg_polling_activate+'"><img src="/images/icons/control_play.png" alt="'+msg_polling_activate+'" /></a></span>';
            $('#poll_ad_'+id).html(cntn);
        }
        return;
    }

    var url = "/pollings/is_in_side_block";
    var poststr = "id="+id+"&action=0";

    $.ajax({
        type: "POST",
        url: url,
        data: poststr,
        dataType: "json",
        success: gotInfo,
        error: gotError
    });
}
/* pollings control */

/* add post */

// DRAFT
var FCKeditor_LOADED = false;
var Draft = {};

Draft.saveInProg = false;
Draft.epoch      = 0;
Draft.lastSavedBody = "";
Draft.prevCheckBody = "";
Draft.lastTypeTime  = 0;
Draft.lastSaveTime  = 0;
Draft.autoSaveInterval = 5;
Draft.savedMsg = "Autosaved at [[time]]";

Draft.save = function (drafttext, draftheader, cb) {

    var callback = cb;  // old safari closure bug
    if (Draft.saveInProg)
    return;

    Draft.saveInProg = true;

    var finished = function () {
        Draft.saveInProg = false;
        if (callback) callback();
    };

    $.ajax({
        type: "POST",
        url: "/my_blog/save_draft/",
        data: {"content": drafttext, "header": draftheader, "ajax":1},
        dataType: "json",
        success: finished
    });
};

Draft.resumeDraft = function() {
    if (confirm(msg_get_draft)) {
        $("#header").val(draftHeader);

        var oEditor = CKEDITOR.instances.content;

        if (typeof(CKEDITOR) == 'undefined' || !oEditor) {
            $("#content").val(draftContent);
        } else {
            if (oEditor) {
                alert(CKEDITOR.instances.content.focusManager.hasFocus);
                oEditor.setData(draftContent);
                oEditor.focusManager.focus();
            }
        }
    }
}

Draft.startTimer = function () {
    setInterval(Draft.checkIfDirty, 1000);  // check every second
    Draft.epoch = 0;
};

Draft.checkIfDirty = function () {

    Draft.epoch++;
    var curBody;
    var curHeader = $("#header").val();

    if (!document.getElementById("content")) return false;

    if (document.getElementById("content").style.display == 'none') {

        // Need to check this to deal with hitting the back button
        // Since they may start using the RTE in the middle of writing their
        // entry, we should just get the editor each time.

        if (!FCKeditor_LOADED) return;
        if (!CKEDITOR) return;
        var oEditor = CKEDITOR.instances.content;
        if (oEditor.getData()) {
            curBody = oEditor.getData();
        }
    } else {
        curBody = $("#content").val();
    }
    if (curBody == '<p></p>' || curBody == '') return false;
    // no changes to save
    if (curBody == Draft.lastSavedBody)
    return;

    // at this point, things are dirty.

    // see if they've typed in the last second.  if so,
    // we'll want to note their last type time, and defer
    // saving until they settle down, unless they've been
    // typing up a storm and pass our 15 second barrier.
    if (curBody != Draft.prevCheckBody) {
        Draft.lastTypeTime  = Draft.epoch;
        Draft.prevCheckBody = curBody;
    }

    if (Draft.lastSaveTime < Draft.lastTypeTime - 15) {
        // let's fall through and save!  they've been busy.
    } else if (Draft.lastTypeTime > Draft.epoch - 3) {
        // they're recently typing, don't save.  let them finish.
        return;
    } else if (Draft.lastSaveTime > Draft.epoch - Draft.autoSaveInterval) {
        // we've saved recently enough.
        return;
    }

    // async save, and pass in our callback
    var curEpoch = Draft.epoch;
    Draft.save(curBody, curHeader, function () {
        var date = new Date();
        $("#draft_alert").html('<img src="/images/inform.gif" align="top" id="draft_notice_icon" class="tooltip_title" title="'+msg_draft_dsr+'" /> '+msg_save_draft+' '+date.toLocaleTimeString());
        Draft.lastSaveTime  = curEpoch; /* capture lexical.  remember: async! */
        Draft.lastSavedBody = curBody;

        $('#draft_notice_icon').bt({
            fill: '#F7F7F7',
            strokeStyle: '#B7B7B7',
            spikeLength: 10,
            spikeGirth: 10,
            padding: 8,
            cornerRadius: 0,
            positions: ['right', 'bottom'],
            cssStyles: {
                fontFamily: 'tahoma,verdana,arial,sans-serif',
                fontSize: '11px'
            }
        });

    });
};

/* add post */


/* scaleImg */
function scaleImg( i, x, y ) {
    messageObj.setHtmlContent("<img src="+i+" onclick=\"closeMessage();\" style=\"cursor:pointer;border:0;\" />");
    messageObj.setSize(x, y);
    messageObj.display();
}
/* scaleImg */

/*  editor fucntions */
$.fn.insertAtCaret = function (myValue) {
    return this.each(function(){
        //IE support
        if (document.selection) {
            this.focus();
            sel = document.selection.createRange();
            sel.text = myValue;
            this.focus();
        }
        //MOZILLA/NETSCAPE support
        else if (this.selectionStart || this.selectionStart == '0') {
            var startPos = this.selectionStart;
            var endPos = this.selectionEnd;
            var scrollTop = this.scrollTop;
            this.value = this.value.substring(0, startPos)
            + myValue
            + this.value.substring(endPos,
            this.value.length);
            this.focus();
            this.selectionStart = startPos + myValue.length;
            this.selectionEnd = startPos + myValue.length;
            this.scrollTop = scrollTop;
        } else {
            this.value += myValue;
            this.focus();
        }
    });

};

ToggleEditors = {};

ToggleEditors.eWidth = '100%';
ToggleEditors.eHeight = 400;
ToggleEditors.switched_rte_on = 0;
ToggleEditors.textArea = 'content';
ToggleEditors.oEditor = null;
ToggleEditors.Toolbar = 'Default';

ToggleEditors.init = function(textArea, w,h, defaultRte, toolbar) {

    ToggleEditors.textArea = textArea;

    if (w) ToggleEditors.eWidth = w;
    if (h) ToggleEditors.eHeight = h;
    if (toolbar) ToggleEditors.Toolbar = toolbar;

    if (!defaultRte) {
        ToggleEditors.usePlainText(textArea);
    } else {
        ToggleEditors.useRichText(textArea);
    }
}

ToggleEditors.useRichText = function(textArea) {

    if ( ToggleEditors.switched_rte_on == '1' ) return;


    var entry_html = $("#"+textArea).val();

    ToggleEditors.oEditor = CKEDITOR.replace(textArea, {width: ToggleEditors.eWidth, height: ToggleEditors.eHeight, toolbar: ToggleEditors.Toolbar});
    CKEDITOR.on('instanceReady', function(ev)
    	{
    		ev.editor.dataProcessor.writer.setRules('p',
    			{
    				indent : false,
    				breakBeforeOpen : true,
    				breakAfterOpen : false,
    				breakBeforeClose : false,
    				breakAfterClose : true
    			});
    	});

	ToggleEditors.oEditor.setData(entry_html);

    if ($("#tab-html")) $("#tab-html").removeClass();
    if ($("#tab-rich-text")) $("#tab-rich-text").addClass('on');
    if ($("#tab-img")) $("#tab-img").hide();

    ToggleEditors.switched_rte_on = 1;

    return false;
}

ToggleEditors.usePlainText = function(textArea) {
    if ( ToggleEditors.switched_rte_on == 0 ) return;

    if (typeof(CKEDITOR) == 'undefined') return;
    if (!ToggleEditors.oEditor) return;

    var html = ToggleEditors.oEditor.getData();

    html = html.replace(/&nbsp;/g, ' ');

    $("#"+textArea).val(html);

    if ($("#tab-html")) $("#tab-html").addClass('on');
    if ($("#tab-rich-text")) $("#tab-rich-text").removeClass();
    if ($("#tab-img")) $("#tab-img").show();

    ToggleEditors.oEditor.destroy();

    ToggleEditors.switched_rte_on = 0;

    return false;
}

ToggleEditors.browseServer = function(textArea) {

    if(ToggleEditors.switched_rte_on != 0) ToggleEditors.usePlainText(textArea);

    txtArea = textArea;
    window.open('/filemanager.php','preview','width=700,height=500,resizable=yes,status=yes,toolbar=no,location=no,menubar=no,scrollbars=no');
    return false;
}

var txtArea;

function SetUrl( url, width, height, alt ) {
    var img = "<img src='"+url+"' alt='' />"
    document.getElementById(txtArea).value = document.getElementById(txtArea).value + img;
    document.getElementById(txtArea).focus();
}

function toggleSmiles() {
    $("#post-smiles").toggle();
}

function addSmile(what) {

    var smile = "<img src='"+what.src+"' alt='' border='0' />";

    if(ToggleEditors.switched_rte_on) {

        var oEditor = FCKeditorAPI.GetInstance(ToggleEditors.textArea);
        oEditor.InsertHtml(smile);

    } else {
        $("#"+ToggleEditors.textArea).insertAtCaret(smile);
    }
}

/*  editor fucntions */

/* add and edit post */
function chekAuth(type, element) {
    document.getElementById('auth_list').style.display = type;
    if (element.value == 'auth') {
        document.getElementById('acl-notice').style.display = 'block';
    } else {
        document.getElementById('acl-notice').style.display = 'none';
    }
}

function chekAuth2(type) {
    document.getElementById('auth_list2').style.display = type;
}

function clearValue(id) {
    document.getElementById( id ).value = '';
    return true;
}

function addField() {
    // Get a reference to the table
    var tr, td;

    var tableRef = document.getElementById('table_1');
    var tbody = document.getElementById('tbody_1');
    tr = tbody.insertRow(tbody.rows.length);
    var i = tbody.rows.length - 1;
    td = tr.insertCell(tr.cells.length);
    td.innerHTML = '<label for="_image_'+ i +'">' + text_1 + ' '+ i + '</label>';

    td = tr.insertCell(tr.cells.length);
    td.innerHTML = "<input name=\"image_"+i+"\" type=\"file\" class=\"forma\" id=\"_image_"+i+"\" />";

    var tbody = document.getElementById('tbody_2');
    tr = tbody.insertRow(tbody.rows.length);
    var i = tbody.rows.length - 1;
    td = tr.insertCell(tr.cells.length);
    td.style.textAlign = 'right';
    td.innerHTML = '<label for="_i_comm_'+ i +'">'+ text_2 + ' '+ i + '</label>';

    td = tr.insertCell(tr.cells.length);
    td.style.textAlign = 'left';
    td.innerHTML = "<input name=\"i_comm_"+i+"\" type=\"text\" class=\"forma\" id=\"_i_comm_"+i+"\" />";
}

function showDatePop(self) {
    if( self.gfPop )
    gfPop.fPopCalendar(document.entryform.cdatetime);

    document.entryform.cdatetime.focus();
}

function checkIfDateIsInFuture(what) {

    tr = document.getElementById('id_tr_post_in_future');

    var cDate = new Date();

    tmp_date = what.value;
    tmp_date = tmp_date.replace("-", ",", "gi");

    var input_date = document.getElementById('id_cdatetime');
    var uDate = new Date();

    uDate = Date.parse(input_date.value.replace("-", "/", "gi"));

    if(uDate > cDate.getTime()) {
        $("#id_tr_post_in_future").show();
    }

    var length = input_date.value.length;
    if( length <= 10) {
        var uDate = new Date();
        var h = uDate.getHours();
        var m = uDate.getMinutes();
        var s = uDate.getSeconds();
        if(uDate.getHours() < 10)   var h = '0'+uDate.getHours();
        if(uDate.getMinutes() < 10) var m = '0'+uDate.getMinutes();
        if(uDate.getSeconds() < 10) var s = '0'+uDate.getSeconds();
        input_date.value = input_date.value + ' ' + h + ':'+ m + ':'+ s;
    }
}

function entryPreview() {
    var f = document.getElementById('entryform');
    var action=f.action;
    f.action='/my_blog/preview.html';
    f.target='preview';
    window.open('','preview','width=900,height=600,resizable=yes,status=yes,toolbar=no,location=no,menubar=no,scrollbars=yes');
    f.submit();
    f.action=action;
    f.target='_self';

    return false;
}

/* add and edit post */
