
/**
 * -----------------------------------------------------------------------------
 * {{ Dropdown menu }}
 * -----------------------------------------------------------------------------
 */

/**
 * -----------------------------------------------------------------------------
 * {{ Tabs }}
 * -----------------------------------------------------------------------------
 */
function initTabs()
{
    tabAreas = document.getElementsByClassName('round-tabs');
    for (i = 0; i < tabAreas.length; i++) {
        zIndex = 10;
        tabs = tabAreas[i].getElementsByTagName('a');
        for (j = 0; j < tabs.length; j++) {
            if (tabs[j].className == 'active') {
                continue;
            }
            tabs[j].style.zIndex = --zIndex;
        }
    }
}

/**
 * toggle extra list text
 *
 */
function toggleListText()
{
    $('more-list-text').toggle();
}

function togglePokeTypes()
{
    $('pokeTypes').toggle();
}

/**
 * toggle sub nav
 *
 */
function toggleNav(elem)
{
    $(elem).toggle();
}

/**
 * toggle section
 *
 */
function toggleSynonymGroup(id)
{
    $('synonym-group-' + id).toggle();
}

/**
 * toggle dynamic comments in suggestion list
 *
 * @param int suggestionId
 * @param string requestUrl
 */
function toggleDynamicSuggestionComments(suggestionId, requestUrl)
{
    $('suggestion-comments-content-' + suggestionId).innerHTML = '&nbsp;';
	
    $('suggestion-comments-' + suggestionId).toggle();

    $('suggestion-comments-content-' + suggestionId).toggleClassName('suggestionsLoading');
    new Ajax.Updater('suggestion-comments-content-' + suggestionId, requestUrl, {
        //onComplete: $('formErrors').toggleClassName('loading'),
        onSuccess: function(t) {
        //handleValidateResponse(t, formId)
        },
        onComplete: function(t) {
            $('suggestion-comments-content-' + suggestionId).toggleClassName('suggestionsLoading')
        }
    });
}

function toggleSuggestionForm(suggestionId, requestUrl)
{
    $('suggestion-edit-content-' + suggestionId).innerHTML = '&nbsp;';
	
    $('suggestion-edit-' + suggestionId).toggle();

    $('suggestion-edit-content-' + suggestionId).toggleClassName('suggestionsLoading');
    new Ajax.Updater('suggestion-edit-content-' + suggestionId, requestUrl, {
        //onComplete: $('formErrors').toggleClassName('loading'),
        onSuccess: function(t) {
        //handleValidateResponse(t, formId)
        },
        onComplete: function(t) {
            $('suggestion-edit-content-' + suggestionId).toggleClassName('suggestionsLoading')
        }
    });
}

/**
 * display page overlay
 *
 */
var displayOverlay = function()
{
    Effect.Appear('pageOverlay', {
        duration: 0.3,
        to: 0.7
    });
    Effect.SlideDown('pageOverlayContent', {
        duration: 0.3
    });
}

/**
 * hide page overlay
 *
 */
var closeOverlay = function()
{
    Effect.Fade('pageOverlay', {
        duration: 0.3,
        to: 0.0
    });
    Effect.SlideUp('pageOverlayContent', {
        duration: 0.3
    });
}

/* --------------------------------------------------------------------------------- */

/**
 * validate user form by ajax request
 *
 * @param string formId
 * @param string requestUrl
 */
var validateForm = function(formId, requestUrl)
{
    new Ajax.Updater('formErrors', requestUrl, {
        onComplete: $('formErrors').toggleClassName('loading'),
        onSuccess: function(t) {
            handleValidateResponse(t, formId)
        },
        parameters: Form.serialize(formId)
    });
}

/**
 * handle ajax response, display error message
 *
 * @param mixed response
 * @param string formId
 */
var handleValidateResponse = function(t, formId)
{
    if (t.responseText) {
        $('formErrors').toggleClassName('loading');
        if ($('formErrors').visible()) {
            Effect.Pulsate('formErrors', {
                duration: 0.3,
                pulses: 1
            });
        } else {
            Effect.Appear('formErrors');
        }
    } else {
        $('formErrors').hide();
        $(formId).submit();
    }
}

/* --------------------------------------------------------------------------------- */

/**
 * toggle suggestion comments
 *
 */
var toggleSuggestionComments = function()
{
    Effect.toggle('suggestionComments', 'blind');
}

/**
 * get suggestions
 *
 * @param string type
 */
var getSuggestions = function(type, language)
{
    $(type + 'Suggestions').innerHTML = '';
    $(type + 'Suggestions').toggleClassName('suggestionsLoading');
    new Ajax.Updater(type + 'Suggestions', '/suggestions/getsuggestions/' + type + '/' + language, {
        onComplete: function(t) {
            $(type + 'Suggestions').toggleClassName('suggestionsLoading')
        }
    });
}

/**
 * rate suggestion
 *
 * @param int suggestionId
 * @param int user rating
 */
var rateSuggestion = function(suggestionId, rating)
{
    if (rating < 0) {
        $('suggestionRatingNegative' + suggestionId).innerHTML = '';
        $('suggestionRatingNegative' + suggestionId).toggleClassName('ratingLoading');
        new Ajax.Updater('suggestionRatingNegative' + suggestionId, '/suggestions/ratesuggestion/' + suggestionId + '/' + rating, {
            onComplete: function(t) {
                $('suggestionRatingNegative' + suggestionId).toggleClassName('ratingLoading')
            }
        });
    } else {
        $('suggestionRatingPositive' + suggestionId).innerHTML = '';
        $('suggestionRatingPositive' + suggestionId).toggleClassName('ratingLoading');
        new Ajax.Updater('suggestionRatingPositive' + suggestionId, '/suggestions/ratesuggestion/' + suggestionId + '/' + rating, {
            onComplete: function(t) {
                $('suggestionRatingPositive' + suggestionId).toggleClassName('ratingLoading')
            }
        });
    }
}

/**
 * rate website
 *
 * @param int websiteId
 * @param int user rating
 */
var rateWebsite = function(websiteId, rating)
{
    if (rating < 0) {
        $('websiteRatingNegative-' + websiteId).innerHTML = '';
        $('websiteRatingNegative-' + websiteId).toggleClassName('ratingLoading');
        new Ajax.Updater('websiteRatingNegative-' + websiteId, '/synonyms/ratewebsite/' + websiteId + '/' + rating, {
            onComplete: function(t) {
                $('websiteRatingNegative-' + websiteId).toggleClassName('ratingLoading')
            }
        });
    } else {
        $('websiteRatingPositive-' + websiteId).innerHTML = '';
        $('websiteRatingPositive-' + websiteId).toggleClassName('ratingLoading');
        new Ajax.Updater('websiteRatingPositive-' + websiteId, '/synonyms/ratewebsite/' + websiteId + '/' + rating, {
            onComplete: function(t) {
                $('websiteRatingPositive-' + websiteId).toggleClassName('ratingLoading')
            }
        });
    }
}

/* --------------------------------------------------------------------------------- */

/**
 * validate maxlength
 *
 * @param string domId
 * @param int maxlength
 *
 * FIXME using css class name
 */
var checkInputMaxLength = function(domId, maxLength)
{
    strLength = $F(domId).length;
    remainingLength = maxLength - strLength;
    if (remainingLength >= 0) {
        $(domId + 'CharCount').innerHTML = maxLength - strLength;
    }
    if (strLength > maxLength - 30) {
        $(domId).style.color = 'black';
    }
    if (strLength > maxLength - 20) {
        $(domId).style.color = 'orange';
    }
    if (strLength > maxLength - 10) {
        $(domId).style.color = 'red';
    }
}

/* --------------------------------------------------------------------------------- */

/**
 * toggleMenuWritability
 *
 * @param string domId
 * @param string targetId
 */
var toggleMenuWritability = function(domId, targetId)
{
    domValue = $F(domId).strip();
    if (domValue == '') {
        $(targetId).enable();
        $(domId).focus();
    } else {
        $(targetId).disable();
        $(domId).focus();
    }
}

/**
 * update word descriptions menu
 *
 * @param string translateFrom
 * @param string translateInto
 * @param string word
 * @param string targetId
 * @param string selectId
 * @param string loadingId
 */
var updateWordDescriptions = function(transFrom, transInto, word, targetId, selectId, loadingId)
{
    translateFrom = $F(transFrom);
    translateInto = $F(transInto);
    wordStr = $F(word);
    $(targetId).hide();
    $(loadingId).show();
    new Ajax.Updater(targetId, '/suggestions/getworddescriptions', {
        method: 'post',
        parameters: {
            'translateFrom': translateFrom,
            'translateInto': translateInto,
            'wordFrom': wordStr,
            'selectName': selectId
        },
        onComplete: function(t) {
            $(targetId).show();
            $(loadingId).hide();
        }
    });
}

/**
 * update synonym groups
 *
 */
var updateSynonymGroups = function()
{
    lang = $F('lang');
    word = $F('word');
    if (word == '') {
        return;
    }
    $('synonymGroups').toggle();
    $('synonymGroupsLoading').toggle();
    new Ajax.Updater('synonymGroups', '/suggestions/getsynonymgroups', {
        method: 'post',
        parameters: {
            'lang': lang,
            'word': word
        },
        onComplete: function(t) {
            $('synonymGroups').toggle();
            $('synonymGroupsLoading').toggle();
        }
    });
}

/**
 * update antonym groups
 *
 */
var updateAntonymGroups = function()
{
    lang = $F('lang');
    word = $F('word');
    if (word == '') {
        return;
    }
    $('antonymGroups').toggle();
    $('antonymGroupsLoading').toggle();
    new Ajax.Updater('antonymGroups', '/suggestions/getsynonymgroups', {
        method: 'post',
        parameters: {
            'lang': lang,
            'word': word
        },
        onComplete: function(t) {
            $('antonymGroups').toggle();
            $('antonymGroupsLoading').toggle();
        }
    });
}

function loadUserActivities(type)
{
    /*
    new Ajax.Updater('userActivities_' + type, '/dev/getuseractivities', {
        method: 'post',
        parameters: {
            'type': type,
            'limit': limit,
            'offset': offset
        },
        onComplete: function(t) {
            $('').toggle();
            $('').toggle();
        }
    });*/
}

/* --------------------------------------------------------------------------------- */

/**
 * Charmap
*/
document.observe("dom:loaded", function() {
    $(this)
});

/**
 * toggle charmap
 *
 */
var toggleCharmap = function(domId)
{
    Effect.toggle(domId, 'slide', {
        duration: 0.3
    });
}

/**
 * toggle emoticons
 *
 */
var toggleEmoticons = function()
{
    Effect.toggle('emoticons', 'blind');
}

/**
 * toggle charmap
 *
 * @param string domId
 * @param string emoticon
 *
 * FIXME insert at cursor position
 */
var insertEmoticon = function(domId, str)
{
    $(domId).value += ' ' + str;
}

/**
 * insert bbcode
 *
 * @param string domId
 * @param string strBegin
 * @param string strEnd
 */
var insertBBcode = function insert(domId, strBegin, strEnd)
{
    var input = $(domId);
    input.focus();
    // IE
    if (typeof document.selection != 'undefined') {
        var range = document.selection.createRange();
        var insText = range.text;
        range.text = strBegin + insText + strEnd;
        range = document.selection.createRange();
        if (insText.length == 0) {
            range.move('character', -strEnd.length);
        } else {
            range.moveStart('character', strBegin.length + insText.length + strEnd.length);
        }
        range.select();
    }
    // gecko
    else if (typeof input.selectionStart != 'undefined') {
        var start = input.selectionStart;
        var end = input.selectionEnd;
        var insText = input.value.substring(start, end);
        input.value = input.value.substr(0, start) + strBegin + insText + strEnd + input.value.substr(end);
        var pos;
        if (insText.length == 0) {
            pos = start + strBegin.length;
        } else {
            pos = start + strBegin.length + insText.length + strEnd.length;
        }
        input.selectionStart = pos;
        input.selectionEnd = pos;
    }
} 

/* --------------------------------------------------------------------------------- */

/**
 * insert single specialchar
 *
 * @param string domId
 * @param char specialchar
 */
var insertChar = function(domId, char)
{
    $(domId).value += char;
    $(domId).focus();
}

/* --------------------------------------------------------------------------------- */

/**
 * toggle example sentence form
 *
 */
var toggleSentenceForm = function()
{
    Effect.toggle('containerSentenceForm', 'slide');
}

/**
 * toggle word form
 *
 */
var toggleWordForm = function()
{
    Effect.toggle('containerWordForm', 'slide');
}

/* --------------------------------------------------------------------------------- */

/**
 * select language radion button
 * submit form by clicking on flag
 */
var selectLanguage = function(langKey, formId, fieldId)
{
    $('languageSelect_' + langKey).checked = true;
    if ($F(fieldId) != '') {
        $(formId).submit();
        return;
    }
    selectLabels = $$('#searchbox_large_languages .selectLabel');
    for (i = 0; i < selectLabels.length; i++) {
        if ($(selectLabels[i]).id == 'selectLabel_' + langKey) {
            $(selectLabels[i]).addClassName('active');
        } else {
            $(selectLabels[i]).removeClassName('active');
        }
    }
    $(fieldId).focus();
}

/**
 * UPDATED VERSION select language by clicking a flag
 */
var selectLanguageNew = function(section, langKey, formId, fieldId)
{
    $('languageSelect_' + section + '_' + langKey).checked = true;
    if ($F(fieldId) != '') {
        $(formId).submit();
        return;
    }
    selectLabels = $$('#searchbox_large_languages_' + section + ' .selectLabel');
    for (i = 0; i < selectLabels.length; i++) {
        if ($(selectLabels[i]).id == 'selectLabel_' + section + '_' + langKey) {
            $(selectLabels[i]).addClassName('active');
        } else {
            $(selectLabels[i]).removeClassName('active');
        }
    }
    $(fieldId).focus();
}

/* --------------------------------------------------------------------------------- */

var searchString = '';

if (readCookie('searchString'))
{
    searchString = readCookie('searchString');
}

/**
 * save search string to cookie
 *
 * @param mixed element
 */
var saveSearchString = function(element)
{
    searchString = unescape($F(element));

    if (readCookie('searchString') != searchString) {
        createCookie('searchString', searchString, 1);
    }
}

/**
 * get current search string
 *
 * @param mixed element
 */
var getSearchString = function(element)
{
    //$(element).value = utf8_decode(unescape(unescape(searchString)));
	
    $(element).value = utf8_decode(unescape(unescape(searchString)));
}

/**
 * toggle tabs
 *
 * @param string domId
 * @param int tabNumber
 */
var toggleTab = function(domId, tabNumber)
{
    tabLinks = $$('#' + domId + ' .tabLink');
    tabDisplays = $$('#' + domId + ' .tabDisplay');
    for (i = 0; i < tabLinks.length; i++) {
        if (i == tabNumber) {
            
            $(tabDisplays[i]).show();
            $(tabLinks[i]).addClassName('active');
        } else {
            $(tabDisplays[i]).hide();
            $(tabLinks[i]).removeClassName('active');
        }
    }
}

/* --------------------------------------------------------------------------------- */

/**
 * toggle absurd display: second life
 *
 * @param int displayId
 */
var toggleSecondLifeDisplay = function(displayId)
{
    icons = $$('#secondLifeDisplays .secondLiveIcon');
    displays = $$('#secondLifeDisplays .secondLifeDisplay');
    $('secondLifeDisplayCurrent').value = displayId;
    for (i = 0; i < displays.length; i++) {
        $(displays[i]).hide();
        $(icons[i]).removeClassName('secondLiveIconActive');
    }
    $('secondLifeDisplay_' + displayId).show();
    $('secondLifeIcon_' + displayId).addClassName('secondLiveIconActive');
}

/**
 * swap rorschach images
 *
 * @param int imageId
 */
var swapRorschachImage = function(imageId)
{
    images = $$('#rorschachImages .rorschachImage');
    displays = $$('#rorschachImages .rorschachDisplay');
    $('rorschachImageLarge').src = $('rorschachImage' + imageId).src;
    for (i = 0; i < images.length; i++) {
        $(displays[i]).hide();
        $(images[i]).removeClassName('rorschachImageActive');
    }
    $('rorschachDisplay' + imageId).show();
    $('rorschachImage' + imageId).addClassName('rorschachImageActive');
}

/**
 * toggle suggestion type
 *
 * @param string type
 */
var toggleSuggestionType = function(imagePath, type)
{
    if ($('suggestionType_' + type).src == imagePath + '/' + type + '_active.gif') {
        createCookie('hideSuggestions_' + type, true, 30);
        $('suggestionType_' + type).src = imagePath + '/' + type + '_inactive.gif';
    } else {
        eraseCookie('hideSuggestions_' + type);
        $('suggestionType_' + type).src = imagePath + '/' + type + '_active.gif';
    }
}

/**
 * switch gender icons
 *
 * @param char gender
 */
var switchGenderIcons = function(gender)
{
    if (gender == 'f') {
        $('genderIconsMale').hide();
        $('genderIconsFemale').show();
        $$('#genderIconsFemale input')[0].checked = true;
    } else if (gender == 'm') {
        $('genderIconsMale').show();
        $('genderIconsFemale').hide();
        $$('#genderIconsMale input')[0].checked = true;
    } else {
        $('genderIconsMale').hide();
        $('genderIconsFemale').hide();
        $$('#genderIconsMale input').checked = false;
        $$('#genderIconsFemale input').checked = false;
    }
}

/**
 * Rate a question
 * 
 */
var rateQuestion = function(elem, questionId)
{
    rating = $F(elem);
    if (0 == rating) {
        return;
    }

    $('questionRatingContent').innerHTML = '&nbsp;';
    $('questionRatingContent').toggleClassName('ratingLoading');

    new Ajax.Updater('questionRatingContent', '/questions/ratequestion', {
        onSuccess: function(t) {
            
        },
        onComplete: function(t) {
            $('questionRatingContent').toggleClassName('ratingLoading');
        },
        parameters: {
            'questionId' : questionId,
            'rating'     : rating
        }
    });
}

var addQuestionsCategory = function()
{
    categoryName = $F('questionCategory');

    oldVal = $F('submitCategory');
    $('submitCategory').value = 'Loading...';

    new Ajax.Request('/questions/addcategory', {
        parameters: {
            'questionCategory' : categoryName
        },
        onComplete: function(t) {
            $('questionCategory').value = '';
            $('submitCategory').value = oldVal;
            $('questionCategoryList').insert({
                bottom: t.responseText
                })
        }
    });
}

/**
 * Hide register tip
*/
var closeRegisterTip = function()
{
    Effect.Fade('registerTip', {
        duration: .5
    });

    createCookie('registerTipShown', true, 30);
}

/**
 * create new cookie
 *
 * @param string name
 * @param string value
 * @param int days expiry
 */
function createCookie(name, value, days)
{
    if (days) {
        date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    } else {
        expires = ""
    };
	
    hostName = window.location.hostname;
    hostFragments = hostName.split(".");

    if (hostFragments.length > 2) {
        // Format like www.woxikon.de OR www.woxikon.com.br
        domain = "; domain=." + hostFragments[1] + "." + hostFragments[2];
    } else if (hostFragments.length == 2) {
        // Format like woxikon.local
        domain = "; domain=." + hostFragments[0] + "." + hostFragments[1];
    } else {
        domain = "";
    }
	
    document.cookie = name + "=" + value + expires + domain + "; path=/;";
}

/**
 * read cookie
 *
 * @param string name
 * @return string cookie value
 */
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;
}

/**
 * delete cookie
 *
 * @param string name
 */
function eraseCookie(name)
{
    createCookie(name, "" , -1);
}

function utf8_decode ( str_data )
{
    // http://kevin.vanzonneveld.net
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +      input by: Aman Gupta
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: utf8_decode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'
 
    var tmp_arr = [], i = ac = c = c1 = c2 = 0;
 
    while ( i < str_data.length ) {
        c = str_data.charCodeAt(i);
        if (c < 128) {
            tmp_arr[ac++] = String.fromCharCode(c); 
            i++;
        } else if ((c > 191) && (c < 224)) {
            c2 = str_data.charCodeAt(i+1);
            tmp_arr[ac++] = String.fromCharCode(((c & 31) << 6) | (c2 & 63));
            i += 2;
        } else {
            c2 = str_data.charCodeAt(i+1);
            c3 = str_data.charCodeAt(i+2);
            tmp_arr[ac++] = String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }
    }
    
    return tmp_arr.join('');
}




