var dupTest = '';
var searchTimestamp = 0;
var browserName = navigator.appName;
var bw = false;

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
}

String.prototype.ltrim = function() {
    return this.replace(/^\s+/,"");
}

String.prototype.rtrim = function() {
    return this.replace(/\s+$/,"");
}

Number.prototype.filesizeFormat = function() {

    if (this >= 1073741824)
        return (this / 1024.0 / 1024.0 / 1024.0).format(2) + " GB";
    else if (this >= 1048576)
        return (this / 1024.0 / 1024.0).format(2) + " MB";
    else if (this >= 1024)
        return (this / 1024.0).format(2) + " KB";
    else if (this > 0 && this < 1024)
        return this + " B";

    return "0 B";
}

Number.prototype.format = function(decimalPoints, thousandsSep, decimalSep)
    {
        var val = this + '', re = /^(-?)(\d+)/, x;
        if (decimalPoints != null)
            val = this.toFixed(decimalPoints);

        if (thousandsSep && (x = re.exec(val)))
            {
                for (var a = x[2].split(''), i = a.length - 3; i > 0; i -= 3)
                    a.splice(i, 0, thousandsSep);

                val = val.replace(re, x[1] + a.join(''));
            }

        if (decimalSep)
            val = val.replace(/\./, decimalSep);

        return val;
    }

if (typeof Number.prototype.toFixed != 'function' || (.9).toFixed() == '0' || (.007).toFixed(2) == '0.00')
    Number.prototype.toFixed = function(f) {
        if (isNaN(f *= 1) || f < 0 || f > 20)
            f = 0;

        var s = '', x = this.valueOf(), m = '';
        if (this < 0) {
            s = '-';
            x *= -1;
        }

        if (x >= Math.pow(10, 21))
            m = x.toString();
        else
            {
                m = Math.round(Math.pow(10, f) * x).toString();
                if (f != 0)
                    {
                        var k = m.length;
                        if (k <= f)
                            {
                                var z = '00000000000000000000'.substring(0, f + 1 - k);
                                m = z + m;
                                k = f + 1;
                            }

                        var a = m.substring(0, k - f);
                        var b = m.substring(k - f);
                        m = a + '.' + b;
                    }
            }

        if (m == '0')
            s = '';

        return s + m;
    }

function setCookie(name, value, expireDays) {
    var exdate = new Date()
    exdate.setDate(exdate.getDate() + expireDays)
    document.cookie = name + "=" + value + ((expireDays == null) ? "" : ";expires=" + exdate.toGMTString())
}

function getPosition(element)
    {
        var iebody = (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body;
        var dsocleft = document.all? iebody.scrollLeft : pageXOffset;
        var dsoctop = document.all? iebody.scrollTop : pageYOffset;

        var posReal = Position.realOffset(element);
        var pos = Position.cumulativeOffset(element);

        var top = pos[1] - posReal[1] + dsoctop;
        var left = pos[0] + posReal[0] - dsocleft;

        var offsetWidth = element.offsetWidth;
        var offsetHeight = element.offsetHeight;

        return {
			left: left,
			top: top,
			width: offsetWidth,
			height:  offsetHeight
		};
    }

function initQuickSearch() {
	$('searchCriteria').style.color = '#000000';
	$('searchCriteria').value = '';
}

function resetQuickSearch() {
	$('searchCriteria').style.color = '#b4b4b4';
	$('searchCriteria').value = qsMsg;
}

function doQuickSearch(e, field) {

	var seed = field.value;
	if (e.keyCode == 27) {
		field.value = '';
		seed = '';
	}

    if ((seed = seed.trim()) == '')
        Effect.Fade('quickSearchResultDiv', {duration: .2});
    else {

        if (dupTest == seed)
            return;

        dupTest = seed;
        var pos = getPosition($('searchCriteria'));
        var resultDiv = $('quickSearchResultDiv');
        resultDiv.style.top = pos.top + pos.height + 2;
        resultDiv.style.left = pos.left;
        resultDiv.innerHTML = '<div class=qsSearching><img src=/images/loading.gif align=absmiddle> ' + qsSearching + '</div>';
        Element.show('quickSearchResultDiv');

        var params = {
            seed: seed,
            rand: Math.random()
        };
        var url = '/servlet/com.fototalk.servlets.QuickSearchAJAX?' + $H(params).toQueryString();
        new Ajax.Request( url, {
                method: 'get',
                onSuccess: processSearchResult
            }
        );
    }
}

function processSearchResult(req) {

    if (req.responseText.length < 2)
        return;

    var result = {};
    eval('result = (' + req.responseText + ')');
    if (result.timestamp < searchTimestamp)
        return;

    searchTimestamp = result.timestamp;
    var html = '';

    if (result.users.length == 0 && result.keywords.length == 0 && result.pictures.length == 0 && result.equipment.length == 0)
        html += '<div class=qsLineInfo>' + qsNoResults + '</div>';

    for (key in result) {

        if (!key || !result[key].length)
            continue;
        
        if (key == 'users' && result.users.length > 0) {

            html += '<div class="qsHeader">Users</div><table class=qsResults>';
            for (i = 0; i < result.users.length; i++) {

                var user = result.users[i];
				var ident = user.ident;
				if (ident.length > 20)
					ident = ident.substring(0, 20) + '...';

                html += '<tr>';
                html += '<td class=qsTd1><a href=/profile/' + user.uid + '><img src="' + user.avatar + '" class="smallAvatar"></a></td>';
                html += '<td class=qsTd2><a href=/profile/' + user.uid + ' class=blueLink>' + ident + '</a><div class=qsLine2>' + user.type + '</div></td>';
                html += '</tr>';

            }

            html += '</table>';


        } else if (key == 'keywords' && result.keywords.length > 0) {

            html += '<div class="qsHeader">Keywords</div>';
            html += '<div class=qsKeywords>';
            for (i = 0; i < result.keywords.length; i++) {

                var word = result.keywords[i];

                html += '<a href=/galleries/keywords/' + word.wid + ' class=blueLink>' + word.word + '</a>';
                html += (i + 1 < result.keywords.length) ? ', ' : '';
            }

            html += '</div>';

        } else if (key == 'pictures' && result.pictures.length > 0) {

            html += '<div class="qsHeader">Pictures</div>';
            html += '<table class=qsResults>';

            for (var i = 0; i < result.pictures.length; i++) {

                var picture = result.pictures[i];
				var ident = picture.owner.ident;
				var title = picture.title;

                if (ident && ident.length > 20)
					ident = ident.substring(0, 20) + '...';

				if (title && title.length > 20)
					title = title.substring(0, 20) + '...';

                html += '<tr>';
                html += '<td class=qsTd1><a href="' + picture.url + '"><img src="' + picture.src + '" class=newPhoto width=' + picture.width + ' height=' + picture.height + ' style="margin-bottom:0px;"></a></td>';
                html += '<td class=qsTd2><div class=glanceAuthorName><a href=/profile/' + picture.owner.uid + '>' + ident + '</a></div><div class=glancePhotoTitle>' + title + '</div>';
                html += '</td>';
                html += '</tr>';
            }

            html += '</table>';


        } else if (key == 'equipment' && result.equipment.length > 0) {

            html += '<div class="qsHeader">Equipment</div>';
            html += '<table class=qsResults>';

            for (i = 0; i < result.equipment.length; i++) {

                var equipment = result.equipment[i];
				var freestyle = equipment.freestyle;
				if (freestyle.length > 20)
					freestyle = freestyle.substring(0, 20) + '...';

                html += '<tr>';
                html += '<td class=qsTd1><a href="' + equipment.link + '"><img src="' + equipment.src + '" border=0 class=newPhoto style="margin-bottom:0px;"></a></td>';
                html += '<td class=qsTd2><a href="' + equipment.link + '" class=blueLink>' + freestyle + '</a><div class=qsLine2>';
                html += equipment.type + '</div>';
                html += '</td>';
                html += '</tr>';
            }

            html += '</table>';

        }
    }

    var t = document.createElement('div');
	t.innerHTML = html + '<div class=qsClose><a href=# class=blueLink onClick="new Effect.SlideUp(quickSearchResultDiv, {duration:.4}); return false;">' + msgClose + '</a></div>';

	$('quickSearchResultDiv').innerHTML = "";
	$('quickSearchResultDiv').appendChild(t);
}

function convertToBw() {

    bw = !bw;
	$("themainpic").style.filter = "Gray";
	$("themainpic").filters["Gray"].enabled = bw;
}

function showHideRules() {

    var msgDiv = $('schoolMessageDev');
    var openCloseDiv = $('helpOpenCloseDiv');

    if (msgDiv.style.display == '') {

        new Effect.SlideUp('schoolMessageDev', {duration: .3});
        setCookie('schoolMessageVis', 'no', 365);
        openCloseDiv.innerHTML = msgOpen;
    } else {
        
        new Effect.SlideDown('schoolMessageDev', {duration: .3});
        setCookie('schoolMessageVis', 'yes', 365);
        openCloseDiv.innerHTML = msgClose;
    }
}

function addToFavorite(type, foreignId, action) {

    var text = $('addFavDiv' + type).innerHTML;
    $('addFavDiv' + type).innerHTML = '<img src=/images/favoriteOff.png style="vertical-align: middle; margin-right: 5px; border: 0px;"> Just a moment...';

    if (action == undefined || action == null)
        action = 'add';

    var params = {
        ajax: true,
        type: type,
        id: foreignId,
        action: action,
        rand: Math.random()
    };
    var url = '/servlet/com.fototalk.servlets.AddRemoveFavorite?' + $H(params).toQueryString();
    new Ajax.Request( url, {
            method: 'get',
            onSuccess: function(resp) {

                $('addFavDiv' + type).innerHTML = text;
                var result = resp.responseText.evalJSON();
                if (result.code != 1)
                    return;

                if (params.action == 'add') {
                    Element.hide('addFavDiv' + type);
                    Element.show('myFavDiv' + type);
                } else {
                    Element.show('addFavDiv' + type);
                    Element.hide('myFavDiv' + type);
                }
            }
        }
    );
}
