/**
 * @author: Tremend Software Consulting
 */
Prototype.Browser.IE6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5))==6;
Prototype.Browser.IE7 = Prototype.Browser.IE && !Prototype.Browser.IE6;

/**
 * Upload manager with methods for starting the upload (start monitoring and submitting the form) and checking the upload progress
 */
var uploadMgr = {
    /**
     * Uploads the item specified with the position
     * @param pos           the identifier of the upload slot
     * @param callbackName  what to do when upload is done
     */
    startUpload: function(pos, callbackName, acceptedTypes) {
        var uploadFile = $("uploadFile" + pos);
        var uploadForm = $("uploadForm" + pos);
        if (!(objIsValid(uploadFile)
                && objIsValid(uploadForm)
                )) {
            this.uploadFailed(pos);
            return;
        }
        var name = uploadFile.value;
        var reImg = /(.)*.(jpg|jpeg|gif|png)/i;
        var re = reImg;
        if(typeof(acceptedTypes) != "undefined" && acceptedTypes != null) {
            re = acceptedTypes;
            if(!name.match(re)) {
                alert("Fisierul nu este de tip imagine sau video");
                this.uploadFailed(pos);
                return;
            }
            if(name.match(reImg)) {
                uploadForm.action = "/upload";
            } else {
                uploadForm.action = "/uploadVideo";
            }
        } else {
            if(!name.match(re)) {
                alert("Fisierul nu este de tip imagine");
                this.uploadFailed(pos);
                return;
            }
        }
        uploadMgr.startUploadMonitoring(pos, callbackName);
        uploadForm.submit();
    },

    /**
     * Called when upload finishes
     * @param pos the identifier of the upload slot
     */
    uploadFinished: function(pos) {
    },

    /**
     * Called when upload fails
     * @param pos the identifier of the upload slot
     */
    uploadFailed: function(pos) {
        var uploadButton = $("uploadButton" + pos);
        if (objIsValid(uploadButton)) {
            disableAnchor(uploadButton, false);
        }
    },

    /**
     * Called periodically to check the status of the upload
     * @param pos           the identifier of the upload slot
     * @param callbackName  what to do when upload finishes
     */
    checkStatus: function(pos, callbackName) {
        siteUploadProxy.getStatus(function(stat) {
            if (stat.status == 1) {
                uploadMgr.updateProgressBar(pos, stat.percentComplete);
                window.setTimeout("uploadMgr.checkStatus(" + pos + (objIsValid(callbackName) ? ",'" + callbackName + "'" : "") + ")", 500);
            } else if (stat.status == 2) {
                uploadMgr.updateProgressBar(pos, 100);
                if(objIsValid(callbackName)) {
                    eval(callbackName + "()");
                }
                uploadMgr.uploadFinished(pos);
            } else if (stat.status == 3) {
                alert("Eroare: " + stat.message);
                uploadMgr.uploadFailed(pos);
                if(objIsValid(callbackName)) {
                    eval(callbackName + "()");
                }
            } else if (stat.status == 4) {
                window.setTimeout("uploadMgr.checkStatus(" + pos + (objIsValid(callbackName) ? ",'" + callbackName + "'" : "") + ")", 500);
            }
        });
    },

    /**
     * Updates the progress bar (percentage monitoring)
     * @param pos           the identifier of the upload slot
     * @param percentage    the status
     */
    updateProgressBar: function(pos, percentage) {
        $("uploadProgress" + pos).innerHTML = percentage + "%";
    },

    /**
     * Starts checking the status of the upload. The method is called after half second to give the upload form the chance to submit itself.
     * Otherwise the checking will mess status indicators on the server.
     * @param pos           the identifier of the upload slot
     * @param callbackName  what to do when upload finishes
     */
    startUploadMonitoring: function(pos, callbackName) {
        window.setTimeout("uploadMgr.checkStatus(" + pos + (objIsValid(callbackName) ? ",'" + callbackName + "'" : "") + ")", 500);
        return true;
    }
};

// Font size increase/decrease
var minFontSize = 8;
var maxFontSize = 22;
var MIN_FONT_SIZE = 8;
var MAX_FONT_SIZE = 32;
var FONT_SIZE_STEP = 2;

/**
 * Sets a cookie
 */
function setCookie(/*String*/name, /*String*/value, /*Number?*/days, /*String?*/path, /*String?*/domain, /*boolean?*/secure) {
    var expires = -1;
    if ((typeof days == "number") && (days >= 0)) {
        var d = new Date();
        d.setTime(d.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = d.toGMTString();
    }
    //alert("expires " + expires);
    value = escape(value);
    var cookies = name + "=" + value + ";"
            + (expires != -1 ? " expires=" + expires + ";" : "")
            + (path ? "path=" + path : "")
            + (domain ? "; domain=" + domain : "")
            + (secure ? "; secure" : "");
    //alert("cookies: " + cookies);
    document.cookie = cookies;
    //alert("document.cookie: " + document.cookie);
};

/**
 * Retrieves the value for a cookie.
 * This fixes an issue with the old method that used
 * document.cookie.indexOf( name + "=" );
 */
var getCookie = function(/*String*/cookieName, /*String*/defaultValue) {
    // 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 (var 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 cookieName
        if (cookie_name == cookieName) {
            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;
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if (!b_cookie_found) {
        return defaultValue;
    }
}

/*
 * Delete a cookie
 */
var deleteCookie = function (name, path, domain) {
    document.cookie = name + "="
            + (path ? ";path=" + path : "")
            + (domain ? ";domain=" + domain : "" )
            + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function typeInInputField(field) {
    field.typedIn = true;
}

function showInputFieldTip(field) {
    if (!field.typedIn) {
        field.value = field.value_bak;
    }
}

function hideInputFieldTip(field) {
    if (!field.typedIn) {
        field.value_bak = field.value;
        field.value = '';
    }
}

function typeInPasswordField(field) {
    field.typedIn = true;
}

/**
 * Handles the login
 */
function doLogin2() {
//    $('master_sus_acegi_security_remember_me').value = $('master_sus_subpanel_acegi_security_remember_me').checked ? "on" : "";
    ajaxLogin('loginForm2', 'master_sus_subpanel_message', '<img src="/images/new/ajax_loading_anim_1.gif" height="16" alt=""/> Se conecteaza...',
            'master_sus_subpanel_message', 'master_sus_login', 'loginPanel', doLogin2Success);
};

/**
 * Performs the login via AJAX
 */
function ajaxLogin(loginForm, waitingMessageContainer, waitingMessage,
                   loginMessageContainer, replaceLoginContainer,
                   loginPanel, loginSuccessFunction) {
    loginForm = $(loginForm);
    /*var acegiRememberMe = $('master_sus_subpanel_acegi_security_remember_me');
    if (objIsValid(acegiRememberMe)) {
        acegiRememberMe.hide();
        insertBefore(acegiRememberMe, loginForm.firstChild);
    } */
    Element.update(waitingMessageContainer, waitingMessage);
    Element.show(waitingMessageContainer);
    new Ajax.Request('/web_login_check', {
        method: 'post',
        postBody: Form.serialize(loginForm) + '&ajax=true',
        onSuccess: loginSuccessFunction
    });
}

function doLogin2Success(response) {
    doLoginSuccess(response, 'master_sus_subpanel_message',
            'master_sus_subpanel_message', 'login2', 'login');
}

function doLoginSuccess(response, waitingMessageContainer,
                   loginMessageContainer, replaceLoginContainer, loginPanel) {
    Element.hide(waitingMessageContainer);
    var msg = response.responseText;
    if (msg.startsWith("error:")) {
        Element.update(loginMessageContainer, '<font color="red" align="center">Login invalid</font>');
        Element.show(loginMessageContainer);
    } else if (msg.startsWith("url:")) {
        location.href = msg.substring("url:".length);
    } else if (msg.startsWith("success:")) {
        var nickname = msg.substring("success:".length);
        if ($(replaceLoginContainer)) {
            Element.update(replaceLoginContainer,
                '<div class="salut">Salut ' + nickname.escapeHTML() + '!</div>' +
                '<div class="myAccount"><a href="/mywebpr/detalii">Contul meu</a></div>' +
                '<a class="logout_link" style="color:#454545;" href="javascript:doLogout(\'/logout?a=\'+(new Date()).getTime())">Log-out</a>');
            $(replaceLoginContainer).show();
        }
        if ($(loginPanel)) {
            Element.hide(loginPanel);
        }
//        window.location.href = '/myhotnews';
    }
}

/**
 * Logs out the current logged in user
 */
function doLogout(logoutUrl) {
//    window.location.href = logoutUrl;
    var opt = {
        method: 'post',
        postBody: 'ajax=true',
        onSuccess: function(response) {
            if ($('login') != null) {
                welcomeUsername = null;
                Element.update('login', '<form action="/web_login_check" method="post" id="loginForm2" style="">' +
					'<a href="javascript:doLogin2();">Log-in</a> |' +
					'<a href="/inregistrare">Cont nou</a>' +
                '<input type="text" id="j_username2" name="j_username" value="Email" style="width: 115px;" class="input"' +
                   'onkeydown="typeInInputField(this)"' +
                   'onclick="hideInputFieldTip(this);"' +
                   'onblur="showInputFieldTip(this)" />' +
                '<input type="text" id="j_password2" name="j_password" value="Parola" style="width:65px" class="input"' +
                   'onblur="showPasswordFieldTip(this, \'j_password2\', \'doLogin2\')"' +
                   'onfocus="hidePasswordFieldTip(this, \'j_password2\', \'doLogin2\');"/>' +
                    '<br class="clear"/>' +
                    '<div id="master_sus_subpanel_message" style="display:none;margin-top:1px;"></div>' +
                '</form>');
                $('login2').hide();
                $('login').show();
            }
        }
    }
    new Ajax.Request(logoutUrl, opt);
};


function showPasswordFieldTip(field, id, loginFunctionName) {
    if (field.type != 'text') {
        var clone = document.createElement('input');
        clone.type = 'text';
        clone.id = id;
        clone.name = "j_password";
        clone.className = "input";
        clone.style.width = "65px";
        clone.value = field.value_bak;
        field.parentNode.replaceChild(clone, field);
        window.setTimeout("$('" + id + "').focus();"
                + "Event.observe($('" + id + "'), 'focus', "
                + "function(e){hidePasswordFieldTip(this, '" + id + "'"
                + (objIsValid(loginFunctionName) ? ",'" + loginFunctionName + "'" : "")
                + ")});",
                10);
    }
}

function hidePasswordFieldTip(field, id, loginFunctionName) {
    if (field.type != 'password') {
        var clone = document.createElement('input');
        clone.type = 'password';
        clone.id = id;
        clone.name = "j_password";
        clone.className = "input";
        clone.style.width = "65px";
        clone.value_bak = field.value;
        field.parentNode.replaceChild(clone, field);
        clone.focus();
/*
        window.setTimeout("$('" + id + "').focus();"
                + "Event.observe($('" + id + "'), 'blur', "
                + "function(e){showPasswordFieldTip(this, '" + id + "'"
                + (objIsValid(loginFunctionName) ? ",'" + loginFunctionName + "'" : "")
                + ")});",
                10);
*/
        if (objIsValid(loginFunctionName)) {
            window.setTimeout("$('" + id + "').focus();"
                    + "Event.observe($('" + id + "'), 'keypress', "
                    + "function(e){if(e.keyCode==Event.KEY_RETURN){" + loginFunctionName + "();}});",
                    10);
        }
    }
}

function isValidEmail(strEmail) {
    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    return filter.test(strEmail);
}

/**
 * Validates quick search box
 */
function checkSearch() {
    var name = "_quickSearchString";
    if ($(name).value.strip().length < 3 || !$(name).typedIn) {
        alert('Pentru a efectua cautarea, introduceti un cuvant cu cel putin trei litere');
        return false;
    }
    return true;
};

/**
 * Validates the quick search box and redirects to the search page
 */
function doSearch(siteUrl, searchPage, searchFieldName) {
    var searchString = $(searchFieldName).value.strip();
    if (searchString.length < 3 || !$(searchFieldName).typedIn) {
        alert('Pentru a efectua cautarea, introduceti un cuvant cu cel putin trei litere');
    } else {
        document.location.href = /*siteUrl +*/ "/" + searchPage + "/" + encodeURIComponent(searchString) + "/1";
    }
};

function doAdvancedSearch(siteUrl) {
    $('advancedSearchForm').submit();
}

/**
 * Opens up the print dialog page
 */
function printArticle(siteUrl, articleId) {
    window.open(siteUrl + "/print?articleId=" + articleId, "Printeaza", "height=800,width=800,resizable=yes,scrollbars=yes");
};

/**
 * Send article link via email
 */
function sendArticleLinkByMail(siteUrl, articleId, articleUrl) {
    var img = $("sendCount");
    if (img) {
        img.src = "";
        img.src = siteUrl + "/pageCount.htm?type=mail&articleId=" + articleId;
    }
    window.location.href = "mailto:?subject=Un articol interesant&body=" + articleUrl;
};

/**
 * Send article link via YM
 */
function sendArticleLinkByYM(siteUrl, articleId, articleUrl) {
    var img = $("sendCount");
    if (img) {
        img.src = "";
        img.src = siteUrl + "/pageCount.htm?type=ym&articleId=" + articleId;
    }
    window.location.href = "ymsgr:im?+&msg=" + articleUrl;
};

/**
 * Send link via email
 */
function sendLinkByMail(siteUrl, url) {
    var img = $("sendCount");
    if (img) {
        img.src = "";
        img.src = siteUrl + "/pageCount.htm?type=mail&url=" + url;
    }
    window.location.href = "mailto:?subject=O pagina interesanta&body=" + url;
};

/**
 * Send link via YM
 */
function sendLinkByYM(siteUrl, url) {
    var img = $("sendCount");
    if (img) {
        img.src = "";
        img.src = siteUrl + "/pageCount.htm?type=ym&url=" + url;
    }
    window.location.href = "ymsgr:im?+&msg=" + url;
};

/**
 * Decrease font size for article page
 */
function decreaseFontSize() {
    var articleContent = $("articleContent");
    if (articleContent) {
        var fontSize = articleContent.style.fontSize;
        var pos = fontSize.indexOf("px");
        if (pos > 0) {
            fontSize = fontSize.substr(0, pos);
            if (fontSize > MIN_FONT_SIZE) {
                fontSize = parseInt(fontSize) - parseInt(FONT_SIZE_STEP);
                articleContent.style.fontSize = fontSize + "px";
            }
        }
    }
}

/**
 * Increase font size for article page
 */
function increaseFontSize() {
    var articleContent = $("articleContent");
    if (articleContent) {
        var fontSize = articleContent.style.fontSize;
        var pos = fontSize.indexOf("px");
        if (pos > 0) {
            fontSize = fontSize.substr(0, pos);
            if (fontSize < MAX_FONT_SIZE) {
                fontSize = parseInt(fontSize) + parseInt(FONT_SIZE_STEP);
                articleContent.style.fontSize = fontSize + "px";
            }
        }
    }
}

/**
 * Inits comments container
 */
function initComments(addCommentFormContainer, elemComentariu, elemSizebox) {
    // aici initializam campul cu nr de caractere
    var comentariu = $(elemComentariu);
    if (comentariu) {
        updateSizebox(elemSizebox, comentariu.value.length);
    }
    // aici afisam un element din pagina, daca a fost cerut explicit in URL
    var url = window.location.href;
    var pos = url.indexOf("#") + 1;
    if (pos > 0 && pos < url.length) {
        var urlFragment = url.substr(pos);
        if (urlFragment == "adaugaComentariu") {
            var formContainer = $(addCommentFormContainer);
            if (formContainer) {
                formContainer.style.display = "block";
                formContainer.style.visibility = "visible";
            }
            window.location.href = "#" + urlFragment;
        } else {
            var comentariu_ = "comentariu_";
            var len = comentariu_.length;
            if (urlFragment.substr(0, len) == comentariu_) {
                var commentId = urlFragment.substr(len + 1);
                expandComment(commentId);
                window.location.href = "#" + urlFragment;
            }
        }
    }
}

/**
 * Trims the comment value
 */
function updateSizebox(elemSizebox, textarea, size) {
    if (size > 2000) {
        //alert("EROARE! Comentariul contine " + size + " caractere si depaseste dimensiunea maxima de 2000 de caractere!");
        textarea.value = textarea.value.substr(0, 2000);
        return;
    }
    var sizebox = $(elemSizebox);
    if (sizebox) {
        sizebox.value = size + ' caractere scrise';
    }
}

/**
 * Collapses a comment
 */
function collapseComment(commentId) {
    var comment = $("co_" + commentId);
    if (comment) {
        comment.className = "commentCollapsed";
        comment.isCollapsed = true;
    }
}

/**
 * Expands a comment
 */
function expandComment(commentId) {
    var comment = $("co_" + commentId);
    if (comment) {
        comment.className = "cEx";
        comment.isCollapsed = false;
    }
}

/**
 * Toggles a comment
 */
function tc(commentId) {
    var comment = $("co_" + commentId);
    if (comment) {
        if (comment.className == "cEx") {
            comment.className = "cCo";
            comment.isCollapsed = true;
        } else {
            comment.className = "cEx";
            comment.isCollapsed = false;
        }
    }
}

/**
 * Shows the comment form as reply to another comment
 */
function rc(commentId, postLink/*, addCommentFormContainer, replyToCommentElem*/) {
    var addCommentFormContainer = 'addCommentFormContainer';
    var replyToCommentElem = 'replyToComment';
    //var postLink = $('pl' + commentId);

    var formContainer = $(addCommentFormContainer);
    if (formContainer) {
        if (postLink) {
            insertAfter(formContainer, postLink);
        }
        $$("#addCommentForm").each(function(elem) {elem.reset()});
        $("addCommentFormInnerContainer").show();
        formContainer.show();
    }
    var replyToComment = $(replyToCommentElem);
    if (replyToComment) {
        replyToComment.value = commentId;
    }
}

/**
 * Sends a comment
 */
function sendComment(replyToComment, nume, email, subiect, comentariu, tokenId, param_ts, responseContainer, loadingMessage) {
    $("addCommentErrorMessage").hide();

    var rootObjectType = null;
    var rootObjectId = null;
    // Get the form values
    if (typeof(currentArticleId) != "undefined" && currentArticleId) {
        rootObjectType = 1;
        rootObjectId = parseInt(currentArticleId);
    }
    if (typeof(currentObjectType) != "undefined" && currentObjectType && typeof(currentObjectId) != "undefined" && currentObjectId) {
        rootObjectType = parseInt(currentObjectType);
        rootObjectId = parseInt(currentObjectId);
    }
    if (rootObjectType == null || rootObjectId == null) {
        return;
    }
    nume = $F(nume).strip();
    email = $F(email).strip();
    subiect = $F(subiect).strip();
    comentariu = $F(comentariu).strip();
    replyToComment = $F(replyToComment);
    tokenId = $F(tokenId);
    var ts = param_ts.value;

    // Check if values are valid
    if (nume.length == 0 || email.length == 0 || subiect.length == 0 || comentariu.length == 0) {
        alert("Toate câmpurile sunt obligatorii!");
        return;
    }
    if (comentariu.length > 2000) {
        alert("EROARE! Comentariul contine " + comentariu.length + " caractere si depaseste dimensiunea maxima de 2000 de caractere!");
        return;
    }

    // Show the loading message
    var $responseContainer = $(responseContainer);
    $responseContainer.update(loadingMessage);
    $responseContainer.show();

    // Send the request
    var parameters = {
        name: nume,
        email: email,
        title: subiect,
        comment: comentariu,
        parentCommentStr: replyToComment
    };
    addCommentProxy.addComment(rootObjectType, rootObjectId, parameters, tokenId, ts, function(response) {
        $responseContainer.hide();
        if (response.status == 0) {
            $("addCommentForm").reset();
            $("addCommentFormInnerContainer").hide();
            $("addCommentSuccessMessage").show();
        } else {
            if (response.obj) {
                $("addCommentErrorMessageText").update(response.obj);
            }
            $("addCommentErrorMessage").show();
        }
    });
}

/**
 * Cancels a comment by hiding the comment window
 */
function cancelSendComment(addCommentFormContainer) {
    var formContainer = $(addCommentFormContainer);
    if (formContainer) {
        formContainer.hide();
    }
}

/**
 * Votes for a comment
 */
function vp(commentId) {
    commentVotingProxy.voteForComment(commentId, true, function(response) {
        if (response.status == 0) {
            var nrVotesSpan = $("v_" + commentId);
            if (nrVotesSpan) {
                var nrVotes = nrVotesSpan.innerHTML;
                if (nrVotes) {
                    nrVotes ++;
                    if (nrVotes > 0) {
                        nrVotes = "+" + nrVotes;
                    } else {
                        nrVotes = "" + nrVotes;
                    }
                    nrVotesSpan.innerHTML = nrVotes;
                }
            }
            var nrVotesTotalSpan = $("vt_" + commentId);
            var nrVotesTotalStrSpan = $("wt_" + commentId);
            if (nrVotesTotalSpan && nrVotesTotalStrSpan) {
                var nrVotesTotal = nrVotesTotalSpan.innerHTML;
                if (nrVotesTotal) {
                    nrVotesTotal ++;
                    nrVotesTotalSpan.innerHTML = nrVotesTotal;
                    if (nrVotesTotal == 1) {
                        nrVotesTotalStrSpan.innerHTML = "vot" ;
                    } else {
                        nrVotesTotalStrSpan.innerHTML = "voturi" ;
                    }
                }
            }

        } else {
            alert(response.obj);
            if (response.status != 5) {
                var loginPanel = $('loginPanel');
                if (loginPanel) {
                    var postLink = $("co_" + commentId);
                    if (postLink) {
                        insertBefore(loginPanel, postLink);
                    }
                    loginPanel.show();
                    window.location.hash = "loginPanel";
                }
            }
        }
    });
}

/**
 * Votes against a comment
 */
function vc(commentId) {
    commentVotingProxy.voteForComment(commentId, false, function(response) {
        if (response.status == 0) {
            var nrVotesSpan = $("v_" + commentId);
            if (nrVotesSpan) {
                var nrVotes = nrVotesSpan.innerHTML;
                if (nrVotes) {
                    nrVotes --;
                    if (nrVotes > 0) {
                        nrVotes = "+" + nrVotes;
                    } else {
                        nrVotes = "" + nrVotes;
                    }
                    nrVotesSpan.innerHTML = nrVotes;
                }
            }
            var nrVotesTotalSpan = $("vt_" + commentId);
            var nrVotesTotalStrSpan = $("wt_" + commentId);
            if (nrVotesTotalSpan && nrVotesTotalStrSpan) {
                var nrVotesTotal = nrVotesTotalSpan.innerHTML;
                if (nrVotesTotal) {
                    nrVotesTotal ++;
                    nrVotesTotalSpan.innerHTML = nrVotesTotal;
                    if (nrVotesTotal == 1) {
                        nrVotesTotalStrSpan.innerHTML = "vot" ;
                    } else {
                        nrVotesTotalStrSpan.innerHTML = "voturi" ;
                    }
                }
            }

        } else {
            alert(response.obj);
            if (response.status != 5) {
                var loginPanel = $('loginPanel');
                if (loginPanel) {
                    var postLink = $("co_" + commentId);
                    if (postLink) {
                        insertBefore(loginPanel, postLink);
                    }
                    loginPanel.show();
                    window.location.hash = "loginPanel";
                }
            }
        }
    });
}

/**
 * Vote for an object
 */
function vo(objectTypeId, objectId, votePro) {
    votingProxy.voteForObject(objectTypeId, objectId, votePro, function(response) {
        if (response.status == 0) {
            var nrVotesSpan = $('nrVotes');
            if (nrVotesSpan) {
                var nrVotes = nrVotesSpan.innerHTML;
                if (nrVotes) {
                    if (votePro) {
                        nrVotes += votePro;
                    } else {
                        nrVotes += votePro;
                    }
                    if (nrVotes > 0) {
                        nrVotes = "+" + nrVotes;
                    } else {
                        nrVotes = "" + nrVotes;
                    }
                    nrVotesSpan.innerHTML = nrVotes;
                }
                var nrVotesTotalSpan = $("vt");
                var nrVotesTotalStrSpan = $("wt");
                if (nrVotesTotalSpan && nrVotesTotalStrSpan) {
                    var nrVotesTotal = nrVotesTotalSpan.innerHTML;
                    if (nrVotesTotal) {
                        nrVotesTotal ++;
                        nrVotesTotalSpan.innerHTML = nrVotesTotal;
                        if (nrVotesTotal == 1) {
                            nrVotesTotalStrSpan.innerHTML = "vot" ;
                        } else {
                            nrVotesTotalStrSpan.innerHTML = "voturi" ;
                        }
                    }
                }
            } else {
                var msg = $('ratingMsg');
                if(msg) {
                    msg.innerHTML = 'Votul dvs a fost salvat';
                }
            }

        } else {
            alert(response.obj);
            if (response.status != 5) {
                var loginPanel = $('loginPanel');
                if (loginPanel) {
                    var postLink = null;
                    if (postLink) {
                        insertBefore(loginPanel, postLink);
                    }
                    loginPanel.show();
                    if (postLink) {
                        window.location.hash = 'loginPanel';
                    }
                }
            }
        }
    });
}

/**
 * @Deprecated
 */
function getSecureToken(warning, url, param_ts) {
    $(warning).remove();
    new Ajax.Request(url, {
        method: 'get',
        onSuccess: function(transport) {
            param_ts.value = "" + transport.responseText;
        },
        onFailure: function() {
            alert('A aparut o problema pe server. Va rugam sa incercati mai tarziu.')
        }
    });
}

/**
 * Opens a centered popup
 */
function openCenteredPopup(url, name, w, h) {
    var int_windowLeft = (screen.width - w) / 2;
    var int_windowTop = (screen.height - h) / 2;
    var str_windowProperties = 'height=' + h + ',width=' + w + ',top=' + int_windowTop + ',left=' + int_windowLeft + ',scrollbars=' + false + ',resizable=' + true + ',menubar=' + false + ',toolbar=' + false + ',location=' + false + ',statusbar=' + false + ',fullscreen=' + false + '';
    var obj_window = window.open(url, name, str_windowProperties);
    if (parseInt(navigator.appVersion) >= 4) {
        obj_window.window.focus();
    }
}

/**
 * Opens zoom version for a picture
 */
function openZoom(zoomUrl, imageUrl, width, height) {
    var int_windowLeft = (screen.width - width) / 2;
    var int_windowTop = (screen.height - height) / 2;
    var newWindow = window.open(
            zoomUrl + '&imgUrl=' + imageUrl,
            'ZOOM',
            'scrollbars=yes,left=' + int_windowLeft + ',top=' + int_windowTop + ',width=' + width + ',height=' + height + ',resizable=1,toolbar=0,location=0,directories=0,status=0,menubar=0,copyhistory=0'
            );
    if (document.images) {
        newWindow.focus();
    }
}

/**
 * Checks whether an object is valid or not (not null, not undefined, etc)
 *
 * @param obj the object to be checked
 * @return true if is valid, false otherwise
 */
function objIsValid(obj) {
    return !(!obj || obj == null || typeof(obj) == "undefined" || obj == "null");
}

/**
 * DOM util function for inserting node after ref
 */
function insertAfter(/*Node*/node, /*Node*/ref) {
    var parent = ref.parentNode;
    if (ref == parent.lastChild) {
        parent.appendChild(node);
    } else {
        return insertBefore(node, ref.nextSibling);
    }
    return true;
};

/**
 * DOM util function for inserting node before ref
 */
function insertBefore(/*Node*/node, /*Node*/ref) {
    var parent = ref.parentNode;
    parent.insertBefore(node, ref);
    return true;
};

/**
 * Checks for form submit by ENTER key
 */
function checkLoginEnter(e) {
    if (e.keyCode == Event.KEY_RETURN) {
		doLogin();
	}
};

/**
 * Returns true if login is invalid
 */
function invalidLogin() {
    var url = document.location.href;
    var pos = url.indexOf("login_invalid");
    return (pos >= 0);
};

/**
 * Checks for form submit by ENTER key
 */
function checkLoginEnterSubmit(e) {
    if (e.keyCode == Event.KEY_RETURN) {
		doLoginSubmit();
	}
};
