// ============================================================================
// Developed by Kernel Team.
// http://kernel-team.com
// ============================================================================

// ============================================================================
// | Common functions                                                         |
// ============================================================================

function stub() {
}

function addCl(el, cl) {
    if (!hasCl(el, cl)) {
        if (el.className.length == 0) {
            el.className = cl;
        } else {
            el.className += ' ' + cl;
        }
    }
}

function hasCl(el, cl) {
    var classes = el.className.split(' ');
    for (var i = 0; i < classes.length; i++) {
        if (classes[i] == cl) {
            return true;
        }
    }
    return false;
}

function removeCl(el, cl) {
    var classes = el.className.split(' ');
    var newClass = '';
    for (var i = 0; i < classes.length; i++) {
        if (classes[i] != cl) {
            newClass += ' ' + classes[i];
        }
    }
    el.className = newClass;
}

function getXmlr() {
    var res = null;
    if (window.XMLHttpRequest) {
        res = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        res = new ActiveXObject('Microsoft.XMLHTTP');
    }
    return res;
}

function doPost(url, data, needText, callback) {
    var req = getXmlr();
    if (!req) {
        return null;
    }
    try {
        req.open('POST', encodeURI(url), true);
        req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        req.onreadystatechange = function() {
            if (req.readyState == 4) {
                if (needText) {
                    callback(req.responseText);
                } else {
                    callback(req.responseXML);
                }

            }
        };
        req.send(data);
    } catch (e) {
        return e;
    }
    return null;
}

function doGet(url, needText, callback) {
    var req = getXmlr();
    if (!req) {
        return null;
    }
    try {
        req.open('GET', encodeURI(url), true);
        req.onreadystatechange = function() {
            if (req.readyState == 4) {
                if (needText) {
                    callback(req.responseText);
                } else {
                    callback(req.responseXML);
                }

            }
        };
        req.send(null);
    } catch (e) {
        return e;
    }
    return null;
}

function getSuccess(xml) {
    if ((xml) && (xml.documentElement)) {
        if (xml.documentElement.nodeName == 'success') {
            return xml.documentElement;
        }
    }
    return null;
}

function getErrors(xml) {
    if ((xml) && (xml.documentElement)) {
        if (xml.documentElement.nodeName == 'failure') {
            var childs = xml.documentElement.childNodes;
            var result = new Array();
            for (var i = 0; i < childs.length; i++) {
                if (childs[i].nodeName == 'errors') {
                    result.push(childs[i]);
                }
            }
            return result;
        }
    }
    return null;
}

function getTextContent(node) {
    if (node) {
        if (node.textContent) {
            return node.textContent;
        } else if (node.innerText) {
            return node.innerText;
        } else if (node.text) {
            return node.text;
        }
    }
    return null;
}

function setInnerHtml(id, html) {
    var doc = document.getElementById(id);
    if (doc) {
        doc.innerHTML = html;
    }
}

function getHumanSizeDesc(size) {
    var temp = size;
    var modifier = 'bytes';
    if (temp > 1024) {
        temp /= 1024;
        modifier = 'KB';
    }
    if (temp > 1024) {
        temp /= 1024;
        modifier = 'MB';
    }
    if (temp > 1024) {
        temp /= 1024;
        modifier = 'GB';
    }
    temp = Math.floor(temp * 10) / 10;
    return temp + ' ' + modifier;
}

function getHumanTimeDesc(seconds) {
    var temp = Math.floor(seconds);
    var modifier = 'second(s)'
    if (temp < 60) {
        return temp + ' ' + modifier;
    } else {
        temp = Math.floor(temp / 60);
        modifier = 'minute(s)'
    }

    if (temp < 60) {
        return temp + ' ' + modifier;
    } else {
        var hours = Math.floor(temp / 60);
        var minutes = temp % 60;
        return hours + ' hour(s) ' + minutes + ' minute(s)';
    }
}

// ============================================================================
// | MD5 Encoder                                                              |
// ============================================================================

function KTMD5Encoder() {
}

KTMD5Encoder.prototype.encode = function(s) {
    return this._convertToHex(this._algo(this._convertToBinary(s), s.length * KTMD5Encoder._chrsz));
}

KTMD5Encoder.prototype._algo = function(x, len) {
    x[len >> 5] |= 0x80 << ((len) % 32);
    x[(((len + 64) >>> 9) << 4) + 14] = len;

    var a = 1732584193;
    var b = -271733879;
    var c = -1732584194;
    var d = 271733878;

    for (var i = 0; i < x.length; i += 16) {
        var olda = a;
        var oldb = b;
        var oldc = c;
        var oldd = d;

        a = this._bbb(a, b, c, d, x[i    ], 7, -680876936);
        d = this._bbb(d, a, b, c, x[i + 1], 12, -389564586);
        c = this._bbb(c, d, a, b, x[i + 2], 17, 606105819);
        b = this._bbb(b, c, d, a, x[i + 3], 22, -1044525330);
        a = this._bbb(a, b, c, d, x[i + 4], 7, -176418897);
        d = this._bbb(d, a, b, c, x[i + 5], 12, 1200080426);
        c = this._bbb(c, d, a, b, x[i + 6], 17, -1473231341);
        b = this._bbb(b, c, d, a, x[i + 7], 22, -45705983);
        a = this._bbb(a, b, c, d, x[i + 8], 7, 1770035416);
        d = this._bbb(d, a, b, c, x[i + 9], 12, -1958414417);
        c = this._bbb(c, d, a, b, x[i + 10], 17, -42063);
        b = this._bbb(b, c, d, a, x[i + 11], 22, -1990404162);
        a = this._bbb(a, b, c, d, x[i + 12], 7, 1804603682);
        d = this._bbb(d, a, b, c, x[i + 13], 12, -40341101);
        c = this._bbb(c, d, a, b, x[i + 14], 17, -1502002290);
        b = this._bbb(b, c, d, a, x[i + 15], 22, 1236535329);

        a = this._ccc(a, b, c, d, x[i + 1], 5, -165796510);
        d = this._ccc(d, a, b, c, x[i + 6], 9, -1069501632);
        c = this._ccc(c, d, a, b, x[i + 11], 14, 643717713);
        b = this._ccc(b, c, d, a, x[i   ], 20, -373897302);
        a = this._ccc(a, b, c, d, x[i + 5], 5, -701558691);
        d = this._ccc(d, a, b, c, x[i + 10], 9, 38016083);
        c = this._ccc(c, d, a, b, x[i + 15], 14, -660478335);
        b = this._ccc(b, c, d, a, x[i + 4], 20, -405537848);
        a = this._ccc(a, b, c, d, x[i + 9], 5, 568446438);
        d = this._ccc(d, a, b, c, x[i + 14], 9, -1019803690);
        c = this._ccc(c, d, a, b, x[i + 3], 14, -187363961);
        b = this._ccc(b, c, d, a, x[i + 8], 20, 1163531501);
        a = this._ccc(a, b, c, d, x[i + 13], 5, -1444681467);
        d = this._ccc(d, a, b, c, x[i + 2], 9, -51403784);
        c = this._ccc(c, d, a, b, x[i + 7], 14, 1735328473);
        b = this._ccc(b, c, d, a, x[i + 12], 20, -1926607734);

        a = this._ddd(a, b, c, d, x[i + 5], 4, -378558);
        d = this._ddd(d, a, b, c, x[i + 8], 11, -2022574463);
        c = this._ddd(c, d, a, b, x[i + 11], 16, 1839030562);
        b = this._ddd(b, c, d, a, x[i + 14], 23, -35309556);
        a = this._ddd(a, b, c, d, x[i + 1], 4, -1530992060);
        d = this._ddd(d, a, b, c, x[i + 4], 11, 1272893353);
        c = this._ddd(c, d, a, b, x[i + 7], 16, -155497632);
        b = this._ddd(b, c, d, a, x[i + 10], 23, -1094730640);
        a = this._ddd(a, b, c, d, x[i + 13], 4, 681279174);
        d = this._ddd(d, a, b, c, x[i   ], 11, -358537222);
        c = this._ddd(c, d, a, b, x[i + 3], 16, -722521979);
        b = this._ddd(b, c, d, a, x[i + 6], 23, 76029189);
        a = this._ddd(a, b, c, d, x[i + 9], 4, -640364487);
        d = this._ddd(d, a, b, c, x[i + 12], 11, -421815835);
        c = this._ddd(c, d, a, b, x[i + 15], 16, 530742520);
        b = this._ddd(b, c, d, a, x[i + 2], 23, -995338651);

        a = this._eee(a, b, c, d, x[i   ], 6, -198630844);
        d = this._eee(d, a, b, c, x[i + 7], 10, 1126891415);
        c = this._eee(c, d, a, b, x[i + 14], 15, -1416354905);
        b = this._eee(b, c, d, a, x[i + 5], 21, -57434055);
        a = this._eee(a, b, c, d, x[i + 12], 6, 1700485571);
        d = this._eee(d, a, b, c, x[i + 3], 10, -1894986606);
        c = this._eee(c, d, a, b, x[i + 10], 15, -1051523);
        b = this._eee(b, c, d, a, x[i + 1], 21, -2054922799);
        a = this._eee(a, b, c, d, x[i + 8], 6, 1873313359);
        d = this._eee(d, a, b, c, x[i + 15], 10, -30611744);
        c = this._eee(c, d, a, b, x[i + 6], 15, -1560198380);
        b = this._eee(b, c, d, a, x[i + 13], 21, 1309151649);
        a = this._eee(a, b, c, d, x[i + 4], 6, -145523070);
        d = this._eee(d, a, b, c, x[i + 11], 10, -1120210379);
        c = this._eee(c, d, a, b, x[i + 2], 15, 718787259);
        b = this._eee(b, c, d, a, x[i + 9], 21, -343485551);

        a = this._add(a, olda);
        b = this._add(b, oldb);
        c = this._add(c, oldc);
        d = this._add(d, oldd);
    }
    return Array(a, b, c, d);
}

KTMD5Encoder.prototype._aaa = function(q, a, b, x, s, t) {
    return this._add(this._rol(this._add(this._add(a, q), this._add(x, t)), s), b);
}

KTMD5Encoder.prototype._bbb = function(a, b, c, d, x, s, t) {
    return this._aaa((b & c) | ((~b) & d), a, b, x, s, t);
}

KTMD5Encoder.prototype._ccc = function(a, b, c, d, x, s, t) {
    return this._aaa((b & d) | (c & (~d)), a, b, x, s, t);
}

KTMD5Encoder.prototype._ddd = function(a, b, c, d, x, s, t) {
    return this._aaa(b ^ c ^ d, a, b, x, s, t);
}

KTMD5Encoder.prototype._eee = function(a, b, c, d, x, s, t) {
    return this._aaa(c ^ (b | (~d)), a, b, x, s, t);
}

KTMD5Encoder.prototype._add = function(x, y)
{
    var lsw = (x & 0xFFFF) + (y & 0xFFFF);
    var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
    return (msw << 16) | (lsw & 0xFFFF);
}

KTMD5Encoder.prototype._rol = function(num, cnt) {
    return (num << cnt) | (num >>> (32 - cnt));
}

KTMD5Encoder.prototype._convertToBinary = function(str) {
    var bin = Array();
    var mask = (1 << KTMD5Encoder._chrsz) - 1;
    for (var i = 0; i < str.length * KTMD5Encoder._chrsz; i += KTMD5Encoder._chrsz) {
        bin[i >> 5] |= (str.charCodeAt(i / KTMD5Encoder._chrsz) & mask) << (i % 32);
    }
    return bin;
}

KTMD5Encoder.prototype._convertToHex = function(binarray) {
    var hex_tab = KTMD5Encoder._hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
    var str = "";
    for (var i = 0; i < binarray.length * 4; i++) {
        str += hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8 + 4)) & 0xF) + hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8  )) & 0xF);
    }
    return str;
}

KTMD5Encoder._chrsz = 8;
KTMD5Encoder._hexcase = 0;

// ============================================================================
// | Star voting                                                              |
// ============================================================================


function KTStarVoting(idPrefix, emptyStyle, fullStyle, halfStyle, moverStyle, postUrl, successContainerId, failureContainerId) {
    var stars = new Array();
    var hasVoted = false;
    for (var i = 1; ; i++) {
        var el = document.getElementById(idPrefix + i);
        if (el) {
            var star = new Object();
            star['el'] = el;
            if (hasCl(el, emptyStyle)) {
                star['old'] = emptyStyle;
            } else if (hasCl(el, fullStyle)) {
                star['old'] = fullStyle;
            } else if (hasCl(el, halfStyle)) {
                star['old'] = halfStyle;
            } else {
                continue;
            }
            el.onmouseover = function() {
                if (hasVoted) {
                    return;
                }
                var cl = moverStyle;
                for (var j = 0; j < stars.length; j++) {
                    removeCl(stars[j]['el'], stars[j]['old']);
                    addCl(stars[j]['el'], cl);
                    if (stars[j]['el'] == this) {
                        cl = emptyStyle;
                    }
                }
            };
            el.onmouseout = function() {
                if (hasVoted) {
                    return;
                }
                var cl = moverStyle;
                for (var j = 0; j < stars.length; j++) {
                    removeCl(stars[j]['el'], cl);
                    addCl(stars[j]['el'], stars[j]['old']);
                    if (stars[j]['el'] == this) {
                        cl = emptyStyle;
                    }
                }
            };
            el.onclick = function() {
                if (hasVoted) {
                    return;
                }
                var x = this.id.indexOf(idPrefix);
                if ((x >= 0) && (x + idPrefix.length < this.id.length)) {
                    var idx = this.id.substring(x + idPrefix.length);
                    doPost(postUrl, 'vote=' + idx, false, function(xml) {
                        var success = getSuccess(xml);
                        if (success) {
                            var childs = success.childNodes;
                            for (var i = 0; i < childs.length; i++) {
                                if (childs[i].nodeName == 'message') {
                                    setInnerHtml(successContainerId, getTextContent(childs[i]));
                                } else if (childs[i].nodeName == 'rating') {
                                    try {
                                        var rating = parseFloat(getTextContent(childs[i]));
                                        for (var j = 0; j < stars.length; j++) {
                                            if (rating >= j + 1) {
                                                removeCl(stars[j]['el'], moverStyle);
                                                removeCl(stars[j]['el'], emptyStyle);
                                                removeCl(stars[j]['el'], halfStyle);
                                                addCl(stars[j]['el'], fullStyle);
                                            } else if (rating > j) {
                                                removeCl(stars[j]['el'], moverStyle);
                                                removeCl(stars[j]['el'], emptyStyle);
                                                removeCl(stars[j]['el'], fullStyle);
                                                addCl(stars[j]['el'], halfStyle);
                                            } else {
                                                removeCl(stars[j]['el'], moverStyle);
                                                removeCl(stars[j]['el'], halfStyle);
                                                removeCl(stars[j]['el'], fullStyle);
                                                addCl(stars[j]['el'], emptyStyle);
                                            }
                                        }
                                    } catch (e) {
                                        return e;
                                    }
                                }
                            }
                        } else {
                            var errors = getErrors(xml);
                            if ((errors) && (errors.length > 0)) {
                                setInnerHtml(failureContainerId, getTextContent(errors[0]));
                            }
                        }
                    });
                    hasVoted = true;
                }
            }
            stars.push(star);
        } else {
            break;
        }
    }
}

// ============================================================================
// | Blocks visibility switcher                                               |
// ============================================================================

function KTBlockSwitcher(globalId, blockId, swictherId, switcherSelectedStyle) {
    var block = document.getElementById(blockId);
    var switcher = document.getElementById(swictherId);

    if (switcher) {
        switcher.onclick = function() {
            KTBlockSwitcher._switch(globalId, blockId, swictherId, switcherSelectedStyle);
        };
        if (hasCl(switcher, switcherSelectedStyle)) {
            KTBlockSwitcher._cb[globalId] = block;
            KTBlockSwitcher._cs[globalId] = switcher;
            KTBlockSwitcher._csss[globalId] = switcherSelectedStyle;
        }
    }
}

KTBlockSwitcher._cb = new Object();
KTBlockSwitcher._cs = new Object();
KTBlockSwitcher._csss = new Object();

KTBlockSwitcher._switch = function(gid, blid, swid, cl) {
    var bl = document.getElementById(blid);
    var sw = document.getElementById(swid);
    if ((!bl) || (bl == KTBlockSwitcher._cb[gid])) {
        return;
    }
    if (KTBlockSwitcher._cb[gid]) {
        KTBlockSwitcher._cb[gid].style.display = 'none';
    }
    if (KTBlockSwitcher._cs[gid]) {
        removeCl(KTBlockSwitcher._cs[gid], KTBlockSwitcher._csss[gid]);
    }

    bl.style.display = 'block';
    if (bl.style.visibility = 'hidden') {
        bl.style.visibility = 'visible';
    }
    KTBlockSwitcher._cb[gid] = bl;

    if (sw && cl) {
        addCl(sw, cl);
        KTBlockSwitcher._cs[gid] = sw;
        KTBlockSwitcher._csss[gid] = cl;
    }
}

// ============================================================================
// | Comment posting                                                          |
// ============================================================================


// ============================================================================
// | Uploader                                                                 |
// ============================================================================

function KTFileUpload(form) {
    var file = null;
    var hash = null;
    if (form) {
        for (var i = 0; i < form.elements.length; i++) {
            if (form.elements[i].id == KTFileUpload._ID_FORM_FILE) {
                file = form.elements[i];
            } else if (form.elements[i].id == KTFileUpload._ID_FORM_FILENAME) {
                hash = form.elements[i];
            }
        }
        if (file && hash) {
            if (!file.value) {
                alert('Please specify a file to upload.');
                return;
            }
            var allExt = '';
            var accepted = false;
            for (var j = 0; j < KTFileUpload._FILE_ALLOWED_EXTENSIONS.length; j++) {
                if (file.value.indexOf(KTFileUpload._FILE_ALLOWED_EXTENSIONS[j]) == file.value.length - KTFileUpload._FILE_ALLOWED_EXTENSIONS[j].length) {
                    accepted = true;
                    break;
                }
                allExt += KTFileUpload._FILE_ALLOWED_EXTENSIONS[j];
                if (j < KTFileUpload._FILE_ALLOWED_EXTENSIONS.length - 1) {
                    allExt += ', ';
                }
            }
            if (!accepted) {
                alert('The file you\'ve provided can not be accepted. The allowed file types are the following:\n\n' + allExt.toUpperCase());
                return;
            }

            hash.value = new KTMD5Encoder().encode(file.value + new Date().getTime());
            form.submit();

            var fc = document.getElementById(KTFileUpload._ID_FORM_CONTAINER);
            if (fc) {
                fc.style.display = 'none';
            }

            var pr = document.getElementById(KTFileUpload._ID_PROGRESS);
            if (pr) {
                pr.style.display = 'block';
                if (pr.style.visibility == 'hidden') {
                    pr.style.visibility = 'visible';
                }
            }

            setInnerHtml(KTFileUpload._ID_PROGRESS_TITLE, file.value);
            setInnerHtml(KTFileUpload._ID_PROGRESS_MESSAGE, 'Initializing upload...');

            KTFileUpload._uploadStarted = new Date().getTime();
            KTFileUpload._failedAttempsCount = 0;
            KTFileUpload._setTimeout(hash.value);
        }
    }
}

KTFileUpload._sendProgressRequest = function(hash) {
    doGet(KTFileUpload._STATUS_URL + '?file=' + hash + '&rand=' + new Date().getTime(), false, function(xml) {
        KTFileUpload._processProgressResponse(hash, xml);
    });
}

KTFileUpload._processProgressResponse = function(hash, xml) {
    var loaded = 0;
    var total = 1;
    if (xml) {
        if ((xml.documentElement) && (xml.documentElement.nodeName == 'status')) {
            var childs = xml.documentElement.childNodes;
            for (var i = 0; i < childs.length; i++) {
                if (childs[i].nodeName == 'errorId') {
                    setInnerHtml(KTFileUpload._ID_PROGRESS_MESSAGE, getTextContent(childs[i]));
                    return;
                } else if (childs[i].nodeName == 'loaded') {
                    loaded = getTextContent(childs[i]);
                } else if (childs[i].nodeName == 'total') {
                    total = getTextContent(childs[i]);
                }
            }
        }
    }
    if (loaded == 0) {
        this._failedAttempsCount++;
        if (this._failedAttempsCount >= KTFileUpload._MAX_FAILED_ATTEMPTS) {
            setInnerHtml(KTFileUpload._ID_PROGRESS_MESSAGE, 'Unexpected server response, please try again later.');
        }
    } else {
        this._failedAttempsCount = 0;
        var pc = loaded / total;
        var speed = loaded / (new Date().getTime() - KTFileUpload._uploadStarted) * 1000;
        var timeLeft = (total - loaded) / speed;
        var message = getHumanTimeDesc(timeLeft) + ' - ' + getHumanSizeDesc(loaded) + ' of ' + getHumanSizeDesc(total) + ' (' + getHumanSizeDesc(speed) + '/sec)';

        setInnerHtml(KTFileUpload._ID_PROGRESS_MESSAGE, message);

        var pr = document.getElementById(KTFileUpload._ID_PROGRESS_BAR);
        var prpc = document.getElementById(KTFileUpload._ID_PROGRESS_BAR_PC);
        if (pr && prpc) {
            var width = Math.floor((pr.offsetWidth - 10) * pc);
            prpc.style.width = width + 'px';
        }
    }
    KTFileUpload._setTimeout(hash);
}

KTFileUpload._setTimeout = function(hash) {
    setTimeout('KTFileUpload._sendProgressRequest(\'' + hash + '\')', KTFileUpload._REFRESH_TIMEOUT_MS);
}

KTFileUpload._failedAttempsCount = 0;
KTFileUpload._uploadStarted = 0;

KTFileUpload._ID_FORM_CONTAINER = 'uploader_form_container';
KTFileUpload._ID_FORM_FILE = 'uploader_form_file';
KTFileUpload._ID_FORM_FILENAME = 'uploader_form_filename';
KTFileUpload._ID_PROGRESS = 'uploader_progress';
KTFileUpload._ID_PROGRESS_TITLE = 'uploader_progress_title';
KTFileUpload._ID_PROGRESS_BAR = 'uploader_progress_bar';
KTFileUpload._ID_PROGRESS_BAR_PC = 'uploader_progress_bar_pc';
KTFileUpload._ID_PROGRESS_MESSAGE = 'uploader_progress_message';

KTFileUpload._REFRESH_TIMEOUT_MS = 1000;
KTFileUpload._MAX_FAILED_ATTEMPTS = 10;
KTFileUpload._FILE_ALLOWED_EXTENSIONS = ['.txt', '.log'];
KTFileUpload._FILE_SUBMIT_URL = 'http://simplex-studio.com/cgi-bin/uploader.cgi';
KTFileUpload._STATUS_URL = 'http://simplex-studio.com/get_upload_status.php';

$(document).ready(function(){

  $('.ssearch-input').val('Search...');
  $('.ssearch-input').click(function(){
    if($(this).val()=='Search...') {
      $(this).val('').css({
        color: '#fff',
        fontStyle: 'normal'
      });
    }
  });

  $('#pane1').jScrollPane();

  // light BOX
  $(".list-sets-page .photos a, .index-photos a").click(function(){
    var $photo_lb = $("#photo-lb").clone(), $overlay = $("<div></div>"), thumb = $(this).attr("rel");
    $(".lb-image img", $photo_lb).attr("src", thumb);
    $("body").append($overlay
      .attr("id", "lb-overlay")
      .css("height", $(document).height())
      .click(function(){
        $photo_lb.remove();
        $overlay.remove();
      })
    ).append($photo_lb
      .addClass("current-lb")
      .css({
        display: "block",
        top: $(window).scrollTop() + 50
      })
      .append($("<a href='#' class='lb-close' title='Close'></a>")
        .click(function(){
          $photo_lb.remove();
          $overlay.remove();
          return false;
        })
      )
    );
    return false;
  });
  // END light BOX

  $("#account, .close-account").click(function () {
    $("#myaccount").slideToggle("slow");
    return false;
  });

 $("#profile-form").ajaxForm({
      beforeSubmit: function() {
        $('#profile-answer').text('Saving...');
      },
      success: function(data) {
        if (!data.match(/\#success/)) {
          $('#profile-answer').text(data);
        } else {
          $('#profile-answer').text('Your profile saved.');
        }
      },
      error: function() {$('#profile-answer').text('Sorry! Connection problems.');}
  });

  $(".vote .star").click(function(){
    $(".vote .star").unbind();
    $(".vote").unbind();
    $.post(
      '/add_rating.php',
      {gallery_id: '{{$set_info.gallery_id}}', vote: 1+$(".vote .star").index(this)},
      function (data) {
        if (!data.match(/\#success/)) {
          alert(data);
        } else {
          $("#rating-amt").text(parseInt($("#rating-amt").text())+1);
          alert('Thank you!');
        }
      }
    );
    $(".vote").fadeTo('slow', 0.2, function(){
      resetRating();
      $(this).fadeTo('fast', 1.0);
    });
    return false;
  });
  $(".vote .star").mouseover(function(){
    if (starsReset) {clearTimeout(starsReset);}
    var current = $(".vote .star").index(this);
    for (var i = 0; i <= current; i++) {$(".vote .star:eq("+i+")").attr('src', '/images/star-full.gif')}
    for (var i = current+1; i < 5; i++) {$(".vote .star:eq("+i+")").attr('src', '/images/star-empty.gif')}
  });
  $(".vote").mouseout(function(){
    if (starsReset) {clearTimeout(starsReset);}
    starsReset = setTimeout(resetRating, 500);
  });

});
